feat(runtime): observe turn evidence without changing execution controls

This commit is contained in:
Agent Workbench Dev
2026-11-04 11:26:47 +08:00
parent 785dd0c54d
commit 6fe04042c5
291 changed files with 66740 additions and 3 deletions
+7
View File
@@ -89,3 +89,10 @@
.checkpoint-assessment ul { margin: 8px 0; padding-left: 18px; overflow-wrap: anywhere; }
.checkpoint-assessment .button, .task-checkpoints > .button { margin-top: 8px; height: auto; min-height: 36px; white-space: normal; }
@media (max-width: 620px) { .task-checkpoints .button, .task-checkpoints .text-button { min-height: 44px; } }
.turn-progress { margin-top: 14px; font-size: 12px; line-height: 1.65; overflow-wrap: anywhere; }
.turn-progress summary { cursor: pointer; color: #154b4a; font-weight: 600; }
.turn-progress ol { list-style: none; padding: 0; margin: 10px 0; }
.turn-progress li { border-top: 1px solid #dce7e2; padding: 10px 0; }
.turn-progress li strong { font-size: 12px; }
.turn-progress li p { margin: 4px 0; }
@media (max-width: 620px) { .turn-progress .text-button { min-height: 44px; } }
+2
View File
@@ -10,6 +10,7 @@ import { WorkspacePanel } from './WorkspacePanel';
import { BrowserPanel } from './BrowserPanel';
import { TaskPlanPanel } from './TaskPlanPanel';
import { RequirementPanel } from './RequirementPanel';
import { TurnProgress } from './TurnProgress';
import { TaskCheckpointPanel } from './TaskCheckpointPanel';
import { McpJobHistory } from './McpJobHistory';
import './TaskPanel.css';
@@ -116,6 +117,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
<dt>本次预算</dt><dd>{number(run.budget?.maxTokens)} tokens · {Math.round((run.budget?.maxDurationMs ?? 0) / 60000)} 分钟 · {run.budget?.maxSteps} 轮</dd><dt>任务累计</dt><dd>{number(execution?.accountedTaskTokens)} / {number(task.budget.maxTokens)} tokens</dd>
</dl>{run.stopReason && <p className="run-stop">{stopReasons[run.stopReason] || run.stopReason}</p>}
<p className="record-footnote">用量按请求尝试累计,包含失败响应已报告的 tokens;未报告的请求单独估算。历史缺失不补造,tokens 不等于费用。</p>
<TurnProgress run={run} openArtifact={openArtifact} />
</> : <p className="record-empty"><LoaderCircle size={14} className="spin" />正在读取运行记录</p>}
</section>}
{run && <RequestContextPanel session={session} runId={run.id} onError={onError} openArtifact={openArtifact} />}
+25
View File
@@ -0,0 +1,25 @@
import type { Run } from './types';
const labels: Record<string, string> = { baseline: '本次运行基线', waiting: '等待所属操作', evidence_growth: '新增外显证据', new_failure_evidence: '新增失败证据',
user_boundary: '用户边界变化', repeated_failure_candidate: '重复失败候选', repeated_read_candidate: '重复读取候选', no_observed_change: '未见新外显事实', unknown_bounded: '观察容量已满,保留未知' };
const failureLabels: Record<string, string> = { invalid_input: '参数无效', permission: '权限或审批拒绝', requires_verification: '结果待核对', network: '网络连接', service: '上游服务',
authentication: '身份验证', rate_limit: '请求限流', quota: '服务额度', tool_or_environment: '工具或环境', unknown: '尚未分类' };
export function TurnProgress({ run, openArtifact }: { run: Run; openArtifact: (id: string) => void }) {
if (!run.progressShadow && !run.progressShadowError) return null;
const shadow = run.progressShadow;
return <details className="turn-progress" aria-label="单轮观察">
<summary>单轮观察 · 仅记录{shadow ? ` · 已保留 ${shadow.turns.filter(row => row.phase === 'settled').length} 轮` : ''}</summary>
<p className="record-footnote">依据实际工具、文件范围、失败和证据变化分类;观察不改变停止、权限或预算。</p>
{run.progressShadowError && <p className="plan-problem">部分观察未能记录,原工具结果保留。</p>}
{shadow?.truncated && <p className="record-footnote">观察已达保留上限;较早收据仍在原工件中,未保留范围不推定为重复。</p>}
<ol>{shadow?.turns.map((turn, index) => <li key={`${turn.stepId}/${turn.phase}/${index}`}>
<strong>{turn.stepIndex === null ? '基线' : `第 ${turn.stepIndex} 轮`} · {labels[turn.classification] ?? turn.classification}</strong>
<p>新增读取 {turn.delta.read_characters} 字符 · 重复读取 {turn.delta.repeated_reads} 次{turn.delta.changed_files ? ` · 改动文件 ${turn.delta.changed_files}` : ''}{turn.delta.check_results ? ` · 检查结果 ${turn.delta.check_results}` : ''}{turn.delta.requirement_evidence ? ` · 要求证据 ${turn.delta.requirement_evidence}` : ''}</p>
{!!(turn.delta.new_failures || turn.delta.repeated_failures) && <p>新失败 {turn.delta.new_failures} · 重复失败 {turn.delta.repeated_failures}</p>}
{turn.reasons.some(reason => /^(new|repeated)_failure:/.test(reason)) && <p>失败类别:{[...new Set(turn.reasons.filter(reason => /^(new|repeated)_failure:/.test(reason)).map(reason => {
const kind = reason.split(':')[1]; return failureLabels[kind] ?? kind;
}))].join('、')}</p>}
{!!turn.waiting.length && <p>等待 {turn.waiting.map(row => ({ approval: '审批', check_job: '检查作业', review: '审查' }[row.kind] ?? row.kind)).join('、')}</p>}
{run.progressShadowArtifactIds?.[index] && <button className="text-button" onClick={() => openArtifact(run.progressShadowArtifactIds![index])}>查看原观察收据</button>}
</li>)}</ol>
</details>;
}
+6
View File
@@ -142,6 +142,12 @@ export interface Usage { requests: number; inputTokens: number; outputTokens: nu
export interface RunBudget { maxSteps: number; maxDurationMs: number; maxTokens: number; maxTaskTokens: number }
export interface RunBrief { id: string; taskId: string; status: string; startedAt: string; finishedAt: string | null; steps: number; toolCalls: number; usage: Usage; stopReason: string | null; model: ModelSnapshot; budget: RunBudget; resumeOf: string | null; workspaceIdentity?: WorkspaceIdentity }
export interface Run extends RunBrief { engine: string; review?: { kind: string; planId: string; status: string; preparedAt?: string; resolvedAt?: string }; currentContextPlanId?: string; checkpoint: { completedToolIds: string[]; pendingToolIds: string[]; requiresVerification: string[] } }
export interface TurnObservation {
stepId: string | null; stepIndex: number | null; phase: string; classification: string; reasons: string[]; truncated: boolean;
delta: { read_characters: number; repeated_reads: number; changed_files: number; check_results: number; requirement_evidence: number; new_failures: number; repeated_failures: number };
waiting: { kind: string; id: string }[];
}
export interface Run { progressShadow?: { mode: 'shadow'; observations: number; truncated: boolean; turns: TurnObservation[] }; progressShadowArtifactIds?: string[]; progressShadowError?: { kind: string; phase: string } }
export interface RunBrief { purpose?: 'execution' | 'diagnostic'; source?: string; taskStatusBefore?: string; consumption?: ModelConsumption[] }
export interface TaskCheckpoint {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; createdAt: string;
@@ -0,0 +1,90 @@
import { observeTurn, toolProgressFacts } from './turn-progress.mjs';
import { planHash } from '../../shared/contracts/task-plans.mjs';
// Local, bounded observation. Original tools/jobs remain the evidence of record.
// Observer failure is recorded on the Run and cannot interrupt execution.
export function recordTurnProgress(store, session, run, step, phase = 'settled', failure = null) {
try {
if (run.taskId !== session.taskId || run.sessionId !== session.id || run.projectId !== session.projectId) throw new Error('Observer Task/Run ownership mismatch.');
if (step && (step.runId !== run.id || step.taskId !== run.taskId || step.sessionId !== session.id || step.projectId !== session.projectId))
throw new Error('Observer step ownership mismatch.');
const task = store.owned('task', run.taskId, session.id);
const owned = row => row.taskId === run.taskId && row.sessionId === session.id && row.projectId === session.projectId;
const tools = [];
// Waiting is an intermediate snapshot, not a second consumption of tools
// already completed earlier in this same turn. Settle them exactly once.
for (const id of phase === 'waiting' ? [] : step?.progressToolIds ?? []) {
const record = store.owned('tool', id, session.id);
if (!owned(record) || record.runId !== run.id || record.stepId !== step.id) throw new Error('Observer tool ownership mismatch.');
const artifact = store.owned('artifact', record.resultArtifactId, session.id);
if (!owned(artifact) || artifact.runId !== run.id || artifact.kind !== 'tool-result') throw new Error('Observer result ownership mismatch.');
tools.push(toolProgressFacts(record, JSON.parse(store.artifactStore.read(artifact)), artifact, record.progressFailureCategory));
}
if (failure) {
const event = session.events.findLast(row => row.runId === run.id && row.diagnostic?.id === failure.id);
tools.push({ id: failure.id ?? null, name: 'model_request',
sourceEventId: event?.id, diagnosticSha256: event ? planHash(event.diagnostic) : null,
artifactId: failure.upstream?.artifactId, resultSha256: failure.upstream?.artifactSha256,
failure: { category: failure.kind ?? 'unknown', signature: planHash({ kind: failure.kind, code: failure.code,
httpStatus: failure.httpStatus, stage: failure.stage, outcome: failure.outcome, message: failure.message }) } });
}
const waiting = session.approvals.filter(row => row.taskId === run.taskId && row.projectId === session.projectId && row.runId === run.id && row.status === 'pending').map(row => ({ kind: 'approval', id: row.id }));
for (const row of store.core.check_job.values()) if (owned(row) && ['queued', 'running'].includes(row.status)) waiting.push({ kind: 'check_job', id: row.id });
if (session.status === 'needs_review') waiting.push({ kind: 'review', id: run.id });
const facts = { projectId: session.projectId, sessionId: session.id, taskId: run.taskId, runId: run.id,
stepId: step?.id, stepIndex: step?.index, phase, tools, waiting,
changes: session.changes.filter(row => row.taskId === run.taskId && row.status === 'applied').map(row => [row.path, row.sha256]),
checks: [...store.core.check_job.values()].filter(row => owned(row) && !row.requiresVerification && !row.stale && ['passed', 'failed'].includes(row.status))
.map(row => [row.sourceFingerprint, row.status, row.results.map(result => [result.name, result.status, store.core.artifact.get(result.logArtifactId)?.sha256])]),
requirements: (task.requirementProofs ?? []).filter(row => row.status === 'verified' && task.requirementRevisions?.at(-1)?.items.some(item => item.key === row.key && planHash(item) === row.requirementSha256))
.map(row => [row.key, row.requirementSha256, row.sourceFingerprint, row.outcome ? planHash(row.outcome) : planHash(row.note)]),
userBoundaries: (task.instructions ?? []).filter(row => row.source !== 'review-action').map(row => [row.id, planHash(row.content)]) };
const result = observeTurn(run.progressShadow, facts);
// Persist only the individual public-fact observation as an immutable receipt.
const artifact = store.artifactStore.write(session, run, result.observation, { kind: 'turn-progress-shadow' });
store.core.artifact.set(artifact.id, artifact);
run.progressShadow = result.state;
run.progressShadowArtifactIds = [...(run.progressShadowArtifactIds ?? []), artifact.id].slice(-40);
store.save(session, { type: 'run.progress_shadow', detail: { runId: run.id, stepId: step?.id ?? null, classification: result.observation.classification, artifactId: artifact.id } });
return result.observation;
} catch {
run.progressShadowError = { kind: 'observation_unavailable', phase };
return null;
}
}
export function inspectTurnProgress(store, session, run) {
if (!run.progressShadow) return { mode: 'shadow', recorded: false, turns: [], evidence_verified: false, error: run.progressShadowError ?? null };
const view = { mode: 'shadow', recorded: true, observations: run.progressShadow.observations, truncated: run.progressShadow.truncated,
turns: structuredClone(run.progressShadow.turns), artifact_ids: run.progressShadowArtifactIds ?? [], evidence_verified: true,
error: run.progressShadowError ? '部分观察未能记录,保留的原收据单独核对;原执行结果保持。' : null };
try {
const owned = row => row.sessionId === session.id && row.projectId === session.projectId && row.taskId === run.taskId && row.runId === run.id;
if (view.turns.length !== view.artifact_ids.length) throw new Error('单轮观察与原收据数量不一致。');
for (let i = 0; i < view.turns.length; i++) {
const artifact = store.owned('artifact', view.artifact_ids[i], session.id);
if (!owned(artifact) || artifact.kind !== 'turn-progress-shadow') throw new Error('单轮观察原收据归属不一致。');
const original = JSON.parse(store.artifactStore.read(artifact));
if (planHash(original) !== planHash(view.turns[i])) throw new Error('单轮观察与原收据不一致。');
for (const ref of original.tools) {
if (ref.tool === 'model_request') {
const event = session.events.find(row => row.id === ref.source_event_id && row.runId === run.id);
if (!event?.diagnostic || event.diagnostic.id !== ref.id || planHash(event.diagnostic) !== ref.diagnostic_sha256)
throw new Error('单轮观察的原模型失败记录待核对。');
if (ref.result_artifact_id) {
const result = store.owned('artifact', ref.result_artifact_id, session.id);
if (!owned(result) || result.sha256 !== ref.result_sha256 || !['model-http-response', 'model-stream-response'].includes(result.kind))
throw new Error('单轮观察的原模型失败响应来源变化。');
store.artifactStore.read(result);
}
continue;
}
const record = store.owned('tool', ref.id, session.id), result = store.owned('artifact', ref.result_artifact_id, session.id);
if (!owned(record) || !owned(result) || record.tool !== ref.tool || record.argsSha256 !== ref.args_sha256 || result.kind !== 'tool-result'
|| record.resultArtifactId !== result.id || result.sha256 !== ref.result_sha256) throw new Error('单轮观察的工具或原结果来源变化。');
store.artifactStore.read(result);
}
}
} catch { view.evidence_verified = false; view.error = '单轮观察的原收据或工具结果待核对;不用于交付通过判定。'; }
return view;
}
+97
View File
@@ -0,0 +1,97 @@
import { createHash } from 'node:crypto';
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
const validRange = read => read && typeof read.key === 'string' && /^[a-f0-9]{64}$/.test(read.sha256)
&& Number.isSafeInteger(read.start) && Number.isSafeInteger(read.end) && read.start >= 0 && read.end > read.start;
const merge = ranges => ranges.sort((a, b) => a[0] - b[0]).reduce((result, range) => {
const last = result.at(-1); if (last && range[0] <= last[1]) last[1] = Math.max(last[1], range[1]); else result.push([...range]); return result;
}, []);
const size = ranges => ranges.reduce((sum, [start, end]) => sum + end - start, 0);
export const TURN_PROGRESS_LIMITS = Object.freeze({ sources: 32, ranges: 24, facts: 96, failures: 48, turns: 40, tools: 64 });
// External facts only. Neither message wording nor model reasoning is an input.
// Every result is shadow data, never a stop/permission/budget decision.
export function observeTurn(previous, facts) {
const scope = { projectId: facts.projectId, sessionId: facts.sessionId, taskId: facts.taskId, runId: facts.runId };
if (previous && hash(previous.scope) !== hash(scope)) throw new Error('Turn observation belongs to another Task/Run.');
const state = previous ? structuredClone(previous) : { schemaVersion: 1, mode: 'shadow', scope, reads: [], facts: [], failures: [], turns: [], observations: 0, truncated: false };
let uncertain = false;
const remember = (collection, signature, limit) => {
if (collection.includes(signature)) return false;
if (collection.length >= limit) { state.truncated = true; uncertain = true; return false; }
collection.push(signature); return true;
};
const delta = { read_characters: 0, new_sources: 0, repeated_reads: 0, changed_files: 0, check_results: 0, requirement_evidence: 0,
user_boundaries: 0, new_failures: 0, repeated_failures: 0, other_observations: 0 };
const reasons = [], refs = [];
const tools = facts.tools ?? [];
if (tools.length > TURN_PROGRESS_LIMITS.tools) { state.truncated = true; uncertain = true; }
for (const tool of tools.slice(0, TURN_PROGRESS_LIMITS.tools)) {
refs.push({ id: tool.id, tool: tool.name, args_sha256: tool.argsSha256 ?? null, result_artifact_id: tool.artifactId ?? null, result_sha256: tool.resultSha256 ?? null,
...(tool.sourceEventId ? { source_event_id: tool.sourceEventId, diagnostic_sha256: tool.diagnosticSha256 } : {}) });
if (tool.failure) {
const signature = hash([tool.name, tool.argsSha256, tool.failure.category, tool.failure.signature]);
if (remember(state.failures, signature, TURN_PROGRESS_LIMITS.failures)) { delta.new_failures++; reasons.push('new_failure:' + tool.failure.category); }
else if (!uncertain) { delta.repeated_failures++; reasons.push('repeated_failure:' + tool.failure.category); }
continue;
}
if (validRange(tool.read)) {
const read = tool.read, key = hash([read.key, read.sha256, read.unit]);
let entry = state.reads.find(value => value.key === key);
if (!entry) {
if (state.reads.length >= TURN_PROGRESS_LIMITS.sources) { state.truncated = true; uncertain = true; continue; }
entry = { key, sha256: read.sha256, unit: read.unit, ranges: [] }; state.reads.push(entry); delta.new_sources++;
}
const ranges = merge([...entry.ranges, [read.start, read.end]]), growth = size(ranges) - size(entry.ranges);
if (ranges.length > TURN_PROGRESS_LIMITS.ranges) { state.truncated = true; uncertain = true; continue; }
entry.ranges = ranges; delta.read_characters += growth;
if (!growth) delta.repeated_reads++;
} else if (tool.observationSignature && remember(state.facts, hash(['observation', tool.name, tool.observationSignature]), TURN_PROGRESS_LIMITS.facts)) delta.other_observations++;
}
const count = (rows, kind, field) => {
if ((rows?.length ?? 0) > TURN_PROGRESS_LIMITS.facts) { state.truncated = true; uncertain = true; }
for (const row of (rows ?? []).slice(0, TURN_PROGRESS_LIMITS.facts))
if (remember(state.facts, hash([kind, row]), TURN_PROGRESS_LIMITS.facts)) delta[field]++;
};
count(facts.changes, 'changes', 'changed_files'); count(facts.checks, 'checks', 'check_results');
count(facts.requirements, 'requirements', 'requirement_evidence'); count(facts.userBoundaries, 'user', 'user_boundaries');
if (delta.read_characters) reasons.push('new_returned_file_or_artifact_range');
if (delta.repeated_reads) reasons.push('same_sha_range_already_returned');
for (const field of ['changed_files', 'check_results', 'requirement_evidence', 'user_boundaries', 'other_observations']) if (delta[field]) reasons.push(field);
const waiting = (facts.waiting ?? []).slice(0, 16).map(row => ({ kind: row.kind, id: row.id }));
const growth = delta.read_characters + delta.changed_files + delta.check_results + delta.requirement_evidence + delta.other_observations;
const classification = facts.phase === 'baseline' ? 'baseline' : waiting.length ? 'waiting' : growth ? 'evidence_growth' : delta.new_failures ? 'new_failure_evidence'
: delta.user_boundaries ? 'user_boundary' : uncertain ? 'unknown_bounded' : delta.repeated_failures ? 'repeated_failure_candidate'
: delta.repeated_reads ? 'repeated_read_candidate' : 'no_observed_change';
if (facts.phase === 'baseline') { for (const key of Object.keys(delta)) delta[key] = 0; reasons.length = 0; reasons.push('existing_facts_not_run_progress'); }
const observation = { schemaVersion: 1, mode: 'shadow', taskId: scope.taskId, runId: scope.runId,
stepId: facts.stepId ?? null, stepIndex: facts.stepIndex ?? null, phase: facts.phase ?? 'settled', classification,
delta, reasons: [...new Set(reasons)].slice(0, 16), tools: refs, waiting, truncated: state.truncated,
note: '外显事实观察;不等于业务交付,不改变停止、权限或预算。' };
state.observations++; state.turns.push(observation);
if (state.turns.length > TURN_PROGRESS_LIMITS.turns) { state.turns.shift(); state.truncated = true; }
return { state, observation };
}
export function toolProgressFacts(record, result, artifact, failureCategory = null) {
const value = { id: record.id, name: record.tool, argsSha256: record.argsSha256, artifactId: artifact?.id, resultSha256: artifact?.sha256 };
const status = result.status;
if (record.requiresVerification || ['unknown', 'interrupted', 'unverified'].includes(status)) {
value.failure = { category: 'requires_verification', signature: hash([status, result.code, result.message]) };
} else if (['failed', 'error', 'denied'].includes(status)) {
value.failure = { category: status === 'denied' ? 'permission' : failureCategory ?? 'tool_or_environment', signature: hash([status, result.code, result.message, result.exit_code]) };
} else if (['read_file', 'read_artifact', 'read_browser_result', 'read_research_evidence'].includes(record.tool) && typeof result.content === 'string') {
const start = result.offset ?? 0, end = result.next_offset ?? start + result.content.length;
// Offsets refer to UTF-16 characters within the original tool range. They
// are deliberately not labeled file bytes or cumulative token savings.
if (end - start === result.content.length) value.read = { key: hash([result.path ?? result.artifact_id ?? result.job_id,
result.range_start_line ?? result.start_line ?? null, result.range_end_line ?? result.end_line ?? null, result.section ?? null]),
sha256: result.sha256, start, end, unit: 'utf16_in_original_range' };
} else if (['inspect_project', 'list_files', 'search_files', 'index_project', 'query_code'].includes(record.tool)) {
const { tool_invocation_id, repeated_read_count, reading_hint, ...actual } = result;
// Random invocation IDs and changing timestamps are not observation growth.
delete actual.inspectedAt; delete actual.createdAt; delete actual.durationMs;
value.observationSignature = hash(actual);
}
return value;
}
+11
View File
@@ -10,6 +10,7 @@ import { verifyPythonCheckEvidence } from './python-runtime.mjs';
import { currentBrowserVerification, verifyBrowserJob } from './browser/browser-manager.mjs';
import { TaskPlanManager } from './tasks/task-plan-manager.mjs';
import { RequirementReview } from './tasks/requirement-review.mjs';
import { inspectTurnProgress } from './context/turn-progress-recorder.mjs';
import { FileResults } from './tasks/file-results.mjs';
import { taskContract } from '../shared/contracts/task-control.mjs';
import { modelIdentityLabel } from '../shared/contracts/model-identity.mjs';
@@ -141,6 +142,8 @@ export class DeliveryReporter {
contract, delivery: task.delivery ?? null,
workspaceIdentity: task.workspaceIdentity ?? null, requirementsAcceptance: requirements.status, note: '源码和检查证据不代替业务需求验收。' },
requirements,
turnObservations: [...this.store.core.run.values()].filter(value => value.sessionId === session.id && value.taskId === taskId)
.map(value => ({ runId: value.id, ...inspectTurnProgress(this.store, session, value) })),
fileResults, fileDelivery,
checkPolicy: contract.checks === 'skip' ? 'not_requested' : contract.checks,
gitOutcome: { status: !fileDelivery.newChanges && hasFileScope ? 'no_new_changes' : commits.length ? 'committed' : 'uncommitted',
@@ -212,6 +215,14 @@ export function renderDeliveryMarkdown(report) {
if (report.requirements.unreviewed_sources?.length) lines.push('', '尚未审阅的用户来源:' + report.requirements.unreviewed_sources.join('、'));
if (report.requirements.error) lines.push('', report.requirements.error);
}
if (report.turnObservations?.some(row => row.recorded || row.error)) {
lines.push('', '## 单轮观察(仅记录)', '', '外显事实分类不改变停止、权限或预算;不是自主交付收益证明。');
for (const run of report.turnObservations) if (run.error) lines.push('', escapeCell(run.runId + ':' + (typeof run.error === 'string' ? run.error : '观察未能记录,原执行结果保留。')), '');
lines.push('', '| Run / 轮次 | 观察 | 新读取字符 | 重复读取 | 新失败 / 重复失败 | 原收据核对 |', '| --- | --- | --- | --- | --- | --- |');
for (const run of report.turnObservations) for (const turn of run.turns) lines.push('| ' + [run.runId + ' / ' + (turn.stepIndex ?? turn.phase),
turn.classification, turn.delta.read_characters, turn.delta.repeated_reads, turn.delta.new_failures + ' / ' + turn.delta.repeated_failures,
run.evidence_verified ? '原字节已核对' : run.error].map(escapeCell).join(' | ') + ' |');
}
if (report.taskPlan?.configured) {
lines.push('', '## 执行计划与实际核验', '', '计划:' + (report.taskPlan.plan_id ?? '无法核对'),
'核验:' + (report.taskPlan.verified_steps ?? 0) + '/' + (report.taskPlan.total_steps ?? 0), '',
+19
View File
@@ -41,6 +41,7 @@ import { BrowserManager, publicBrowserPlan } from '../core/browser/browser-manag
import { browserPlanInput } from '../shared/contracts/browser.mjs';
import { TaskPlanManager } from '../core/tasks/task-plan-manager.mjs';
import { RequirementReview } from '../core/tasks/requirement-review.mjs';
import { recordTurnProgress } from '../core/context/turn-progress-recorder.mjs';
import { FileResults } from '../core/tasks/file-results.mjs';
import { fileResultInput, fileResultToolDefinitions } from '../shared/contracts/file-results.mjs';
import { verifiedCheck } from '../core/delivery-report.mjs';
@@ -314,6 +315,7 @@ export class Runtime {
async run(session, config, run) {
const signal = run.controller.signal;
let projectionLogged = false;
let currentStep = null;
try {
// Immediate providers and local tools still need to deliver UI events and
// process stop/deadline input between completed, persisted operations.
@@ -325,10 +327,12 @@ export class Runtime {
if (current.sourceFingerprint === originalTask.stagnation.sourceFingerprint) throw new BudgetExceeded('no_progress', '连续两次运行未增加源码改动、检查结果或新的读取依据。本次未请求模型;请根据原日志修改源码或发送具体调整,避免重复空续接。');
originalTask.stagnation = null;
}
recordTurnProgress(this.store, session, run.record, null, 'baseline');
for (let step = 0; step < config.maxSteps; step++) {
signal.throwIfAborted();
checkBudget(run.record, this.store.core.task.get(run.taskId));
const stepRecord = this.store.beginStep(session, run.record);
currentStep = stepRecord;
const task = this.store.core.task.get(run.taskId);
config.inputImages=this.inputAttachments().images(session,task);
if(config.inputImages.length&&config.mode==='demo')throw new Error('固定演示执行器不会读取图片;请连接并声明支持视觉的模型。');
@@ -546,6 +550,8 @@ export class Runtime {
}
else if (signal.aborted) result = { status: 'interrupted', message: '用户停止了任务,这次调用没有执行。' };
else result = await this.executeTool(session, call, run);
const invocation = [...this.store.core.tool.values()].findLast(row => row.runId === run.id && row.callId === call.id);
if (invocation?.resultArtifactId) (stepRecord.progressToolIds ??= []).push(invocation.id);
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);
@@ -587,6 +593,8 @@ export class Runtime {
this.store.save(session, { type: 'change_set.awaiting_review', detail: { changeSetId: id } });
return;
}
stepRecord.progressSettled = true;
recordTurnProgress(this.store, session, run.record, stepRecord);
if (this.store.core.task.get(run.taskId).readProgress?.pause) throw new BudgetExceeded('no_progress',
'模型连续重复读取工件或核对相同的工程状态,未推进当前任务。实际结果和原任务已保存,请核对后继续。');
}
@@ -626,6 +634,10 @@ export class Runtime {
}
this.store.save(session);
} finally {
if (currentStep && !currentStep.progressSettled) {
currentStep.progressSettled = true;
recordTurnProgress(this.store, session, run.record, currentStep, 'settled', session.lastFailure?.runId === run.id ? session.lastFailure : null);
}
if (run.worker?.engine) await this.engineRunner().finish(session, run);
}
}
@@ -635,14 +647,17 @@ export class Runtime {
?? this.store.event(session, { kind: 'tool', toolCallId: call.id, tool, label: labels[tool] ?? tool, phase: 'queued', startedAt: now() });
this.store.beginInvocation(session, call, run.record, event);
let result;
let progressFailureCategory = 'invalid_input';
try {
const args = JSON.parse(call.function.arguments);
validateToolArgs(tool, args);
progressFailureCategory = 'permission';
if (!taskToolAllowed(this.store.core.task.get(run.taskId), run.record, tool, args)) throw new Error(run.record.purpose === 'diagnostic'
? '本次是只读运行诊断,不执行文件修改、命令或其他副作用操作。原任务目标保持。' : '原任务明确无需测试;这项自动检查没有执行。请直接完成原目标,追加测试需要用户明确要求。');
assertWorkerTool(this.store, session, tool, args);
if (run.worker?.engine) this.engineRunner().assertCurrent(session, run);
event.input = JSON.parse(this.provider.redact(JSON.stringify(args)));
progressFailureCategory = 'tool_or_environment';
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 } : {}) };
@@ -780,6 +795,7 @@ export class Runtime {
...(check.python ? { python: { runtime: check.python.runtime, mode: check.python.mode } } : {}) })),
reason: '执行工程检查计划 ' + plan.id.slice(0, 8) + ';保存测试数量、退出码和日志。' }, run, async () => {
const { promise } = await this.checkRunner().start(session, plan.id, { signal: run.controller.signal, source: 'agent' });
recordTurnProgress(this.store, session, run.record, [...this.store.core.step.values()].findLast(row => row.runId === run.id), 'waiting');
const job = await promise;
return { status: job.status === 'cancelled' ? 'interrupted' : job.status === 'passed' ? 'completed' : job.status,
check_status: job.status, job_id: job.id, plan_id: job.planId, results: job.results, summary: job.summary,
@@ -814,6 +830,8 @@ export class Runtime {
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;
} catch (error) {
const record = this.store.core.tool.get(event.invocationId);
if (record) record.progressFailureCategory = progressFailureCategory;
result = { status: run.controller.signal.aborted ? 'interrupted' : 'error', message: this.provider.redact(error.message ?? String(error)) };
event.phase = result.status === 'interrupted' ? 'interrupted' : 'failed';
event.output = result.message;
@@ -837,6 +855,7 @@ export class Runtime {
session.approvals.push(approval);
event.phase = 'waiting'; session.status = 'awaiting_approval';
this.store.invocationState(session, event, 'waiting');
recordTurnProgress(this.store, session, run.record, [...this.store.core.step.values()].findLast(row => row.runId === run.id), 'waiting');
const decision = await new Promise(resolve => {
const signal = run.controller.signal;
const settle = value => { this.waiters.delete(approval.id); signal.removeEventListener('abort', cancel); resolve(value); };