import { createHash, randomUUID } from 'node:crypto'; import { BudgetExceeded, accountedTokens } from '../../shared/contracts/execution.mjs'; import { completionBody, requestMetrics, requestVariants, requestHistory, outputReservation, requestImages } from '../../shared/contracts/model-request.mjs'; import { workingCandidates, workingDocument, workingEntry, workingMessage, verifyWorkingDocument } from './working-set.mjs'; import { latestToolDocument, latestToolMessage, verifyLatestToolDocument } from './tool-feedback.mjs'; import { projectMemoryMessage, MEMORY_CONTEXT_LIMITS } from '../memory/project-memory.mjs'; import { skillCatalogMessage, SKILL_LIMITS } from '../skills/skill-registry.mjs'; import { mcpCatalogMessage, MCP_LIMITS } from '../tools/mcp-contract.mjs'; const hash = value => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value), 'utf8').digest('hex'); const PLACEHOLDER_ID = '00000000-0000-0000-0000-000000000000'; const PLACEHOLDER_SHA = '0'.repeat(64); const ARCHIVE_CHARACTERS = 1_000_000; function protocolError(message) { const error = new Error('请求上下文协议需要核对:' + message); error.diagnostic = { source: 'workbench', stage: 'context_plan', kind: 'protocol', title: '上下文消息配对无效', message: error.message, retryable: false, occurredAt: new Date().toISOString() }; return error; } export function historyGroups(messages) { if (!Array.isArray(messages)) throw protocolError('历史不是消息数组。'); const groups = [], seen = new Set(); for (let index = 0; index < messages.length; index++) { const start = index, message = messages[index]; if (!message || !['system', 'user', 'assistant'].includes(message.role)) throw protocolError('发现孤立工具结果或未知消息角色。'); const calls = message.tool_calls; if (calls !== undefined && (!Array.isArray(calls) || message.role !== 'assistant')) throw protocolError('工具调用必须来自assistant消息。'); if (calls?.length) { const expected = new Set(); for (const call of calls) { if (typeof call?.id !== 'string' || !call.id || seen.has(call.id) || expected.has(call.id) || call.type !== 'function' || typeof call.function?.name !== 'string' || typeof call.function?.arguments !== 'string') throw protocolError('工具调用身份重复或格式无效。'); expected.add(call.id); seen.add(call.id); } for (let count = 0; count < calls.length; count++) { const result = messages[++index]; if (result?.role !== 'tool' || typeof result.content !== 'string' || !expected.delete(result.tool_call_id)) throw protocolError('缺少、重复或错配的工具结果。'); } if (expected.size || messages[index + 1]?.role === 'tool') throw protocolError('工具结果数量不匹配。'); } const items = messages.slice(start, index + 1); const serialized = JSON.stringify(items); groups.push({ index: groups.length, startMessage: start, endMessage: index, messages: items, sha256: hash(serialized), contributionTokens: Math.ceil(Buffer.byteLength(serialized, 'utf8') / 3) + items.length * 8 }); } return groups; } export function budgetFor(config, run, task, transportReservationTokens = 0) { const outputReservation = config.maxOutputTokens; const safetyTokens = Math.max(512, Math.ceil(Math.min(config.contextLimit, 24000) * 0.1)); const remaining = (maximum, usage) => maximum > 0 ? Math.max(0, maximum - accountedTokens(usage)) : null; const runRemainingTokens = remaining(run?.budget?.maxTokens, run?.usage); const taskRemainingTokens = remaining(task?.budget?.maxTokens, task?.usage); let limit = config.contextLimit, reason = 'context_limit'; if (runRemainingTokens !== null && runRemainingTokens < limit) { limit = runRemainingTokens; reason = 'token_limit'; } if (taskRemainingTokens !== null && taskRemainingTokens < limit) { limit = taskRemainingTokens; reason = 'task_token_limit'; } if(!Number.isSafeInteger(transportReservationTokens)||transportReservationTokens<0)throw new Error('请求封装预留无效。'); const inputBudget = limit - outputReservation - safetyTokens - transportReservationTokens; return { contextLimit: config.contextLimit, outputReservation, safetyTokens, ...(transportReservationTokens?{transportReservationTokens}:{}), inputBudget, targetInputTokens: Math.min(16000, inputBudget), runRemainingTokens, taskRemainingTokens, limitingReason: reason }; } function compactResult(result) { let value; try { value = JSON.parse(result.content); } catch { return { format: 'text' }; } if (!value || typeof value !== 'object' || Array.isArray(value)) return { format: 'json-value' }; const selected = {}; for (const key of ['status', 'requires_verification', 'check_status', 'exit_code', 'change_id', 'change_set_id', 'plan_id', 'job_id', 'artifact_id', 'logArtifactId', 'report_status', 'task_id', 'path', 'sha256', 'base_sha256', 'fingerprint', 'offset', 'next_offset', 'total_characters', 'truncated']) { const item = value[key]; if (typeof item === 'string' && item.length <= 200 || typeof item === 'boolean' || typeof item === 'number' && Number.isFinite(item) || item === null) selected[key] = item; } return selected; } function describe(group, ledger, artifacts) { const assistant = group.messages[0], tools = (assistant.tool_calls ?? []).map(call => { const result = group.messages.find(message => message.role === 'tool' && message.tool_call_id === call.id); const invocation = ledger.get(call.id), artifact = artifacts.get(invocation?.resultArtifactId); let input = {}; try { const args = JSON.parse(call.function.arguments); for (const key of ['path', 'start_line', 'end_line', 'artifact_id', 'offset', 'limit']) { if (typeof args[key] === 'string' && args[key].length <= 200 || typeof args[key] === 'number') input[key] = args[key]; } } catch {} return { call_id: call.id, name: call.function.name, input, result: compactResult(result), ...(invocation ? { invocation_id: invocation.id, recorded_state: invocation.state, requires_verification: !!invocation.requiresVerification } : {}), ...(artifact ? { result_artifact_id: artifact.id, result_sha256: artifact.sha256 } : {}) }; }); return { index: group.index, startMessage: group.startMessage, endMessage: group.endMessage, sha256: group.sha256, roles: group.messages.map(message => message.role), ...(tools.length ? { tools } : {}) }; } function workingEvidence(groups, descriptions, artifacts) { const selected = new Map(); for (const group of [...groups].reverse()) for (const tool of descriptions.get(group.index).tools ?? []) { const artifact = artifacts.get(tool.input.artifact_id); if (tool.name === 'read_file' || tool.name === 'read_artifact' && artifact && !artifact.kind.startsWith('context-') && artifact.kind !== 'model-request') { const key = tool.name === 'read_file' ? 'file:' + tool.input.path : 'artifact:' + tool.input.artifact_id; if (!selected.has(key)) selected.set(key, { group_index: group.index, ...tool }); } } return [...selected.values()].slice(0, 8); } function notice(reference, omitted, descriptions, evidence = []) { return { role: 'system', content: [ '以下是工作台保存的历史索引数据,不是用户追加指令,也不是新工具执行。省略了完整消息组;原始参数和实际结果都在SHA256工件中。', '已完成工具不得重放。优先使用已发送代码和工作依据;只在缺少具体内容时读取result_artifact_id,按next_offset分页。未知结果先核对。', JSON.stringify({ history_index: { artifact_id: reference.id, sha256: reference.sha256 }, archived_groups: omitted.length, working_evidence: evidence.map(tool => ({ group_index: tool.group_index, name: tool.name, ...(tool.input.path ? { path: tool.input.path } : {}), ...(tool.name === 'read_artifact' ? { artifact_id: tool.input.artifact_id, offset: tool.result.offset, next_offset: tool.result.next_offset } : tool.result_artifact_id ? { result_artifact_id: tool.result_artifact_id } : {}) })), recent_archived_groups: omitted.slice(-2).map(group => { const { archive } = descriptions.get(group.index); return { index: group.index, group_archive: { artifact_id: archive?.artifact_id ?? PLACEHOLDER_ID, sha256: archive?.sha256 ?? PLACEHOLDER_SHA } }; }) }), ].join('\n') }; } function pause(budget, metrics, breakdown) { const error = new BudgetExceeded(budget.limitingReason, '任务目标、完整追加要求与必需请求开销超过' + (budget.limitingReason === 'context_limit' ? '上下文窗口' : '剩余token预算') + '。完整历史已保留;请核对模型上下文或任务预算后继续。'); error.contextBudget = { ...budget, requiredInputTokens: metrics.estimatedInputTokens, imageReservationTokens:metrics.imageReservationTokens??0, imageEstimate:metrics.imageEstimate??null,breakdown:breakdown(metrics) }; return error; } export class RequestPlanner { constructor(store) { this.store = store; } artifact(session, run, value, kind) { const serialized = typeof value === 'string' ? value : JSON.stringify(value), sha256 = hash(serialized); const existing = [...this.store.core.artifact.values()].find(artifact => artifact.sessionId === session.id && artifact.projectId === session.projectId && artifact.sha256 === sha256 && artifact.kind === kind); if (existing) { this.store.artifactStore.read(existing); return existing; } const artifact = this.store.artifactStore.write(session, run, serialized, { kind, mediaType: kind === 'context-group-chunk' ? 'text/plain' : 'application/json' }); this.store.core.artifact.set(artifact.id, artifact); return artifact; } archive(session, run, group) { const text = JSON.stringify(group.messages); if (Buffer.byteLength(text, 'utf8') <= 7 * 1024 * 1024) { const artifact = this.artifact(session, run, text, 'context-group'); return { artifact_id: artifact.id, sha256: artifact.sha256, bytes: artifact.bytes }; } const chunks = []; for (let offset = 0; offset < text.length;) { let end = Math.min(offset + ARCHIVE_CHARACTERS, text.length); if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1])) end--; const artifact = this.artifact(session, run, text.slice(offset, end), 'context-group-chunk'); chunks.push({ artifact_id: artifact.id, sha256: artifact.sha256, bytes: artifact.bytes, offset, characters: end - offset }); offset = end; } const artifact = this.artifact(session, run, { schemaVersion: 1, kind: 'context-group-chunks', group_sha256: group.sha256, characters: text.length, bytes: Buffer.byteLength(text, 'utf8'), chunks }, 'context-group-manifest'); 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, tools, stepId, projectMemory = null, skillCatalog = null, mcpCatalog = null, transportReservationTokens = 0 }) { 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 lastUser = groups.findLast(group => group.messages[0].role === 'user'); const fixed = { role: 'system', content: system }; const breakdown = metrics => { const empty=requestMetrics(completionBody(config,[],[])).estimatedInputTokens; const fixedText=requestMetrics(completionBody(config,[fixed],[])).estimatedInputTokens; const fixedTools=requestMetrics(completionBody(config,[fixed],tools)).estimatedInputTokens; return {transportAndImageFramingTokens:empty-(metrics.imageReservationTokens??0),goalAndContextTextTokens:fixedText-empty, toolDefinitionTokens:fixedTools-fixedText,historyAndEvidenceTokens:metrics.estimatedInputTokens-fixedTools, imageReservationTokens:metrics.imageReservationTokens??0}; }; const ledger = new Map([...this.store.core.tool.values()].filter(tool => tool.sessionId === session.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], tools), before = requestMetrics(original); const selected = new Set(groups.map(group => group.index)); let omitted = [], reference = null, workingReference = null, latestReference = null; const latestDocument = latestToolDocument(this.store, session, run, groups); const entries = []; const metricsFor = (indices, includeNotice = true, currentEntries = entries, includeLatest = true) => { const missing = groups.filter(group => !indices.has(group.index)); const messages = [fixed, ...(missing.length && includeNotice ? [notice({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, missing, descriptions, evidence)] : []), ...(includeLatest && latestDocument && !indices.has(latestDocument.group_index) ? [latestToolMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, latestDocument)] : []), ...(currentEntries.length ? [workingMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, workingDocument(session, run, currentEntries))] : []), ...groups.filter(group => indices.has(group.index)).flatMap(group => group.messages)]; return requestMetrics(completionBody(config, messages, tools)); }; if (before.estimatedInputTokens > budget.targetInputTokens) { selected.clear(); if (lastUser) selected.add(lastUser.index); const mandatory = metricsFor(selected); if (mandatory.estimatedInputTokens > budget.inputBudget) throw pause(budget, mandatory, breakdown); const observed = workingCandidates(this.store, session, run, groups); // Reserve other small source files before admitting a new result group. // Historical locator pages are optional; they cannot evict actual code. const newest = groups.at(-1); const newestFiles = new Set((newest?.messages[0].tool_calls ?? []).filter(call => call.function.name === 'read_file').map(call => { try { return JSON.parse(call.function.arguments).path; } catch { return null; } })); const pinned = observed.filter(candidate => candidate.observation.kind === 'file' && candidate.observation.content.length <= 2000 && !newestFiles.has(candidate.observation.path)).slice(0, 12).map(candidate => workingEntry(candidate, candidate.observation.content.length)); const retention = Math.min(2048, Math.max(0, metricsFor(selected, true, pinned).estimatedInputTokens - mandatory.estimatedInputTokens)); const newestUseful = newest?.messages.every(message => { if (message.role !== 'tool') return true; try { const result = JSON.parse(message.content); return !result.kind?.startsWith('context-') && result.kind !== 'tool-result'; } catch { return true; } }); if (newestUseful && !selected.has(newest.index) && newest.contributionTokens <= budget.inputBudget) { selected.add(newest.index); if (metricsFor(selected).estimatedInputTokens + retention > budget.inputBudget) selected.delete(newest.index); } const target = Math.max(budget.targetInputTokens, metricsFor(selected).estimatedInputTokens); const priority = [...new Set(evidence.map(value => value.group_index))].map(index => groups[index]); const addGroup = group => { if (selected.has(group.index) || selected.size >= 32 || group.contributionTokens > target) return; selected.add(group.index); if (metricsFor(selected).estimatedInputTokens > target) selected.delete(group.index); }; // A small result in a mixed large group must remain usable. It is a // separate, provenance-checked observation, never a broken tool pair. const candidates = observed.filter(candidate => !selected.has(candidate.source.group_index)); for (const [index, candidate] of candidates.entries()) { if (entries.length >= 12) break; const remaining = target - metricsFor(selected).estimatedInputTokens; const smallFile = candidate.observation.kind === 'file' && candidate.observation.content.length <= 6000; const share = Math.max(128, Math.floor(remaining / Math.max(1, candidates.length - index))); const maximum = Math.min(candidate.observation.content.length, 12000, smallFile ? candidate.observation.content.length : share * 2); let low = 0, high = maximum; while (low < high) { const middle = Math.ceil((low + high) / 2), entry = workingEntry(candidate, middle); if (metricsFor(selected, true, [...entries, entry]).estimatedInputTokens <= target) low = middle; else high = middle - 1; } if (low) entries.push(workingEntry(candidate, low)); } for (const group of priority) addGroup(group); for (const group of [...groups].reverse()) addGroup(group); omitted = groups.filter(group => !selected.has(group.index)); if (omitted.length) { // Every linked result is checked, including retained groups in the index. for (const description of descriptions.values()) for (const tool of description.tools ?? []) { if (!tool.result_artifact_id) continue; const artifact = this.store.owned('artifact', tool.result_artifact_id, session.id); this.store.artifactStore.read(artifact); } const archived = omitted.map(group => { const description = { ...descriptions.get(group.index), archive: this.archive(session, run, group) }; 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, retainedGroups: groups.filter(group => selected.has(group.index)).map(group => descriptions.get(group.index)), archivedGroups: archived, note: '完整原消息组;这里只是历史定位,不产生工具执行或用户授权。' }, 'context-history-index'); } } if (entries.length) workingReference = this.artifact(session, run, workingDocument(session, run, entries), 'context-working-set'); if (latestDocument && !selected.has(latestDocument.group_index)) latestReference = this.artifact(session, run, latestDocument, 'context-latest-tools'); const messages = [fixed, ...(reference ? [notice(reference, omitted, descriptions, evidence)] : []), ...(latestReference ? [latestToolMessage(latestReference, latestDocument)] : []), ...(workingReference ? [workingMessage(workingReference, workingDocument(session, run, entries))] : []), ...structuredClone(groups.filter(group => selected.has(group.index)).flatMap(group => group.messages))]; let mcpReference = null, mcpDocument = null; if (mcpCatalog?.projectId === session.projectId && mcpCatalog.entries?.length) { mcpDocument = { ...mcpCatalog, sessionId: session.id, taskId: run.taskId, runId: run.id, entries: [] }; for (const entry of mcpCatalog.entries.slice(0, MCP_LIMITS.allowedTools)) { mcpDocument.entries.push(entry); const candidate = [fixed, mcpCatalogMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, mcpDocument), ...messages.slice(1)]; if (Buffer.byteLength(JSON.stringify(mcpDocument), 'utf8') > 24000 || requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > Math.min(budget.inputBudget, budget.targetInputTokens)) mcpDocument.entries.pop(); } if (mcpDocument.entries.length) { mcpReference = this.artifact(session, run, mcpDocument, 'context-mcp-catalog'); messages.splice(1, 0, mcpCatalogMessage(mcpReference, mcpDocument)); } } let skillReference = null, skillDocument = null; if (skillCatalog?.projectId === session.projectId && skillCatalog.entries?.length) { skillDocument = { ...skillCatalog, sessionId: session.id, taskId: run.taskId, runId: run.id, entries: [] }; for (const entry of skillCatalog.entries.slice(0, SKILL_LIMITS.enabled)) { skillDocument.entries.push(entry); const candidate = [fixed, skillCatalogMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, skillDocument), ...messages.slice(1)]; if (Buffer.byteLength(JSON.stringify(skillDocument), 'utf8') > SKILL_LIMITS.catalogBytes || requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > Math.min(budget.inputBudget, budget.targetInputTokens)) skillDocument.entries.pop(); } if (skillDocument.entries.length) { skillReference = this.artifact(session, run, skillDocument, 'context-skill-catalog'); messages.splice(1, 0, skillCatalogMessage(skillReference, skillDocument)); } } // Optional catalogs and memory use only space left after goals, paired history and current code evidence. let memoryReference = null, memoryDocument = null; if (projectMemory?.projectId === session.projectId && projectMemory.entries?.length) { memoryDocument = { ...projectMemory, sessionId: session.id, taskId: run.taskId, runId: run.id, entries: [] }; const memoryBudget = Math.min(budget.inputBudget, budget.targetInputTokens); for (const entry of projectMemory.entries.slice(0, MEMORY_CONTEXT_LIMITS.entries)) { if (entry.sourceFingerprint !== projectMemory.sourceFingerprint) continue; memoryDocument.entries.push(entry); const candidate = [fixed, projectMemoryMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, memoryDocument), ...messages.slice(1)]; if (Buffer.byteLength(JSON.stringify(memoryDocument), 'utf8') > MEMORY_CONTEXT_LIMITS.bytes || requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > memoryBudget) memoryDocument.entries.pop(); } if (memoryDocument.entries.length) { memoryReference = this.artifact(session, run, memoryDocument, 'context-project-memory'); messages.splice(1, 0, projectMemoryMessage(memoryReference, memoryDocument)); } } const body = completionBody(config, messages, tools), metrics = requestMetrics(body); if (metrics.estimatedInputTokens > budget.inputBudget) throw pause(budget, metrics, breakdown); const requestArtifact = this.artifact(session, run, body, 'model-request'); 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, estimateMethod: metrics.estimateMethod, beforeInputTokens: before.estimatedInputTokens, beforeBytes: before.bytes, budget, ...(metrics.imageCount?{imageCount:metrics.imageCount,imageReservationTokens:metrics.imageReservationTokens,imageEstimate:metrics.imageEstimate, inputImages:config.inputImages.map(({dataUrl,...identity})=>identity)}:{}), mandatoryInputTokens: metricsFor(new Set(lastUser ? [lastUser.index] : []), true, []).estimatedInputTokens, // The next result replaces the current latest-result feedback. Do not // reserve both views when sizing that result's actual protocol page. nextReadFixedInputTokens: metricsFor(new Set(lastUser ? [lastUser.index] : []), true, [], false).estimatedInputTokens, workingRetentionTokens: Math.min(2048, Math.max(0, metricsFor(new Set(lastUser ? [lastUser.index] : []), true, entries.filter(entry => entry.observation.kind === 'file' && !entry.truncated && entry.total_content_characters <= 2000)).estimatedInputTokens - metricsFor(new Set(lastUser ? [lastUser.index] : []), true, []).estimatedInputTokens)), originalMessages: session.providerMessages.length, retainedMessages: messages.length - 1 - (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, workingSetViewVersion: 2, latestToolsArtifactId: latestReference?.id ?? null, latestToolsSha256: latestReference?.sha256 ?? null, latestToolsEntries: latestReference ? latestDocument.entries.length : 0, projectMemoryArtifactId: memoryReference?.id ?? null, projectMemorySha256: memoryReference?.sha256 ?? null, projectMemoryEntries: memoryReference ? memoryDocument.entries.length : 0, skillCatalogArtifactId: skillReference?.id ?? null, skillCatalogSha256: skillReference?.sha256 ?? null, skillCatalogEntries: skillReference ? skillDocument.entries.length : 0, mcpCatalogArtifactId: mcpReference?.id ?? null, mcpCatalogSha256: mcpReference?.sha256 ?? null, mcpCatalogEntries: mcpReference ? mcpDocument.entries.length : 0, requestAttempts: 0, responseSha256: null, source: 'workbench' }; const artifact = this.artifact(session, run, record, 'context-plan'); record.artifactId = artifact.id; run.currentContextPlanId = record.id; session.estimatedTokens = record.estimatedInputTokens; const step = this.store.core.step.get(stepId); if (step) step.contextPlanId = record.id; this.store.putRecord('context_plan', session, record, 'context.prepared'); return { messages, body, record }; } finish(session, record, { response = null, error = null, attempts = 0 } = {}) { this.store.owned('context_plan', record.id, session.id); record.status = error ? error.name === 'AbortError' || session.status === 'stopping' ? 'interrupted' : 'failed' : 'completed'; record.finishedAt = new Date().toISOString(); record.actualUsage = response?.usage ?? null; record.responseSha256 = response?.message ? hash(response.message) : null; record.requestAttempts = attempts; if (error) record.error = String(error.message ?? error).slice(0, 800); this.store.save(session, { type: 'context.' + record.status, detail: { recordId: record.id } }); } } export function verifyPlanEvidence(store, session, plan, cache = new Map()) { const get = (id, kind, sha256 = null) => { const artifact = store.owned('artifact', id, session.id); if (artifact.kind !== kind || sha256 && artifact.sha256 !== sha256) throw new Error('上下文工件身份不匹配。'); return artifact; }; const request = get(plan.requestArtifactId, 'model-request', plan.requestSha256); const body = JSON.parse(store.artifactStore.read(request)), metrics = requestMetrics(body); if (metrics.bytes !== plan.requestBytes || metrics.estimatedInputTokens !== plan.estimatedInputTokens || requestVariants(body).some(value => outputReservation(value) !== plan.budget.outputReservation) || metrics.estimatedInputTokens > plan.budget.inputBudget) throw new Error('请求预算与原正文不匹配。'); 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 ['imageCount','imageReservationTokens','imageEstimate','inputImages']) { if(JSON.stringify(frozen[key]??null)!==JSON.stringify(plan[key]??null))throw new Error('图片身份或预算与发送前封存不匹配。'); } if(metrics.imageCount) { if(metrics.imageCount!==plan.imageCount||metrics.imageReservationTokens!==plan.imageReservationTokens||metrics.imageEstimate!==plan.imageEstimate ||plan.inputImages?.length!==metrics.imageCount)throw new Error('图片预算与实际正文不匹配。'); for(const variant of requestVariants(body)) { const images=requestImages(variant); if(images.length!==plan.inputImages.length)throw new Error('图片请求线路不一致。'); for(const [index,url] of images.entries()) { const identity=plan.inputImages[index],row=store.owned('input_attachment',identity.id,session.id); const artifact=get(row.sentArtifactId,'input-image-sent',identity.sha256),bytes=store.artifactStore.readBytes(artifact); const original=get(row.originalArtifactId,'input-image-original',row.sha256);store.artifactStore.readBytes(original); if(row.taskId!==plan.taskId||row.status!=='attached'||artifact.taskId!==plan.taskId||artifact.runId!==row.runId ||original.taskId!==plan.taskId||original.runId!==row.runId ||row.sentSha256!==identity.sha256||row.sentWidth!==identity.width||row.sentHeight!==identity.height ||url!=='data:image/png;base64,'+bytes.toString('base64'))throw new Error('图片原字节或任务归属与实际正文不匹配。'); } } } else if(plan.imageCount||plan.inputImages?.length)throw new Error('请求缺少封存的图像。'); if (frozen.id !== plan.id || frozen.requestSha256 !== plan.requestSha256 || frozen.requestArtifactId !== plan.requestArtifactId || JSON.stringify(frozen.budget) !== JSON.stringify(plan.budget)) throw new Error('请求计划与发送前的封存记录不匹配。'); if ((frozen.workingSetArtifactId ?? null) !== (plan.workingSetArtifactId ?? null) || (frozen.workingSetSha256 ?? null) !== (plan.workingSetSha256 ?? null) || (frozen.workingSetEntries ?? 0) !== (plan.workingSetEntries ?? 0)) throw new Error('工作依据与发送前的封存记录不匹配。'); if ((frozen.workingSetViewVersion ?? 1) !== (plan.workingSetViewVersion ?? 1) || (frozen.workingRetentionTokens ?? 0) !== (plan.workingRetentionTokens ?? 0)) throw new Error('工作依据视图或保留预算与封存记录不匹配。'); if ((frozen.nextReadFixedInputTokens ?? null) !== (plan.nextReadFixedInputTokens ?? null)) throw new Error('下一工具页的固定预算与封存记录不匹配。'); if ((frozen.latestToolsArtifactId ?? null) !== (plan.latestToolsArtifactId ?? null) || (frozen.latestToolsSha256 ?? null) !== (plan.latestToolsSha256 ?? null) || (frozen.latestToolsEntries ?? 0) !== (plan.latestToolsEntries ?? 0)) throw new Error('最新工具反馈与发送前的封存记录不匹配。'); if ((frozen.projectMemoryArtifactId ?? null) !== (plan.projectMemoryArtifactId ?? null) || (frozen.projectMemorySha256 ?? null) !== (plan.projectMemorySha256 ?? null) || (frozen.projectMemoryEntries ?? 0) !== (plan.projectMemoryEntries ?? 0)) throw new Error('项目记忆与发送前的封存记录不匹配。'); if (plan.projectMemoryArtifactId) { const artifact = get(plan.projectMemoryArtifactId, 'context-project-memory', plan.projectMemorySha256); const document = JSON.parse(store.artifactStore.read(artifact)); if (artifact.taskId !== plan.taskId || artifact.runId !== plan.runId || document.projectId !== session.projectId || document.sessionId !== session.id || document.taskId !== plan.taskId || document.runId !== plan.runId || document.kind !== 'source-checked-project-memory' || document.entries.length !== plan.projectMemoryEntries || document.entries.length > MEMORY_CONTEXT_LIMITS.entries || Buffer.byteLength(JSON.stringify(document), 'utf8') > MEMORY_CONTEXT_LIMITS.bytes || document.entries.some(entry => entry.sourceFingerprint !== document.sourceFingerprint)) throw new Error('项目记忆工件归属或范围不匹配。'); const message = projectMemoryMessage(artifact, document); if (requestHistory(body).filter(value => value.role === 'system' && value.content === message.content).length !== 1) throw new Error('项目记忆与实际发送内容不匹配。'); } if ((frozen.skillCatalogArtifactId ?? null) !== (plan.skillCatalogArtifactId ?? null) || (frozen.skillCatalogSha256 ?? null) !== (plan.skillCatalogSha256 ?? null) || (frozen.skillCatalogEntries ?? 0) !== (plan.skillCatalogEntries ?? 0)) throw new Error('技能目录与发送前的封存记录不匹配。'); if (plan.skillCatalogArtifactId) { const artifact = get(plan.skillCatalogArtifactId, 'context-skill-catalog', plan.skillCatalogSha256); const document = JSON.parse(store.artifactStore.read(artifact)); if (artifact.taskId !== plan.taskId || artifact.runId !== plan.runId || document.projectId !== session.projectId || document.sessionId !== session.id || document.taskId !== plan.taskId || document.runId !== plan.runId || document.kind !== 'registered-skill-catalog' || !Array.isArray(document.entries) || document.entries.length !== plan.skillCatalogEntries || document.entries.length > SKILL_LIMITS.enabled || Buffer.byteLength(JSON.stringify(document), 'utf8') > SKILL_LIMITS.catalogBytes || new Set(document.entries.map(entry => entry.id)).size !== document.entries.length) throw new Error('技能目录归属或范围不匹配。'); const message = skillCatalogMessage(artifact, document); if (requestHistory(body).filter(value => value.role === 'system' && value.content === message.content).length !== 1) throw new Error('技能目录与实际发送内容不匹配。'); } if ((frozen.mcpCatalogArtifactId ?? null) !== (plan.mcpCatalogArtifactId ?? null) || (frozen.mcpCatalogSha256 ?? null) !== (plan.mcpCatalogSha256 ?? null) || (frozen.mcpCatalogEntries ?? 0) !== (plan.mcpCatalogEntries ?? 0)) throw new Error('MCP目录与发送前的封存记录不匹配。'); if (plan.mcpCatalogArtifactId) { const artifact = get(plan.mcpCatalogArtifactId, 'context-mcp-catalog', plan.mcpCatalogSha256); const document = JSON.parse(store.artifactStore.read(artifact)); if (artifact.taskId !== plan.taskId || artifact.runId !== plan.runId || document.projectId !== session.projectId || document.sessionId !== session.id || document.taskId !== plan.taskId || document.runId !== plan.runId || document.kind !== 'registered-mcp-catalog' || !Array.isArray(document.entries) || document.entries.length !== plan.mcpCatalogEntries || document.entries.length > MCP_LIMITS.allowedTools || Buffer.byteLength(JSON.stringify(document), 'utf8') > 24000) throw new Error('MCP目录归属或范围不匹配。'); const message = mcpCatalogMessage(artifact, document); if (requestHistory(body).filter(value => value.role === 'system' && value.content === message.content).length !== 1) throw new Error('MCP目录与实际发送内容不匹配。'); } if (plan.latestToolsArtifactId) { 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))); const message = latestToolMessage(artifact, document); if (requestHistory(body).filter(value => value.role === 'system' && value.content === message.content).length !== 1) throw new Error('最新工具反馈与实际发送内容不匹配。'); } if (plan.workingSetArtifactId) { 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))); 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('工作依据与实际发送内容不匹配。'); } if (!plan.historyIndexArtifactId) return; const index = JSON.parse(store.artifactStore.read(get(plan.historyIndexArtifactId, 'context-history-index', plan.historyIndexSha256))); if (index.sessionId !== session.id || index.projectId !== session.projectId || index.taskId !== plan.taskId || index.kind !== 'request-history-index' || index.archivedGroups.length !== plan.archivedGroups) throw new Error('历史索引身份或范围不匹配。'); for (const group of index.archivedGroups) { const artifact = store.owned('artifact', group.archive.artifact_id, session.id), key = artifact.id + ':' + artifact.sha256; if (artifact.sha256 !== group.archive.sha256) throw new Error('原消息组工件身份不匹配。'); if (cache.get(key) !== group.sha256) { const text = store.artifactStore.read(artifact); if (artifact.kind === 'context-group') { if (hash(text) !== group.sha256) throw new Error('原消息组SHA256不匹配。'); historyGroups(JSON.parse(text)); } else if (artifact.kind === 'context-group-manifest') { const manifest = JSON.parse(text), digest = createHash('sha256'); let characters = 0, bytes = 0; if (manifest.kind !== 'context-group-chunks' || manifest.group_sha256 !== group.sha256) throw new Error('原消息组分片清单不匹配。'); for (const chunk of manifest.chunks) { const part = get(chunk.artifact_id, 'context-group-chunk', chunk.sha256), content = store.artifactStore.read(part); if (chunk.offset !== characters || chunk.characters !== content.length || part.bytes !== chunk.bytes) throw new Error('原消息组分片范围不匹配。'); characters += content.length; bytes += part.bytes; digest.update(content, 'utf8'); } if (characters !== manifest.characters || bytes !== manifest.bytes || digest.digest('hex') !== group.sha256) throw new Error('原消息组分片内容校验失败。'); } else throw new Error('原消息组工件格式不匹配。'); cache.set(key, group.sha256); } for (const tool of group.tools ?? []) { if (!tool.result_artifact_id) continue; const result = get(tool.result_artifact_id, 'tool-result', tool.result_sha256), resultKey = result.id + ':' + result.sha256; if (!cache.has(resultKey)) { store.artifactStore.read(result); cache.set(resultKey, result.sha256); } } } }