import fs from 'node:fs'; import path from 'node:path'; import { EventEmitter } from 'node:events'; 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'; import { WORKSPACE_ACTIVE, projectWorkspaceIdentity, assertWorkspacePath } from '../shared/contracts/workspaces.mjs'; export const now = () => new Date().toISOString(); export function atomicJson(file, value) { fs.mkdirSync(path.dirname(file), { recursive: true }); const temporary = file + '.' + randomUUID() + '.tmp'; const handle = fs.openSync(temporary, 'wx', 0o600); try { fs.writeFileSync(handle, JSON.stringify(value, null, 2), 'utf8'); fs.fsyncSync(handle); } finally { fs.closeSync(handle); } try { if (fs.existsSync(file)) fs.copyFileSync(file, file + '.bak'); fs.renameSync(temporary, file); } finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); } } export function readJson(file, fallback) { for (const candidate of [file, file + '.bak']) { if (!fs.existsSync(candidate)) continue; try { return JSON.parse(fs.readFileSync(candidate, 'utf8')); } catch { if (candidate === file) fs.copyFileSync(candidate, candidate + '.corrupt-' + Date.now()); } } return structuredClone(fallback); } export function repairToolPairs(messages, lookupResult = null) { const result = []; 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; } result.push(message); if (message.role !== 'assistant' || !message.tool_calls?.length) continue; const received = new Map(); while (messages[index + 1]?.role === 'tool') { const tool = messages[++index]; if (!received.has(tool.tool_call_id)) received.set(tool.tool_call_id, tool); else dropped++; } for (const call of message.tool_calls) { 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 = lookupResult?.(call.id); if (saved && (saved.status === 'unknown' || placeholder && saved.status !== 'interrupted')) { 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, message: '服务重启时没有收到这次工具调用的完成结果。请核对当前项目状态;终端命令重新执行需要再次确认。', }) }); } } dropped += [...received.keys()].filter(id => !message.tool_calls.some(call => call.id === id)).length; } return { messages: result, interrupted, recovered, changed: interrupted > 0 || dropped > 0 || recovered > 0 }; } export class Store extends EventEmitter { constructor(directory, options = {}) { super(); this.directory = path.resolve(directory); this.sessions = new Map(); 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) { const missing = CORE_KINDS.filter(kind => !this.core?.[kind]); if (missing.length) { const next = { ...this.core }; for (const kind of missing) next[kind] = new Map(); for (const record of this.storage.load().records) if (missing.includes(record.kind)) next[record.kind].set(record.value.id, record.value); this.core = next; } 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 (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 plan of this.core.context_plan.values()) if (plan.sessionId === session.id && ['prepared', 'requesting'].includes(plan.status)) { plan.status = 'interrupted'; plan.finishedAt = now(); plan.error = '进程中断,未保存完整模型响应;不自动发送请求或重放工具。'; changed = true; } for (const job of this.core.check_job.values()) if (job.sessionId === session.id && ['queued', 'running', 'waiting'].includes(job.status)) { job.requiresVerification = job.status !== 'queued'; job.status = job.requiresVerification ? 'unknown' : 'interrupted'; job.finishedAt = now(); job.summary = job.requiresVerification ? '检查进程中断,未得到完整结果;需要核对实际状态,不自动重放。' : '检查尚未进入执行,恢复不会自动运行。'; const task = this.core.task.get(job.taskId); if (task) task.verification = { status: job.status, checkJobId: job.id }; changed = true; } for (const job of this.core.delivery_job.values()) if (job.sessionId === session.id && ['queued', 'preparing', 'prepared', 'publishing', 'committed'].includes(job.status)) { job.requiresVerification = !!job.lockPath || !!job.referenceAttempted; job.status = job.requiresVerification ? 'unknown' : 'interrupted'; job.finishedAt = now(); job.summary = job.requiresVerification ? '提交进程中断,先核对实际Git结果和本次索引锁;不会重放提交。' : '提交尚未进入执行,恢复不会自动运行。'; changed = true; } for (const job of this.core.delivery_job.values()) if (job.sessionId === session.id && job.status === 'reporting') { job.status = 'completed'; job.requiresVerification = false; job.finishedAt = now(); job.reportError = 'Git提交和索引已经核对,进程在报告生成前退出;可以重新生成报告。'; changed = true; } for (const set of this.core.change_set.values()) if (set.sessionId === session.id && ['applying', 'rolling_back'].includes(set.status)) { set.status = 'unknown'; set.requiresVerification = true; set.finishedAt = now(); set.summary = '文件批次在执行中断;请核对实际原文/建议字节,不会自动续写或回退。'; session.status = 'paused'; session.recoveryNotice = set.summary; changed = true; } for (const workspace of this.core.workspace.values()) if (workspace.sessionId === session.id && WORKSPACE_ACTIVE.has(workspace.status)) { workspace.status = 'unknown'; workspace.requiresVerification = true; workspace.finishedAt = now(); workspace.summary = '隔离工作区创建中断,请核对实际目录、分支和Git登记。不会重放创建、删除或重置。'; session.status = 'paused'; session.recoveryNotice = workspace.summary; 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 ? '调用已进入执行阶段,服务中断后未记录完成结果。实际结果需要核对。' : '这次调用没有完成;不会自动重放。'; changed = true; } } for (const approval of session.approvals ?? []) { if (approval.status === 'pending') { approval.status = 'interrupted'; changed = true; } } 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; } 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, { 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(); 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) { 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; } addProject(root, { id = null, name = null, workspace = null } = {}) { if (id !== null && !isId(id) || name !== null && (typeof name !== 'string' || !name.trim() || name.length > 200 || /[\x00-\x1f]/.test(name))) throw new Error('内部项目身份或名称无效。'); const resolved = fs.realpathSync.native(path.resolve(root)); if (!fs.statSync(resolved).isDirectory()) throw new Error('请选择项目文件夹。'); const key = process.platform === 'win32' ? resolved.toLowerCase() : resolved; const existing = this.projects.find(project => (process.platform === 'win32' ? project.root.toLowerCase() : project.root) === key); if (existing) { if (id && existing.id !== id || workspace && JSON.stringify(existing.workspace) !== JSON.stringify(workspace)) throw Object.assign(new Error('目标目录已经属于另一个项目身份,不能替换。'), { status: 409 }); return existing; } if (id && this.projects.some(project => project.id === id)) throw Object.assign(new Error('项目身份已经用于另一个目录。'), { status: 409 }); if (workspace) { const record = this.core.workspace.get(workspace.id), source = record && this.project(record.projectId); const expected = record && { id: record.id, sourceProjectId: record.projectId, sourceSessionId: record.sessionId, sourceRoot: record.source.root, sourceWorkspaceId: source.workspace?.id ?? null, baseCommit: record.source.head, branch: record.branch, commonGitDir: record.source.commonDir, gitDir: record.observation?.gitDir, fingerprint: record.fingerprint }; if (!record || record.status !== 'registering' || record.childProjectId !== id || record.root !== resolved || JSON.stringify(workspace) !== JSON.stringify(expected)) throw Object.assign(new Error('工作区项目必须来自已验证的持久创建记录。'), { status: 409 }); assertWorkspacePath({ root: resolved, workspace }); } const project = { id: id ?? randomUUID(), root: resolved, name: name ?? path.basename(resolved), addedAt: now(), ...(workspace ? { workspace: structuredClone(workspace) } : {}) }; const next = [project, ...this.projects]; this.storage.transaction(() => this.storage.writeProjects(next)); this.projects = next; return project; } project(id) { const project = this.projects.find(item => item.id === id); if (!project) throw Object.assign(new Error('项目不存在。'), { status: 404 }); return project; } createSession(projectId, title = '新任务', { id = null } = {}) { this.project(projectId); if (id !== null && !isId(id)) throw new Error('内部会话身份无效。'); if (id && this.sessions.has(id)) { const existing = this.sessions.get(id); if (existing.projectId !== projectId) throw Object.assign(new Error('会话身份已经属于另一个项目。'), { status: 409 }); return existing; } const session = { id: id ?? randomUUID(), projectId, title, status: 'idle', createdAt: now(), updatedAt: now(), messages: [], providerMessages: [], events: [], changes: [], approvals: [], failure: null, lastFailure: null, compactions: 0, estimatedTokens: 0, usage: null, archived: false, }; this.sessions.set(session.id, session); this.save(session); return session; } session(id) { const session = this.sessions.get(id); if (!session) throw Object.assign(new Error('会话不存在。'), { status: 404 }); return session; } beginRun(session, content, resume, config, { instructionSource = null } = {}) { 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 (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 workspaceIdentity = projectWorkspaceIdentity(this.project(session.projectId)); task.workspaceIdentity ??= structuredClone(workspaceIdentity); if (JSON.stringify(task.workspaceIdentity) !== JSON.stringify(workspaceIdentity)) throw Object.assign(new Error('任务的工作区身份已变化,不能将原任务移动到另一个工作区。'), { status: 409 }); const run = createRun(session, task, config, resume ? previousRunId : null); run.workspaceIdentity = structuredClone(workspaceIdentity); 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 = record.state; 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: '工具结果工件缺失或校验失败,实际结果需要核对。' }; const session = this.session(sessionId), event = session.events.find(value => value.id === record.eventId); if (event) { event.phase = 'unknown'; event.output = record.result.message; } const run = this.core.run.get(record.runId); if (run && !run.checkpoint.requiresVerification.includes(record.id)) run.checkpoint.requiresVerification.push(record.id); if (run) run.checkpoint.completedToolIds = run.checkpoint.completedToolIds.filter(id => id !== record.id); } } 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); const projectWorkspaces = [...this.core.workspace.values()].filter(value => value.projectId === session.projectId); const recentWorkspaceIds = new Set(projectWorkspaces.slice(-12).map(value => value.id)); return { schemaVersion: 1, task: task ?? null, run: run ?? null, workspaceIdentity: projectWorkspaceIdentity(this.project(session.projectId)), workspaces: projectWorkspaces.filter(value => recentWorkspaceIds.has(value.id) || value.requiresVerification || ['prepared', 'creating', 'verifying', 'registering'].includes(value.status)), 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, model: value.model, budget: value.budget, resumeOf: value.resumeOf, ...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}), ...(value.review ? { review: value.review } : {}) })), 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, contextPlans: [...this.core.context_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-30), changeSets: [...this.core.change_set.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-12), plans: [...this.core.check_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-5), deliveries: [...this.core.delivery_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-10), deliveryPlans: [...this.core.delivery_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-3).map(({ snapshot, ...value }) => ({ ...value, baseline: { head: snapshot.head, branch: snapshot.branch, reference: snapshot.reference }, })), 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() })); } invalidateChecks(projectId, reason = '工程文件已变化,需要重新检查。') { for (const job of this.core.check_job.values()) { if (job.projectId !== projectId || job.status !== 'passed' || job.stale) continue; job.stale = true; job.staleReason = reason; const session = this.session(job.sessionId), task = this.core.task.get(job.taskId); if (task?.verification.checkJobId === job.id) task.verification = { ...task.verification, status: 'stale', reason }; this.save(session, { type: 'check.stale', detail: { jobId: job.id } }); } } 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 }; } return structuredClone(visible); } listSessions() { return [...this.sessions.values()].filter(session => !session.archived) .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)) .map(session => ({ id: session.id, projectId: session.projectId, title: session.title, status: session.status, revision: session.revision ?? 0, updatedAt: session.updatedAt, changeCount: session.changes.filter(change => ['pending', 'conflict'].includes(change.status)).length })); } event(session, 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; } message(session, role, content) { const message = { id: randomUUID(), role, content, createdAt: now() }; session.messages.push(message); this.save(session); return message; } }