import { validateRuntimeBudgets } from '../core/models/runtime-settings.mjs'; import fs from 'node:fs'; import { createHash } from 'node:crypto'; import path from 'node:path'; import { listFiles, readText, proposeFile, proposePatch, applyChange } from './files.mjs'; import { APP_VERSION, executionEnvironment, sessionSnapshot } from './diagnostics.mjs'; import { inspectProject } from '../core/project-inspector.mjs'; import { assertProposalUnsealed } from '../shared/contracts/change-sets.mjs'; import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs'; import { verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs'; import { publicEngineJob } from '../shared/contracts/engines.mjs'; import { publicEngineRun, verifyEngineInput, originalEngineRun } from '../shared/contracts/engine-execution.mjs'; import { resolvePurgeSource,resolveOriginalPurgeSource,ORIGINAL_PURGE_KIND } from '../core/engines/purge-strategy.mjs'; import { verifyBrowserJob } from '../core/browser/browser-manager.mjs'; import { ConfigImporter } from '../core/models/config-import.mjs'; import { ProjectMemoryManager } from '../core/memory/project-memory.mjs'; import { workerForProject, workerConflict, assertWorkersResolved } from '../shared/contracts/workers.mjs'; import { hostAuthority } from '../core/desktop/host-authority.mjs'; import { companionGateway } from './companion-gateway.mjs'; import { inspectOperations } from './operations.mjs'; import { validateModelWaitSettings } from '../core/models/request-deadline.mjs'; import { nativeParameterSettings } from '../shared/contracts/native-parameters.mjs'; import { localDirectories } from './local-directories.mjs'; import { readInstallationProgress } from '../core/desktop/installation-progress.mjs'; export function createSessionPublisher(clients) { return session => { const snapshot = JSON.stringify({ kind: 'session', seq: session.eventSeq, session }); // Large source/Run receipts stay in the session API. Repeatedly queueing // them on SSE can disconnect a healthy reader before it receives a cursor. const data = Buffer.byteLength(snapshot) <= 64 * 1024 ? snapshot : JSON.stringify({ kind: 'session_changed', seq: session.eventSeq, sessionId: session.id, projectId: session.projectId, revision: session.revision }); const payload = (session.eventSeq ? 'id: ' + session.eventSeq + '\n' : '') + 'data: ' + data + '\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, server, store, provider, runtime, token, clients, started, getPort, exampleProject, shutdown }) { const host = () => hostAuthority({ appDirectory, server, store, provider, runtime }); const research = [ { id: 'overview', title: '统一机制报告', file: 'RESEARCH.md', description: '研究结论、证据与本产品采用的独立设计。' }, { id: 'cursor', title: 'Cursor:执行与编辑', file: 'research/CURSOR-MECHANISMS.md', description: '工具能力、执行事件、取消、恢复与文本改动。' }, { id: 'context', title: 'Claude Code:上下文与恢复', file: 'research/CONTEXT-RECOVERY.md', description: '压缩预算、摘要校验、会话链与未完成调用。' }, { id: 'tools', title: 'Claude Code:工具循环', file: 'research/TOOL-LOOP.md', description: '参数校验、队列、并发安全与权限判断。' }, ]; const memories = new ProjectMemoryManager(store); function json(response, value, status = 200) { response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' }); response.end(JSON.stringify(value)); } async function body(request, maximum=2*1024*1024) { if (!String(request.headers['content-type'] ?? '').startsWith('application/json')) throw Object.assign(new Error('请求需要 JSON。'), { status: 415 }); const chunks = []; let length = 0; for await (const chunk of request) { length += chunk.length; if (length > maximum) throw Object.assign(new Error('请求超过允许大小。'), { status: 413 }); chunks.push(chunk); } let input; try { input = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); } catch { throw Object.assign(new Error('请求 JSON 无效。'), { status: 400 }); } if (!input || typeof input !== 'object' || Array.isArray(input)) throw Object.assign(new Error('请求需要 JSON 对象。'), { status: 400 }); return input; } function allowRequest(request, url) { const actualPort = getPort(); const allowed = ['127.0.0.1:' + actualPort, 'localhost:' + actualPort]; if (!allowed.includes(request.headers.host)) throw Object.assign(new Error('服务仅接受本地工作台地址。'), { status: 421 }); const origin = request.headers.origin; if (origin && !allowed.map(host => 'http://' + host).includes(origin)) throw Object.assign(new Error('请求来源不属于本地工作台。'), { status: 403 }); if (url.pathname.startsWith('/api/') && !['/api/health', '/api/bootstrap'].includes(url.pathname)) { const supplied = request.headers['x-workbench-token'] || (url.pathname === '/api/events' ? url.searchParams.get('token') : ''); if (supplied !== token) throw Object.assign(new Error('请重新打开工作台以更新连接。'), { status: 403 }); } } return async (request, response) => { try { response.setHeader('Referrer-Policy', 'no-referrer'); response.setHeader('X-Frame-Options', 'DENY'); // Scripts and API requests belong to this workbench origin. Inline styles // are limited to the existing React layout; model text never becomes HTML. response.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; frame-src http://127.0.0.1:*; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'"); const actualPort = getPort(); if (server && (!server.listening || server.address().port !== actualPort)) throw new Error('本地执行宿主已经变化,请重新连接工作台。'); const url = new URL(request.url, 'http://127.0.0.1:' + actualPort); allowRequest(request, url); const method = request.method; const route = url.pathname; if (method === 'GET' && route === '/api/health') return json(response, { app: 'agent-workbench', version: APP_VERSION, pid: process.pid, ready: server?.workbenchReady !== false, uptimeMs: Date.now() - started }); if (route.startsWith('/api/companion')) { const gateway = companionGateway({ appDirectory, server, store, provider, runtime }); if (method === 'GET' && route === '/api/companion') return json(response, gateway.status()); if (method === 'POST' && route === '/api/companion/start') return json(response, await gateway.start(await body(request))); if (method === 'POST' && route === '/api/companion/close') { const value = await body(request); if (Object.keys(value).length) throw Object.assign(new Error('关闭手机连接不接受额外字段。'), { status: 400 }); return json(response, await gateway.close()); } if (method === 'POST' && route === '/api/companion/pair') return json(response, await gateway.pairing(await body(request))); const revoke = route.match(/^\/api\/companion\/devices\/([a-f0-9-]+)\/revoke$/); if (method === 'POST' && revoke) { const value = await body(request); if (Object.keys(value).length !== 1 || !Number.isSafeInteger(value.revision)) throw Object.assign(new Error('设备撤销需要原登记修订。'), { status: 400 }); return json(response, gateway.revoke(revoke[1], value.revision)); } if (method === 'GET' && route === '/api/companion/certificate') { const certificate = gateway.tls.publicCertificate(); response.writeHead(200, { 'Content-Type': 'application/pkix-cert', 'Content-Disposition': 'attachment; filename="Agent-Workbench-Mobile-CA.cer"', 'Cache-Control': 'no-store' }); return response.end(certificate.bytes); } return json(response, { error: '手机连接管理操作不存在。' }, 404); } if (method === 'GET' && route === '/api/host/identity') return json(response, host().attest(url.searchParams.get('challenge'))); if (method === 'GET' && route === '/api/host/status') return json(response, host().status()); if (method === 'GET' && route === '/api/installation/status') return json(response, { ...readInstallationProgress({ appRoot: appDirectory, dataRoot: store.directory }), runningVersion: APP_VERSION }); if (method === 'POST' && route === '/api/host/windows/register') return json(response, host().registerWindow(await body(request))); if (method === 'POST' && route === '/api/host/windows/unregister') { const input = await body(request); const result = host().unregisterWindow(input); runtime.browsing?.disconnect(input.windowId); return json(response, result); } if (method === 'POST' && /^\/api\/browsing-desktop\/(poll|complete|validate)$/.test(route)) { const input = await body(request, 12 * 1024 * 1024), owner = input.owner, registered = host().windows?.get(owner?.windowId); if (!registered || ['windowId','pid','createdAt','instanceId','runtimeIdentity'].some(key => registered[key] !== owner[key])) throw Object.assign(new Error('原桌面进程登记已变化。'), { status: 403 }); runtime.workbenchOrigin = 'http://127.0.0.1:' + actualPort; const manager = runtime.browsingManager(); manager.workbenchOrigin = runtime.workbenchOrigin; if (route.endsWith('/poll')) return json(response, manager.poll(owner.windowId, input.states)); if (route.endsWith('/validate')) { const pending = manager.active.get(input.id); if (!pending || pending.job.windowId !== owner.windowId || pending.nonce !== input.nonce || !pending.job.dispatchedAt) throw Object.assign(new Error('原动作已经停止或授权已撤销。'), { status: 409 }); return json(response, { valid: true }); } return json(response, manager.complete(owner.windowId, input)); } if (method === 'POST' && route === '/api/host/stop') { const result = await host().stop(await body(request)); json(response, result); setTimeout(shutdown, 100); return; } if (!['GET', 'HEAD'].includes(method) && server?.workbenchHostAuthority?.stopping) throw Object.assign(new Error('执行宿主正在停止,请等待所属操作结束。'), { status: 409 }); const skillsMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/skills(?:\/(toggle|refresh|content))?$/i); if (skillsMatch) { const registry = runtime.skillRegistry(), projectId = skillsMatch[1], action = skillsMatch[2]; if (method === 'GET' && !action) return json(response, registry.view(projectId)); if (method === 'GET' && action === 'content') return json(response, registry.content(projectId, url.searchParams.get('id'), Number(url.searchParams.get('revision')))); if (method === 'POST') { if (workerForProject(store, projectId)) throw workerConflict('受限子项目不能修改Skills登记,请返回父项目。'); const input = await body(request); if (!action) return json(response, registry.register(projectId, input), 201); if (action === 'toggle') return json(response, registry.toggle(projectId, input)); if (action === 'refresh') return json(response, registry.refresh(projectId, input), 201); } } const mcpMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/mcp(?:\/(configure))?$/i); if (mcpMatch) { const registry = runtime.mcpRegistry(), projectId = mcpMatch[1]; if (method === 'GET' && !mcpMatch[2]) return json(response, registry.view(projectId)); if (method === 'POST') { if (workerForProject(store, projectId)) throw workerConflict('受限子项目不能修改MCP登记,请返回父项目。'); const input = await body(request); return json(response, mcpMatch[2] ? registry.configure(projectId, input) : registry.register(projectId, input), mcpMatch[2] ? 200 : 201); } } const projectMemoryMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/memories$/i); if (projectMemoryMatch && method === 'GET') { const includeExpired = url.searchParams.get('include_expired') !== '0'; return json(response, await memories.list(projectMemoryMatch[1], { includeExpired })); } const sessionMemoryMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)\/memories$/i); if (sessionMemoryMatch && method === 'GET') { const session = store.session(sessionMemoryMatch[1]); const includeExpired = url.searchParams.get('include_expired') !== '0'; return json(response, await memories.list(session.projectId, { includeExpired })); } const sessionMemoryArchiveMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)\/memories\/([a-f0-9-]+)\/archive$/i); if (sessionMemoryArchiveMatch && method === 'POST') { const session = store.session(sessionMemoryArchiveMatch[1]); if (workerForProject(store, session.projectId)) throw workerConflict('受限子任务不能修改项目记忆,请返回父项目。'); await body(request); return json(response, memories.archive(session, sessionMemoryArchiveMatch[2])); } if (sessionMemoryMatch && method === 'POST') { const session = store.session(sessionMemoryMatch[1]); if (workerForProject(store, session.projectId)) throw workerConflict('受限子任务不能修改项目记忆,请返回父项目。'); const input = await body(request); return json(response, await memories.create(session, input), 201); } if (route.startsWith('/api/model-center')) { const hub = provider.modelHub(store); const importer = () => hub.importer ??= new ConfigImporter(hub); if (method === 'GET' && route === '/api/model-center') return json(response, hub.view()); if (method === 'GET' && route === '/api/model-center/network-diagnostics') return json(response, hub.networkDiagnostics().view()); const networkStop = route.match(/^\/api\/model-center\/network-diagnostics\/([a-f0-9-]{36})\/stop$/i); if (method === 'POST' && networkStop) return json(response, await hub.networkDiagnostics().stop(networkStop[1], await body(request))); if (method === 'POST' && route === '/api/model-center/network-diagnostics') { if (runtime.hasActivity()) throw Object.assign(new Error('请等待当前任务或诊断结束,再开始新的连接诊断。'), { status: 409 }); return json(response, hub.networkDiagnostics().start(await body(request)), 201); } if (method === 'GET' && route === '/api/model-center/selection') return json(response, { config: { ...store.config, hasKey: provider.hasKey() }, modelSelection: hub.selectionView(), }); if (method === 'GET' && route === '/api/model-center/credentials') return json(response, hub.vault().view(hub)); if (method === 'GET' && route === '/api/model-center/imports') return json(response, importer().discover()); if (method === 'POST') { const input = await body(request); if (route === '/api/model-center/toggle') return json(response, hub.toggle(input.id, input.enabled)); if (runtime.hasActivity() || hub.networkChecks?.active.size) throw Object.assign(new Error('请等待正在运行的任务或连接诊断结束,再修改或测试模型配置。'), { status: 409 }); if (route === '/api/model-center/runtime-budgets') { store.saveConfig(validateRuntimeBudgets(input)); return json(response, { config: { ...store.config, hasKey: provider.hasKey() }, modelSelection: hub.selectionView() }); } if (route === '/api/model-center/mode') { if (!input || Object.keys(input).length !== 1 || !['demo', 'compatible'].includes(input.mode)) throw new Error('请选择离线演示或真实模型模式。'); store.saveConfig({ mode: input.mode }); return json(response, { config: { ...store.config, hasKey: provider.hasKey() }, modelSelection: hub.selectionView() }); } if (route === '/api/model-center/wait-settings') { store.saveConfig(validateModelWaitSettings(input, store.config)); return json(response, { center: hub.view(), config: { ...store.config, hasKey: provider.hasKey() } }); } if (route === '/api/model-center/credentials') return json(response, hub.manageCredential(input)); if (route === '/api/model-center/native-parameters') return json(response, hub.setNativeParameters(input)); if (route === '/api/model-center/connections') return json(response, hub.upsert(input), 201); if (route === '/api/model-center/pools') return json(response, hub.pool(input), 201); if (route === '/api/model-center/select') return json(response, { center: hub.select(input, { mode: 'compatible' }), config: { ...store.config, hasKey: provider.hasKey() } }); if (route === '/api/model-center/import-preview') return json(response, importer().preview(input.source, String(input.path ?? ''))); if (route === '/api/model-center/import-apply') return json(response, importer().apply(input.previewId, input.autoSync, input.persistCredentials)); if (route === '/api/model-center/import-toggle') return json(response, importer().toggle(input.id, input.enabled)); if (route === '/api/model-center/import-sync') return json(response, { results: importer().sync(), center: hub.view() }); if (route === '/api/model-center/probe') { return json(response, await hub.probe(input.id, input.scope ?? 'text')); } } } if (method === 'GET' && route === '/api/operations') { return json(response, inspectOperations({ store, provider, runtime, server, appDirectory, version: APP_VERSION, parameters: url.searchParams })); } if (method === 'GET' && route === '/api/bootstrap') { const hub = provider.modelHub(store); return json(response, { token, version: APP_VERSION, config: { ...store.config, hasKey: provider.hasKey() }, modelSelection: hub.selectionView(), eventCursor: store.eventCursor, storage: store.storageInfo(), runtimeRoot: appDirectory, environment: executionEnvironment(), projects: store.projects, sessions: store.listSessions(), exampleProjectId: exampleProject?.id ?? null, capabilities: { environmentPreparation:'sealed-npm-ci-in-owned-worktree',environmentDiagnostics:'node-python-runtime-and-dependency-bytes',workspaces: 'owned-git-worktree-and-explicit-recovery', gitReview: 'durable-confirmation-boundary', requestContext: 'bounded-whole-request-and-history-artifacts', latestToolFeedback: 'sealed-original-result-fields', changeSets: 'reviewed-recoverable-batches', fileChanges: 'review', exactPatches: 'sha256-unique-anchors', codeIndex: 'bounded-ast-and-candidates', commands: 'per-call-approval', recovery: 'durable-tool-results', model: 'chat-completions-compatible', execution: 'task-run-step', events: 'persistent-cursor', artifacts: 'sha256-verified', checks: 'npm-and-python-counted-jobs', pythonChecks: 'bound-interpreter-and-structured-results', browserChecks: 'sealed-static-build-and-real-edge-assertions', projectInspection: 'bounded-source-and-git', projectMemory: 'project-scoped-source-fingerprint-and-expiry', gitDelivery: 'reviewed-local-snapshot', deliveryReports: 'evidence-json-markdown' }, }); } if (method === 'GET' && route === '/api/diagnostics') { const selected = url.searchParams.get('session'); const session = selected ? store.session(selected) : null; 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 }, storage: store.storageInfo(), projectCache: runtime.projectIndexer().status(session ? store.project(session.projectId) : undefined), session: session ? { ...sessionSnapshot(session, store.project(session.projectId), store.config, value => provider.redact(value)), execution: store.executionSnapshot(session) } : null, }); } if (route === '/api/project-cache') { if (method === 'GET') return json(response, runtime.projectIndexer().status()); if (method === 'POST') { const input = await body(request); if (!input || Object.keys(input).length !== 1 || typeof input.enabled !== 'boolean') throw new Error('仅接受enabled缓存开关。'); return json(response, runtime.projectIndexer().configure(input.enabled)); } } if (method === 'GET' && route === '/api/research/availability') return json(response, runtime.researchManager().availability()); if (method === 'GET' && route === '/api/engines/deepseek/availability') return json(response, runtime.engineManager().availability(url.searchParams.has('root') ? url.searchParams.get('root') : undefined)); if (method === 'GET' && route === '/api/engines/deepseek/controlled-availability') return json(response, runtime.engineRunner().availability(url.searchParams.has('root') ? url.searchParams.get('root') : undefined)); if (method === 'GET' && route === '/api/engines/purge/source') { const root=url.searchParams.has('root')?url.searchParams.get('root'):undefined; if(url.searchParams.get('kind')===ORIGINAL_PURGE_KIND)return json(response,resolveOriginalPurgeSource(appDirectory,root, runtime.engineRunner().availability(url.searchParams.has('harnessRoot')?url.searchParams.get('harnessRoot'):undefined))); if(url.searchParams.has('kind')&&url.searchParams.get('kind')!=='purge-prompt-experiment')throw Object.assign(new Error('未知 Purge 策略。'),{status:400}); return json(response,resolvePurgeSource(appDirectory,root)); } 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' }); 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')); if (url.searchParams.get('download') === '1') { const extension = artifact.mediaType === 'application/json' ? '.json' : artifact.mediaType === 'text/markdown' ? '.md' : '.txt'; response.writeHead(200, { 'Content-Type': artifact.mediaType + '; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'attachment; filename="agent-workbench-' + artifact.kind + '-' + artifact.id + extension + '"' }); response.end(store.artifactStore.readBytes(artifact)); return; } 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('请输入项目文件夹的完整路径。'); return json(response, store.addProject(input.root), 201); } const cacheMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/index-cache$/); if (cacheMatch && ['GET', 'DELETE'].includes(method)) { const project = store.project(cacheMatch[1]); await verifyWorkspaceProject(store, project); if (method === 'DELETE') { const input = await body(request); if (!input || Object.keys(input).length) throw new Error('清除派生缓存不接受路径或其他字段。'); return json(response, runtime.projectIndexer().clear(project)); } return json(response, runtime.projectIndexer().status(project)); } if (method === 'GET' && route === '/api/local-directories') return json(response, await localDirectories(url.searchParams.get('path') || '')); if (method === 'GET' && route === '/api/local-file-preview-access') return json(response, runtime.filePreviews?.access(url.searchParams.get('url') || '') || { allowed: false }); const filePreview = route.match(/^\/api\/projects\/([a-f0-9-]+)\/file-previews(?:\/([a-f0-9-]+))?$/); if (filePreview) { const project = store.project(filePreview[1]); if (method === 'POST' && !filePreview[2]) { const input = await body(request); if (Object.keys(input).some(key => key !== 'path')) throw new Error('文件预览只接受项目相对路径。'); return json(response, await runtime.localFilePreviews().start(project, input.path), 201); } if (method === 'DELETE' && filePreview[2]) { const input = await body(request); if (Object.keys(input).length) throw new Error('关闭预览不接受额外字段。'); return json(response, runtime.filePreviews ? await runtime.filePreviews.close(project.id, filePreview[2]) : { closed: true }); } } const projectMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/(files|file|inspection|code-index|code-query)$/); if (method === 'GET' && projectMatch) { const project = store.project(projectMatch[1]); await verifyWorkspaceProject(store, project); if (projectMatch[2] === 'inspection') return json(response, await inspectProject(project)); if (['code-index', 'code-query'].includes(projectMatch[2])) { const indexer = runtime.projectIndexer(), index = await indexer.refresh(project); return json(response, projectMatch[2] === 'code-index' ? indexer.summary(index) : indexer.query(index, { query: url.searchParams.get('query') ?? '', kind: url.searchParams.get('kind') ?? 'all', limit: url.searchParams.has('limit') ? Number(url.searchParams.get('limit')) : 30 })); } return json(response, projectMatch[2] === 'files' ? listFiles(project, url.searchParams.get('path') || '', 7, 1200) : readText(project, url.searchParams.get('path') || '')); } if (method === 'GET' && route === '/api/sessions') return json(response, store.listSessions()); if (method === 'POST' && route === '/api/sessions') { const input = await body(request); if (workerForProject(store, input.projectId)) throw workerConflict('隔离项目使用原受限子会话,请从父协作打开。'); await verifyWorkspaceProject(store, store.project(input.projectId)); return json(response, store.publicSession(store.createSession(input.projectId)), 201); } const sessionMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)(?:\/(.*))?$/); if (sessionMatch) { const id = sessionMatch[1], action = sessionMatch[2] ?? ''; const session = store.session(id); if (action === 'input-attachments') { if (method === 'GET') return json(response,runtime.inputAttachments().list(session)); if (workerForProject(store,session.projectId)) throw workerConflict('截图附件请在父任务中添加。'); if (method === 'POST') return json(response,runtime.inputAttachments().upload(session,await body(request,3*1024*1024)),201); } const inputImage = action.match(/^input-attachments\/([a-f0-9-]+)(?:\/(image|original))?$/); if (inputImage) { const manager=runtime.inputAttachments(); if(method==='DELETE'&&!inputImage[2]) { await body(request);return json(response,manager.remove(session,inputImage[1])); } if(method==='GET'&&inputImage[2]) { const {row,artifact,bytes}=manager.read(session,inputImage[1],{original:inputImage[2]==='original'}); const download=inputImage[2]==='original'||url.searchParams.get('download')==='1'; response.writeHead(200,{'Content-Type':artifact.mediaType,'Cache-Control':'no-store','X-Content-Type-Options':'nosniff','X-Content-SHA256':artifact.sha256, ...(download?{'Content-Disposition':'attachment; filename="workbench-input-'+row.id+(artifact.mediaType==='image/png'?'.png':'.jpg')+'"'}:{})}); response.end(bytes);return; } } if (method === 'POST' && workerForProject(store, session.projectId) && /^(?:mcp|engines|research|workspaces|delivery|browser|browsing|preview|task-plans|task-proofs|file-results|task-checkpoints|collaborations|evaluations)(?:\/|-|$)/.test(action)) throw workerConflict('受限子任务只开放原目标的读取、范围内改动和已审批检查;此操作请返回父项目。'); if (method === 'GET' && action === 'evaluations') return json(response,runtime.evaluationManager().view(session)); if (method === 'POST' && action === 'evaluations') { const batch=await runtime.evaluationManager().plan(session,await body(request)); return json(response,{batch,session:store.publicSession(session)},201); } const evaluation=action.match(/^evaluations\/([a-f0-9-]+)\/(prepare|baseline|start|seal|adopt|finalize|retain|stop|report)$/); if (evaluation) { const manager=runtime.evaluationManager(); if (method==='GET' && evaluation[2]==='report') { const batch=manager.own(session,evaluation[1]); return json(response,manager.readReport(session,batch,manager.sample(batch,url.searchParams.get('sampleId')))); } if (method==='POST' && evaluation[2]!=='report') { const input=await body(request); if (!input || typeof input!=='object' || Array.isArray(input) || !/^[a-f0-9]{64}$/.test(input.fingerprint??'') || Object.keys(input).some(key=>!['fingerprint','sampleId'].includes(key))) throw workerConflict('评测操作需要原计划指纹,只接受固定样本身份。'); const batch=manager.own(session,evaluation[1],input.fingerprint); let result; if(evaluation[2]==='stop'){await runtime.stop(session.id);result=batch;} else if(evaluation[2]==='finalize')result=await manager.finalize(session,batch.id,input.fingerprint); else if(evaluation[2]==='retain')result=manager.retain(session,batch.id,input.fingerprint); else result=await manager[evaluation[2]](session,batch.id,input.fingerprint,input.sampleId); return json(response,{batch:result.batch??result,session:store.publicSession(session)},result.promise?202:200); } } if (method === 'GET' && action === 'collaborations') return json(response, runtime.workerManager().view(session)); if (method === 'POST' && action === 'collaborations') { const group = await runtime.workerManager().plan(session, await body(request)); return json(response, { group, session: store.publicSession(session) }, 201); } const collaboration = action.match(/^collaborations\/([a-f0-9-]+)\/(prepare|start|stop|collect|merge|finalize|discard|reconcile|acknowledge|collection|evidence)$/); if (collaboration) { const manager = runtime.workerManager(); if (method === 'GET' && ['collection', 'evidence'].includes(collaboration[2])) { const group = manager.own(session, collaboration[1], null, { current: false }); return json(response, collaboration[2] === 'collection' ? await manager.readCollection(session, group) : manager.readEvidence(session, group)); } if (method === 'POST' && !['collection', 'evidence'].includes(collaboration[2])) { const input = await body(request); if (Object.keys(input).some(key => !['fingerprint', 'workerId', 'evidenceSha256', 'retain'].includes(key))) throw workerConflict('协作操作字段无效,不能添加命令或模型配置。'); const group = manager.own(session, collaboration[1], input.fingerprint); if (group.evaluation && ['prepare','start','collect','merge','finalize'].includes(collaboration[2])) throw workerConflict('这个协作属于固定评测,请返回评测样本执行。'); let result; if (collaboration[2] === 'prepare') result = manager.prepare(session, group.id, input.fingerprint); else if (collaboration[2] === 'start') result = manager.start(session, group.id, input.fingerprint, input.workerId ?? null); else if (collaboration[2] === 'stop') { await runtime.stop(session.id); result = group; } else if (collaboration[2] === 'collect') result = manager.collect(session, group.id, input.fingerprint); else if (collaboration[2] === 'merge') result = manager.prepareMerge(session, group.id, input.fingerprint); else if (collaboration[2] === 'finalize') result = await manager.finalize(session, group.id, input.fingerprint); else if (collaboration[2] === 'discard') result = manager.discard(session, group.id, input.fingerprint); else if (collaboration[2] === 'reconcile') result = manager.reconcile(session, group.id, input.fingerprint); else result = await manager.acknowledge(session, group.id, input.fingerprint, input.evidenceSha256, input.retain === true); return json(response, { group: result.group ?? result, session: store.publicSession(session) }, result.promise ? 202 : 200); } } if (method === 'GET' && !action) return json(response, store.publicSession(session)); if (method === 'GET' && action === 'execution') return json(response, store.executionSnapshot(session)); if (method === 'GET' && action === 'engine-runs') return json(response, [...store.core.engine_run.values()].filter(job => job.sessionId === id).slice(-30).map(publicEngineRun)); const engineRun = action.match(/^engine-runs\/([a-f0-9-]+)\/(input|report|download)$/); if (method === 'GET' && engineRun) { const job = store.owned('engine_run', engineRun[1], id); const text = engineRun[2] === 'input' ? store.artifactStore.read(verifyEngineInput(store, session, job)) : originalEngineRun(store, session, job); if (engineRun[2] !== 'download') { const artifact = store.owned('artifact', engineRun[2] === 'input' ? job.inputArtifactId : job.reportArtifactId, id); const offset = cursorNumber(url.searchParams.get('offset')), limit = Math.min(16000, url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 4000); if (!limit || offset > text.length) throw Object.assign(new Error('原引擎记录的读取位置或页长超出范围。'), { status: 400 }); return json(response, { ...artifact, content: text.slice(offset, offset + limit), offset, totalCharacters: text.length, truncated: offset + limit < text.length }); } response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', ...(engineRun[2] === 'download' ? { 'Content-Disposition': 'attachment; filename="agent-workbench-engine-run-' + job.id + '.json"' } : {}) }); response.end(text); return; } if (method === 'GET' && action === 'mcp/jobs') return json(response, runtime.mcpRegistry().jobs(session)); if (method === 'POST' && action === 'mcp/probe') { const started = runtime.mcpRegistry().start(session, await body(request)); return json(response, { job: started.job, session: store.publicSession(session) }, 202); } if (method === 'POST' && action === 'mcp/stop') { await body(request); await runtime.mcpRegistry().stop(session.id); return json(response, store.publicSession(session)); } const mcpReport = action.match(/^mcp\/jobs\/([a-f0-9-]+)\/(report|input|evidence|acknowledge)$/i); if (mcpReport && method === 'GET' && mcpReport[2] === 'report') return json(response, runtime.mcpRegistry().report(session, mcpReport[1])); if (mcpReport && method === 'GET' && mcpReport[2] === 'input') return json(response, runtime.mcpRegistry().input(session, mcpReport[1])); if (mcpReport && method === 'GET' && mcpReport[2] === 'evidence') return json(response, runtime.mcpRegistry().evidence(session, mcpReport[1])); if (mcpReport && method === 'POST' && mcpReport[2] === 'acknowledge') { const input = await body(request); if (input.confirm !== true || typeof input.evidence_sha256 !== 'string' || Object.keys(input).some(key => !['confirm', 'evidence_sha256'].includes(key))) throw Object.assign(new Error('核对外部结果需要显式确认及当前记录指纹;状态仍保留unknown。'), { status: 400 }); return json(response, runtime.mcpRegistry().acknowledge(session, mcpReport[1], input.evidence_sha256)); } if (method === 'GET' && action === 'engines') { const manager = runtime.engineManager(); return json(response, { availability: manager.availability(), jobs: manager.jobs(session).map(publicEngineJob) }); } if (method === 'POST' && action === 'engines/jobs') { const started = runtime.engineManager().start(session, await body(request)); return json(response, { job: publicEngineJob(started.job), session: store.publicSession(session) }, 202); } if (method === 'POST' && action === 'engines/stop') { await runtime.engineManager().stop(id); return json(response, store.publicSession(session)); } const engineJob = action.match(/^engines\/jobs\/([a-f0-9-]+)(?:\/(report|download))?$/); if (method === 'GET' && engineJob) { const manager = runtime.engineManager(), job = store.owned('engine_job', engineJob[1], id); if (engineJob[2]) { if (!job.reportArtifactId) throw Object.assign(new Error('这次引擎检查尚未封存原记录,请等待检查结束。'), { status: 409 }); const text = manager.originalReport(session, job), artifact = store.owned('artifact', job.reportArtifactId, id); if (engineJob[2] === 'download') { response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'attachment; filename="agent-workbench-engine-' + job.id + '.json"' }); response.end(text); return; } const offset = cursorNumber(url.searchParams.get('offset')); const limit = Math.min(16000, url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 4000); if (!limit || offset > text.length) throw Object.assign(new Error('原记录的读取位置或页长超出范围。'), { status: 400 }); return json(response, { ...artifact, content: text.slice(offset, offset + limit), offset, totalCharacters: text.length, truncated: offset + limit < text.length }); } if (job.reportArtifactId) manager.originalReport(session, job); else manager.inputFor(session, job); return json(response, publicEngineJob(job)); } if (method === 'GET' && action === 'research') { const manager = runtime.researchManager(); return json(response, { availability: manager.availability(), targets: manager.targets(session), jobs: manager.jobs(session) }); } if (method === 'GET' && action === 'task-checkpoints') return json(response, runtime.checkpointManager().list(session)); if (method === 'POST' && action === 'task-checkpoints') { const input = await body(request); if (Object.keys(input).some(key => !['taskId', 'runId'].includes(key)) || input.taskId !== session.taskId || input.runId !== session.runId) throw Object.assign(new Error('检查点的原任务或运行已变化,请刷新当前任务。'), { status: 409 }); const checkpoint = await runtime.checkpointManager().create(session); return json(response, { checkpoint, session: store.publicSession(session) }, 201); } const checkpointMatch = action.match(/^task-checkpoints\/([a-f0-9-]+)(?:\/(resume))?$/i); if (checkpointMatch && method === 'GET' && !checkpointMatch[2]) return json(response, await runtime.checkpointManager().inspect(session, checkpointMatch[1])); if (checkpointMatch && method === 'POST' && checkpointMatch[2] === 'resume') { const input = await body(request); if (Object.keys(input).some(key => key !== 'sha256') || typeof input.sha256 !== 'string') throw Object.assign(new Error('检查点续接需要已核对的原SHA256。'), { status: 400 }); await runtime.checkpointManager().resume(session, checkpointMatch[1], input.sha256, runtime); return json(response, store.publicSession(session), 202); } if (method === 'GET' && action === 'task-plan') { const taskId = session.taskId, runId = session.runId; if (url.searchParams.has('taskId') && url.searchParams.get('taskId') !== taskId) throw Object.assign(new Error('所选任务已变化,请刷新当前任务计划。'), { status: 409 }); const plan = await runtime.taskPlanner().inspect(session); if (session.taskId !== taskId || session.runId !== runId) throw Object.assign(new Error('核对期间任务已变化,请刷新当前计划。'), { status: 409 }); return json(response, plan); } if (method === 'GET' && action === 'file-results') return json(response, runtime.fileResults().inspect(session, { path: url.searchParams.get('path') })); if (method === 'POST' && ['file-results', 'file-results/complete'].includes(action)) { const { taskId, runId, ...input } = await body(request); if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('任务或运行已切换,未修改其他任务成果。'), { status: 409 }); if (runtime.projectHasActivity(session.projectId)) throw Object.assign(new Error('工程仍有活动,请等待原操作结束后核对。'), { status: 409 }); await verifyWorkspaceProject(store, store.project(session.projectId)); if (taskId !== session.taskId || runId !== session.runId || runtime.projectHasActivity(session.projectId)) throw Object.assign(new Error('核对期间任务或工程活动已变化。'), { status: 409 }); if (action === 'file-results/complete') { if (Object.keys(input).length) throw Object.assign(new Error('结束任务不接受额外完成结论。'), { status: 400 }); await runtime.completeFileResults(session); } else runtime.fileResults().record(session, input, { source: 'user' }); return json(response, { session: store.publicSession(session), ...runtime.fileResults().inspect(session) }); } if (method === 'POST' && ['task-plans', 'task-proofs'].includes(action)) { const { taskId, runId, ...input } = await body(request); if (typeof taskId !== 'string' || typeof runId !== 'string' || taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('提交的任务或运行已变化,未修改其他任务计划。'), { status: 409 }); const manager = runtime.taskPlanner(); const result = action === 'task-plans' ? await manager.plan(session, input) : await manager.verify(session, input); const plan = await manager.inspect(session); if (session.taskId !== taskId || session.runId !== runId) throw Object.assign(new Error('保存结果属于原任务,请刷新所选任务。'), { status: 409 }); return json(response, { session: store.publicSession(session), plan, ...(action === 'task-proofs' ? { verification: result } : {}) }, action === 'task-plans' ? 201 : 200); } if (method === 'GET' && action === 'browser') { const manager = runtime.browserManager(), available = manager.availability(); return json(response, { availability: { status: available.status, engine: available.engine, playwrightVersion: available.playwrightVersion, message: available.message }, builds: manager.builds(store.project(session.projectId)), plans: manager.plans(session), jobs: manager.jobs(session) }); } if (method === 'POST' && action === 'browser-plans') { await runtime.browserManager().plan(session, await body(request)); return json(response, store.publicSession(session), 201); } if (method === 'POST' && action === 'browser-jobs') { const input = await body(request), started = runtime.browserManager().start(session, input.planId); if (started.reused) await started.promise; return json(response, store.publicSession(session), 202); } const browserJob = action.match(/^browser-jobs\/([a-f0-9-]+)(?:\/(stop|acknowledge|record))?$/); if (browserJob && method === 'POST' && ['stop', 'acknowledge'].includes(browserJob[2])) { const input = await body(request); store.owned('browser_job', browserJob[1], id); if (browserJob[2] === 'stop') await runtime.browserManager().stop(id, browserJob[1]); else runtime.browserManager().acknowledge(session, browserJob[1], input.fingerprint); return json(response, store.publicSession(session)); } if (browserJob && method === 'GET') { const job = store.owned('browser_job', browserJob[1], id); if (browserJob[2] === 'record') { verifyBrowserJob(store, session, job); const artifact = store.owned('artifact', job.resultArtifactId, id), text = store.artifactStore.read(artifact); const offset = cursorNumber(url.searchParams.get('offset')), limit = Math.min(16000, url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 8000); if (!limit || offset > text.length) throw Object.assign(new Error('浏览器原结果分页范围无效。'), { status: 400 }); return json(response, { ...artifact, content: text.slice(offset, offset + limit), offset, totalCharacters: text.length, truncated: offset + limit < text.length }); } if (!browserJob[2]) { if (job.resultArtifactId) verifyBrowserJob(store, session, job); else runtime.browserManager().planFor(session, job.planId); return json(response, job); } } const browserImage = action.match(/^browser-jobs\/([a-f0-9-]+)\/images\/([a-f0-9-]+)$/); if (method === 'GET' && browserImage) { const job = store.owned('browser_job', browserImage[1], id); verifyBrowserJob(store, session, job); const image = job.screenshots.find(value => value.artifactId === browserImage[2]); if (!image) throw Object.assign(new Error('图片不属于这次浏览器检查。'), { status: 404 }); const artifact = store.owned('artifact', image.artifactId, id); response.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', ...(url.searchParams.get('download') === '1' ? { 'Content-Disposition': 'attachment; filename="workbench-browser-' + job.id + '-' + image.label + '.png"' } : {}) }); response.end(store.artifactStore.readBytes(artifact)); return; } if (method === 'POST' && action === 'research/targets') { const target = await runtime.researchManager().register(session, await body(request)); return json(response, { target, session: store.publicSession(session) }, 201); } if (method === 'POST' && action === 'research/jobs') { const input = await body(request); if (input.refresh !== undefined && typeof input.refresh !== 'boolean') throw Object.assign(new Error('重新分析选项需要布尔值。'), { status: 400 }); const started = runtime.researchManager().start(session, input.targetId, input.operation, { source: 'user', refresh: input.refresh === true }); return json(response, { job: started.job, session: store.publicSession(session) }, 202); } if (method === 'POST' && action === 'research/stop') { await runtime.researchManager().stop(id); return json(response, store.publicSession(session)); } const researchJob = action.match(/^research\/jobs\/([a-f0-9-]+)(?:\/(evidence|raw|download))?$/); if (method === 'GET' && researchJob) { const manager = runtime.researchManager(), job = store.owned('research_job', researchJob[1], id); if (!researchJob[2]) return json(response, job); if (researchJob[2] === 'evidence') return json(response, manager.readEvidence(session, job.id, { pointer: url.searchParams.get('pointer') ?? '/normalized_result', offset: cursorNumber(url.searchParams.get('offset')), limit: Math.min(16000, Math.max(1, cursorNumber(url.searchParams.get('limit')) || 4000)), maximumMessageBytes: 100000 })); if (researchJob[2] === 'raw') { const text = manager.originalDocument(session, job, 'raw'), offset = cursorNumber(url.searchParams.get('offset')), limit = Math.min(16000, Math.max(1, cursorNumber(url.searchParams.get('limit')) || 4000)); return json(response, { content: text.slice(offset, offset + limit), offset, next_offset: Math.min(text.length, offset + limit), total_characters: text.length, truncated: offset + limit < text.length, source_document_sha256: job.raw.documentSha256 }); } const kind = url.searchParams.get('kind') ?? 'bundle', original = manager.originalDocument(session, job, kind); response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'attachment; filename="agent-workbench-rea-' + job.id + '.json"' }); response.end(original); return; } if (method === 'GET' && action === 'workspaces') return json(response, store.executionSnapshot(session).workspaces); if (method === 'POST' && action === 'workspaces') { const input = await body(request); return json(response, await runtime.workspaceManager().prepare(session, input.label), 201); } const workspace = action.match(/^workspaces\/([a-f0-9-]+)(?:\/(create|reconcile|acknowledge|discard|open|stop))?$/); if (workspace && method === 'GET' && !workspace[2]) return json(response, store.owned('workspace', workspace[1], id)); if (workspace && method === 'POST' && workspace[2]) { const input = await body(request), record = store.owned('workspace', workspace[1], id); if (workspace[2] === 'open') { if (record.status !== 'ready') throw Object.assign(new Error('工作区尚未完整确认,请先核对创建结果。'), { status: 409 }); const project = store.project(record.childProjectId), child = store.session(record.childSessionId); await verifyWorkspaceProject(store, project); if (child.projectId !== project.id || child.archived) throw Object.assign(new Error('原工作区会话已归档或归属变化,请从项目栏打开该项目的当前会话。'), { status: 409 }); return json(response, { workspace: record, project, session: store.publicSession(child) }); } const manager = runtime.workspaceManager(); if (workspace[2] === 'create') await manager.start(session, record.id, input.fingerprint); else if (workspace[2] === 'reconcile') await manager.reconcile(session, record.id, input.fingerprint); else if (workspace[2] === 'acknowledge') await manager.acknowledge(session, record.id, input.fingerprint, input.observationFingerprint); else if (workspace[2] === 'discard') manager.discard(session, record.id, input.fingerprint); else await manager.stop(id); return json(response, record, workspace[2] === 'create' ? 202 : 200); } if (method === 'GET' && action === 'context-plans') { const runId = url.searchParams.get('run'); if (runId) store.owned('run', runId, id); return json(response, [...store.core.context_plan.values()].filter(plan => plan.sessionId === id && (!runId || plan.runId === runId)).slice(-100)); } const contextPlan = action.match(/^context-plans\/([a-f0-9-]+)(?:\/(history))?$/); if (method === 'GET' && contextPlan) { const plan = store.owned('context_plan', contextPlan[1], id); if (!contextPlan[2]) return json(response, plan); if (!plan.historyIndexArtifactId) return json(response, { planId: plan.id, groups: [], offset: 0, totalGroups: 0, truncated: false }); const artifact = store.owned('artifact', plan.historyIndexArtifactId, id); if (artifact.sha256 !== plan.historyIndexSha256) throw new Error('历史索引身份与请求计划不一致。'); const index = JSON.parse(store.artifactStore.read(artifact)); if (index.kind !== 'request-history-index' || index.sessionId !== id || index.projectId !== session.projectId || index.taskId !== plan.taskId) throw new Error('历史索引不属于这个任务。'); const offset = cursorNumber(url.searchParams.get('offset')), limit = Math.min(50, Math.max(1, cursorNumber(url.searchParams.get('limit')) || 12)); return json(response, { planId: plan.id, groups: index.archivedGroups.slice(offset, offset + limit), offset, totalGroups: index.archivedGroups.length, truncated: offset + limit < index.archivedGroups.length }); } if (method === 'POST' && action === 'change-sets') { const input = await body(request); await runtime.changeSetManager().prepare(session, input.changeIds); return json(response, store.publicSession(session), 201); } const changeSet = action.match(/^change-sets\/([a-f0-9-]+)(?:\/(apply|reconcile|rollback|discard|acknowledge|stop))?$/); if (changeSet && method === 'GET' && !changeSet[2]) return json(response, store.owned('change_set', changeSet[1], id)); if (changeSet && method === 'POST' && changeSet[2]) { const input = await body(request), manager = runtime.changeSetManager(); if (changeSet[2] === 'apply') await manager.start(session, changeSet[1], input.fingerprint); else if (changeSet[2] === 'reconcile') await manager.reconcile(session, changeSet[1]); else if (changeSet[2] === 'rollback') await manager.rollback(session, changeSet[1], input.fingerprint); else if (changeSet[2] === 'discard') manager.discard(session, changeSet[1], input.fingerprint); else if (changeSet[2] === 'acknowledge') manager.acknowledge(session, changeSet[1], input.fingerprint, input.observationFingerprint); else { store.owned('change_set', changeSet[1], id); await manager.stop(id); } return json(response, store.publicSession(session), changeSet[2] === 'apply' ? 202 : 200); } if (method === 'POST' && action === 'delivery-plans') { const input = await body(request); await runtime.gitDelivery().plan(session, input); return json(response, store.publicSession(session), 201); } if (method === 'POST' && action === 'delivery-jobs') { const input = await body(request); await runtime.gitDelivery().start(session, input.planId); return json(response, store.publicSession(session), 202); } const discardedDeliveryPlan = action.match(/^delivery-plans\/([a-f0-9-]+)\/discard$/); if (method === 'POST' && discardedDeliveryPlan) { await body(request); runtime.gitDelivery().discardPlan(session, discardedDeliveryPlan[1]); return json(response, store.publicSession(session)); } const deliveryJob = action.match(/^delivery-jobs\/([a-f0-9-]+)(?:\/(stop|reconcile))?$/); if (deliveryJob && method === 'GET' && !deliveryJob[2]) return json(response, store.owned('delivery_job', deliveryJob[1], id)); if (deliveryJob && method === 'POST' && deliveryJob[2]) { await body(request); if (deliveryJob[2] === 'stop') await runtime.gitDelivery().stop(id, deliveryJob[1]); else await runtime.gitDelivery().reconcile(session, deliveryJob[1]); return json(response, store.publicSession(session)); } if (method === 'POST' && action === 'delivery-reports') { await body(request); await runtime.gitDelivery().report(session); return json(response, store.publicSession(session), 201); } if (method === 'GET' && action === 'browsing') return json(response, runtime.browsingManager().snapshot(session)); const browsingImage = action.match(/^browsing\/observations\/([a-f0-9-]+)\/image$/); if (method === 'GET' && browsingImage) { const observation = store.owned('browsing_observation', browsingImage[1], id), artifact = store.owned('artifact', observation.screenshotArtifactId, id); if (artifact.kind !== 'browsing-screenshot' || artifact.sha256 !== observation.screenshotSha256) throw new Error('原页面截图身份无法核对。'); const bytes = store.artifactStore.readBytes(artifact); response.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': bytes.length, 'Cache-Control': 'no-store', 'X-Content-SHA256': artifact.sha256 }); return response.end(bytes); } if (method === 'POST' && action === 'browsing/tabs') { runtime.workbenchOrigin = 'http://127.0.0.1:' + actualPort; runtime.browsingManager().workbenchOrigin = runtime.workbenchOrigin; await runtime.browsingManager().open(session, await body(request)); return json(response, store.publicSession(session), 201); } const browsingTab = action.match(/^browsing\/tabs\/([a-f0-9-]+)\/(observe|act|close|clear)$/); if (method === 'POST' && browsingTab) { const input = await body(request), manager = runtime.browsingManager(), tabId = browsingTab[1]; if (browsingTab[2] === 'observe') await manager.observe(session, tabId); else if (browsingTab[2] === 'act') { const { approved, ...operation } = input; await manager.act(session, tabId, operation, { approved }); } else { if (input.approved !== true) throw Object.assign(new Error('关闭/撤销需要明确确认。'), { status: 400 }); await manager.close(session, tabId, { clear: browsingTab[2] === 'clear' }); } return json(response, store.publicSession(session)); } const browsingAck = action.match(/^browsing\/actions\/([a-f0-9-]+)\/acknowledge$/); if (method === 'POST' && browsingAck) { const input = await body(request); if (input.approved !== true) throw Object.assign(new Error('请先核对原页面和回执,再明确保留未知结果。'), { status: 400 }); runtime.browsingManager().acknowledge(session, browsingAck[1]); return json(response, store.publicSession(session)); } if (method === 'POST' && action === 'preview-plans') { await runtime.previewManager().plan(session, await body(request)); return json(response, store.publicSession(session), 201); } if (method === 'POST' && action === 'preview-jobs') { const input = await body(request); if (!input || Array.isArray(input) || Object.keys(input).some(key => !['planId','fingerprint','approved'].includes(key))) throw Object.assign(new Error('预览启动只接受原计划身份和明确审批。'), { status: 400 }); await runtime.previewManager().start(session, input.planId, input.fingerprint, { approved: input.approved }); return json(response, store.publicSession(session), 202); } const previewJob = action.match(/^preview-jobs\/([a-f0-9-]+)\/(stop|reconcile)$/); if (method === 'POST' && previewJob) { const input = await body(request), manager = runtime.previewManager(); store.owned('preview_job', previewJob[1], id); if (previewJob[2] === 'stop') await manager.stop(id, previewJob[1]); else await manager.reconcile(session, previewJob[1], input.fingerprint); return json(response, store.publicSession(session)); } if (method === 'POST' && action === 'environment-diagnostics') { await body(request); await runtime.environmentManager().diagnose(session); return json(response,store.publicSession(session),201); } if (method === 'POST' && action === 'environment-plans') { await runtime.environmentManager().plan(session,await body(request)); return json(response,store.publicSession(session),201); } if (method === 'POST' && action === 'environment-jobs') { const input=await body(request); if(!input || Array.isArray(input) || Object.keys(input).some(key=>!['planId','fingerprint','approved'].includes(key))) throw Object.assign(new Error('依赖执行只接受原计划身份与明确审批。'),{status:400}); await runtime.environmentManager().start(session,input.planId,input.fingerprint,{approved:input.approved}); return json(response,store.publicSession(session),202); } const environmentJob=action.match(/^environment-jobs\/([a-f0-9-]+)\/(stop|reconcile)$/); if(method==='POST' && environmentJob) { const input=await body(request),manager=runtime.environmentManager(); if(environmentJob[2]==='stop')await manager.stop(session.id,environmentJob[1]); else await manager.reconcile(session,environmentJob[1],input.fingerprint); return json(response,store.publicSession(session)); } if (method === 'POST' && action === 'check-plans') { const input = await body(request); if (runtime.isActive(id)) throw Object.assign(new Error('任务或检查正在执行,请等待结束后再准备检查。'), { status: 409 }); await runtime.checkRunner().plan(session, input.names); return json(response, store.publicSession(session), 201); } if (method === 'POST' && action === 'check-jobs') { const input = await body(request); await runtime.checkRunner().start(session, input.planId); return json(response, store.publicSession(session), 202); } const checkJob = action.match(/^check-jobs\/([a-f0-9-]+)(?:\/(stop))?$/); if (checkJob && method === 'GET' && !checkJob[2]) return json(response, store.owned('check_job', checkJob[1], id)); if (checkJob && method === 'POST' && checkJob[2] === 'stop') { await body(request); await runtime.checkRunner().stop(id, checkJob[1]); return json(response, store.publicSession(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"' }); response.end(JSON.stringify({ schemaVersion: 1, executionSchemaVersion: 1, exportedAt: new Date().toISOString(), project: store.project(session.projectId), session, execution: store.executionSnapshot(session) }, null, 2)); return; } if (method === 'POST' && action === 'messages') { const input = await body(request); runtime.start(id, input.content,false,{attachmentIds:input.attachmentIds??[]}); return json(response, store.publicSession(session), 202); } if (method === 'POST' && action === 'resume') { const input = await body(request); runtime.resume(id, input.content); return json(response, store.publicSession(session), 202); } if(method==='POST'&&action==='resume-preview')return json(response,runtime.budgetResumes().prepare(session,await body(request)),201); if(method==='POST'&&action==='resume-budget'){runtime.resumeBudget(id,await body(request));return json(response,store.publicSession(session),202);} if (method === 'POST' && action === 'continue-reviewed') { await body(request); runtime.continueReviewed(id); return json(response, store.publicSession(session), 202); } if (method === 'POST' && action === 'stop') { await body(request); await runtime.stop(id); return json(response, store.publicSession(session)); } if (method === 'POST' && action === 'archive') { await body(request); if (runtime.isActive(id)) throw new Error('请先停止执行中的任务。'); session.archived = true; store.save(session); return json(response, { archived: true }); } const approval = action.match(/^approvals\/([a-f0-9-]+)$/); if (method === 'POST' && approval) { const input = await body(request); runtime.decide(id, approval[1], input.allow === true); return json(response, store.publicSession(session)); } const change = action.match(/^changes\/([a-f0-9-]+)\/(apply|reject)$/); if (method === 'POST' && change) { await body(request); if (runtime.projectHasActivity(session.projectId)) throw Object.assign(new Error('项目正在执行任务或检查,请等待结束或停止后再审查文件改动。'), { status: 409 }); assertWorkspacesResolved(store, session.projectId, { includePrepared: true }); await verifyWorkspaceProject(store, store.project(session.projectId)); if (change[2] === 'apply') applyChange(store, session, change[1]); else { const item = session.changes.find(candidate => candidate.id === change[1]); if (!item || !['pending', 'conflict'].includes(item.status)) throw new Error('改动无法撤回。'); assertProposalUnsealed(store, item); item.status = 'rejected'; if (session.status === 'needs_review' && !session.changes.some(candidate => ['pending', 'conflict'].includes(candidate.status))) session.status = 'completed'; store.save(session); } return json(response, store.publicSession(session)); } if (method === 'POST' && ['proposals', 'patch-proposals'].includes(action)) { const input = await body(request); if (runtime.workers?.projectActive(session.projectId) || runtime.checks?.projectActive(session.projectId) || runtime.deliveries?.projectActive(session.projectId) || runtime.changeSets?.projectActive(session.projectId) || runtime.workspaces?.projectActive(session.projectId)) throw Object.assign(new Error('协作、工程检查、Git交付、文件批次或工作区正在执行,请等待结束后再编辑文件。'), { status: 409 }); assertWorkspacesResolved(store, session.projectId, { includePrepared: true }); await verifyWorkspaceProject(store, store.project(session.projectId)); if (action === 'patch-proposals') proposePatch(store, session, input); else proposeFile(store, session, input); return json(response, store.publicSession(session), 201); } } if (method === 'POST' && route === '/api/config') { const input = await body(request); if (runtime.hasActivity()) throw Object.assign(new Error('请先停止正在运行的任务或检查,再改变模型连接。'), { status: 409 }); if (!['demo', 'compatible'].includes(input.mode)) throw new Error('请选择有效运行模式。'); const config = { mode: input.mode, baseUrl: String(input.baseUrl || '').trim(), model: String(input.model || '').trim(), 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))), ...validateModelWaitSettings(input, store.config), 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') && (typeof input.apiKey !== 'string' || input.apiKey.length > 16000)) throw new Error('模型凭据格式无效。'); if (provider.hub) provider.hub.select({ type: 'legacy' }, config); else store.saveConfig(config); if (Object.hasOwn(input, 'apiKey')) provider.setKey(input.apiKey); return json(response, { ...store.config, hasKey: provider.hasKey() }); } if (method === 'POST' && route === '/api/config/models') { const input = await body(request); if (runtime.hasActivity()) throw Object.assign(new Error('请先停止正在运行的任务或检查,再测试新的模型连接。'), { status: 409 }); const config = { ...store.config, baseUrl: String(input.baseUrl || store.config.baseUrl), mode: 'demo' }; return json(response, { models: await provider.models(config, Object.hasOwn(input, 'apiKey') ? String(input.apiKey).trim() : provider.apiKey) }); } if (method === 'POST' && route === '/api/config/test') { const input = await body(request); if (runtime.hasActivity()) throw Object.assign(new Error('请先停止正在运行的任务或检查,再测试模型连接。'), { status: 409 }); const config = { ...store.config, baseUrl: String(input.baseUrl || store.config.baseUrl), model: String(input.model || store.config.model), mode: 'compatible' }; provider.validate(config); const startedAt = Date.now(); const native = nativeParameterSettings('chat-completions', config.nativeParameters ?? {}, config.outputTokenField); const result = await provider.request(config, '/chat/completions', { model: config.model, stream: false, [native.outputTokenField]: 64, ...native.nativeParameters, messages: [{ role: 'user', content: 'Connection check. Reply with OK.' }] }, undefined, Object.hasOwn(input, 'apiKey') ? String(input.apiKey).trim() : provider.apiKey); if (!result.choices?.[0]?.message) throw new Error('模型服务响应中缺少 choices[0].message。'); return json(response, { ok: true, model: config.model, durationMs: Date.now() - startedAt, attempts: provider.lastRequest?.attempts ?? 1 }); } if (method === 'GET' && route === '/api/research') return json(response, research.map(({ file, ...item }) => item)); const report = route.match(/^\/api\/research\/([a-z]+)$/); if (method === 'GET' && report) { const document = research.find(item => item.id === report[1]); if (!document) throw new Error('研究报告不存在。'); const file = path.join(appDirectory, 'docs', document.file); if (!fs.existsSync(file)) throw Object.assign(new Error('这份原研究报告缺失,请核对完整发行文件。'), { status: 404 }); const bytes = fs.readFileSync(file); return json(response, { title: document.title, content: bytes.toString('utf8'), sha256: createHash('sha256').update(bytes).digest('hex') }); } if (method === 'POST' && route === '/api/shutdown') { await body(request); const authority = host(), identity = authority.identity(); const result = await authority.stop({ ...identity, confirmation: 'stop-owned-host' }); json(response, result); setTimeout(shutdown, 100); return; } if (route.startsWith('/api/')) return json(response, { error: '接口不存在。' }, 404); if (method !== 'GET' && method !== 'HEAD') return json(response, { error: '请求方法不支持。' }, 405); const staticRoot = path.join(appDirectory, 'dist-client'); const requested = decodeURIComponent(route).replace(/^\/+/, ''); let file = path.resolve(staticRoot, requested || 'index.html'); if (!file.startsWith(staticRoot + path.sep)) throw new Error('文件路径无效。'); if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) { if (path.extname(requested)) return json(response, { error: '资源不存在。' }, 404); file = path.join(staticRoot, 'index.html'); } if (!fs.existsSync(file)) return json(response, { error: '请先构建工作台界面。' }, 503); const mime = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.woff2': 'font/woff2' }; response.writeHead(200, { 'Content-Type': mime[path.extname(file)] || 'application/octet-stream', 'X-Content-Type-Options': 'nosniff', 'Cache-Control': file.endsWith('index.html') ? 'no-store' : 'public, max-age=3600' }); if (method === 'HEAD') response.end(); else fs.createReadStream(file).pipe(response); } catch (error) { if (!response.headersSent) json(response, { error: provider.redact(error.message ?? String(error)), diagnostic: error.diagnostic ?? null }, error.status ?? (error.diagnostic ? 502 : 400)); else response.destroy(); } }; }