feat(context): audit tool visibility and isolate diagnostic history
This commit is contained in:
@@ -6,6 +6,10 @@ import type { ContextHistory, ContextHistoryGroup, ContextPlan, Session } from '
|
||||
|
||||
const number = (value: number | null | undefined) => (value ?? 0).toLocaleString('zh-CN');
|
||||
const states: Record<string, string> = { prepared: '已准备', requesting: '正在请求', completed: '已收到响应', failed: '请求失败', interrupted: '请求已中断' };
|
||||
const toolReasons: Record<string, string> = { visible: '本轮可见', not_assembled: '未装配', missing_current_resource: '缺少当前任务资源', disabled: '已停用',
|
||||
disabled_by_policy: '当前策略未启用', disabled_by_execution_mode: '当前执行方式未启用', disabled_by_worker_contract: '子任务范围外', disabled_by_task_contract: '当前任务约定不执行', not_assembled_for_worker: '子任务未装配' };
|
||||
const changeLabel = (path: string) => path === 'tools' ? '工具定义' : path === 'model' ? '请求型号' : path === 'system' ? '系统规则'
|
||||
: path.startsWith('messages[') || path.startsWith('input[') ? '消息段 ' + (Number(path.match(/\[(\d+)\]/)?.[1]) + 1) : path;
|
||||
const toolNames: Record<string, string> = { read_file: '读取文件', read_artifact: '读取保存工件', inspect_project: '识别工程', inspect_session: '核对运行记录',
|
||||
index_project: '建立符号索引', query_code: '定位代码', propose_patch: '精确补丁提案', propose_file: '文件提案', run_command: '终端命令', run_checks: '工程检查',
|
||||
plan_checks: '检查计划', prepare_change_set: '封存变更集', plan_delivery: 'Git交付预览', delivery_report: '交付报告', list_files: '查看文件', search_files: '搜索文件' };
|
||||
@@ -28,6 +32,8 @@ export function RequestContextPanel({ session, runId, openArtifact, onError }: {
|
||||
: historical.filter(plan => plan.runId === runId && plan.sessionId === session.id);
|
||||
const plan = plans.find(plan => plan.id === selected) ?? plans.at(-1);
|
||||
if (!plan) return null;
|
||||
const observation = plan.requestObservation, surface = observation?.toolSurface;
|
||||
const userMessage = observation?.userMessageInstances.filter(message => message.origin === 'user').at(-1);
|
||||
const total = plan.estimatedInputTokens + (plan.budget.outputReservation ?? 0) + plan.budget.safetyTokens;
|
||||
return <section className="task-record-section request-context" aria-label="请求上下文">
|
||||
<div className="record-heading"><BrainCircuit size={15} /><h3>请求上下文</h3><span>{states[plan.status] ?? plan.status}</span></div>
|
||||
@@ -40,11 +46,21 @@ export function RequestContextPanel({ session, runId, openArtifact, onError }: {
|
||||
<dt>历史记录</dt><dd>保留 {plan.retainedMessages} 条 · 保存 {plan.archivedGroups} 组原记录</dd>
|
||||
<dt>上游缓存命中</dt><dd>{plan.actualUsage?.prompt_tokens_details?.cached_tokens === undefined ? '上游未报告' : number(plan.actualUsage.prompt_tokens_details.cached_tokens) + ' tokens'}</dd>
|
||||
{plan.prefixAudit && <><dt>缓存前缀核对</dt><dd>{plan.prefixAudit.variants.map((variant, index) => <div key={variant.connectionId ?? index}>{variant.model} · {variant.previousPromptBytes === null ? '首次请求或新路线' : '共同前缀 ' + number(variant.commonPrefixBytes) + ' B'}{variant.reason === 'tool_surface_changed' ? ' · 可用工具已变化' : ''}</div>)}<small>共同前缀用于核对稳定性,不等于上游命中。</small></dd></>}
|
||||
{observation && <><dt>请求归属</dt><dd>{({ main: '主任务', diagnostic: '独立诊断', worker: '子任务' } as Record<string, string>)[observation.path.kind] ?? observation.path.kind}</dd></>}
|
||||
{userMessage && <><dt>用户消息实例</dt><dd><code title={userMessage.id}>{userMessage.id.slice(0, 12)}</code><small>同样的文字分别记录,不按文本合并。</small></dd></>}
|
||||
{plan.prefixAudit?.variants.some(variant => variant.firstChange && variant.previousPromptBytes !== null) && <><dt>首次变化位置</dt><dd>{plan.prefixAudit.variants.filter(variant => variant.previousPromptBytes !== null).map((variant, index) => <div key={variant.connectionId ?? index}>{variant.model} · {variant.firstChange ? changeLabel(variant.firstChange.path) : '前缀内容相同'}</div>)}</dd></>}
|
||||
{!!plan.workingSetEntries && <><dt>当前任务依据</dt><dd>{plan.workingSetEntries} 项代码与执行结果</dd></>}
|
||||
{!!plan.projectMemoryEntries && <><dt>项目记忆</dt><dd>{plan.projectMemoryEntries} 条来源已核对的记录</dd></>}
|
||||
{!!plan.skillCatalogEntries && <><dt>技能目录</dt><dd>{plan.skillCatalogEntries} 项本次目录记录</dd></>}
|
||||
<dt>发送内容</dt><dd>{number(plan.requestBytes)} B<code className="context-sha" title={plan.requestSha256}>{plan.requestSha256.slice(0, 16)}</code></dd>
|
||||
</dl>
|
||||
{surface && <details className="context-tool-surface" key={plan.id}><summary>本轮工具 · 可见 {surface.entries.filter(entry => entry.visible).length} / 已登记 {surface.entries.length}</summary>
|
||||
<p className="record-footnote">这是本次实际发送的工具范围。资源和权限在执行时重新核对;登记不代表本轮可用。</p>
|
||||
<ul aria-label="本轮工具可见性">{surface.entries.map(entry => <li key={entry.name}>
|
||||
<div><code>{entry.name}</code><span>{toolReasons[entry.reason] ?? entry.reason}</span></div>
|
||||
<small title={'schema ' + entry.schemaSha256 + ' · generation ' + entry.generation}>{number(entry.definitionBytes)} B · schema {entry.schemaSha256.slice(0, 12)} · 代次 {entry.generation.slice(0, 8)}</small>
|
||||
</li>)}</ul>
|
||||
</details>}
|
||||
<p className="record-footnote">估算包含系统提示、工具定义和历史。{plan.budget.capacityMode === 'passthrough' ? '本次完整传递历史,不按本地上下文额度裁剪或拒发。' : plan.historyPolicy === 'preserve' ? '本次完整传递历史,容量不足时暂停。' : '任务要求完整保留;整理过的原记录可从本机工件检索。'}实际用量与缓存命中以模型服务为准。</p>
|
||||
{plan.error && <p className="run-stop">{plan.error}</p>}
|
||||
<div className="context-actions"><button type="button" className="text-button" onClick={() => openArtifact(plan.requestArtifactId)}><FileText size={13} />查看发送内容</button>
|
||||
|
||||
@@ -77,6 +77,14 @@
|
||||
.context-meter { height: 5px; margin: 15px 0; border-radius: 9px; overflow: hidden; background: #e8eeeb; }
|
||||
.context-meter i { display: block; height: 100%; background: #56877b; border-radius: inherit; }
|
||||
.context-sha { display: block; font-size: 10px; color: var(--muted); margin-top: 4px; overflow-wrap: anywhere; }
|
||||
.context-tool-surface { margin: 12px 0; border-block: 1px solid var(--border); padding: 10px 0; }
|
||||
.context-tool-surface summary { cursor: pointer; font-size: 12px; font-weight: 600; }
|
||||
.context-tool-surface ul { list-style: none; margin: 8px 0 0; padding: 0; max-height: 340px; overflow: auto; }
|
||||
.context-tool-surface li { padding: 8px 0; border-bottom: 1px solid var(--border); }
|
||||
.context-tool-surface li > div { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px; font-size: 12px; }
|
||||
.context-tool-surface code { overflow-wrap: anywhere; }
|
||||
.context-tool-surface li small { display: block; margin-top: 4px; color: var(--muted); font-size: 11px; overflow-wrap: anywhere; }
|
||||
.request-context .record-fields dd small { display: block; margin-top: 4px; }
|
||||
.context-actions { display: flex; flex-wrap: wrap; gap: 4px 12px; }
|
||||
.context-actions .text-button { padding-left: 0; }
|
||||
.context-history-list { flex: 1; min-height: 0; overflow: auto; padding: 1px; }
|
||||
|
||||
+7
-1
@@ -185,7 +185,13 @@ export interface ContextPlan {
|
||||
skillCatalogArtifactId?: string | null; skillCatalogSha256?: string | null; skillCatalogEntries?: number;
|
||||
actualUsage: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number; prompt_tokens_details?: { cached_tokens?: number; cache_creation_tokens?: number } } | null; requestAttempts: number; error?: string;
|
||||
historyPolicy?: 'preserve' | 'compact'; contextLayout?: string;
|
||||
prefixAudit?: { variants: { connectionId: string | null; model: string; commonPrefixBytes: number; previousPromptBytes: number | null; reason: string; toolNames: string[]; toolsSha256: string }[] };
|
||||
prefixAudit?: { schemaVersion: number; previousPlanId: string | null; variants: { connectionId: string | null; model: string; commonPrefixBytes: number; previousPromptBytes: number | null; reason: string; toolNames: string[]; toolsSha256: string;
|
||||
firstChange?: { path: string; kind: string; sha256: string | null; previousSha256: string | null } | null;
|
||||
blocks?: { path: string; role: string | null; sha256: string; bytes: number }[];
|
||||
}[] };
|
||||
requestObservation?: { schemaVersion: number; path: { kind: string; key: string }; providerHistorySha256: string;
|
||||
userMessageInstances: { id: string; providerIndex: number; origin: string; sha256: string }[];
|
||||
toolSurface: { generation: string; execution: string; entries: { name: string; group: string; registered: boolean; assembled: boolean; visible: boolean; reason: string; schemaSha256: string; definitionSha256: string; definitionBytes: number; generation: string }[] } | null };
|
||||
budget: { executionMode?: 'unrestricted' | 'restricted';
|
||||
capacityMode?: 'passthrough'; contextLimit: number | null; outputReservation: number | null; safetyTokens: number; inputBudget: number | null; targetInputTokens: number | null; runRemainingTokens: number | null; taskRemainingTokens: number | null };
|
||||
}
|
||||
|
||||
@@ -4,11 +4,30 @@ 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) {
|
||||
export function prefixAudit(body, previous = null, { schemaVersion = 1 } = {}) {
|
||||
if (![1, 2].includes(schemaVersion)) throw new Error('未知前缀观测版本。');
|
||||
const old = previous ? variants(previous) : [];
|
||||
return { schemaVersion: 1, method: 'ordered-wire-prompt-fields-utf8', upstreamCache: 'unknown', variants: variants(body).map(current => {
|
||||
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;
|
||||
@@ -18,6 +37,7 @@ export function prefixAudit(body, previous = null) {
|
||||
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' };
|
||||
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) : {}) };
|
||||
}) };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
export const requestPath = run => run.purpose === 'diagnostic' ? { kind: 'diagnostic', key: 'diagnostic:' + run.id }
|
||||
: run.workerId ? { kind: 'worker', key: 'worker:' + run.workerId } : { kind: 'main', key: 'main' };
|
||||
export const providerHistory = (session, run) => run.diagnosticMessages ?? session.providerMessages;
|
||||
|
||||
export function observeRequest(store, session, run, history, toolSurface = null) {
|
||||
const path = requestPath(run);
|
||||
const inputs = [...store.core.run.values()].filter(value => value.sessionId === session.id && value.inputMessage
|
||||
&& requestPath(value).key === path.key);
|
||||
return { schemaVersion: 1, path, providerHistorySha256: hash(history), toolSurface,
|
||||
userMessageInstances: history.flatMap((message, index) => {
|
||||
if (message.role !== 'user') return [];
|
||||
const input = inputs.find(value => value.inputMessage.providerIndex === index)?.inputMessage;
|
||||
return [{ id: input?.id ?? session.id + ':' + path.key + ':provider:' + index, providerIndex: index,
|
||||
origin: input?.origin ?? (input ? 'user' : 'unclassified_provider_user'), sha256: hash(message) }];
|
||||
}) };
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import { mcpCatalogMessage, MCP_LIMITS } from '../tools/mcp-contract.mjs';
|
||||
import { modelReservation,taskConsumption,verifyModelReservation } from '../../shared/contracts/model-reservation.mjs';
|
||||
import { fileContinuation } from './read-continuation.mjs';
|
||||
import { prefixAudit } from './prefix-audit.mjs';
|
||||
import { observeRequest, providerHistory, requestPath } from './request-observation.mjs';
|
||||
import { verifyToolSurface } from './tool-surface.mjs';
|
||||
import { isPassthrough } from '../../shared/contracts/model-capacity.mjs';
|
||||
|
||||
const hash = value => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value), 'utf8').digest('hex');
|
||||
@@ -187,10 +189,11 @@ export class RequestPlanner {
|
||||
return { artifact_id: artifact.id, sha256: artifact.sha256, group_sha256: group.sha256, bytes: Buffer.byteLength(text, 'utf8'), chunks: chunks.length };
|
||||
}
|
||||
|
||||
prepare(session, run, config, { system, contextTail = null, tools, stepId, projectMemory = null, skillCatalog = null, mcpCatalog = null, transportReservationTokens = 0,engineStepOnly=false }) {
|
||||
prepare(session, run, config, { system, contextTail = null, tools, toolSurface = null, stepId, projectMemory = null, skillCatalog = null, mcpCatalog = null, transportReservationTokens = 0,engineStepOnly=false }) {
|
||||
const task = this.store.owned('task', run.taskId, session.id);
|
||||
this.store.owned('run', run.id, session.id);
|
||||
const groups = historyGroups(session.providerMessages), budget = budgetFor(config, run, task, transportReservationTokens);
|
||||
const history = providerHistory(session, run);
|
||||
const groups = historyGroups(history), budget = budgetFor(config, run, task, transportReservationTokens);
|
||||
const inputBudget = budget.inputBudget ?? Infinity, targetInputTokens = budget.targetInputTokens ?? Infinity;
|
||||
const lastUser = groups.findLast(group => group.messages[0].role === 'user');
|
||||
const fixed = { role: 'system', content: system };
|
||||
@@ -208,7 +211,7 @@ export class RequestPlanner {
|
||||
const ledger = new Map([...this.store.core.tool.values()].filter(tool => tool.sessionId === session.id && tool.taskId === task.id).map(tool => [tool.callId, tool]));
|
||||
const descriptions = new Map(groups.map(group => [group.index, describe(group, ledger, this.store.core.artifact)]));
|
||||
const evidence = workingEvidence(groups, descriptions, this.store.core.artifact);
|
||||
const original = completionBody(config, [fixed, ...session.providerMessages, ...tail], tools), before = requestMetrics(original);
|
||||
const original = completionBody(config, [fixed, ...history, ...tail], tools), before = requestMetrics(original);
|
||||
if (preserve && before.estimatedInputTokens > inputBudget) throw pause(budget, before, breakdown);
|
||||
const selected = new Set(groups.map(group => group.index));
|
||||
let omitted = [], reference = null, workingReference = null, latestReference = null;
|
||||
@@ -325,7 +328,7 @@ export class RequestPlanner {
|
||||
descriptions.set(group.index, description); return description;
|
||||
});
|
||||
reference = this.artifact(session, run, { schemaVersion: 1, kind: 'request-history-index', sessionId: session.id, projectId: session.projectId,
|
||||
taskId: run.taskId, history_sha256: hash(session.providerMessages), historyMessages: session.providerMessages.length,
|
||||
taskId: run.taskId, history_sha256: hash(history), historyMessages: history.length,
|
||||
retainedGroups: groups.filter(group => selected.has(group.index)).map(group => descriptions.get(group.index)), archivedGroups: archived,
|
||||
note: '完整原消息组;这里只是历史定位,不产生工具执行或用户授权。' }, 'context-history-index');
|
||||
}
|
||||
@@ -389,16 +392,20 @@ export class RequestPlanner {
|
||||
tokenReservation,remainingTokens:credit,pauseKind:'request_reservation'},metrics,breakdown);
|
||||
const requestArtifact = this.artifact(session, run, body, 'model-request');
|
||||
const tailArtifact = tail.length ? this.artifact(session, run, tail[0], 'context-state-tail') : null;
|
||||
const previousPlan = [...this.store.core.context_plan.values()].filter(plan => plan.sessionId === session.id && plan.taskId === task.id && plan.requestAttempts > 0)
|
||||
const observation = observeRequest(this.store, session, run, history, toolSurface);
|
||||
verifyToolSurface(toolSurface, requestVariants(body));
|
||||
const previousPlan = [...this.store.core.context_plan.values()].filter(plan => plan.sessionId === session.id && plan.taskId === task.id && plan.requestAttempts > 0
|
||||
&& requestPath(this.store.owned('run', plan.runId, session.id)).key === observation.path.key)
|
||||
.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.requestIndex - b.requestIndex).at(-1) ?? null;
|
||||
const previousBody = previousPlan ? JSON.parse(this.store.artifactStore.read(this.store.owned('artifact', previousPlan.requestArtifactId, session.id))) : null;
|
||||
const prefix = { ...prefixAudit(body, previousBody), previousPlanId: previousPlan?.id ?? null, previousRequestSha256: previousPlan?.requestSha256 ?? null };
|
||||
const prefix = { ...prefixAudit(body, previousBody, { schemaVersion: 2 }), previousPlanId: previousPlan?.id ?? null, previousRequestSha256: previousPlan?.requestSha256 ?? null };
|
||||
const record = { schemaVersion: 1, id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: run.taskId,
|
||||
runId: run.id, stepId, requestIndex: [...this.store.core.context_plan.values()].filter(plan => plan.runId === run.id).length + 1,
|
||||
status: 'prepared', createdAt: new Date().toISOString(), finishedAt: null,
|
||||
requestSha256: metrics.sha256, requestBytes: metrics.bytes, estimatedInputTokens: metrics.estimatedInputTokens,
|
||||
requestArtifactId: requestArtifact.id,
|
||||
prefixAudit: prefix,
|
||||
requestObservation: observation,
|
||||
...(preserve ? { contextLayout: 'stable-prefix-1', historyPolicy: 'preserve', contextTailArtifactId: tailArtifact?.id ?? null, contextTailSha256: tailArtifact?.sha256 ?? null } : {}),
|
||||
...(tokenReservation?{tokenReservation,maxBudgetAttempts:Math.min(8,Math.floor(credit/tokenReservation.reservedTokens))}:{engineStepOnly:true}),
|
||||
estimateMethod: metrics.estimateMethod, beforeInputTokens: before.estimatedInputTokens, beforeBytes: before.bytes, budget,
|
||||
@@ -416,7 +423,7 @@ export class RequestPlanner {
|
||||
// sizing reserves that observed framing growth before returning bytes;
|
||||
// the next complete request is still checked against its original limit.
|
||||
readStateGrowthTokens: 1536,
|
||||
originalMessages: session.providerMessages.length, retainedMessages: messages.length - 1 - tail.length - (reference ? 1 : 0) - (workingReference ? 1 : 0) - (latestReference ? 1 : 0) - (memoryReference ? 1 : 0) - (skillReference ? 1 : 0) - (mcpReference ? 1 : 0),
|
||||
originalMessages: history.length, retainedMessages: messages.length - 1 - tail.length - (reference ? 1 : 0) - (workingReference ? 1 : 0) - (latestReference ? 1 : 0) - (memoryReference ? 1 : 0) - (skillReference ? 1 : 0) - (mcpReference ? 1 : 0),
|
||||
archivedGroups: omitted.length, retainedGroups: groups.filter(group => selected.has(group.index)).map(group => group.index),
|
||||
historyIndexArtifactId: reference?.id ?? null, historyIndexSha256: reference?.sha256 ?? null, actualUsage: null,
|
||||
workingSetArtifactId: workingReference?.id ?? null, workingSetSha256: workingReference?.sha256 ?? null, workingSetEntries: entries.length,
|
||||
@@ -467,14 +474,21 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|
||||
historyGroups(requestHistory(body));
|
||||
for (const variant of requestVariants(body)) historyGroups(requestHistory(variant));
|
||||
const frozen = JSON.parse(store.artifactStore.read(get(plan.artifactId, 'context-plan')));
|
||||
for (const key of ['contextLayout', 'historyPolicy', 'contextTailArtifactId', 'contextTailSha256', 'prefixAudit']) {
|
||||
for (const key of ['contextLayout', 'historyPolicy', 'contextTailArtifactId', 'contextTailSha256', 'prefixAudit', 'requestObservation']) {
|
||||
if (JSON.stringify(frozen[key] ?? null) !== JSON.stringify(plan[key] ?? null)) throw new Error('前缀或历史策略与发送前封存不匹配。');
|
||||
}
|
||||
if (plan.requestObservation) {
|
||||
const run = store.owned('run', plan.runId, session.id);
|
||||
const expected = observeRequest(store, session, run, providerHistory(session, run).slice(0, plan.originalMessages), plan.requestObservation.toolSurface);
|
||||
if (JSON.stringify(expected) !== JSON.stringify(plan.requestObservation)) throw new Error('消息实例或请求路径与原历史不匹配。');
|
||||
verifyToolSurface(plan.requestObservation.toolSurface, requestVariants(body));
|
||||
}
|
||||
if (plan.prefixAudit) {
|
||||
const previous = plan.prefixAudit.previousPlanId ? store.owned('context_plan', plan.prefixAudit.previousPlanId, session.id) : null;
|
||||
if (previous && (previous.taskId !== plan.taskId || previous.id === plan.id || previous.createdAt > plan.createdAt || previous.requestSha256 !== plan.prefixAudit.previousRequestSha256)) throw new Error('前缀对照来源不匹配。');
|
||||
if (previous && (previous.taskId !== plan.taskId || previous.id === plan.id || previous.createdAt > plan.createdAt || previous.requestSha256 !== plan.prefixAudit.previousRequestSha256
|
||||
|| plan.requestObservation && requestPath(store.owned('run', previous.runId, session.id)).key !== plan.requestObservation.path.key)) throw new Error('前缀对照来源不匹配。');
|
||||
const previousBody = previous ? JSON.parse(store.artifactStore.read(get(previous.requestArtifactId, 'model-request', previous.requestSha256))) : null;
|
||||
const expected = { ...prefixAudit(body, previousBody), previousPlanId: previous?.id ?? null, previousRequestSha256: previous?.requestSha256 ?? null };
|
||||
const expected = { ...prefixAudit(body, previousBody, { schemaVersion: plan.prefixAudit.schemaVersion }), previousPlanId: previous?.id ?? null, previousRequestSha256: previous?.requestSha256 ?? null };
|
||||
if (JSON.stringify(expected) !== JSON.stringify(plan.prefixAudit)) throw new Error('前缀观测与原请求字节不匹配。');
|
||||
}
|
||||
const carriesContext = content => requestHistory(body).filter(value => typeof value.content === 'string'
|
||||
@@ -565,7 +579,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|
||||
const artifact = get(plan.latestToolsArtifactId, 'context-latest-tools', plan.latestToolsSha256);
|
||||
const document = JSON.parse(store.artifactStore.read(artifact));
|
||||
if (artifact.taskId !== plan.taskId) throw new Error('最新工具反馈的工件任务归属不匹配。');
|
||||
verifyLatestToolDocument(store, session, plan, document, historyGroups(session.providerMessages.slice(0, plan.originalMessages)));
|
||||
verifyLatestToolDocument(store, session, plan, document, historyGroups(providerHistory(session, store.owned('run', plan.runId, session.id)).slice(0, plan.originalMessages)));
|
||||
const message = latestToolMessage(artifact, document, plan.latestToolsViewVersion ?? 1);
|
||||
if (requestHistory(body).filter(value => value.role === 'system' && value.content === message.content).length !== 1) throw new Error('最新工具反馈与实际发送内容不匹配。');
|
||||
}
|
||||
@@ -573,7 +587,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|
||||
const artifact = get(plan.workingSetArtifactId, 'context-working-set', plan.workingSetSha256);
|
||||
const document = JSON.parse(store.artifactStore.read(artifact));
|
||||
if (artifact.taskId !== plan.taskId) throw new Error('工作依据工件任务归属不匹配。');
|
||||
verifyWorkingDocument(store, session, plan, document, historyGroups(session.providerMessages.slice(0, plan.originalMessages)));
|
||||
verifyWorkingDocument(store, session, plan, document, historyGroups(providerHistory(session, store.owned('run', plan.runId, session.id)).slice(0, plan.originalMessages)));
|
||||
const message = workingMessage(artifact, document, plan.workingSetViewVersion ?? 1);
|
||||
if (requestHistory(body).filter(value => value.role === 'system' && value.content === message.content).length !== 1) throw new Error('工作依据与实际发送内容不匹配。');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const bytes = value => Buffer.byteLength(JSON.stringify(value));
|
||||
export const toolName = tool => tool.function?.name ?? tool.name;
|
||||
|
||||
// Observations only. Resource managers still recheck current authority at
|
||||
// execution; registration and model visibility do not grant that authority.
|
||||
export function observeToolSurface(groups, tools, policy = {}) {
|
||||
const sent = new Map(tools.map(tool => [toolName(tool), tool]));
|
||||
const entries = groups.flatMap(group => group.definitions.map(definition => {
|
||||
const name = toolName(definition), actual = sent.get(name);
|
||||
const reason = actual ? 'visible' : !group.assembled ? group.reason ?? 'not_assembled'
|
||||
: policy.reason?.(name) ?? 'disabled_by_policy';
|
||||
const identity = actual ?? definition;
|
||||
return { name, group: group.name, registered: true, assembled: !!group.assembled, visible: !!actual,
|
||||
reason, schemaSha256: hash(identity.function?.parameters ?? identity.input_schema ?? {}),
|
||||
definitionSha256: hash(identity), definitionBytes: bytes(identity),
|
||||
generation: hash({ definition: identity, reason, resources: group.resources ?? [], policy: policy.identity ?? null }) };
|
||||
}));
|
||||
const observation = { schemaVersion: 1, method: 'assembled-tool-definitions-and-resource-revisions',
|
||||
execution: 'rechecked_at_execution', policy: policy.identity ?? null,
|
||||
resources: groups.map(group => ({ group: group.name, identities: group.resources ?? [] })), entries };
|
||||
return { ...observation, generation: hash(observation) };
|
||||
}
|
||||
|
||||
export function verifyToolSurface(surface, bodyVariants) {
|
||||
if (!surface) return;
|
||||
const { generation, ...observation } = surface;
|
||||
if (surface.schemaVersion !== 1 || hash(observation) !== generation) throw new Error('工具可见性代次不匹配。');
|
||||
const expected = surface.entries.filter(entry => entry.visible);
|
||||
if (new Set(surface.entries.map(entry => entry.name)).size !== surface.entries.length) throw new Error('工具可见性有重复名称。');
|
||||
for (const body of bodyVariants) {
|
||||
const actual = body.tools ?? [];
|
||||
if (actual.length !== expected.length || actual.some((tool, index) => toolName(tool) !== expected[index].name
|
||||
|| hash(tool.function?.parameters ?? tool.input_schema ?? tool.parameters ?? {}) !== expected[index].schemaSha256)) {
|
||||
throw new Error('工具可见性与实际协议工具不匹配。');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
|
||||
export const APP_VERSION = '1.25.7';
|
||||
export const APP_VERSION = '1.25.8';
|
||||
|
||||
export function executionEnvironment() {
|
||||
const windows = process.platform === 'win32';
|
||||
|
||||
+42
-14
@@ -30,6 +30,8 @@ import { projectEnvironment } from '../core/process-environment.mjs';
|
||||
import { GitDelivery } from '../core/git-delivery.mjs';
|
||||
import { ProjectIndex } from '../core/context/project-index.mjs';
|
||||
import { RequestPlanner, verifyPlanEvidence } from '../core/context/request-plan.mjs';
|
||||
import { observeToolSurface } from '../core/context/tool-surface.mjs';
|
||||
import { providerHistory } from '../core/context/request-observation.mjs';
|
||||
import { ENGINE_SEED_RESERVATION } from '../shared/contracts/engine-context.mjs';
|
||||
import { InputAttachments } from '../core/context/input-attachments.mjs';
|
||||
import { BudgetResume } from '../core/context/budget-resume.mjs';
|
||||
@@ -291,6 +293,7 @@ export class Runtime {
|
||||
if (attachments.length && config.mode==='demo') throw Object.assign(new Error('演示执行器不会读取图片,请先选择支持视觉的模型连接。'),{status:409});
|
||||
if (!unrestricted(config) && attachments.length && !config.modelRouting) throw Object.assign(new Error('请在模型中心添加并声明支持视觉的连接,再发送图片。'),{status:409});
|
||||
const record = this.store.beginRun(session, content, resume, config, { instructionSource, inputAttachments:attachments,resumePlan });
|
||||
if (record.purpose === 'diagnostic') record.diagnosticMessages = structuredClone(session.providerMessages);
|
||||
const run = { controller, id: record.id, taskId: record.taskId, project, record, config, ...(worker ? { worker } : {}) };
|
||||
this.active.set(id, run);
|
||||
session.status = 'running'; session.recoveryNotice = null; session.executionMode = config.mode;
|
||||
@@ -299,7 +302,9 @@ export class Runtime {
|
||||
if (!resume || content) {
|
||||
const userMessage=this.store.message(session, 'user', String(content));
|
||||
if(attachments.length)userMessage.attachmentIds=attachments.map(row=>row.boundAttachmentId);
|
||||
session.providerMessages.push({ role: 'user', content: String(content) });
|
||||
const history = providerHistory(session, record);
|
||||
record.inputMessage = { id: userMessage.id, providerIndex: history.length, origin: instructionSource ? 'system_action' : 'user' };
|
||||
history.push({ role: 'user', content: String(content) });
|
||||
}
|
||||
if (resume) this.store.message(session, 'system', '从已保存的执行记录继续,已完成的工具结果保留。');
|
||||
session.failure = null;
|
||||
@@ -412,15 +417,38 @@ export class Runtime {
|
||||
}) : ''));
|
||||
const skillCatalog = run.worker ? null : this.skillRegistry().catalog(session.projectId);
|
||||
const mcpCatalog = run.worker ? null : this.mcpRegistry().catalog(session.projectId);
|
||||
const availableTools = [...toolDefinitions, ...(unrestricted(config) ? automaticToolDefinitions : []), ...taskPlanToolDefinitions, ...fileResultToolDefinitions, ...(unrestricted(config) || [...this.store.core.browsing_tab.values()].some(tab=>tab.sessionId===session.id&&tab.taskId===run.taskId&&tab.status==='open')?browsingToolDefinitions:[]), ...(skillCatalog?.entries.some(value => value.status === 'current') ? skillToolDefinitions : []),
|
||||
...(mcpCatalog?.entries.length ? mcpToolDefinitions : []),
|
||||
...([...this.store.core.research_target.values()].some(target => target.sessionId === session.id && target.taskId === run.taskId) ? researchToolDefinitions : []),
|
||||
...([...this.store.core.engine_job.values()].some(job => job.sessionId === session.id && job.taskId === run.taskId) ? engineToolDefinitions : []),
|
||||
...(this.browserManager().builds(run.project).length || [...this.store.core.browser_plan.values()].some(plan => plan.sessionId === session.id && plan.taskId === run.taskId) ? browserToolDefinitions : [])];
|
||||
const owned = kind => [...this.store.core[kind].values()].filter(value => value.sessionId === session.id && value.taskId === run.taskId);
|
||||
const tabs = owned('browsing_tab').filter(tab => tab.status === 'open'), targets = owned('research_target'), engines = owned('engine_job');
|
||||
const browserResources = [...this.browserManager().builds(run.project).map(value => ({ kind: 'build', path: value })),
|
||||
...owned('browser_plan').map(value => ({ kind: 'plan', id: value.id }))];
|
||||
const registrations = registry => registry.state().registrations.filter(value => value.projectId === session.projectId)
|
||||
.map(({ id, enabled, revision, configurationRevision }) => ({ id, enabled, revision, configurationRevision }));
|
||||
const skills = run.worker ? [] : registrations(this.skillRegistry()), mcps = run.worker ? [] : registrations(this.mcpRegistry());
|
||||
const groups = [
|
||||
{ name: 'core', definitions: toolDefinitions, assembled: true },
|
||||
{ name: 'automatic', definitions: automaticToolDefinitions, assembled: unrestricted(config), reason: 'disabled_by_execution_mode' },
|
||||
{ name: 'task_plan', definitions: taskPlanToolDefinitions, assembled: true },
|
||||
{ name: 'file_results', definitions: fileResultToolDefinitions, assembled: true },
|
||||
{ name: 'browsing', definitions: browsingToolDefinitions, assembled: unrestricted(config) || !!tabs.length, reason: 'missing_current_resource', resources: tabs.map(({ id, revision }) => ({ id, revision })) },
|
||||
{ name: 'skills', definitions: skillToolDefinitions, assembled: !!skillCatalog?.entries.some(value => value.status === 'current'),
|
||||
reason: run.worker ? 'not_assembled_for_worker' : skills.length && !skills.some(value => value.enabled) ? 'disabled' : 'missing_current_resource',
|
||||
resources: [{ registrations: skills, entries: skillCatalog?.entries ?? [] }] },
|
||||
{ name: 'mcp', definitions: mcpToolDefinitions, assembled: !!mcpCatalog?.entries.length,
|
||||
reason: run.worker ? 'not_assembled_for_worker' : mcps.length && !mcps.some(value => value.enabled) ? 'disabled' : 'missing_current_resource',
|
||||
resources: [{ registrations: mcps, entries: mcpCatalog?.entries ?? [] }] },
|
||||
{ name: 'research', definitions: researchToolDefinitions, assembled: !!targets.length, reason: 'missing_current_resource', resources: targets.map(({ id }) => ({ id })) },
|
||||
{ name: 'engine', definitions: engineToolDefinitions, assembled: !!engines.length, reason: 'missing_current_resource', resources: engines.map(({ id }) => ({ id })) },
|
||||
{ name: 'browser_checks', definitions: browserToolDefinitions, assembled: !!browserResources.length, reason: 'missing_current_resource', resources: browserResources },
|
||||
];
|
||||
const availableTools = groups.filter(group => group.assembled).flatMap(group => group.definitions);
|
||||
const tools = openToolDefinitions(availableTools.filter(tool => unrestricted(config) || (!run.worker || WORKER_TOOLS.has(tool.function.name)) && taskToolAllowed(task, run.record, tool.function.name)), config);
|
||||
const toolSurface = observeToolSurface(groups, tools, { identity: { executionMode: config.executionMode ?? 'restricted', approvalMode: config.approvalMode ?? 'ask',
|
||||
purpose: run.record.purpose ?? 'execution', workerId: run.worker?.id ?? null },
|
||||
reason: name => run.worker && !WORKER_TOOLS.has(name) ? 'disabled_by_worker_contract'
|
||||
: !taskToolAllowed(task, run.record, name) ? 'disabled_by_task_contract' : 'disabled_by_execution_mode' });
|
||||
const projectMemory = await this.memoryManager().context(session, { redact: value => this.provider.redact(value) });
|
||||
signal.throwIfAborted();
|
||||
const planned = this.requestPlanner().prepare(session, run.record, config, { system: stablePrefix ? this.provider.redact(fixedContext) : context, contextTail: stablePrefix ? context : null, tools, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog,
|
||||
const planned = this.requestPlanner().prepare(session, run.record, config, { system: stablePrefix ? this.provider.redact(fixedContext) : context, contextTail: stablePrefix ? context : null, tools, toolSurface, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog,
|
||||
transportReservationTokens:run.worker?.engine?ENGINE_SEED_RESERVATION:0,engineStepOnly:!!run.worker?.engine });
|
||||
if (planned.record.archivedGroups && !projectionLogged) {
|
||||
projectionLogged = true; session.compactions++;
|
||||
@@ -484,7 +512,7 @@ export class Runtime {
|
||||
response = externalEngine
|
||||
? await this.engineRunner().complete(session, run, planned.messages, progressHandler, planned.record, tools)
|
||||
: await this.provider.complete(requestConfig, planned.messages, run.project, signal, progressHandler, planned.record, tools,
|
||||
{ ...(config.mode === 'demo' ? { demoHistory: session.providerMessages } : {}), maxBudgetAttempts:planned.record.maxBudgetAttempts,beforeDispatch:({previousFailure}={})=>checkModelDispatchBudget(this.store,session,run.record,requestConfig,planned.body,0,previousFailure)});
|
||||
{ ...(config.mode === 'demo' ? { demoHistory: providerHistory(session, run.record) } : {}), maxBudgetAttempts:planned.record.maxBudgetAttempts,beforeDispatch:({previousFailure}={})=>checkModelDispatchBudget(this.store,session,run.record,requestConfig,planned.body,0,previousFailure)});
|
||||
if (response.compatibility?.length && requestEvent) { requestEvent.compatibility = response.compatibility; this.store.save(session); }
|
||||
this.requestPlanner().finish(session, planned.record, { response, attempts: planned.record.requestAttempts });
|
||||
if (run.worker && !externalEngine && !responseAccounted) {
|
||||
@@ -518,7 +546,7 @@ export class Runtime {
|
||||
// The truncated assistant turn was never appended, so the conversation
|
||||
// stays valid. Feed the instruction to the model as a standalone turn
|
||||
// in the provider history, and mirror it to the visible chat log.
|
||||
session.providerMessages.push({ role: 'user', content: note });
|
||||
providerHistory(session, run.record).push({ role: 'user', content: note });
|
||||
this.store.event(session, { kind: 'context', runId: run.id, label: '模型输出被上限截断,已请求拆分后继续', phase: 'completed', contextPlanId: planned.record.id,
|
||||
output: '第 ' + run.record.outputTruncationRecoveries + '/' + OUTPUT_TRUNCATION_RECOVERY_LIMIT + ' 次恢复:上一响应 finish_reason=length,未执行任何工具,原响应与用量已保存。' });
|
||||
this.store.message(session, 'system', note);
|
||||
@@ -545,9 +573,9 @@ export class Runtime {
|
||||
: this.store.owned('artifact', args.artifact_id, session.id).bytes;
|
||||
return Math.max(0, Math.min(size - (args.offset ?? 0), args.limit ?? (call.function.name === 'read_artifact' ? 2000 : Infinity)));
|
||||
});
|
||||
const previousIds = new Set(session.providerMessages.flatMap(item => (item.tool_calls ?? []).map(call => call.id)));
|
||||
const previousIds = new Set(providerHistory(session, run.record).flatMap(item => (item.tool_calls ?? []).map(call => call.id)));
|
||||
if (new Set(calls.map(call => call.id)).size !== calls.length || calls.some(call => previousIds.has(call.id))) throw new Error('模型返回了重复的工具调用 ID,请重新发送任务。');
|
||||
session.providerMessages.push(message);
|
||||
providerHistory(session, run.record).push(message);
|
||||
if (!responseAccounted) this.store.recordResponse(session, run.record, response.usage, planned.record.estimatedInputTokens + Math.ceil(Buffer.byteLength(JSON.stringify(message), 'utf8') / 3) + 8);
|
||||
for (const call of calls) {
|
||||
const event = { id: randomUUID(), createdAt: now(), startedAt: now(), kind: 'tool', phase: 'queued',
|
||||
@@ -621,7 +649,7 @@ export class Runtime {
|
||||
const invocation = [...this.store.core.tool.values()].findLast(row => row.runId === run.id && row.callId === call.id);
|
||||
if (invocation?.resultArtifactId) (stepRecord.progressToolIds ??= []).push(invocation.id);
|
||||
spendReadBudget(run.readBatchBudget, call, result);
|
||||
session.providerMessages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
|
||||
providerHistory(session, run.record).push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
|
||||
if (call.function.name === 'prepare_change_set' && result.status === 'awaiting_review') preparedSets.add(result.change_set_id);
|
||||
if (call.function.name === 'call_registered_mcp' && result.requires_verification) mcpReview = result.mcp_job_id;
|
||||
if (call.function.name === 'plan_delivery' && result.status === 'awaiting_review') {
|
||||
@@ -674,8 +702,8 @@ export class Runtime {
|
||||
this.store.save(session);
|
||||
} catch (error) {
|
||||
this.store.interruptPending(session, run.record);
|
||||
const repaired = repairToolPairs(session.providerMessages, callId => this.store.savedToolResult(session.id, callId));
|
||||
if (repaired.changed) session.providerMessages = repaired.messages;
|
||||
const history = providerHistory(session, run.record), repaired = repairToolPairs(history, callId => this.store.savedToolResult(session.id, callId));
|
||||
if (repaired.changed) history.splice(0, history.length, ...repaired.messages);
|
||||
const budget = error instanceof BudgetExceeded ? error : signal.reason instanceof BudgetExceeded ? signal.reason : null;
|
||||
if (signal.aborted || budget) {
|
||||
run.stopReason = budget?.reason ?? 'cancelled';
|
||||
|
||||
Reference in New Issue
Block a user