import fs from 'node:fs'; import path from 'node:path'; import http from 'node:http'; import os from 'node:os'; import { randomBytes } from 'node:crypto'; import { fileURLToPath } from 'node:url'; import { Store } from './store.mjs'; import { Provider } from './provider.mjs'; import { Runtime } from './runtime.mjs'; import { createRequestHandler, createSessionPublisher } from './app.mjs'; import { APP_VERSION } from './diagnostics.mjs'; import { ConfigImporter } from '../core/models/config-import.mjs'; import { hostAuthority } from '../core/desktop/host-authority.mjs'; import { initializeExampleProject } from '../core/initial-example-project.mjs'; const appDirectory = process.env.AGENT_WORKBENCH_APP_DIR || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const dataDirectory = process.env.AGENT_WORKBENCH_DATA_DIR || path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), '.local', 'share'), 'AgentWorkbench'); const requestedPort = Number(process.env.AGENT_WORKBENCH_PORT || 4318); const store = new Store(dataDirectory); store.claimRuntime(); const provider = new Provider(); const runtime = new Runtime(store, provider, { appDirectory }); const token = randomBytes(32).toString('hex'); const clients = new Set(); const started = Date.now(); let actualPort = requestedPort; let closing = false; let exampleProject = null; const modelImportSync = setInterval(() => { try { const hub = provider.modelHub(store); if (!Object.values(hub.state.imports).some(source => source.enabled)) return; (hub.importer ??= new ConfigImporter(hub)).sync(); } catch {} }, 60000); modelImportSync.unref(); try { exampleProject = initializeExampleProject(store, appDirectory); } catch {} store.on('update', createSessionPublisher(clients)); const server = http.createServer(); server.workbenchReady = false; server.on('request', createRequestHandler({ appDirectory, server, store, provider, runtime, token, clients, started, getPort: () => actualPort, exampleProject, shutdown })); async function shutdown() { if (closing) return; closing = true; clearInterval(modelImportSync); try { await server.workbenchCompanion?.close(); } catch { closing = false; console.error('Workbench shutdown rejected while companion gateway is starting.'); return; } try { await Promise.all([provider.abortRequests(), runtime.stopAll()]); } catch (cause) { closing = false; provider.resumeRequests(); console.error('Workbench shutdown remains unverified: ' + provider.redact(cause.message)); return; } for (const response of clients) response.end(); clients.clear(); server.close(() => { store.close(); process.exit(0); }); setTimeout(() => process.exit(0), 3000).unref(); } process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown); server.on('error', error => { store.close(); console.error('Workbench could not start: ' + error.message); process.exitCode = 1; }); server.listen(requestedPort, '127.0.0.1', () => { actualPort = server.address().port; try { hostAuthority({ appDirectory, server, store, provider, runtime }).initialize(); server.workbenchReady = true; } catch (cause) { console.error('Workbench registration failed: ' + provider.redact(cause.message)); server.close(() => { store.close(); process.exit(1); }); return; } console.log(JSON.stringify({ app: 'agent-workbench', ready: true, url: 'http://127.0.0.1:' + actualPort, version: APP_VERSION })); });