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
@@ -17,19 +17,29 @@
17
17
  * settled 是吸收态:只 settle 一次、只释放一次名额(终态上行的幂等由 Emitter 负责)。
18
18
  */
19
19
  import { spawn } from 'node:child_process';
20
+ import { randomUUID } from 'node:crypto';
21
+ import { AcpAuthRequiredError, runAcpPrompt, } from '../adapters/acp-codebuddy.js';
22
+ import { runCodexPrompt } from '../adapters/codex-app-server.js';
23
+ import { runClaudeStreamPrompt } from '../adapters/claude-stream.js';
20
24
  import { existsSync, realpathSync, statSync } from 'node:fs';
21
25
  import { resolve as resolvePath, sep } from 'node:path';
22
- import { agentDefOf, resolveBin } from '../adapters/agent-adapters.js';
26
+ import { agentDefOf, killCliProcess, resolveBin, taskArgsForPermission } from '../adapters/agent-adapters.js';
23
27
  import { captureWorktreeDiff } from '../infra/git.js';
24
- import { chunkLog } from '../protocol.js';
28
+ import { chunkLog, } from '../protocol.js';
25
29
  import { buildWinCommandLine, isWinShim } from '../adapters/win-exec.js';
30
+ import { withoutHostEnv } from '../adapters/host-env.js';
31
+ import { createStepParser, claudeToolCallOf } from '../adapters/step-parsers.js';
26
32
  import { BridgeError } from './errors.js';
33
+ import { PartialMessageTracker, acpChunkText, claudeBlockText, codexDeltaText } from './partial-messages.js';
34
+ import { decidePermissionMode, fullResidualPermissionOutcome, permissionEnvFor } from './permission-policy.js';
35
+ import { externalProxyEnv } from '../infra/proxy-env.js';
36
+ import { InteractionBroker } from './interaction-broker.js';
27
37
  export const DEFAULT_TIMEOUT_MS = 10 * 60_000;
28
38
  export const KILL_GRACE_MS = 2000;
29
- /** 默认并发上限:几个大模型 CLI 同时跑就能卡死整机 */
30
- export const DEFAULT_MAX_TASKS = 3;
31
- /** 默认队列上限:再长的排队对调用方也没意义 */
32
- export const DEFAULT_MAX_QUEUED = 32;
39
+ /** 默认并发上限:30(2026-10-24 面向平台批量调度调整,原为 3);防呆夹取上限见 config.ts */
40
+ export const DEFAULT_MAX_TASKS = 30;
41
+ /** 默认队列上限:再长的排队对调用方也没意义(2026-10-24 由 32 调整为 60) */
42
+ export const DEFAULT_MAX_QUEUED = 60;
33
43
  /**
34
44
  * `child` 是否位于 `parent` 目录之下(含相等)。
35
45
  * 必须按目录边界判断;Windows 路径大小写不敏感,比较前统一折叠。
@@ -46,6 +56,34 @@ export function isUnder(child, parent) {
46
56
  function buildArgs(template, prompt) {
47
57
  return template.map((a) => (prompt === undefined ? a : a.replaceAll('{{prompt}}', prompt)));
48
58
  }
59
+ /**
60
+ * 认证守卫的有界缓冲匹配(纯函数便于单测):
61
+ * 模式可能跨 stderr 分片断裂,所以合并最近 4KB 再匹配;命中即「未登录/凭据失效」。
62
+ */
63
+ export function feedAuthGuard(guard, buffer, text) {
64
+ const merged = (buffer + text).slice(-4096);
65
+ return { buffer: merged, hit: guard.patterns.some((re) => re.test(merged)) };
66
+ }
67
+ /**
68
+ * 从 stdout 分片中提取首个原生 session id。
69
+ * 字段可能跨 chunk(DSH 实测为 sessionId);只保留最近 512 字符作为拼接尾,命中后停止扫描。
70
+ */
71
+ export function createNativeSessionDetector() {
72
+ let tail = '';
73
+ let found = false;
74
+ return (chunk) => {
75
+ if (found)
76
+ return undefined;
77
+ const merged = tail + chunk;
78
+ const match = /"(?:session_id|thread_id|conversation_id|sessionId|sessionID)"\s*:\s*"([A-Za-z0-9._:-]{1,200})"/.exec(merged);
79
+ if (match?.[1]) {
80
+ found = true;
81
+ return match[1];
82
+ }
83
+ tail = merged.slice(-512);
84
+ return undefined;
85
+ };
86
+ }
49
87
  function timeoutOf(req) {
50
88
  return req.timeoutMs && req.timeoutMs > 0 ? req.timeoutMs : DEFAULT_TIMEOUT_MS;
51
89
  }
@@ -67,20 +105,139 @@ function reject(req, hooks, code, message) {
67
105
  return { taskId: req.taskId, cancel: () => undefined, done: Promise.resolve('failed') };
68
106
  }
