feat: persist execution state and tool results in SQLite

This commit is contained in:
Agent Workbench Dev
2026-10-29 13:11:30 +08:00
parent b047665a33
commit 93f4d90ccb
21 changed files with 1125 additions and 81 deletions
+17 -13
View File
@@ -45,16 +45,17 @@ function sameTarget(target, file) {
return target.title === displayName && target.url === 'file://' + displayName;
}
export async function upgradeRunning({ url, pid, currentRoot, newRoot }) {
export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRoot }) {
const origin = localUrl(url), original = fs.realpathSync.native(currentRoot), next = fs.realpathSync.native(newRoot);
const originalScript = path.join(original, 'dist-server', 'server.mjs');
const upgradeScript = path.join(next, 'dist-server', 'hot-upgrade.mjs');
if (!fs.existsSync(originalScript) || !fs.existsSync(upgradeScript) || !fs.existsSync(path.join(next, 'dist-client', 'index.html'))) throw new Error('Upgrade bundles are incomplete.');
if (!Number.isInteger(pid) || pid < 1 || pid === process.pid) throw new Error('Invalid target process.');
const before = await (await fetch(origin + '/api/bootstrap', { signal: AbortSignal.timeout(5000) })).json();
if (!before.token || before.version !== '0.1.0') throw new Error('This migration accepts an existing 0.1.0 Workbench.');
if (!before.token || !['0.1.0', '1.0.0', '1.1.0'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
if (before.sessions.some(session => ['running', 'awaiting_approval', 'stopping'].includes(session.status))) throw new Error('Wait for existing tasks and approvals before upgrading.');
let protocol, socket, enabledHere = false, paused = false, breakpoint;
let protocol, socket, enabledHere = false, paused = false;
const breakpoints = [];
try {
let targets;
try { targets = await (await fetch('http://127.0.0.1:9229/json/list', { signal: AbortSignal.timeout(500) })).json(); } catch {}
@@ -80,20 +81,23 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot }) {
const identity = await protocol.send('Runtime.evaluate', { expression: 'process.pid', returnByValue: true });
if (identity.result.value !== pid) throw new Error('The inspector belongs to a different process.');
await protocol.send('Debugger.enable');
const script = scripts.find(item => sameFile(item.url, originalScript));
if (!script) throw new Error('The existing server module is missing from inspector metadata.');
const { scriptSource } = await protocol.send('Debugger.getScriptSource', { scriptId: script.scriptId });
const lines = scriptSource.split('\n');
const locations = lines.flatMap((line, index) => line.includes('const url = new URL(request.url') ? [index] : []);
if (locations.length !== 1) throw new Error('The existing request handler could not be identified uniquely.');
breakpoint = (await protocol.send('Debugger.setBreakpoint', { location: { scriptId: script.scriptId, lineNumber: locations[0] } })).breakpointId;
const previousRoot = handlerRoot || before.runtimeRoot;
const expectedScripts = [originalScript, ...(previousRoot ? [path.join(fs.realpathSync.native(previousRoot), 'dist-server', 'hot-upgrade.mjs')] : [])];
const candidates = scripts.filter(item => expectedScripts.some(file => sameFile(item.url, file)));
if (!candidates.length) throw new Error('The existing server module is missing from inspector metadata.');
for (const script of candidates) {
const { scriptSource } = await protocol.send('Debugger.getScriptSource', { scriptId: script.scriptId });
const locations = scriptSource.split('\n').flatMap((line, index) => line.includes('const url = new URL(request.url') ? [index] : []);
if (locations.length !== 1) throw new Error('The existing request handler could not be identified uniquely.');
breakpoints.push((await protocol.send('Debugger.setBreakpoint', { location: { scriptId: script.scriptId, lineNumber: locations[0] } })).breakpointId);
}
const probe = fetch(origin + '/api/health', { signal: AbortSignal.timeout(15000) });
probe.catch(() => {});
const event = await within(pausedEvent, 10000, 'Workbench request observation');
const captured = await protocol.send('Debugger.evaluateOnCallFrame', { callFrameId: event.callFrames[0].callFrameId,
expression: "globalThis.__awUpgradeContext = { server, store, provider, runtime, token, clients, started, exampleProject, shutdown }; 'context-ready'", returnByValue: true });
if (captured.exceptionDetails || captured.result.value !== 'context-ready') throw new Error('Could not retain the existing runtime objects.');
await protocol.send('Debugger.removeBreakpoint', { breakpointId: breakpoint }); breakpoint = null;
for (const breakpointId of breakpoints.splice(0)) await protocol.send('Debugger.removeBreakpoint', { breakpointId });
await protocol.send('Debugger.resume'); paused = false; await probe;
const expression = '(() => { try { const module = process.getBuiltinModule("module").createRequire(' + JSON.stringify(upgradeScript) + ')(' + JSON.stringify(upgradeScript) + '); return module.installUpgrade(globalThis.__awUpgradeContext, { appDirectory: ' + JSON.stringify(next) + ' }); } finally { delete globalThis.__awUpgradeContext; } })()';
const upgraded = await protocol.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
@@ -108,7 +112,7 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot }) {
return { ...result, verified: true, connectionPreserved: true, url: origin };
} finally {
if (protocol) {
try { if (breakpoint) await protocol.send('Debugger.removeBreakpoint', { breakpointId: breakpoint }); } catch {}
for (const breakpointId of breakpoints) { try { await protocol.send('Debugger.removeBreakpoint', { breakpointId }); } catch {} }
try { if (paused) await protocol.send('Debugger.resume'); } catch {}
try { await protocol.send('Runtime.evaluate', { expression: 'delete globalThis.__awUpgradeContext; true', returnByValue: true }); } catch {}
if (enabledHere) {
@@ -124,6 +128,6 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
const args = Object.fromEntries(process.argv.slice(2).reduce((items, value, index, all) => {
if (value.startsWith('--')) items.push([value.slice(2), all[index + 1]]); return items;
}, []));
const result = await upgradeRunning({ url: args.url || 'http://127.0.0.1:4318', pid: Number(args.pid), currentRoot: args['current-root'], newRoot: args['new-root'] });
const result = await upgradeRunning({ url: args.url || 'http://127.0.0.1:4318', pid: Number(args.pid), currentRoot: args['current-root'], newRoot: args['new-root'], handlerRoot: args['handler-root'] });
console.log(JSON.stringify(result, null, 2));
}