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