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
@@ -6,8 +6,27 @@
6
6
  *
7
7
  * 上行一律经 `Emitter.emit()`(终态幂等 / 日志脱敏 / 审计 / 信封收口都在这条路上)。
8
8
  */
9
+ import { readFileSync, statSync } from 'node:fs';
10
+ import { createHash, randomUUID } from 'node:crypto';
11
+ import { join } from 'node:path';
12
+ import { hasAnsi } from '../core/ansi.js';
13
+ import { resolveWithinCwd, mimeTypeOf } from '../core/artifact-extract.js';
14
+ import { approvalExpiry, approvalFingerprint, canAutoApprove, PERSISTENT_OPTION_KINDS, permissionTarget, persistentAllowOption, } from '../core/permission-ledger.js';
9
15
  import { startTask } from '../runner.js';
16
+ import { ARTIFACT_INLINE_MAX_BYTES } from '../protocol.js';
10
17
  import { authorizeService } from './service-gate.js';
18
+ import { writeAudit } from '../infra/audit.js';
19
+ import { canRunAcp } from '../adapters/acp-codebuddy.js';
20
+ import { acpSpecFor, agentDefOf } from '../adapters/agent-adapters.js';
21
+ import { DEFAULT_TENANT } from '../core/session-store.js';
22
+ import { dispatchConversationRun } from './conversation.js';
23
+ function clearIdleTimer(o, sessionId) {
24
+ const timer = o.idleTimers?.get(sessionId);
25
+ if (!timer)
26
+ return;
27
+ clearTimeout(timer);
28
+ o.idleTimers?.delete(sessionId);
29
+ }
11
30
  /** 取消同样要鉴权:拿到 task:create 的令牌不等于能杀别人的任务 */
12
31
  export function dispatchCancelTask(msg, o) {
13
32
  const gate = authorizeService(msg, 'cancel_task', msg.taskId, 'task:cancel', o.requireServiceToken);
@@ -17,8 +36,318 @@ export function dispatchCancelTask(msg, o) {
17
36
  }
18
37
  o.tasks.get(msg.taskId)?.cancel();
19
38
  }
