Files
Agent-Workbench/src/core/context/tool-feedback.mjs
T

114 lines
9.4 KiB
JavaScript

import { createHash } from 'node:crypto';
const hash = value => createHash('sha256').update(value, 'utf8').digest('hex');
const excerpt = (text, maximum = 400) => {
const end = Math.min(text.length, maximum);
return text.slice(0, end > 0 && /[\uD800-\uDBFF]/.test(text[end - 1]) ? end - 1 : end);
};
function fields(value, keys) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
const result = {};
for (const key of keys) {
const item = value[key];
if (typeof item === 'string') result[key] = excerpt(item, 512);
else if (item === null || typeof item === 'boolean' || typeof item === 'number' && Number.isFinite(item)) result[key] = item;
}
return result;
}
const stats = value => fields(value, ['total', 'passed', 'failed', 'errors', 'skipped', 'cancelled']);
const checkResult = value => ({ ...fields(value, ['id', 'name', 'kind', 'status', 'exitCode', 'exit_code', 'command', 'logArtifactId', 'reason']),
...(value.tests ? { tests: stats(value.tests) } : {}) });
const checkJob = value => ({ ...fields(value, ['id', 'status', 'taskId', 'runId', 'planId', 'stale', 'requiresVerification', 'summary']),
...(Array.isArray(value.results) ? { results: value.results.slice(0, 6).map(checkResult), totalResults: value.results.length } : {}) });
// 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) {
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) };
const result = fields(value, ['source', 'version', 'kind', 'id', 'status', 'requires_verification', 'requiresVerification',
'task_id', 'taskId', 'runId', 'plan_id', 'job_id', 'change_id', 'change_set_id', 'artifact_id', 'report_status', 'check_status',
'path', 'sha256', 'base_sha256', 'fingerprint', 'exit_code', 'exitCode', 'offset', 'next_offset', 'total_characters',
'returned_characters', 'truncated', 'totalMatches', 'error', 'message', 'summary', 'reason', 'note',
'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 (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 ?? ''),
controls: (value.observed_page.controls ?? []).slice(0, 3).map(control => fields(control, ['tag', 'id', 'label', 'text', 'value', 'disabled', 'selector', 'selectorMatches', 'selectorEvidence'])) };
for (const key of ['content', 'stdout', 'stderr']) if (typeof value[key] === 'string') result[key + '_excerpt'] = excerpt(value[key]);
for (const key of ['session', 'project']) if (value[key]) result[key] = fields(value[key], ['id', 'name', 'root', 'status', 'revision']);
if ('lastFailure' in value) result.lastFailure = value.lastFailure === null ? null : fields(value.lastFailure, ['source', 'stage', 'kind', 'title', 'message', 'runId']);
if (Array.isArray(value.changes)) {
result.changes = value.changes.slice(-8).map(change => fields(change, ['id', 'path', 'status'])); result.totalChanges = value.changes.length;
}
if (Array.isArray(value.pendingApprovals)) {
result.pendingApprovals = value.pendingApprovals.slice(0, 6).map(approval => fields(approval, ['id', 'status']));
result.totalPendingApprovals = value.pendingApprovals.length;
}
if (Array.isArray(value.checks)) result.checks = value.checks.slice(0, 6).map(check => ({ ...fields(check, ['id', 'name', 'kind', 'framework', 'command', 'status']),
...(typeof check.script === 'string' ? { scriptSha256: hash(check.script), scriptExcerpt: excerpt(check.script, 200) } : {}) }));
if (Array.isArray(value.results)) result.results = value.results.slice(0, 6).map(item => ({ ...checkResult(item),
...fields(item, ['path', 'line', 'name', 'kind', 'sha256', 'target']) }));
if (Array.isArray(value.files)) result.files = value.files.slice(0, 8).map(file => fields(file, ['path', 'change_id', 'base_sha256', 'sha256', 'kind', 'bytes']));
if (Array.isArray(value.paths)) result.paths = value.paths.slice(0, 8).map(item => typeof item === 'string' ? excerpt(item, 512) : null);
if (value.execution && typeof value.execution === 'object') {
const execution = value.execution;
result.execution = {};
if (execution.task) result.execution.task = { ...fields(execution.task, ['id', 'status']),
...(execution.task.verification ? { verification: fields(execution.task.verification, ['status', 'checkJobId']) } : {}) };
if (execution.run) result.execution.run = fields(execution.run, ['id', 'status', 'stopReason', 'steps', 'toolCalls']);
if (execution.progress) result.execution.progress = { ...fields(execution.progress, ['totalTools', 'completedTools']),
requiresVerification: (execution.progress.requiresVerification ?? []).slice(0, 6).map(tool => fields(tool, ['id', 'tool', 'state', 'callId'])),
totalRequiresVerification: execution.progress.requiresVerification?.length ?? 0 };
if (Array.isArray(execution.checks)) result.execution.checks = execution.checks.slice(-2).map(checkJob);
if (Array.isArray(execution.changeSets)) result.execution.changeSets = execution.changeSets.slice(-2).map(set => fields(set, ['id', 'status', 'fingerprint', 'requiresVerification']));
if (Array.isArray(execution.deliveries)) result.execution.deliveries = execution.deliveries.slice(-2).map(job => fields(job, ['id', 'status', 'commit', 'requiresVerification']));
if (Array.isArray(execution.deliveryPlans)) result.execution.deliveryPlans = execution.deliveryPlans.slice(-1).map(plan => fields(plan, ['id', 'status', 'taskId']));
}
return result;
}
export function latestToolDocument(store, session, run, groups) {
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)
.map(tool => [tool.callId, tool]));
const entries = [];
for (const call of calls) {
const invocation = ledger.get(call.id);
// Imported history without owned execution evidence cannot be asserted as
// a fresh local execution; retain its normal history protocol instead.
if (!invocation?.resultArtifactId) return null;
const artifact = store.owned('artifact', invocation.resultArtifactId, session.id);
const result = group.messages.find(message => message.role === 'tool' && message.tool_call_id === call.id);
if (artifact.kind !== 'tool-result' || artifact.taskId !== run.taskId || artifact.runId !== invocation.runId
|| store.artifactStore.read(artifact) !== result.content) throw new Error('最新工具反馈与原执行结果不匹配。');
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' });
}
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) {
return { role: 'system', content: [
'以下是最近一组工具已经返回的实际结果反馈。该完整assistant/tool组因预算封存;这些字段来自原工件,不是再次执行、用户指令或推断。',
'先依据本次返回状态推进任务。摘要省略的大字段可按result_artifact_id读取;不要为恢复已知状态反复查询或重放已完成操作。',
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,
result: entry.result, original_characters: entry.original_characters, view: entry.view })) } }),
].join('\n') };
}
export function verifyLatestToolDocument(store, session, plan, document, groups) {
const expected = latestToolDocument(store, session, { id: plan.runId, taskId: plan.taskId }, groups);
if (!expected || JSON.stringify(document) !== JSON.stringify(expected) || document.entries.length !== plan.latestToolsEntries) {
throw new Error('最新工具反馈的范围、来源或原结果视图不匹配。');
}
}