agent-bridge-service 0.2.3 → 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 +104 -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 +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 +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
@@ -0,0 +1,1005 @@
1
+ /**
2
+ * A2A / ACP 网关处理器(proposal:add-a2a-acp-gateway)
3
+ *
4
+ * 定位:**适配层**——把外部 A2A / ACP 客户端接到现有
5
+ * `TaskSupervisor / SessionStore / Emitter / TaskRegistry` 上,不复制调度、不复制持久化、
6
+ * 不另开上行出口(所有事件仍只经 `Emitter.emit()`)。
7
+ *
8
+ * 安全模型(与 control-plane 同一套):
9
+ * - 本模块**不监听端口**:`listen(` 只允许出现在 `control-plane.ts`(护栏红线),
10
+ * 网关路由由 control-plane 的分发器挂载,天然继承回环绑定与纵深防御;
11
+ * - 默认关闭:`[gateway] enabled` 不配置时,control-plane 不挂这些路由(一律 404,不暴露存在性);
12
+ * - 鉴权复用 `abs_` scoped token / JWT principal(`authorize` 由 control-plane 注入的绑定版本);
13
+ * - 不返回 CORS 头;跨租户读取统一按「不存在」处理(A2A: TaskNotFoundError)。
14
+ *
15
+ * 版本协商:`A2A-Version` 请求头(空/缺省 = 0.3,规范规定;`1.0` = v1 拼写家族)。
16
+ * 方法名同时接受 v1.0 PascalCase(`GetTask`)与 0.3 小写(`tasks/get`)。
17
+ */
18
+ import { randomBytes } from 'node:crypto';
19
+ import { DEFAULT_TENANT } from '../core/session-store.js';
20
+ import { A2A_JSONRPC_ERRORS, a2aEmitStyleFor, negotiateA2aVersion, toA2aTask, toA2aTaskState, } from './a2a-mapping.js';
21
+ import { ACP_JSONRPC_ERRORS, acpMethodForInteractionKind, acpPromptToText, fromAcpElicitationResult, fromAcpPermissionOutcome, toAcpPermissionRequestParams, toAcpElicitationParams, toAcpUrlElicititationParams, } from './acp-gateway-mapping.js';
22
+ const json = (res, status, payload) => {
23
+ const body = JSON.stringify(payload);
24
+ res.writeHead(status, {
25
+ 'content-type': 'application/json; charset=utf-8',
26
+ 'content-length': Buffer.byteLength(body),
27
+ // 不返回 CORS 头(与 control-plane 同红线)
28
+ 'cache-control': 'no-store',
29
+ });
30
+ res.end(body);
31
+ };
32
+ /** JSON-RPC 成功响应 */
33
+ const rpcOk = (res, id, result) => json(res, 200, { jsonrpc: '2.0', id, result });
34
+ /** JSON-RPC 错误响应(鉴权类失败已由 authorize 走 problem 响应终结,这里都是 200) */
35
+ const rpcErr = (res, id, code, message, data) => json(res, 200, {
36
+ jsonrpc: '2.0',
37
+ id,
38
+ error: { code, message, ...(data ? { data } : {}) },
39
+ });
40
+ const A2A_METHODS = {
41
+ // v1.0 PascalCase
42
+ GetTask: 'getTask',
43
+ SendMessage: 'sendMessage',
44
+ CancelTask: 'cancelTask',
45
+ SubscribeToTask: 'subscribeToTask',
46
+ // 0.3 小写
47
+ 'tasks/get': 'getTask',
48
+ 'message/send': 'sendMessage',
49
+ 'tasks/cancel': 'cancelTask',
50
+ 'tasks/resubscribe': 'subscribeToTask',
51
+ };
52
+ /** 全部四个操作已实现(SendMessage / CancelTask / SubscribeToTask 于第二批接入) */
53
+ const UNIMPLEMENTED = {
54
+ getTask: undefined,
55
+ sendMessage: undefined,
56
+ cancelTask: undefined,
57
+ subscribeToTask: undefined,
58
+ };
59
+ export function createGatewayHandlers(deps) {
60
+ const baseUrl = () => deps.baseUrl();
61
+ const buildAgentCard = () => ({
62
+ name: 'agent-bridge',
63
+ description: 'A2A gateway surface of agent-bridge: routes tasks to locally installed AI coding CLIs (single outbound WebSocket to the platform; loopback gateway for external orchestrators).',
64
+ version: deps.version,
65
+ // v1.0 字段:preferredTransport + supportedInterfaces;0.3 客户端读 url/protocolVersion
66
+ protocolVersion: '1.0',
67
+ preferredTransport: 'JSONRPC',
68
+ url: `${baseUrl()}/a2a`,
69
+ capabilities: {
70
+ // 真实能力声明(capability 真源原则:没实现的不写 true)
71
+ streaming: false,
72
+ pushNotifications: false,
73
+ stateTransitionHistory: false,
74
+ extensions: false,
75
+ },
76
+ defaultInputModes: ['text/plain'],
77
+ defaultOutputModes: ['text/plain'],
78
+ skills: deps.agents.map((a) => ({
79
+ id: a.id,
80
+ name: a.name,
81
+ tags: ['coding-agent', a.id],
82
+ inputModes: ['text/plain'],
83
+ outputModes: ['text/plain'],
84
+ })),
85
+ supportedInterfaces: [
86
+ {
87
+ url: `${baseUrl()}/a2a`,
88
+ protocolBinding: 'JSONRPC',
89
+ protocolVersion: '1.0',
90
+ },
91
+ ],
92
+ });
93
+ const handleAgentCard = (ctx) => {
94
+ if (ctx.req.method !== 'GET' && ctx.req.method !== 'HEAD') {
95
+ json(ctx.res, 405, { error: 'method not allowed' });
96
+ return;
97
+ }
98
+ json(ctx.res, 200, buildAgentCard());
99
+ };
100
+ /**
101
+ * `tasks/get`:SQLite 快照 → A2A Task。
102
+ * 跨租户/不存在统一 TaskNotFoundError(-32001):不泄露「存在但不是你的」。
103
+ */
104
+ const handleGetTask = (ctx, authorize, rpcId, taskId, style) => {
105
+ // 只读口径与 /v1/sessions/{id} 一致:session:read 窄 scope 优先,旧 task:read 兼容
106
+ if (!authorize(['session:read', 'task:read']))
107
+ return;
108
+ if (typeof taskId !== 'string' || !taskId) {
109
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidParams, 'params.id 必须是非空字符串');
110
+ return;
111
+ }
112
+ let task;
113
+ try {
114
+ const snap = deps.store.snapshot(taskId, {
115
+ afterEventSeq: 0,
116
+ limit: 1000,
117
+ tenantId: ctx.tenantId,
118
+ });
119
+ task = toA2aTask({
120
+ session: snap.session,
121
+ events: snap.events,
122
+ artifacts: snap.artifacts,
123
+ style,
124
+ baseUrl: baseUrl(),
125
+ });
126
+ }
127
+ catch {
128
+ // SessionStoreError(含跨租户按 not found 处理)
129
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.taskNotFound, `任务不存在:${String(taskId)}`);
130
+ return;
131
+ }
132
+ rpcOk(ctx.res, rpcId, task);
133
+ };
134
+ /**
135
+ * `SendMessage`(message/send):message.parts → prompt,message.metadata 带 bridge 扩展字段
136
+ * (agentType / cwd 必填;timeoutMs / captureDiff / permissionMode 可选)。
137
+ * messageId 即幂等键:客户端重发同 messageId 拿回同一 taskId,不会跑两遍。
138
+ * 网关**永远立即返回**(等价 returnImmediately):bridge 任务是分钟级长任务,阻塞到终态
139
+ * 会把 A2A 客户端的 HTTP 超时拖穿;后续状态走 GetTask 轮询或 SubscribeToTask 订阅。
140
+ */
141
+ const handleSendMessage = (ctx, authorize, rpcId, params, style) => {
142
+ if (!authorize('task:create'))
143
+ return;
144
+ const message = params?.['message'];
145
+ if (!message || typeof message !== 'object') {
146
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidParams, 'params.message 必须是 Message 对象');
147
+ return;
148
+ }
149
+ const role = message['role'];
150
+ if (role !== 'user' && role !== 'ROLE_USER') {
151
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidParams, '创建任务的 message.role 必须是 user(ROLE_USER)');
152
+ return;
153
+ }
154
+ const parts = message['parts'];
155
+ if (!Array.isArray(parts) || parts.length === 0) {
156
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidParams, 'message.parts 必须是非空数组');
157
+ return;
158
+ }
159
+ const texts = [];
160
+ for (const p of parts) {
161
+ const part = p;
162
+ const kind = part?.['kind'] ?? part?.['type'];
163
+ if (kind !== 'text') {
164
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.contentTypeNotSupported, '只支持 text part(file/data part 暂不支持)');
165
+ return;
166
+ }
167
+ const text = part?.['text'];
168
+ if (typeof text !== 'string') {
169
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidParams, 'text part 缺 text 字段');
170
+ return;
171
+ }
172
+ texts.push(text);
173
+ }
174
+ const prompt = texts.join('\n');
175
+ if (!prompt.trim()) {
176
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidParams, 'prompt 不能为空');
177
+ return;
178
+ }
179
+ const metadata = message['metadata'];
180
+ const agentType = typeof metadata?.['agentType'] === 'string' ? metadata['agentType'] : undefined;
181
+ const cwd = typeof metadata?.['cwd'] === 'string' ? metadata['cwd'] : undefined;
182
+ if (!agentType || !cwd) {
183
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidParams, 'message.metadata 缺 bridge 扩展字段:agentType(12 个受管 CLI 之一)与 cwd(须存在且在 allowed_cwd 内)');
184
+ return;
185
+ }
186
+ if (!deps.agents.some((a) => a.id === agentType)) {
187
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidParams, `未知 agentType:${agentType}(不在受管适配器白名单内)`);
188
+ return;
189
+ }
190
+ const timeoutMs = typeof metadata?.['timeoutMs'] === 'number' ? metadata['timeoutMs'] : undefined;
191
+ const messageId = typeof message['messageId'] === 'string' && message['messageId'] ? message['messageId'] : undefined;
192
+ if (!messageId) {
193
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidParams, 'message.messageId 必须是非空字符串(幂等键)');
194
+ return;
195
+ }
196
+ let taskId;
197
+ let replay;
198
+ try {
199
+ const created = deps.ops.createTask({
200
+ tenantId: ctx.tenantId ?? DEFAULT_TENANT,
201
+ agentType,
202
+ cwd,
203
+ prompt,
204
+ timeoutMs,
205
+ requestedBy: typeof metadata?.['requestedBy'] === 'string' ? metadata['requestedBy'] : undefined,
206
+ idempotencyKey: messageId,
207
+ idempotencyFingerprint: { agentType, cwd, prompt, timeoutMs },
208
+ });
209
+ ({ taskId, replay } = created);
210
+ }
211
+ catch (error) {
212
+ const code = error.code;
213
+ if (code === 'idempotency_conflict') {
214
+ rpcErr(ctx.res, rpcId, -32000, '同 messageId 的请求内容不同(幂等冲突)', { code });
215
+ return;
216
+ }
217
+ // startTask 的受控拒绝(device_busy / tool_not_installed / cwd_* 等):code 放进 data,客户端按 code 分支
218
+ rpcErr(ctx.res, rpcId, -32000, `任务创建被拒绝:${error.message}`, code ? { code } : undefined);
219
+ return;
220
+ }
221
+ let task;
222
+ try {
223
+ const snap = deps.store.snapshot(taskId, { afterEventSeq: 0, limit: 1000, tenantId: ctx.tenantId });
224
+ task = toA2aTask({ session: snap.session, events: snap.events, artifacts: snap.artifacts, style, baseUrl: baseUrl() });
225
+ }
226
+ catch {
227
+ // 创建成功但快照读取失败:任务确实已调度,不能谎报失败 —— 给可用的最小 Task
228
+ task = {
229
+ id: taskId,
230
+ contextId: taskId,
231
+ status: { state: style.state('TASK_STATE_SUBMITTED') },
232
+ metadata: { bridge: { replay } },
233
+ };
234
+ if (style.taskKindDiscriminator)
235
+ task.kind = 'task';
236
+ rpcOk(ctx.res, rpcId, task);
237
+ return;
238
+ }
239
+ if (replay)
240
+ (task.metadata ??= {})['idempotentReplay'] = true;
241
+ rpcOk(ctx.res, rpcId, task);
242
+ };
243
+ /**
244
+ * `CancelTask`(tasks/cancel):走 control-plane 的取消语义(SIGTERM → 2s → SIGKILL,终态经 Emitter 回传)。
245
+ * A2A 规范语义:终态任务取消回 TaskNotCancelableError(-32002);跨租户/不存在统一 -32001。
246
+ */
247
+ const handleCancelTask = (ctx, authorize, rpcId, params, style) => {
248
+ if (!authorize('task:cancel'))
249
+ return;
250
+ const id = params?.['id'];
251
+ if (typeof id !== 'string' || !id) {
252
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidParams, 'params.id 必须是非空字符串');
253
+ return;
254
+ }
255
+ const outcome = deps.ops.cancelTask(id, ctx.tenantId ?? DEFAULT_TENANT);
256
+ if (outcome === 'not_found') {
257
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.taskNotFound, `任务不存在:${id}`);
258
+ return;
259
+ }
260
+ if (outcome === 'terminal') {
261
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.taskNotCancelable, `任务已终态,不可取消:${id}`);
262
+ return;
263
+ }
264
+ if (outcome === 'not_owned') {
265
+ // 平台下发的任务网关无权替它做取消决定;对外按「不可取消」表达,不暴露所有权细节
266
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.taskNotCancelable, `任务 ${id} 不是网关通道创建,无法从这里取消`);
267
+ return;
268
+ }
269
+ // cancelled:终态还没落库(supervisor 异步回传),返回当前快照(working 态)
270
+ try {
271
+ const snap = deps.store.snapshot(id, { afterEventSeq: 0, limit: 1000, tenantId: ctx.tenantId });
272
+ rpcOk(ctx.res, rpcId, toA2aTask({ session: snap.session, events: snap.events, artifacts: snap.artifacts, style, baseUrl: baseUrl() }));
273
+ }
274
+ catch {
275
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.taskNotFound, `任务不存在:${id}`);
276
+ }
277
+ };
278
+ /**
279
+ * `SubscribeToTask`(tasks/resubscribe):SSE 流,`eventSeq` 补洞。
280
+ * 帧格式是 bridge 网关自定义(不声称 A2A v1.0 StreamResponse 兼容——card 的 streaming 仍为 false):
281
+ * - `event: task` → A2A Task 完整快照(首帧与终帧)
282
+ * - `event: message` → { eventSeq, message: A2A Message }
283
+ * - `event: status` → { eventSeq, status: A2A TaskStatus }
284
+ * - `event: artifact` → { eventSeq, artifact: A2A Artifact }
285
+ * - `event: log|step` → 调试扩展(task_log/task_step,按 proposal 不冒充标准消息)
286
+ * - `event: done` → { taskId, status }
287
+ * 补洞起点:`params.metadata.afterEventSeq`(缺省 0 = 全量回放);终态任务按规范回 -32004。
288
+ */
289
+ const handleSubscribeToTask = (ctx, authorize, rpcId, params, style) => {
290
+ if (!authorize(['session:read', 'task:read']))
291
+ return;
292
+ const id = params?.['id'];
293
+ if (typeof id !== 'string' || !id) {
294
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidParams, 'params.id 必须是非空字符串');
295
+ return;
296
+ }
297
+ // 闭包别名:function 声明(emitStoreEvent)不保留参数 narrowing,显式固定为 string
298
+ const taskKey = id;
299
+ const meta = params?.['metadata'];
300
+ const afterRaw = Number(meta?.['afterEventSeq'] ?? 0);
301
+ const after = Number.isFinite(afterRaw) ? Math.max(0, Math.floor(afterRaw)) : 0;
302
+ let snap;
303
+ try {
304
+ snap = deps.store.snapshot(id, { afterEventSeq: 0, limit: 1, tenantId: ctx.tenantId });
305
+ }
306
+ catch {
307
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.taskNotFound, `任务不存在:${id}`);
308
+ return;
309
+ }
310
+ // 规范:终态任务不再可订阅(SubscribeToTask on terminal task → UnsupportedOperationError)
311
+ if (snap.session.status !== 'running') {
312
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.unsupportedOperation, `任务已终态(${snap.session.status}),订阅已关闭:${id}`);
313
+ return;
314
+ }
315
+ ctx.res.writeHead(200, {
316
+ 'content-type': 'text/event-stream; charset=utf-8',
317
+ 'cache-control': 'no-cache, no-transform',
318
+ connection: 'keep-alive',
319
+ 'x-accel-buffering': 'no',
320
+ });
321
+ let lastSeq = after;
322
+ const writeEvent = (event, data) => {
323
+ try {
324
+ ctx.res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
325
+ }
326
+ catch {
327
+ /* 客户端已断开 */
328
+ }
329
+ };
330
+ writeEvent('task', toA2aTask({
331
+ session: snap.session,
332
+ events: snap.events,
333
+ artifacts: snap.artifacts,
334
+ style,
335
+ baseUrl: baseUrl(),
336
+ }));
337
+ // 回放:按 eventSeq 追平持久化事件(慢消费者断线后可能落后很多,分批补)
338
+ for (;;) {
339
+ const replay = deps.store.listEvents(id, { afterEventSeq: lastSeq, limit: 1000, tenantId: ctx.tenantId });
340
+ for (const item of replay)
341
+ emitStoreEvent(item);
342
+ if (replay.length < 1000)
343
+ break;
344
+ const next = replay.at(-1)?.eventSeq;
345
+ if (next === undefined || next <= lastSeq)
346
+ break;
347
+ lastSeq = next;
348
+ }
349
+ let closed = false;
350
+ const cleanup = () => {
351
+ if (closed)
352
+ return;
353
+ closed = true;
354
+ off();
355
+ clearInterval(heartbeat);
356
+ try {
357
+ ctx.res.end();
358
+ }
359
+ catch {
360
+ /* already ended */
361
+ }
362
+ };
363
+ const send = (upstream) => {
364
+ if (closed)
365
+ return;
366
+ const msg = upstream;
367
+ if (!('taskId' in msg) || msg.taskId !== id)
368
+ return;
369
+ const seq = 'eventSeq' in msg && typeof msg.eventSeq === 'number' ? msg.eventSeq : undefined;
370
+ if (seq !== undefined && seq <= lastSeq)
371
+ return;
372
+ if (seq !== undefined)
373
+ lastSeq = seq;
374
+ switch (msg.type) {
375
+ case 'task_message':
376
+ if (msg.state !== 'complete')
377
+ return; // delta 是流式增量,不进订阅流(快照语义)
378
+ writeEvent('message', {
379
+ eventSeq: seq,
380
+ message: {
381
+ role: style.role('agent'),
382
+ parts: [{ [style.partDiscriminator]: 'text', text: msg.text }],
383
+ messageId: msg.messageId,
384
+ taskId: id,
385
+ },
386
+ });
387
+ break;
388
+ case 'task_status': {
389
+ writeEvent('status', {
390
+ eventSeq: seq,
391
+ status: {
392
+ state: style.state(toA2aTaskState(msg.status, msg.phase)),
393
+ timestamp: new Date().toISOString(),
394
+ ...(msg.status !== 'running' && msg.error ? { message: { role: style.role('agent'), parts: [{ [style.partDiscriminator]: 'text', text: msg.error }], messageId: `err_${seq ?? 0}` } } : {}),
395
+ },
396
+ });
397
+ if (msg.status !== 'running') {
398
+ // 终态:回一个最终快照再关流(订阅方拿到确定结束点)
399
+ const current = deps.store.getSession(id, ctx.tenantId);
400
+ if (current) {
401
+ const finalSnap = deps.store.snapshot(id, { afterEventSeq: 0, limit: 1, tenantId: ctx.tenantId });
402
+ writeEvent('task', toA2aTask({ session: finalSnap.session, events: finalSnap.events, artifacts: finalSnap.artifacts, style, baseUrl: baseUrl() }));
403
+ }
404
+ writeEvent('done', { taskId: id, status: msg.status });
405
+ cleanup();
406
+ }
407
+ break;
408
+ }
409
+ case 'task_artifact':
410
+ writeEvent('artifact', {
411
+ eventSeq: seq,
412
+ artifact: {
413
+ artifactId: msg.artifactId,
414
+ name: msg.name,
415
+ parts: [{ [style.partDiscriminator]: 'file', file: { uri: `${baseUrl()}/v1/sessions/${encodeURIComponent(id)}/artifacts/${encodeURIComponent(msg.artifactId)}`, mimeType: msg.mimeType || 'application/octet-stream', name: msg.name } }],
416
+ metadata: { size: msg.size, sha256: msg.sha256, kind: msg.kind },
417
+ },
418
+ });
419
+ break;
420
+ default:
421
+ break; // task_log / task_step:持久化回放里有(emitStoreEvent),实时流里不重复发
422
+ }
423
+ };
424
+ /** 持久化事件 → 帧映射(回放用;与实时 send 保持同一 vocab) */
425
+ function emitStoreEvent(item) {
426
+ const payload = (item.payload ?? {});
427
+ if (item.type === 'task_message' && payload['state'] === 'complete') {
428
+ writeEvent('message', {
429
+ eventSeq: item.eventSeq,
430
+ message: {
431
+ role: style.role(payload['role'] === 'user' ? 'user' : 'agent'),
432
+ parts: [{ [style.partDiscriminator]: 'text', text: typeof payload['text'] === 'string' ? payload['text'] : '' }],
433
+ messageId: typeof payload['messageId'] === 'string' ? payload['messageId'] : `msg_${item.eventSeq}`,
434
+ taskId: taskKey,
435
+ },
436
+ });
437
+ }
438
+ else if (item.type === 'task_status') {
439
+ const status = payload['status'];
440
+ if (typeof status === 'string') {
441
+ writeEvent('status', {
442
+ eventSeq: item.eventSeq,
443
+ status: { state: style.state(toA2aTaskState(status, undefined)), timestamp: item.createdAt },
444
+ });
445
+ }
446
+ }
447
+ else if (item.type === 'task_artifact') {
448
+ const artId = typeof payload['artifactId'] === 'string' && payload['artifactId'] ? payload['artifactId'] : `ar_${item.eventSeq}`;
449
+ writeEvent('artifact', {
450
+ eventSeq: item.eventSeq,
451
+ artifact: {
452
+ artifactId: artId,
453
+ name: typeof payload['name'] === 'string' ? payload['name'] : undefined,
454
+ parts: [
455
+ {
456
+ [style.partDiscriminator]: 'file',
457
+ file: { uri: `${baseUrl()}/v1/sessions/${encodeURIComponent(taskKey)}/artifacts/${encodeURIComponent(artId)}` },
458
+ },
459
+ ],
460
+ },
461
+ });
462
+ }
463
+ else if (item.type === 'task_log' || item.type === 'task_step') {
464
+ // 调试扩展:透传 type + eventSeq(按 proposal:task_log 不冒充标准消息)
465
+ writeEvent(item.type === 'task_log' ? 'log' : 'step', { eventSeq: item.eventSeq, payload: item.payload });
466
+ }
467
+ }
468
+ const off = deps.emitter.subscribe(send);
469
+ const heartbeat = setInterval(() => writeEvent('heartbeat', { at: Date.now() }), 15_000);
470
+ heartbeat.unref?.();
471
+ ctx.req.on('close', cleanup);
472
+ ctx.res.on('close', cleanup);
473
+ };
474
+ const handleA2a = (ctx, authorize) => {
475
+ const header = ctx.req.headers['a2a-version'];
476
+ const headerStr = Array.isArray(header) ? header[0] : header;
477
+ const version = negotiateA2aVersion(headerStr);
478
+ const rawId = ctx.body?.['id'];
479
+ const rpcId = rawId === undefined ? null : rawId;
480
+ if (version === 'unsupported') {
481
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.versionNotSupported, `不支持的 A2A-Version:${String(headerStr)}`);
482
+ return;
483
+ }
484
+ const style = a2aEmitStyleFor(version);
485
+ const body = ctx.body;
486
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
487
+ rpcErr(ctx.res, null, A2A_JSONRPC_ERRORS.invalidRequest, '请求体必须是单个 JSON-RPC 2.0 对象');
488
+ return;
489
+ }
490
+ if (body['jsonrpc'] !== '2.0') {
491
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidRequest, 'jsonrpc 字段必须是 "2.0"');
492
+ return;
493
+ }
494
+ const method = body['method'];
495
+ if (typeof method !== 'string' || !method) {
496
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.invalidRequest, 'method 必须是非空字符串');
497
+ return;
498
+ }
499
+ const op = A2A_METHODS[method];
500
+ if (!op) {
501
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.methodNotFound, `未知方法:${method}`);
502
+ return;
503
+ }
504
+ const unimplemented = UNIMPLEMENTED[op];
505
+ if (unimplemented) {
506
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.unsupportedOperation, unimplemented);
507
+ return;
508
+ }
509
+ const params = body['params'];
510
+ if (op === 'getTask') {
511
+ handleGetTask(ctx, authorize, rpcId, params?.['id'], style);
512
+ return;
513
+ }
514
+ if (op === 'sendMessage') {
515
+ handleSendMessage(ctx, authorize, rpcId, params, style);
516
+ return;
517
+ }
518
+ if (op === 'cancelTask') {
519
+ handleCancelTask(ctx, authorize, rpcId, params, style);
520
+ return;
521
+ }
522
+ if (op === 'subscribeToTask') {
523
+ handleSubscribeToTask(ctx, authorize, rpcId, params, style);
524
+ return;
525
+ }
526
+ // 理论不可达(上面 UNIMPLEMENTED 已挡),保留兜底防未来漏分支
527
+ rpcErr(ctx.res, rpcId, A2A_JSONRPC_ERRORS.unsupportedOperation, '操作未实现');
528
+ };
529
+ // ==================== ACP server(tasks 3.x) ====================
530
+ // ACP v1 over HTTP:请求 POST /acp(JSON-RPC 2.0);session/prompt 的下行走 SSE
531
+ // (`event: update` 通知帧 / `event: request` agent→client 请求帧 / `event: result` 终帧)。
532
+ // 客户端对 agent→client 请求的应答用另一条 POST /acp 发「响应报文」(无 method、带 id+result),
533
+ // 网关按出站 id 关联 pending 交互后走与 /v1/interactions/{id}:respond 同一条 dispatch 路径。
534
+ /** ACP 会话登记:acpSessionId → 启动参数与 conversation 绑定(add-acp-session-memory) */
535
+ const acpSessions = new Map();
536
+ /** 出站交互请求:JSON-RPC id → pending 交互定位(客户端应答时反向解析) */
537
+ const outboundRequests = new Map();
538
+ let outboundSeq = 0;
539
+ /** 交互记录 → ACP agent→client 请求帧的 params(按 kind 分派,畸形 payload 报错不透传) */
540
+ const toAcpRequestFrame = (kind, interaction) => {
541
+ if (kind === 'permission') {
542
+ const params = toAcpPermissionRequestParams(interaction);
543
+ return 'invalid' in params ? params : { method: acpMethodForInteractionKind(kind), params };
544
+ }
545
+ if (kind === 'auth-url') {
546
+ const params = toAcpUrlElicititationParams(interaction);
547
+ return 'invalid' in params ? params : { method: 'elicitation/create', params };
548
+ }
549
+ const params = toAcpElicitationParams(interaction);
550
+ return 'invalid' in params ? params : { method: acpMethodForInteractionKind(kind), params };
551
+ };
552
+ /**
553
+ * ACP `initialize`:只声明真实能力(loadSession=false —— 会话不持久续接;
554
+ * prompt 只收 text block;fs/terminal 客户端能力默认不开放)。
555
+ */
556
+ const handleAcpInitialize = (ctx) => {
557
+ rpcOk(ctx.res, 'acp-init', {
558
+ protocolVersion: 1,
559
+ agentCapabilities: {
560
+ loadSession: false,
561
+ promptCapabilities: { image: false, audio: false, embeddedContext: false },
562
+ mcpCapabilities: { http: false, sse: false },
563
+ },
564
+ agentInfo: { name: 'agent-bridge', title: 'agent-bridge ACP gateway', version: deps.version },
565
+ authMethods: [],
566
+ });
567
+ };
568
+ /** ACP `session/new`:固化 agentType/cwd(`params._meta.agentType` 扩展字段);prompt 逐轮建任务 */
569
+ const handleAcpSessionNew = (ctx, authorize, rpcId, params) => {
570
+ // initialize / session/new 用 device:read(握手与会话登记,不涉及任务数据)
571
+ if (!authorize('device:read'))
572
+ return;
573
+ const cwd = typeof params?.['cwd'] === 'string' ? params['cwd'] : undefined;
574
+ const meta = (params?.['_meta'] ?? params?.['meta']);
575
+ const agentType = typeof meta?.['agentType'] === 'string'
576
+ ? meta['agentType']
577
+ : typeof params?.['agentType'] === 'string'
578
+ ? params['agentType']
579
+ : undefined;
580
+ if (!agentType || !cwd) {
581
+ rpcErr(ctx.res, rpcId, ACP_JSONRPC_ERRORS.invalidParams, 'session/new 需要 params.cwd 与 params._meta.agentType(bridge 有 12 个 CLI,必须显式选择)');
582
+ return;
583
+ }
584
+ if (!deps.agents.some((a) => a.id === agentType)) {
585
+ rpcErr(ctx.res, rpcId, ACP_JSONRPC_ERRORS.invalidParams, `未知 agentType:${agentType}(不在受管适配器白名单内)`);
586
+ return;
587
+ }
588
+ const acpSessionId = `acp_${randomBytes(8).toString('hex')}`;
589
+ acpSessions.set(acpSessionId, {
590
+ agentType,
591
+ cwd,
592
+ tenantId: ctx.tenantId ?? DEFAULT_TENANT,
593
+ });
594
+ rpcOk(ctx.res, rpcId, { sessionId: acpSessionId });
595
+ };
596
+ /**
597
+ * ACP `session/prompt`:一轮 prompt = 一个 bridge 任务(proposal:session/prompt 映射到 run_task)。
598
+ * SSE 下行:`event: prompt`(taskId 对照)→ `event: update`(session/update 通知)→
599
+ * 交互时 `event: request`(agent→client 请求)→ `event: result`(stopReason 终帧)。
600
+ */
601
+ /**
602
+ * ACP `session/prompt`(add-acp-session-memory:conversation 多轮语义)。
603
+ * 首轮 = `run_task(sessionMode=conversation)`(创建 bridge 会话);后续轮 = `send_message`
604
+ * (续接同一会话,CLI 原生续接,token 只传增量)。SSE 下行:`event: prompt` →
605
+ * `event: update`(agent_message_chunk)→ 交互时 `event: request` → `event: result`
606
+ * (本轮 turn 结束:waiting_user → end_turn;turn 失败 → JSON-RPC error,会话随之关闭)。
607
+ */
608
+ const handleAcpSessionPrompt = (ctx, authorize, rpcId, params) => {
609
+ if (!authorize('task:create'))
610
+ return;
611
+ const conversation = deps.conversation;
612
+ if (!conversation) {
613
+ rpcErr(ctx.res, rpcId, ACP_JSONRPC_ERRORS.unsupportedOperation, 'conversation 编排未接入(该进程未启用多轮会话)');
614
+ return;
615
+ }
616
+ const sessionId = params?.['sessionId'];
617
+ if (typeof sessionId !== 'string' || !sessionId) {
618
+ rpcErr(ctx.res, rpcId, ACP_JSONRPC_ERRORS.invalidParams, 'params.sessionId 必须是非空字符串');
619
+ return;
620
+ }
621
+ const session = acpSessions.get(sessionId);
622
+ // 跨租户:统一按不存在处理(不暴露「存在但不是你的」)
623
+ if (!session || session.tenantId !== (ctx.tenantId ?? DEFAULT_TENANT)) {
624
+ rpcErr(ctx.res, rpcId, ACP_JSONRPC_ERRORS.sessionNotFound, `ACP 会话不存在:${sessionId}`);
625
+ return;
626
+ }
627
+ if (session.currentTurnId) {
628
+ rpcErr(ctx.res, rpcId, ACP_JSONRPC_ERRORS.promptBusy, `会话 ${sessionId} 已有进行中的轮次(turn ${session.currentTurnId}),先 session/cancel`);
629
+ return;
630
+ }
631
+ const text = acpPromptToText(params?.['prompt']);
632
+ if ('unsupported' in text) {
633
+ rpcErr(ctx.res, rpcId, ACP_JSONRPC_ERRORS.invalidParams, text.unsupported);
634
+ return;
635
+ }
636
+ // 续轮前置检查:bridge 会话已终态(空闲回收/失败)→ 如实拒绝,让客户端 session/new 重开
637
+ // (重启后的 acpSession 登记丢失走 sessionNotFound,同一条诚实原则)
638
+ if (session.bridgeSessionId) {
639
+ const bridge = deps.store.getSession(session.bridgeSessionId, session.tenantId);
640
+ if (!bridge || bridge.status !== 'running') {
641
+ rpcErr(ctx.res, rpcId, ACP_JSONRPC_ERRORS.sessionNotFound, `会话已结束(${bridge?.status ?? 'missing'}):请 session/new 新建会话`);
642
+ return;
643
+ }
644
+ }
645
+ // 透传 Bearer(dispatch 层的服务身份校验与 HTTP 鉴权同一令牌体系)
646
+ const header = ctx.req.headers['authorization'];
647
+ const raw = Array.isArray(header) ? header[0] : header;
648
+ const token = raw?.startsWith('Bearer ') ? raw.slice(7).trim() : undefined;
649
+ const bridgeSessionId = session.bridgeSessionId ?? `bt_${randomBytes(6).toString('hex')}`;
650
+ const isFirstTurn = session.bridgeSessionId === undefined;
651
+ session.bridgeSessionId = bridgeSessionId;
652
+ ctx.res.writeHead(200, {
653
+ 'content-type': 'text/event-stream; charset=utf-8',
654
+ 'cache-control': 'no-cache, no-transform',
655
+ connection: 'keep-alive',
656
+ 'x-accel-buffering': 'no',
657
+ });
658
+ const writeFrame = (event, data) => {
659
+ try {
660
+ ctx.res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
661
+ }
662
+ catch {
663
+ /* 客户端已断开 */
664
+ }
665
+ };
666
+ writeFrame('prompt', { sessionId, taskId: bridgeSessionId, turn: isFirstTurn ? 'first' : 'continue' });
667
+ let lastContent;
668
+ let currentTurnId;
669
+ let closed = false;
670
+ const writeUpdate = (text) => {
671
+ writeFrame('update', {
672
+ jsonrpc: '2.0',
673
+ method: 'session/update',
674
+ params: {
675
+ sessionId,
676
+ update: {
677
+ sessionUpdate: 'agent_message_chunk',
678
+ content: { type: 'text', text },
679
+ },
680
+ },
681
+ });
682
+ };
683
+ /** 本轮 turn 收尾:waiting_user → end_turn(会话保持开放);终帧后关流、清 currentTurnId */
684
+ const finishTurn = (stopReason) => {
685
+ const current = acpSessions.get(sessionId);
686
+ if (current && current.currentTurnId === currentTurnId)
687
+ current.currentTurnId = undefined;
688
+ writeFrame('result', { jsonrpc: '2.0', id: rpcId, result: { sessionId, stopReason, content: lastContent } });
689
+ cleanup();
690
+ };
691
+ /** 会话终态(turn 失败/超时):conversation 语义是会话随之关闭;error 帧不用假成功 */
692
+ const finishSession = (status, info) => {
693
+ const current = acpSessions.get(sessionId);
694
+ if (current && current.currentTurnId === currentTurnId)
695
+ current.currentTurnId = undefined;
696
+ writeFrame('result', {
697
+ jsonrpc: '2.0',
698
+ id: rpcId,
699
+ error: {
700
+ code: -32000,
701
+ message: `会话${status === 'timeout' ? '超时' : status === 'cancelled' ? '被取消' : '失败'}:${info?.error ?? 'no detail'}`,
702
+ data: { bridgeStatus: status, exitCode: info?.exitCode },
703
+ },
704
+ });
705
+ cleanup();
706
+ };
707
+ const reject = (errorCode) => {
708
+ const current = acpSessions.get(sessionId);
709
+ if (current)
710
+ current.currentTurnId = undefined;
711
+ writeFrame('result', {
712
+ jsonrpc: '2.0',
713
+ id: rpcId,
714
+ error: { code: -32000, message: `消息被拒绝:${errorCode}`, data: { code: errorCode } },
715
+ });
716
+ cleanup();
717
+ };
718
+ /** 等待人工交互:把 pending 交互转成 agent→client 请求帧 */
719
+ const sendPendingInteractions = () => {
720
+ const pendings = deps.store.queryInteractions({ sessionId: bridgeSessionId, tenantId: session.tenantId, state: 'pending', limit: 10 });
721
+ for (const interaction of pendings) {
722
+ const key = `gwir_${++outboundSeq}`;
723
+ const frame = toAcpRequestFrame(interaction.kind, interaction);
724
+ if ('invalid' in frame) {
725
+ deps.log('error', `[gateway] ACP 交互 ${interaction.requestId} 映射失败:${frame.invalid}`);
726
+ continue;
727
+ }
728
+ outboundRequests.set(key, {
729
+ requestId: interaction.requestId,
730
+ sessionId: bridgeSessionId,
731
+ tenantId: session.tenantId,
732
+ kind: interaction.kind,
733
+ });
734
+ writeFrame('request', { jsonrpc: '2.0', id: key, method: frame.method, params: frame.params });
735
+ }
736
+ };
737
+ const cleanup = () => {
738
+ if (closed)
739
+ return;
740
+ closed = true;
741
+ off();
742
+ clearInterval(heartbeat);
743
+ // 出站请求登记随流结束清理(客户端应答晚到 → 404 出站请求不存在,诚实失败)
744
+ for (const [key, value] of outboundRequests) {
745
+ if (value.sessionId === bridgeSessionId && value.kind === 'permission')
746
+ outboundRequests.delete(key);
747
+ }
748
+ try {
749
+ ctx.res.end();
750
+ }
751
+ catch {
752
+ /* already ended */
753
+ }
754
+ };
755
+ const send = (upstream) => {
756
+ if (closed)
757
+ return;
758
+ const msg = upstream;
759
+ if (!('taskId' in msg) || msg.taskId !== bridgeSessionId)
760
+ return;
761
+ // message_ack:queued/duplicate 锁定本轮 turnId;rejected → 拒绝帧
762
+ if (msg.type === 'message_ack') {
763
+ if (typeof msg.turnId === 'string' && currentTurnId === undefined)
764
+ currentTurnId = msg.turnId;
765
+ if (msg.delivery === 'rejected')
766
+ reject(String(msg.errorCode ?? 'rejected'));
767
+ return;
768
+ }
769
+ // turn 过滤:currentTurnId 锁定前,第一个带 turnId 的事件即本轮(订阅先于发起,无旧轮噪声)
770
+ const turnId = 'turnId' in msg && typeof msg.turnId === 'string' ? msg.turnId : undefined;
771
+ if (turnId !== undefined && currentTurnId === undefined)
772
+ currentTurnId = turnId;
773
+ if (turnId !== undefined && currentTurnId !== undefined && turnId !== currentTurnId)
774
+ return;
775
+ if (msg.type === 'task_message' && msg.state === 'complete') {
776
+ lastContent = msg.text;
777
+ writeUpdate(msg.text);
778
+ }
779
+ else if (msg.type === 'task_status') {
780
+ if (msg.status !== 'running') {
781
+ finishSession(msg.status, { error: msg.error, exitCode: msg.exitCode });
782
+ return;
783
+ }
784
+ if (msg.phase === 'waiting_user') {
785
+ finishTurn('end_turn');
786
+ return;
787
+ }
788
+ if (msg.phase === 'waiting_interaction')
789
+ sendPendingInteractions();
790
+ }
791
+ };
792
+ // 订阅先于发起:run/message 的同步 emit(turn 建立、ack)全部实时可达,无需回放
793
+ const off = deps.emitter.subscribe(send);
794
+ const heartbeat = setInterval(() => writeFrame('heartbeat', { at: Date.now() }), 15_000);
795
+ heartbeat.unref?.();
796
+ ctx.req.on('close', cleanup);
797
+ ctx.res.on('close', cleanup);
798
+ // 发起本轮(在 SSE 与订阅就绪之后)
799
+ void (async () => {
800
+ try {
801
+ if (isFirstTurn) {
802
+ conversation.run({
803
+ type: 'run_task',
804
+ taskId: bridgeSessionId,
805
+ agentType: session.agentType,
806
+ cwd: session.cwd,
807
+ args: [],
808
+ prompt: text.text,
809
+ sessionMode: 'conversation',
810
+ requestedBy: 'acp-gateway',
811
+ ...(token ? { serviceToken: token } : {}),
812
+ });
813
+ // 首轮 turn:dispatchConversationRun 同步建 turn
814
+ const turn = deps.store.listTurns(bridgeSessionId, session.tenantId).at(-1);
815
+ if (turn && currentTurnId === undefined) {
816
+ currentTurnId = turn.turnId;
817
+ session.currentTurnId = turn.turnId;
818
+ }
819
+ }
820
+ else {
821
+ const messageId = `acpmsg_${randomBytes(6).toString('hex')}`;
822
+ await conversation.message({
823
+ type: 'send_message',
824
+ taskId: bridgeSessionId,
825
+ messageId,
826
+ parts: [{ kind: 'text', text: text.text }],
827
+ ...(token ? { serviceToken: token } : {}),
828
+ });
829
+ // 续轮 turn:message_ack(queued).turnId 已由 send 捕获;兜底查 store(queued/running 的最新 turn)
830
+ if (currentTurnId === undefined) {
831
+ const turn = deps.store.listTurns(bridgeSessionId, session.tenantId).at(-1);
832
+ if (turn && (turn.status === 'queued' || turn.status === 'running')) {
833
+ currentTurnId = turn.turnId;
834
+ session.currentTurnId = turn.turnId;
835
+ }
836
+ }
837
+ else {
838
+ session.currentTurnId = currentTurnId;
839
+ }
840
+ }
841
+ }
842
+ catch (error) {
843
+ reject(error?.code ?? 'conversation_error');
844
+ }
845
+ })();
846
+ };
847
+ /** ACP `session/cancel`:取消当前轮次(cancel_turn 编排;无活动轮次静默成功——notification 语义) */
848
+ const handleAcpSessionCancel = (ctx, authorize, rpcId, params) => {
849
+ if (!authorize('task:cancel'))
850
+ return;
851
+ const conversation = deps.conversation;
852
+ const sessionId = params?.['sessionId'];
853
+ if (typeof sessionId !== 'string' || !sessionId) {
854
+ rpcErr(ctx.res, rpcId, ACP_JSONRPC_ERRORS.invalidParams, 'params.sessionId 必须是非空字符串');
855
+ return;
856
+ }
857
+ const session = acpSessions.get(sessionId);
858
+ if (!session || session.tenantId !== (ctx.tenantId ?? DEFAULT_TENANT)) {
859
+ rpcErr(ctx.res, rpcId, ACP_JSONRPC_ERRORS.sessionNotFound, `ACP 会话不存在:${sessionId}`);
860
+ return;
861
+ }
862
+ if (!session.currentTurnId || !session.bridgeSessionId) {
863
+ // v1 notification 语义:无活动轮次时静默成功(不报错)
864
+ rpcOk(ctx.res, rpcId, { cancelled: false });
865
+ return;
866
+ }
867
+ if (!conversation) {
868
+ rpcErr(ctx.res, rpcId, ACP_JSONRPC_ERRORS.unsupportedOperation, 'conversation 编排未接入');
869
+ return;
870
+ }
871
+ // 先取局部快照:cancel 会经 Emitter 触发 prompt 流 finish,把 currentTurnId 清掉
872
+ const turnId = session.currentTurnId;
873
+ const taskId = session.bridgeSessionId;
874
+ const header = ctx.req.headers['authorization'];
875
+ const raw = Array.isArray(header) ? header[0] : header;
876
+ const token = raw?.startsWith('Bearer ') ? raw.slice(7).trim() : undefined;
877
+ conversation.cancelTurn({
878
+ type: 'cancel_turn',
879
+ taskId,
880
+ turnId,
881
+ operationId: `acpcancel_${randomBytes(6).toString('hex')}`,
882
+ ...(token ? { serviceToken: token } : {}),
883
+ });
884
+ rpcOk(ctx.res, rpcId, { cancelled: true, taskId, turnId });
885
+ };
886
+ /**
887
+ * ACP 客户端应答 agent→client 请求(响应报文:无 method、带 id + result)。
888
+ * 走与 `POST /v1/interactions/{id}:respond` **同一条** dispatch 路径(权限判定双保险)。
889
+ */
890
+ const handleAcpInteractionAnswer = async (ctx, authorize, body) => {
891
+ const respond = deps.respondInteraction;
892
+ const key = body['id'];
893
+ if (typeof key !== 'string') {
894
+ json(ctx.res, 400, { error: '交互应答的 id 必须是网关下发的字符串' });
895
+ return;
896
+ }
897
+ const pending = outboundRequests.get(key);
898
+ if (!pending) {
899
+ json(ctx.res, 404, { error: `未找到出站请求 ${key}(流已结束或不存在)` });
900
+ return;
901
+ }
902
+ // 按交互种类要 scope(与 HTTP :respond 同规则);dispatch 内部还会复核一次
903
+ if (!authorize(pending.kind === 'permission' ? 'task:approve' : 'task:respond'))
904
+ return;
905
+ const kind = pending.kind;
906
+ let state;
907
+ let payload;
908
+ if (kind === 'permission') {
909
+ const outcome = fromAcpPermissionOutcome(body['result']);
910
+ if ('invalid' in outcome) {
911
+ json(ctx.res, 400, { error: outcome.invalid });
912
+ return;
913
+ }
914
+ if (outcome.state === 'accepted') {
915
+ state = 'accepted';
916
+ payload = { optionId: outcome.optionId };
917
+ }
918
+ else {
919
+ state = 'cancelled';
920
+ }
921
+ }
922
+ else {
923
+ const outcome = fromAcpElicitationResult(body['result']);
924
+ if ('invalid' in outcome) {
925
+ json(ctx.res, 400, { error: outcome.invalid });
926
+ return;
927
+ }
928
+ if (outcome.state === 'accepted') {
929
+ state = 'accepted';
930
+ payload = { content: outcome.content };
931
+ }
932
+ else {
933
+ state = outcome.state === 'declined' ? 'declined' : 'cancelled';
934
+ }
935
+ }
936
+ if (!respond) {
937
+ json(ctx.res, 501, { error: '当前进程未启用交互响应通道(只读模式)' });
938
+ return;
939
+ }
940
+ const header = ctx.req.headers['authorization'];
941
+ const raw = Array.isArray(header) ? header[0] : header;
942
+ const token = raw?.startsWith('Bearer ') ? raw.slice(7).trim() : undefined;
943
+ const outcome = await respond({
944
+ type: 'task_interaction_response',
945
+ taskId: pending.sessionId,
946
+ requestId: pending.requestId,
947
+ responseId: `rs_${key.replace(/[^a-z0-9_]/gi, '').slice(0, 24) || 'gw'}`,
948
+ tenantId: pending.tenantId,
949
+ state,
950
+ ...(payload ? { payload } : {}),
951
+ ...(token ? { serviceToken: token } : {}),
952
+ });
953
+ if (outcome.ok) {
954
+ json(ctx.res, 200, { ok: true, state: outcome.state, resultSeq: outcome.resultSeq });
955
+ }
956
+ else {
957
+ json(ctx.res, 409, { ok: false, errorCode: outcome.errorCode });
958
+ }
959
+ };
960
+ const handleAcp = (ctx, authorize) => {
961
+ const body = ctx.body;
962
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
963
+ json(ctx.res, 400, { error: '请求体必须是单个 JSON-RPC 2.0 对象' });
964
+ return;
965
+ }
966
+ if (body['jsonrpc'] !== '2.0') {
967
+ json(ctx.res, 400, { error: 'jsonrpc 字段必须是 "2.0"' });
968
+ return;
969
+ }
970
+ // 响应报文(客户端应答 agent→client 请求):无 method、带 id+result
971
+ if (typeof body['method'] !== 'string' || !body['method']) {
972
+ if (body['result'] !== undefined || body['error'] !== undefined) {
973
+ void handleAcpInteractionAnswer(ctx, authorize, body);
974
+ return;
975
+ }
976
+ json(ctx.res, 400, { error: '缺 method(请求)或 result/error(应答)' });
977
+ return;
978
+ }
979
+ const method = body['method'];
980
+ const rpcId = body['id'] === undefined ? null : body['id'];
981
+ const params = body['params'];
982
+ if (method === 'initialize') {
983
+ handleAcpInitialize(ctx);
984
+ return;
985
+ }
986
+ if (method === 'session/new') {
987
+ handleAcpSessionNew(ctx, authorize, rpcId, params);
988
+ return;
989
+ }
990
+ if (method === 'session/prompt') {
991
+ handleAcpSessionPrompt(ctx, authorize, rpcId, params);
992
+ return;
993
+ }
994
+ if (method === 'session/cancel') {
995
+ handleAcpSessionCancel(ctx, authorize, rpcId, params);
996
+ return;
997
+ }
998
+ rpcErr(ctx.res, rpcId, ACP_JSONRPC_ERRORS.methodNotFound, `ACP 方法未实现:${method}(当前支持 initialize/session/new/session/prompt/session/cancel)`);
999
+ };
1000
+ return {
1001
+ agentCard: handleAgentCard,
1002
+ a2a: handleA2a,
1003
+ acp: handleAcp,
1004
+ };
1005
+ }