825 lines
57 KiB
JavaScript
825 lines
57 KiB
JavaScript
import { unrestricted, ceiling } from '../shared/contracts/execution-policy.mjs';
|
|
import { publicEnvironmentDiagnostic } from '../core/environment/environment-manager.mjs';
|
|
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 { bindDiagnosticContext } from '../core/tasks/diagnostic-context.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 { isContinuation, isDiagnosticQuestion, taskContract, updateTaskContract } from '../shared/contracts/task-control.mjs';
|
|
import { WORKSPACE_ACTIVE, projectWorkspaceIdentity, assertWorkspacePath } from '../shared/contracts/workspaces.mjs';
|
|
import { RESEARCH_ACTIVE } from '../shared/contracts/research.mjs';
|
|
import { ENGINE_ACTIVE, publicEngineJob } from '../shared/contracts/engines.mjs';
|
|
import { ENGINE_RUN_ACTIVE, publicEngineRun, verifyEngineModelInput } from '../shared/contracts/engine-execution.mjs';
|
|
import { BROWSER_ACTIVE } from '../shared/contracts/browser.mjs';
|
|
import { publicBrowserPlan } from '../core/browser/browser-manager.mjs';
|
|
import { MCP_ACTIVE } from '../core/tools/mcp-contract.mjs';
|
|
import { EVALUATION_ACTIVE } from '../shared/contracts/evaluations.mjs';
|
|
import { COLLABORATION_ACTIVE, COLLABORATION_CLOSED } from '../shared/contracts/workers.mjs';
|
|
|
|
export const now = () => new Date().toISOString();
|
|
|
|
export function physicalDataDirectory(directory) {
|
|
const resolved = path.resolve(directory), parsed = path.parse(resolved);
|
|
let current = parsed.root;
|
|
for (const component of resolved.slice(parsed.root.length).split(path.sep).filter(Boolean)) {
|
|
current = path.join(current, component);
|
|
if (fs.lstatSync(current).isSymbolicLink()) throw new Error('任务数据目录不接受符号链接或目录联接。');
|
|
}
|
|
return fs.realpathSync.native(resolved);
|
|
}
|
|
|
|
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 = {}) {
|
|
// A retained pre-desktop Store may still name an MSIX-virtualized LocalAppData
|
|
// directory. Bind new path-scoped services to that same physical directory,
|
|
// including when SQLite is already open; do not reopen or move its data.
|
|
this.directory = physicalDataDirectory(this.directory);
|
|
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.artifactStore.unrestricted = () => unrestricted(this);
|
|
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) {
|
|
if (plan.workerDispatchedAt && !plan.workerUsageAccounted && !plan.engineStepOnly) {
|
|
const run = this.core.run.get(plan.runId);
|
|
if (run && this.core.task.get(run.taskId)?.workerId) {
|
|
this.recordResponse(session, run, null, plan.tokenReservation?.reservedTokens??plan.estimatedInputTokens + (run.model.maxOutputTokens ?? 2048));
|
|
plan.workerUsageAccounted = true; plan.workerUsageRecovered = true; changed = true;
|
|
}
|
|
}
|
|
if (['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 job of this.core.research_job.values()) if (job.sessionId === session.id && RESEARCH_ACTIVE.has(job.status)) {
|
|
job.status = job.analysisDispatched ? 'unknown' : 'interrupted'; job.requiresVerification = !!job.analysisDispatched; job.finishedAt = now();
|
|
job.evidenceBinding = null; job.summary = '研究连接中断,未保存可核验完成结果。原进程关闭状态未知;不会根据历史PID停止进程或重放分析。';
|
|
const event = session.events.find(value => value.id === job.eventId);
|
|
if (event) { event.phase = job.status; event.finishedAt = job.finishedAt; event.output = job.summary; }
|
|
changed = true;
|
|
}
|
|
for (const job of this.core.mcp_job.values()) if (job.sessionId === session.id && MCP_ACTIVE.has(job.status)) {
|
|
job.status = 'unknown'; job.requiresVerification = true; job.finishedAt = now();
|
|
job.error = { code: 'MCP_HOST_INTERRUPTED', message: '宿主中断,外部MCP结果及原进程状态待核对。不按历史PID停止进程,不重放请求。' }; changed = true;
|
|
}
|
|
for (const batch of this.core.evaluation.values()) if (batch.sessionId === session.id && EVALUATION_ACTIVE.has(batch.status)) {
|
|
for (const sample of batch.samples) if (EVALUATION_ACTIVE.has(sample.status)) { sample.interruptedStatus = sample.status; sample.status = 'unknown'; sample.error = '宿主中断;原执行结果保持未知,不自动重跑。'; }
|
|
batch.status = 'unknown'; batch.message = '宿主中断,评测及所属执行需要核对;不重放已完成工具。'; changed = true;
|
|
}
|
|
for (const group of this.core.collaboration.values()) if (group.sessionId === session.id && COLLABORATION_ACTIVE.has(group.status)) {
|
|
group.status = 'unknown'; group.requiresVerification = true; group.finishedAt = now();
|
|
group.summary = '父协作在宿主中断时没有完整收尾;保留子任务和工作区,核对原输入与现场后显式处理,不自动重放。';
|
|
session.status = 'paused'; session.recoveryNotice = group.summary; changed = true;
|
|
}
|
|
for (const worker of this.core.worker.values()) if (worker.sessionId === session.id && ['running', 'stopping'].includes(worker.status)) {
|
|
worker.status = 'unknown'; worker.requiresVerification = true; worker.finishedAt = now();
|
|
worker.summary = '子执行在宿主中断时没有完整收尾;原进程结束及实际修改待核对,不按历史PID停止进程或重放工具。';
|
|
session.status = 'paused'; session.recoveryNotice = worker.summary; changed = true;
|
|
}
|
|
for (const job of this.core.engine_run.values()) if (job.sessionId === session.id && ENGINE_RUN_ACTIVE.has(job.status)) {
|
|
for (const request of job.requests) if (request.dispatchedAt && !request.finishedAt) {
|
|
const run = this.core.run.get(job.runId);
|
|
try {
|
|
verifyEngineModelInput(this, session, job, request);
|
|
const count = request.actualAttemptsFinal ?? request.maxAttempts;
|
|
if (run) while (request.accountedAttempts < count) {
|
|
request.accountedAttempts++; this.recordResponse(session, run, null, request.reservedPerAttempt);
|
|
request.recoveredUnknownAttempts = (request.recoveredUnknownAttempts ?? 0) + 1;
|
|
}
|
|
} catch (error) {
|
|
request.verificationError = error.message;
|
|
if (run) this.recordResponse(session, run, null, Math.max(0, this.core.task.get(job.taskId).budget.maxTokens - accountedTokens(this.core.task.get(job.taskId).usage)));
|
|
request.recoveryConservativeCharge = true;
|
|
}
|
|
request.status = 'interrupted'; request.finishedAt = now();
|
|
request.error = '宿主中断,原模型结果未完整封存;按原尝试预算核对,不自动请求。';
|
|
}
|
|
job.status = 'unknown'; job.requiresVerification = true; job.verified = false; job.finishedAt = now();
|
|
job.error = '受控引擎宿主中断,原工具/模型结果及进程树待核对。原输入保留,不按历史PID终止或重放。';
|
|
session.status = 'paused'; session.recoveryNotice = job.error; changed = true;
|
|
}
|
|
for (const job of this.core.engine_job.values()) if (job.sessionId === session.id && ENGINE_ACTIVE.has(job.status)) {
|
|
job.status = 'unknown'; job.requiresVerification = true; job.verification = null; job.finishedAt = now();
|
|
job.summary = '外部引擎连接检查中断,原进程关闭状态未知。不会根据历史PID停止进程或重放请求,请查看所属原记录。';
|
|
const event = session.events.find(value => value.id === job.eventId);
|
|
if (event) { event.phase = 'unknown'; event.finishedAt = job.finishedAt; event.output = job.summary; }
|
|
changed = true;
|
|
}
|
|
for (const job of this.core.browser_job.values()) if (job.sessionId === session.id && BROWSER_ACTIVE.has(job.status)) {
|
|
job.status = job.browserDispatched ? 'unknown' : 'interrupted'; job.requiresVerification = !!job.browserDispatched; job.finishedAt = now();
|
|
job.summary = '浏览器检查在宿主中断时未封存完成结果。保留实际步骤;原进程结束状态未知,不按历史PID停止进程或重放。';
|
|
const event = session.events.find(value => value.id === job.eventId);
|
|
if (event) { event.phase = job.status; event.finishedAt = job.finishedAt; event.output = job.summary; }
|
|
changed = true;
|
|
}
|
|
for (const tab of this.core.browsing_tab.values()) if (tab.sessionId === session.id && tab.status === 'open') {
|
|
tab.status = 'unavailable'; tab.error = '原桌面连接中断;原观察保留,不恢复或重放页面动作。'; changed = true;
|
|
}
|
|
for (const action of this.core.browsing_action.values()) if (action.sessionId === session.id && ['queued','dispatched'].includes(action.status)) {
|
|
action.status = action.dispatchedAt && action.kind === 'act' ? 'unknown' : 'interrupted'; action.requiresVerification = action.status === 'unknown'; action.finishedAt = now(); changed = true;
|
|
}
|
|
for (const job of this.core.preview_job.values()) {
|
|
if (job.sessionId !== session.id || !['queued','starting','ready','stopping'].includes(job.status)) continue;
|
|
job.status = 'unknown'; job.requiresVerification = true; job.finishedAt = now();
|
|
job.summary = '宿主中断,原预览进程需只读核对;不接管历史PID或自动重启。'; changed = true;
|
|
}
|
|
for (const job of this.core.environment_job.values()) {
|
|
if (job.sessionId !== session.id || !['queued','running','stopping'].includes(job.status)) continue;
|
|
job.status = 'unknown'; job.requiresVerification = true; job.finishedAt = now();
|
|
job.summary = '宿主中断,原依赖进程与结果需只读核对;不按历史PID结束进程,不自动重放。'; 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' });
|
|
}
|
|
for (const group of this.core.collaboration.values()) {
|
|
const unresolved = group.children.some(child => this.core.worker.get(child.id)?.requiresVerification
|
|
|| this.core.workspace.get(child.workspaceId)?.requiresVerification
|
|
|| ['tool', 'check_job', 'change_set', 'engine_run'].some(kind => [...this.core[kind].values()].some(record => record.taskId === child.taskId && record.requiresVerification)))
|
|
|| [...this.core.change_set.values()].some(set => set.taskId === group.taskId && set.requiresVerification);
|
|
if (!COLLABORATION_CLOSED.has(group.status) && unresolved && (!group.requiresVerification || group.status !== 'unknown')) {
|
|
group.status = 'unknown'; group.requiresVerification = true; group.finishedAt = now();
|
|
group.summary = '所属子执行或父批次仍有未知结果,原协作需要核对;不自动重放。';
|
|
const session = this.session(group.sessionId); session.status = 'paused'; session.recoveryNotice = group.summary;
|
|
this.save(session, { type: 'collaboration.recovered_children' });
|
|
}
|
|
}
|
|
}
|
|
|
|
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) { if (run?.purpose !== 'diagnostic' || run.finishedAt) 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, { beforeSave } = {}) {
|
|
const next = cleanConfig({ ...this.config, ...config, configRevision: (this.config.configRevision ?? 0) + 1 });
|
|
this.storage.transaction(() => { beforeSave?.(); 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 });
|
|
Object.defineProperty(project, 'executionMode', { configurable: true, enumerable: false, get: () => this.config.executionMode });
|
|
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, forceNewTask = false, inputAttachments = [],resumePlan=null } = {}) {
|
|
let task = this.core.task.get(session.taskId);
|
|
if(resumePlan&&(!resume||!task||resumePlan.taskId!==task.id||this.owned('resume_plan',resumePlan.id,session.id)!==resumePlan||resumePlan.status!=='prepared'))throw new Error('续接预览不属于原任务。');
|
|
// Bind inputs in the same session transaction as run.started.
|
|
const inputs = inputAttachments.map(row => {
|
|
if (this.owned('input_attachment',row.id,session.id) !== row || row.status !== 'draft') throw new Error('附件选择已变化。');
|
|
return {row,artifacts:[row.originalArtifactId,row.sentArtifactId].map(id=>this.owned('artifact',id,session.id))};
|
|
});
|
|
if (!unrestricted(config) && (inputs.length>1 || inputs.length && !forceNewTask && task?.attachmentIds?.length && (resume || !['completed','idle'].includes(task.status)))) throw new Error('当前任务已有截图,请新建任务再添加。');
|
|
const previousRunId = session.runId ?? null;
|
|
if (task) task.contract ??= taskContract(task, id => this.core.task.get(id));
|
|
const purpose = !forceNewTask && task && !resume && isDiagnosticQuestion(content) ? 'diagnostic' : 'execution';
|
|
const continuing = task && isContinuation(content);
|
|
if (forceNewTask || !task || !resume && !continuing && purpose !== 'diagnostic' && ['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 && purpose !== 'diagnostic' && (!resume || instructionSource)) {
|
|
task.instructions.push({ id: randomUUID(), content, createdAt: now(), source: instructionSource ?? 'user' });
|
|
updateTaskContract(task, content);
|
|
if (!continuing && !instructionSource) task.stagnation = null;
|
|
}
|
|
task.contract ??= taskContract(task, id => this.core.task.get(id));
|
|
if (task.readProgress) {
|
|
task.readProgress.repeated = 0; task.readProgress.changingIndexes = []; task.readProgress.warning = null; task.readProgress.pause = false; task.readProgress.checkPause = false;
|
|
task.readProgress.sessionInspection = null;
|
|
task.readProgress.noopPause = 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 || continuing ? previousRunId : null);
|
|
// A new open Run adopts the user's current policy even when it continues
|
|
// an exhausted legacy Task. Historical Run budgets and usage stay intact.
|
|
if (unrestricted(config)) task.budget.maxTokens = 0;
|
|
run.purpose = purpose;
|
|
if (purpose === 'diagnostic') {
|
|
run.question = String(content); run.taskStatusBefore = task.status;
|
|
run.diagnosticContext = bindDiagnosticContext(this, session, task, run);
|
|
}
|
|
if (instructionSource) run.source = instructionSource;
|
|
if(resumePlan){task.budget.maxTokens=config.maxTaskTokens;run.resumePlanId=resumePlan.id;resumePlan.status='consumed';resumePlan.newRunId=run.id;}
|
|
run.workspaceIdentity = structuredClone(workspaceIdentity);
|
|
this.core.run.set(run.id, run); task.activeRunId = run.id;
|
|
for (const {row,artifacts} of inputs) {
|
|
const copies=artifacts.map(artifact=>({...artifact,id:randomUUID(),taskId:task.id,runId:run.id}));
|
|
for(const artifact of copies)this.core.artifact.set(artifact.id,artifact);
|
|
const bound={...row,id:randomUUID(),taskId:task.id,runId:run.id,status:'attached',sourceDraftId:row.id,
|
|
originalArtifactId:copies[0].id,sentArtifactId:copies[1].id};
|
|
this.core.input_attachment.set(bound.id,bound);
|
|
row.status='consumed';row.boundAttachmentId=bound.id;
|
|
}
|
|
if (inputs.length) task.attachmentIds=[...(task.attachmentIds??[]),...inputs.map(({row})=>row.boundAttachmentId)];
|
|
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;
|
|
}
|
|
|
|
recordConsumption(session, run, receipt, estimate = 0) {
|
|
if (!receipt?.attemptId || typeof receipt.attemptId !== 'string') throw new Error('模型消费记录缺少实际尝试身份。');
|
|
const receipts = run.consumption ??= [];
|
|
if (receipts.some(value => value.attemptId === receipt.attemptId)) return false;
|
|
receipts.push({ attemptId: receipt.attemptId, requestId: receipt.requestId ?? null,
|
|
connectionId: receipt.connectionId ?? null, connectionName: receipt.connectionName ?? null,
|
|
model: receipt.model, endpoint: receipt.endpoint, protocol: receipt.protocol,
|
|
...(receipt.requestUrl ? { requestUrl: receipt.requestUrl, responseUrl: receipt.responseUrl ?? null, redirected: receipt.redirected === true, redirectMode: receipt.redirectMode } : {}),
|
|
startedAt: receipt.startedAt, finishedAt: receipt.finishedAt, outcome: receipt.outcome,
|
|
usageStatus: receipt.usage ? 'reported' : 'unknown', usage: receipt.usage ?? null,
|
|
...(receipt.localEstimate?{localEstimate:structuredClone(receipt.localEstimate)}:{}),
|
|
...(receipt.modelIdentity?{modelIdentity:structuredClone(receipt.modelIdentity)}:{}),
|
|
estimatedUnknownTokens: receipt.usage ? 0 : Math.max(0, Math.ceil(estimate)) });
|
|
this.recordResponse(session, run, receipt.usage, estimate);
|
|
this.save(session, { type: 'model.consumption', detail: { attemptId: receipt.attemptId, usageStatus: receipt.usage ? 'reported' : 'unknown' } });
|
|
return true;
|
|
}
|
|
|
|
finishRun(session, run, stopReason = null, { status = session.status } = {}) {
|
|
run.status = status; run.finishedAt = now(); run.stopReason = stopReason;
|
|
const task = this.core.task.get(run.taskId);
|
|
if (run.purpose !== 'diagnostic' && !task.workerId && ['no_progress', 'step_limit'].includes(stopReason) && run.finalSourceFingerprint) {
|
|
const checks = [...this.core.check_job.values()].filter(job => job.taskId === task.id).map(job => ({ input: job.inputIdentity ?? job.sourceFingerprint, status: job.status }));
|
|
const signature = createHash('sha256').update(JSON.stringify({ source: run.finalSourceFingerprint,
|
|
changes: session.changes.filter(change => change.taskId === task.id).map(change => ({ path: change.path, sha256: change.sha256, status: change.status })),
|
|
checks: [...new Map(checks.map(check => [JSON.stringify(check), check])).values()],
|
|
reads: (task.readProgress?.reads ?? []).filter(read => !read.kind?.startsWith('context-')) })).digest('hex');
|
|
task.stagnation = { signature, sourceFingerprint: run.finalSourceFingerprint, count: task.stagnation?.signature === signature ? task.stagnation.count + 1 : 1, runId: run.id };
|
|
} else if (run.purpose !== 'diagnostic') task.stagnation = null;
|
|
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?.state === 'resolved_external' && record.review?.result === 'unknown-preserved') return {
|
|
status: 'unknown', requires_verification: false, invocation_id: record.id, evidence_sha256: record.review.evidenceSha256,
|
|
message: '原结果保持未知,用户已核对原输入与现场;此调用不会重放,重新检查须使用新计划与审批。',
|
|
};
|
|
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 mcpAll = [...this.core.mcp_job.values()].filter(value => value.sessionId === session.id);
|
|
const mcpPreview = mcpAll.filter(value => value.taskId === task?.id || value.requiresVerification).slice(-30);
|
|
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));
|
|
const engineRuns = [...this.core.engine_run.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20).map(publicEngineRun);
|
|
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.purpose ? { purpose: value.purpose, source: value.source, taskStatusBefore: value.taskStatusBefore } : {}),
|
|
...(value.consumption ? { consumption: value.consumption } : {}),
|
|
...(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,
|
|
...([...this.core.file_result.values()].some(value => value.sessionId === session.id && value.taskId === task?.id) ? {
|
|
fileResults: [...this.core.file_result.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-16),
|
|
} : {}),
|
|
browsingTabs: [...this.core.browsing_tab.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-16),
|
|
browsingActions: [...this.core.browsing_action.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-24),
|
|
previewPlans: [...this.core.preview_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-5),
|
|
previewJobs: [...this.core.preview_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification || ['queued','starting','ready','stopping'].includes(value.status))).slice(-12),
|
|
...([...this.core.environment_diagnostic.values()].some(value=>value.sessionId===session.id) ? {
|
|
environmentDiagnostics: [...this.core.environment_diagnostic.values()].filter(value=>value.sessionId===session.id && value.taskId===task?.id).slice(-4).map(publicEnvironmentDiagnostic),
|
|
environmentPlans: [...this.core.environment_plan.values()].filter(value=>value.sessionId===session.id && value.taskId===task?.id).slice(-5),
|
|
environmentJobs: [...this.core.environment_job.values()].filter(value=>value.sessionId===session.id && (value.taskId===task?.id || value.requiresVerification)).filter((value,index,all)=>index>=all.length-12 || value.requiresVerification || ['queued','running','stopping'].includes(value.status)),
|
|
} : {}),
|
|
mcpJobs: mcpPreview, mcpJobCount: mcpAll.length, mcpJobsTruncated: mcpAll.length > mcpPreview.length,
|
|
taskPlans: [...this.core.task_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-6),
|
|
taskProofs: [...this.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-24),
|
|
researchTargets: [...this.core.research_target.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-32),
|
|
researchJobs: [...this.core.research_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20),
|
|
engineJobs: [...this.core.engine_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20).map(publicEngineJob),
|
|
...(engineRuns.length ? { engineRuns } : {}),
|
|
browserPlans: [...this.core.browser_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-5).map(publicBrowserPlan),
|
|
browserJobs: [...this.core.browser_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-12),
|
|
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),
|
|
...([...this.core.evaluation.values()].some(value => value.sessionId === session.id) ? { evaluations: [...this.core.evaluation.values()].filter(value => value.sessionId === session.id) } : {}),
|
|
...([...this.core.collaboration.values()].some(value => value.sessionId === session.id) ? {
|
|
collaborations: [...this.core.collaboration.values()].filter(value => value.sessionId === session.id),
|
|
} : {}),
|
|
...([...this.core.worker.values()].some(value => value.sessionId === session.id) ? {
|
|
workers: [...this.core.worker.values()].filter(value => value.sessionId === session.id),
|
|
} : {}),
|
|
};
|
|
}
|
|
|
|
get eventCursor() { return this.storage.cursor; }
|
|
eventsAfter(cursor, options) { return this.storage.eventsAfter(cursor, options); }
|
|
storageInfo() {
|
|
return { engine: 'sqlite', schemaVersion: this.storage.database.prepare('PRAGMA user_version').get().user_version, eventCursor: this.eventCursor, pendingPublications: this.storage.pendingPublications(),
|
|
migratedFromJson: !!this.storage.meta('migration'), recovery: 'verify-unknown-results', compatibilityExport: 'explicit-json' };
|
|
}
|
|
|
|
claimRuntime() {
|
|
const owner = this.storage.meta('runtimeOwner');
|
|
if (runtimeOwnerAlive(owner)) throw new Error('这个数据目录已被另一个执行宿主使用。');
|
|
this.ownerId ??= randomUUID();
|
|
if (owner?.pid === process.pid && owner.id === this.ownerId) return;
|
|
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.inputAttachments=[...this.core.input_attachment.values()].filter(row=>row.sessionId===session.id&&['draft','attached'].includes(row.status));
|
|
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;
|
|
}
|
|
}
|