feat: persist execution state and tool results in SQLite
This commit is contained in:
+43
-3
@@ -3,6 +3,22 @@ import path from 'node:path';
|
||||
import { listFiles, readText, proposeFile, applyChange } from './files.mjs';
|
||||
import { APP_VERSION, executionEnvironment, sessionSnapshot } from './diagnostics.mjs';
|
||||
|
||||
export function createSessionPublisher(clients) {
|
||||
return session => {
|
||||
const payload = (session.eventSeq ? 'id: ' + session.eventSeq + '\n' : '') + 'data: ' + JSON.stringify({ kind: 'session', seq: session.eventSeq, session }) + '\n\n';
|
||||
for (const response of clients) {
|
||||
if (response.destroyed || response.writableEnded || response.writableLength > 2 * 1024 * 1024) { response.destroy(); clients.delete(response); }
|
||||
else response.write(payload);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function cursorNumber(value) {
|
||||
if (value === undefined || value === null || value === '') return 0;
|
||||
if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value))) throw new Error('事件游标无效。');
|
||||
return Number(value);
|
||||
}
|
||||
|
||||
export function createRequestHandler({ appDirectory, store, provider, runtime, token, clients, started, getPort, exampleProject, shutdown }) {
|
||||
const research = [
|
||||
{ id: 'overview', title: '统一机制报告', file: 'RESEARCH.md', description: '研究结论、证据与本产品采用的独立设计。' },
|
||||
@@ -50,9 +66,10 @@ return async (request, response) => {
|
||||
if (method === 'GET' && route === '/api/health') return json(response, { app: 'agent-workbench', version: APP_VERSION, pid: process.pid, ready: true, uptimeMs: Date.now() - started });
|
||||
if (method === 'GET' && route === '/api/bootstrap') return json(response, {
|
||||
token, version: APP_VERSION, config: { ...store.config, hasKey: provider.hasKey() },
|
||||
eventCursor: store.eventCursor, storage: store.storageInfo(), runtimeRoot: appDirectory,
|
||||
environment: executionEnvironment(),
|
||||
projects: store.projects, sessions: store.listSessions(), exampleProjectId: exampleProject?.id ?? null,
|
||||
capabilities: { fileChanges: 'review', commands: 'per-call-approval', recovery: 'explicit-resume', model: 'chat-completions-compatible' },
|
||||
capabilities: { fileChanges: 'review', commands: 'per-call-approval', recovery: 'durable-tool-results', model: 'chat-completions-compatible', execution: 'task-run-step', events: 'persistent-cursor', artifacts: 'sha256-verified' },
|
||||
});
|
||||
if (method === 'GET' && route === '/api/diagnostics') {
|
||||
const selected = url.searchParams.get('session');
|
||||
@@ -60,16 +77,33 @@ return async (request, response) => {
|
||||
return json(response, {
|
||||
version: APP_VERSION, environment: executionEnvironment(),
|
||||
connection: { mode: store.config.mode, endpoint: store.config.baseUrl, model: store.config.model, hasKey: provider.hasKey(), lastRequest: provider.lastRequest ?? null },
|
||||
session: session ? sessionSnapshot(session, store.project(session.projectId), store.config, value => provider.redact(value)) : null,
|
||||
storage: store.storageInfo(),
|
||||
session: session ? { ...sessionSnapshot(session, store.project(session.projectId), store.config, value => provider.redact(value)), execution: store.executionSnapshot(session) } : null,
|
||||
});
|
||||
}
|
||||
if (method === 'GET' && route === '/api/events') {
|
||||
const cursor = Math.max(cursorNumber(url.searchParams.get('after')), cursorNumber(request.headers['last-event-id']));
|
||||
if (cursor > store.eventCursor) throw Object.assign(new Error('事件游标超出当前历史,请重新加载工作台。'), { status: 409 });
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });
|
||||
clients.add(response); response.write('data: {"kind":"ready"}\n\n');
|
||||
const history = store.eventsAfter(cursor, { limit: 500 });
|
||||
for (const entry of history.events) response.write('id: ' + entry.seq + '\ndata: ' + JSON.stringify({ kind: 'session_changed', ...entry }) + '\n\n');
|
||||
clients.add(response); response.write('data: ' + JSON.stringify({ kind: 'ready', eventCursor: store.eventCursor, replayIncomplete: history.hasMore }) + '\n\n');
|
||||
const heartbeat = setInterval(() => response.write(': heartbeat\n\n'), 20000);
|
||||
request.on('close', () => { clearInterval(heartbeat); clients.delete(response); });
|
||||
return;
|
||||
}
|
||||
if (method === 'GET' && route === '/api/events/history') {
|
||||
const selected = url.searchParams.get('session'); if (selected) store.session(selected);
|
||||
return json(response, store.eventsAfter(cursorNumber(url.searchParams.get('after')), { sessionId: selected,
|
||||
limit: url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 100 }));
|
||||
}
|
||||
const artifactMatch = route.match(/^\/api\/artifacts\/([a-f0-9-]+)$/);
|
||||
if (method === 'GET' && artifactMatch) {
|
||||
const artifact = store.owned('artifact', artifactMatch[1], url.searchParams.get('session'));
|
||||
const text = store.artifactStore.read(artifact), offset = cursorNumber(url.searchParams.get('offset'));
|
||||
const limit = Math.min(64000, url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 16000);
|
||||
return json(response, { ...artifact, content: text.slice(offset, offset + limit), offset, totalCharacters: text.length, truncated: offset + limit < text.length });
|
||||
}
|
||||
if (method === 'POST' && route === '/api/projects') {
|
||||
const input = await body(request);
|
||||
if (typeof input.root !== 'string' || input.root.length > 2000) throw new Error('请输入项目文件夹的完整路径。');
|
||||
@@ -92,6 +126,9 @@ return async (request, response) => {
|
||||
const id = sessionMatch[1], action = sessionMatch[2] ?? '';
|
||||
const session = store.session(id);
|
||||
if (method === 'GET' && !action) return json(response, store.publicSession(session));
|
||||
if (method === 'GET' && action === 'execution') return json(response, store.executionSnapshot(session));
|
||||
const runMatch = action.match(/^runs\/([a-f0-9-]+)$/);
|
||||
if (method === 'GET' && runMatch) return json(response, store.owned('run', runMatch[1], session.id));
|
||||
if (method === 'GET' && action === 'export') {
|
||||
response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8',
|
||||
'Content-Disposition': 'attachment; filename="agent-workbench-session-' + id + '.json"' });
|
||||
@@ -153,6 +190,9 @@ return async (request, response) => {
|
||||
contextLimit: Math.trunc(Math.max(1000, Math.min(200000, Number(input.contextLimit) || 16000))),
|
||||
maxSteps: Math.trunc(Math.max(1, Math.min(30, Number(input.maxSteps) || 12))),
|
||||
maxOutputTokens: Math.trunc(Math.max(256, Math.min(16000, Number(input.maxOutputTokens) || 2048))),
|
||||
maxRunDurationMs: Math.trunc(Math.max(1000, Math.min(3600000, Number(input.maxRunDurationMs) || store.config.maxRunDurationMs))),
|
||||
maxRunTokens: Math.trunc(Math.max(1000, Math.min(2000000, Number(input.maxRunTokens) || store.config.maxRunTokens))),
|
||||
maxTaskTokens: Math.trunc(Math.max(1000, Math.min(10000000, Number(input.maxTaskTokens) || store.config.maxTaskTokens))),
|
||||
};
|
||||
provider.validate(config);
|
||||
if (Object.hasOwn(input, 'apiKey')) provider.setKey(input.apiKey);
|
||||
|
||||
Reference in New Issue
Block a user