feat(runtime): default to passthrough and persist execution permissions

This commit is contained in:
Agent Workbench Dev
2026-11-06 04:58:57 +08:00
parent 67c034f4b6
commit 2fa220735d
113 changed files with 1866 additions and 631 deletions
+1 -1
View File
@@ -61,7 +61,7 @@ export class IndexCache {
if (envelope.schemaVersion !== 1 || hash(JSON.stringify(envelope.payload)) !== envelope.sha256) return { entries: null, reason: 'corrupt' };
const payload = envelope.payload;
if (JSON.stringify(payload.identity) !== JSON.stringify(identity)) return { entries: null, reason: 'identity-changed' };
if (!Array.isArray(payload.entries) || payload.entries.length > 1000) return { entries: null, reason: 'corrupt' };
if (!Array.isArray(payload.entries) || payload.entries.length > (this.maximumProjects === Infinity ? Infinity : 1000)) return { entries: null, reason: 'corrupt' };
return { entries: new Map(payload.entries.map(entry => [entry.path, entry])), reason: 'disk' };
} catch { this.error = '派生缓存读取失败;本次从当前源码重建。'; return { entries: null, reason: 'unavailable' }; }
}
+12 -11
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import { randomUUID } from 'node:crypto';
import { PNG } from 'pngjs';
import jpeg from 'jpeg-js';
@@ -78,23 +79,23 @@ function sentImage(decoded, orientation, maximum) {
}
return { bytes:PNG.sync.write(output),width,height };
}
export function validateImage(input) {
export function validateImage(input, config = {}) {
if (!input || Object.keys(input).some(key => !['name','mediaType','base64'].includes(key)) || typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160
|| /[\\/\x00-\x1f]/.test(input.name) || !['image/png','image/jpeg'].includes(input.mediaType) || typeof input.base64 !== 'string') throw reject('请选择PNG或JPEG图片,文件名不能包含路径。');
if (input.base64.length > Math.ceil(IMAGE_LIMITS.bytes / 3) * 4) throw reject('单张图片最多2MB,请先裁剪或压缩。',413);
if (input.base64.length > Math.ceil(ceiling(config, IMAGE_LIMITS.bytes) / 3) * 4) throw reject('单张图片最多2MB,请先裁剪或压缩。',413);
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input.base64)) throw reject('图片编码无效。');
const bytes = Buffer.from(input.base64,'base64');
if (bytes.length > IMAGE_LIMITS.bytes) throw reject('单张图片最多2MB,请先裁剪或压缩。',413);
if (bytes.length > ceiling(config, IMAGE_LIMITS.bytes)) throw reject('单张图片最多2MB,请先裁剪或压缩。',413);
if (!bytes.length || bytes.toString('base64') !== input.base64) throw reject('图片编码或大小无效。');
const size = dimensions(bytes,input.mediaType);
if (!size.width || !size.height || Math.max(size.width,size.height)>IMAGE_LIMITS.dimension || size.width*size.height>IMAGE_LIMITS.pixels) throw reject('图片尺寸过大,请裁剪后再添加。',413);
if (!size.width || !size.height || Math.max(size.width,size.height)>ceiling(config, IMAGE_LIMITS.dimension) || size.width*size.height>ceiling(config, IMAGE_LIMITS.pixels)) throw reject('图片尺寸过大,请裁剪后再添加。',413);
let decoded;
try { decoded = input.mediaType==='image/png' ? PNG.sync.read(bytes,{checkCRC:true}) : jpeg.decode(bytes,{useTArray:true,tolerantDecoding:false,maxResolutionInMP:16.8,maxMemoryUsageInMB:160}); }
try { decoded = input.mediaType==='image/png' ? PNG.sync.read(bytes,{checkCRC:true}) : jpeg.decode(bytes,{useTArray:true,tolerantDecoding:false,maxResolutionInMP:ceiling(config,16.8),maxMemoryUsageInMB:ceiling(config,160)}); }
catch { throw reject('图片无法完整解码,请重新导出PNG/JPEG。'); }
if (decoded.width!==size.width || decoded.height!==size.height) throw reject('图片实际尺寸不一致。');
let maximum = IMAGE_LIMITS.sentDimension, sent = sentImage(decoded,size.orientation,maximum);
while(sent.bytes.length>IMAGE_LIMITS.sentBytes && maximum>64) { maximum=Math.floor(maximum*0.75);sent=sentImage(decoded,size.orientation,maximum); }
if(sent.bytes.length>IMAGE_LIMITS.sentBytes)throw reject('图片发送副本超过大小限制,请先裁剪。',413);
let maximum = unrestricted(config) ? Math.max(decoded.width, decoded.height) : IMAGE_LIMITS.sentDimension, sent = sentImage(decoded,size.orientation,maximum);
while(sent.bytes.length>ceiling(config, IMAGE_LIMITS.sentBytes) && maximum>64) { maximum=Math.floor(maximum*0.75);sent=sentImage(decoded,size.orientation,maximum); }
if(sent.bytes.length>ceiling(config, IMAGE_LIMITS.sentBytes))throw reject('图片发送副本超过大小限制,请先裁剪。',413);
return { bytes, sent:sent.bytes, width:size.width,height:size.height,orientation:size.orientation,sentWidth:sent.width,sentHeight:sent.height };
}
@@ -103,8 +104,8 @@ export class InputAttachments {
list(session) { return [...this.store.core.input_attachment.values()].filter(row=>row.sessionId===session.id && ['draft','attached'].includes(row.status)).map(row=>structuredClone(row)); }
upload(session,input) {
if(this.busy(session.projectId))throw reject('请等待当前项目执行结束后再添加附件。',409);
if(this.list(session).filter(row=>row.status==='draft').length>=IMAGE_LIMITS.drafts)throw reject('待发送图片已满,请先移除不用的图片。',409);
const value=validateImage(input),identity={id:session.id,projectId:session.projectId,taskId:null,runId:null};
if(this.list(session).filter(row=>row.status==='draft').length>=ceiling(this.store, IMAGE_LIMITS.drafts))throw reject('待发送图片已满,请先移除不用的图片。',409);
const value=validateImage(input, this.store.config),identity={id:session.id,projectId:session.projectId,taskId:null,runId:null};
const original=this.store.artifactStore.write(identity,null,value.bytes,{kind:'input-image-original',mediaType:input.mediaType});
const sent=this.store.artifactStore.write(identity,null,value.sent,{kind:'input-image-sent',mediaType:'image/png'});
this.store.core.artifact.set(original.id,original);this.store.core.artifact.set(sent.id,sent);
@@ -120,7 +121,7 @@ export class InputAttachments {
row.status='withdrawn';this.store.save(session,{type:'input_attachment.withdrawn'});return this.list(session);
}
validateSelection(session,ids) {
if(!Array.isArray(ids)||ids.length>IMAGE_LIMITS.perTask||new Set(ids).size!==ids.length)throw reject('每个任务当前支持一张图片。');
if(!Array.isArray(ids)||ids.length>ceiling(this.store, IMAGE_LIMITS.perTask)||new Set(ids).size!==ids.length)throw reject('每个任务当前支持一张图片。');
return ids.map(id=>{const row=this.get(session,id);if(row.status!=='draft')throw reject('图片已发送或移除,请重新选择。',409);this.read(session,id);this.read(session,id,{original:true});return row;});
}
read(session,id,{original=false}={}) {
+16 -14
View File
@@ -15,7 +15,7 @@ const names = { FunctionDeclaration: 'function', FunctionExpression: 'function',
const parserVersion = 'babel-parser-7.29.11';
const nodeName = node => node?.type === 'Identifier' ? node.name : node?.type === 'PrivateName' ? '#' + node.id.name : node?.type === 'StringLiteral' ? node.value : null;
function javascript(source, filename, maximumNodes, maximumSymbols) {
function javascript(source, filename, maximumNodes, maximumSymbols, open = false) {
const plugins = [...(/\.(?:[mc]?ts|tsx)$/i.test(filename) ? ['typescript'] : []), ...(/\.(?:[mc]?js|jsx|tsx)$/i.test(filename) ? ['jsx'] : []), 'decorators-legacy'];
const ast = parse(source, { sourceType: 'unambiguous', plugins, createImportExpressions: true, allowReturnOutsideFunction: true, allowAwaitOutsideFunction: true });
const exported = new Set(), exportNames = new Set(), topLevel = new Set();
@@ -58,8 +58,8 @@ function javascript(source, filename, maximumNodes, maximumSymbols) {
else if (node.type === 'ImportExpression') { sourceNode = node.source; importKind = 'literal-dynamic-import'; }
else if (node.type === 'CallExpression' && node.callee?.type === 'Identifier' && node.callee.name === 'require') { sourceNode = node.arguments[0]; importKind = 'literal-require-call'; }
else if (node.type === 'TSImportEqualsDeclaration' && node.moduleReference?.type === 'TSExternalModuleReference') { sourceNode = node.moduleReference.expression; importKind = 'import-equals'; }
if (sourceNode?.type === 'StringLiteral' && imports.length < 400) imports.push({ source: sourceNode.value.slice(0, 500), line: node.loc.start.line,
kind: importKind, bindings: node.type === 'TSImportEqualsDeclaration' ? [nodeName(node.id)].filter(Boolean) : (node.specifiers ?? []).map(value => nodeName(value.local)).filter(Boolean).slice(0, 30), evidenceMethod: 'javascript-typescript-ast' });
if (sourceNode?.type === 'StringLiteral' && imports.length < (open ? Infinity : 400)) imports.push({ source: sourceNode.value.slice(0, open ? Infinity : 500), line: node.loc.start.line,
kind: importKind, bindings: node.type === 'TSImportEqualsDeclaration' ? [nodeName(node.id)].filter(Boolean) : (node.specifiers ?? []).map(value => nodeName(value.local)).filter(Boolean).slice(0, open ? Infinity : 30), evidenceMethod: 'javascript-typescript-ast' });
else if (sourceNode) { truncated = true; if (sourceNode.type !== 'StringLiteral') opaqueImports++; }
let childScope = scope;
if (name && (names[node.type] && ['function', 'class'].includes(kind) || node.type === 'VariableDeclarator' && kind === 'function' || kind === 'method')) childScope = [...scope, name];
@@ -72,7 +72,7 @@ function javascript(source, filename, maximumNodes, maximumSymbols) {
// This lexer only removes comments and string bodies so declaration candidates
// do not come from docstrings. It is deliberately not a Python compiler.
function python(source, maximumSymbols) {
function python(source, maximumSymbols, open = false) {
let triple = null, quote = null, escaped = false, truncated = false, bracketDepth = 0, lineContinuation = false;
const symbols = [], imports = [], scopes = [];
const lines = source.split('\n');
@@ -109,7 +109,7 @@ function python(source, maximumSymbols) {
if (imported) {
const sources = imported[1] ? [imported[1]] : imported[3].split(',').map(value => value.trim().split(/\s+/)[0]);
for (const source of sources) if (source) {
if (imports.length < 400) imports.push({ source: source.slice(0, 500), line: index + 1, kind: 'python-import-candidate', bindings: [], evidenceMethod: 'python-declaration-candidate' });
if (imports.length < (open ? Infinity : 400)) imports.push({ source: source.slice(0, open ? Infinity : 500), line: index + 1, kind: 'python-import-candidate', bindings: [], evidenceMethod: 'python-declaration-candidate' });
else truncated = true;
}
}
@@ -143,7 +143,9 @@ function resolveImport(from, dependency, files) {
export class ProjectIndex {
constructor({ maximumProjects = 8, maximumFileBytes = 256000, maximumSymbols = 6000, maximumSymbolsPerFile = 300, maximumAstNodes = 80000,
cacheDirectory, maximumCacheBytes = 32 * 1024 * 1024, maximumEntryBytes = 8 * 1024 * 1024, parserRevision = 'index-2-python-candidates-1' } = {}) {
cacheDirectory, maximumCacheBytes = 32 * 1024 * 1024, maximumEntryBytes = 8 * 1024 * 1024, executionMode = 'restricted', parserRevision = 'index-2-python-candidates-1' } = {}) {
this.open = executionMode === 'unrestricted';
if (this.open) maximumProjects = maximumFileBytes = maximumSymbols = maximumSymbolsPerFile = maximumAstNodes = maximumCacheBytes = maximumEntryBytes = Infinity;
this.maximumProjects = maximumProjects; this.maximumFileBytes = maximumFileBytes; this.maximumSymbols = maximumSymbols;
this.maximumSymbolsPerFile = maximumSymbolsPerFile; this.maximumAstNodes = maximumAstNodes;
this.projects = new Map(); this.pending = new Map(); this.identities = new Map(); this.latest = new Map(); this.memoryBytes = new Map(); this.generation = 0;
@@ -189,7 +191,7 @@ export class ProjectIndex {
const text = readText(project, file.path);
if (text.sha256 !== file.sha256) throw conflict('建立索引期间文件已变化,请刷新工程索引:' + file.path);
const parseStarted = performance.now(); parsedFiles++;
try { Object.assign(entry, js.test(file.path) ? javascript(text.content, file.path, this.maximumAstNodes, this.maximumSymbolsPerFile) : python(text.content, this.maximumSymbolsPerFile)); }
try { Object.assign(entry, js.test(file.path) ? javascript(text.content, file.path, this.maximumAstNodes, this.maximumSymbolsPerFile, this.open) : python(text.content, this.maximumSymbolsPerFile, this.open)); }
finally { parseMs += performance.now() - parseStarted; }
entry.status = entry.truncated ? 'partial' : 'indexed';
} catch (error) {
@@ -212,7 +214,7 @@ export class ProjectIndex {
const allSymbols = entries.flatMap(file => file.symbols.map(value => ({ ...value, path: file.path, sha256: file.sha256, language: file.language })));
const symbols = allSymbols.slice(0, this.maximumSymbols).sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line || a.name.localeCompare(b.name));
const allImports = entries.flatMap(file => file.imports.map(value => resolveImport(file.path, value, available)));
const imports = allImports.slice(0, 6000);
const imports = allImports.slice(0, this.open ? Infinity : 6000);
const removedFiles = [...previous.keys()].filter(file => !next.has(file)).length;
const entryBytes = Buffer.byteLength(JSON.stringify([...next.values()])), withinCapacity = entryBytes <= Math.min(this.cache.maximumEntryBytes, this.cache.maximumBytes);
const canStore = this.cache.enabled && inspection.scope.complete && generation === this.generation && withinCapacity;
@@ -251,21 +253,21 @@ export class ProjectIndex {
sourceScope: index.sourceScope, warnings: index.warnings.slice(0, 20), notes: index.notes, ...(index.cache ? { cache: index.cache } : {}) };
}
validEntry(entry) {
const bounded = value => typeof value === 'string' && value.length <= 10000;
const bounded = value => typeof value === 'string' && value.length <= (this.open ? Infinity : 10000);
return Array.isArray(entry.symbols) && entry.symbols.length <= this.maximumSymbolsPerFile
&& entry.symbols.every(value => value && bounded(value.name) && bounded(value.qualifiedName) && bounded(value.kind) && bounded(value.signature)
&& Number.isInteger(value.column) && value.column > 0 && Number.isInteger(value.line) && value.line > 0
&& Number.isInteger(value.endLine) && value.endLine >= value.line && typeof value.exported === 'boolean' && bounded(value.evidenceMethod))
&& Array.isArray(entry.imports) && entry.imports.length <= 400
&& Array.isArray(entry.imports) && entry.imports.length <= (this.open ? Infinity : 400)
&& entry.imports.every(value => value && bounded(value.source) && bounded(value.kind) && bounded(value.evidenceMethod) && Number.isInteger(value.line) && value.line > 0
&& Array.isArray(value.bindings) && value.bindings.length <= 30 && value.bindings.every(bounded))
&& Array.isArray(value.bindings) && value.bindings.length <= (this.open ? Infinity : 30) && value.bindings.every(bounded))
&& ['metadata-only', 'indexed', 'partial', 'outside-index-budget'].includes(entry.status)
&& ['file-sha256', 'javascript-typescript-ast', 'python-declaration-candidate'].includes(entry.method)
&& typeof entry.truncated === 'boolean';
}
query(index, { query = '', kind = 'all', limit = 30 } = {}) {
if (typeof query !== 'string' || query.length > 200 || !['all', 'symbols', 'imports', 'files'].includes(kind)
|| !Number.isInteger(limit) || limit < 1 || limit > 60) throw new Error('索引查询需要200字以内文本、有效类型与1到60条结果上限。');
query(index, { query = '', kind = 'all', limit = this.open ? Infinity : 30 } = {}) {
if (typeof query !== 'string' || query.length > (this.open ? Infinity : 200) || !['all', 'symbols', 'imports', 'files'].includes(kind)
|| !(this.open && limit === Infinity) && (!Number.isSafeInteger(limit) || limit < 1 || !this.open && limit > 60)) throw new Error('索引查询需要200字以内文本、有效类型与1到60条结果上限。');
const terms = query.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean);
const score = (name, filename) => {
const lower = name.toLocaleLowerCase(), all = (name + ' ' + filename).toLocaleLowerCase();
+6 -2
View File
@@ -11,7 +11,7 @@ const pooledReads = calls => calls?.length && calls.every(isPagedRead) && (calls
// This is the actual tool page, not a rewrite of a historical result. Count
// the escaped JSON tool message which will be present in the next request.
export function artifactPage(artifact, text, args, { maximumMessageBytes = 16000, callId = '' } = {}) {
const requestedOffset = args.offset ?? 0, requestedLimit = args.limit ?? 2000;
const requestedOffset = args.offset ?? 0, requestedLimit = args.limit ?? (maximumMessageBytes === Infinity ? text.length : 2000);
let offset = Math.min(requestedOffset, text.length);
if (offset > 0 && /[\uDC00-\uDFFF]/.test(text[offset]) && /[\uD800-\uDBFF]/.test(text[offset - 1])) offset--;
let maximumEnd = boundary(text, Math.min(offset + requestedLimit, text.length));
@@ -32,6 +32,7 @@ export function artifactPage(artifact, text, args, { maximumMessageBytes = 16000
}
export function readMessageBudget(plan, message) {
if (plan.budget.inputBudget === null) return Infinity;
const calls = message.tool_calls?.length ?? 1;
const assistantTokens = Math.ceil(Buffer.byteLength(JSON.stringify(message), 'utf8') / 3) + 8;
// Reserve space for the current call's framing and the next state/notice.
@@ -46,7 +47,10 @@ export function readMessageBudget(plan, message) {
// read. Mixed batches and historical plans retain the original 2560 reserve.
// This is page sizing, never dispatch authorization: the complete next wire
// request and observed-usage reservation are still checked independently.
const growth = Math.max(plan.readStateGrowthTokens ?? 0, pureReads ? 512 + Math.min(2048, Math.max(0, calls - 1) * 256) : 2560);
// Browser fields do not grow source-page coverage. Keep the larger source
// reservation for file/artifact reads without shrinking a small browser page.
const browserOnly = message.tool_calls?.length && message.tool_calls.every(call => call.function.name === 'read_browser_result');
const growth = Math.max(browserOnly ? 0 : plan.readStateGrowthTokens ?? 0, pureReads ? 512 + Math.min(2048, Math.max(0, calls - 1) * 256) : 2560);
const tokens = plan.budget.inputBudget - (plan.nextReadFixedInputTokens ?? plan.mandatoryInputTokens) - (plan.workingRetentionTokens ?? 0) - assistantTokens - calls * 8 - growth;
return Math.max(1024, Math.floor(tokens * 3 / calls));
}
+33 -23
View File
@@ -9,6 +9,7 @@ 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 { isPassthrough } from '../../shared/contracts/model-capacity.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';
@@ -61,6 +62,14 @@ export function budgetFor(config, run, task, transportReservationTokens = 0) {
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.
@@ -182,9 +191,10 @@ export class RequestPlanner {
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 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 = config.historyPolicy === 'preserve';
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 => {
@@ -199,7 +209,7 @@ export class RequestPlanner {
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);
if (preserve && before.estimatedInputTokens > budget.inputBudget) throw pause(budget, before, breakdown);
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;
@@ -224,7 +234,7 @@ export class RequestPlanner {
...groups.filter(group => indices.has(group.index)).flatMap(group => group.messages), ...tail];
return requestMetrics(completionBody(config, messages, tools));
};
if (!preserve && before.estimatedInputTokens > budget.targetInputTokens) {
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
@@ -232,14 +242,14 @@ export class RequestPlanner {
// 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 > budget.inputBudget) {
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 > budget.inputBudget) throw pause(budget, mandatory, breakdown);
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
@@ -250,12 +260,12 @@ export class RequestPlanner {
// 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 = budget.inputBudget;
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 > budget.inputBudget) selected.delete(newest.index);
if (metricsFor(selected).estimatedInputTokens > inputBudget) selected.delete(newest.index);
}
for (const candidate of observed.filter(completeSmallSource)) {
if (entries.length >= 12) break;
@@ -270,13 +280,13 @@ export class RequestPlanner {
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) {
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 > budget.inputBudget) selected.delete(newest.index);
if (metricsFor(selected, true, remaining).estimatedInputTokens > inputBudget) selected.delete(newest.index);
else entries.splice(0, entries.length, ...remaining);
}
const target = Math.max(budget.targetInputTokens, metricsFor(selected).estimatedInputTokens);
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;
@@ -329,11 +339,11 @@ export class RequestPlanner {
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)) {
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') > 24000
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > Math.min(budget.inputBudget, budget.targetInputTokens)) mcpDocument.entries.pop();
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');
@@ -343,11 +353,11 @@ export class RequestPlanner {
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)) {
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') > SKILL_LIMITS.catalogBytes
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > Math.min(budget.inputBudget, budget.targetInputTokens)) skillDocument.entries.pop();
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');
@@ -358,12 +368,12 @@ export class RequestPlanner {
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)) {
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') > MEMORY_CONTEXT_LIMITS.bytes
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) {
@@ -372,7 +382,7 @@ export class RequestPlanner {
}
}
const body = completionBody(config, messages, tools), metrics = requestMetrics(body);
if (metrics.estimatedInputTokens > budget.inputBudget) throw pause(budget, metrics, breakdown);
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',
@@ -453,7 +463,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|| 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 || metrics.estimatedInputTokens > plan.budget.inputBudget) throw new Error('请求预算与原正文不匹配。');
|| 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')));
@@ -519,7 +529,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
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
|| 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('项目记忆与实际发送内容不匹配。');
@@ -533,7 +543,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
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
|| 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('技能目录与实际发送内容不匹配。');