chore: baseline Agent Workbench 1.0.0

This commit is contained in:
Agent Workbench Dev
2026-10-29 11:23:43 +08:00
commit bac87da23e
167 changed files with 30172 additions and 0 deletions
+213
View File
@@ -0,0 +1,213 @@
import fs from 'node:fs';
import path from 'node:path';
import { listFiles, readText, proposeFile, applyChange } from './files.mjs';
import { APP_VERSION, executionEnvironment, sessionSnapshot } from './diagnostics.mjs';
export function createRequestHandler({ appDirectory, store, provider, runtime, token, clients, started, getPort, exampleProject, shutdown }) {
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: '参数校验、队列、并发安全与权限判断。' },
];
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) {
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 > 2 * 1024 * 1024) throw Object.assign(new Error('请求超过 2 MB。'), { 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 {
const actualPort = getPort();
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: true, uptimeMs: Date.now() - started });
if (method === 'GET' && route === '/api/bootstrap') return json(response, {
token, version: APP_VERSION, config: { ...store.config, hasKey: provider.hasKey() },
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' },
});
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 },
session: session ? sessionSnapshot(session, store.project(session.projectId), store.config, value => provider.redact(value)) : null,
});
}
if (method === 'GET' && route === '/api/events') {
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 heartbeat = setInterval(() => response.write(': heartbeat\n\n'), 20000);
request.on('close', () => { clearInterval(heartbeat); clients.delete(response); });
return;
}
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 projectMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/(files|file)$/);
if (method === 'GET' && projectMatch) {
const project = store.project(projectMatch[1]);
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);
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 (method === 'GET' && !action) return json(response, store.publicSession(session));
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, exportedAt: new Date().toISOString(), project: store.project(session.projectId), session }, null, 2));
return;
}
if (method === 'POST' && action === 'messages') {
const input = await body(request);
runtime.start(id, input.content);
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 === '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.isActive(id)) throw Object.assign(new Error('任务正在执行,请等待结束或停止后再审查文件改动。'), { status: 409 });
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('改动无法撤回。');
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' && action === 'proposals') {
const input = await body(request);
proposeFile(store, session, input);
return json(response, store.publicSession(session), 201);
}
}
if (method === 'POST' && route === '/api/config') {
const input = await body(request);
if (runtime.active.size) 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))),
};
provider.validate(config);
if (Object.hasOwn(input, 'apiKey')) provider.setKey(input.apiKey);
store.saveConfig(config);
return json(response, { ...store.config, hasKey: provider.hasKey() });
}
if (method === 'POST' && route === '/api/config/models') {
const input = await body(request);
if (runtime.active.size) 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.active.size) 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 result = await provider.request(config, '/chat/completions', { model: config.model, stream: false, max_tokens: 64,
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);
return json(response, { title: document.title, content: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '这份报告正在整理,完成后会保存在产品的 docs 目录。' });
}
if (method === 'POST' && route === '/api/shutdown') {
await body(request); json(response, { closing: true });
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();
}
};
}