20
- export function dispatchRunTask(msg, o) {
21
- const gate = authorizeService(msg, 'run_task', msg.taskId, 'task:create', o.requireServiceToken);
39
+ function terminalStatus(status) {
40
+ return status === 'success' || status === 'failed' || status === 'cancelled' || status === 'timeout';
41
+ }
42
+ function ackSession(o, msg, action, ok, extra = {}) {
43
+ o.emitter.emit({
44
+ type: 'session_ack',
45
+ taskId: msg.taskId,
46
+ operationId: msg.operationId,
47
+ action,
48
+ ok,
49
+ status: extra.status,
50
+ errorCode: extra.errorCode,
51
+ at: new Date().toISOString(),
52
+ });
53
+ }
54
+ export function dispatchCloseSession(msg, o) {
55
+ const gate = authorizeService(msg, 'cancel_task', msg.taskId, 'task:cancel', o.requireServiceToken);
56
+ if (!gate.ok) {
57
+ ackSession(o, msg, 'close_session', false, { errorCode: gate.code });
58
+ return;
59
+ }
60
+ const session = o.store.getSession(msg.taskId);
61
+ if (!session) {
62
+ ackSession(o, msg, 'close_session', false, { errorCode: 'session_not_found' });
63
+ return;
64
+ }
65
+ if (session.status !== 'running') {
66
+ clearIdleTimer(o, msg.taskId);
67
+ o.residentSessions?.get(msg.taskId)?.close();
68
+ o.residentSessions?.delete(msg.taskId);
69
+ ackSession(o, msg, 'close_session', true, { status: session.status });
70
+ return;
71
+ }
72
+ const handle = o.tasks.get(msg.taskId);
73
+ if (handle) {
74
+ clearIdleTimer(o, msg.taskId);
75
+ handle.cancel();
76
+ ackSession(o, msg, 'close_session', true, { status: 'cancelled' });
77
+ return;
78
+ }
79
+ const active = o.store.getActiveTurn(msg.taskId);
80
+ if (active) {
81
+ o.store.updateTurn(msg.taskId, active.turnId, {
82
+ status: 'cancelled',
83
+ stopReason: 'session_closed',
84
+ finishedAt: new Date().toISOString(),
85
+ });
86
+ }
87
+ clearIdleTimer(o, msg.taskId);
88
+ const closed = o.store.closeSession(msg.taskId, 'cancelled', 'session_closed');
89
+ o.residentSessions?.get(msg.taskId)?.close();
90
+ o.residentSessions?.delete(msg.taskId);
91
+ ackSession(o, msg, 'close_session', true, { status: closed.status });
92
+ }
93
+ export function dispatchCancelTurn(msg, o) {
94
+ const gate = authorizeService(msg, 'cancel_task', msg.taskId, 'task:cancel', o.requireServiceToken);
95
+ if (!gate.ok) {
96
+ ackSession(o, msg, 'cancel_turn', false, { errorCode: gate.code });
97
+ return;
98
+ }
99
+ const session = o.store.getSession(msg.taskId);
100
+ if (!session) {
101
+ ackSession(o, msg, 'cancel_turn', false, { errorCode: 'session_not_found' });
102
+ return;
103
+ }
104
+ const active = o.store.getActiveTurn(msg.taskId);
105
+ if (!active || active.turnId !== msg.turnId) {
106
+ ackSession(o, msg, 'cancel_turn', false, { errorCode: 'turn_not_found' });
107
+ return;
108
+ }
109
+ const handle = o.tasks.get(msg.taskId);
110
+ if (handle) {
111
+ handle.cancel();
112
+ ackSession(o, msg, 'cancel_turn', true, { status: 'cancelled' });
113
+ return;
114
+ }
115
+ o.store.updateTurn(msg.taskId, active.turnId, {
116
+ status: 'cancelled',
117
+ stopReason: 'turn_cancelled',
118
+ finishedAt: new Date().toISOString(),
119
+ });
120
+ if (session.mode === 'task') {
121
+ o.store.closeSession(msg.taskId, 'cancelled', 'turn_cancelled');
122
+ }
123
+ else {
124
+ o.store.updateSession(msg.taskId, { phase: 'waiting_user' });
125
+ }
126
+ ackSession(o, msg, 'cancel_turn', true, { status: 'cancelled' });
127
+ }
128
+ /** WS 与 HTTP 只做鉴权和适配器入口接线;响应矩阵统一由当前 supervisor 的 Broker 判定。 */
129
+ export async function dispatchInteractionResponse(msg, o) {
130
+ const interaction = o.store.getInteraction(msg.taskId, msg.requestId, msg.tenantId ?? 'default');
131
+ if (!interaction)
132
+ return { ok: false, errorCode: 'interaction_not_found' };
133
+ const scope = interaction.kind === 'permission' ? 'task:approve' : 'task:respond';
134
+ const gate = authorizeService(msg, 'task_interaction_response', msg.taskId, scope, o.requireServiceToken);
135
+ if (!gate.ok)
136
+ return { ok: false, errorCode: gate.code };
137
+ if (!o.interactions)
138
+ return { ok: false, errorCode: 'internal' };
139
+ const outcome = await o.interactions.respond(msg);
140
+ if (outcome.deliveryFailed)
141
+ o.tasks.get(msg.taskId)?.cancel();
142
+ // 交互响应审计(5.11,spec「响应幂等、限流与审计」):记 who/what/result,
143
+ // 只写 optionId(permission)或 action(form),Form content 的值绝不落审计。
144
+ writeAudit({
145
+ at: new Date().toISOString(),
146
+ action: 'interaction_response',
147
+ outcome: outcome.ok ? 'allowed' : 'denied',
148
+ taskId: msg.taskId,
149
+ requestId: msg.requestId,
150
+ responseId: msg.responseId,
151
+ kind: interaction.kind,
152
+ choice: interaction.kind === 'permission'
153
+ ? (typeof msg.payload?.['optionId'] === 'string' ? String(msg.payload['optionId']) : msg.state)
154
+ : msg.state === 'accepted'
155
+ ? 'accept'
156
+ : msg.state === 'declined'
157
+ ? 'decline'
158
+ : 'cancel',
159
+ requestedBy: msg.respondedBy,
160
+ reason: outcome.ok ? undefined : (outcome.errorCode ?? 'rejected'),
161
+ });
162
+ // 仅首次 accepted 且真实交付成功才写账本;duplicate/replay/conflict 不得重复授权。
163
+ if (outcome.ok &&
164
+ outcome.deliveredNow === true &&
165
+ outcome.result?.responseStatus === 'accepted' &&
166
+ msg.state === 'accepted' &&
167
+ interaction.kind === 'permission' &&
168
+ o.approvalLedger?.enabled) {
169
+ const optionId = outcome.result.resolution?.['optionId'];
170
+ const rawOptions = interaction.payload?.['options'];
171
+ const options = Array.isArray(rawOptions)
172
+ ? rawOptions.filter((option) => typeof option === 'object' && option !== null)
173
+ : [];
174
+ const chosenKind = options.find((option) => option['optionId'] === optionId)?.['kind'];
175
+ if (typeof chosenKind === 'string' && PERSISTENT_OPTION_KINDS.includes(chosenKind)) {
176
+ persistApproval(o, msg, interaction.payload, gate, chosenKind);
177
+ }
178
+ }
179
+ return outcome;
180
+ }
181
+ export function dispatchGetTask(msg, o) {
182
+ const gate = authorizeService(msg, 'get_task', msg.taskId, 'task:read', o.requireServiceToken);
183
+ if (!gate.ok) {
184
+ o.emitter.emit({
185
+ type: 'task_snapshot',
186
+ taskId: msg.taskId,
187
+ requestId: msg.requestId,
188
+ found: false,
189
+ errorCode: gate.code,
190
+ });
191
+ return;
192
+ }
193
+ // 两个游标语义相反,同时给只能猜一个 —— 宁可明确拒绝,也不静默挑一个
194
+ if (msg.afterEventSeq !== undefined && msg.beforeEventSeq !== undefined) {
195
+ o.emitter.emit({
196
+ type: 'task_snapshot',
197
+ taskId: msg.taskId,
198
+ requestId: msg.requestId,
199
+ found: false,
200
+ errorCode: 'protocol_incompatible',
201
+ });
202
+ return;
203
+ }
204
+ // 会话不存在要分成两种:从没存在过 / 存在过但内容已删(tombstone)。后者永不复用该 ID,
205
+ // 平台据 session_deleted 就该放弃重试,而不是拿 task_not_found 反复重发。
206
+ if (!o.store.getSession(msg.taskId)) {
207
+ const tombstone = o.store.getTombstone(msg.taskId);
208
+ o.emitter.emit({
209
+ type: 'task_snapshot',
210
+ taskId: msg.taskId,
211
+ requestId: msg.requestId,
212
+ found: false,
213
+ errorCode: tombstone ? 'session_deleted' : 'task_not_found',
214
+ });
215
+ return;
216
+ }
217
+ try {
218
+ const snapshot = o.store.snapshot(msg.taskId, {
219
+ ...(msg.afterEventSeq !== undefined ? { afterEventSeq: msg.afterEventSeq } : {}),
220
+ ...(msg.beforeEventSeq !== undefined ? { beforeEventSeq: msg.beforeEventSeq } : {}),
221
+ limit: msg.limit,
222
+ });
223
+ const prunedThrough = snapshot.prunedThrough ?? 0;
224
+ // 游标落在已裁剪区间:内容确实取不回来了。found 仍为 true(任务在),
225
+ // errorCode 表达的是「这次补取的完整性结论」,平台据此显示"更早的历史已清理"。
226
+ const cursor = msg.beforeEventSeq !== undefined
227
+ ? msg.beforeEventSeq
228
+ : msg.afterEventSeq !== undefined
229
+ ? msg.afterEventSeq
230
+ : undefined;
231
+ const pruned = cursor !== undefined && cursor < prunedThrough;
232
+ o.emitter.emit({
233
+ type: 'task_snapshot',
234
+ taskId: msg.taskId,
235
+ requestId: msg.requestId,
236
+ found: true,
237
+ ...(pruned ? { errorCode: 'session_history_pruned' } : {}),
238
+ session: snapshot.session,
239
+ turns: snapshot.turns,
240
+ events: snapshot.events.map((event) => ({
241
+ eventSeq: event.eventSeq,
242
+ type: event.type,
243
+ payload: event.payload,
244
+ createdAt: event.createdAt,
245
+ })),
246
+ oldestEventSeq: snapshot.oldestEventSeq,
247
+ latestEventSeq: snapshot.latestEventSeq,
248
+ ...(() => {
249
+ const partial = o.partialMessages?.(msg.taskId) ?? [];
250
+ return partial.length ? { partialMessages: partial } : {};
251
+ })(),
252
+ ...(() => {
253
+ const pending = o.store
254
+ .listInteractions(msg.taskId)
255
+ .find((interaction) => interaction.state === 'pending' || interaction.state === 'submitting');
256
+ return pending ? { pendingInteraction: pending } : {};
257
+ })(),
258
+ ...(() => {
259
+ const results = o.store.listLatestInteractionResults(msg.taskId);
260
+ return results.length
261
+ ? { interactionResults: results }
262
+ : {};
263
+ })(),
264
+ hasMoreBefore: snapshot.hasMoreBefore ?? false,
265
+ ...(prunedThrough > 0 ? { prunedThrough } : {}),
266
+ // 缺口必须一起给:平台拿到连续的 [oldest, latest] 不代表中间没丢
267
+ eventWindow: {
268
+ oldestEventSeq: snapshot.oldestEventSeq,
269
+ latestEventSeq: snapshot.latestEventSeq,
270
+ gaps: o.store.eventGaps(msg.taskId, snapshot.session.tenantId),
271
+ },
272
+ });
273
+ }
274
+ catch (error) {
275
+ o.emitter.emit({
276
+ type: 'task_snapshot',
277
+ taskId: msg.taskId,
278
+ requestId: msg.requestId,
279
+ found: false,
280
+ errorCode: 'task_not_found',
281
+ });
282
+ o.log('error', `[agent-bridge] 读取快照失败 ${msg.taskId}:${error.message}`);
283
+ }
284
+ }
285
+ /**
286
+ * `get_artifact`:按 artifactId 从持久元数据 + CAS 取回内容(1.0)。
287
+ *
288
+ * 为什么不能顺手把内容塞进 task_artifact:那是**事件**,重放会重复传输;
289
+ * 而这里是平台主动补取(终态后仍可用)。超过内联上限只回元数据 + `too_large`,
290
+ * 让平台走 artifact_download 分块通道 —— 大块 base64 会拖垮 WS 心跳。
291
+ * 也**不重读工作区**:避免 TOCTOU 与内容漂移,只认已落盘的那份。
292
+ */
293
+ export function dispatchGetArtifact(msg, o) {
294
+ const deny = (errorCode) => {
295
+ o.emitter.emit({
296
+ type: 'artifact_content',
297
+ taskId: msg.taskId,
298
+ artifactId: msg.artifactId,
299
+ requestId: msg.requestId,
300
+ found: false,
301
+ errorCode,
302
+ });
303
+ };
304
+ // 读产物与 get_task 同权(都是读该任务的结果面)
305
+ const gate = authorizeService(msg, 'get_artifact', msg.taskId, 'task:read', o.requireServiceToken);
306
+ if (!gate.ok) {
307
+ deny(gate.code);
308
+ return;
309
+ }
310
+ const session = o.store.getSession(msg.taskId);
311
+ const record = o.store.getArtifact(msg.artifactId, session?.tenantId);
312
+ // 必须同时校验归属:拿 A 任务的 id 读 B 任务的附件属于越权,不是「找不到」
313
+ if (!record || record.sessionId !== msg.taskId) {
314
+ deny('artifact_not_found');
315
+ return;
316
+ }
317
+ const meta = {
318
+ type: 'artifact_content',
319
+ taskId: msg.taskId,
320
+ artifactId: record.artifactId,
321
+ requestId: msg.requestId,
322
+ found: true,
323
+ name: record.name,
324
+ mimeType: record.mimeType,
325
+ size: record.size,
326
+ sha256: record.sha256,
327
+ kind: record.kind,
328
+ };
329
+ if (record.size > ARTIFACT_INLINE_MAX_BYTES) {
330
+ o.emitter.emit({ ...meta, contentUnavailableReason: 'too_large' });
331
+ return;
332
+ }
333
+ try {
334
+ if (!o.artifactRootDir)
335
+ throw new Error('未配置附件根目录');
336
+ const data = readFileSync(join(o.artifactRootDir, record.storageKey));
337
+ o.emitter.emit({ ...meta, data: data.toString('base64') });
338
+ }
339
+ catch (error) {
340
+ // 元数据还在但 CAS 文件已回收:如实回 not_readable,不伪造成「任务不存在」
341
+ o.emitter.emit({ ...meta, contentUnavailableReason: 'not_readable' });
342
+ o.log('error', `[agent-bridge] 读取附件失败 ${record.artifactId}:${error.message}`);
343
+ }
344
+ }
345
+ export function dispatchRunTask(msg, o, recoveryTurnId, recoveryTenantId) {
346
+ const storeTenant = recoveryTenantId ?? DEFAULT_TENANT;
347
+ // queued 恢复来自本机 SQLite 中已鉴权、已接受的执行快照,不伪造旧 serviceToken 重验。
348
+ const gate = recoveryTurnId
349
+ ? { ok: true }
350
+ : authorizeService(msg, 'run_task', msg.taskId, 'task:create', o.requireServiceToken);
22
351
  if (!gate.ok) {
23
352
  o.log('error', `[agent-bridge] 拒绝执行 ${msg.taskId}:${gate.message}`);
24
353
  o.emitter.emit({
@@ -31,8 +360,94 @@ export function dispatchRunTask(msg, o) {
31
360
  });
32
361
  return;
33
362
  }
363
+ if (msg.sessionMode === 'conversation') {
364
+ dispatchConversationRun(msg, o);
365
+ return;
366
+ }
367
+ let sessionCreated = false;
368
+ let turn;
369
+ try {
370
+ const existing = o.store.getSession(msg.taskId, storeTenant);
371
+ if (existing && existing.status !== 'running') {
372
+ // SQLite 终态优先于内存句柄生命周期:即使 done 的清理微任务尚未执行,也绝不重新校验/spawn。
373
+ // 回放原始终态快照,保留首次拒绝的 errorCode、权限结果与 eventSeq,而不是另造一个通用失败。
374
+ const terminal = o.store.getLatestEvent(msg.taskId, 'task_status', storeTenant);
375
+ const payload = terminal && typeof terminal.payload === 'object' && terminal.payload !== null
376
+ ? terminal.payload
377
+ : { error: '会话已结束(幂等重放,未重复执行)' };
378
+ const latestTurn = o.store.listTurns(msg.taskId, storeTenant).at(-1);
379
+ o.emitter.emit({
380
+ ...payload,
381
+ type: 'task_status',
382
+ taskId: msg.taskId,
383
+ status: existing.status,
384
+ turnId: latestTurn?.turnId,
385
+ eventSeq: terminal?.eventSeq,
386
+ });
387
+ return;
388
+ }
389
+ if (!existing) {
390
+ const created = o.store.createSession({
391
+ sessionId: msg.taskId,
392
+ tenantId: storeTenant,
393
+ mode: 'task',
394
+ agentType: msg.agentType,
395
+ cwd: msg.cwd,
396
+ phase: 'queued',
397
+ });
398
+ sessionCreated = created.created;
399
+ turn = o.store.createTurn({
400
+ sessionId: msg.taskId,
401
+ status: 'queued',
402
+ execution: {
403
+ args: [...msg.args],
404
+ prompt: msg.prompt,
405
+ timeoutMs: msg.timeoutMs,
406
+ allowInteractive: msg.allowInteractive,
407
+ captureDiff: msg.captureDiff,
408
+ permissionMode: msg.permissionMode,
409
+ requestedBy: msg.requestedBy,
410
+ purpose: msg.purpose,
411
+ },
412
+ });
413
+ }
414
+ else if (recoveryTurnId) {
415
+ const recovered = o.store.getTurn(msg.taskId, recoveryTurnId, storeTenant);
416
+ if (!recovered || recovered.status !== 'queued')
417
+ return;
418
+ turn = recovered;
419
+ sessionCreated = true;
420
+ }
421
+ }
422
+ catch (error) {
423
+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : 'session_store_error';
424
+ o.emitter.emit({
425
+ type: 'task_status',
426
+ taskId: msg.taskId,
427
+ status: 'failed',
428
+ error: `会话状态不可用:${error.message}`,
429
+ errorCode: code,
430
+ requestedBy: msg.requestedBy,
431
+ });
432
+ return;
433
+ }
34
434
  const who = msg.requestedBy ? `(${msg.requestedBy}${msg.purpose ? ` / ${msg.purpose}` : ''})` : '';
35
435
  o.log('info', `\n▶ 执行任务 ${msg.taskId}:${msg.agentType}${who}`);
436
+ o.registry.register(msg.taskId, { agentType: msg.agentType, cwd: msg.cwd, source: 'platform', tenantId: storeTenant });
437
+ // 交互额度(1.0):按任务计数,不是全局 —— 一个任务问爆了不该拖累别的任务
438
+ const maxInteractions = o.maxInteractionsPerTask ?? 16;
439
+ const interactionBudgetMs = o.interactionTimeoutMs ?? 15 * 60 * 1000;
440
+ let interactionCount = 0;
441
+ /** 交互过期时刻:适配器给了 expiresAt 就取较小值,绝不让单次等待超过本机上限 */
442
+ const interactionDeadline = (requested) => {
443
+ const cap = Date.now() + interactionBudgetMs;
444
+ const asked = requested ? Date.parse(requested) : NaN;
445
+ return new Date(Number.isFinite(asked) ? Math.min(asked, cap) : cap).toISOString();
446
+ };
447
+ // full 不需要原生权限回问:非交互时直接选 headless,别让上游无条件选 ACP/app-server 后被 supervisor 拒死。
448
+ // full + allowInteractive 仍保留不支持通道,由 supervisor 按契约拒绝,不静默吞掉交互请求。
449
+ const headlessFull = (msg.permissionMode === 'full' || (msg.permissionMode === undefined && o.permissionPolicy === 'full')) &&
450
+ msg.allowInteractive !== true;
36
451
  const handle = startTask({
37
452
  taskId: msg.taskId,
38
453
  agentType: msg.agentType,
@@ -45,37 +460,498 @@ export function dispatchRunTask(msg, o) {
45
460
  maxQueued: o.maxQueued,
46
461
  captureDiff: msg.captureDiff === true || o.captureDiffByDefault,
47
462
  diffMaxBytes: o.diffMaxBytes,
463
+ // 权限模式(1.0):平台请求 + 本机策略设备,实际模式由 TaskSupervisor 在 spawn 前定判
464
+ permissionMode: msg.permissionMode,
465
+ permissionPolicy: o.permissionPolicy,
466
+ externalSandbox: o.externalSandbox,
467
+ interactionSessionId: msg.taskId,
468
+ interactionTenantId: storeTenant,
469
+ interactive: msg.allowInteractive === true && o.interactionEnabled === true,
470
+ acp: !headlessFull && Boolean(msg.prompt) && canRunAcp(agentDefOf(msg.agentType)?.acp),
471
+ acpSpec: acpSpecFor(agentDefOf(msg.agentType)),
472
+ appServer: !headlessFull && msg.agentType === 'codex' && Boolean(msg.prompt),
473
+ /**
474
+ * 双向 stream-json 通道只给 claude-code。
475
+ *
476
+ * qoder-cli 虽然也支持 `--input-format stream-json`(实测输出与 claude 同构),但
477
+ * **不认 `--verbose`**,而这条通道的启动旗标是按 claude 写死的 —— 实测
478
+ * `qodercli -p --input-format stream-json --output-format stream-json --verbose`
479
+ * 直接 `unknown option '--verbose'` 退出。与其塞一套它不认的参数,
480
+ * 不如让它走 headless(`-p --output-format stream-json` + resumeArgs,已实测能跑且能续会话)。
481
+ */
482
+ claudeStream: Boolean(msg.prompt) &&
483
+ msg.allowInteractive === true &&
484
+ o.interactionEnabled === true &&
485
+ msg.agentType === 'claude-code',
48
486
  }, {
487
+ onBeforeLaunch: () => turn ? o.store.claimTurnForLaunch(msg.taskId, turn.turnId, turn.tenantId) : true,
49
488
  onLog: (stream, data) => {
50
489
  const text = data.replace(/\x1b\[[0-9;]*m/g, '');
51
490
  if (text.trim())
52
491
  o.log('info', `[${stream}] ${text.trimEnd()}`);
53
- o.emitter.emit({ type: 'task_log', taskId: msg.taskId, stream, data, isAnsi: true });
492
+ let eventSeq;
493
+ if (sessionCreated) {
494
+ eventSeq = o.store.appendEvent({
495
+ sessionId: msg.taskId,
496
+ tenantId: storeTenant,
497
+ type: 'task_log',
498
+ payload: { stream, data, isAnsi: hasAnsi(data) },
499
+ }).eventSeq;
500
+ }
501
+ o.emitter.emit({
502
+ type: 'task_log',
503
+ taskId: msg.taskId,
504
+ stream,
505
+ data,
506
+ isAnsi: hasAnsi(data),
507
+ turnId: turn?.turnId,
508
+ eventSeq,
509
+ });
510
+ },
511
+ // 步骤流(B 批次):仅 steps:true 的工具会触发;label 的截断与脱敏在 Emitter 收口
512
+ onStep: (step) => {
513
+ o.registry.updateStep(msg.taskId, step);
514
+ const at = new Date().toISOString();
515
+ let eventSeq;
516
+ if (sessionCreated) {
517
+ eventSeq = o.store.appendEvent({
518
+ sessionId: msg.taskId,
519
+ tenantId: storeTenant,
520
+ type: 'task_step',
521
+ payload: { ...step, at },
522
+ }).eventSeq;
523
+ }
524
+ o.emitter.emit({
525
+ type: 'task_step',
526
+ taskId: msg.taskId,
527
+ ...step,
528
+ at,
529
+ turnId: turn?.turnId,
530
+ eventSeq,
531
+ });
532
+ },
533
+ onPlan: (items) => {
534
+ o.registry.updatePlan(msg.taskId, items);
535
+ },
536
+ // 中间 agent 消息(4.7):canonical task_message(complete 语义;text 的脱敏在 Emitter 出口)。
537
+ // appendMessage 同事务写 messages + events(message.eventSeq 即事件序号,不重复 appendEvent);
538
+ // 同 ID 同文本 duplicate 直接短路;同 ID 异文本抛 session_conflict —— 跳过并记日志,不阻塞任务。
539
+ onAgentMessage: (message) => {
540
+ if (!sessionCreated)
541
+ return;
542
+ const messageId = message.messageId ?? `msg_${msg.taskId}_am_${randomUUID().replace(/-/g, '').slice(0, 12)}`;
543
+ try {
544
+ const saved = o.store.appendMessage({
545
+ sessionId: msg.taskId,
546
+ tenantId: storeTenant,
547
+ messageId,
548
+ role: 'agent',
549
+ text: message.text,
550
+ turnId: turn?.turnId,
551
+ });
552
+ if (saved.duplicate)
553
+ return;
554
+ o.emitter.emit({
555
+ type: 'task_message',
556
+ taskId: msg.taskId,
557
+ messageId,
558
+ role: 'agent',
559
+ state: 'complete',
560
+ text: message.text,
561
+ turnId: turn?.turnId,
562
+ eventSeq: saved.message.eventSeq,
563
+ at: saved.message.createdAt,
564
+ });
565
+ }
566
+ catch (error) {
567
+ o.log('warn', `[agent-bridge] 中间消息 ${messageId} 未落库:${error.message}`);
568
+ }
569
+ },
570
+ onSession: (nativeSessionId) => {
571
+ try {
572
+ o.store.updateSession(msg.taskId, { nativeSessionId }, storeTenant);
573
+ }
574
+ catch (error) {
575
+ o.log('error', `[agent-bridge] 保存 native session id 失败 ${msg.taskId}:${error.message}`);
576
+ }
577
+ },
578
+ onInteraction: (request) => {
579
+ // 本机关闭交互 / 超出单任务额度:**主动回拒绝**而不是静默丢弃 ——
580
+ // 静默会让上游的 Promise 一直悬着,任务白等到总超时。
581
+ const refuse = (why) => {
582
+ o.tasks.get(msg.taskId)?.respondInteraction?.(request.requestId, { action: 'decline' });
583
+ o.log('info', `[agent-bridge] ${why},已拒绝交互 ${request.kind}/${request.requestId}`);
584
+ };
585
+ if (o.interactionEnabled !== true) {
586
+ refuse('交互已关闭');
587
+ return;
588
+ }
589
+ interactionCount += 1;
590
+ if (interactionCount > maxInteractions) {
591
+ refuse(`交互次数超过上限 ${maxInteractions}`);
592
+ return;
593
+ }
594
+ const expiresAt = interactionDeadline(request.expiresAt);
595
+ try {
596
+ if (!o.interactions)
597
+ throw new Error('InteractionBroker 未接入');
598
+ o.interactions.open({
599
+ sessionId: msg.taskId,
600
+ requestId: request.requestId,
601
+ kind: request.kind,
602
+ payload: request.payload,
603
+ turnId: turn?.turnId,
604
+ expiresAt,
605
+ tenantId: storeTenant,
606
+ });
607
+ // waiting 状态由 supervisor 在 request 持久化/上行后统一发出。
608
+ }
609
+ catch (error) {
610
+ o.log('error', `[agent-bridge] 创建交互失败 ${msg.taskId}:${error.message}`);
611
+ }
54
612
  },
613
+ onApprovalLookup: (input) => resolveApproval(o, input, msg.taskId),
55
614
  onStatus: (status, info) => {
615
+ o.registry.updateStatus(msg.taskId, status, info);
616
+ // 权限判定审计(每个任务一条,终态时落):只写策略名/模式/结果,不写 argv 与环境值
617
+ if (terminalStatus(status)) {
618
+ const deniedByPolicy = info?.errorCode === 'permission_policy_denied' || info?.errorCode === 'permission_mode_unsupported';
619
+ writeAudit({
620
+ at: new Date().toISOString(),
621
+ action: 'permission_decision',
622
+ outcome: deniedByPolicy ? 'denied' : 'allowed',
623
+ taskId: msg.taskId,
624
+ agent: msg.agentType,
625
+ requestedBy: msg.requestedBy,
626
+ purpose: msg.purpose,
627
+ policy: o.permissionPolicy ?? 'default',
628
+ permissionMode: info?.permissionMode,
629
+ reason: deniedByPolicy ? info?.error : undefined,
630
+ });
631
+ }
56
632
  if (info?.changedFiles?.length) {
57
633
  o.log('info', `[agent-bridge] 变更 ${info.changedFiles.length} 个文件:${info.changedFiles.slice(0, 8).join(', ')}`);
58
634
  }
635
+ let eventSeq;
636
+ if (sessionCreated) {
637
+ try {
638
+ // 最终回答先落 canonical task_message,再落终态;平台按 eventSeq 可完整重建。
639
+ if (terminalStatus(status) && info?.result?.trim()) {
640
+ const at = new Date().toISOString();
641
+ const messageId = `msg_${msg.taskId}_final`;
642
+ const messageEvent = o.store.appendEvent({
643
+ sessionId: msg.taskId,
644
+ tenantId: storeTenant,
645
+ type: 'task_message',
646
+ payload: {
647
+ messageId,
648
+ role: 'agent',
649
+ state: 'complete',
650
+ text: info.result,
651
+ turnId: turn?.turnId,
652
+ at,
653
+ },
654
+ });
655
+ o.emitter.emit({
656
+ type: 'task_message',
657
+ taskId: msg.taskId,
658
+ messageId,
659
+ role: 'agent',
660
+ state: 'complete',
661
+ text: info.result,
662
+ turnId: turn?.turnId,
663
+ eventSeq: messageEvent.eventSeq,
664
+ at,
665
+ });
666
+ }
667
+ // 任务产物元数据(4.9):captureDiff 捕到的 changedFiles 只生成元数据事件。
668
+ // spec「附件路径安全」:无 adapter 明确 artifact 事件时**不读取内容** ——
669
+ // size 用 stat(元数据操作,经 resolveWithinCwd 安全检查),sha256 省略并显式给出原因;
670
+ // 越界/凭据/已清理的文件连名字都不上行。内容下载必须等 adapter artifact 事件(get_artifact 如实 404)。
671
+ if (terminalStatus(status) && info?.changedFiles?.length) {
672
+ const at = new Date().toISOString();
673
+ for (const file of info.changedFiles.slice(0, 50)) {
674
+ const within = resolveWithinCwd(msg.cwd, file);
675
+ if (!within.ok)
676
+ continue;
677
+ let size = 0;
678
+ try {
679
+ size = statSync(within.abs).size;
680
+ }
681
+ catch {
682
+ continue; // 任务自己清理掉了:没有产物就没有事件
683
+ }
684
+ const artifactId = `af_${msg.taskId}_${createHash('sha256')
685
+ .update(file)
686
+ .digest('hex')
687
+ .slice(0, 12)}`;
688
+ const artifactEvent = o.store.appendEvent({
689
+ sessionId: msg.taskId,
690
+ tenantId: storeTenant,
691
+ type: 'task_artifact',
692
+ payload: {
693
+ artifactId,
694
+ name: file,
695
+ mimeType: mimeTypeOf(file),
696
+ size,
697
+ kind: 'output',
698
+ source: 'agent',
699
+ contentUnavailableReason: 'no_adapter_artifact_event',
700
+ turnId: turn?.turnId,
701
+ at,
702
+ },
703
+ });
704
+ o.emitter.emit({
705
+ type: 'task_artifact',
706
+ taskId: msg.taskId,
707
+ artifactId,
708
+ name: file,
709
+ mimeType: mimeTypeOf(file),
710
+ size,
711
+ kind: 'output',
712
+ source: 'agent',
713
+ contentUnavailableReason: 'no_adapter_artifact_event',
714
+ eventSeq: artifactEvent.eventSeq,
715
+ });
716
+ }
717
+ }
718
+ const nextPhase = status === 'running'
719
+ ? info?.phase === 'queued'
720
+ ? 'queued'
721
+ : info?.phase === 'waiting_interaction'
722
+ ? 'waiting_interaction'
723
+ : 'running'
724
+ : 'settled';
725
+ o.store.updateSession(msg.taskId, { phase: nextPhase }, storeTenant);
726
+ if (turn) {
727
+ const at = new Date().toISOString();
728
+ const turnPatch = {
729
+ status: status === 'running'
730
+ ? info?.phase === 'queued'
731
+ ? 'queued'
732
+ : 'running'
733
+ : status,
734
+ };
735
+ if (status === 'running' && info?.phase !== 'queued')
736
+ turnPatch.startedAt = at;
737
+ if (terminalStatus(status))
738
+ turnPatch.finishedAt = at;
739
+ o.store.updateTurn(msg.taskId, turn.turnId, turnPatch, storeTenant);
740
+ }
741
+ const payload = {
742
+ taskId: msg.taskId,
743
+ status,
744
+ exitCode: info?.exitCode,
745
+ error: info?.error,
746
+ errorCode: info?.errorCode,
747
+ phase: info?.phase,
748
+ interactionId: info?.interactionId,
749
+ queuePosition: info?.queuePosition,
750
+ diff: info?.diff,
751
+ changedFiles: info?.changedFiles,
752
+ diffTruncated: info?.diffTruncated,
753
+ requestedBy: msg.requestedBy,
754
+ permissionMode: info?.permissionMode,
755
+ stopReason: info?.stopReason,
756
+ feedIncomplete: info?.feedIncomplete,
757
+ };
758
+ eventSeq = o.store.appendEvent({
759
+ sessionId: msg.taskId,
760
+ tenantId: storeTenant,
761
+ type: 'task_status',
762
+ payload,
763
+ }).eventSeq;
764
+ if (terminalStatus(status)) {
765
+ o.store.closeSession(msg.taskId, status, info?.error, storeTenant);
766
+ }
767
+ }
768
+ catch (error) {
769
+ o.log('error', `[agent-bridge] 会话事件落库失败 ${msg.taskId}:${error.message}`);
770
+ }
771
+ }
59
772
  o.emitter.emit({
60
773
  type: 'task_status',
61
774
  taskId: msg.taskId,
62
775
  status,
63
776
  exitCode: info?.exitCode,
64
777
  error: info?.error,
65
- // 受控错误码:给平台做程序化分支(error 仍是可直接展示的人类可读串)
66
778
  errorCode: info?.errorCode,
67
- // 排队语义:status 恒为 running,phase/queuePosition 供新平台区分(v1 兼容)
68
779
  phase: info?.phase,
780
+ interactionId: info?.interactionId,
69
781
  queuePosition: info?.queuePosition,
70
- // P0-6:终态带 diff(未开启 captureDiff 时这些字段都是 undefined,不会出现在 JSON 里)
71
782
  diff: info?.diff,
72
783
  changedFiles: info?.changedFiles,
73
784
  diffTruncated: info?.diffTruncated,
74
- // P0-8:回显服务身份,供平台落 requested_by 审计
75
785
  requestedBy: msg.requestedBy,
786
+ permissionMode: info?.permissionMode,
787
+ stopReason: info?.stopReason,
788
+ feedIncomplete: info?.feedIncomplete,
789
+ turnId: turn?.turnId,
790
+ eventSeq,
76
791
  });
77
792
  },
78
793
  });
79
794
  o.tasks.set(msg.taskId, handle);
80
795
  void handle.done.then(() => o.tasks.delete(msg.taskId));
81
796
  }
797
+ /**
798
+ * 把一次人工「持久允许」写进账本(1.0 approval ledger)。
799
+ *
800
+ * 三条保险,任一不满足就只留审计、不落库:
801
+ * 1. 本机开了账本(`approval_ledger_enabled`)—— 调用方已判;
802
+ * 2. 响应方通过 `task:approve` 且**额外**具备 `approval:persist` —— 授权别人的未来任务比批一次更重;
803
+ * 3. 能定位到 agent 与资源 —— 定位不了就不猜(不按 title/模型文本造授权)。
804
+ *
805
+ * ⚠️ 落库失败也绝不抛:本次响应已经发出,会话内授权由 ACP 自己维持。
806
+ */
807
+ function persistApproval(o, msg, requestPayload, gate, optionKind) {
808
+ const ledger = o.approvalLedger;
809
+ if (!ledger)
810
+ return;
811
+ const at = new Date().toISOString();
812
+ const session = o.store.getSession(msg.taskId, undefined);
813
+ const agentType = session?.agentType;
814
+ if (!agentType) {
815
+ o.log('warn', `[ledger] 无法确定 ${msg.taskId} 的 agent,跳过持久授权`);
816
+ return;
817
+ }
818
+ let persistScope;
819
+ if (ledger.requirePersistScope === false) {
820
+ persistScope = { ok: true, scopes: gate.scopes };
821
+ }
822
+ else if (gate.scopes === undefined) {
823
+ // 没有令牌 = 未鉴权:兼容模式(require_service_token=false)下不落库,只提示
824
+ persistScope = { ok: false, scopes: [], reason: 'no_service_token' };
825
+ }
826
+ else if (!gate.scopes.includes('approval:persist')) {
827
+ persistScope = { ok: false, scopes: gate.scopes, reason: 'missing_scope:approval:persist' };
828
+ }
829
+ else {
830
+ persistScope = { ok: true, scopes: gate.scopes };
831
+ }
832
+ if (!persistScope.ok) {
833
+ writeAudit({
834
+ at,
835
+ action: 'approval_grant',
836
+ outcome: 'denied',
837
+ taskId: msg.taskId,
838
+ agent: agentType,
839
+ cwd: session?.cwd,
840
+ requestedBy: msg.respondedBy,
841
+ scopes: persistScope.scopes,
842
+ reason: persistScope.reason,
843
+ });
844
+ o.log('warn', `[ledger] 不落库(${persistScope.reason}):本次授权仅在当前会话内有效`);
845
+ return;
846
+ }
847
+ const target = permissionTarget(requestPayload['toolCall'], session?.cwd);
848
+ // 同上:没有资源就不落库。写一条「通用授权」等于给该工具开永久后门。
849
+ if (target.resourceKey === '-') {
850
+ writeAudit({
851
+ at,
852
+ action: 'approval_grant',
853
+ outcome: 'denied',
854
+ taskId: msg.taskId,
855
+ agent: agentType,
856
+ cwd: session?.cwd,
857
+ requestedBy: msg.respondedBy,
858
+ reason: 'no_resource_to_bind',
859
+ });
860
+ o.log('warn', '[ledger] 该请求没有可绑定的资源,不写入持久授权(仅在当前会话有效)');
861
+ return;
862
+ }
863
+ const fingerprint = approvalFingerprint({ agentType, tool: target.tool, resourceKey: target.resourceKey });
864
+ const approvalId = `ap_${randomUUID().replace(/-/g, '').slice(0, 20)}`;
865
+ try {
866
+ o.store.addApproval({
867
+ tenantId: ledger.tenantId,
868
+ approvalId,
869
+ principalId: msg.respondedBy ?? 'local',
870
+ agentType,
871
+ tool: target.tool,
872
+ action: 'permission',
873
+ resource: target.display,
874
+ scope: optionKind,
875
+ fingerprint,
876
+ expiresAt: approvalExpiry(Date.now(), ledger.ttlMs),
877
+ createdAt: at,
878
+ });
879
+ writeAudit({
880
+ at,
881
+ action: 'approval_grant',
882
+ outcome: 'allowed',
883
+ taskId: msg.taskId,
884
+ agent: agentType,
885
+ cwd: session?.cwd,
886
+ requestedBy: msg.respondedBy,
887
+ scopes: persistScope.scopes,
888
+ approvalId,
889
+ reason: `tool=${target.tool} resource=${target.display} expires=${approvalExpiry(Date.now(), ledger.ttlMs)}`,
890
+ });
891
+ o.log('info', `[ledger] 已记住授权 ${approvalId}(tool=${target.tool}),可用 approvals revoke 撤销`);
892
+ }
893
+ catch (error) {
894
+ writeAudit({
895
+ at,
896
+ action: 'approval_grant',
897
+ outcome: 'error',
898
+ taskId: msg.taskId,
899
+ agent: agentType,
900
+ requestedBy: msg.respondedBy,
901
+ reason: error.message,
902
+ });
903
+ o.log('error', `[ledger] 持久授权写入失败:${error.message}`);
904
+ }
905
+ }
906
+ /**
907
+ * 查询持久授权(1.0):命中就返回**请求里真实存在**的 optionId。
908
+ *
909
+ * 独立成函数而非内联在 hooks 里,是因为「命中判定」是安全边界,必须能被单测直接打到。
910
+ * 判定规则全在 `canAutoApprove()`;这里只负责取指纹、找记录、写审计。
911
+ */
912
+ export function resolveApproval(o, input, taskId) {
913
+ const ledger = o.approvalLedger;
914
+ // 账本未开启时既没有记录也不该查(等价于从未授过权)
915
+ if (ledger?.enabled !== true)
916
+ return undefined;
917
+ const target = permissionTarget(input.toolCall, input.cwd);
918
+ // 没有可归一化的资源时一律不自动批准:否则所有「无资源」请求会共享同一个指纹,
919
+ // 等于批准一次就永久放开该工具的全部调用 —— 这比不给账本更危险。
920
+ if (target.resourceKey === '-') {
921
+ o.log('info', '[ledger] 请求没有可归一化的资源,不自动批准(继续询问)');
922
+ return undefined;
923
+ }
924
+ const fingerprint = approvalFingerprint({
925
+ agentType: input.agentType,
926
+ tool: target.tool,
927
+ resourceKey: target.resourceKey,
928
+ });
929
+ const record = o.store.findApproval(ledger.tenantId, input.agentType, fingerprint);
930
+ const option = persistentAllowOption(input.options);
931
+ const verdict = canAutoApprove(record, {
932
+ fingerprint,
933
+ permissionMode: input.permissionMode,
934
+ hasPersistentOption: option !== undefined,
935
+ });
936
+ if (!verdict.ok) {
937
+ // 未命中是常态,不留审计噪声;只有"本来有记录却用不上"才值得记一行
938
+ if (record && verdict.reason !== 'no_persistent_option') {
939
+ o.log('info', `[ledger] 未自动批准:${verdict.reason}`);
940
+ }
941
+ return undefined;
942
+ }
943
+ writeAudit({
944
+ at: new Date().toISOString(),
945
+ action: 'approval_hit',
946
+ outcome: 'allowed',
947
+ taskId,
948
+ agent: input.agentType,
949
+ cwd: input.cwd,
950
+ approvalId: record?.approvalId,
951
+ reason: `tool=${target.tool} resource=${target.display}`,
952
+ permissionMode: input.permissionMode,
953
+ });
954
+ if (!option)
955
+ return undefined;
956
+ return { optionId: option.optionId, approvalId: record?.approvalId ?? '' };
957
+ }