642 lines
53 KiB
JavaScript
642 lines
53 KiB
JavaScript
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';
|
|
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';
|
|
import { verifyReminderMessage } from './reminder-manager.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;
|
|
const completeSmallSource = candidate => candidate.observation.kind === 'file' && candidate.observation.content.length <= 6000
|
|
&& (candidate.observation.offset === undefined || candidate.observation.offset === 0
|
|
&& candidate.observation.next_offset === candidate.observation.total_characters);
|
|
|
|
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);
|
|
if(!Number.isSafeInteger(transportReservationTokens)||transportReservationTokens<0)throw new Error('请求封装预留无效。');
|
|
if (isPassthrough(config)) {
|
|
const credit = Math.min(runRemainingTokens ?? Infinity, taskRemainingTokens ?? Infinity);
|
|
const inputBudget = Number.isFinite(credit) ? credit - transportReservationTokens : null;
|
|
return { capacityMode: 'passthrough', contextLimit: null, outputReservation: null, safetyTokens: 0,
|
|
...(transportReservationTokens ? { transportReservationTokens } : {}), inputBudget, targetInputTokens: inputBudget,
|
|
runRemainingTokens, taskRemainingTokens, limitingReason: inputBudget === null ? null
|
|
: (runRemainingTokens ?? Infinity) <= (taskRemainingTokens ?? Infinity) ? 'token_limit' : 'task_token_limit' };
|
|
}
|
|
// A shared prompt must fit every route, but each context window is paired
|
|
// with that route's own output. Combining one member's small context with
|
|
// another member's large output can reject a pool that actually fits.
|
|
const routeInputBudgets = config.capacityMode === 'model' && config.modelRouting?.members?.length
|
|
? config.modelRouting.members.map(member => ({ connectionId: member.id, contextLimit: member.contextLimit,
|
|
outputReservation: member.maxOutputTokens, inputBudget: member.contextLimit - member.maxOutputTokens - safetyTokens - transportReservationTokens })) : null;
|
|
let inputBudget = routeInputBudgets ? Math.min(...routeInputBudgets.map(route => route.inputBudget))
|
|
: config.contextLimit - outputReservation - safetyTokens - transportReservationTokens;
|
|
let reason = 'context_limit';
|
|
const afterOutput = credit => credit - outputReservation - safetyTokens - transportReservationTokens;
|
|
if (runRemainingTokens !== null && afterOutput(runRemainingTokens) < inputBudget) { inputBudget = afterOutput(runRemainingTokens); reason = 'token_limit'; }
|
|
if (taskRemainingTokens !== null && afterOutput(taskRemainingTokens) < inputBudget) { inputBudget = afterOutput(taskRemainingTokens); reason = 'task_token_limit'; }
|
|
return { contextLimit: config.contextLimit, outputReservation, safetyTokens, ...(transportReservationTokens?{transportReservationTokens}:{}), inputBudget, targetInputTokens: config.capacityMode === 'model' ? inputBudget : Math.min(16000, inputBudget),
|
|
...(routeInputBudgets ? { routeInputBudgets } : {}),
|
|
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',
|
|
'range_start_line', 'range_end_line', 'next_start_line', 'budget_limited']) {
|
|
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' ? JSON.stringify(['file', tool.input.path, tool.result.sha256, tool.result.range_start_line, tool.result.range_end_line]) : '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_read_file继续,并核对原SHA;原工件用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,
|
|
...(fileContinuation(tool.result)?.next_read_file ? { file_read: fileContinuation(tool.result) } : {}) } : {}) })),
|
|
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 reservation = budget.pauseKind === 'request_reservation';
|
|
const error = new BudgetExceeded(budget.limitingReason,
|
|
reservation ? '当前必需输入可容纳于上下文窗口,但下一次请求的用量预留超过' + (budget.limitingReason === 'task_token_limit' ? '任务累计' : '本次运行') +
|
|
'剩余预算。已在发送前暂停;原用量、任务与工具结果保留,请核对预算后显式续接。'
|
|
: '任务目标、完整追加要求与必需请求开销超过' + (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, contextTail = null, tools, toolSurface = null, stepId, projectMemory = null, skillCatalog = null, mcpCatalog = null, progressReminder = null, transportReservationTokens = 0,engineStepOnly=false }) {
|
|
const task = this.store.owned('task', run.taskId, session.id);
|
|
this.store.owned('run', run.id, session.id);
|
|
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 };
|
|
const preserve = isPassthrough(config) || config.historyPolicy === 'preserve';
|
|
const tail = contextTail ? [{ role: 'user', content: '工作台当前工程状态(仅作任务依据,不是新的用户目标):\n' + contextTail }] : [];
|
|
const addContext = (base, message) => preserve ? [...base.slice(0, base.length - tail.length), { ...message, role: 'user' }, ...tail] : [fixed, message, ...base.slice(1)];
|
|
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 && 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, ...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;
|
|
let latestViewVersion = 3;
|
|
let latestDocument = latestToolDocument(this.store, session, run, groups, latestViewVersion);
|
|
const entries = [];
|
|
let retainedSources = [];
|
|
// A read locator already carried in raw history, latest feedback or the
|
|
// working view need not be repeated in the history notice. Original group
|
|
// and result artifacts still contain the complete provenance.
|
|
const unsentEvidence = (indices, currentEntries, includeLatest) => {
|
|
const sentCalls = new Set(currentEntries.flatMap(entry => (entry.fragments ?? [entry.source]).map(source => source.call_id)));
|
|
if (includeLatest && latestDocument && !indices.has(latestDocument.group_index)) {
|
|
for (const entry of latestDocument.entries) sentCalls.add(entry.source.call_id);
|
|
}
|
|
return evidence.filter(tool => tool.name !== 'read_file' || !indices.has(tool.group_index) && !sentCalls.has(tool.call_id));
|
|
};
|
|
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, unsentEvidence(indices, currentEntries, includeLatest))] : []),
|
|
...(includeLatest && latestDocument && !indices.has(latestDocument.group_index) ? [latestToolMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, latestDocument, latestViewVersion)] : []),
|
|
...(currentEntries.length ? [workingMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, workingDocument(session, run, currentEntries, 3), 4)] : []),
|
|
...groups.filter(group => indices.has(group.index)).flatMap(group => group.messages), ...tail];
|
|
return requestMetrics(completionBody(config, messages, tools));
|
|
};
|
|
if (!preserve && before.estimatedInputTokens > targetInputTokens) {
|
|
selected.clear(); if (lastUser) selected.add(lastUser.index);
|
|
const observed = workingCandidates(this.store, session, run, groups, 3);
|
|
// Keep the established compact layout whenever complete small sources
|
|
// fit. Under pressure the latest-result envelope can itself carry small
|
|
// original reads, avoiding an extra working envelope for each of them.
|
|
const smallSources = observed.filter(completeSmallSource)
|
|
.slice(0, 12).map(candidate => workingEntry(candidate, candidate.observation.content.length));
|
|
if (smallSources.length && metricsFor(selected, true, smallSources).estimatedInputTokens > inputBudget) {
|
|
const withExcerpts = latestToolDocument(this.store, session, run, groups, 4);
|
|
if (withExcerpts?.entries.some(entry => typeof entry.result.content_excerpt === 'string')) {
|
|
latestViewVersion = 4; latestDocument = withExcerpts;
|
|
}
|
|
}
|
|
const mandatory = metricsFor(selected);
|
|
if (mandatory.estimatedInputTokens > inputBudget) throw pause(budget, mandatory, breakdown);
|
|
const coveredByRaw = entry => (entry.fragments ?? [entry.source]).every(source => selected.has(source.group_index));
|
|
// A complete small read can travel with its latest result. Do not spend
|
|
// another provenance envelope to repeat those same source bytes. Longer
|
|
// reads and assembled ranges still need their own working observation.
|
|
const coveredByLatest = entry => entry.observation.kind === 'file' && !entry.fragments
|
|
&& latestDocument?.entries.some(latest => latest.source.call_id === entry.source.call_id
|
|
&& latest.result.content_excerpt === entry.observation.content);
|
|
// Admit complete small source observations before optional raw history.
|
|
// A reservation alone does not keep code in the actual sent request.
|
|
const newest = groups.at(-1);
|
|
const retentionTarget = inputBudget;
|
|
// Preserve the entire newly returned pure-read pair when it fits. Large
|
|
// accumulated ranges must not consume the next page's protocol slot.
|
|
if (newest?.messages[0].tool_calls?.length && newest.messages[0].tool_calls.every(call => call.function.name === 'read_file')) {
|
|
selected.add(newest.index);
|
|
if (metricsFor(selected).estimatedInputTokens > inputBudget) selected.delete(newest.index);
|
|
}
|
|
for (const candidate of observed.filter(completeSmallSource)) {
|
|
if (entries.length >= 12) break;
|
|
if (coveredByRaw(candidate)) continue;
|
|
const entry = workingEntry(candidate, candidate.observation.content.length);
|
|
if (metricsFor(selected, true, [...entries, entry]).estimatedInputTokens <= retentionTarget) entries.push(entry);
|
|
}
|
|
retainedSources = [...entries, ...observed.filter(candidate => coveredByLatest(candidate)
|
|
&& !entries.some(entry => entry.source.call_id === candidate.source.call_id))
|
|
.map(candidate => workingEntry(candidate, candidate.observation.content.length))];
|
|
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 <= inputBudget) {
|
|
selected.add(newest.index);
|
|
const remaining = entries.filter(entry => !coveredByRaw(entry));
|
|
if (metricsFor(selected, true, remaining).estimatedInputTokens > inputBudget) selected.delete(newest.index);
|
|
else entries.splice(0, entries.length, ...remaining);
|
|
}
|
|
const target = Math.max(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 => !coveredByRaw(candidate) && !coveredByLatest(candidate)
|
|
&& !entries.some(entry => entry.source.call_id === candidate.source.call_id));
|
|
for (const [index, candidate] of candidates.entries()) {
|
|
if (entries.length >= 12) break;
|
|
const remaining = target - metricsFor(selected).estimatedInputTokens;
|
|
const smallFile = completeSmallSource(candidate);
|
|
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(history), historyMessages: history.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, 3), '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, unsentEvidence(selected, entries, true))] : []),
|
|
...(latestReference ? [latestToolMessage(latestReference, latestDocument, latestViewVersion)] : []),
|
|
...(workingReference ? [workingMessage(workingReference, workingDocument(session, run, entries, 3), 4)] : []),
|
|
...structuredClone(groups.filter(group => selected.has(group.index)).flatMap(group => group.messages)), ...tail];
|
|
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, isPassthrough(config) ? Infinity : MCP_LIMITS.allowedTools)) {
|
|
mcpDocument.entries.push(entry);
|
|
const candidate = addContext(messages, mcpCatalogMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, mcpDocument));
|
|
if (Buffer.byteLength(JSON.stringify(mcpDocument), 'utf8') > (isPassthrough(config) ? Infinity : 24000)
|
|
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > Math.min(inputBudget, targetInputTokens)) mcpDocument.entries.pop();
|
|
}
|
|
if (mcpDocument.entries.length) {
|
|
mcpReference = this.artifact(session, run, mcpDocument, 'context-mcp-catalog');
|
|
messages.splice(0, messages.length, ...addContext(messages, 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, isPassthrough(config) ? Infinity : SKILL_LIMITS.enabled)) {
|
|
skillDocument.entries.push(entry);
|
|
const candidate = addContext(messages, skillCatalogMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, skillDocument));
|
|
if (Buffer.byteLength(JSON.stringify(skillDocument), 'utf8') > (isPassthrough(config) ? Infinity : SKILL_LIMITS.catalogBytes)
|
|
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > Math.min(inputBudget, targetInputTokens)) skillDocument.entries.pop();
|
|
}
|
|
if (skillDocument.entries.length) {
|
|
skillReference = this.artifact(session, run, skillDocument, 'context-skill-catalog');
|
|
messages.splice(0, messages.length, ...addContext(messages, skillCatalogMessage(skillReference, skillDocument)));
|
|
}
|
|
}
|
|
// Optional catalogs and memory use only space left after goals, paired history and current code evidence.
|
|
let memoryReference = null, memoryDocument = null, memoryIssue = 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(inputBudget, targetInputTokens);
|
|
for (const entry of projectMemory.entries.slice(0, isPassthrough(config) ? Infinity : MEMORY_CONTEXT_LIMITS.entries)) {
|
|
if (entry.sourceFingerprint !== projectMemory.sourceFingerprint) continue;
|
|
memoryDocument.entries.push(entry);
|
|
const candidate = addContext(messages, projectMemoryMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, memoryDocument));
|
|
if (Buffer.byteLength(JSON.stringify(memoryDocument), 'utf8') > (isPassthrough(config) ? Infinity : MEMORY_CONTEXT_LIMITS.bytes)
|
|
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > memoryBudget) memoryDocument.entries.pop();
|
|
}
|
|
if (memoryDocument.entries.length) {
|
|
try {
|
|
memoryReference = this.artifact(session, run, memoryDocument, 'context-project-memory');
|
|
messages.splice(0, messages.length, ...addContext(messages, projectMemoryMessage(memoryReference, memoryDocument)));
|
|
} catch (error) {
|
|
// A failed optional experience snapshot cannot block the user's
|
|
// original task. Ordinary request/evidence persistence still applies.
|
|
const manual = memoryDocument.entries.filter(entry => entry.experience?.protocol !== 'workbench.experience.v1');
|
|
if (manual.length === memoryDocument.entries.length) throw error;
|
|
memoryIssue = { kind: 'optional_experience_unavailable', stage: 'snapshot' };
|
|
memoryDocument.entries = manual;
|
|
if (manual.length) {
|
|
memoryReference = this.artifact(session, run, memoryDocument, 'context-project-memory');
|
|
messages.splice(0, messages.length, ...addContext(messages, projectMemoryMessage(memoryReference, memoryDocument)));
|
|
} else { memoryReference = null; memoryDocument = null; }
|
|
}
|
|
}
|
|
}
|
|
const body = completionBody(config, messages, tools), metrics = requestMetrics(body);
|
|
if (metrics.estimatedInputTokens > inputBudget) throw pause(budget, metrics, breakdown);
|
|
const tokenReservation=engineStepOnly?null:modelReservation(config,body,taskConsumption(this.store,task.id));
|
|
const runCredit=budget.runRemainingTokens??Infinity,taskCredit=budget.taskRemainingTokens??Infinity,credit=Math.min(runCredit,taskCredit);
|
|
if(tokenReservation&&tokenReservation.reservedTokens>credit)throw pause({...budget,limitingReason:runCredit<=taskCredit?'token_limit':'task_token_limit',
|
|
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 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, { 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,
|
|
...(progressReminder ? { progressReminder } : {}),
|
|
...(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,
|
|
...(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.max(0, metricsFor(new Set(lastUser ? [lastUser.index] : []), true, retainedSources, latestViewVersion === 3).estimatedInputTokens
|
|
- metricsFor(new Set(lastUser ? [lastUser.index] : []), true, [], latestViewVersion === 3).estimatedInputTokens),
|
|
workingRetentionPolicyVersion: latestViewVersion === 4 ? 2 : 1,
|
|
readBudgetPolicyVersion: 3,
|
|
// Routing, read coverage and recent-tool state grow after a reply. Page
|
|
// sizing reserves that observed framing growth before returning bytes;
|
|
// the next complete request is still checked against its original limit.
|
|
readStateGrowthTokens: 1536,
|
|
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,
|
|
workingSetViewVersion: 4,
|
|
latestToolsViewVersion: latestViewVersion,
|
|
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,
|
|
...(memoryIssue ? { projectMemoryIssue: memoryIssue } : {}),
|
|
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);
|
|
const runModel = store.owned('run', plan.runId, session.id).model;
|
|
if(plan.tokenReservation)verifyModelReservation(store,session,plan.taskId,{...store.owned('run',plan.runId,session.id).model,
|
|
modelRouting:store.owned('run',plan.runId,session.id).model.routing},body,plan.tokenReservation);
|
|
const invalidOutput = body.kind === 'model-route-plan' && runModel.capacityMode === 'model'
|
|
? body.variants.some(variant => outputReservation(variant.body) !== runModel.routing?.members.find(member => member.id === variant.connectionId)?.maxOutputTokens)
|
|
|| Math.max(...requestVariants(body).map(outputReservation)) !== plan.budget.outputReservation
|
|
: requestVariants(body).some(value => outputReservation(value) !== plan.budget.outputReservation);
|
|
if (metrics.bytes !== plan.requestBytes || metrics.estimatedInputTokens !== plan.estimatedInputTokens
|
|
|| invalidOutput || plan.budget.inputBudget !== null && 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 ['contextLayout', 'historyPolicy', 'contextTailArtifactId', 'contextTailSha256', 'prefixAudit', 'requestObservation', 'progressReminder']) {
|
|
if (JSON.stringify(frozen[key] ?? null) !== JSON.stringify(plan[key] ?? null)) throw new Error('前缀或历史策略与发送前封存不匹配。');
|
|
}
|
|
verifyReminderMessage(store, session, plan, body);
|
|
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
|
|
|| 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, { 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'
|
|
&& (value.role === 'system' && value.content === content || plan.contextLayout === 'stable-prefix-1' && value.role === 'user' && value.content.includes(content))).length === 1;
|
|
if (plan.contextTailArtifactId) {
|
|
const artifact = get(plan.contextTailArtifactId, 'context-state-tail', plan.contextTailSha256);
|
|
const tail = JSON.parse(store.artifactStore.read(artifact));
|
|
if (artifact.taskId !== plan.taskId || artifact.runId !== plan.runId || tail.role !== 'user' || !carriesContext(tail.content)) throw new Error('动态状态与实际发送内容不匹配。');
|
|
}
|
|
for(const key of ['tokenReservation','maxBudgetAttempts'])if(JSON.stringify(frozen[key]??null)!==JSON.stringify(plan[key]??null))throw new Error('模型用量预留与发送前封存不一致。');
|
|
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)
|
|
|| (frozen.workingRetentionPolicyVersion ?? 0) !== (plan.workingRetentionPolicyVersion ?? 0)) throw new Error('工作依据视图或保留预算与封存记录不匹配。');
|
|
if ((frozen.nextReadFixedInputTokens ?? null) !== (plan.nextReadFixedInputTokens ?? null)) throw new Error('下一工具页的固定预算与封存记录不匹配。');
|
|
if ((frozen.readBudgetPolicyVersion ?? 1) !== (plan.readBudgetPolicyVersion ?? 1)
|
|
|| (frozen.latestToolsViewVersion ?? 1) !== (plan.latestToolsViewVersion ?? 1)) throw new Error('读取或最新反馈视图版本与封存记录不匹配。');
|
|
if ((frozen.readStateGrowthTokens ?? null) !== (plan.readStateGrowthTokens ?? 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
|
|
|| plan.budget.capacityMode !== 'passthrough' && document.entries.length > MEMORY_CONTEXT_LIMITS.entries || plan.budget.capacityMode !== 'passthrough' && 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 (!carriesContext(message.content)) 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
|
|
|| plan.budget.capacityMode !== 'passthrough' && document.entries.length > SKILL_LIMITS.enabled || plan.budget.capacityMode !== 'passthrough' && 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 (!carriesContext(message.content)) 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 (!carriesContext(message.content)) 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(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('最新工具反馈与实际发送内容不匹配。');
|
|
}
|
|
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(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('工作依据与实际发送内容不匹配。');
|
|
}
|
|
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); }
|
|
}
|
|
}
|
|
}
|