feat: persist execution state and tool results in SQLite
This commit is contained in:
+49
-16
@@ -6,6 +6,7 @@ import { safePath, listFiles, readLines, searchFiles, proposeFile } from './file
|
||||
import { projectContext, projectMessages } from './provider.mjs';
|
||||
import { now, repairToolPairs } from './store.mjs';
|
||||
import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnostics.mjs';
|
||||
import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs';
|
||||
|
||||
const labels = { inspect_session: '核对工作台运行记录', list_files: '查看项目文件', read_file: '读取文件', search_files: '搜索项目', propose_file: '准备文件改动', run_command: '运行终端命令' };
|
||||
|
||||
@@ -33,7 +34,8 @@ export class Runtime {
|
||||
const controller = new AbortController();
|
||||
const config = structuredClone(this.store.config);
|
||||
if (config.mode !== 'demo') this.provider.validate(config);
|
||||
const run = { controller, id: randomUUID(), project };
|
||||
const record = this.store.beginRun(session, content, resume, config);
|
||||
const run = { controller, id: record.id, taskId: record.taskId, project, record, config };
|
||||
this.active.set(id, run);
|
||||
session.status = 'running'; session.recoveryNotice = null; session.executionMode = config.mode;
|
||||
session.runId = run.id;
|
||||
@@ -44,7 +46,11 @@ export class Runtime {
|
||||
} else this.store.message(session, 'system', '从已保存的执行记录继续,已完成的工具结果保留。');
|
||||
session.failure = null;
|
||||
this.store.save(session);
|
||||
run.promise = this.run(session, config, run).finally(() => this.active.delete(id));
|
||||
const deadline = record.budget.maxDurationMs > 0 ? setTimeout(() => controller.abort(new BudgetExceeded('time_limit', '已到达本次运行的时间预算,执行记录已保存。')), record.budget.maxDurationMs) : null;
|
||||
run.promise = this.run(session, config, run).finally(() => {
|
||||
clearTimeout(deadline); this.active.delete(id);
|
||||
this.store.finishRun(session, record, run.stopReason ?? null);
|
||||
});
|
||||
return session;
|
||||
}
|
||||
resume(id, content) {
|
||||
@@ -60,6 +66,8 @@ export class Runtime {
|
||||
try {
|
||||
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);
|
||||
const projected = projectMessages(session.providerMessages, config.contextLimit);
|
||||
session.estimatedTokens = projected.estimatedTokens;
|
||||
if (projected.projected && !projectionLogged) {
|
||||
@@ -69,11 +77,17 @@ export class Runtime {
|
||||
}
|
||||
const state = session.changes.map(change => ({ path: change.path, status: change.status, id: change.id }));
|
||||
const context = projectContext(run.project) + '\n当前文件提案状态:' + JSON.stringify(state).slice(0, 8000)
|
||||
+ '\n当前任务目标与追加要求(来自用户,完整原文保存在任务记录):\n' + JSON.stringify({
|
||||
goal: this.store.core.task.get(run.taskId).goal,
|
||||
instructions: this.store.core.task.get(run.taskId).instructions.slice(-8),
|
||||
acceptance: this.store.core.task.get(run.taskId).acceptance,
|
||||
}).slice(0, 16000)
|
||||
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value));
|
||||
if (projected.estimatedTokens > config.contextLimit * 2) throw new Error('这次任务上下文仍超出预算,请缩小读取范围或新建会话。');
|
||||
let requestEvent;
|
||||
const response = await this.provider.complete(config, [{ role: 'system', content: context }, ...projected.messages], run.project, signal, progress => {
|
||||
if (!requestEvent) requestEvent = this.store.event(session, { kind: 'model', runId: run.id, source: 'model_connection', label: '请求模型服务', phase: 'running', startedAt: now() });
|
||||
stepRecord.modelAttempts = Math.max(stepRecord.modelAttempts, progress.attempt ?? 0);
|
||||
requestEvent.phase = progress.phase; requestEvent.attempts = progress.attempt;
|
||||
requestEvent.label = progress.phase === 'retrying' ? '正在重试模型连接' : progress.phase === 'completed' ? '模型响应已收到' : progress.phase === 'failed' ? '模型连接失败' : '请求模型服务';
|
||||
requestEvent.output = progress.phase === 'retrying' ? '第 ' + progress.attempt + ' 次请求失败,将自动重试(最多 ' + progress.maxAttempts + ' 次)。'
|
||||
@@ -90,10 +104,17 @@ export class Runtime {
|
||||
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);
|
||||
session.usage = response.usage;
|
||||
this.store.recordResponse(session, run.record, response.usage, projected.estimatedTokens + Math.ceil(JSON.stringify(message).length / 4));
|
||||
for (const call of calls) {
|
||||
const event = { id: randomUUID(), createdAt: now(), startedAt: now(), kind: 'tool', phase: 'queued',
|
||||
toolCallId: call.id, tool: call.function.name, label: labels[call.function.name] ?? call.function.name, taskId: run.taskId, runId: run.id };
|
||||
session.events.push(event); this.store.registerInvocation(session, call, run.record, event);
|
||||
}
|
||||
if (message.content) this.store.message(session, 'assistant', message.content);
|
||||
else this.store.save(session);
|
||||
checkBudget(run.record, this.store.core.task.get(run.taskId));
|
||||
if (!calls.length) {
|
||||
this.store.finishStep(session, stepRecord);
|
||||
session.status = session.changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review' : 'completed';
|
||||
this.store.save(session); return;
|
||||
}
|
||||
@@ -103,20 +124,26 @@ export class Runtime {
|
||||
else result = await this.executeTool(session, call, run);
|
||||
session.providerMessages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
|
||||
this.store.save(session);
|
||||
signal.throwIfAborted();
|
||||
}
|
||||
this.store.finishStep(session, stepRecord);
|
||||
}
|
||||
session.status = 'paused';
|
||||
run.stopReason = 'step_limit';
|
||||
this.store.message(session, 'assistant', '已到达本次工具步数上限。执行记录已保存,可以查看结果后继续。');
|
||||
this.store.save(session);
|
||||
} catch (error) {
|
||||
const repaired = repairToolPairs(session.providerMessages);
|
||||
this.store.interruptPending(session, run.record);
|
||||
const repaired = repairToolPairs(session.providerMessages, callId => this.store.savedToolResult(session.id, callId));
|
||||
if (repaired.changed) session.providerMessages = repaired.messages;
|
||||
if (signal.aborted) {
|
||||
const budget = error instanceof BudgetExceeded ? error : signal.reason instanceof BudgetExceeded ? signal.reason : null;
|
||||
if (signal.aborted || budget) {
|
||||
run.stopReason = budget?.reason ?? 'cancelled';
|
||||
for (const event of session.events.filter(item => item.kind === 'model' && item.runId === run.id && ['running', 'retrying'].includes(item.phase))) {
|
||||
event.phase = 'interrupted'; event.finishedAt = now(); event.output = '模型请求已停止,已完成的工具结果保留。';
|
||||
}
|
||||
session.status = 'paused';
|
||||
this.store.message(session, 'system', '任务已停止,执行记录已保存。');
|
||||
this.store.message(session, 'system', budget?.message ?? '任务已停止,执行记录已保存。');
|
||||
} else {
|
||||
session.status = 'failed';
|
||||
const diagnostic = error.diagnostic ?? { source: 'workbench', stage: 'agent_loop', kind: 'runtime',
|
||||
@@ -132,14 +159,17 @@ export class Runtime {
|
||||
}
|
||||
async executeTool(session, call, run) {
|
||||
const tool = call.function.name;
|
||||
const event = this.store.event(session, { kind: 'tool', toolCallId: call.id, tool, label: labels[tool] ?? tool, phase: 'running', startedAt: now() });
|
||||
const event = session.events.find(value => value.toolCallId === call.id && value.runId === run.id)
|
||||
?? 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;
|
||||
try {
|
||||
const args = JSON.parse(call.function.arguments);
|
||||
validateToolArgs(tool, args);
|
||||
event.input = args;
|
||||
this.store.save(session);
|
||||
if (tool === 'inspect_session') result = sessionSnapshot(session, run.project, this.store.config, value => this.provider.redact(value));
|
||||
event.input = JSON.parse(this.provider.redact(JSON.stringify(args)));
|
||||
if (tool !== 'run_command') 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) };
|
||||
else if (tool === 'list_files') result = listFiles(run.project, args.path, args.depth ?? 3, 500);
|
||||
else if (tool === 'read_file') result = readLines(run.project, args);
|
||||
else if (tool === 'search_files') result = searchFiles(run.project, args);
|
||||
@@ -157,17 +187,19 @@ export class Runtime {
|
||||
}
|
||||
event.finishedAt = now();
|
||||
event.durationMs = Date.parse(event.finishedAt) - Date.parse(event.startedAt);
|
||||
this.store.save(session);
|
||||
result = JSON.parse(this.provider.redact(JSON.stringify(result)));
|
||||
this.store.finishInvocation(session, event, result);
|
||||
return result;
|
||||
}
|
||||
async requestCommand(session, event, args, run) {
|
||||
const command = String(args.command ?? '').trim();
|
||||
if (!command || command.length > 6000) throw new Error('终端命令不能为空,也不能超过 6,000 字符。');
|
||||
const approval = { id: randomUUID(), toolCallId: event.toolCallId, eventId: event.id, command,
|
||||
const approval = { id: randomUUID(), toolCallId: event.toolCallId, eventId: event.id, invocationId: event.invocationId,
|
||||
taskId: run.taskId, runId: run.id, projectId: session.projectId, command,
|
||||
reason: String(args.reason ?? '').slice(0, 800), cwd: run.project.root, shell: executionEnvironment().shell, status: 'pending', createdAt: now() };
|
||||
session.approvals.push(approval);
|
||||
event.phase = 'waiting'; session.status = 'awaiting_approval';
|
||||
this.store.save(session);
|
||||
this.store.invocationState(session, event, '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); };
|
||||
@@ -176,11 +208,11 @@ export class Runtime {
|
||||
signal.addEventListener('abort', cancel, { once: true });
|
||||
if (signal.aborted) cancel();
|
||||
});
|
||||
if (!decision) return { status: run.controller.signal.aborted ? 'interrupted' : 'denied', message: '命令未执行。' };
|
||||
if (!decision) { if (!run.controller.signal.aborted) session.status = 'running'; return { status: run.controller.signal.aborted ? 'interrupted' : 'denied', message: '命令未执行。', requires_verification: false }; }
|
||||
run.controller.signal.throwIfAborted();
|
||||
const cwd = safePath(run.project);
|
||||
event.phase = 'running'; event.executedAt = now(); session.status = 'running';
|
||||
this.store.save(session);
|
||||
this.store.invocationState(session, event, 'running');
|
||||
return this.executeCommand(command, cwd, run.controller.signal, output => {
|
||||
event.output = output; this.store.save(session);
|
||||
});
|
||||
@@ -189,7 +221,8 @@ export class Runtime {
|
||||
const session = this.store.session(sessionId);
|
||||
const approval = session.approvals.find(item => item.id === approvalId);
|
||||
const waiter = this.waiters.get(approvalId);
|
||||
if (!approval || approval.status !== 'pending' || !waiter || waiter.sessionId !== sessionId || waiter.runId !== session.runId) throw Object.assign(new Error('确认请求已过期;需要重新请求命令。'), { status: 409 });
|
||||
if (!approval || approval.status !== 'pending' || !waiter || waiter.sessionId !== sessionId || waiter.runId !== session.runId
|
||||
|| approval.runId !== session.runId || approval.taskId !== session.taskId || approval.projectId !== session.projectId) throw Object.assign(new Error('确认请求已过期;需要重新请求命令。'), { status: 409 });
|
||||
approval.status = allow ? 'approved' : 'denied'; approval.decidedAt = now();
|
||||
this.store.save(session); waiter.settle(!!allow);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user