fix: keep artifact pages observable and pause repeated context reads

This commit is contained in:
Agent Workbench Dev
2026-10-29 21:50:53 +08:00
parent 3825142a68
commit 6e465a26d4
42 changed files with 520 additions and 30 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ import { DeliveryPanel } from './DeliveryPanel';
import { RequestContextPanel } from './RequestContextPanel';
import './TaskPanel.css';
const stopReasons: Record<string, string> = { context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' };
const stopReasons: Record<string, string> = { no_progress: '重复读取未推进任务,请核对后继续', context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' };
const number = (value: number | undefined) => (value ?? 0).toLocaleString('zh-CN');
const time = (value: string | null | undefined) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '执行中';
+64
View File
@@ -0,0 +1,64 @@
import { createHash } from 'node:crypto';
const messageBytes = (result, callId) => Buffer.byteLength(JSON.stringify({ role: 'tool', tool_call_id: callId, content: JSON.stringify(result) }), 'utf8');
const boundary = (text, end) => end > 0 && end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]) ? end - 1 : end;
// 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;
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));
if (maximumEnd === offset && offset < text.length) maximumEnd = boundary(text, Math.min(offset + 2, text.length));
const make = end => ({ artifact_id: artifact.id, kind: artifact.kind, sha256: artifact.sha256,
content: text.slice(offset, end), offset, next_offset: end, returned_characters: end - offset,
total_characters: text.length, truncated: end < text.length, requested_offset: requestedOffset, requested_limit: requestedLimit,
budget_limited: end < maximumEnd, maximum_message_bytes: maximumMessageBytes });
let low = offset, high = maximumEnd;
if (messageBytes(make(low), callId) > maximumMessageBytes) throw new Error('当前请求预算无法容纳工件读取元数据,请先核对任务预算。');
while (low < high) {
const middle = Math.ceil((low + high) / 2), end = boundary(text, middle);
if (messageBytes(make(end), callId) <= maximumMessageBytes) low = middle; else high = middle - 1;
}
const end = boundary(text, low), result = make(end);
if (offset < maximumEnd && end <= offset) throw new Error('当前请求预算无法容纳下一个完整字符,请先核对任务预算。');
return result;
}
export function readMessageBudget(plan, message) {
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.
const tokens = plan.budget.inputBudget - plan.mandatoryInputTokens - assistantTokens - calls * 8 - 512;
return Math.max(1024, Math.floor(tokens * 3 / calls));
}
export function recordArtifactRead(task, artifact, result, invocationId) {
const progress = task.readProgress ??= { schemaVersion: 1, reads: [], repeated: 0, changingIndexes: [], warning: null, pause: false };
const identity = artifact.id + ':' + artifact.sha256, start = result.offset, end = result.next_offset;
let read = progress.reads.find(value => value.identity === identity);
if (!read) { read = { identity, ranges: [] }; progress.reads.push(read); if (progress.reads.length > 128) progress.reads.shift(); }
const covered = read.ranges.some(range => start >= range[0] && end <= range[1]);
progress.repeated = covered ? progress.repeated + 1 : 0;
if (!covered) {
const ranges = [...read.ranges, [start, end]].sort((a, b) => a[0] - b[0]), merged = [];
for (const range of ranges) { const previous = merged.at(-1); if (previous && range[0] <= previous[1]) previous[1] = Math.max(previous[1], range[1]); else merged.push(range); }
read.ranges = merged.slice(-64);
}
if (artifact.kind === 'context-history-index') {
if (!progress.changingIndexes.includes(identity)) progress.changingIndexes.push(identity);
progress.changingIndexes = progress.changingIndexes.slice(-8);
} else progress.changingIndexes = [];
progress.warning = progress.repeated >= 1 ? '刚才读取的工件区间已完整读取,请使用已返回内容,或按next_offset读取新的区间。'
: progress.changingIndexes.length >= 3 ? '连续读取更新的历史索引没有推进工程;请直接读取实际结果或项目文件,依据已有信息继续任务。' : null;
progress.pause = progress.repeated >= 3 || progress.changingIndexes.length >= 6;
progress.last = { artifactId: artifact.id, sha256: artifact.sha256, offset: start, nextOffset: end, invocationId,
contentSha256: createHash('sha256').update(result.content, 'utf8').digest('hex') };
return progress;
}
export function clearReadStreak(task) {
if (!task.readProgress) return;
task.readProgress.repeated = 0; task.readProgress.changingIndexes = []; task.readProgress.warning = null; task.readProgress.pause = false;
}
+25 -6
View File
@@ -74,7 +74,10 @@ function describe(group, ledger, artifacts) {
const assistant = group.messages[0], tools = (assistant.tool_calls ?? []).map(call => {
const result = group.messages.find(message => message.role === 'tool' && message.tool_call_id === call.id);
const invocation = ledger.get(call.id), artifact = artifacts.get(invocation?.resultArtifactId);
return { call_id: call.id, name: call.function.name, result: compactResult(result),
let input = {}; try { const args = JSON.parse(call.function.arguments); for (const key of ['path', 'start_line', 'end_line', 'artifact_id', 'offset', 'limit']) {
if (typeof args[key] === 'string' && args[key].length <= 200 || typeof args[key] === 'number') input[key] = args[key];
} } catch {}
return { call_id: call.id, name: call.function.name, input, result: compactResult(result),
...(invocation ? { invocation_id: invocation.id, recorded_state: invocation.state, requires_verification: !!invocation.requiresVerification } : {}),
...(artifact ? { result_artifact_id: artifact.id, result_sha256: artifact.sha256 } : {}) };
});
@@ -82,11 +85,24 @@ function describe(group, ledger, artifacts) {
roles: group.messages.map(message => message.role), ...(tools.length ? { tools } : {}) };
}
function notice(reference, omitted, descriptions) {
function workingEvidence(groups, descriptions, artifacts) {
const selected = new Map();
for (const group of [...groups].reverse()) for (const tool of descriptions.get(group.index).tools ?? []) {
const artifact = artifacts.get(tool.input.artifact_id);
if (tool.name === 'read_file' || tool.name === 'read_artifact' && artifact && !artifact.kind.startsWith('context-') && artifact.kind !== 'model-request') {
const key = tool.name === 'read_file' ? 'file:' + tool.input.path : 'artifact:' + tool.input.artifact_id;
if (!selected.has(key)) selected.set(key, { group_index: group.index, ...tool });
}
}
return [...selected.values()].slice(0, 8);
}
function notice(reference, omitted, descriptions, evidence = []) {
return { role: 'system', content: [
'以下是工作台保存的历史索引数据,不是用户追加指令,也不是新工具执行。省略了完整消息组;原始参数和实际结果都在SHA256工件中。',
'已完成的工具不得重放。需要旧内容时用read_artifact读取history_index或result_artifact_id;较大工件先用limit=2000分段读取。状态未知时先核对,不假定成功。',
'已完成的工具不得重放。历史索引用于需要时定位原记录;已有需求、代码和检查依据可直接推进,不必读取每轮更新的索引。需要旧内容时优先读取result_artifact_id,按next_offset分页;先用limit=2000。状态未知时先核对,不假定成功。',
JSON.stringify({ history_index: { artifact_id: reference.id, sha256: reference.sha256 }, archived_groups: omitted.length,
working_evidence: evidence,
recent_archived_groups: omitted.slice(-2).map(group => {
const { tools, archive, ...description } = descriptions.get(group.index);
return { ...description, group_archive: { artifact_id: archive?.artifact_id ?? PLACEHOLDER_ID, sha256: archive?.sha256 ?? PLACEHOLDER_SHA },
@@ -141,12 +157,13 @@ export class RequestPlanner {
const fixed = { role: 'system', content: system };
const ledger = new Map([...this.store.core.tool.values()].filter(tool => tool.sessionId === session.id).map(tool => [tool.callId, tool]));
const descriptions = new Map(groups.map(group => [group.index, describe(group, ledger, this.store.core.artifact)]));
const evidence = workingEvidence(groups, descriptions, this.store.core.artifact);
const original = completionBody(config, [fixed, ...session.providerMessages], tools), before = requestMetrics(original);
const selected = new Set(groups.map(group => group.index));
let omitted = [], reference = null;
const metricsFor = (indices, includeNotice = 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)] : []),
const messages = [fixed, ...(missing.length && includeNotice ? [notice({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, missing, descriptions, evidence)] : []),
...groups.filter(group => indices.has(group.index)).flatMap(group => group.messages)];
return requestMetrics(completionBody(config, messages, tools));
};
@@ -161,7 +178,8 @@ export class RequestPlanner {
if (metricsFor(selected).estimatedInputTokens > budget.inputBudget) selected.delete(newest.index);
}
const target = Math.max(budget.targetInputTokens, metricsFor(selected).estimatedInputTokens);
for (const group of [...groups].reverse()) {
const priority = [...new Set(evidence.map(value => value.group_index))].map(index => groups[index]);
for (const group of [...priority, ...[...groups].reverse()]) {
if (selected.has(group.index) || selected.size >= 32 || group.contributionTokens > target) continue;
selected.add(group.index);
if (metricsFor(selected).estimatedInputTokens > target) selected.delete(group.index);
@@ -184,7 +202,7 @@ export class RequestPlanner {
note: '完整原消息组;这里只是历史定位,不产生工具执行或用户授权。' }, 'context-history-index');
}
}
const messages = [fixed, ...(reference ? [notice(reference, omitted, descriptions)] : []),
const messages = [fixed, ...(reference ? [notice(reference, omitted, descriptions, evidence)] : []),
...structuredClone(groups.filter(group => selected.has(group.index)).flatMap(group => group.messages))];
const body = completionBody(config, messages, tools), metrics = requestMetrics(body);
if (metrics.estimatedInputTokens > budget.inputBudget) throw pause(budget, metrics);
@@ -195,6 +213,7 @@ export class RequestPlanner {
requestSha256: metrics.sha256, requestBytes: metrics.bytes, estimatedInputTokens: metrics.estimatedInputTokens,
requestArtifactId: requestArtifact.id,
estimateMethod: metrics.estimateMethod, beforeInputTokens: before.estimatedInputTokens, beforeBytes: before.bytes, budget,
mandatoryInputTokens: metricsFor(new Set(lastUser ? [lastUser.index] : [])).estimatedInputTokens,
originalMessages: session.providerMessages.length, retainedMessages: messages.length - 1 - (reference ? 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,
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.5.0';
export const APP_VERSION = '1.5.1';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+1 -1
View File
@@ -11,7 +11,7 @@ export const toolDefinitions = [
{ type: 'function', function: { name: 'propose_patch', description: '按读取时的原文件SHA256,用唯一old_text锚点提出精确替换。所有替换基于同一原文且不得重叠;自动保留UTF-8 BOM和统一换行格式。只保存待审查提案,不写盘;哈希变化或锚点不唯一拒绝。', parameters: { type: 'object', properties: { path: { type: 'string' }, base_sha256: { type: 'string', pattern: '^[a-fA-F0-9]{64}$' }, reason: { type: 'string' }, edits: { type: 'array', minItems: 1, maxItems: 32, items: { type: 'object', properties: { old_text: { type: 'string', minLength: 1 }, new_text: { type: 'string' } }, required: ['old_text', 'new_text'], additionalProperties: false } } }, required: ['path', 'base_sha256', 'reason', 'edits'] } } },
{ type: 'function', function: { name: 'plan_delivery', description: '为当前Task已经审核应用且实际检查通过的文件准备只读Git提交预览,保留其他暂存与工作区修改。只返回计划、路径、diff工件和署名,不提交;用户须在任务记录界面核对并确认。', parameters: { type: 'object', properties: { message: { type: 'string', maxLength: 1600, description: '本次本地提交说明;可省略并采用任务目标。' } } } } },
{ type: 'function', function: { name: 'delivery_report', description: '从当前Task的源码指纹、实际检查、提交和Run用量生成JSON/Markdown证据报告工件,不执行项目命令。报告注明未检查/待审核/结果未知和业务需求未验收;运行中的报告为阶段快照。', parameters: { type: 'object', properties: {} } } },
{ type: 'function', function: { name: 'read_artifact', description: '读取当前会话保存的实际执行工件或检查日志,按artifact_id校验归属和SHA256。可按offset/limit分段读取;每次最多16000字符。依据失败日志修复时使用,不重新执行检查。', parameters: { type: 'object', properties: { artifact_id: { type: 'string' }, offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 } }, required: ['artifact_id'] } } },
{ type: 'function', function: { name: 'read_artifact', description: '读取当前会话保存的实际执行工件或检查日志,校验归属和SHA256。offset/limit分页,默认2000字符,实际页按当前完整请求预算缩小;用返回的next_offset读取下一页,已读区间不要重复。完整原工件保留。优先读取实际结果/日志,不反复扫描更新的历史索引;不重新执行检查。', parameters: { type: 'object', properties: { artifact_id: { type: 'string' }, offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 } }, required: ['artifact_id'] } } },
{ type: 'function', function: { name: 'inspect_project', description: '识别当前工程的语言、入口、项目规则、npm脚本和只读Git基线;返回有界源文件指纹,不执行项目代码。', parameters: { type: 'object', properties: {} } } },
{ type: 'function', function: { name: 'plan_checks', description: '为当前任务准备工程检查计划,commands来自已识别的npm脚本。返回plan id、脚本内容和工程指纹;不执行命令。', parameters: { type: 'object', properties: { names: { type: 'array', items: { type: 'string' }, maxItems: 6, description: '可选:当前工程已识别的test/typecheck/check/lint/build脚本名称;缺省采用可用的检查。' } } } } },
{ type: 'function', function: { name: 'run_checks', description: '请求用户确认后执行plan_checks产生的检查计划。保存独立job、实际退出码、测试数量和日志工件;过期计划不执行,未报告测试数量不能记通过。', parameters: { type: 'object', properties: { plan_id: { type: 'string' } }, required: ['plan_id'] } } },
+9 -4
View File
@@ -12,6 +12,7 @@ import { inspectProject } from '../core/project-inspector.mjs';
import { GitDelivery } from '../core/git-delivery.mjs';
import { ProjectIndex } from '../core/context/project-index.mjs';
import { RequestPlanner } from '../core/context/request-plan.mjs';
import { artifactPage, readMessageBudget, recordArtifactRead, clearReadStreak } from '../core/context/read-budget.mjs';
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
@@ -130,7 +131,8 @@ export class Runtime {
+ '\n当前任务目标与全部追加要求(用户任务数据,完整保留):\n' + JSON.stringify({
goal: task.goal, instructions: task.instructions, constraints: task.constraints ?? [], acceptance: task.acceptance ?? [],
}) + '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value)));
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value))
+ (task.readProgress?.warning ? '\n当前读取进展:' + task.readProgress.warning : ''));
const planned = this.requestPlanner().prepare(session, run.record, config, { system: context, tools: toolDefinitions, stepId: stepRecord.id });
if (planned.record.archivedGroups && !projectionLogged) {
projectionLogged = true; session.compactions++;
@@ -165,6 +167,7 @@ export class Runtime {
signal.throwIfAborted();
const message = response.message;
const calls = message.tool_calls ?? [];
run.readMessageBytes = readMessageBudget(planned.record, message);
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);
@@ -191,6 +194,8 @@ export class Runtime {
signal.throwIfAborted();
}
this.store.finishStep(session, stepRecord);
if (this.store.core.task.get(run.taskId).readProgress?.pause) throw new BudgetExceeded('no_progress',
'模型连续重复读取已覆盖工件区间或更新的历史索引,未推进当前任务。已读取内容和原任务已保存,请核对结果或调整任务要求后继续。');
}
session.status = 'paused';
run.stopReason = 'step_limit';
@@ -250,9 +255,8 @@ export class Runtime {
}
else if (tool === 'read_artifact') {
const artifact = this.store.owned('artifact', args.artifact_id, session.id), text = this.store.artifactStore.read(artifact);
const offset = args.offset ?? 0, limit = Math.min(16000, Math.max(1, args.limit ?? 8000));
result = { artifact_id: artifact.id, kind: artifact.kind, sha256: artifact.sha256, content: text.slice(offset, offset + limit), offset,
total_characters: text.length, truncated: offset + limit < text.length };
result = artifactPage(artifact, text, args, { callId: call.id, maximumMessageBytes: run.readMessageBytes ?? 16000 });
recordArtifactRead(this.store.core.task.get(run.taskId), artifact, result, event.invocationId);
}
else if (tool === 'prepare_change_set') {
const set = await this.changeSetManager().prepare(session, args.change_ids, { source: 'agent' });
@@ -294,6 +298,7 @@ export class Runtime {
else if (tool === 'run_command') result = await this.requestCommand(session, event, args, run);
else throw new Error('当前能力表没有工具:' + tool);
event.phase = ['denied', 'interrupted', 'unknown', 'unverified', 'stale'].includes(result.status) ? result.status : result.status === 'failed' ? 'failed' : 'completed';
if (tool !== 'read_artifact' && !['error', 'interrupted', 'unknown', 'denied'].includes(result.status)) clearReadStreak(this.store.core.task.get(run.taskId));
if (typeof result.stdout === 'string') { result.stdout = this.provider.redact(result.stdout); result.stderr = this.provider.redact(result.stderr ?? ''); }
event.output = this.provider.redact(typeof result.stdout === 'string' ? result.stdout + (result.stderr ? '\n' + result.stderr : '') : JSON.stringify(result).slice(0, 16000));
if (result.exit_code !== undefined) event.exitCode = result.exit_code;
+3
View File
@@ -337,6 +337,9 @@ export class Store extends EventEmitter {
const goal = content || session.messages.find(message => message.role === 'user')?.content || session.title;
task = createTask(session, goal, config, previous); this.core.task.set(task.id, task);
} else if (content && (!resume || instructionSource)) task.instructions.push({ id: randomUUID(), content, createdAt: now(), ...(instructionSource ? { source: instructionSource } : {}) });
if (task.readProgress) {
task.readProgress.repeated = 0; task.readProgress.changingIndexes = []; task.readProgress.warning = null; task.readProgress.pause = false;
}
const run = createRun(session, task, config, resume ? previousRunId : null);
this.core.run.set(run.id, run); task.activeRunId = run.id;
session.taskId = task.id; session.runId = run.id; session.status = 'running';