feat: persist execution state and tool results in SQLite
This commit is contained in:
+338
-31
@@ -1,8 +1,12 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
import { lastSessionFailure } from './diagnostics.mjs';
|
||||
import { StateDatabase, runtimeOwnerAlive } from '../core/storage/state-database.mjs';
|
||||
import { ArtifactStore } from '../core/storage/artifact-store.mjs';
|
||||
import { collectLegacy, cleanConfig } from '../core/storage/legacy-import.mjs';
|
||||
import { ACTIVE_STATES, CORE_KINDS, createTask, createRun, ownedRecord, emptyUsage, accumulateUsage, accountedTokens, isId } from '../shared/contracts/execution.mjs';
|
||||
|
||||
export const now = () => new Date().toISOString();
|
||||
|
||||
@@ -29,9 +33,9 @@ export function readJson(file, fallback) {
|
||||
return structuredClone(fallback);
|
||||
}
|
||||
|
||||
export function repairToolPairs(messages) {
|
||||
export function repairToolPairs(messages, lookupResult = null) {
|
||||
const result = [];
|
||||
let interrupted = 0, dropped = 0;
|
||||
let interrupted = 0, dropped = 0, recovered = 0;
|
||||
for (let index = 0; index < messages.length; index++) {
|
||||
const message = messages[index];
|
||||
if (message.role === 'tool') { dropped++; continue; }
|
||||
@@ -44,8 +48,21 @@ export function repairToolPairs(messages) {
|
||||
else dropped++;
|
||||
}
|
||||
for (const call of message.tool_calls) {
|
||||
if (received.has(call.id)) result.push(received.get(call.id));
|
||||
if (received.has(call.id)) {
|
||||
const existing = received.get(call.id);
|
||||
let placeholder = false;
|
||||
try { const value = JSON.parse(existing.content); placeholder = value.status === 'interrupted' && value.requires_verification === true; } catch {}
|
||||
const saved = placeholder ? lookupResult?.(call.id) : null;
|
||||
if (saved && !['unknown', 'interrupted'].includes(saved.status)) { recovered++; result.push({ ...existing, content: JSON.stringify(saved) }); }
|
||||
else result.push(existing);
|
||||
}
|
||||
else {
|
||||
const saved = lookupResult?.(call.id);
|
||||
if (saved) {
|
||||
recovered++;
|
||||
result.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(saved) });
|
||||
continue;
|
||||
}
|
||||
interrupted++;
|
||||
result.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify({
|
||||
status: 'interrupted', requires_verification: true,
|
||||
@@ -55,33 +72,118 @@ export function repairToolPairs(messages) {
|
||||
}
|
||||
dropped += [...received.keys()].filter(id => !message.tool_calls.some(call => call.id === id)).length;
|
||||
}
|
||||
return { messages: result, interrupted, changed: interrupted > 0 || dropped > 0 };
|
||||
return { messages: result, interrupted, recovered, changed: interrupted > 0 || dropped > 0 || recovered > 0 };
|
||||
}
|
||||
|
||||
export class Store extends EventEmitter {
|
||||
constructor(directory) {
|
||||
constructor(directory, options = {}) {
|
||||
super();
|
||||
this.directory = path.resolve(directory);
|
||||
this.sessions = new Map();
|
||||
fs.mkdirSync(path.join(this.directory, 'sessions'), { recursive: true });
|
||||
this.config = readJson(path.join(this.directory, 'config.json'), {
|
||||
mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '',
|
||||
contextLimit: 16000, maxSteps: 12, maxOutputTokens: 2048,
|
||||
});
|
||||
delete this.config.apiKey;
|
||||
this.projects = readJson(path.join(this.directory, 'projects.json'), []);
|
||||
for (const file of fs.readdirSync(path.join(this.directory, 'sessions'))) {
|
||||
if (!/^[a-f0-9-]+\.json$/.test(file)) continue;
|
||||
const session = readJson(path.join(this.directory, 'sessions', file), null);
|
||||
if (!session?.id || !session.projectId) continue;
|
||||
fs.mkdirSync(this.directory, { recursive: true });
|
||||
try { this.ensureStorage(options); this.recover(); }
|
||||
catch (error) { this.storage?.close(); throw error; }
|
||||
}
|
||||
|
||||
ensureStorage(options = {}) {
|
||||
if (this.storage?.database) return;
|
||||
this.core = Object.fromEntries(CORE_KINDS.map(kind => [kind, new Map()]));
|
||||
this.persistedSessions = new Map();
|
||||
this.artifactStore = new ArtifactStore(this.directory);
|
||||
this.storage = new StateDatabase(this.directory, options);
|
||||
if (runtimeOwnerAlive(this.storage.meta('runtimeOwner'))) throw new Error('另一个执行宿主正在使用这个数据目录。请使用独立数据目录。');
|
||||
if (!this.storage.initialized) {
|
||||
const existing = this.config && this.projects && this.sessions?.size ? { config: this.config, projects: this.projects, sessions: this.sessions } : null;
|
||||
const imported = collectLegacy(this.directory, existing);
|
||||
this.config = imported.config; this.projects = imported.projects;
|
||||
this.sessions = new Map(imported.sessions.map(session => [session.id, session]));
|
||||
for (const session of imported.sessions) this.importExecution(session);
|
||||
const records = imported.sessions.flatMap(session => this.recordsFor(session));
|
||||
this.storage.initialize({ ...imported, records });
|
||||
}
|
||||
const loaded = this.storage.load();
|
||||
this.config = cleanConfig(loaded.config); this.projects = loaded.projects;
|
||||
this.sessions ??= new Map();
|
||||
for (const session of loaded.sessions) {
|
||||
const current = this.sessions.get(session.id);
|
||||
if (current) { for (const key of Object.keys(current)) delete current[key]; Object.assign(current, session); }
|
||||
else this.sessions.set(session.id, session);
|
||||
}
|
||||
for (const record of loaded.records) this.core[record.kind]?.set(record.value.id, record.value);
|
||||
for (const session of this.sessions.values()) this.persistedSessions.set(session.id, structuredClone(session));
|
||||
}
|
||||
|
||||
importExecution(session) {
|
||||
if (!session.messages.length && !session.providerMessages.length && !session.changes.length) return;
|
||||
const goal = session.messages.find(message => message.role === 'user')?.content ?? session.title;
|
||||
const task = createTask(session, goal, this.config); task.origin = 'legacy-import'; task.status = session.status;
|
||||
task.createdAt = session.createdAt; task.updatedAt = session.updatedAt;
|
||||
this.core.task.set(task.id, task); session.taskId = task.id;
|
||||
const run = createRun(session, task, this.config);
|
||||
if (isId(session.runId)) run.id = session.runId;
|
||||
run.origin = 'legacy-import'; run.status = session.status;
|
||||
run.model = { mode: session.executionMode ?? null, model: null, baseUrl: null, configRevision: null, verified: false };
|
||||
run.startedAt = session.createdAt; run.finishedAt = ACTIVE_STATES.has(session.status) ? null : session.updatedAt;
|
||||
this.core.run.set(run.id, run); session.runId = run.id; task.activeRunId = run.id;
|
||||
const results = new Map(session.providerMessages.filter(message => message.role === 'tool').map(message => [message.tool_call_id, message.content]));
|
||||
for (const message of session.providerMessages) for (const call of message.tool_calls ?? []) {
|
||||
let result; try { if (results.has(call.id)) result = JSON.parse(results.get(call.id)); } catch {}
|
||||
const event = session.events.find(item => item.toolCallId === call.id);
|
||||
const invocation = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
|
||||
callId: call.id, tool: call.function?.name ?? 'unknown', eventId: event?.id ?? null, stepId: null,
|
||||
state: result ? ['error', 'failed'].includes(result.status) ? 'failed' : ['denied', 'interrupted', 'unknown'].includes(result.status) ? result.status : 'completed'
|
||||
: event?.executedAt ? 'running' : 'queued', startedAt: event?.startedAt ?? session.createdAt, finishedAt: event?.finishedAt ?? null,
|
||||
result: result ?? null, resultArtifactId: null, requiresVerification: !result && !!event?.executedAt, origin: 'legacy-import' };
|
||||
this.core.tool.set(invocation.id, invocation);
|
||||
}
|
||||
}
|
||||
|
||||
recordsFor(session) {
|
||||
return CORE_KINDS.flatMap(kind => [...this.core[kind].values()].filter(value => value.sessionId === session.id).map(value => {
|
||||
const record = ownedRecord(kind, value, session);
|
||||
if (record.taskId && kind !== 'task') {
|
||||
const task = this.core.task.get(record.taskId);
|
||||
if (!task || task.sessionId !== session.id || task.projectId !== session.projectId) throw new Error('记录不属于这个任务。');
|
||||
}
|
||||
if (record.runId && kind !== 'run') {
|
||||
const run = this.core.run.get(record.runId);
|
||||
if (!run || run.taskId !== record.taskId || run.sessionId !== session.id) throw new Error('记录不属于这个运行。');
|
||||
}
|
||||
return record;
|
||||
}));
|
||||
}
|
||||
|
||||
recover() {
|
||||
for (const session of this.sessions.values()) {
|
||||
let changed = false;
|
||||
if (['running', 'awaiting_approval', 'stopping'].includes(session.status)) {
|
||||
if (ACTIVE_STATES.has(session.status)) {
|
||||
session.status = 'paused';
|
||||
session.recoveryNotice = '上次任务被中断。继续前请核对执行记录与文件状态。';
|
||||
changed = true;
|
||||
}
|
||||
for (const invocation of this.core.tool.values()) {
|
||||
if (invocation.sessionId !== session.id || !['queued', 'validating', 'waiting', 'running'].includes(invocation.state)) continue;
|
||||
invocation.requiresVerification = invocation.state === 'running';
|
||||
invocation.state = invocation.requiresVerification ? 'unknown' : 'interrupted'; invocation.finishedAt = now();
|
||||
invocation.result = { status: invocation.state, invocation_id: invocation.id, requires_verification: invocation.requiresVerification,
|
||||
message: invocation.requiresVerification ? '执行阶段没有持久完成结果,实际副作用需要核对;不会自动重放。' : '调用未完成,恢复不会自动执行。' };
|
||||
changed = true;
|
||||
}
|
||||
for (const run of this.core.run.values()) if (run.sessionId === session.id && ACTIVE_STATES.has(run.status)) {
|
||||
run.status = 'paused'; run.finishedAt = now(); run.stopReason = 'restart'; changed = true;
|
||||
}
|
||||
for (const step of this.core.step.values()) if (step.sessionId === session.id && ['running', 'waiting'].includes(step.status)) {
|
||||
step.status = 'interrupted'; step.finishedAt = now(); changed = true;
|
||||
}
|
||||
for (const job of this.core.check_job.values()) if (job.sessionId === session.id && ['running', 'waiting'].includes(job.status)) {
|
||||
job.status = 'unknown'; job.finishedAt = now(); job.requiresVerification = true; changed = true;
|
||||
}
|
||||
for (const event of session.events ?? []) {
|
||||
if (['running', 'waiting', 'retrying'].includes(event.phase)) {
|
||||
const invocation = [...this.core.tool.values()].find(item => item.sessionId === session.id && item.callId === event.toolCallId);
|
||||
if (invocation && ['completed', 'denied', 'failed'].includes(invocation.state)) {
|
||||
event.phase = invocation.state; event.finishedAt = invocation.finishedAt; changed = true; continue;
|
||||
}
|
||||
event.phase = 'interrupted';
|
||||
event.finishedAt = now();
|
||||
event.output = event.kind === 'model' ? '上次模型请求已中断,可以从已保存记录继续。' : event.executedAt
|
||||
@@ -96,31 +198,64 @@ export class Store extends EventEmitter {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
const repaired = repairToolPairs(session.providerMessages ?? []);
|
||||
const repaired = repairToolPairs(session.providerMessages ?? [], callId => this.savedToolResult(session.id, callId));
|
||||
if (repaired.changed) {
|
||||
session.providerMessages = repaired.messages;
|
||||
session.recoveryNotice = repaired.interrupted
|
||||
? '已为 ' + repaired.interrupted + ' 个未完成工具调用记录中断结果。不会自动重放命令。'
|
||||
: '已整理会话中的工具结果配对。请核对执行记录后继续。';
|
||||
: repaired.recovered ? '已从持久工具账本恢复 ' + repaired.recovered + ' 项实际结果。不会重新执行已完成工具。' : '已整理会话中的工具结果配对。请核对执行记录后继续。';
|
||||
changed = true;
|
||||
}
|
||||
this.sessions.set(session.id, session);
|
||||
if (changed) this.save(session);
|
||||
for (const run of this.core.run.values()) if (run.sessionId === session.id) {
|
||||
const tools = [...this.core.tool.values()].filter(value => value.runId === run.id);
|
||||
const checkpoint = { ...run.checkpoint,
|
||||
pendingToolIds: tools.filter(value => ['queued', 'validating', 'waiting', 'running'].includes(value.state)).map(value => value.id),
|
||||
completedToolIds: tools.filter(value => !value.requiresVerification && ['completed', 'failed', 'denied', 'interrupted'].includes(value.state)).map(value => value.id),
|
||||
requiresVerification: tools.filter(value => value.requiresVerification).map(value => value.id) };
|
||||
if (JSON.stringify(checkpoint) !== JSON.stringify(run.checkpoint)) { run.checkpoint = checkpoint; changed = true; }
|
||||
}
|
||||
if (changed) this.save(session, { type: 'session.recovered' });
|
||||
}
|
||||
}
|
||||
|
||||
save(session) {
|
||||
save(session, { type = 'session.updated', detail = {} } = {}) {
|
||||
if (!this.storage?.database) throw new Error('任务存储已关闭。');
|
||||
const before = this.persistedSessions.get(session.id);
|
||||
session.revision = (session.revision ?? 0) + 1;
|
||||
session.updatedAt = now();
|
||||
atomicJson(path.join(this.directory, 'sessions', session.id + '.json'), session);
|
||||
this.emit('update', this.publicSession(session));
|
||||
const task = this.core.task.get(session.taskId), run = this.core.run.get(session.runId);
|
||||
if (task) { task.status = session.status; task.updatedAt = session.updatedAt; }
|
||||
if (run && !run.finishedAt) run.status = session.status;
|
||||
let committed;
|
||||
try { committed = this.storage.save(session, this.recordsFor(session), type, { status: session.status, ...detail }); }
|
||||
catch (error) {
|
||||
if (before) { for (const key of Object.keys(session)) delete session[key]; Object.assign(session, structuredClone(before)); }
|
||||
else this.sessions.delete(session.id);
|
||||
const loaded = this.storage.load();
|
||||
for (const kind of CORE_KINDS) {
|
||||
const persisted = loaded.records.filter(record => record.kind === kind);
|
||||
const ids = new Set(persisted.map(record => record.value.id));
|
||||
for (const id of this.core[kind].keys()) if (!ids.has(id)) this.core[kind].delete(id);
|
||||
for (const { value } of persisted) {
|
||||
const current = this.core[kind].get(value.id);
|
||||
if (current) { for (const key of Object.keys(current)) delete current[key]; Object.assign(current, value); }
|
||||
else this.core[kind].set(value.id, value);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
this.persistedSessions.set(session.id, structuredClone(session));
|
||||
try { if (this.listenerCount('update')) { this.emit('update', this.publicSession(session)); this.storage.published(committed.seq); } }
|
||||
catch { this.publicationNotice = '状态已保存,通知尚未发布;客户端可按事件游标补发。'; }
|
||||
return session;
|
||||
}
|
||||
|
||||
saveConfig(config) {
|
||||
this.config = { ...this.config, ...config };
|
||||
delete this.config.apiKey;
|
||||
atomicJson(path.join(this.directory, 'config.json'), this.config);
|
||||
const next = cleanConfig({ ...this.config, ...config, configRevision: (this.config.configRevision ?? 0) + 1 });
|
||||
this.storage.transaction(() => this.storage.setMeta('config', next));
|
||||
this.config = next;
|
||||
// A compatibility export for old launchers; SQLite is authoritative after migration.
|
||||
try { atomicJson(path.join(this.directory, 'config.json'), this.config); } catch { this.publicationNotice = '配置已保存,兼容JSON导出未更新。'; }
|
||||
return this.config;
|
||||
}
|
||||
|
||||
@@ -131,8 +266,9 @@ export class Store extends EventEmitter {
|
||||
const existing = this.projects.find(project => (process.platform === 'win32' ? project.root.toLowerCase() : project.root) === key);
|
||||
if (existing) return existing;
|
||||
const project = { id: randomUUID(), root: resolved, name: path.basename(resolved), addedAt: now() };
|
||||
this.projects.unshift(project);
|
||||
atomicJson(path.join(this.directory, 'projects.json'), this.projects);
|
||||
const next = [project, ...this.projects];
|
||||
this.storage.transaction(() => this.storage.writeProjects(next));
|
||||
this.projects = next;
|
||||
return project;
|
||||
}
|
||||
|
||||
@@ -161,8 +297,179 @@ export class Store extends EventEmitter {
|
||||
return session;
|
||||
}
|
||||
|
||||
beginRun(session, content, resume, config) {
|
||||
let task = this.core.task.get(session.taskId);
|
||||
const previousRunId = session.runId ?? null;
|
||||
if (!task || !resume && ['completed', 'idle'].includes(task.status)) {
|
||||
const previous = task?.id ?? null;
|
||||
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 (!resume && content) task.instructions.push({ id: randomUUID(), content, createdAt: now() });
|
||||
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';
|
||||
this.save(session, { type: 'run.started', detail: { resumeOf: run.resumeOf } });
|
||||
return run;
|
||||
}
|
||||
|
||||
beginStep(session, run) {
|
||||
const step = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: run.taskId, runId: run.id,
|
||||
index: run.steps + 1, status: 'running', startedAt: now(), finishedAt: null, modelAttempts: 0 };
|
||||
run.steps++; run.checkpoint.stepId = step.id; this.core.step.set(step.id, step);
|
||||
this.save(session, { type: 'step.started', detail: { stepId: step.id, index: step.index } });
|
||||
return step;
|
||||
}
|
||||
|
||||
finishStep(session, step, status = 'completed') {
|
||||
step.status = status; step.finishedAt = now();
|
||||
this.save(session, { type: 'step.finished', detail: { stepId: step.id, status } });
|
||||
}
|
||||
|
||||
recordResponse(session, run, usage, estimate) {
|
||||
run.usage = accumulateUsage(run.usage, usage, estimate);
|
||||
const task = this.core.task.get(run.taskId);
|
||||
task.usage = accumulateUsage(task.usage, usage, estimate);
|
||||
session.usage = usage;
|
||||
}
|
||||
|
||||
finishRun(session, run, stopReason = null) {
|
||||
run.status = session.status; run.finishedAt = now(); run.stopReason = stopReason;
|
||||
const step = this.core.step.get(run.checkpoint.stepId);
|
||||
if (step && ['running', 'waiting'].includes(step.status)) { step.status = session.status === 'completed' || session.status === 'needs_review' ? 'completed' : 'interrupted'; step.finishedAt = now(); }
|
||||
this.save(session, { type: 'run.finished', detail: { stopReason } });
|
||||
}
|
||||
|
||||
registerInvocation(session, call, run, event) {
|
||||
const record = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: run.taskId, runId: run.id,
|
||||
stepId: run.checkpoint.stepId, callId: call.id, eventId: event.id, tool: call.function.name,
|
||||
argsSha256: createHash('sha256').update(String(call.function.arguments)).digest('hex'),
|
||||
state: 'queued', startedAt: now(), finishedAt: null, result: null, resultArtifactId: null, requiresVerification: false, origin: 'workbench' };
|
||||
event.invocationId = record.id; event.taskId = run.taskId; event.runId = run.id;
|
||||
this.core.tool.set(record.id, record); run.toolCalls++; run.checkpoint.pendingToolIds.push(record.id);
|
||||
return record;
|
||||
}
|
||||
|
||||
beginInvocation(session, call, run, event) {
|
||||
const record = [...this.core.tool.values()].find(value => value.runId === run.id && value.callId === call.id) ?? this.registerInvocation(session, call, run, event);
|
||||
const actualHash = createHash('sha256').update(String(call.function.arguments)).digest('hex');
|
||||
if (actualHash !== record.argsSha256 || record.state !== 'queued') throw new Error('工具输入已改变或这个调用已进入执行,不能重复执行。');
|
||||
event.invocationId = record.id; event.phase = 'running'; record.state = 'validating';
|
||||
this.save(session, { type: 'tool.validating', detail: { invocationId: record.id } });
|
||||
return record;
|
||||
}
|
||||
|
||||
interruptPending(session, run) {
|
||||
for (const record of this.core.tool.values()) {
|
||||
if (record.runId !== run.id || !['queued', 'validating', 'waiting', 'running'].includes(record.state)) continue;
|
||||
record.requiresVerification = record.state === 'running';
|
||||
record.state = record.requiresVerification ? 'unknown' : 'interrupted'; record.finishedAt = now();
|
||||
record.result = { status: record.state, invocation_id: record.id, requires_verification: record.requiresVerification,
|
||||
message: record.requiresVerification ? '执行进入后没有记录完成结果,需要核对实际状态。' : '任务中断,这次调用未执行。' };
|
||||
const event = session.events.find(value => value.id === record.eventId);
|
||||
if (event) { event.phase = 'interrupted'; event.finishedAt = record.finishedAt; event.output = record.result.message; }
|
||||
}
|
||||
run.checkpoint.pendingToolIds = [];
|
||||
run.checkpoint.requiresVerification = [...this.core.tool.values()].filter(value => value.runId === run.id && value.requiresVerification).map(value => value.id);
|
||||
}
|
||||
|
||||
invocationState(session, event, state) {
|
||||
const record = this.core.tool.get(event.invocationId);
|
||||
if (!record) throw new Error('工具执行账本不存在。');
|
||||
record.state = state;
|
||||
if (state === 'running') record.enteredExecutionAt = now();
|
||||
this.save(session, { type: 'tool.' + state, detail: { invocationId: record.id } });
|
||||
}
|
||||
|
||||
finishInvocation(session, event, result) {
|
||||
const record = this.core.tool.get(event.invocationId);
|
||||
if (!record) throw new Error('工具执行账本不存在。');
|
||||
const run = this.core.run.get(record.runId);
|
||||
const artifact = this.artifactStore.write(session, run, result);
|
||||
this.core.artifact.set(artifact.id, artifact);
|
||||
record.state = ['error', 'failed'].includes(result.status) ? 'failed' : ['denied', 'interrupted', 'unknown'].includes(result.status) ? result.status : 'completed';
|
||||
record.finishedAt = now(); record.requiresVerification = result.requires_verification === true;
|
||||
record.resultArtifactId = artifact.id;
|
||||
record.result = Buffer.byteLength(JSON.stringify(result), 'utf8') <= 8000 ? structuredClone(result) : null;
|
||||
event.artifactId = artifact.id;
|
||||
run.checkpoint.pendingToolIds = run.checkpoint.pendingToolIds.filter(id => id !== record.id);
|
||||
if (record.requiresVerification) run.checkpoint.requiresVerification.push(record.id);
|
||||
else run.checkpoint.completedToolIds.push(record.id);
|
||||
this.save(session, { type: 'tool.result', detail: { invocationId: record.id, state: record.state, artifactId: artifact.id } });
|
||||
return artifact;
|
||||
}
|
||||
|
||||
savedToolResult(sessionId, callId) {
|
||||
const record = [...this.core.tool.values()].find(value => value.sessionId === sessionId && value.callId === callId);
|
||||
if (!record || !['completed', 'failed', 'denied', 'interrupted', 'unknown'].includes(record.state)) return null;
|
||||
if (record.resultArtifactId) {
|
||||
try { return JSON.parse(this.artifactStore.read(this.core.artifact.get(record.resultArtifactId))); }
|
||||
catch {
|
||||
record.state = 'unknown'; record.requiresVerification = true;
|
||||
record.result = { status: 'unknown', requires_verification: true, invocation_id: record.id, message: '工具结果工件缺失或校验失败,实际结果需要核对。' };
|
||||
}
|
||||
}
|
||||
return record.result;
|
||||
}
|
||||
|
||||
putRecord(kind, session, value, type) {
|
||||
ownedRecord(kind, value, session); this.core[kind].set(value.id, value);
|
||||
this.save(session, { type, detail: { recordId: value.id } }); return value;
|
||||
}
|
||||
|
||||
owned(kind, id, sessionId) {
|
||||
const record = this.core[kind]?.get(id);
|
||||
if (!record || record.sessionId !== sessionId || record.projectId !== this.session(sessionId).projectId) throw Object.assign(new Error('执行记录不属于当前会话。'), { status: 404 });
|
||||
return record;
|
||||
}
|
||||
|
||||
executionSnapshot(session) {
|
||||
const task = this.core.task.get(session.taskId), run = this.core.run.get(session.runId);
|
||||
const tools = [...this.core.tool.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id);
|
||||
const artifacts = [...this.core.artifact.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-30);
|
||||
const jobs = [...this.core.check_job.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-10);
|
||||
return {
|
||||
schemaVersion: 1, task: task ?? null, run: run ?? null,
|
||||
runs: [...this.core.run.values()].filter(value => value.sessionId === session.id).slice(-20).map(value => ({ id: value.id, taskId: value.taskId,
|
||||
status: value.status, startedAt: value.startedAt, finishedAt: value.finishedAt, steps: value.steps, toolCalls: value.toolCalls, usage: value.usage, stopReason: value.stopReason })),
|
||||
progress: { totalTools: tools.length, completedTools: tools.filter(value => value.state === 'completed').length,
|
||||
requiresVerification: tools.filter(value => value.requiresVerification).map(value => ({ id: value.id, tool: value.tool, callId: value.callId, state: value.state })) },
|
||||
artifacts, checks: jobs, accountedTaskTokens: accountedTokens(task?.usage),
|
||||
};
|
||||
}
|
||||
|
||||
get eventCursor() { return this.storage.cursor; }
|
||||
eventsAfter(cursor, options) { return this.storage.eventsAfter(cursor, options); }
|
||||
storageInfo() {
|
||||
return { engine: 'sqlite', schemaVersion: 1, eventCursor: this.eventCursor, pendingPublications: this.storage.pendingPublications(),
|
||||
migratedFromJson: !!this.storage.meta('migration'), recovery: 'verify-unknown-results', compatibilityExport: 'explicit-json' };
|
||||
}
|
||||
|
||||
claimRuntime() {
|
||||
if (runtimeOwnerAlive(this.storage.meta('runtimeOwner'))) throw new Error('这个数据目录已被另一个执行宿主使用。');
|
||||
this.ownerId ??= randomUUID();
|
||||
this.storage.transaction(() => this.storage.setMeta('runtimeOwner', { pid: process.pid, id: this.ownerId, startedAt: now() }));
|
||||
}
|
||||
|
||||
exportLegacyData(directory) {
|
||||
const target = path.resolve(directory);
|
||||
if (fs.existsSync(target) && fs.readdirSync(target).length) throw new Error('回退导出需要一个新的空目录。');
|
||||
fs.mkdirSync(path.join(target, 'sessions'), { recursive: true });
|
||||
atomicJson(path.join(target, 'config.json'), cleanConfig(this.config));
|
||||
atomicJson(path.join(target, 'projects.json'), this.projects);
|
||||
for (const session of this.sessions.values()) atomicJson(path.join(target, 'sessions', session.id + '.json'), session);
|
||||
return { directory: target, sessions: this.sessions.size, projects: this.projects.length, source: 'sqlite-export' };
|
||||
}
|
||||
|
||||
close() {
|
||||
if (!this.storage?.database) return;
|
||||
const owner = this.storage.meta('runtimeOwner');
|
||||
if (this.ownerId && owner?.id === this.ownerId) this.storage.transaction(() => this.storage.setMeta('runtimeOwner', null));
|
||||
this.storage.close();
|
||||
}
|
||||
|
||||
publicSession(session) {
|
||||
const { providerMessages, ...visible } = session;
|
||||
visible.execution = this.executionSnapshot(session);
|
||||
visible.lastFailure = lastSessionFailure(session);
|
||||
if (session.status === 'failed' && !visible.failure && visible.lastFailure) {
|
||||
visible.failure = { ...visible.lastFailure, messageId: session.messages.findLast(message => message.role === 'system')?.id };
|
||||
@@ -178,7 +485,7 @@ export class Store extends EventEmitter {
|
||||
}
|
||||
|
||||
event(session, event) {
|
||||
const entry = { id: randomUUID(), createdAt: now(), ...event };
|
||||
const entry = { id: randomUUID(), createdAt: now(), taskId: session.taskId ?? null, runId: session.runId ?? null, ...event };
|
||||
session.events.push(entry);
|
||||
this.save(session);
|
||||
return entry;
|
||||
|
||||
Reference in New Issue
Block a user