Files
Agent-Workbench/src/core/context/prefix-audit.mjs
T

44 lines
3.6 KiB
JavaScript

import { createHash } from 'node:crypto';
const hash = value => createHash('sha256').update(value).digest('hex');
const variants = body => body.kind === 'model-route-plan' ? body.variants : [{ connectionId: null, protocol: body.input ? 'responses' : Array.isArray(body.system) ? 'anthropic-messages' : 'chat-completions', body }];
const prompt = body => Buffer.from(JSON.stringify({ model: body.model, tools: body.tools ?? [], system: body.system ?? null, messages: body.messages ?? body.input ?? [] }));
const block = (path, value, role = null) => ({ path, role, sha256: hash(JSON.stringify(value)), bytes: Buffer.byteLength(JSON.stringify(value)) });
const blocks = body => [block('model', body.model), block('tools', body.tools ?? []), block('system', body.system ?? null),
...(body.messages ?? body.input ?? []).map((message, index) => block((body.input ? 'input' : 'messages') + '[' + index + ']', message, message.role ?? message.type ?? null))];
function segmentAudit(body, previous) {
const current = blocks(body), prior = previous ? blocks(previous) : [];
const first = current.findIndex((entry, index) => entry.sha256 !== prior[index]?.sha256);
const index = first >= 0 ? first : prior.length > current.length ? current.length : -1;
return { blocks: current, firstChange: index < 0 ? null : { path: (current[index] ?? prior[index]).path,
kind: !prior[index] ? 'added' : !current[index] ? 'removed' : 'changed',
reason: !previous ? 'first_route_request' : index === 1 ? 'tool_definitions_changed' : index === 0 ? 'model_changed'
: index === 2 ? 'native_system_changed' : 'message_sequence_changed',
previousSha256: prior[index]?.sha256 ?? null, sha256: current[index]?.sha256 ?? null },
tools: (body.tools ?? []).map(tool => ({ name: tool.function?.name ?? tool.name,
schemaSha256: hash(JSON.stringify(tool.function?.parameters ?? tool.input_schema ?? tool.parameters ?? {})),
definitionSha256: hash(JSON.stringify(tool)), bytes: Buffer.byteLength(JSON.stringify(tool)) })) };
}
// This measures ordered prompt fields, not a supplier cache hit or saved
// tokens. Metadata stays outside the request and cannot invalidate its prefix.
export function prefixAudit(body, previous = null, { schemaVersion = 1 } = {}) {
if (![1, 2].includes(schemaVersion)) throw new Error('未知前缀观测版本。');
const old = previous ? variants(previous) : [];
return { schemaVersion, method: 'ordered-wire-prompt-fields-utf8', upstreamCache: 'unknown', variants: variants(body).map(current => {
const tools = JSON.stringify(current.body.tools ?? []), bytes = prompt(current.body);
const prior = old.find(value => value.connectionId === current.connectionId && value.protocol === current.protocol && value.body.model === current.body.model);
const previousBytes = prior ? prompt(prior.body) : null;
let common = 0;
if (previousBytes) while (common < Math.min(previousBytes.length, bytes.length) && previousBytes[common] === bytes[common]) common++;
const toolsChanged = !!prior && JSON.stringify(prior.body.tools ?? []) !== tools;
return { connectionId: current.connectionId, protocol: current.protocol, model: current.body.model,
toolsSha256: hash(tools), toolBytes: Buffer.byteLength(tools), toolNames: (current.body.tools ?? []).map(tool => tool.function?.name ?? tool.name),
promptBytes: bytes.length, previousPromptBytes: previousBytes?.length ?? null, commonPrefixBytes: common,
reason: !prior ? 'new_route_or_first_request' : toolsChanged ? 'tool_surface_changed' : bytes.equals(previousBytes) ? 'same_prompt' : 'prompt_append_or_change',
...(schemaVersion >= 2 ? segmentAudit(current.body, prior?.body) : {}) };
}) };
}