69
107
  export class TaskSupervisor {
108
+ /** 每个调度域独立的交互状态/交付 flight;不得使用模块级共享 Broker。 */
109
+ interactions = new InteractionBroker();
70
110
  running = 0;
71
111
  queue = [];
72
112
  maxTasks;
113
+ /**
114
+ * 活跃任务跟踪表(WS 重发同一 taskId 不重复 spawn 的内存快路径)。
115
+ *
116
+ * 只保留 queued/running/waiting 条目:settle 在 hooks.onStatus(生产 = SQLite 落库)
117
+ * 同步返回后即回收,容量天然有界(并发 + 队列上限)。
118
+ * 终态后的同 ID 重发由调度入口的 SQLite 前置检查拦截回放(task-dispatch 的
119
+ * getSession 终态回放 / control-plane 的 runIdempotent / conversation 的每轮新 executionId)
120
+ * —— SQLite 是唯一权威,这里不再保留 MAX_TRACKED 式的终态容量淘汰。
121
+ */
122
+ byId = new Map();
123
+ /** 最近一次提交生效的队列上限(上限本是请求级字段,水位上报取最近值) */
124
+ lastMaxQueued = DEFAULT_MAX_QUEUED;
125
+ capacityListeners = new Set();
126
+ /**
127
+ * 运行中任务的半截文本(`task_snapshot.partialMessages`)。
128
+ * 只放内存、只放**当前**回合,终态即清 —— 理由见 `core/partial-messages.ts` 的注释。
129
+ */
130
+ partials = new PartialMessageTracker();
73
131
  constructor(maxConcurrent = DEFAULT_MAX_TASKS) {
74
132
  this.maxTasks = maxConcurrent > 0 ? Math.floor(maxConcurrent) : DEFAULT_MAX_TASKS;
75
133
  }
134
+ /**
135
+ * 半截消息读取入口(`get_task` 用)。
136
+ * 放在实例上而不是模块级变量:调度状态必须可实例化,两个调度域不能互相串数据。
137
+ */
138
+ listPartialMessages(taskId) {
139
+ return this.partials.list(taskId);
140
+ }
141
+ /**
142
+ * 三条流式通道(ACP `agent_message_chunk` / codex `item/agentMessage/delta` /
143
+ * claude stream `text` block)的唯一写入口 —— 收敛到一个方法,才不会有的通道记、有的忘。
144
+ */
145
+ recordPartialText(taskId, text) {
146
+ this.partials.append(taskId, text);
147
+ }
76
148
  get runningCount() {
77
149
  return this.running;
78
150
  }
79
151
  get queuedCount() {
80
152
  return this.queue.length;
81
153
  }
154
+ /** 内存中跟踪的任务数(活跃 + 尚未被落库回调释放的瞬态)。观测/测试用;终态语义见 byId 注释。 */
155
+ get trackedTaskCount() {
156
+ return this.byId.size;
157
+ }
158
+ /** 订阅容量水位(每次调度状态变化后回调一次;回调异常不影响调度) */
159
+ subscribeCapacity(fn) {
160
+ this.capacityListeners.add(fn);
161
+ return () => this.capacityListeners.delete(fn);
162
+ }
163
+ capacitySnapshot() {
164
+ return {
165
+ running: this.running,
166
+ queued: this.queue.length,
167
+ maxTasks: this.maxTasks,
168
+ maxQueued: this.lastMaxQueued,
169
+ };
170
+ }
171
+ notifyCapacity() {
172
+ const snap = this.capacitySnapshot();
173
+ for (const fn of this.capacityListeners) {
174
+ try {
175
+ fn(snap);
176
+ }
177
+ catch {
178
+ /* 观察者绝不阻断调度 */
179
+ }
180
+ }
181
+ }
182
+ /** 登记活跃任务(终态在 settle 的落库回调后回收,见 settle()) */
183
+ track(entry) {
184
+ this.byId.set(entry.req.taskId, entry);
185
+ }
186
+ /** 取消逻辑收口:首个句柄与幂等重放句柄共用(取消本身是幂等的) */
187
+ cancelEntry(entry) {
188
+ if (entry.state === 'settled')
189
+ return;
190
+ if (entry.state === 'queued') {
191
+ this.settle(entry, 'cancelled', { error: '任务已取消(排队中被取消)', errorCode: 'cancelled' });
192
+ return;
193
+ }
194
+ entry.status = 'cancelled';
195
+ this.terminate(entry);
196
+ }
197
+ /**
198
+ * 幂等重放(A1):同一 taskId 重复提交时不再 spawn。
199
+ * 未终态回当前状态快照。settled 分支正常情况下不可达(终态条目在落库回调后即回收),
200
+ * 仅作为直接调用方无 SQLite 前置时的防御保留;生产幂等以 SQLite 为权威(见 byId 注释)。
201
+ */
202
+ replay(entry, hooks) {
203
+ if (entry.state === 'settled') {
204
+ hooks.onStatus(entry.status, entry.finishInfo ?? {});
205
+ }
206
+ else if (entry.state === 'queued') {
207
+ hooks.onStatus('running', {
208
+ phase: 'queued',
209
+ queuePosition: this.queue.indexOf(entry) + 1,
210
+ error: '任务已存在(幂等去重,未重复执行)',
211
+ });
212
+ }
213
+ else if (entry.state === 'waiting') {
214
+ hooks.onStatus('running', {
215
+ phase: 'waiting_interaction',
216
+ interactionId: entry.interactionId,
217
+ permissionMode: entry.permissionMode,
218
+ });
219
+ }
220
+ else {
221
+ hooks.onStatus('running');
222
+ }
223
+ return {
224
+ taskId: entry.req.taskId,
225
+ cancel: () => this.cancelEntry(entry),
226
+ done: entry.done,
227
+ write: (line) => this.writeTo(entry, line),
228
+ respondInteraction: (requestId, answer) => this.respondAcp(entry, requestId, answer),
229
+ steer: (text) => this.steerEntry(entry, text),
230
+ };
231
+ }
82
232
  /** 提交任务:校验 → 排队或立即启动。返回句柄(可取消、可 await 终态) */
83
233
  submit(req, hooks) {
234
+ // 幂等去重在最前:重发一律回放,不重复校验、不重复 spawn
235
+ const dup = this.byId.get(req.taskId);
236
+ if (dup)
237
+ return this.replay(dup, hooks);
238
+ // 新一次运行从干净桶开始:同一 taskId 被重试/复用时,不能带上一次的半截文本。
239
+ // 放在 dup 之后 —— 回放路径不该清掉正在跑的那个任务的累积。
240
+ this.partials.clear(req.taskId);
84
241
  const def = agentDefOf(req.agentType);
85
242
  if (!def) {
86
243
  return reject(req, hooks, 'tool_not_installed', `不支持的工具:${req.agentType}`);
@@ -91,7 +248,32 @@ export class TaskSupervisor {
91
248
  if (req.allowedCwd?.length && !req.allowedCwd.some((root) => isUnder(req.cwd, root))) {
92
249
  return reject(req, hooks, 'cwd_not_allowed', `工作目录不在允许范围内:${req.cwd}`);
93
250
  }
94
- const args = req.args.length > 0 ? req.args : buildArgs(def.taskArgs, req.prompt ?? '');
251
+ // 权限策略(1.0):在 spawn 前定判,拒绝即不产生任何子进程;不允许静默降级到 default
252
+ const permission = decidePermissionMode({
253
+ policy: req.permissionPolicy,
254
+ requested: req.permissionMode,
255
+ args: req.args,
256
+ fullArgs: def.fullArgs,
257
+ kind: def.kind,
258
+ externalSandbox: req.externalSandbox,
259
+ });
260
+ if (!permission.ok) {
261
+ return reject(req, hooks, permission.code, permission.message);
262
+ }
263
+ // 非 headless 通道尚未实现 full 权限映射:必须在解析/启动 CLI 前拒绝,不能丢掉 fullArgs 后按 default 跑。
264
+ if (permission.mode === 'full' && (req.acp || req.appServer || req.claudeStream)) {
265
+ return reject(req, hooks, 'permission_mode_unsupported', '该执行通道尚未实现 full 权限映射;请使用 headless default/full 组合,不以 default 静默降级');
266
+ }
267
+ const template = taskArgsForPermission(def, permission.mode);
268
+ /**
269
+ * `{{prompt}}` 的替换必须覆盖**两条来源**,不能只处理 adapter 模板:
270
+ * 1. 平台可以自己传 args,协议明写「平台可用 {{prompt}} 占位」(protocol.ts RunTaskCommand.args);
271
+ * 2. 会话续接是 bridge 自己拼的 `resumeArgs`(conversation.ts 只替换 {{sessionId}})。
272
+ * 原来只在「args 为空」时替换,这两条来源里的占位符会被原样交给 CLI ——
273
+ * 表现是任务照常 success,但模型收到的是字面量 `{{prompt}}`,用户这一轮说的话根本没进去。
274
+ */
275
+ const selectedArgs = req.args.length > 0 ? req.args : (req.internalArgs ?? template);
276
+ const args = buildArgs(selectedArgs, req.prompt ?? '');
95
277
  let cmd;
96
278
  let argv;
97
279
  if (def.npxSpec && !resolveBin([def.bin, ...(def.altBins ?? [])])) {
@@ -109,6 +291,7 @@ export class TaskSupervisor {
109
291
  if (req.maxConcurrent && req.maxConcurrent > 0)
110
292
  this.maxTasks = Math.floor(req.maxConcurrent);
111
293
  const maxQueued = req.maxQueued !== undefined && req.maxQueued >= 0 ? Math.floor(req.maxQueued) : DEFAULT_MAX_QUEUED;
294
+ this.lastMaxQueued = maxQueued;
112
295
  if (this.running >= this.maxTasks && this.queue.length >= maxQueued) {
113
296
  return reject(req, hooks, 'device_busy', `任务队列已满(并发 ${this.maxTasks},排队 ${maxQueued}),请稍后重试`);
114
297
  }
@@ -123,9 +306,18 @@ export class TaskSupervisor {
123
306
  argv,
124
307
  state: 'queued',
125
308
  status: 'running',
309
+ stepFormat: def.steps,
310
+ stepSeq: 0,
311
+ permissionMode: permission.mode,
312
+ permissionEnv: permissionEnvFor(def.kind, permission.mode),
313
+ preferSystemProxy: def.preferSystemProxy,
314
+ stepRefs: new Map(),
315
+ authGuard: def.authGuard,
316
+ authStderr: '',
126
317
  resolve,
127
318
  done,
128
319
  };
320
+ this.track(entry);
129
321
  // timeoutMs 从入队开始算:排队也是调用方的等待时间
130
322
  entry.timer = setTimeout(() => {
131
323
  if (entry.state === 'settled')
@@ -144,24 +336,98 @@ export class TaskSupervisor {
144
336
  hooks.onStatus('running', {
145
337
  phase: 'queued',
146
338
  queuePosition: this.queue.length,
339
+ permissionMode: permission.mode,
147
340
  error: `排队中(第 ${this.queue.length} 位,并发上限 ${this.maxTasks})`,
148
341
  });
149
342
  }
343
+ this.notifyCapacity();
150
344
  return {
151
345
  taskId: req.taskId,
152
- cancel: () => {
153
- if (entry.state === 'settled')
154
- return;
155
- if (entry.state === 'queued') {
156
- this.settle(entry, 'cancelled', { error: '任务已取消(排队中被取消)', errorCode: 'cancelled' });
157
- return;
158
- }
159
- entry.status = 'cancelled';
160
- this.terminate(entry);
161
- },
346
+ cancel: () => this.cancelEntry(entry),
162
347
  done,
348
+ write: (line) => this.writeTo(entry, line),
349
+ respondInteraction: (requestId, answer) => this.respondAcp(entry, requestId, answer),
350
+ steer: (text) => this.steerEntry(entry, text),
163
351
  };
164
352
  }
353
+ steerEntry(entry, text) {
354
+ if (entry.state !== 'running' || !entry.codexSteer)
355
+ return Promise.resolve(false);
356
+ return entry.codexSteer(text).then(() => true, () => false);
357
+ }
358
+ waitForInteraction(entry, requestId) {
359
+ if (entry.state !== 'running')
360
+ return;
361
+ entry.state = 'waiting';
362
+ entry.interactionId = requestId;
363
+ // waiting 仍占 running 名额,总 timeout 不从新计时。
364
+ entry.hooks.onStatus('running', {
365
+ phase: 'waiting_interaction',
366
+ interactionId: requestId,
367
+ permissionMode: entry.permissionMode,
368
+ });
369
+ }
370
+ async respondAcp(entry, requestId, answer) {
371
+ const deliver = entry.acpPermissions?.get(requestId);
372
+ if (!deliver)
373
+ return false;
374
+ entry.acpPermissions?.delete(requestId);
375
+ let delivered = false;
376
+ try {
377
+ delivered = await deliver(answer);
378
+ }
379
+ catch {
380
+ delivered = false;
381
+ }
382
+ return delivered;
383
+ }
384
+ /** Broker 在 result 落库并上行后调用,保证 result 先于 running。 */
385
+ completeInteraction(taskId, requestId) {
386
+ const entry = [...this.byId.values()].find((item) => item.interactionId === requestId && (item.req.interactionSessionId ?? item.req.taskId) === taskId);
387
+ if (!entry || entry.state !== 'waiting')
388
+ return;
389
+ entry.state = 'running';
390
+ entry.interactionId = undefined;
391
+ entry.hooks.onStatus('running', { phase: 'running', permissionMode: entry.permissionMode });
392
+ }
393
+ /** 首次 delivery unknown 的 result 上行后,再终止对应回合。 */
394
+ failInteraction(taskId, requestId) {
395
+ const entry = [...this.byId.values()].find((item) => item.interactionId === requestId && (item.req.interactionSessionId ?? item.req.taskId) === taskId);
396
+ if (!entry || entry.state === 'settled')
397
+ return;
398
+ entry.status = 'failed';
399
+ entry.acpAbort?.abort();
400
+ this.settle(entry, 'failed', {
401
+ error: '交互响应交付结果不确定,已终止回合且禁止重试',
402
+ errorCode: 'interaction_delivery_unknown',
403
+ });
404
+ }
405
+ /**
406
+ * 单次交互等待到期且无 reject_once 可选(spec「等待状态、超时与取消」):
407
+ * 已以 cancelled outcome 完成请求,这里取消回合并以 interaction_timeout 结算。
408
+ */
409
+ expireInteraction(taskId, requestId) {
410
+ const entry = [...this.byId.values()].find((item) => item.interactionId === requestId && (item.req.interactionSessionId ?? item.req.taskId) === taskId);
411
+ if (!entry || entry.state === 'settled')
412
+ return;
413
+ entry.status = 'cancelled';
414
+ entry.acpAbort?.abort();
415
+ this.settle(entry, 'cancelled', {
416
+ error: `交互等待超时(${requestId}),已取消回合`,
417
+ errorCode: 'interaction_timeout',
418
+ });
419
+ }
420
+ writeTo(entry, line) {
421
+ const stdin = entry.child?.stdin;
422
+ if (!stdin || stdin.destroyed || !stdin.writable)
423
+ return false;
424
+ try {
425
+ return stdin.write(line.endsWith('\n') ? line : `${line}\n`);
426
+ }
427
+ catch {
428
+ return false;
429
+ }
430
+ }
165
431
  // ---------- 内部 ----------
166
432
  pump() {
167
433
  while (this.running < this.maxTasks && this.queue.length > 0) {
@@ -174,28 +440,117 @@ export class TaskSupervisor {
174
440
  launch(entry) {
175
441
  if (entry.state !== 'queued')
176
442
  return;
443
+ if (entry.hooks.onBeforeLaunch && !entry.hooks.onBeforeLaunch()) {
444
+ this.settle(entry, 'failed', {
445
+ error: 'Turn 启动前持久化闸门未通过,未启动 CLI',
446
+ errorCode: 'internal',
447
+ });
448
+ return;
449
+ }
177
450
  entry.state = 'running';
178
451
  this.running += 1;
179
- // 子进程环境恒为 bridge 自身进程环境:平台**不能**注入环境变量
452
+ if (entry.req.acp) {
453
+ this.launchAcp(entry);
454
+ return;
455
+ }
456
+ if (entry.req.appServer) {
457
+ this.launchAppServer(entry);
458
+ return;
459
+ }
460
+ if (entry.req.claudeStream) {
461
+ this.launchClaudeStream(entry);
462
+ return;
463
+ }
464
+ // 子进程环境恒为 bridge 自身进程环境:平台**不能**注入环境变量。
465
+ // 唯一例外是 full 模式下 bridge 自己固定注入的那一个键(CodeBuddy 的沙箱声明)。
466
+ //
467
+ // 但「bridge 自身环境」里还混着宿主注入的会话上下文(CODEBUDDY_SESSION_ID /
468
+ // CODEBUDDY_MCP_CONFIG / SERVER__PORT…),子 CLI 继承会冒充宿主会话:
469
+ // 实测 codebuddy `-p` 因此去抢宿主端口,`listen EADDRINUSE 127.0.0.1:57193` 直接失败。
470
+ // 清理表与 ACP 通道共用(adapters/host-env.ts),认证令牌等例外也在那里声明。
471
+ const baseEnv = withoutHostEnv(process.env);
472
+ const childEnvBase = entry.permissionEnv ? { ...baseEnv, ...entry.permissionEnv } : baseEnv;
473
+ const childEnv = entry.preferSystemProxy ? externalProxyEnv(childEnvBase) : childEnvBase;
180
474
  const shim = isWinShim(entry.cmd);
475
+ const stdinMode = entry.req.interactive ? 'pipe' : 'ignore';
181
476
  const child = shim
182
477
  ? spawn(buildWinCommandLine(entry.cmd, entry.argv), {
183
478
  cwd: entry.req.cwd,
184
- env: process.env,
479
+ env: childEnv,
185
480
  shell: true,
186
481
  windowsHide: true,
187
- stdio: ['ignore', 'pipe', 'pipe'],
482
+ stdio: [stdinMode, 'pipe', 'pipe'],
188
483
  })
189
484
  : spawn(entry.cmd, entry.argv, {
190
485
  cwd: entry.req.cwd,
191
- env: process.env,
486
+ env: childEnv,
192
487
  windowsHide: true,
193
- stdio: ['ignore', 'pipe', 'pipe'],
488
+ stdio: [stdinMode, 'pipe', 'pipe'],
194
489
  });
195
490
  entry.child = child;
491
+ // 步骤流解析器(B 批次):仅声明了 steps 格式的工具;stdout 原样上行 task_log 不受影响
492
+ const stepParser = entry.stepFormat ? createStepParser(entry.stepFormat) : undefined;
493
+ entry.stepParser = stepParser;
494
+ const feedSteps = (text) => {
495
+ // 终态后不再产生 step/plan 上行:close 的 EOF flush 在 settle 之前喂(顺序见下方 close 回调),
496
+ // 守卫只拦「settle 之后才到达的迟到输出」——「拒绝终态后 log/step」的第一道闸门。
497
+ if (entry.state === 'settled')
498
+ return;
499
+ if (!stepParser)
500
+ return;
501
+ // 即使调用方不关心 onStep,也必须喂解析器:finalOutcome/finalText 是任务真实性的独立闸门。
502
+ for (const step of stepParser.feed(text)) {
503
+ const onStep = entry.hooks.onStep;
504
+ if (!onStep)
505
+ continue;
506
+ // finished 按 ref 配对回 started 的序号:tool_use/tool_result 是同一步的两半。
507
+ const paired = step.state === 'finished' && step.ref !== undefined ? entry.stepRefs.get(step.ref) : undefined;
508
+ if (paired !== undefined) {
509
+ onStep({ ...step, seq: paired });
510
+ continue;
511
+ }
512
+ entry.stepSeq += 1;
513
+ if (step.ref !== undefined)
514
+ entry.stepRefs.set(step.ref, entry.stepSeq);
515
+ onStep({ ...step, seq: entry.stepSeq });
516
+ }
517
+ // 中间 agent 消息(4.7):drain 语义,取走即清空;终态后由守卫拦住不再产生
518
+ const onAgentMessage = entry.hooks.onAgentMessage;
519
+ if (onAgentMessage && stepParser.drainMessages) {
520
+ for (const message of stepParser.drainMessages())
521
+ onAgentMessage(message);
522
+ }
523
+ const plan = stepParser.plan?.();
524
+ if (plan && entry.hooks.onPlan)
525
+ entry.hooks.onPlan(plan);
526
+ };
527
+ const detectNativeSession = createNativeSessionDetector();
196
528
  const emit = (stream, buf) => {
197
- for (const piece of chunkLog(buf.toString('utf8')))
529
+ // authGuard 命中路径是 kill 与 settle 同步连发:kill 生效前残余 data 已入队的
530
+ // 输出会在 settle 之后到达这里 —— 终态后一律不再上行(Emitter.settled 只是纵深防御)。
531
+ if (entry.state === 'settled')
532
+ return;
533
+ const text = buf.toString('utf8');
534
+ if (stream === 'stdout' && entry.hooks.onSession) {
535
+ const nativeSessionId = detectNativeSession(text);
536
+ if (nativeSessionId)
537
+ entry.hooks.onSession(nativeSessionId);
538
+ }
539
+ for (const piece of chunkLog(text))
198
540
  entry.hooks.onLog(stream, piece);
541
+ // 未登录挂死守卫(agy 实测):认证提示在 stderr 上**立即**出现,先于任何 stdout 事件;
542
+ // 不 kill 的话它会静默等 60s、吐完 status:"ERROR" 还不退出(干等总超时)。
543
+ if (stream === 'stderr' && entry.authGuard) {
544
+ const fed = feedAuthGuard(entry.authGuard, entry.authStderr, text);
545
+ entry.authStderr = fed.buffer;
546
+ if (fed.hit) {
547
+ if (entry.child)
548
+ killCliProcess(entry.child, entry.cmd);
549
+ this.settle(entry, 'failed', { error: entry.authGuard.hint, errorCode: 'tool_no_credentials' });
550
+ }
551
+ }
552
+ if (stream === 'stdout')
553
+ feedSteps(text);
199
554
  };
200
555
  child.stdout?.on('data', (b) => emit('stdout', b));
201
556
  child.stderr?.on('data', (b) => emit('stderr', b));
@@ -204,6 +559,8 @@ export class TaskSupervisor {
204
559
  errorCode: 'agent_error',
205
560
  }));
206
561
  child.on('close', (code) => {
562
+ // EOF 未必带末尾换行;只补解析器输入,不伪造一条 task_log。
563
+ feedSteps('\n');
207
564
  if (entry.status === 'timeout') {
208
565
  this.settle(entry, 'timeout', {
209
566
  exitCode: code ?? undefined,
@@ -219,23 +576,505 @@ export class TaskSupervisor {
219
576
  });
220
577
  }
221
578
  else if (code === 0) {
222
- this.settle(entry, 'success', { exitCode: 0 });
579
+ // 退出码 0 ≠ 完成(agy 官方文档:--print-timeout 到期以 0 结束并给部分结果)。
580
+ // 解析器见过流内终态且明示失败时推翻「成功」;没见过终态的流维持退出码语义。
581
+ const outcome = entry.stepParser?.finalOutcome?.();
582
+ if (outcome && outcome.ok === false) {
583
+ this.settle(entry, 'failed', {
584
+ exitCode: 0,
585
+ error: outcome.error ?? 'CLI 报告本回合未成功完成',
586
+ errorCode: 'agent_error',
587
+ ...(outcome.result !== undefined ? { result: outcome.result } : {}),
588
+ });
589
+ }
590
+ else {
591
+ this.settle(entry, 'success', { exitCode: 0 });
592
+ }
223
593
  }
224
594
  else {
595
+ // agy 类:退出码非 0 时流内终态错误(如 status=ERROR 的信封 error)比「退出码 N」可操作得多;
596
+ // 其他解析器不实现 finalOutcome,维持原文案不变
597
+ const outcome = entry.stepParser?.finalOutcome?.();
225
598
  this.settle(entry, 'failed', {
226
599
  exitCode: code ?? undefined,
227
- error: `CLI 退出码 ${code ?? 'unknown'}`,
600
+ error: outcome?.error ?? `CLI 退出码 ${code ?? 'unknown'}`,
228
601
  errorCode: 'agent_error',
602
+ ...(outcome?.result !== undefined ? { result: outcome.result } : {}),
603
+ });
604
+ }
605
+ });
606
+ entry.hooks.onStatus('running');
607
+ }
608
+ launchClaudeStream(entry) {
609
+ const controller = new AbortController();
610
+ entry.acpAbort = controller;
611
+ entry.hooks.onStatus('running');
612
+ void runClaudeStreamPrompt({
613
+ // entry.cmd 是 startTask 里 resolveBin 出来的绝对路径。不传的话 adapter 会默认 'claude',
614
+ // 于是 qoder-cli 的 stream 通道会去跑 claude 本体 —— 看起来「成功」,其实是别的工具在答。
615
+ command: entry.cmd,
616
+ cwd: entry.req.cwd,
617
+ prompt: entry.req.prompt ?? '',
618
+ nativeSessionId: entry.req.nativeSessionId,
619
+ timeoutMs: timeoutOf(entry.req),
620
+ signal: controller.signal,
621
+ onSession: (sessionId) => entry.hooks.onSession?.(sessionId),
622
+ onUpdate: (event) => {
623
+ // 终态后 stream-json 通道的残余 assistant 消息不再上行(同 onAcpUpdate 的在途窗口)
624
+ if (entry.state === 'settled')
625
+ return;
626
+ if (event['type'] !== 'assistant')
627
+ return;
628
+ const message = event['message'];
629
+ const blocks = Array.isArray(message?.content) ? message.content : [];
630
+ for (const block of blocks) {
631
+ if (!block || typeof block !== 'object')
632
+ continue;
633
+ const item = block;
634
+ const blockText = claudeBlockText(item);
635
+ if (blockText !== undefined) {
636
+ entry.hooks.onLog('stdout', blockText);
637
+ // claude stream-json 给的是整条 assistant 消息(不是 token 增量),
638
+ // 但相对「回合终态」它仍是半截 —— 刷新后照样该看得到
639
+ this.recordPartialText(entry.req.taskId, blockText);
640
+ }
641
+ if (!entry.hooks.onStep)
642
+ continue;
643
+ if (item['type'] === 'tool_use' && typeof item['name'] === 'string') {
644
+ entry.stepSeq += 1;
645
+ const ref = typeof item['id'] === 'string' ? item['id'] : undefined;
646
+ if (ref)
647
+ entry.stepRefs.set(ref, entry.stepSeq);
648
+ entry.hooks.onStep({
649
+ action: item['name'],
650
+ label: typeof item['input'] === 'object' ? JSON.stringify(item['input']).slice(0, 200) : undefined,
651
+ state: 'started',
652
+ ref,
653
+ seq: entry.stepSeq,
654
+ // 富 toolCall(4.8):与 headless 解析器同一映射(kind/locations;rawInput 不上行)
655
+ toolCall: claudeToolCallOf(item['name'], item['id'], item['input']),
656
+ });
657
+ }
658
+ if (item['type'] === 'tool_result' && typeof item['tool_use_id'] === 'string') {
659
+ const seq = entry.stepRefs.get(item['tool_use_id']);
660
+ if (seq !== undefined) {
661
+ entry.hooks.onStep({
662
+ action: 'tool_result',
663
+ state: 'finished',
664
+ ok: item['is_error'] !== true,
665
+ ref: item['tool_use_id'],
666
+ seq,
667
+ });
668
+ }
669
+ }
670
+ }
671
+ },
672
+ })
673
+ .then((result) => {
674
+ if (entry.state === 'settled')
675
+ return;
676
+ this.settle(entry, 'success', { exitCode: 0, result: result.text });
677
+ })
678
+ .catch((error) => {
679
+ if (entry.state === 'settled')
680
+ return;
681
+ if (entry.status === 'cancelled') {
682
+ this.settle(entry, 'cancelled', { error: '任务已取消', errorCode: 'cancelled' });
683
+ return;
684
+ }
685
+ if (entry.status === 'timeout') {
686
+ this.settle(entry, 'timeout', { error: '任务超时,Claude stream 已中断', errorCode: 'timeout' });
687
+ return;
688
+ }
689
+ this.settle(entry, 'failed', {
690
+ error: error.message,
691
+ errorCode: 'agent_error',
692
+ });
693
+ });
694
+ }
695
+ launchAppServer(entry) {
696
+ const controller = new AbortController();
697
+ entry.acpAbort = controller;
698
+ entry.acpPermissions = new Map();
699
+ entry.hooks.onStatus('running');
700
+ void runCodexPrompt({
701
+ // 同 launchClaudeStream:不让 adapter 用裸名 'codex' 依赖 PATH
702
+ command: entry.cmd,
703
+ cwd: entry.req.cwd,
704
+ prompt: entry.req.prompt ?? '',
705
+ nativeThreadId: entry.req.nativeSessionId,
706
+ timeoutMs: timeoutOf(entry.req),
707
+ signal: controller.signal,
708
+ onTurn: (turn) => {
709
+ entry.codexSteer = turn.steer;
710
+ },
711
+ onUpdate: (notification) => this.onCodexUpdate(entry, notification),
712
+ onApproval: (request) => {
713
+ // full 残余权限(同 ACP onPermission 的 fail closed):有 reject_once(decline)自动拒绝,
714
+ // 否则 cancelled + 取消回合(interaction_denied)—— 不转人工、不伪造选项。
715
+ if (entry.permissionMode === 'full') {
716
+ const outcome = fullResidualPermissionOutcome([
717
+ { optionId: 'accept', kind: 'allow_once' },
718
+ { optionId: 'acceptForSession', kind: 'allow_always' },
719
+ { optionId: 'decline', kind: 'reject_once' },
720
+ ]);
721
+ if ('optionId' in outcome)
722
+ return 'decline';
723
+ entry.status = 'cancelled';
724
+ entry.acpAbort?.abort();
725
+ this.settle(entry, 'cancelled', {
726
+ error: 'full 模式的残余权限请求已被拒绝,取消回合',
727
+ errorCode: 'interaction_denied',
728
+ });
729
+ return 'decline';
730
+ }
731
+ // 每任务一个 pending:已有未决请求时直接拒绝,不上行
732
+ if (entry.acpPermissions?.size)
733
+ return 'decline';
734
+ // 交互关闭(interactionEnabled=false → interactive=false)时必须直接拒绝,
735
+ // 否则 Promise 永远悬着,任务会一直等到总超时
736
+ if (!entry.req.interactive || !entry.hooks.onInteraction)
737
+ return 'decline';
738
+ const requestId = `ir_${randomUUID().replace(/-/g, '').slice(0, 20)}`;
739
+ const answer = new Promise((resolve) => {
740
+ entry.acpPermissions?.set(requestId, (value) => {
741
+ resolve(value?.optionId);
742
+ return request.delivery;
743
+ });
744
+ });
745
+ const options = [
746
+ { optionId: 'accept', kind: 'allow_once', name: '允许一次' },
747
+ { optionId: 'acceptForSession', kind: 'allow_always', name: '本会话允许' },
748
+ { optionId: 'decline', kind: 'reject_once', name: '拒绝' },
749
+ ];
750
+ entry.hooks.onInteraction({
751
+ requestId,
752
+ kind: 'permission',
753
+ payload: {
754
+ protocol: 'codex-app-server',
755
+ method: request.method,
756
+ toolCall: request.payload,
757
+ options,
758
+ },
229
759
  });
760
+ this.waitForInteraction(entry, requestId);
761
+ return answer;
762
+ },
763
+ })
764
+ .then((result) => {
765
+ if (entry.state === 'settled')
766
+ return;
767
+ entry.hooks.onSession?.(result.threadId);
768
+ if (entry.acpPermissions?.size) {
769
+ this.settle(entry, 'failed', {
770
+ error: 'Codex 回合结束时仍有未决交互',
771
+ errorCode: 'agent_protocol_error',
772
+ feedIncomplete: true,
773
+ });
774
+ return;
775
+ }
776
+ this.settle(entry, 'success', { exitCode: 0, result: result.text });
777
+ })
778
+ .catch((error) => {
779
+ if (entry.state === 'settled')
780
+ return;
781
+ if (entry.status === 'cancelled') {
782
+ this.settle(entry, 'cancelled', { error: '任务已取消', errorCode: 'cancelled' });
783
+ return;
784
+ }
785
+ if (entry.status === 'timeout') {
786
+ this.settle(entry, 'timeout', { error: '任务超时,Codex turn 已中断', errorCode: 'timeout' });
787
+ return;
230
788
  }
789
+ this.settle(entry, 'failed', {
790
+ error: error.message,
791
+ errorCode: 'agent_error',
792
+ });
231
793
  });
794
+ }
795
+ onCodexUpdate(entry, notification) {
796
+ // 终态后 app-server 通知仍可能到达(回合结束与通知流关闭不同步)——不再上行
797
+ if (entry.state === 'settled')
798
+ return;
799
+ const method = String(notification['method'] ?? '');
800
+ const params = (notification['params'] ?? {});
801
+ if (method === 'item/agentMessage/delta') {
802
+ const delta = codexDeltaText(notification);
803
+ if (delta !== undefined) {
804
+ entry.hooks.onLog('stdout', delta);
805
+ this.recordPartialText(entry.req.taskId, delta);
806
+ }
807
+ return;
808
+ }
809
+ if (method !== 'item/started' && method !== 'item/completed')
810
+ return;
811
+ if (!entry.hooks.onStep)
812
+ return;
813
+ const item = (params['item'] ?? {});
814
+ const ref = String(item['id'] ?? '');
815
+ const type = String(item['type'] ?? 'item');
816
+ const finished = method === 'item/completed';
817
+ if (finished && !ref)
818
+ return;
819
+ let seq = ref ? entry.stepRefs.get(ref) : undefined;
820
+ if (seq === undefined) {
821
+ entry.stepSeq += 1;
822
+ seq = entry.stepSeq;
823
+ if (ref)
824
+ entry.stepRefs.set(ref, seq);
825
+ }
826
+ entry.hooks.onStep({
827
+ action: type,
828
+ label: String(item['command'] ?? item['path'] ?? item['title'] ?? ''),
829
+ state: finished ? 'finished' : 'started',
830
+ ...(finished ? { ok: !item['error'] } : {}),
831
+ ref: ref || undefined,
832
+ seq,
833
+ });
834
+ }
835
+ launchAcp(entry) {
836
+ const controller = new AbortController();
837
+ entry.acpAbort = controller;
838
+ entry.acpPermissions = new Map();
232
839
  entry.hooks.onStatus('running');
840
+ void runAcpPrompt({
841
+ cwd: entry.req.cwd,
842
+ prompt: entry.req.prompt ?? '',
843
+ spec: entry.req.acpSpec,
844
+ timeoutMs: timeoutOf(entry.req),
845
+ nativeSessionId: entry.req.nativeSessionId,
846
+ replayPrompt: entry.req.replayPrompt,
847
+ signal: controller.signal,
848
+ onUpdate: (update) => this.onAcpUpdate(entry, update),
849
+ onPermission: (request) => {
850
+ // 持久授权(1.0):只问一次账本,命中就不再打扰平台(这个问题人工已经回答过)。
851
+ // 三个前提缺一不可 —— default 模式、请求真实提供 persistent 选项、指纹匹配;
852
+ // 判定在 permission-ledger.canAutoApprove(),这里只负责「问」和「用」。
853
+ const approved = entry.permissionMode === 'default' && entry.hooks.onApprovalLookup
854
+ ? entry.hooks.onApprovalLookup({
855
+ agentType: entry.req.agentType,
856
+ cwd: entry.req.cwd,
857
+ permissionMode: entry.permissionMode,
858
+ toolCall: request.toolCall,
859
+ options: request.options,
860
+ })
861
+ : undefined;
862
+ if (approved) {
863
+ entry.hooks.onLog('stdout', `[ledger] 命中持久授权 ${approved.approvalId},已自动允许\n`);
864
+ return approved.optionId;
865
+ }
866
+ // full 残余权限(spec「权限与问题的组合语义」):fail closed,不转交人工。
867
+ // 只有 options 真实提供 reject_once 才按原 optionId 自动拒绝(回合继续);
868
+ // 否则以 cancelled outcome 回复、取消回合并以 interaction_denied 结束 —— 不伪造选项。
869
+ if (entry.permissionMode === 'full') {
870
+ const outcome = fullResidualPermissionOutcome(Array.isArray(request.options)
871
+ ? request.options
872
+ : undefined);
873
+ if ('optionId' in outcome)
874
+ return outcome.optionId;
875
+ entry.status = 'cancelled';
876
+ entry.acpAbort?.abort();
877
+ this.settle(entry, 'cancelled', {
878
+ error: 'full 模式的残余权限请求已被拒绝(无 reject_once 可选),取消回合',
879
+ errorCode: 'interaction_denied',
880
+ });
881
+ return undefined;
882
+ }
883
+ // 每任务最多一个 pending(design §7.1):已有未决请求时新请求直接以 cancel outcome 完成,
884
+ // 不再上行 —— 平台永远只会看到一个待答问题。
885
+ if (entry.acpPermissions?.size)
886
+ return undefined;
887
+ if (!entry.req.interactive || !entry.hooks.onInteraction)
888
+ return undefined;
889
+ const requestId = `ir_${randomUUID().replace(/-/g, '').slice(0, 20)}`;
890
+ const answer = new Promise((resolve) => {
891
+ entry.acpPermissions?.set(requestId, (value) => {
892
+ resolve(value?.optionId);
893
+ return request.delivery;
894
+ });
895
+ });
896
+ entry.hooks.onInteraction({
897
+ requestId,
898
+ kind: 'permission',
899
+ payload: { toolCall: request.toolCall, options: request.options },
900
+ });
901
+ this.waitForInteraction(entry, requestId);
902
+ return answer;
903
+ },
904
+ onForm: (request) => {
905
+ // 每任务一个 pending:已有未决请求时 Form 直接 cancel,不上行
906
+ if (entry.acpPermissions?.size)
907
+ return { action: 'cancel' };
908
+ if (!entry.req.interactive || !entry.hooks.onInteraction)
909
+ return { action: 'cancel' };
910
+ const answer = new Promise((resolve) => {
911
+ entry.acpPermissions?.set(request.requestId, (value) => {
912
+ if (value?.action === 'accept') {
913
+ resolve({ action: 'accept', content: value.content ?? {} });
914
+ }
915
+ else {
916
+ resolve({ action: value?.action === 'decline' ? 'decline' : 'cancel' });
917
+ }
918
+ return request.delivery;
919
+ });
920
+ });
921
+ entry.hooks.onInteraction({
922
+ requestId: request.requestId,
923
+ kind: 'form',
924
+ payload: { message: request.message, requestedSchema: request.requestedSchema },
925
+ ...(request.expiresAt ? { expiresAt: request.expiresAt } : {}),
926
+ });
927
+ this.waitForInteraction(entry, request.requestId);
928
+ return answer;
929
+ },
930
+ })
931
+ .then((result) => {
932
+ if (entry.state === 'settled')
933
+ return;
934
+ entry.hooks.onSession?.(result.sessionId);
935
+ // 收到 result ≠ 成功:必须按 stopReason 结算,否则 max_tokens / refusal 会被当成正常完成
936
+ const stop = knownStopReason(result.stopReason);
937
+ if (entry.acpPermissions?.size) {
938
+ this.settle(entry, 'failed', {
939
+ error: 'ACP 回合结束时仍有未决交互',
940
+ errorCode: 'agent_protocol_error',
941
+ feedIncomplete: true,
942
+ });
943
+ return;
944
+ }
945
+ if (result.stopReason === 'end_turn' || result.stopReason === undefined) {
946
+ this.settle(entry, 'success', {
947
+ exitCode: 0,
948
+ result: result.text,
949
+ ...(stop ? { stopReason: stop } : {}),
950
+ });
951
+ return;
952
+ }
953
+ if (result.stopReason === 'cancelled') {
954
+ this.settle(entry, 'cancelled', {
955
+ error: 'ACP 回合已取消',
956
+ errorCode: 'cancelled',
957
+ stopReason: 'cancelled',
958
+ });
959
+ return;
960
+ }
961
+ this.settle(entry, 'failed', {
962
+ error: `ACP 回合未正常结束(stopReason=${result.stopReason})`,
963
+ errorCode: 'agent_error',
964
+ // 回合没有 end_turn,canonical feed 必然不完整 —— 如实标注,别让 UI 当完整历史
965
+ feedIncomplete: true,
966
+ ...(stop ? { stopReason: stop } : {}),
967
+ ...(result.text.trim() ? { result: result.text } : {}),
968
+ });
969
+ })
970
+ .catch((error) => {
971
+ if (entry.state === 'settled')
972
+ return;
973
+ if (entry.status === 'cancelled') {
974
+ this.settle(entry, 'cancelled', { error: '任务已取消', errorCode: 'cancelled' });
975
+ return;
976
+ }
977
+ if (entry.status === 'timeout') {
978
+ this.settle(entry, 'timeout', { error: '任务超时,ACP 会话已终止', errorCode: 'timeout' });
979
+ return;
980
+ }
981
+ const auth = error instanceof AcpAuthRequiredError;
982
+ this.settle(entry, 'failed', {
983
+ error: error.message,
984
+ errorCode: auth ? 'tool_no_credentials' : 'agent_error',
985
+ });
986
+ });
987
+ }
988
+ onAcpUpdate(entry, update) {
989
+ // 终态后 agent 的 session/update 仍可能在途(取消/超时先结算,子进程清理是异步的)——不再上行
990
+ if (entry.state === 'settled')
991
+ return;
992
+ const kind = String(update['sessionUpdate'] ?? '');
993
+ if (kind === 'agent_message_chunk') {
994
+ const text = acpChunkText(update);
995
+ if (text !== undefined) {
996
+ entry.hooks.onLog('stdout', text);
997
+ // 真正的流式增量(ACP):同时喂给半截消息累积器,刷新后才能看到这半段
998
+ this.recordPartialText(entry.req.taskId, text);
999
+ }
1000
+ return;
1001
+ }
1002
+ if (kind === 'plan' && entry.hooks.onPlan && Array.isArray(update['entries'])) {
1003
+ const items = [];
1004
+ for (const raw of update['entries']) {
1005
+ const text = String(raw['content'] ?? raw['text'] ?? '');
1006
+ if (!text)
1007
+ continue;
1008
+ const state = String(raw['status'] ?? 'pending');
1009
+ items.push({
1010
+ text,
1011
+ state: state === 'completed' ? 'completed' : state === 'in_progress' ? 'in_progress' : 'pending',
1012
+ });
1013
+ }
1014
+ entry.hooks.onPlan(items);
1015
+ return;
1016
+ }
1017
+ if ((kind === 'tool_call' || kind === 'tool_call_update') && entry.hooks.onStep) {
1018
+ const ref = String(update['toolCallId'] ?? '');
1019
+ const status = String(update['status'] ?? 'pending');
1020
+ const finished = status === 'completed' || status === 'failed';
1021
+ const paired = ref ? entry.stepRefs.get(ref) : undefined;
1022
+ if (!finished && paired !== undefined)
1023
+ return;
1024
+ let seq = paired;
1025
+ if (seq === undefined) {
1026
+ entry.stepSeq += 1;
1027
+ seq = entry.stepSeq;
1028
+ if (ref)
1029
+ entry.stepRefs.set(ref, seq);
1030
+ }
1031
+ entry.hooks.onStep({
1032
+ action: String(update['kind'] ?? update['title'] ?? 'tool'),
1033
+ label: String(update['title'] ?? ''),
1034
+ state: finished ? 'finished' : 'started',
1035
+ ...(finished ? { ok: status === 'completed' } : {}),
1036
+ ref: ref || undefined,
1037
+ seq,
1038
+ // 富 toolCall(4.8):ACP 原生 kind/title/locations/content 直传;
1039
+ // rawInput/rawOutput 不上行(ACP 字段本就未透传)。
1040
+ toolCall: {
1041
+ ...(ref ? { toolCallId: ref } : {}),
1042
+ name: String(update['kind'] ?? update['title'] ?? 'tool'),
1043
+ ...(acpToolKind(update['kind']) ? { kind: acpToolKind(update['kind']) } : {}),
1044
+ ...(typeof update['title'] === 'string' && update['title'] ? { title: update['title'] } : {}),
1045
+ status,
1046
+ ...acpToolLocations(update['locations']),
1047
+ ...acpToolContent(update['content']),
1048
+ },
1049
+ });
1050
+ }
233
1051
  }
234
1052
  terminate(entry) {
235
- if (!entry.child)
1053
+ if (!entry.child) {
1054
+ if (entry.acpAbort) {
1055
+ entry.acpAbort.abort();
1056
+ const status = entry.status === 'timeout' ? 'timeout' : 'cancelled';
1057
+ this.settle(entry, status, {
1058
+ error: status === 'timeout' ? '任务超时,ACP 会话已终止' : '任务已取消',
1059
+ errorCode: status,
1060
+ });
1061
+ }
236
1062
  return;
237
- entry.child.kill('SIGTERM');
238
- entry.killTimer = setTimeout(() => entry.child?.kill('SIGKILL'), KILL_GRACE_MS);
1063
+ }
1064
+ if (isWinShim(entry.cmd)) {
1065
+ killCliProcess(entry.child, entry.cmd);
1066
+ }
1067
+ else {
1068
+ entry.child.kill('SIGTERM');
1069
+ }
1070
+ entry.killTimer = setTimeout(() => {
1071
+ if (!entry.child)
1072
+ return;
1073
+ if (isWinShim(entry.cmd))
1074
+ killCliProcess(entry.child, entry.cmd);
1075
+ else
1076
+ entry.child.kill('SIGKILL');
1077
+ }, KILL_GRACE_MS);
239
1078
  }
240
1079
  /** 唯一终态收口:只 settle 一次、只释放一次名额 */
241
1080
  settle(entry, status, info = {}) {
@@ -245,7 +1084,17 @@ export class TaskSupervisor {
245
1084
  clearTimeout(entry.timer);
246
1085
  if (entry.killTimer)
247
1086
  clearTimeout(entry.killTimer);
248
- if (entry.state === 'running') {
1087
+ // 终态之后半截文本就该消失:平台该读事件里的 complete,而不是 pm_ 桶里那半段
1088
+ this.partials.clear(entry.req.taskId);
1089
+ // 权限模式回显:终态必须带(平台据此区分「按 full 跑的」与「按 default 跑的」)
1090
+ if (info.permissionMode === undefined)
1091
+ info = { ...info, permissionMode: entry.permissionMode };
1092
+ // 最终回答:步骤解析器从事件流提取(C 批次;面板结果视图与平台同享),上限 16KB
1093
+ const resultText = entry.stepParser?.finalText?.();
1094
+ if (resultText && info.result === undefined) {
1095
+ info = { ...info, result: resultText.length > 16_384 ? `${resultText.slice(0, 16_384)}…` : resultText };
1096
+ }
1097
+ if (entry.state === 'running' || entry.state === 'waiting') {
249
1098
  this.running = Math.max(0, this.running - 1);
250
1099
  }
251
1100
  else {
@@ -255,13 +1104,79 @@ export class TaskSupervisor {
255
1104
  }
256
1105
  entry.state = 'settled';
257
1106
  entry.status = status;
258
- entry.hooks.onStatus(status, withDiff(entry.req, info));
1107
+ for (const requestId of entry.acpPermissions?.keys() ?? []) {
1108
+ this.interactions.cancelRequest(entry.req.interactionSessionId ?? entry.req.taskId, entry.req.interactionTenantId ?? 'default', requestId);
1109
+ }
1110
+ for (const resolve of entry.acpPermissions?.values() ?? [])
1111
+ resolve(undefined);
1112
+ entry.acpPermissions?.clear();
1113
+ // 终态快照存 entry:本条调用链内的重放直接用,不重跑 git diff
1114
+ entry.finishInfo = withDiff(entry.req, info);
1115
+ entry.hooks.onStatus(status, entry.finishInfo);
1116
+ // 落库回调(生产 = SQLite 同步写)返回后,内存条目即可回收:
1117
+ // 同 ID 重发的终态回放由调度入口的 SQLite 前置检查负责,这里不再持有终态历史。
1118
+ this.byId.delete(entry.req.taskId);
259
1119
  entry.resolve(status);
260
1120
  this.pump();
1121
+ this.notifyCapacity();
261
1122
  }
262
1123
  }
263
1124
  /** 进程内的默认调度域(`runner.ts` 的 `startTask` 走它,保持 v1 调用方零改动) */
264
1125
  export const defaultSupervisor = new TaskSupervisor();
1126
+ const ACP_TOOL_KINDS = new Set([
1127
+ 'read',
1128
+ 'edit',
1129
+ 'delete',
1130
+ 'move',
1131
+ 'search',
1132
+ 'execute',
1133
+ 'think',
1134
+ 'fetch',
1135
+ 'switch_mode',
1136
+ 'other',
1137
+ ]);
1138
+ function acpToolKind(raw) {
1139
+ const kind = String(raw ?? '');
1140
+ return ACP_TOOL_KINDS.has(kind) ? kind : undefined;
1141
+ }
1142
+ function acpToolLocations(raw) {
1143
+ if (!Array.isArray(raw))
1144
+ return {};
1145
+ const locations = [];
1146
+ for (const item of raw.slice(0, 8)) {
1147
+ if (!item || typeof item !== 'object')
1148
+ continue;
1149
+ const o = item;
1150
+ const path = typeof o['path'] === 'string' ? o['path'] : undefined;
1151
+ const line = typeof o['line'] === 'number' ? o['line'] : undefined;
1152
+ if (path === undefined && line === undefined)
1153
+ continue;
1154
+ locations.push({ ...(path !== undefined ? { path } : {}), ...(line !== undefined ? { line } : {}) });
1155
+ }
1156
+ return locations.length > 0 ? { locations } : {};
1157
+ }
1158
+ /** ACP tool_call 的 content 块:只收 text/diff/terminal 三类,单块 16KB 截断、最多 8 块 */
1159
+ function acpToolContent(raw) {
1160
+ if (!Array.isArray(raw))
1161
+ return {};
1162
+ const blocks = [];
1163
+ for (const item of raw.slice(0, 8)) {
1164
+ if (!item || typeof item !== 'object')
1165
+ continue;
1166
+ const o = item;
1167
+ const kind = String(o['kind'] ?? '');
1168
+ if (kind !== 'text' && kind !== 'diff' && kind !== 'terminal')
1169
+ continue;
1170
+ const text = typeof o['text'] === 'string' ? o['text'] : '';
1171
+ if (!text)
1172
+ continue;
1173
+ blocks.push({
1174
+ kind,
1175
+ text: text.length > 16_384 ? `${text.slice(0, 16_383)}…` : text,
1176
+ });
1177
+ }
1178
+ return blocks.length > 0 ? { content: blocks } : {};
1179
+ }
265
1180
  /** 给 CLI 展示用的摘要(不含任何路径/密钥细节) */
266
1181
  export function describeTask(req) {
267
1182
  return `${req.agentType} @ ${realpathOr(req.cwd)}`;
@@ -274,4 +1189,14 @@ function realpathOr(p) {
274
1189
  return p;
275
1190
  }
276
1191
  }
1192
+ /**
1193
+ * 把上游的 stopReason 收敛到受控枚举:只认这五个值,其他(含 `unknown`)一律当未知,
1194
+ * 于是不会被写进 wire 的受限字段 —— 未知原因只体现为 failed + agent_error。
1195
+ */
1196
+ const STOP_REASONS = ['end_turn', 'max_tokens', 'max_turn_requests', 'refusal', 'cancelled'];
1197
+ export function knownStopReason(raw) {
1198
+ return typeof raw === 'string' && STOP_REASONS.includes(raw)
1199
+ ? raw
1200
+ : undefined;
1201
+ }
277
1202
  export { BridgeError };