import fs from 'node:fs'; 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'; 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, server, 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(); 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: 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: { workspaces: 'owned-git-worktree-and-explicit-recovery', gitReview: 'durable-confirmation-boundary', requestContext: 'bounded-whole-request-and-history-artifacts', 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-script-jobs', projectInspection: 'bounded-source-and-git', 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(), 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' }); 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')); 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(text); return; } 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 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); 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 (method === 'GET' && !action) return json(response, store.publicSession(session)); if (method === 'GET' && action === 'execution') return json(response, store.executionSnapshot(session)); 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 === '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); 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 === '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.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))), 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); 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.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 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(); } }; }