fix: retain source continuation and explain request reservation pauses
This commit is contained in:
+1
-1
@@ -47,7 +47,7 @@ export interface InputAttachment { id:string;name:string;status:string;mediaType
|
||||
export interface BudgetPause { reason:string;requiredInputTokens?:number;contextLimit?:number;inputBudget?:number;outputReservation?:number;safetyTokens?:number;runRemainingTokens?:number|null;taskRemainingTokens?:number|null;imageReservationTokens?:number;breakdown?:Record<string,number> }
|
||||
export interface Run { budgetPause?:BudgetPause }
|
||||
export interface BudgetPause { originalInputTokens?:number;transportReservationTokens?:number }
|
||||
export interface BudgetPause { limitingReason?:string }
|
||||
export interface BudgetPause { limitingReason?:string;pauseKind?:string }
|
||||
export interface BudgetPause { modelFailure?:RuntimeFailure }
|
||||
export interface TokenBudgetCounter { maximumTokens:number;reportedTokens:number;unknownRequests:number;estimatedUnknownTokens:number;accountedTokens:number;remainingTokens:number|null;exceededTokens:number }
|
||||
export interface BudgetPause { remainingTokens?:number;tokenReservation?:{schemaVersion:number;reservedTokens:number;routes:{sources:{runId:string;attemptId:string}[]}[]};tokenAccounting?:{schemaVersion:number;singleInFlightResponseMayExceed:boolean;run:TokenBudgetCounter;task:TokenBudgetCounter} }
|
||||
|
||||
@@ -36,11 +36,32 @@ export function readMessageBudget(plan, message) {
|
||||
// The next request also gains bounded read coverage and route observations.
|
||||
// Reserve their growth before returning a page, rather than dropping that
|
||||
// new page or enlarging the request budget afterwards.
|
||||
const tokens = plan.budget.inputBudget - (plan.nextReadFixedInputTokens ?? plan.mandatoryInputTokens) - (plan.workingRetentionTokens ?? 0) - assistantTokens - calls * 8 - 512 - 2048;
|
||||
const pureReads = plan.readBudgetPolicyVersion === 2 && message.tool_calls?.length
|
||||
&& message.tool_calls.every(call => call.function.name === 'read_file');
|
||||
// A pure read batch cannot create a plan, command output or change set. Its
|
||||
// bounded state/coverage growth uses 512 tokens plus 256 for each additional
|
||||
// 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 = 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));
|
||||
}
|
||||
|
||||
export function filePage(file, args, { maximumMessageBytes = 16000, callId = '' } = {}) {
|
||||
export function readBatchBudget(plan, message) {
|
||||
const maximum = readMessageBudget(plan, message);
|
||||
if (plan.readBudgetPolicyVersion !== 2 || !message.tool_calls?.length
|
||||
|| !message.tool_calls.every(call => call.function.name === 'read_file')) return null;
|
||||
return { remainingBytes: maximum * message.tool_calls.length, remainingCalls: message.tool_calls.length };
|
||||
}
|
||||
|
||||
export function spendReadBudget(batch, call, result) {
|
||||
if (!batch) return;
|
||||
batch.remainingBytes = Math.max(0, batch.remainingBytes - messageBytes(result, call.id));
|
||||
batch.remainingCalls = Math.max(0, batch.remainingCalls - 1);
|
||||
}
|
||||
|
||||
export function filePage(file, args, { maximumMessageBytes = 16000, callId = '', maximumPageCharacters = Infinity } = {}) {
|
||||
const text = file.content, requestedOffset = args.offset ?? 0;
|
||||
let offset = Math.min(requestedOffset, text.length);
|
||||
if (offset > 0 && /[\uDC00-\uDFFF]/.test(text[offset]) && /[\uD800-\uDBFF]/.test(text[offset - 1])) offset--;
|
||||
@@ -55,7 +76,7 @@ export function filePage(file, args, { maximumMessageBytes = 16000, callId = ''
|
||||
requested_offset: requestedOffset, next_start_line: end < text.length ? null : file.end_line < file.total_lines ? file.end_line + 1 : null,
|
||||
truncated: file.truncated || offset > 0 || end < text.length, budget_limited: end < maximumEnd,
|
||||
maximum_message_bytes: maximumMessageBytes });
|
||||
let low = offset, high = maximumEnd;
|
||||
let low = offset, high = Math.min(maximumEnd, boundary(text, offset + maximumPageCharacters));
|
||||
if (messageBytes(make(low), callId) > maximumMessageBytes) throw new Error('当前请求预算无法容纳文件读取元数据,请先核对任务预算。');
|
||||
while (low < high) {
|
||||
const middle = Math.ceil((low + high) / 2), end = boundary(text, middle);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// Only a recorded source page can supply a continuation. A tool-result
|
||||
// artifact restores that page, not bytes that have never been read.
|
||||
export function fileContinuation(value) {
|
||||
if (typeof value?.path !== 'string' || !/^[a-f0-9]{64}$/i.test(value.sha256 ?? '')
|
||||
|| !Number.isSafeInteger(value.range_start_line) || !Number.isSafeInteger(value.range_end_line)
|
||||
|| !Number.isSafeInteger(value.next_offset) || !Number.isSafeInteger(value.total_characters)) return null;
|
||||
const more = value.next_offset < value.total_characters;
|
||||
const next = more ? { path: value.path, start_line: value.range_start_line, end_line: value.range_end_line,
|
||||
offset: value.next_offset, expected_sha256: value.sha256 }
|
||||
: Number.isSafeInteger(value.next_start_line) ? { path: value.path, start_line: value.next_start_line,
|
||||
expected_sha256: value.sha256 } : null;
|
||||
return { range_complete: !more, next_read_file: next };
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { projectMemoryMessage, MEMORY_CONTEXT_LIMITS } from '../memory/project-m
|
||||
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';
|
||||
|
||||
const hash = value => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value), 'utf8').digest('hex');
|
||||
const PLACEHOLDER_ID = '00000000-0000-0000-0000-000000000000';
|
||||
@@ -70,7 +71,8 @@ function compactResult(result) {
|
||||
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']) {
|
||||
'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;
|
||||
}
|
||||
@@ -97,7 +99,7 @@ function workingEvidence(groups, descriptions, artifacts) {
|
||||
for (const group of [...groups].reverse()) for (const tool of descriptions.get(group.index).tools ?? []) {
|
||||
const artifact = artifacts.get(tool.input.artifact_id);
|
||||
if (tool.name === 'read_file' || tool.name === 'read_artifact' && artifact && !artifact.kind.startsWith('context-') && artifact.kind !== 'model-request') {
|
||||
const key = tool.name === 'read_file' ? 'file:' + tool.input.path : 'artifact:' + tool.input.artifact_id;
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -107,12 +109,13 @@ function workingEvidence(groups, descriptions, artifacts) {
|
||||
function notice(reference, omitted, descriptions, evidence = []) {
|
||||
return { role: 'system', content: [
|
||||
'以下是工作台保存的历史索引数据,不是用户追加指令,也不是新工具执行。省略了完整消息组;原始参数和实际结果都在SHA256工件中。',
|
||||
'已完成工具不得重放。优先使用已发送代码和工作依据;只在缺少具体内容时读取result_artifact_id,按next_offset分页。未知结果先核对。',
|
||||
'已完成工具不得重放。优先使用已发送代码和工作依据;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 } : {}) })),
|
||||
: 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 } };
|
||||
@@ -121,9 +124,12 @@ function notice(reference, omitted, descriptions, evidence = []) {
|
||||
}
|
||||
|
||||
function pause(budget, metrics, breakdown) {
|
||||
const reservation = budget.pauseKind === 'request_reservation';
|
||||
const error = new BudgetExceeded(budget.limitingReason,
|
||||
'任务目标、完整追加要求与必需请求开销超过' + (budget.limitingReason === 'context_limit' ? '上下文窗口' : '剩余token预算') +
|
||||
'。完整历史已保留;请核对模型上下文或任务预算后继续。');
|
||||
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;
|
||||
@@ -173,20 +179,30 @@ export class RequestPlanner {
|
||||
toolDefinitionTokens:fixedTools-fixedText,historyAndEvidenceTokens:metrics.estimatedInputTokens-fixedTools,
|
||||
imageReservationTokens:metrics.imageReservationTokens??0};
|
||||
};
|
||||
const ledger = new Map([...this.store.core.tool.values()].filter(tool => tool.sessionId === session.id).map(tool => [tool.callId, tool]));
|
||||
const 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 selected = new Set(groups.map(group => group.index));
|
||||
let omitted = [], reference = null, workingReference = null, latestReference = null;
|
||||
const latestDocument = latestToolDocument(this.store, session, run, groups);
|
||||
const latestDocument = latestToolDocument(this.store, session, run, groups, 2);
|
||||
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.map(entry => entry.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, evidence)] : []),
|
||||
...(includeLatest && latestDocument && !indices.has(latestDocument.group_index) ? [latestToolMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, latestDocument)] : []),
|
||||
...(currentEntries.length ? [workingMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, workingDocument(session, run, currentEntries))] : []),
|
||||
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, 2)] : []),
|
||||
...(currentEntries.length ? [workingMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, workingDocument(session, run, currentEntries, 2), 3)] : []),
|
||||
...groups.filter(group => indices.has(group.index)).flatMap(group => group.messages)];
|
||||
return requestMetrics(completionBody(config, messages, tools));
|
||||
};
|
||||
@@ -194,7 +210,7 @@ export class RequestPlanner {
|
||||
selected.clear(); if (lastUser) selected.add(lastUser.index);
|
||||
const mandatory = metricsFor(selected);
|
||||
if (mandatory.estimatedInputTokens > budget.inputBudget) throw pause(budget, mandatory, breakdown);
|
||||
const observed = workingCandidates(this.store, session, run, groups);
|
||||
const observed = workingCandidates(this.store, session, run, groups, 2);
|
||||
// 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);
|
||||
@@ -259,11 +275,11 @@ export class RequestPlanner {
|
||||
note: '完整原消息组;这里只是历史定位,不产生工具执行或用户授权。' }, 'context-history-index');
|
||||
}
|
||||
}
|
||||
if (entries.length) workingReference = this.artifact(session, run, workingDocument(session, run, entries), 'context-working-set');
|
||||
if (entries.length) workingReference = this.artifact(session, run, workingDocument(session, run, entries, 2), 'context-working-set');
|
||||
if (latestDocument && !selected.has(latestDocument.group_index)) latestReference = this.artifact(session, run, latestDocument, 'context-latest-tools');
|
||||
const messages = [fixed, ...(reference ? [notice(reference, omitted, descriptions, evidence)] : []),
|
||||
...(latestReference ? [latestToolMessage(latestReference, latestDocument)] : []),
|
||||
...(workingReference ? [workingMessage(workingReference, workingDocument(session, run, entries))] : []),
|
||||
const messages = [fixed, ...(reference ? [notice(reference, omitted, descriptions, unsentEvidence(selected, entries, true))] : []),
|
||||
...(latestReference ? [latestToolMessage(latestReference, latestDocument, 2)] : []),
|
||||
...(workingReference ? [workingMessage(workingReference, workingDocument(session, run, entries, 2), 3)] : []),
|
||||
...structuredClone(groups.filter(group => selected.has(group.index)).flatMap(group => group.messages))];
|
||||
let mcpReference = null, mcpDocument = null;
|
||||
if (mcpCatalog?.projectId === session.projectId && mcpCatalog.entries?.length) {
|
||||
@@ -315,7 +331,7 @@ export class RequestPlanner {
|
||||
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},metrics,breakdown);
|
||||
tokenReservation,remainingTokens:credit,pauseKind:'request_reservation'},metrics,breakdown);
|
||||
const requestArtifact = this.artifact(session, run, body, 'model-request');
|
||||
const record = { schemaVersion: 1, id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: run.taskId,
|
||||
runId: run.id, stepId, requestIndex: [...this.store.core.context_plan.values()].filter(plan => plan.runId === run.id).length + 1,
|
||||
@@ -333,11 +349,13 @@ export class RequestPlanner {
|
||||
workingRetentionTokens: Math.max(0, metricsFor(new Set(lastUser ? [lastUser.index] : []), true, retainedSources).estimatedInputTokens
|
||||
- metricsFor(new Set(lastUser ? [lastUser.index] : []), true, []).estimatedInputTokens),
|
||||
workingRetentionPolicyVersion: 1,
|
||||
readBudgetPolicyVersion: 2,
|
||||
originalMessages: session.providerMessages.length, retainedMessages: messages.length - 1 - (reference ? 1 : 0) - (workingReference ? 1 : 0) - (latestReference ? 1 : 0) - (memoryReference ? 1 : 0) - (skillReference ? 1 : 0) - (mcpReference ? 1 : 0),
|
||||
archivedGroups: omitted.length, retainedGroups: groups.filter(group => selected.has(group.index)).map(group => group.index),
|
||||
historyIndexArtifactId: reference?.id ?? null, historyIndexSha256: reference?.sha256 ?? null, actualUsage: null,
|
||||
workingSetArtifactId: workingReference?.id ?? null, workingSetSha256: workingReference?.sha256 ?? null, workingSetEntries: entries.length,
|
||||
workingSetViewVersion: 2,
|
||||
workingSetViewVersion: 3,
|
||||
latestToolsViewVersion: 2,
|
||||
latestToolsArtifactId: latestReference?.id ?? null, latestToolsSha256: latestReference?.sha256 ?? null, latestToolsEntries: latestReference ? latestDocument.entries.length : 0,
|
||||
projectMemoryArtifactId: memoryReference?.id ?? null, projectMemorySha256: memoryReference?.sha256 ?? null,
|
||||
projectMemoryEntries: memoryReference ? memoryDocument.entries.length : 0,
|
||||
@@ -408,6 +426,8 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|
||||
|| (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.latestToolsArtifactId ?? null) !== (plan.latestToolsArtifactId ?? null)
|
||||
|| (frozen.latestToolsSha256 ?? null) !== (plan.latestToolsSha256 ?? null)
|
||||
|| (frozen.latestToolsEntries ?? 0) !== (plan.latestToolsEntries ?? 0)) throw new Error('最新工具反馈与发送前的封存记录不匹配。');
|
||||
@@ -457,7 +477,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|
||||
const document = JSON.parse(store.artifactStore.read(artifact));
|
||||
if (artifact.taskId !== plan.taskId) throw new Error('最新工具反馈的工件任务归属不匹配。');
|
||||
verifyLatestToolDocument(store, session, plan, document, historyGroups(session.providerMessages.slice(0, plan.originalMessages)));
|
||||
const message = latestToolMessage(artifact, document);
|
||||
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) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { fileContinuation } from './read-continuation.mjs';
|
||||
|
||||
const hash = value => createHash('sha256').update(value, 'utf8').digest('hex');
|
||||
const excerpt = (text, maximum = 400) => {
|
||||
@@ -23,7 +24,7 @@ const checkJob = value => ({ ...fields(value, ['id', 'status', 'taskId', 'runId'
|
||||
|
||||
// These are deterministic selected fields from a saved result, never a new
|
||||
// execution or an inferred success. Full JSON/text remains in its own artifact.
|
||||
export function compactToolFeedback(content) {
|
||||
export function compactToolFeedback(content, viewVersion = 1) {
|
||||
let value;
|
||||
try { value = JSON.parse(content); } catch { return { format: 'text-excerpt', excerpt: excerpt(content) }; }
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return { format: 'json-excerpt', excerpt: excerpt(content) };
|
||||
@@ -33,6 +34,7 @@ export function compactToolFeedback(content) {
|
||||
'returned_characters', 'truncated', 'totalMatches', 'error', 'message', 'summary', 'reason', 'note', 'unchanged_action_count', 'reading_hint',
|
||||
'browser_status', 'browser_job_id', 'result_artifact_id', 'evidence_verified', 'source_fingerprint', 'build_sha256', 'section', 'view_sha256', 'source_artifact_id', 'source_sha256',
|
||||
'tool_invocation_id', 'proof_id', 'proof_artifact_id', 'step_key', 'revision', 'all_verified', 'verified_steps', 'total_steps', 'requirements_current', 'contract_artifact_id', 'binding_sha256']);
|
||||
if (viewVersion === 2 && fileContinuation(value)?.next_read_file) result.file_read = fileContinuation(value);
|
||||
if (value.assertions) result.assertions = stats(value.assertions);
|
||||
if (Array.isArray(value.failed_steps)) result.failed_steps = value.failed_steps.slice(0, 3).map(step => fields(step, ['index', 'action', 'selector', 'status', 'error', 'actual']));
|
||||
if (value.observed_page) result.observed_page = { ...fields(value.observed_page, ['title']), text: excerpt(value.observed_page.text ?? ''),
|
||||
@@ -70,7 +72,7 @@ export function compactToolFeedback(content) {
|
||||
return result;
|
||||
}
|
||||
|
||||
export function latestToolDocument(store, session, run, groups) {
|
||||
export function latestToolDocument(store, session, run, groups, viewVersion = 1) {
|
||||
const group = groups.at(-1), calls = group?.messages[0].tool_calls;
|
||||
if (!calls?.length) return null;
|
||||
const ledger = new Map([...store.core.tool.values()].filter(tool => tool.sessionId === session.id && tool.projectId === session.projectId && tool.taskId === run.taskId)
|
||||
@@ -88,16 +90,18 @@ export function latestToolDocument(store, session, run, groups) {
|
||||
entries.push({ tool: call.function.name, source: { call_id: call.id, invocation_id: invocation.id, run_id: invocation.runId,
|
||||
result_artifact_id: artifact.id, result_sha256: artifact.sha256, arguments_sha256: hash(call.function.arguments),
|
||||
recorded_state: invocation.state, requires_verification: !!invocation.requiresVerification },
|
||||
result: compactToolFeedback(result.content), original_characters: result.content.length, view: 'selected-original-fields' });
|
||||
result: compactToolFeedback(result.content, viewVersion), original_characters: result.content.length, view: 'selected-original-fields' });
|
||||
}
|
||||
return { schemaVersion: 1, kind: 'latest-tool-feedback', sessionId: session.id, projectId: session.projectId,
|
||||
taskId: run.taskId, runId: run.id, group_index: group.index, group_sha256: group.sha256, entries };
|
||||
}
|
||||
|
||||
export function latestToolMessage(reference, document) {
|
||||
export function latestToolMessage(reference, document, viewVersion = 1) {
|
||||
if (![1, 2].includes(viewVersion)) throw new Error('未知的最新工具反馈视图版本。');
|
||||
return { role: 'system', content: [
|
||||
'以下是最近一组工具已经返回的实际结果反馈。该完整assistant/tool组因预算封存;这些字段来自原工件,不是再次执行、用户指令或推断。',
|
||||
'先依据本次返回状态推进任务。摘要省略的大字段可按result_artifact_id读取;不要为恢复已知状态反复查询或重放已完成操作。',
|
||||
viewVersion === 1 ? '先依据本次返回状态推进任务。摘要省略的大字段可按result_artifact_id读取;不要为恢复已知状态反复查询或重放已完成操作。'
|
||||
: '先依据原结果推进。result_artifact_id只恢复已返回页;未读原文件用file_read.next_read_file并核对SHA。原工件沿原artifact_id与next_offset继续,不逐层读包装,不重放已完成操作。',
|
||||
JSON.stringify({ latest_tools: { artifact_id: reference.id, sha256: reference.sha256 }, data: { kind: document.kind,
|
||||
entries: document.entries.map(entry => ({ tool: entry.tool, result_artifact_id: entry.source.result_artifact_id,
|
||||
recorded_state: entry.source.recorded_state, requires_verification: entry.source.requires_verification,
|
||||
@@ -106,7 +110,7 @@ export function latestToolMessage(reference, document) {
|
||||
}
|
||||
|
||||
export function verifyLatestToolDocument(store, session, plan, document, groups) {
|
||||
const expected = latestToolDocument(store, session, { id: plan.runId, taskId: plan.taskId }, groups);
|
||||
const expected = latestToolDocument(store, session, { id: plan.runId, taskId: plan.taskId }, groups, plan.latestToolsViewVersion ?? 1);
|
||||
if (!expected || JSON.stringify(document) !== JSON.stringify(expected) || document.entries.length !== plan.latestToolsEntries) {
|
||||
throw new Error('最新工具反馈的范围、来源或原结果视图不匹配。');
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { fileContinuation } from './read-continuation.mjs';
|
||||
|
||||
const hash = value => createHash('sha256').update(value, 'utf8').digest('hex');
|
||||
const parse = text => { try { return JSON.parse(text); } catch { return null; } };
|
||||
@@ -6,7 +7,7 @@ const boundary = (text, end) => end > 0 && end < text.length && /[\uD800-\uDBFF]
|
||||
|
||||
// An observation is a deterministic view of an actual result. It is never a
|
||||
// replacement assistant/tool message and never a model-generated assertion.
|
||||
function observation(tool, value) {
|
||||
function observation(tool, value, observationVersion = 1) {
|
||||
if (!value || typeof value !== 'object' || value.requires_verification || ['unknown', 'interrupted', 'denied'].includes(value.status)) return null;
|
||||
if (tool === 'read_file' && typeof value.content === 'string' && typeof value.path === 'string' && /^[a-f0-9]{64}$/i.test(value.sha256 ?? '')) {
|
||||
return { kind: 'file', path: value.path, sha256: value.sha256, start_line: value.start_line, end_line: value.end_line,
|
||||
@@ -33,7 +34,7 @@ function observation(tool, value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function workingCandidates(store, session, run, groups) {
|
||||
export function workingCandidates(store, session, run, groups, observationVersion = 1) {
|
||||
const ledger = new Map([...store.core.tool.values()].filter(tool => tool.sessionId === session.id && tool.projectId === session.projectId
|
||||
&& tool.taskId === run.taskId).map(tool => [tool.callId, tool]));
|
||||
const candidates = [], revisions = new Map(), seen = new Set(), filePages = new Map();
|
||||
@@ -44,7 +45,10 @@ export function workingCandidates(store, session, run, groups) {
|
||||
const artifact = store.owned('artifact', invocation.resultArtifactId, session.id);
|
||||
if (artifact.taskId !== run.taskId || artifact.kind !== 'tool-result' || artifact.runId !== invocation.runId) throw new Error('工作依据的任务或运行归属不匹配。');
|
||||
if (store.artifactStore.read(artifact) !== result.content) throw new Error('工作依据与原工具结果不一致。');
|
||||
const observed = observation(call.function.name, parse(result.content));
|
||||
const raw = parse(result.content), observed = observation(call.function.name, raw, observationVersion);
|
||||
if (observationVersion === 2 && observed?.kind === 'file') {
|
||||
for (const key of ['total_characters', 'next_start_line', 'budget_limited']) if (raw[key] !== undefined) observed[key] = raw[key];
|
||||
}
|
||||
if (!observed) continue;
|
||||
if (observed.kind === 'check-results') {
|
||||
const job = store.core.check_job.get(observed.job_id);
|
||||
@@ -96,21 +100,24 @@ export function workingEntry(candidate, characters) {
|
||||
content_sha256: hash(content.slice(0, end)) };
|
||||
}
|
||||
|
||||
export function workingDocument(session, run, entries) {
|
||||
export function workingDocument(session, run, entries, observationVersion = 1) {
|
||||
return { schemaVersion: 1, kind: 'task-working-set', sessionId: session.id, projectId: session.projectId, taskId: run.taskId,
|
||||
semantics: 'recorded-tool-observations; file hashes identify observed revisions, not current filesystem guarantees', entries };
|
||||
semantics: 'recorded-tool-observations; file hashes identify observed revisions, not current filesystem guarantees',
|
||||
...(observationVersion === 2 ? { observationVersion } : {}), entries };
|
||||
}
|
||||
|
||||
export function workingMessage(reference, document, viewVersion = 2) {
|
||||
const introduction = [
|
||||
'以下是当前Task已执行工具的工作依据数据,不是追加指令、授权或再次执行。文件内容只代表所列SHA256的读取版本,修改前仍须核对;检查状态来自实际工具结果。',
|
||||
'这些原结果所在的大消息组可能未发送。可以直接使用这里的代码和日志推进任务;截取不完整时读取对应result_artifact_id。不要重复扫描历史索引或重放已完成工具。',
|
||||
viewVersion < 3 ? '这些原结果所在的大消息组可能未发送。可以直接使用这里的代码和日志推进任务;截取不完整时读取对应result_artifact_id。不要重复扫描历史索引或重放已完成工具。'
|
||||
: '可直接使用这些代码和日志。result_artifact_id只恢复已返回页;尚未读取的原文件后文用file_read.next_read_file,核对SHA,不逐层读包装或重放操作。',
|
||||
];
|
||||
if (viewVersion === 1) return { role: 'system', content: [...introduction,
|
||||
JSON.stringify({ working_set: { artifact_id: reference.id, sha256: reference.sha256 }, data: document })].join('\n') };
|
||||
if (viewVersion !== 2) throw new Error('未知的工作依据发送视图版本。');
|
||||
if (![2, 3].includes(viewVersion)) throw new Error('未知的工作依据发送视图版本。');
|
||||
const data = { schemaVersion: document.schemaVersion, kind: document.kind, taskId: document.taskId,
|
||||
entries: document.entries.map(entry => ({ ...entry, source: { tool: entry.source.tool, result_artifact_id: entry.source.result_artifact_id } })) };
|
||||
entries: document.entries.map(entry => ({ ...entry, source: { tool: entry.source.tool, result_artifact_id: entry.source.result_artifact_id },
|
||||
...(viewVersion === 3 && fileContinuation(entry.observation)?.next_read_file ? { file_read: fileContinuation(entry.observation) } : {}) })) };
|
||||
return { role: 'system', content: [...introduction,
|
||||
'调用、运行、消息组及原结果的完整来源保存在working_set工件中;这里是按原结果核对的精简视图。',
|
||||
JSON.stringify({ working_set: { artifact_id: reference.id, sha256: reference.sha256 }, data }),
|
||||
@@ -130,7 +137,10 @@ export function verifyWorkingDocument(store, session, plan, document, groups) {
|
||||
if (artifact.kind !== 'tool-result' || artifact.sha256 !== source.result_sha256 || artifact.taskId !== plan.taskId || artifact.runId !== source.run_id) throw new Error('工作依据原结果身份不匹配。');
|
||||
const text = store.artifactStore.read(artifact), message = group.messages.find(value => value.role === 'tool' && value.tool_call_id === source.call_id);
|
||||
if (text !== message?.content) throw new Error('工作依据原消息内容不匹配。');
|
||||
const observed = observation(source.tool, parse(text));
|
||||
const raw = parse(text), observed = observation(source.tool, raw, document.observationVersion ?? 1);
|
||||
if (document.observationVersion === 2 && observed?.kind === 'file') {
|
||||
for (const key of ['total_characters', 'next_start_line', 'budget_limited']) if (raw[key] !== undefined) observed[key] = raw[key];
|
||||
}
|
||||
if (!observed || !Number.isInteger(entry.next_content_offset) || entry.next_content_offset < 0 || entry.next_content_offset > observed.content.length
|
||||
|| JSON.stringify(workingEntry({ source, observation: observed }, entry.next_content_offset)) !== JSON.stringify(entry)) throw new Error('工作依据摘录与实际工具结果不匹配。');
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
|
||||
export const APP_VERSION = '1.24.6';
|
||||
export const APP_VERSION = '1.24.7';
|
||||
|
||||
export function executionEnvironment() {
|
||||
const windows = process.platform === 'win32';
|
||||
|
||||
@@ -95,6 +95,7 @@ export function readText(project, relative) {
|
||||
|
||||
export function readLines(project, args) {
|
||||
const file = readText(project, args.path);
|
||||
if (args.expected_sha256 !== undefined && args.expected_sha256.toLowerCase() !== file.sha256) throw new Error('文件SHA256已变化,原分页不能继续拼接;请从新版本重新读取并核对。');
|
||||
const lines = file.content.split('\n');
|
||||
const start = Math.max(1, Number(args.start_line) || 1);
|
||||
const end = Math.min(lines.length, start + 299, Math.max(start, Number(args.end_line) || start + 199));
|
||||
|
||||
@@ -45,9 +45,9 @@ export const toolDefinitions = [
|
||||
parameters: { type: 'object', properties: {}, required: [] } } },
|
||||
{ type: 'function', function: { name: 'list_files', description: '查看当前项目的相对文件路径。依赖、版本目录、链接及常见凭据文件不会加入列表。',
|
||||
parameters: { type: 'object', properties: { path: { type: 'string' }, depth: { type: 'integer', minimum: 0, maximum: 10 } }, required: ['path'] } } },
|
||||
{ type: 'function', function: { name: 'read_file', description: '读取当前项目UTF-8文本与文件SHA256,行范围最多300行;实际页按当前请求预算缩小。分页用同一range_start_line/range_end_line和next_offset作为offset;此范围读完后用next_start_line继续。完整文件和原字节不变。',
|
||||
{ type: 'function', function: { name: 'read_file', description: '读取项目UTF-8行与SHA256(最多300行),按预算分页。续读保持range_start_line/range_end_line,以next_offset为offset并传expected_sha256核对版本;范围读完用next_start_line。',
|
||||
parameters: { type: 'object', properties: { path: { type: 'string' }, start_line: { type: 'integer' }, end_line: { type: 'integer' },
|
||||
offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 } }, required: ['path'] } } },
|
||||
offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 }, expected_sha256: { type: 'string', pattern: '^[a-fA-F0-9]{64}$' } }, required: ['path'] } } },
|
||||
{ type: 'function', function: { name: 'search_files', description: '在当前项目的文本文件中按字面内容检索。结果声明已搜索文件数与数量上限。',
|
||||
parameters: { type: 'object', properties: { query: { type: 'string' }, case_sensitive: { type: 'boolean' } }, required: ['query'] } } },
|
||||
{ type: 'function', function: { name: 'propose_file', description: '提出一个文本文件的完整新内容。只产生待审查提案,不写入项目;由用户查看差异后应用。',
|
||||
@@ -78,7 +78,7 @@ export function projectContext(project) {
|
||||
'浏览器实际观察的controls.selector已在该DOM核对仅匹配一个元素,优先使用此定位并核对当前页面变化。按钮的nth-of-type可能在多个父元素各匹配一次,不能假定唯一。浏览器失败返回原错误;根据实际字段修正新计划,不重复读完的同一页。',
|
||||
'检查结果含实际日志摘录及logArtifactId;需要更多失败信息时用read_artifact分段读取完整工件,不要要求用户重复提供工作台已有的日志。',
|
||||
'若能力表提供浏览器工具,页面任务在构建后先用plan_browser/run_browser取得真实DOM与错误,按实际CSS定位交互和断言;观察或截图不代表通过。修复后重新构建并准备新计划验证,已有浏览器验收未通过时先处理再准备Git交付。',
|
||||
'工作台会保留当前Task的代码与执行依据视图,绑定原工具结果和读取版本;可直接据此推进,不必反复恢复历史索引。内容有截取标记时按原结果工件取得缺少部分。',
|
||||
'可直接使用当前Task的代码与执行依据视图。result_artifact_id只恢复已返回页;未读文件用read_file按原行范围和next_offset续读,expected_sha256核对版本,不拼接不同SHA。',
|
||||
'最新完整工具组过大时,工作台发送可核验的最近工具反馈。先使用已返回状态继续;同一工程状态连续核对三次而未推进任务会暂停,不能把查询次数当成完成工作。',
|
||||
'读取工件继续使用原artifact_id与next_offset;read_artifact这次返回的包装工具结果不是下一页入口。不要逐层读取包装或为了恢复已有代码而反复扫描历史索引。',
|
||||
'文件已审核应用且实际检查通过后,可用plan_delivery准备Git提交预览。成功后工作台停止模型请求,等待用户在任务记录中审查并确认;不要继续查询提交状态,不把预览说成已提交。用delivery_report保存阶段证据;正式提交后的报告由工作台自动生成。',
|
||||
|
||||
+14
-3
@@ -27,7 +27,7 @@ import { RequestPlanner, verifyPlanEvidence } from '../core/context/request-plan
|
||||
import { ENGINE_SEED_RESERVATION } from '../shared/contracts/engine-context.mjs';
|
||||
import { InputAttachments } from '../core/context/input-attachments.mjs';
|
||||
import { BudgetResume } from '../core/context/budget-resume.mjs';
|
||||
import { artifactPage, filePage, readMessageBudget, recordArtifactRead, recordBrowserRead, recordFileRead, recordUnchangedCheck, clearReadStreak, recordSessionInspection, recordUnchangedAction, readCoverageContext, readMetadataReserve, BROWSER_READ_HINT } from '../core/context/read-budget.mjs';
|
||||
import { artifactPage, filePage, readMessageBudget, readBatchBudget, spendReadBudget, recordArtifactRead, recordBrowserRead, recordFileRead, recordUnchangedCheck, clearReadStreak, recordSessionInspection, recordUnchangedAction, readCoverageContext, readMetadataReserve, BROWSER_READ_HINT } from '../core/context/read-budget.mjs';
|
||||
import { taskDeliveryProgress } from '../core/context/delivery-progress.mjs';
|
||||
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
|
||||
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
|
||||
@@ -119,6 +119,7 @@ export function validateToolArgs(tool, args) {
|
||||
for (const field of required) if (typeof args[field] !== 'string') throw new Error('工具参数 ' + field + ' 必须是文本。');
|
||||
for (const field of ['depth', 'start_line', 'end_line', 'offset', 'limit']) if (args[field] !== undefined && (!Number.isInteger(args[field]) || args[field] < 0)) throw new Error('工具参数 ' + field + ' 必须是非负整数。');
|
||||
if (tool === 'read_file' && args.limit !== undefined && (args.limit < 1 || args.limit > 16000)) throw new Error('文件分页limit需要1到16000个字符。');
|
||||
if (tool === 'read_file' && args.expected_sha256 !== undefined && (typeof args.expected_sha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(args.expected_sha256))) throw new Error('文件续读expected_sha256需要64位SHA256。');
|
||||
if (args.case_sensitive !== undefined && typeof args.case_sensitive !== 'boolean') throw new Error('case_sensitive 必须是布尔值。');
|
||||
if (tool === 'plan_checks' && args.names !== undefined && (!Array.isArray(args.names) || args.names.some(name => typeof name !== 'string'))) throw new Error('检查脚本名称需要文本数组。');
|
||||
if (tool === 'plan_delivery' && args.message !== undefined && typeof args.message !== 'string') throw new Error('提交说明需要文本。');
|
||||
@@ -464,6 +465,9 @@ export class Runtime {
|
||||
const calls = message.tool_calls ?? [];
|
||||
if (run.worker && (calls.length > 16 || workerUsage(this.store, run.worker).toolCalls + calls.length > run.worker.budget.maxToolCalls)) throw new BudgetExceeded('worker_tool_limit', '子任务工具次数超出固定累计预算或单次16项上限;这批工具未执行,原响应和用量已保存。');
|
||||
run.readMessageBytes = readMessageBudget(planned.record, message);
|
||||
run.readBatchBudget = readBatchBudget(planned.record, message);
|
||||
run.readPageCharacters = planned.record.budget.inputBudget - planned.record.nextReadFixedInputTokens
|
||||
- (planned.record.workingRetentionTokens ?? 0) < 4096 ? 2000 : Infinity;
|
||||
const previousIds = new Set(session.providerMessages.flatMap(item => (item.tool_calls ?? []).map(call => call.id)));
|
||||
if (new Set(calls.map(call => call.id)).size !== calls.length || calls.some(call => previousIds.has(call.id))) throw new Error('模型返回了重复的工具调用 ID,请重新发送任务。');
|
||||
session.providerMessages.push(message);
|
||||
@@ -526,6 +530,7 @@ export class Runtime {
|
||||
}
|
||||
else if (signal.aborted) result = { status: 'interrupted', message: '用户停止了任务,这次调用没有执行。' };
|
||||
else result = await this.executeTool(session, call, run);
|
||||
spendReadBudget(run.readBatchBudget, call, result);
|
||||
session.providerMessages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
|
||||
if (call.function.name === 'prepare_change_set' && result.status === 'awaiting_review') preparedSets.add(result.change_set_id);
|
||||
if (call.function.name === 'call_registered_mcp' && result.requires_verification) mcpReview = result.mcp_job_id;
|
||||
@@ -625,7 +630,9 @@ export class Runtime {
|
||||
const proofHint = !!this.store.core.task.get(run.taskId)?.currentTaskPlanId && PLAN_READ_TOOLS.includes(tool);
|
||||
const readMetadata = { ...(proofHint ? { tool_invocation_id: event.invocationId } : {}),
|
||||
...(tool === 'read_browser_result' ? { repeated_read_count: Number.MAX_SAFE_INTEGER, reading_hint: BROWSER_READ_HINT } : {}) };
|
||||
const maximumMessageBytes = Math.max(1, (run.readMessageBytes ?? 16000) - readMetadataReserve(readMetadata));
|
||||
const batch = run.readBatchBudget;
|
||||
const pageBytes = batch?.remainingCalls ? Math.floor(batch.remainingBytes / batch.remainingCalls) : run.readMessageBytes ?? 16000;
|
||||
const maximumMessageBytes = Math.max(1, pageBytes - readMetadataReserve(readMetadata));
|
||||
if (!['act_browser_tab','prepare_environment','run_command', 'run_checks', 'run_browser'].includes(tool)) this.store.invocationState(session, event, 'running');
|
||||
else this.store.save(session);
|
||||
if (tool === 'inspect_session') result = { ...sessionSnapshot(session, run.project, run.config, value => this.provider.redact(value)), execution: this.store.executionSnapshot(session) };
|
||||
@@ -765,7 +772,11 @@ export class Runtime {
|
||||
}
|
||||
else if (tool === 'list_files') result = listFiles(run.project, args.path, args.depth ?? 3, 500);
|
||||
else if (tool === 'read_file') {
|
||||
result = filePage(readLines(run.project, args), args, { callId: call.id, maximumMessageBytes });
|
||||
result = filePage(readLines(run.project, args), args, { callId: call.id, maximumMessageBytes,
|
||||
// Match the planner's complete-small-source retention boundary;
|
||||
// returning a larger page that is immediately trimmed adds no useful
|
||||
// throughput. The escaped JSON budget can still make this smaller.
|
||||
...(run.readBatchBudget ? { maximumPageCharacters: run.readPageCharacters } : {}) });
|
||||
recordFileRead(this.store.core.task.get(run.taskId), result, event.invocationId, run.id);
|
||||
}
|
||||
else if (tool === 'search_files') result = searchFiles(run.project, args);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export interface BudgetPauseSource { reason?: string; limitingReason?: string }
|
||||
export interface BudgetPauseSource { reason?: string; limitingReason?: string; pauseKind?: string; tokenReservation?: { reservedTokens: number }; remainingTokens?: number; requiredInputTokens?: number; inputBudget?: number }
|
||||
export function budgetPausePresentation(pause?: BudgetPauseSource, stopReason?: string): {
|
||||
title: string; inputLabel: string; guidance: string;
|
||||
} | null;
|
||||
|
||||
@@ -6,6 +6,13 @@ const reasons = {
|
||||
export function budgetPausePresentation(pause, stopReason = '') {
|
||||
const reason = pause?.reason ?? stopReason;
|
||||
if (!reasons[reason]) return null;
|
||||
if (['token_limit', 'task_token_limit'].includes(reason) && (pause?.pauseKind === 'request_reservation'
|
||||
|| pause?.tokenReservation?.reservedTokens > pause?.remainingTokens)) return {
|
||||
title: reason === 'task_token_limit' ? '下一次请求超出任务余额' : '下一次请求超出运行余额', inputLabel: '当前窗口可用输入',
|
||||
guidance: pause?.requiredInputTokens !== undefined && pause.requiredInputTokens <= pause.inputBudget
|
||||
? '必需输入可容纳于当前窗口;下一次请求的用量预留超过剩余预算。原上游用量保持,请核对运行和任务预算后显式续接。'
|
||||
: '下一次请求的用量预留超过剩余预算。原上游用量保持;没有窗口分解的旧记录不补造输入结论,请核对预算后显式续接。',
|
||||
};
|
||||
if (reason === 'engine_input_budget' && pause?.limitingReason === 'remaining_token_budget') return {
|
||||
title: '原生引擎剩余预算不足', inputLabel: '当前窗口可用输入',
|
||||
guidance: '输入可容纳于当前上下文窗口;下一次请求的用量预留超过剩余预算。请核对运行和任务预算。',
|
||||
|
||||
@@ -23,7 +23,7 @@ export function checkModelDispatchBudget(store,session,run,config,body,overheadT
|
||||
const runRemainingTokens=remaining(run),taskRemainingTokens=remaining(task),remainingTokens=Math.min(runRemainingTokens,taskRemainingTokens);
|
||||
if(tokenReservation.reservedTokens>remainingTokens){
|
||||
const error=new BudgetExceeded(runRemainingTokens<=taskRemainingTokens?'token_limit':'task_token_limit','下一次模型请求的用量预留超过剩余预算,已在发送前暂停。原用量和已完成工具结果保留。');
|
||||
error.contextBudget={tokenReservation,remainingTokens,runRemainingTokens:Number.isFinite(runRemainingTokens)?runRemainingTokens:null,
|
||||
error.contextBudget={pauseKind:'request_reservation',tokenReservation,remainingTokens,runRemainingTokens:Number.isFinite(runRemainingTokens)?runRemainingTokens:null,
|
||||
taskRemainingTokens:Number.isFinite(taskRemainingTokens)?taskRemainingTokens:null};
|
||||
throw error;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user