agent-bridge-service 0.2.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +122 -140
  2. package/README.md +526 -36
  3. package/README.zh-CN.md +457 -34
  4. package/assets/agent-icons/agy.svg +27 -0
  5. package/dist/adapters/acp-auth.js +51 -0
  6. package/dist/adapters/acp-codebuddy.js +507 -0
  7. package/dist/adapters/agent-adapters.js +470 -46
  8. package/dist/adapters/claude-stream.js +159 -0
  9. package/dist/adapters/codex-app-server.js +365 -0
  10. package/dist/adapters/host-env.js +48 -0
  11. package/dist/adapters/mcp-elicitation.js +148 -0
  12. package/dist/adapters/mcp-host.js +70 -0
  13. package/dist/adapters/step-parsers.js +583 -0
  14. package/dist/app/bootstrap.js +163 -74
  15. package/dist/app/claude-resident.js +204 -0
  16. package/dist/app/conversation.js +639 -0
  17. package/dist/app/service-gate.js +1 -1
  18. package/dist/app/session.js +426 -14
  19. package/dist/app/task-dispatch.js +883 -7
  20. package/dist/app/task-registry.js +168 -0
  21. package/dist/cli/dispatch.js +4 -0
  22. package/dist/cli/flags.js +11 -0
  23. package/dist/cli/help.js +26 -7
  24. package/dist/cli/panel.js +334 -0
  25. package/dist/cli/render.js +2 -0
  26. package/dist/commands/approvals.js +80 -0
  27. package/dist/commands/connect.js +124 -4
  28. package/dist/commands/daemon-service.js +81 -0
  29. package/dist/commands/daemon.js +269 -6
  30. package/dist/commands/logout.js +13 -10
  31. package/dist/commands/serve.js +100 -12
  32. package/dist/commands/sessions.js +106 -0
  33. package/dist/core/ansi.js +5 -0
  34. package/dist/core/artifact-extract.js +158 -0
  35. package/dist/core/artifact-transfer.js +583 -0
  36. package/dist/core/device-identity.js +22 -0
  37. package/dist/core/emitter.js +50 -8
  38. package/dist/core/errors.js +43 -0
  39. package/dist/core/form-schema.js +72 -0
  40. package/dist/core/interaction-broker.js +440 -0
  41. package/dist/core/interaction-url.js +63 -0
  42. package/dist/core/partial-messages.js +99 -0
  43. package/dist/core/permission-ledger.js +146 -0
  44. package/dist/core/permission-policy.js +88 -0
  45. package/dist/core/port-fallback.js +22 -0
  46. package/dist/core/redact.js +13 -0
  47. package/dist/core/scan.js +12 -7
  48. package/dist/core/session-store.js +1632 -0
  49. package/dist/core/task-supervisor.js +968 -30
  50. package/dist/infra/atomic-file.js +111 -0
  51. package/dist/infra/audit.js +7 -0
  52. package/dist/infra/auth.js +143 -40
  53. package/dist/infra/config.js +511 -72
  54. package/dist/infra/device-identity-store.js +87 -0
  55. package/dist/infra/jwt.js +149 -0
  56. package/dist/infra/profile-lock.js +295 -0
  57. package/dist/infra/proxy-env.js +81 -0
  58. package/dist/infra/service-token.js +25 -4
  59. package/dist/protocol.js +298 -2
  60. package/dist/transport/a2a-mapping.js +206 -0
  61. package/dist/transport/acp-gateway-mapping.js +186 -0
  62. package/dist/transport/bridge-client.js +31 -22
  63. package/dist/transport/control-plane-page.js +820 -0
  64. package/dist/transport/control-plane-sessions-page.js +90 -0
  65. package/dist/transport/control-plane.js +935 -71
  66. package/dist/transport/gateway.js +1023 -0
  67. package/dist/transport/office-preview.js +154 -0
  68. package/package.json +6 -3
  69. package/assets/agent-icons/gemini.svg +0 -1
@@ -15,14 +15,20 @@
15
15
  * 零新增运行时依赖:`node:http` 手写路由。
16
16
  */
17
17
  import { createServer } from 'node:http';
18
- import { randomBytes } from 'node:crypto';
18
+ import { randomBytes, randomUUID } from 'node:crypto';
19
+ import { createReadStream, readFileSync, statSync } from 'node:fs';
20
+ import { extname, resolve as resolvePath, sep } from 'node:path';
21
+ import { hasAnsi } from '../core/ansi.js';
19
22
  import { isBridgeErrorCode, toProblem } from '../core/errors.js';
23
+ import { DASHBOARD_HTML } from './control-plane-page.js';
24
+ import { SESSIONS_HTML } from './control-plane-sessions-page.js';
25
+ import { OFFICE_MIME_TYPES, renderOfficePreview } from './office-preview.js';
26
+ import { createGatewayHandlers } from './gateway.js';
20
27
  import { verifyServiceToken, } from '../infra/service-token.js';
21
28
  import { writeAudit } from '../infra/audit.js';
29
+ import { DEFAULT_TENANT, fingerprintIdempotency } from '../core/session-store.js';
22
30
  /** 请求体上限:控制面只收任务参数,1 MB 足够,超了直接 413 */
23
31
  const MAX_BODY_BYTES = 1024 * 1024;
