fix(runtime): preserve model capacity history and cache evidence with resumable file proposals

This commit is contained in:
Agent Workbench Dev
2026-11-06 01:18:37 +08:00
parent 2b17821138
commit 72115647d9
39 changed files with 699 additions and 75 deletions
+3 -2
View File
@@ -2,10 +2,11 @@ import { randomUUID,createHash } from 'node:crypto';
import { budgetFor } from './request-plan.mjs';
import { accountedTokens,emptyUsage } from '../../shared/contracts/execution.mjs';
import { capabilityRejections } from '../../shared/contracts/model-capabilities.mjs';
import { CAPACITY_RANGES } from '../../shared/contracts/model-capacity.mjs';
const fail=(message,status=409)=>Object.assign(new Error(message),{status});
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
const ranges={contextLimit:[1000,200000],maxOutputTokens:[256,16000],maxSteps:[1,30],maxRunTokens:[1000,2000000],maxTaskTokens:[1000,10000000],maxRunDurationMs:[1000,3600000]};
const ranges={...CAPACITY_RANGES,maxSteps:[1,30],maxRunTokens:[1000,2000000],maxTaskTokens:[1000,10000000],maxRunDurationMs:[1000,3600000]};
export class BudgetResume {
constructor(store,provider,runtime){this.store=store;this.provider=provider;this.runtime=runtime;}
@@ -18,7 +19,7 @@ export class BudgetResume {
prepare(session,input){
const {task,run}=this.current(session);
if(!input||Object.keys(input).some(key=>![...Object.keys(ranges),'selection'].includes(key)))throw fail('续接预览字段无效。',400);
const config={...this.store.config,maxTaskTokens:task.budget.maxTokens};
const config={...this.store.config,capacityMode:'manual',maxTaskTokens:task.budget.maxTokens};
for(const [key,[minimum,maximum]] of Object.entries(ranges))if(input[key]!==undefined){
if(!Number.isSafeInteger(input[key])||input[key]<minimum||input[key]>maximum)throw fail('续接预算 '+key+' 超出允许范围。',400);
config[key]=input[key];
+23
View File
@@ -0,0 +1,23 @@
import { createHash } from 'node:crypto';
const hash = value => createHash('sha256').update(value).digest('hex');
const variants = body => body.kind === 'model-route-plan' ? body.variants : [{ connectionId: null, protocol: body.input ? 'responses' : Array.isArray(body.system) ? 'anthropic-messages' : 'chat-completions', body }];
const prompt = body => Buffer.from(JSON.stringify({ model: body.model, tools: body.tools ?? [], system: body.system ?? null, messages: body.messages ?? body.input ?? [] }));
// This measures ordered prompt fields, not a supplier cache hit or saved
// tokens. Metadata stays outside the request and cannot invalidate its prefix.
export function prefixAudit(body, previous = null) {
const old = previous ? variants(previous) : [];
return { schemaVersion: 1, method: 'ordered-wire-prompt-fields-utf8', upstreamCache: 'unknown', variants: variants(body).map(current => {
const tools = JSON.stringify(current.body.tools ?? []), bytes = prompt(current.body);
const prior = old.find(value => value.connectionId === current.connectionId && value.protocol === current.protocol && value.body.model === current.body.model);
const previousBytes = prior ? prompt(prior.body) : null;
let common = 0;
if (previousBytes) while (common < Math.min(previousBytes.length, bytes.length) && previousBytes[common] === bytes[common]) common++;
const toolsChanged = !!prior && JSON.stringify(prior.body.tools ?? []) !== tools;
return { connectionId: current.connectionId, protocol: current.protocol, model: current.body.model,
toolsSha256: hash(tools), toolBytes: Buffer.byteLength(tools), toolNames: (current.body.tools ?? []).map(tool => tool.function?.name ?? tool.name),
promptBytes: bytes.length, previousPromptBytes: previousBytes?.length ?? null, commonPrefixBytes: common,
reason: !prior ? 'new_route_or_first_request' : toolsChanged ? 'tool_surface_changed' : bytes.equals(previousBytes) ? 'same_prompt' : 'prompt_append_or_change' };
}) };
}
+45 -16
View File
@@ -8,6 +8,7 @@ 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';
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,7 +62,7 @@ export function budgetFor(config, run, task, transportReservationTokens = 0) {
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),
return { contextLimit: config.contextLimit, outputReservation, safetyTokens, ...(transportReservationTokens?{transportReservationTokens}:{}), inputBudget, targetInputTokens: config.capacityMode === 'model' ? inputBudget : Math.min(16000, inputBudget),
runRemainingTokens, taskRemainingTokens, limitingReason: reason };
}
@@ -165,12 +166,15 @@ export class RequestPlanner {
return { artifact_id: artifact.id, sha256: artifact.sha256, group_sha256: group.sha256, bytes: Buffer.byteLength(text, 'utf8'), chunks: chunks.length };
}
prepare(session, run, config, { system, tools, stepId, projectMemory = null, skillCatalog = null, mcpCatalog = null, transportReservationTokens = 0,engineStepOnly=false }) {
prepare(session, run, config, { system, contextTail = null, tools, stepId, projectMemory = null, skillCatalog = null, mcpCatalog = null, transportReservationTokens = 0,engineStepOnly=false }) {
const task = this.store.owned('task', run.taskId, session.id);
this.store.owned('run', run.id, session.id);
const groups = historyGroups(session.providerMessages), budget = budgetFor(config, run, task, transportReservationTokens);
const lastUser = groups.findLast(group => group.messages[0].role === 'user');
const fixed = { role: 'system', content: system };
const preserve = 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;
@@ -182,7 +186,8 @@ export class RequestPlanner {
const ledger = new Map([...this.store.core.tool.values()].filter(tool => tool.sessionId === session.id && tool.taskId === task.id).map(tool => [tool.callId, tool]));
const descriptions = new Map(groups.map(group => [group.index, describe(group, ledger, this.store.core.artifact)]));
const evidence = workingEvidence(groups, descriptions, this.store.core.artifact);
const original = completionBody(config, [fixed, ...session.providerMessages], tools), before = requestMetrics(original);
const original = completionBody(config, [fixed, ...session.providerMessages, ...tail], tools), before = requestMetrics(original);
if (preserve && before.estimatedInputTokens > budget.inputBudget) throw pause(budget, before, breakdown);
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, 3);
@@ -203,10 +208,10 @@ export class RequestPlanner {
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, 3)] : []),
...(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)];
...groups.filter(group => indices.has(group.index)).flatMap(group => group.messages), ...tail];
return requestMetrics(completionBody(config, messages, tools));
};
if (before.estimatedInputTokens > budget.targetInputTokens) {
if (!preserve && 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);
@@ -288,19 +293,19 @@ export class RequestPlanner {
const messages = [fixed, ...(reference ? [notice(reference, omitted, descriptions, unsentEvidence(selected, entries, true))] : []),
...(latestReference ? [latestToolMessage(latestReference, latestDocument, 3)] : []),
...(workingReference ? [workingMessage(workingReference, workingDocument(session, run, entries, 3), 4)] : []),
...structuredClone(groups.filter(group => selected.has(group.index)).flatMap(group => group.messages))];
...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, MCP_LIMITS.allowedTools)) {
mcpDocument.entries.push(entry);
const candidate = [fixed, mcpCatalogMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, mcpDocument), ...messages.slice(1)];
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 (mcpDocument.entries.length) {
mcpReference = this.artifact(session, run, mcpDocument, 'context-mcp-catalog');
messages.splice(1, 0, mcpCatalogMessage(mcpReference, mcpDocument));
messages.splice(0, messages.length, ...addContext(messages, mcpCatalogMessage(mcpReference, mcpDocument)));
}
}
let skillReference = null, skillDocument = null;
@@ -308,13 +313,13 @@ export class RequestPlanner {
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)];
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 (skillDocument.entries.length) {
skillReference = this.artifact(session, run, skillDocument, 'context-skill-catalog');
messages.splice(1, 0, skillCatalogMessage(skillReference, skillDocument));
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.
@@ -325,13 +330,13 @@ export class RequestPlanner {
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)];
const candidate = addContext(messages, projectMemoryMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, memoryDocument));
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));
messages.splice(0, messages.length, ...addContext(messages, projectMemoryMessage(memoryReference, memoryDocument)));
}
}
const body = completionBody(config, messages, tools), metrics = requestMetrics(body);
@@ -341,11 +346,18 @@ export class RequestPlanner {
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 previousPlan = [...this.store.core.context_plan.values()].filter(plan => plan.sessionId === session.id && plan.taskId === task.id && plan.requestAttempts > 0)
.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.requestIndex - b.requestIndex).at(-1) ?? null;
const previousBody = previousPlan ? JSON.parse(this.store.artifactStore.read(this.store.owned('artifact', previousPlan.requestArtifactId, session.id))) : null;
const prefix = { ...prefixAudit(body, previousBody), previousPlanId: previousPlan?.id ?? null, previousRequestSha256: previousPlan?.requestSha256 ?? null };
const 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,
...(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,
@@ -358,7 +370,7 @@ export class RequestPlanner {
- metricsFor(new Set(lastUser ? [lastUser.index] : []), true, []).estimatedInputTokens),
workingRetentionPolicyVersion: 1,
readBudgetPolicyVersion: 3,
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),
originalMessages: session.providerMessages.length, retainedMessages: messages.length - 1 - tail.length - (reference ? 1 : 0) - (workingReference ? 1 : 0) - (latestReference ? 1 : 0) - (memoryReference ? 1 : 0) - (skillReference ? 1 : 0) - (mcpReference ? 1 : 0),
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,
@@ -404,6 +416,23 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
historyGroups(requestHistory(body));
for (const variant of requestVariants(body)) historyGroups(requestHistory(variant));
const frozen = JSON.parse(store.artifactStore.read(get(plan.artifactId, 'context-plan')));
for (const key of ['contextLayout', 'historyPolicy', 'contextTailArtifactId', 'contextTailSha256', 'prefixAudit']) {
if (JSON.stringify(frozen[key] ?? null) !== JSON.stringify(plan[key] ?? null)) throw new Error('前缀或历史策略与发送前封存不匹配。');
}
if (plan.prefixAudit) {
const previous = plan.prefixAudit.previousPlanId ? store.owned('context_plan', plan.prefixAudit.previousPlanId, session.id) : null;
if (previous && (previous.taskId !== plan.taskId || previous.id === plan.id || previous.createdAt > plan.createdAt || previous.requestSha256 !== plan.prefixAudit.previousRequestSha256)) throw new Error('前缀对照来源不匹配。');
const previousBody = previous ? JSON.parse(store.artifactStore.read(get(previous.requestArtifactId, 'model-request', previous.requestSha256))) : null;
const expected = { ...prefixAudit(body, previousBody), previousPlanId: previous?.id ?? null, previousRequestSha256: previous?.requestSha256 ?? null };
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('图片身份或预算与发送前封存不匹配。');
@@ -451,7 +480,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|| 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 (!carriesContext(message.content)) throw new Error('项目记忆与实际发送内容不匹配。');
}
if ((frozen.skillCatalogArtifactId ?? null) !== (plan.skillCatalogArtifactId ?? null)
|| (frozen.skillCatalogSha256 ?? null) !== (plan.skillCatalogSha256 ?? null)
@@ -465,7 +494,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|| 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 (!carriesContext(message.content)) throw new Error('技能目录与实际发送内容不匹配。');
}
if ((frozen.mcpCatalogArtifactId ?? null) !== (plan.mcpCatalogArtifactId ?? null)
|| (frozen.mcpCatalogSha256 ?? null) !== (plan.mcpCatalogSha256 ?? null)
@@ -478,7 +507,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|| 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 (!carriesContext(message.content)) throw new Error('MCP目录与实际发送内容不匹配。');
}
if (plan.latestToolsArtifactId) {
const artifact = get(plan.latestToolsArtifactId, 'context-latest-tools', plan.latestToolsSha256);
+1
View File
@@ -204,6 +204,7 @@ export class GitDelivery {
}
async plan(session, options = {}, { source = 'user' } = {}) {
if (session.fileDrafts?.some(row => row.taskId === session.taskId && row.status === 'staging')) throw conflict('分段文件草稿尚未完成,请完成提案或显式放弃后再交付。');
assertWorkersResolved(this.store, session.projectId);
if (workerForProject(this.store, session.projectId)) throw conflict('受限子任务不能独立Git提交;请在父任务审查合并后交付。');
const idleOptions = { exceptSessionId: source === 'agent' ? session.id : null };
+2
View File
@@ -35,6 +35,8 @@ export class ConfigImporter {
...(item.outputTokenField !== undefined ? { outputTokenField: item.outputTokenField } : {}),
...(item.parameterProfile !== undefined ? { parameterProfile: item.parameterProfile } : {}),
...(item.protocol === 'anthropic-messages' ? { messagesAuth: item.messagesAuth ?? 'api-key' } : {}),
...(item.contextLimit !== undefined ? { contextLimit: item.contextLimit } : {}),
...(item.maxOutputTokens !== undefined ? { maxOutputTokens: item.maxOutputTokens } : {}),
baseUrl: item.baseUrl, apiKey: item.apiKey, requiresKey: item.requiresKey !== false, brand: item.brand });
}
} else if (source === 'ccswitch') {
+3 -2
View File
@@ -2,6 +2,7 @@ import { randomUUID, createHash } from 'node:crypto';
import { catalogPage, catalogRoute } from '../../shared/contracts/model-catalog.mjs';
import { messagesAuthSettings, validateProtocolEndpoint } from '../../shared/contracts/model-endpoint.mjs';
import { modelProtocol, capabilityDeclarations } from '../../shared/contracts/model-capabilities.mjs';
import { DEFAULT_MODEL_CAPACITY } from '../../shared/contracts/model-capacity.mjs';
const fail = (message, status = 400) => Object.assign(new Error(message), { status });
const stamp = () => new Date().toISOString();
@@ -128,8 +129,8 @@ export class ModelCatalog {
protocol: value.connection.protocol, baseUrl: value.connection.baseUrl, brand: value.connection.brand, messagesAuth: value.connection.messagesAuth,
requiresKey: value.connection.requiresKey, concurrency: value.connection.concurrency, parameterProfile: value.connection.parameterProfile ?? 'auto',
capabilityDeclarations: Object.fromEntries(Object.entries(model.capabilityDeclarations).map(([key, state]) => [key, state === 'unknown' ? declarations[key] : state])), streaming: false,
contextLimit: Math.min(value.connection.contextLimit ?? 16000, model.contextLimit ?? 200000),
maxOutputTokens: Math.min(value.connection.maxOutputTokens ?? 2048, model.maxOutputTokens ?? 16000),
contextLimit: model.contextLimit ?? value.connection.contextLimit ?? DEFAULT_MODEL_CAPACITY.contextLimit,
maxOutputTokens: model.maxOutputTokens ?? value.connection.maxOutputTokens ?? DEFAULT_MODEL_CAPACITY.maxOutputTokens,
...(!owner && value.explicitKey ? { apiKey: value.explicitKey, persistKey: input.persistKey === true } : {}) });
const connection = hub.connection(profile.id); connection.upstreamModel = upstreamModel; connection.source = 'upstream-catalog';
if (!owner) owner = connection;
+3 -2
View File
@@ -13,6 +13,7 @@ import { assertModelParameterSupport } from '../../shared/contracts/model-parame
import { modelIdentitySettings } from '../../shared/contracts/model-identity.mjs';
import { NetworkDiagnostics } from './network-diagnostics.mjs';
import { ModelCatalog, credentialScope } from './model-catalog.mjs';
import { capacitySettings, routedCapacity } from '../../shared/contracts/model-capacity.mjs';
const legacyId = 'legacy-default';
const stamp = () => new Date().toISOString();
@@ -217,7 +218,7 @@ export class ModelHub {
capabilitySchema: 1, capabilityDeclarations: declarations, streaming, ...(native ?? {}), ...modelIdentitySettings(input, previous ?? {}),
...messagesAuthSettings(protocol, input.messagesAuth ?? previous?.messagesAuth),
baseUrl: validateProtocolEndpoint(protocol, modelEndpoint(input.baseUrl)), enabled: input.enabled !== false, requiresKey: input.requiresKey !== false,
contextLimit: bounded(input.contextLimit, 16000, 1000, 200000), maxOutputTokens: bounded(input.maxOutputTokens, 2048, 256, 16000),
...capacitySettings(input, previous ?? undefined),
concurrency: bounded(input.concurrency, 1, 1, 8), revision: (previous?.revision ?? 0) + 1,
source: previous?.source ?? 'manual', ...(previous?.importOrigin ? { importOrigin: previous.importOrigin, importRevision: previous.importRevision } : {}),
createdAt: previous?.createdAt ?? stamp(), updatedAt: stamp() };
@@ -291,7 +292,7 @@ export class ModelHub {
return { ...config, ...messagesAuthSettings(members[0].protocol, members[0].messagesAuth), baseUrl: members[0].baseUrl, model: members[0].model, protocol: modelProtocol(members[0].protocol), streaming: members[0].streaming === true,
nativeParameters: members[0].nativeParameters ?? {}, outputTokenField: members[0].outputTokenField, parameterProfile: members[0].parameterProfile,
modelConnectionId: members[0].id, modelCredentialRevision: members[0].credentialRevision,
contextLimit: Math.min(config.contextLimit, ...members.map(value => value.contextLimit)), maxOutputTokens: Math.min(config.maxOutputTokens, ...members.map(value => value.maxOutputTokens)),
...routedCapacity(config, members),
modelRouting: { type: selection.type, id: selection.id, revision: pool?.revision ?? members[0].revision,
strategy: pool?.strategy ?? 'round-robin', sticky: pool?.sticky ?? true, maxAttempts: pool?.maxAttempts ?? 1, queueTimeoutMs: pool?.queueTimeoutMs ?? 15000, members } };
}
+14 -6
View File
@@ -6,7 +6,7 @@ export const protocolFailure = (message, kind = 'protocol', extra = null) => new
// even a syntactically complete leading tool call is dropped, because any later call in
// the same turn may be cut mid-argument. The diagnostic must tell the model what happened
// and how to proceed, instead of a generic incompleteness message it cannot act on.
export const OUTPUT_TRUNCATED_HINT = '模型输出达到单次 output token 上限(finish_reason=length),本次响应整体未执行任何工具(即使其中一个工具参数已完整也不执行,避免应用被截断的半成品)。请减少单次响应的工具数量:把多文件提案拆成每次一个文件的 propose_file/propose_patch,或分多轮 prepare_change_set,不要在一个响应里堆叠多个大参数工具。';
export const OUTPUT_TRUNCATED_HINT = '上游模型在本次配置的输出额度处停止(finish_reason=length),本次响应整体未执行工具,原响应和用量已保留。请拆分输出:已有文件使用propose_patch;单个长文件用propose_file_chunk分多轮追加较短的完整片段,最后complete=true生成完整提案。已有成功片段使用原draft_id/next_offset/draft_sha256继续,不从头重复。不要在一个响应中堆叠多个大工具参数。原目标和已读依据保留。';
export const outputTruncatedFailure = (kind = 'protocol') => protocolFailure(OUTPUT_TRUNCATED_HINT, kind, { reason: 'output_truncated' });
export { protocolRoute } from '../../shared/contracts/model-endpoint.mjs';
@@ -20,14 +20,22 @@ export function reportedUsage(config, value) {
const input = raw.input_tokens + cached + created, total = input + raw.output_tokens;
if (!Number.isSafeInteger(total)) return null;
return { prompt_tokens: input, completion_tokens: raw.output_tokens, total_tokens: total,
prompt_tokens_details: { cached_tokens: cached, cache_creation_tokens: created }, raw: structuredClone(raw), protocol: 'anthropic-messages' };
...(raw.cache_read_input_tokens !== undefined || raw.cache_creation_input_tokens !== undefined ? { prompt_tokens_details: {
...(raw.cache_read_input_tokens !== undefined ? { cached_tokens: cached } : {}),
...(raw.cache_creation_input_tokens !== undefined ? { cache_creation_tokens: created } : {}) } } : {}),
raw: structuredClone(raw), protocol: 'anthropic-messages' };
}
const input = config.protocol === 'responses' ? raw.input_tokens : raw.prompt_tokens;
const output = config.protocol === 'responses' ? raw.output_tokens : raw.completion_tokens;
const valid = number => Number.isSafeInteger(number) && number >= 0;
if (!valid(raw.total_tokens) && !(valid(input) && valid(output))) return null;
const cached = config.protocol === 'responses' ? raw.input_tokens_details?.cached_tokens : raw.prompt_tokens_details?.cached_tokens ?? raw.prompt_cache_hit_tokens;
const cacheDetails = valid(cached) && valid(input) && cached <= input ? { cached_tokens: cached } : null;
const reasoning = config.protocol === 'responses' ? raw.output_tokens_details?.reasoning_tokens : raw.completion_tokens_details?.reasoning_tokens;
return { ...(valid(input) ? { prompt_tokens: input } : {}), ...(valid(output) ? { completion_tokens: output } : {}),
total_tokens: valid(raw.total_tokens) ? raw.total_tokens : input + output };
total_tokens: valid(raw.total_tokens) ? raw.total_tokens : input + output,
...(cacheDetails ? { prompt_tokens_details: cacheDetails } : {}), ...(valid(reasoning) && valid(output) && reasoning <= output ? { completion_tokens_details: { reasoning_tokens: reasoning } } : {}),
raw: structuredClone(raw), protocol: config.protocol ?? 'chat-completions' };
}
function acceptsEmptyObject(tools, name) {
@@ -84,9 +92,10 @@ export function normalizeProtocolResponse(config, value) {
}
if (config.protocol !== 'responses') {
const received = value?.choices?.[0]?.message;
if (received?.reasoning_content === undefined || received.reasoning_content === null) return value;
if (received?.reasoning_content === undefined || received.reasoning_content === null) return { ...value, usage: reportedUsage(config, value) };
if (typeof received.reasoning_content !== 'string') throw protocolFailure('Chat reasoning_content必须为字符串,原响应未用于执行工具。');
const normalized = structuredClone(value), target = normalized.choices[0].message;
normalized.usage = reportedUsage(config, value);
delete target.reasoning_content;
target.providerState = { protocol: 'chat-completions', endpoint: config.baseUrl, model: config.model,
connectionId: config.modelConnectionId ?? null, credentialRevision: config.modelCredentialRevision ?? null, reasoningContent: received.reasoning_content };
@@ -109,8 +118,7 @@ export function normalizeProtocolResponse(config, value) {
}
} else if (item.type !== 'reasoning') throw protocolFailure('Responses包含当前尚未接入的服务端工具或输出类型:' + String(item.type ?? '未标注').slice(0, 100) + '。');
}
const raw = value.usage, usage = raw ? { prompt_tokens: raw.input_tokens, completion_tokens: raw.output_tokens,
...(raw.total_tokens !== undefined ? { total_tokens: raw.total_tokens } : {}), raw, protocol: 'responses' } : null;
const usage = reportedUsage(config, value);
return { choices: [{ message: { role: 'assistant', content: texts.join(''), ...(calls.length ? { tool_calls: calls } : {}),
providerState: { protocol: 'responses', endpoint: config.baseUrl, model: config.model, responseId: value.id ?? null, items: value.output } }, finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage };
}
+7 -3
View File
@@ -1,15 +1,19 @@
import { CAPACITY_RANGES, capacityMode } from '../../shared/contracts/model-capacity.mjs';
const ranges = {
contextLimit: [1000, 200000], maxOutputTokens: [256, 16000], maxSteps: [1, 30],
...CAPACITY_RANGES, maxSteps: [1, 30],
maxRunDurationMs: [1000, 3600000], maxRunTokens: [1000, 2000000], maxTaskTokens: [1000, 10000000],
};
// Budget-only edits cannot change the selected route, endpoint or credential.
export function validateRuntimeBudgets(input) {
if (!input || typeof input !== 'object' || Array.isArray(input) || !Object.keys(input).length
|| Object.keys(input).some(key => !Object.hasOwn(ranges, key))) throw new Error('只接受运行预算字段;模型连接请在模型选择中切换。');
|| Object.keys(input).some(key => !['capacityMode', 'historyPolicy'].includes(key) && !Object.hasOwn(ranges, key))) throw new Error('只接受运行预算字段;模型连接请在模型选择中切换。');
for (const [key, value] of Object.entries(input)) {
if (key === 'capacityMode') { capacityMode(value); continue; }
if (key === 'historyPolicy') { if (!['preserve', 'compact'].includes(value)) throw new Error('请选择完整传递或允许整理历史。'); continue; }
const [min, max] = ranges[key];
if (!Number.isSafeInteger(value) || value < min || value > max) throw new Error(key + ' 需填写范围内的整数。');
}
return { ...input };
return { ...input, ...(!Object.hasOwn(input, 'capacityMode') && ['contextLimit', 'maxOutputTokens'].some(key => Object.hasOwn(input, key)) ? { capacityMode: 'manual' } : {}) };
}
+5 -1
View File
@@ -2,9 +2,10 @@ import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { isId } from '../../shared/contracts/execution.mjs';
import { DEFAULT_MODEL_CAPACITY } from '../../shared/contracts/model-capacity.mjs';
export const DEFAULT_CONFIG = {
mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 16000, maxSteps: 12, maxOutputTokens: 2048,
mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', ...DEFAULT_MODEL_CAPACITY, capacityMode: 'model', historyPolicy: 'preserve', maxSteps: 12,
maxRunDurationMs: 600000, maxRunTokens: 200000, maxTaskTokens: 1000000, configRevision: 1,
modelResponseTimeoutMs: 300000, modelStreamIdleTimeoutMs: 120000,
};
@@ -12,6 +13,9 @@ export const DEFAULT_CONFIG = {
export function cleanConfig(value = {}) {
const result = { ...DEFAULT_CONFIG };
for (const key of Object.keys(result)) if (Object.hasOwn(value, key)) result[key] = value[key];
// Old settings stay manual. Every saved Run keeps its original snapshot.
if (!Object.hasOwn(value, 'capacityMode') && (Object.hasOwn(value, 'contextLimit') || Object.hasOwn(value, 'maxOutputTokens'))) result.capacityMode = 'manual';
if (!Object.hasOwn(value, 'historyPolicy') && (Object.hasOwn(value, 'contextLimit') || Object.hasOwn(value, 'maxOutputTokens'))) result.historyPolicy = 'compact';
for (const key of ['nativeParameters', 'outputTokenField', 'parameterProfile']) if (Object.hasOwn(value, key)) result[key] = structuredClone(value[key]);
return result;
}
@@ -0,0 +1,70 @@
import fs from 'node:fs';
import { randomUUID } from 'node:crypto';
import { safePath, readText, hash, proposeFile } from '../../server/files.mjs';
import { assertWorkersResolved, assertWorkerWriteScope } from '../../shared/contracts/workers.mjs';
import { assertMcpResolved } from '../tools/mcp-contract.mjs';
import { assertChangeSetsResolved } from '../../shared/contracts/change-sets.mjs';
import { assertWorkspacesResolved } from '../../shared/contracts/workspaces.mjs';
const fail = message => { throw Object.assign(new Error(message), { status: 409 }); };
const emptySha = hash(Buffer.alloc(0));
export const pendingFileDrafts = session => (session.fileDrafts ?? []).filter(row => row.taskId === session.taskId && row.status === 'staging');
// Fragments are immutable artifacts. A partial draft is never a file proposal,
// never a change-set member, and never written into the user's project.
export function proposeFileChunk(store, session, args) {
if (Object.keys(args).some(key => !['path', 'content', 'reason', 'offset', 'complete', 'draft_id', 'expected_sha256', 'base_sha256'].includes(key))
|| typeof args.path !== 'string' || typeof args.content !== 'string' || typeof args.reason !== 'string' || !args.reason.trim()
|| !Number.isSafeInteger(args.offset) || args.offset < 0 || typeof args.complete !== 'boolean'
|| args.content.includes('\0') || !args.content.isWellFormed() || !args.complete && !args.content.length) fail('分段提案需要有效路径、文本、说明、offset和complete;未完成片段不能为空。');
const run = store.owned('run', session.runId, session.id);
if (run.taskId !== session.taskId) fail('分段提案缺少当前Task/Run归属。');
assertWorkersResolved(store, session.projectId); assertWorkerWriteScope(store, session, args.path);
assertMcpResolved(store, session.projectId); assertChangeSetsResolved(store, session.projectId);
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
const project = store.project(session.projectId), target = safePath(project, args.path, true);
const base = fs.existsSync(target) ? readText(project, args.path).sha256 : null;
let draft = args.draft_id ? (session.fileDrafts ?? []).find(row => row.id === args.draft_id) : null;
if (args.draft_id && (!draft || draft.status !== 'staging' || draft.taskId !== session.taskId || draft.projectId !== session.projectId || draft.path !== args.path)) fail('草稿不属于当前Task/路径或已结束,请核对原回执。');
if (!draft) {
if (args.offset !== 0 || args.expected_sha256 !== undefined && args.expected_sha256 !== emptySha) fail('新草稿必须从offset 0开始。');
if (pendingFileDrafts(session).some(row => row.path === args.path) || pendingFileDrafts(session).length >= 16) fail('该路径已有未完成草稿或当前Task已达16份草稿,请继续原草稿或显式放弃。');
if (Object.hasOwn(args, 'base_sha256') && args.base_sha256 !== base) fail('原文件SHA已变化,请重新核对。');
draft = { id: randomUUID(), projectId: session.projectId, taskId: session.taskId, path: args.path, status: 'staging', baseSha256: base,
sha256: emptySha, characters: 0, bytes: 0, chunks: [], createdAt: new Date().toISOString() };
} else if (args.offset !== draft.characters || args.expected_sha256 !== draft.sha256) fail('片段offset或SHA与原草稿不一致,未追加;请使用上一次成功回执,不能从头重复。');
if (draft.baseSha256 !== base || Object.hasOwn(args, 'base_sha256') && args.base_sha256 !== draft.baseSha256) fail('分段期间原文件已变化,草稿不能覆盖新内容;请放弃后按新SHA准备。');
const previous = draft.chunks.map(part => {
const artifact = store.owned('artifact', part.id, session.id);
if (artifact.kind !== 'file-proposal-fragment' || artifact.taskId !== session.taskId || artifact.projectId !== session.projectId || artifact.sha256 !== part.sha256) fail('原片段身份不匹配。');
return store.artifactStore.read(artifact);
}).join('');
if (hash(Buffer.from(previous)) !== draft.sha256 || previous.length !== draft.characters || Buffer.byteLength(previous) !== draft.bytes) fail('原草稿校验失败,未采用任何片段。');
const content = previous + args.content, bytes = Buffer.byteLength(content);
if (bytes > 512000 || draft.chunks.length >= 256) fail('完整文本超过512KB或256段;请按工程模块拆分文件。');
const artifact = store.artifactStore.write(session, run, args.content, { kind: 'file-proposal-fragment', mediaType: 'text/plain' });
store.core.artifact.set(artifact.id, artifact);
const next = { ...draft, sha256: hash(Buffer.from(content)), characters: content.length, bytes, chunks: [...draft.chunks, { id: artifact.id, sha256: artifact.sha256 }] };
const original = session.fileDrafts ?? [];
const originalChanges = [...session.changes], originalStatus = session.status;
session.fileDrafts = [...original.filter(row => row.id !== draft.id), next];
let result;
try {
if (args.complete) {
next.status = 'finalized';
result = proposeFile(store, session, { path: args.path, reason: args.reason, content, base_sha256: next.baseSha256 }, { persist: false });
next.changeId = result.change_id ?? null;
}
store.save(session);
} catch (cause) { session.fileDrafts = original; session.changes = originalChanges; session.status = originalStatus; throw cause; }
return { ...(result ?? { status: 'staged', message: '片段已保存,尚无可应用提案。继续使用draft_id、next_offset和draft_sha256;最后一段complete=true才创建完整审查提案。' }),
draft_id: next.id, path: next.path, next_offset: next.characters, draft_sha256: next.sha256, bytes: next.bytes, complete: args.complete };
}
export function discardFileDraft(store, session, args) {
if (Object.keys(args).some(key => !['draft_id', 'expected_sha256', 'reason'].includes(key)) || typeof args.reason !== 'string' || !args.reason.trim()) fail('放弃草稿需要原身份、SHA与说明。');
const draft = pendingFileDrafts(session).find(row => row.id === args.draft_id);
if (!draft || draft.sha256 !== args.expected_sha256) fail('草稿归属、状态或SHA不匹配。');
draft.status = 'discarded'; draft.discardReason = args.reason.slice(0, 600); store.save(session);
return { status: 'discarded', draft_id: draft.id, path: draft.path, message: '草稿已放弃,原片段保留,项目文件没有改变。' };
}