24
- /** 幂等键上限(有界,插入顺序淘汰) */
25
- const MAX_IDEMPOTENCY_KEYS = 1000;
26
32
  const json = (res, status, payload) => {
27
33
  const body = JSON.stringify(payload);
28
34
  res.writeHead(status, {
@@ -68,7 +74,7 @@ function readBody(req) {
68
74
  const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
69
75
  /** 对外视图:句柄(含 Promise / 函数)不进 JSON */
70
76
  const view = (r) => {
71
- const { handle: _handle, ...rest } = r;
77
+ const { handle: _handle, tenantId: _tenantId, ...rest } = r;
72
78
  return rest;
73
79
  };
74
80
  export async function startControlPlane(settings, deps) {
@@ -81,7 +87,15 @@ export async function startControlPlane(settings, deps) {
81
87
  /** 任务台账:控制面下发的 + 平台下发的(同一进程下都经 emitter,视图统一) */
82
88
  const records = new Map();
83
89
  const order = [];
84
- const idempotency = new Map();
90
+ const tenantOf = (ctx) => ctx.tenantId ?? DEFAULT_TENANT;
91
+ const visibleRecord = (ctx, id) => {
92
+ const rec = records.get(id);
93
+ if (!rec)
94
+ return undefined;
95
+ return (rec.tenantId ?? DEFAULT_TENANT) === tenantOf(ctx) ? rec : undefined;
96
+ };
97
+ const visibleRegistry = (ctx, id) => deps.registry.get(id, tenantOf(ctx));
98
+ const artifactsOf = (ctx) => deps.artifactsForTenant?.(tenantOf(ctx)) ?? deps.artifacts;
85
99
  const remember = (r) => {
86
100
  if (!records.has(r.taskId))
87
101
  order.push(r.taskId);
@@ -96,6 +110,7 @@ export async function startControlPlane(settings, deps) {
96
110
  const base = existing ??
97
111
  {
98
112
  taskId: m.taskId,
113
+ tenantId: deps.registry.get(m.taskId)?.tenantId ?? DEFAULT_TENANT,
99
114
  agentType: 'unknown',
100
115
  cwd: '',
101
116
  state: m.status,
@@ -118,12 +133,83 @@ export async function startControlPlane(settings, deps) {
118
133
  updatedAt: new Date().toISOString(),
119
134
  });
120
135
  });
136
+ // ---------- A2A / ACP 网关(add-a2a-acp-gateway;默认关闭) ----------
137
+ // 网关是本控制面上的一个协议表面:listen 红线限定本文件,回环绑定/纵深防御天然生效。
138
+ // baseUrl 惰性求值:port=0 自动分配时 listen 回调里才能拿到真实端口。
139
+ let actualBaseUrl = `http://${settings.host}:${settings.port}`;
140
+ const gatewayA2aEnabled = settings.gateway?.enabled === true && settings.gateway.a2a !== false;
141
+ const gatewayAcpEnabled = settings.gateway?.enabled === true && settings.gateway.acp !== false;
142
+ const gateway = gatewayA2aEnabled || gatewayAcpEnabled
143
+ ? createGatewayHandlers({
144
+ store: deps.store,
145
+ registry: deps.registry,
146
+ emitter: deps.emitter,
147
+ version: deps.version,
148
+ log: deps.log,
149
+ baseUrl: () => actualBaseUrl,
150
+ agents: deps.gatewayAgents ?? [],
151
+ // ACP 交互响应通道:与 /v1/interactions/{id}:respond 同一条 dispatch 路径
152
+ respondInteraction: deps.respondInteraction,
153
+ // conversation 编排(add-acp-session-memory):ACP session/prompt 的多轮续接
154
+ conversation: deps.conversation,
155
+ // 网关与 POST /v1/tasks、:cancel 共用同一条编排(createTaskCore / cancelTaskCore):
156
+ // 并发上限、权限策略、幂等语义、上行出口单一真源
157
+ ops: {
158
+ createTask: (input) => {
159
+ const { record, replay } = createTaskCore({
160
+ tenantId: input.tenantId,
161
+ agentType: input.agentType,
162
+ cwd: input.cwd,
163
+ args: [],
164
+ prompt: input.prompt,
165
+ timeoutMs: input.timeoutMs,
166
+ allowInteractive: input.allowInteractive,
167
+ requestedBy: input.requestedBy,
168
+ idempotencyKey: input.idempotencyKey,
169
+ idempotencyFingerprint: input.idempotencyFingerprint,
170
+ // 网关的幂等域独立于 HTTP(A2A messageId / ACP 会话与 HTTP Idempotency-Key 不互撞)
171
+ idempotencyScope: 'gateway:task:create',
172
+ });
173
+ return { taskId: record.taskId, replay };
174
+ },
175
+ // 惰性转发:cancelTaskCore 在下方才定义,闭包引用在请求期才求值
176
+ cancelTask: (id, tenantId) => cancelTaskCore(id, tenantId),
177
+ },
178
+ })
179
+ : undefined;
180
+ /**
181
+ * 鉴权:`scope` 传数组表示**任一命中即可**(如 `['session:read','task:read']`)。
182
+ * 1.0 新增的更窄 scope 都按这个方式接入,1.0 之前签发的粗粒度令牌不会当场失效。
183
+ */
121
184
  const authorize = (ctx, scope) => {
122
185
  if (!requireToken)
123
186
  return true;
187
+ const required = Array.isArray(scope) ? scope : [scope];
188
+ const label = required.join(' 或 ');
189
+ if (ctx.principal) {
190
+ const allowed = ctx.principal.scopes.includes('*') || required.some((s) => ctx.principal?.scopes.includes(s));
191
+ writeAudit({
192
+ at: new Date().toISOString(),
193
+ action: 'control_plane',
194
+ outcome: allowed ? 'allowed' : 'denied',
195
+ purpose: `${ctx.req.method} ${ctx.url.pathname}`,
196
+ serviceId: `jwt:${ctx.principal.subject}`,
197
+ scopes: ctx.principal.scopes,
198
+ });
199
+ if (!allowed) {
200
+ problem(ctx.res, 403, 'insufficient_scope', `JWT 缺少 scope: ${label}`);
201
+ return false;
202
+ }
203
+ return true;
204
+ }
124
205
  const header = ctx.req.headers['authorization'];
125
206
  const raw = Array.isArray(header) ? header[0] : header;
126
- const token = raw?.startsWith('Bearer ') ? raw.slice(7).trim() : undefined;
207
+ let token = raw?.startsWith('Bearer ') ? raw.slice(7).trim() : undefined;
208
+ // EventSource 无法自定义请求头:回环面板允许 ?token= 兜底(仅本机回环,文档写明勿外发)
209
+ if (!token) {
210
+ const q = ctx.url.searchParams.get('token');
211
+ token = q && q.trim() ? q.trim() : undefined;
212
+ }
127
213
  const res = verify(token, scope);
128
214
  const at = new Date().toISOString();
129
215
  if (res.ok) {
@@ -153,20 +239,59 @@ export async function startControlPlane(settings, deps) {
153
239
  serviceId: res.record?.id,
154
240
  reason: res.message,
155
241
  });
156
- problem(ctx.res, code === 'insufficient_scope' ? 403 : 401, code, res.message ?? `需要 scope: ${scope}`);
242
+ problem(ctx.res, code === 'insufficient_scope' ? 403 : 401, code, res.message ?? `需要 scope: ${label}`);
157
243
  return false;
158
244
  };
159
245
  // ---------- 路由 ----------
160
246
  const handleHealth = (ctx) => {
247
+ const counts = deps.registry.counts();
248
+ const queued = counts.queued;
249
+ // 完整性自检要读整库,不能挂在 CI 反复轮询的默认路径上 —— 只有显式 ?integrity=quick 才跑
250
+ const integrity = ctx.url.searchParams.get('integrity') === 'quick' ? deps.store.checkIntegrity() : undefined;
161
251
  json(ctx.res, 200, {
162
252
  status: 'ok',
163
253
  version: deps.version,
164
254
  controlPlane: { host: settings.host, port: settings.port, requireToken },
165
- // readiness:任务并发是否还有余量(CI 用它判断"现在能不能下发")
166
- ready: true,
167
- tasks: { tracked: records.size },
255
+ // readiness:队列还有空位才 ready;运行满但队列可排仍算可接收(CI 用它判断"现在能不能下发")
256
+ ready: queued < deps.defaults.maxQueued,
257
+ tasks: { tracked: records.size, running: counts.running, queued },
258
+ capacity: { maxTasks: deps.defaults.maxConcurrent, maxQueued: deps.defaults.maxQueued },
259
+ ...(integrity ? { db: integrity } : {}),
168
260
  });
169
261
  };
262
+ const handleMetrics = (ctx) => {
263
+ const counts = deps.registry.counts(ctx.tenantId);
264
+ const memory = process.memoryUsage();
265
+ const sessions = deps.store.listSessions(ctx.tenantId).length;
266
+ const lines = [
267
+ '# HELP agent_bridge_up Bridge process is running.',
268
+ '# TYPE agent_bridge_up gauge',
269
+ 'agent_bridge_up 1',
270
+ '# HELP agent_bridge_uptime_seconds Process uptime.',
271
+ '# TYPE agent_bridge_uptime_seconds gauge',
272
+ `agent_bridge_uptime_seconds ${process.uptime().toFixed(3)}`,
273
+ '# HELP agent_bridge_tasks_tracked Tasks currently tracked by registry.',
274
+ '# TYPE agent_bridge_tasks_tracked gauge',
275
+ `agent_bridge_tasks_tracked ${counts.running + counts.queued + counts.success + counts.failed}`,
276
+ '# HELP agent_bridge_tasks_running Running tasks.',
277
+ '# TYPE agent_bridge_tasks_running gauge',
278
+ `agent_bridge_tasks_running ${counts.running}`,
279
+ '# HELP agent_bridge_tasks_queued Queued tasks.',
280
+ '# TYPE agent_bridge_tasks_queued gauge',
281
+ `agent_bridge_tasks_queued ${counts.queued}`,
282
+ '# HELP agent_bridge_sessions_total Persisted sessions.',
283
+ '# TYPE agent_bridge_sessions_total gauge',
284
+ `agent_bridge_sessions_total ${sessions}`,
285
+ '# HELP agent_bridge_memory_rss_bytes Resident set size.',
286
+ '# TYPE agent_bridge_memory_rss_bytes gauge',
287
+ `agent_bridge_memory_rss_bytes ${memory.rss}`,
288
+ '# HELP agent_bridge_memory_heap_used_bytes V8 heap used.',
289
+ '# TYPE agent_bridge_memory_heap_used_bytes gauge',
290
+ `agent_bridge_memory_heap_used_bytes ${memory.heapUsed}`,
291
+ ];
292
+ ctx.res.writeHead(200, { 'content-type': 'text/plain; version=0.0.4; charset=utf-8' });
293
+ ctx.res.end(`${lines.join('\n')}\n`);
294
+ };
170
295
  const handleCapabilities = (ctx) => {
171
296
  json(ctx.res, 200, {
172
297
  capabilities: [...deps.capabilities],
@@ -174,9 +299,12 @@ export async function startControlPlane(settings, deps) {
174
299
  scopes: ['task:create', 'task:cancel', 'task:read', 'device:read'],
175
300
  endpoints: [
176
301
  '/v1/health',
302
+ '/v1/metrics',
303
+ '/v1/whoami',
177
304
  '/v1/capabilities',
178
305
  '/v1/agents',
179
306
  '/v1/agents:scan',
307
+ '/v1/board',
180
308
  '/v1/tasks',
181
309
  '/v1/tasks/{id}',
182
310
  '/v1/tasks/{id}:cancel',
@@ -189,63 +317,165 @@ export async function startControlPlane(settings, deps) {
189
317
  const agents = await deps.scan({ fresh: ctx.url.searchParams.get('fresh') === 'true' });
190
318
  json(ctx.res, 200, { agents, scannedAt: new Date().toISOString() });
191
319
  };
192
- const handleCreateTask = (ctx) => {
193
- const body = (ctx.body ?? {});
194
- const agentType = str(body['agentType']);
195
- const cwd = str(body['cwd']);
196
- if (!agentType || !cwd) {
197
- problem(ctx.res, 400, 'protocol_incompatible', '缺 agentType 或 cwd');
198
- return;
320
+ /**
321
+ * 任务创建核心:allocate(SQLite 会话/回合)→ registry 登记 → startTask(supervisor 调度)。
322
+ * `POST /v1/tasks` 与 A2A `SendMessage` 都走这里 —— 并发上限、权限策略、上行出口单一真源。
323
+ * 返回 `replay: true` 表示同幂等键重放(未重复执行副作用)。
324
+ * 抛出:`SessionStoreError('idempotency_conflict')`(同 key 异参);`startTask` 的受控拒绝(device_busy 等)。
325
+ */
326
+ const createTaskCore = (input) => {
327
+ const allocate = () => {
328
+ const allocated = {
329
+ taskId: `bt_${randomBytes(6).toString('hex')}`,
330
+ tenantId: input.tenantId,
331
+ agentType: input.agentType,
332
+ cwd: input.cwd,
333
+ state: 'running',
334
+ requestedBy: input.requestedBy,
335
+ purpose: input.purpose,
336
+ createdAt: new Date().toISOString(),
337
+ updatedAt: new Date().toISOString(),
338
+ };
339
+ deps.store.createSession({
340
+ sessionId: allocated.taskId,
341
+ tenantId: allocated.tenantId,
342
+ mode: 'task',
343
+ agentType: input.agentType,
344
+ cwd: input.cwd,
345
+ phase: 'queued',
346
+ });
347
+ deps.store.createTurn({
348
+ sessionId: allocated.taskId,
349
+ tenantId: allocated.tenantId,
350
+ status: 'queued',
351
+ execution: {
352
+ args: input.args,
353
+ prompt: input.prompt,
354
+ timeoutMs: input.timeoutMs,
355
+ captureDiff: input.captureDiff ?? deps.defaults.captureDiffByDefault,
356
+ permissionMode: input.permissionMode,
357
+ allowInteractive: input.allowInteractive,
358
+ requestedBy: input.requestedBy,
359
+ purpose: input.purpose,
360
+ },
361
+ });
362
+ return allocated;
363
+ };
364
+ let record;
365
+ if (input.idempotencyKey) {
366
+ const saved = deps.store.runIdempotent({
367
+ tenantId: input.tenantId,
368
+ scope: input.idempotencyScope,
369
+ key: input.idempotencyKey,
370
+ fingerprint: fingerprintIdempotency(input.idempotencyFingerprint),
371
+ }, allocate);
372
+ record = saved.value;
373
+ if (saved.replay)
374
+ return { record, replay: true };
199
375
  }
200
- // 幂等:同一 key 重复提交返回同一 taskId(网络重试不至于跑两遍)
201
- const idemRaw = ctx.req.headers['idempotency-key'];
202
- const idem = Array.isArray(idemRaw) ? idemRaw[0] : idemRaw;
203
- if (idem) {
204
- const known = idempotency.get(idem);
205
- if (known) {
206
- const rec = records.get(known);
207
- if (rec) {
208
- json(ctx.res, 200, { ...view(rec), idempotentReplay: true });
209
- return;
210
- }
211
- }
376
+ else {
377
+ record = allocate();
212
378
  }
213
- const taskId = `bt_${randomBytes(6).toString('hex')}`;
214
- const record = {
215
- taskId,
216
- agentType,
217
- cwd,
218
- state: 'running',
219
- requestedBy: str(body['requestedBy']),
220
- purpose: str(body['purpose']),
221
- createdAt: new Date().toISOString(),
222
- updatedAt: new Date().toISOString(),
223
- };
379
+ const taskId = record.taskId;
224
380
  remember(record);
225
- if (idem) {
226
- idempotency.set(idem, taskId);
227
- if (idempotency.size > MAX_IDEMPOTENCY_KEYS) {
228
- const oldest = idempotency.keys().next().value;
229
- if (oldest !== undefined)
230
- idempotency.delete(oldest);
231
- }
232
- }
233
- const captureDiff = body['captureDiff'] === true || deps.defaults.captureDiffByDefault;
381
+ deps.registry.register(taskId, {
382
+ agentType: input.agentType,
383
+ cwd: input.cwd,
384
+ source: 'control-plane',
385
+ tenantId: input.tenantId,
386
+ });
234
387
  const handle = deps.startTask({
235
388
  taskId,
236
- agentType,
237
- cwd,
238
- args: Array.isArray(body['args']) ? body['args'].filter((a) => typeof a === 'string') : [],
239
- prompt: str(body['prompt']),
240
- timeoutMs: typeof body['timeoutMs'] === 'number' ? body['timeoutMs'] : undefined,
389
+ agentType: input.agentType,
390
+ cwd: input.cwd,
391
+ args: input.args,
392
+ prompt: input.prompt,
393
+ timeoutMs: input.timeoutMs,
241
394
  allowedCwd: deps.defaults.allowedCwd,
242
395
  maxConcurrent: deps.defaults.maxConcurrent,
243
396
  maxQueued: deps.defaults.maxQueued,
244
- captureDiff,
397
+ captureDiff: input.captureDiff ?? deps.defaults.captureDiffByDefault,
245
398
  diffMaxBytes: deps.defaults.diffMaxBytes,
399
+ // 交互:调用方只能申请;本机未开放时按非交互跑(supervisor 会直接拒绝 ACP 权限请求)
400
+ interactive: input.allowInteractive === true && deps.defaults.interactionEnabled === true,
401
+ // 权限:平台/本地调用方可以请求,但本机策略同样适用(受管参数模式不会被本地通道绕过)
402
+ permissionMode: input.permissionMode,
403
+ permissionPolicy: deps.defaults.permissionPolicy,
404
+ externalSandbox: deps.defaults.externalSandbox,
246
405
  }, {
247
- onLog: (_stream, data) => deps.emitter.emit({ type: 'task_log', taskId, stream: _stream, data, isAnsi: true }),
406
+ onBeforeLaunch: () => {
407
+ const turn = deps.store.getActiveTurn(taskId, input.tenantId);
408
+ return turn ? deps.store.claimTurnForLaunch(taskId, turn.turnId, input.tenantId) : false;
409
+ },
410
+ onLog: (_stream, data) => deps.emitter.emit({ type: 'task_log', taskId, stream: _stream, data, isAnsi: hasAnsi(data) }),
411
+ // 步骤流(B 批次):控制面任务与平台任务同口径上行
412
+ onStep: (step) => {
413
+ deps.registry.updateStep(taskId, step);
414
+ deps.emitter.emit({ type: 'task_step', taskId, ...step, at: new Date().toISOString() });
415
+ },
416
+ onPlan: (items) => {
417
+ deps.registry.updatePlan(taskId, items);
418
+ },
248
419
  onStatus: (status, info) => {
420
+ try {
421
+ // 最终回答先落 canonical task_message,再落终态(与 WS dispatch 同口径:
422
+ // 平台/网关按 eventSeq 可完整重建;HTTP 与网关通道此前缺这段导致 history 为空)
423
+ if (status !== 'running' && info?.result?.trim()) {
424
+ const at = new Date().toISOString();
425
+ const messageId = `msg_${taskId}_final`;
426
+ const messageEvent = deps.store.appendEvent({
427
+ sessionId: taskId,
428
+ tenantId: input.tenantId,
429
+ type: 'task_message',
430
+ payload: {
431
+ messageId,
432
+ role: 'agent',
433
+ state: 'complete',
434
+ text: info.result,
435
+ at,
436
+ },
437
+ });
438
+ deps.emitter.emit({
439
+ type: 'task_message',
440
+ taskId,
441
+ messageId,
442
+ role: 'agent',
443
+ state: 'complete',
444
+ text: info.result,
445
+ eventSeq: messageEvent.eventSeq,
446
+ at,
447
+ });
448
+ }
449
+ const turn = deps.store.getActiveTurn(taskId, input.tenantId);
450
+ const phase = status === 'running' ? info?.phase ?? 'running' : 'settled';
451
+ deps.store.updateSession(taskId, { phase }, input.tenantId);
452
+ if (turn) {
453
+ deps.store.updateTurn(taskId, turn.turnId, {
454
+ status: status === 'running' && phase === 'queued' ? 'queued' : status,
455
+ startedAt: status === 'running' && phase !== 'queued' ? new Date().toISOString() : turn.startedAt,
456
+ finishedAt: status === 'running' ? turn.finishedAt : new Date().toISOString(),
457
+ }, input.tenantId);
458
+ }
459
+ deps.store.appendEvent({
460
+ sessionId: taskId,
461
+ tenantId: input.tenantId,
462
+ type: 'task_status',
463
+ payload: {
464
+ status,
465
+ phase,
466
+ exitCode: info?.exitCode,
467
+ error: info?.error,
468
+ errorCode: info?.errorCode,
469
+ permissionMode: info?.permissionMode,
470
+ },
471
+ });
472
+ if (status !== 'running')
473
+ deps.store.closeSession(taskId, status, info?.error, input.tenantId);
474
+ }
475
+ catch (error) {
476
+ deps.log('error', `[control-plane] 持久化任务状态失败 ${taskId}:${error.message}`);
477
+ }
478
+ deps.registry.updateStatus(taskId, status, info);
249
479
  const prev = records.get(taskId) ?? record;
250
480
  remember({
251
481
  ...prev,
@@ -257,7 +487,6 @@ export async function startControlPlane(settings, deps) {
257
487
  errorCode: info?.errorCode,
258
488
  diff: info?.diff,
259
489
  changedFiles: info?.changedFiles,
260
- diffTruncated: info?.diffTruncated,
261
490
  updatedAt: new Date().toISOString(),
262
491
  });
263
492
  // 控制面下发的任务同样经 Emitter 上行:平台侧视图不出现"半边失踪"
@@ -274,23 +503,79 @@ export async function startControlPlane(settings, deps) {
274
503
  changedFiles: info?.changedFiles,
275
504
  diffTruncated: info?.diffTruncated,
276
505
  requestedBy: record.requestedBy,
506
+ // 与 WS 通道同口径回显:控制面创建的任务也要能看出按哪个权限模式跑的
507
+ permissionMode: info?.permissionMode,
508
+ stopReason: info?.stopReason,
509
+ feedIncomplete: info?.feedIncomplete,
277
510
  });
278
511
  },
279
512
  });
280
513
  void handle.done.then(() => undefined);
281
514
  // 以**最新**台账为准:startTask 可能同步就把终态回调了(此时 record 还是 running)
282
515
  remember({ ...(records.get(taskId) ?? record), handle });
283
- const { handle: _handle, ...publicView } = records.get(taskId) ?? record;
284
- json(ctx.res, 201, { ...publicView, events: `/v1/tasks/${taskId}/events` });
516
+ return { record: records.get(taskId) ?? record, replay: false };
517
+ };
518
+ const handleCreateTask = (ctx) => {
519
+ const body = (ctx.body ?? {});
520
+ const agentType = str(body['agentType']);
521
+ const cwd = str(body['cwd']);
522
+ if (!agentType || !cwd) {
523
+ problem(ctx.res, 400, 'protocol_incompatible', '缺 agentType 或 cwd');
524
+ return;
525
+ }
526
+ // 交互申请必须是**布尔**:字符串 "true"/1 这类猜测会让「本机到底开没开交互」变得不可推理
527
+ const allowInteractiveRaw = body['allowInteractive'];
528
+ if (allowInteractiveRaw !== undefined && typeof allowInteractiveRaw !== 'boolean') {
529
+ problem(ctx.res, 400, 'protocol_incompatible', 'allowInteractive 必须是布尔');
530
+ return;
531
+ }
532
+ const allowInteractive = allowInteractiveRaw === true;
533
+ // SQLite 是唯一权威:同 key 同 body 重放原 taskId,异参冲突;进程重启/记录数量均不失效。
534
+ const idemRaw = ctx.req.headers['idempotency-key'];
535
+ const idemHeader = Array.isArray(idemRaw) ? idemRaw[0] : idemRaw;
536
+ try {
537
+ const { record, replay } = createTaskCore({
538
+ tenantId: tenantOf(ctx),
539
+ agentType,
540
+ cwd,
541
+ args: Array.isArray(body['args']) ? body['args'].filter((a) => typeof a === 'string') : [],
542
+ prompt: str(body['prompt']),
543
+ timeoutMs: typeof body['timeoutMs'] === 'number' ? body['timeoutMs'] : undefined,
544
+ captureDiff: body['captureDiff'] === true || deps.defaults.captureDiffByDefault,
545
+ permissionMode: body['permissionMode'] === 'full' ? 'full' : body['permissionMode'] === 'default' ? 'default' : undefined,
546
+ allowInteractive,
547
+ requestedBy: str(body['requestedBy']),
548
+ purpose: str(body['purpose']),
549
+ idempotencyKey: idemHeader ?? undefined,
550
+ idempotencyFingerprint: body,
551
+ idempotencyScope: 'http:task:create',
552
+ });
553
+ if (replay) {
554
+ const persisted = deps.store.getSession(record.taskId, record.tenantId);
555
+ const current = records.get(record.taskId) ??
556
+ (persisted ? { ...record, state: persisted.status, updatedAt: persisted.updatedAt } : record);
557
+ json(ctx.res, 200, { ...view(current), idempotentReplay: true });
558
+ return;
559
+ }
560
+ json(ctx.res, 201, { ...view(records.get(record.taskId) ?? record), events: `/v1/tasks/${record.taskId}/events` });
561
+ }
562
+ catch (error) {
563
+ if (error.code === 'idempotency_conflict') {
564
+ problem(ctx.res, 409, 'idempotency_conflict', '同一 Idempotency-Key 的请求内容不同');
565
+ return;
566
+ }
567
+ throw error;
568
+ }
285
569
  };
286
570
  const handleListTasks = (ctx) => {
287
571
  const limit = Math.min(200, Math.max(1, Number(ctx.url.searchParams.get('limit') ?? 50) || 50));
288
572
  const cursor = ctx.url.searchParams.get('cursor');
289
573
  const start = cursor ? order.indexOf(cursor) + 1 : 0;
290
574
  const slice = order.slice(Math.max(0, start), Math.max(0, start) + limit);
575
+ const tenant = tenantOf(ctx);
291
576
  const items = slice
292
577
  .map((id) => records.get(id))
293
- .filter((r) => r !== undefined)
578
+ .filter((r) => r !== undefined && (r.tenantId ?? DEFAULT_TENANT) === tenant)
294
579
  .map(view);
295
580
  const last = items.at(-1)?.taskId;
296
581
  json(ctx.res, 200, {
@@ -300,7 +585,7 @@ export async function startControlPlane(settings, deps) {
300
585
  });
301
586
  };
302
587
  const handleGetTask = (ctx, id) => {
303
- const rec = records.get(id);
588
+ const rec = visibleRecord(ctx, id);
304
589
  if (!rec) {
305
590
  problem(ctx.res, 404, 'internal', `未跟踪的任务:${id}`);
306
591
  return;
@@ -308,20 +593,149 @@ export async function startControlPlane(settings, deps) {
308
593
  json(ctx.res, 200, view(rec));
309
594
  };
310
595
  const handleDiff = (ctx, id) => {
311
- const rec = records.get(id);
312
- if (!rec) {
596
+ const rec = visibleRecord(ctx, id);
597
+ // 平台任务没有控制面 records 台账:用共享注册表兜底,保证结果页双通道一致
598
+ const viewFromRegistry = visibleRegistry(ctx, id);
599
+ if (!rec && !viewFromRegistry) {
313
600
  problem(ctx.res, 404, 'internal', `未跟踪的任务:${id}`);
314
601
  return;
315
602
  }
316
603
  json(ctx.res, 200, {
317
604
  taskId: id,
318
- diff: rec.diff ?? '',
319
- changedFiles: rec.changedFiles ?? [],
320
- diffTruncated: rec.diffTruncated ?? false,
605
+ diff: rec?.diff ?? viewFromRegistry?.diff ?? '',
606
+ changedFiles: rec?.changedFiles ?? viewFromRegistry?.changedFiles ?? [],
607
+ diffTruncated: rec?.diffTruncated ?? viewFromRegistry?.diffTruncated ?? false,
321
608
  });
322
609
  };
323
- const handleCancel = (ctx, id) => {
610
+ /** 步骤时间线(C 批次):任务注册表出完整步骤序列 + 最终回答 */
611
+ const handleSteps = (ctx, id) => {
612
+ const v = visibleRegistry(ctx, id);
613
+ if (!v) {
614
+ problem(ctx.res, 404, 'internal', `未跟踪的任务:${id}`);
615
+ return;
616
+ }
617
+ json(ctx.res, 200, {
618
+ taskId: id,
619
+ status: v.status,
620
+ phase: v.phase,
621
+ queuePosition: v.queuePosition,
622
+ stepCount: v.stepCount,
623
+ steps: v.steps,
624
+ plan: v.plan,
625
+ finalText: v.finalText,
626
+ error: v.error,
627
+ });
628
+ };
629
+ /** 文件预览(结果查看入口):只读、锁任务 cwd、≤512KB、按扩展名给 content-type */
630
+ const MAX_FILE_PREVIEW = 512 * 1024;
631
+ const CONTENT_TYPES = {
632
+ '.md': 'text/markdown; charset=utf-8',
633
+ '.markdown': 'text/markdown; charset=utf-8',
634
+ '.html': 'text/html; charset=utf-8',
635
+ '.htm': 'text/html; charset=utf-8',
636
+ '.png': 'image/png',
637
+ '.jpg': 'image/jpeg',
638
+ '.jpeg': 'image/jpeg',
639
+ '.gif': 'image/gif',
640
+ '.webp': 'image/webp',
641
+ '.svg': 'image/svg+xml',
642
+ '.json': 'application/json; charset=utf-8',
643
+ '.csv': 'text/csv; charset=utf-8',
644
+ '.tsv': 'text/tab-separated-values; charset=utf-8',
645
+ '.pdf': 'application/pdf',
646
+ '.docx': OFFICE_MIME_TYPES['.docx'],
647
+ '.xlsx': OFFICE_MIME_TYPES['.xlsx'],
648
+ '.pptx': OFFICE_MIME_TYPES['.pptx'],
649
+ };
650
+ const handleFilePreview = (ctx, id) => {
651
+ const cwd = visibleRegistry(ctx, id) ? deps.registry.cwdOf(id) : undefined;
652
+ if (!cwd) {
653
+ problem(ctx.res, 404, 'internal', `未跟踪的任务:${id}`);
654
+ return;
655
+ }
656
+ const rel = ctx.url.searchParams.get('path') ?? '';
657
+ if (!rel) {
658
+ problem(ctx.res, 400, 'protocol_incompatible', '缺少 path 参数');
659
+ return;
660
+ }
661
+ const abs = resolvePath(cwd, rel);
662
+ // 防穿越:解析后必须仍在任务 cwd 内
663
+ if (abs !== cwd && !abs.startsWith(cwd.endsWith(sep) ? cwd : cwd + sep)) {
664
+ problem(ctx.res, 403, 'cwd_not_allowed', '路径越出任务工作目录');
665
+ return;
666
+ }
667
+ // allowed_cwd 白名单(配置时才生效)——任务提交时已查过,这里纵深再查一次
668
+ const allowed = deps.defaults.allowedCwd;
669
+ if (allowed && allowed.length > 0) {
670
+ const ok = allowed.some((root) => {
671
+ const r = resolvePath(root);
672
+ return abs === r || abs.startsWith(r.endsWith(sep) ? r : r + sep);
673
+ });
674
+ if (!ok) {
675
+ problem(ctx.res, 403, 'cwd_not_allowed', '路径不在 allowed_cwd 范围');
676
+ return;
677
+ }
678
+ }
679
+ let st;
680
+ try {
681
+ st = statSync(abs);
682
+ }
683
+ catch {
684
+ problem(ctx.res, 404, 'internal', `文件不存在:${rel}`);
685
+ return;
686
+ }
687
+ if (!st.isFile()) {
688
+ problem(ctx.res, 400, 'protocol_incompatible', '不是文件');
689
+ return;
690
+ }
691
+ if (st.size > MAX_FILE_PREVIEW) {
692
+ problem(ctx.res, 413, 'internal', `文件超过 512KB 预览上限(${st.size} 字节)`);
693
+ return;
694
+ }
695
+ const ctype = CONTENT_TYPES[extname(abs).toLowerCase()] || 'application/octet-stream';
696
+ const isBinaryPreview = ctype.startsWith('image/') || ctype === 'application/pdf' || ctype.includes('officedocument');
697
+ const maxBytes = isBinaryPreview ? 20 * 1024 * 1024 : MAX_FILE_PREVIEW;
698
+ if (st.size > maxBytes) {
699
+ problem(ctx.res, 413, 'internal', `文件超过 ${maxBytes / 1024 / 1024}MB 预览上限(${st.size} 字节)`);
700
+ return;
701
+ }
702
+ if (ctx.url.searchParams.get('render') === '1') {
703
+ const html = renderOfficePreview(abs);
704
+ if (html) {
705
+ ctx.res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
706
+ ctx.res.end(html);
707
+ return;
708
+ }
709
+ }
710
+ if (ctx.req.method === 'HEAD') {
711
+ ctx.res.writeHead(200, { 'content-type': ctype, 'content-length': String(st.size), 'cache-control': 'no-store' });
712
+ ctx.res.end();
713
+ return;
714
+ }
715
+ ctx.res.writeHead(200, { 'content-type': ctype, 'content-length': String(st.size), 'cache-control': 'no-store' });
716
+ ctx.res.end(readFileSync(abs));
717
+ };
718
+ /**
719
+ * 取消核心:HTTP `:cancel` 与 A2A `CancelTask` 共用。
720
+ * - `not_found`:跨租户/不存在/本进程未跟踪(对网关统一按 -32001 处理)
721
+ * - `terminal`:已终态(HTTP 幂等 200;A2A 按规范回 TaskNotCancelableError)
722
+ * - `not_owned`:不是本地通道(控制面/网关)下发的,无权替平台做决定
723
+ * - `cancelled`:已向 supervisor 发取消(SIGTERM → 2s → SIGKILL),终态经 Emitter 回传
724
+ */
725
+ const cancelTaskCore = (id, tenantId) => {
324
726
  const rec = records.get(id);
727
+ if (!rec || (rec.tenantId ?? DEFAULT_TENANT) !== tenantId)
728
+ return 'not_found';
729
+ if (rec.state === 'success' || rec.state === 'failed' || rec.state === 'cancelled' || rec.state === 'timeout') {
730
+ return 'terminal';
731
+ }
732
+ if (!rec.handle)
733
+ return 'not_owned';
734
+ rec.handle.cancel();
735
+ return 'cancelled';
736
+ };
737
+ const handleCancel = (ctx, id) => {
738
+ const rec = visibleRecord(ctx, id);
325
739
  if (!rec) {
326
740
  problem(ctx.res, 404, 'internal', `未跟踪的任务:${id}`);
327
741
  return;
@@ -337,11 +751,326 @@ export async function startControlPlane(settings, deps) {
337
751
  return;
338
752
  }
339
753
  // 真正的取消走 supervisor(SIGTERM → 2s → SIGKILL);终态由它经 Emitter 回传,不在这里代发
340
- rec.handle.cancel();
341
- json(ctx.res, 200, view(records.get(id) ?? rec));
754
+ cancelTaskCore(id, tenantOf(ctx));
755
+ json(ctx.res, 200, view(rec));
756
+ };
757
+ const handleSessions = (ctx) => {
758
+ if (!authorize(ctx, SESSION_READ))
759
+ return;
760
+ const limitRaw = Number(ctx.url.searchParams.get('limit') ?? '50');
761
+ const limit = Number.isFinite(limitRaw) ? Math.min(200, Math.max(1, Math.floor(limitRaw))) : 50;
762
+ json(ctx.res, 200, {
763
+ sessions: deps.store.listSessions(ctx.tenantId).slice(-limit).map((session) => {
764
+ const window = deps.store.eventWindow(session.sessionId, ctx.tenantId);
765
+ return { ...session, ...window };
766
+ }),
767
+ });
768
+ };
769
+ /** 只读 scope:会话侧统一按「窄 scope 优先、旧 scope 兼容」判定 */
770
+ const SESSION_READ = ['session:read', 'task:read'];
771
+ /** 交互记录对外视图:Form 答案只留字段名(本来就只存字段名),不额外暴露 payload 内部结构 */
772
+ const viewInteraction = (rec) => ({
773
+ taskId: rec.sessionId,
774
+ requestId: rec.requestId,
775
+ kind: rec.kind,
776
+ state: rec.state,
777
+ payload: rec.payload,
778
+ ...(rec.turnId ? { turnId: rec.turnId } : {}),
779
+ ...(rec.expiresAt ? { expiresAt: rec.expiresAt } : {}),
780
+ ...(rec.responseId ? { responseId: rec.responseId } : {}),
781
+ ...(rec.resultSeq !== undefined ? { resultSeq: rec.resultSeq } : {}),
782
+ ...(rec.resultPayload !== undefined ? { resultPayload: rec.resultPayload } : {}),
783
+ createdAt: rec.createdAt,
784
+ });
785
+ /**
786
+ * `GET /v1/interactions`:有界列出交互(缺省全部状态,最常用的是 `state=pending`)。
787
+ * 只读 —— 回答问题的写入口是下面那条 `:respond`。
788
+ */
789
+ const handleInteractions = (ctx) => {
790
+ if (!authorize(ctx, SESSION_READ))
791
+ return;
792
+ const STATES = [
793
+ 'pending',
794
+ 'submitting',
795
+ 'accepted',
796
+ 'declined',
797
+ 'cancelled',
798
+ 'expired',
799
+ 'failed',
800
+ ];
801
+ const stateRaw = ctx.url.searchParams.get('state');
802
+ if (stateRaw && !STATES.includes(stateRaw)) {
803
+ problem(ctx.res, 400, 'protocol_incompatible', `state 非法:${stateRaw}`);
804
+ return;
805
+ }
806
+ const taskId = ctx.url.searchParams.get('taskId') ?? undefined;
807
+ const limitRaw = Number(ctx.url.searchParams.get('limit') ?? '50');
808
+ const rows = deps.store.queryInteractions({
809
+ tenantId: ctx.tenantId,
810
+ ...(taskId ? { sessionId: taskId } : {}),
811
+ ...(stateRaw ? { state: stateRaw } : {}),
812
+ limit: Number.isFinite(limitRaw) ? limitRaw : 50,
813
+ });
814
+ json(ctx.res, 200, { interactions: rows.map(viewInteraction) });
815
+ };
816
+ /** `GET /v1/interactions/{requestId}`:单条快照(pending 的请求 + 已结算的结果) */
817
+ const handleInteraction = (ctx, requestId) => {
818
+ if (!authorize(ctx, SESSION_READ))
819
+ return;
820
+ const rec = deps.store.findInteractionByRequestId(requestId, ctx.tenantId);
821
+ if (!rec) {
822
+ problem(ctx.res, 404, 'internal', `未找到交互:${requestId}`);
823
+ return;
824
+ }
825
+ json(ctx.res, 200, { interaction: viewInteraction(rec) });
826
+ };
827
+ /**
828
+ * `POST /v1/interactions/{requestId}:respond`:HTTP 侧回答问题。
829
+ *
830
+ * 鉴权分两层,都不可省:本函数按交互种类要 `task:approve`(permission)或 `task:respond`
831
+ * (form / auth-url);随后 dispatch 内部再按同一规则复核一次 —— 两条通道共用一套判定,
832
+ * 不能因为“从 HTTP 来的”就放宽。
833
+ */
834
+ const handleInteractionRespond = async (ctx, requestId) => {
835
+ const rec = deps.store.findInteractionByRequestId(requestId, ctx.tenantId);
836
+ if (!rec) {
837
+ problem(ctx.res, 404, 'internal', `未找到交互:${requestId}`);
838
+ return;
839
+ }
840
+ const respond = deps.respondInteraction;
841
+ if (!respond) {
842
+ problem(ctx.res, 501, 'internal', '当前进程未启用交互响应通道(只读模式)');
843
+ return;
844
+ }
845
+ if (!authorize(ctx, rec.kind === 'permission' ? 'task:approve' : 'task:respond'))
846
+ return;
847
+ const body = (ctx.body ?? {});
848
+ const state = body['state'];
849
+ if (state !== 'accepted' && state !== 'declined' && state !== 'cancelled') {
850
+ problem(ctx.res, 400, 'protocol_incompatible', 'state 必须是 accepted/declined/cancelled');
851
+ return;
852
+ }
853
+ const given = typeof body['responseId'] === 'string' && body['responseId'].trim()
854
+ ? body['responseId'].trim()
855
+ : undefined;
856
+ const responseId = given ?? `rs_${randomUUID().replace(/-/g, '').slice(0, 20)}`;
857
+ const payload = typeof body['payload'] === 'object' && body['payload'] !== null
858
+ ? body['payload']
859
+ : undefined;
860
+ const header = ctx.req.headers['authorization'];
861
+ const raw = Array.isArray(header) ? header[0] : header;
862
+ const token = raw?.startsWith('Bearer ') ? raw.slice(7).trim() : undefined;
863
+ const outcome = await respond({
864
+ type: 'task_interaction_response',
865
+ taskId: rec.sessionId,
866
+ requestId,
867
+ responseId,
868
+ tenantId: rec.tenantId,
869
+ state,
870
+ ...(payload ? { payload } : {}),
871
+ ...(token ? { serviceToken: token } : {}),
872
+ });
873
+ if (!outcome.ok) {
874
+ // 受控错误码只有 18 个(WS 与 HTTP 共用),交互侧的细分失败必须映射进来,
875
+ // 不能为了「好看的错误名」往协议里塞新码。
876
+ const reason = outcome.errorCode ?? 'internal';
877
+ const mapped = reason === 'interaction_not_found'
878
+ ? { status: 404, code: 'internal' }
879
+ : reason === 'interaction_already_resolved'
880
+ ? { status: 409, code: 'protocol_incompatible' }
881
+ : reason === 'interaction_expired'
882
+ ? { status: 410, code: 'timeout' }
883
+ : reason === 'interaction_delivery_unknown'
884
+ ? { status: 500, code: 'interaction_delivery_unknown' }
885
+ : reason === 'insufficient_scope' ||
886
+ reason === 'unauthorized' ||
887
+ reason === 'invalid_token' ||
888
+ reason === 'token_expired'
889
+ ? { status: 403, code: reason }
890
+ : isBridgeErrorCode(reason)
891
+ ? { status: 400, code: reason }
892
+ : { status: 400, code: 'protocol_incompatible' };
893
+ problem(ctx.res, mapped.status, mapped.code, `交互响应失败:${reason}`);
894
+ return;
895
+ }
896
+ json(ctx.res, 200, {
897
+ taskId: rec.sessionId,
898
+ requestId,
899
+ state: outcome.state,
900
+ ...(outcome.responseId ? { responseId: outcome.responseId } : {}),
901
+ ...(outcome.resultSeq !== undefined ? { resultSeq: outcome.resultSeq } : {}),
902
+ });
903
+ };
904
+ const handleArtifactDownload = (ctx, sessionId, artifactId) => {
905
+ if (!authorize(ctx, 'task:read'))
906
+ return;
907
+ const found = artifactsOf(ctx).artifactPath(sessionId, artifactId);
908
+ if (!found) {
909
+ problem(ctx.res, 404, 'internal', `未找到附件:${artifactId}`);
910
+ return;
911
+ }
912
+ ctx.res.writeHead(200, {
913
+ 'content-type': found.artifact.mimeType || 'application/octet-stream',
914
+ 'content-length': String(found.artifact.size),
915
+ 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(found.artifact.name)}`,
916
+ 'cache-control': 'no-store',
917
+ 'x-content-type-options': 'nosniff',
918
+ });
919
+ const stream = createReadStream(found.path);
920
+ stream.on('error', () => {
921
+ try {
922
+ ctx.res.destroy();
923
+ }
924
+ catch {
925
+ /* closed */
926
+ }
927
+ });
928
+ stream.pipe(ctx.res);
929
+ };
930
+ const handleArtifactsGc = (ctx) => {
931
+ if (!authorize(ctx, 'task:cancel'))
932
+ return;
933
+ const body = (ctx.body ?? {});
934
+ const ttlDays = typeof body.ttlDays === 'number' ? Math.floor(body.ttlDays) : 30;
935
+ if (!Number.isFinite(ttlDays) || ttlDays <= 0) {
936
+ problem(ctx.res, 400, 'cwd_not_allowed', 'ttlDays 必须是正整数');
937
+ return;
938
+ }
939
+ const result = artifactsOf(ctx).cleanupArtifacts({
940
+ olderThanMs: ttlDays * 24 * 60 * 60 * 1000,
941
+ dryRun: body.dryRun === true,
942
+ });
943
+ json(ctx.res, 200, { ttlDays, dryRun: body.dryRun === true, ...result });
944
+ };
945
+ const handleSessionSnapshot = (ctx, id) => {
946
+ if (!authorize(ctx, SESSION_READ))
947
+ return;
948
+ try {
949
+ const afterRaw = Number(ctx.url.searchParams.get('afterEventSeq') ?? '0');
950
+ const limitRaw = Number(ctx.url.searchParams.get('limit') ?? '200');
951
+ const snapshot = deps.store.snapshot(id, {
952
+ afterEventSeq: Number.isFinite(afterRaw) ? Math.max(0, Math.floor(afterRaw)) : 0,
953
+ limit: Number.isFinite(limitRaw) ? Math.min(1000, Math.max(1, Math.floor(limitRaw))) : 200,
954
+ tenantId: ctx.tenantId,
955
+ });
956
+ const partial = deps.partialMessages?.(id) ?? [];
957
+ json(ctx.res, 200, { ...snapshot, ...(partial.length ? { partialMessages: partial } : {}) });
958
+ }
959
+ catch {
960
+ problem(ctx.res, 404, 'internal', `未找到会话:${id}`);
961
+ }
962
+ };
963
+ /**
964
+ * 会话 SSE:先回放 SQLite 历史(afterEventSeq 之后),再接实时上行。
965
+ * event: snapshot / event / wire / heartbeat / done
966
+ */
967
+ const handleSessionEvents = (ctx, id) => {
968
+ if (!authorize(ctx, SESSION_READ))
969
+ return;
970
+ let snapshot;
971
+ try {
972
+ snapshot = deps.store.snapshot(id, { afterEventSeq: 0, limit: 1000, tenantId: ctx.tenantId });
973
+ }
974
+ catch {
975
+ problem(ctx.res, 404, 'internal', `未找到会话:${id}`);
976
+ return;
977
+ }
978
+ const afterRaw = Number(ctx.url.searchParams.get('afterEventSeq') ?? '0');
979
+ const after = Number.isFinite(afterRaw) ? Math.max(0, Math.floor(afterRaw)) : 0;
980
+ ctx.res.writeHead(200, {
981
+ 'content-type': 'text/event-stream; charset=utf-8',
982
+ 'cache-control': 'no-cache, no-transform',
983
+ connection: 'keep-alive',
984
+ 'x-accel-buffering': 'no',
985
+ });
986
+ const writeEvent = (event, data) => {
987
+ try {
988
+ ctx.res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
989
+ }
990
+ catch {
991
+ /* 客户端已断开 */
992
+ }
993
+ };
994
+ writeEvent('snapshot', {
995
+ session: snapshot.session,
996
+ oldestEventSeq: snapshot.oldestEventSeq,
997
+ latestEventSeq: snapshot.latestEventSeq,
998
+ // 首帧就是「现在的样子」,半截文本正是它比事件回放多出来的那点信息
999
+ partialMessages: deps.partialMessages?.(id) ?? [],
1000
+ });
1001
+ // 慢消费者断线后可能落后 >1000 条;分批按 eventSeq 追平,避免一次性截断造成缺口。
1002
+ let lastSeq = after;
1003
+ for (;;) {
1004
+ const replay = deps.store.listEvents(id, {
1005
+ afterEventSeq: lastSeq,
1006
+ limit: 1000,
1007
+ tenantId: ctx.tenantId,
1008
+ });
1009
+ for (const item of replay) {
1010
+ writeEvent('event', {
1011
+ eventSeq: item.eventSeq,
1012
+ type: item.type,
1013
+ payload: item.payload,
1014
+ createdAt: item.createdAt,
1015
+ });
1016
+ }
1017
+ if (replay.length < 1000)
1018
+ break;
1019
+ const next = replay.at(-1)?.eventSeq;
1020
+ if (next === undefined || next <= lastSeq)
1021
+ break;
1022
+ lastSeq = next;
1023
+ }
1024
+ if (snapshot.session.status !== 'running') {
1025
+ writeEvent('done', { taskId: id, status: snapshot.session.status });
1026
+ ctx.res.end();
1027
+ return;
1028
+ }
1029
+ let closed = false;
1030
+ const cleanup = () => {
1031
+ if (closed)
1032
+ return;
1033
+ closed = true;
1034
+ off();
1035
+ clearInterval(heartbeat);
1036
+ try {
1037
+ ctx.res.end();
1038
+ }
1039
+ catch {
1040
+ /* already ended */
1041
+ }
1042
+ };
1043
+ const send = (upstream) => {
1044
+ if (closed)
1045
+ return;
1046
+ const raw = upstream;
1047
+ const msg = raw.specversion && raw.data ? raw.data : raw;
1048
+ if (!('taskId' in msg) || msg.taskId !== id)
1049
+ return;
1050
+ const seq = 'eventSeq' in msg && typeof msg.eventSeq === 'number' ? msg.eventSeq : undefined;
1051
+ if (seq !== undefined && seq <= lastSeq)
1052
+ return;
1053
+ if (seq !== undefined)
1054
+ lastSeq = seq;
1055
+ writeEvent('wire', msg);
1056
+ const current = deps.store.getSession(id, ctx.tenantId);
1057
+ if (!current || current.status !== 'running') {
1058
+ writeEvent('done', { taskId: id, status: current?.status ?? 'unknown' });
1059
+ cleanup();
1060
+ }
1061
+ };
1062
+ const off = deps.emitter.subscribe(send);
1063
+ const heartbeat = setInterval(() => writeEvent('heartbeat', { at: Date.now() }), 15_000);
1064
+ heartbeat.unref?.();
1065
+ ctx.req.on('close', cleanup);
1066
+ ctx.res.on('close', cleanup);
342
1067
  };
343
1068
  /** SSE:晚订阅先从环形缓冲补发,再接实时事件 */
344
1069
  const handleEvents = (ctx, id) => {
1070
+ if (!visibleRecord(ctx, id) && !visibleRegistry(ctx, id)) {
1071
+ problem(ctx.res, 404, 'internal', `未跟踪的任务:${id}`);
1072
+ return;
1073
+ }
345
1074
  ctx.res.writeHead(200, {
346
1075
  'content-type': 'text/event-stream; charset=utf-8',
347
1076
  'cache-control': 'no-cache, no-transform',
@@ -351,7 +1080,9 @@ export async function startControlPlane(settings, deps) {
351
1080
  ctx.res.write(`event: hello\ndata: ${JSON.stringify({ taskId: id })}\n\n`);
352
1081
  const send = (msg) => {
353
1082
  const m = msg;
354
- const belongs = (m.type === 'task_log' || m.type === 'task_status') && 'taskId' in m && m.taskId === id;
1083
+ const belongs = (m.type === 'task_log' || m.type === 'task_status' || m.type === 'task_step') &&
1084
+ 'taskId' in m &&
1085
+ m.taskId === id;
355
1086
  if (!belongs)
356
1087
  return;
357
1088
  try {
@@ -401,8 +1132,122 @@ export async function startControlPlane(settings, deps) {
401
1132
  }
402
1133
  }
403
1134
  const ctx = { req, res, url, body };
1135
+ if (path !== '/v1/health' && deps.jwt) {
1136
+ const header = req.headers['authorization'];
1137
+ const raw = Array.isArray(header) ? header[0] : header;
1138
+ const bearer = raw?.startsWith('Bearer ') ? raw.slice(7).trim() : undefined;
1139
+ if (bearer && bearer.split('.').length === 3) {
1140
+ try {
1141
+ ctx.principal = await deps.jwt.verify(bearer);
1142
+ }
1143
+ catch (error) {
1144
+ problem(res, 401, 'invalid_token', `JWT 校验失败:${error.message}`);
1145
+ return;
1146
+ }
1147
+ ctx.tenantId = ctx.principal.tenantId ?? DEFAULT_TENANT;
1148
+ }
1149
+ }
404
1150
  if (path === '/v1/health')
405
1151
  return handleHealth(ctx);
1152
+ // A2A / ACP 网关(默认关闭):未启用时这些路径落到底部 404 —— 不暴露存在性。
1153
+ // agent card 免鉴权(静态描述,无任务数据,与面板页壳同口径);/a2a、/acp 逐方法鉴权。
1154
+ if (gateway) {
1155
+ if (path === '/.well-known/agent-card.json' && gatewayA2aEnabled) {
1156
+ gateway.agentCard(ctx);
1157
+ return;
1158
+ }
1159
+ if (path === '/a2a' && req.method === 'POST' && gatewayA2aEnabled) {
1160
+ gateway.a2a(ctx, (scope) => authorize(ctx, scope));
1161
+ return;
1162
+ }
1163
+ if (path === '/acp' && req.method === 'POST' && gatewayAcpEnabled) {
1164
+ gateway.acp(ctx, (scope) => authorize(ctx, scope));
1165
+ return;
1166
+ }
1167
+ }
1168
+ if (path === '/v1/whoami' && req.method === 'GET') {
1169
+ if (!authorize(ctx, 'device:read'))
1170
+ return;
1171
+ json(res, 200, {
1172
+ authenticated: true,
1173
+ principal: ctx.principal
1174
+ ? {
1175
+ subject: ctx.principal.subject,
1176
+ tenantId: ctx.principal.tenantId,
1177
+ scopes: ctx.principal.scopes,
1178
+ }
1179
+ : { service: true },
1180
+ });
1181
+ return;
1182
+ }
1183
+ if (path === '/v1/metrics' && req.method === 'GET') {
1184
+ if (!authorize(ctx, 'device:read'))
1185
+ return;
1186
+ return handleMetrics(ctx);
1187
+ }
1188
+ if (path === '/favicon.ico' && req.method === 'GET') {
1189
+ ctx.res.writeHead(204);
1190
+ ctx.res.end();
1191
+ return;
1192
+ }
1193
+ // Web 任务面板(C 批次):页面壳免令牌(不含数据),数据仍走带鉴权的 /v1/* 端点
1194
+ if (path === '/' && req.method === 'GET') {
1195
+ ctx.res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
1196
+ ctx.res.end(DASHBOARD_HTML);
1197
+ return;
1198
+ }
1199
+ if (path === '/sessions' && req.method === 'GET') {
1200
+ ctx.res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
1201
+ ctx.res.end(SESSIONS_HTML);
1202
+ return;
1203
+ }
1204
+ // 面板聚合视图:任务注册表(与终端面板同源)+ 计数 + 容量
1205
+ if (path === '/v1/artifacts:gc' && req.method === 'POST') {
1206
+ return handleArtifactsGc(ctx);
1207
+ }
1208
+ if (path === '/v1/sessions' && req.method === 'GET') {
1209
+ return handleSessions(ctx);
1210
+ }
1211
+ // 交互(1.0):HTTP 侧也能看与答,否则只做 HTTP 集成的调用方永远答不了权限确认
1212
+ if (path === '/v1/interactions' && req.method === 'GET') {
1213
+ return handleInteractions(ctx);
1214
+ }
1215
+ const interactionRespondMatch = /^\/v1\/interactions\/([^/:]+):respond$/.exec(path);
1216
+ if (interactionRespondMatch && req.method === 'POST') {
1217
+ return await handleInteractionRespond(ctx, decodeURIComponent(interactionRespondMatch[1] ?? ''));
1218
+ }
1219
+ const interactionMatch = /^\/v1\/interactions\/([^/:]+)$/.exec(path);
1220
+ if (interactionMatch && req.method === 'GET') {
1221
+ return handleInteraction(ctx, decodeURIComponent(interactionMatch[1] ?? ''));
1222
+ }
1223
+ const artifactMatch = /^\/v1\/sessions\/([^/]+)\/artifacts\/([^/]+)$/.exec(path);
1224
+ if (artifactMatch && req.method === 'GET') {
1225
+ return handleArtifactDownload(ctx, decodeURIComponent(artifactMatch[1] ?? ''), decodeURIComponent(artifactMatch[2] ?? ''));
1226
+ }
1227
+ const sessionEventsMatch = /^\/v1\/sessions\/([^/]+)\/events$/.exec(path);
1228
+ if (sessionEventsMatch && req.method === 'GET') {
1229
+ return handleSessionEvents(ctx, decodeURIComponent(sessionEventsMatch[1] ?? ''));
1230
+ }
1231
+ const sessionMatch = /^\/v1\/sessions\/([^/]+)$/.exec(path);
1232
+ if (sessionMatch && req.method === 'GET') {
1233
+ return handleSessionSnapshot(ctx, decodeURIComponent(sessionMatch[1] ?? ''));
1234
+ }
1235
+ if (path === '/v1/board' && req.method === 'GET') {
1236
+ if (!authorize(ctx, 'task:read'))
1237
+ return;
1238
+ const counts = deps.registry.counts(ctx.tenantId);
1239
+ json(ctx.res, 200, {
1240
+ counts,
1241
+ capacity: {
1242
+ running: counts.running,
1243
+ queued: counts.queued,
1244
+ maxTasks: deps.defaults.maxConcurrent,
1245
+ maxQueued: deps.defaults.maxQueued,
1246
+ },
1247
+ tasks: deps.registry.list(ctx.tenantId),
1248
+ });
1249
+ return;
1250
+ }
406
1251
  if (path === '/v1/capabilities') {
407
1252
  if (!authorize(ctx, 'device:read'))
408
1253
  return;
@@ -429,7 +1274,7 @@ export async function startControlPlane(settings, deps) {
429
1274
  return handleCreateTask(ctx);
430
1275
  }
431
1276
  // id 不含 `/` 与 `:`:否则 `:cancel` 会被贪婪的 id 部分吃掉
432
- const m = path.match(/^\/v1\/tasks\/([^/:]+)(:cancel|\/events|\/diff)?$/);
1277
+ const m = path.match(/^\/v1\/tasks\/([^/:]+)(:cancel|\/events|\/diff|\/steps|\/file)?$/);
433
1278
  if (m) {
434
1279
  const id = decodeURIComponent(m[1]);
435
1280
  const suffix = m[2] ?? '';
@@ -438,6 +1283,16 @@ export async function startControlPlane(settings, deps) {
438
1283
  return;
439
1284
  return handleEvents(ctx, id);
440
1285
  }
1286
+ if (suffix === '/steps') {
1287
+ if (!authorize(ctx, 'task:read'))
1288
+ return;
1289
+ return handleSteps(ctx, id);
1290
+ }
1291
+ if (suffix === '/file') {
1292
+ if (!authorize(ctx, 'task:read'))
1293
+ return;
1294
+ return handleFilePreview(ctx, id);
1295
+ }
441
1296
  if (suffix === ':cancel' && req.method === 'POST') {
442
1297
  if (!authorize(ctx, 'task:cancel'))
443
1298
  return;
@@ -468,7 +1323,16 @@ export async function startControlPlane(settings, deps) {
468
1323
  server.listen(settings.port, settings.host, () => {
469
1324
  const addr = server.address();
470
1325
  const port = typeof addr === 'object' && addr ? addr.port : settings.port;
1326
+ actualBaseUrl = `http://${settings.host}:${port}`;
471
1327
  deps.log('info', `[control-plane] 回环控制面已启动 http://${settings.host}:${port}`);
1328
+ if (gateway) {
1329
+ const surfaces = [
1330
+ ...(gatewayA2aEnabled ? ['POST /a2a(agent card 见 /.well-known/agent-card.json)'] : []),
1331
+ ...(gatewayAcpEnabled ? ['POST /acp(ACP v1 over HTTP)'] : []),
1332
+ ];
1333
+ if (surfaces.length)
1334
+ deps.log('info', `[control-plane] 网关已启用:${surfaces.join(',')} @ ${actualBaseUrl}`);
1335
+ }
472
1336
  resolve({
473
1337
  port,
474
1338
  url: `http://${settings.host}:${port}`,