toc-ocra 0.3.1 → 0.3.2

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 (71) hide show
  1. package/README.md +6 -0
  2. package/dist/cli/cli.mjs +3267 -1621
  3. package/dist/service/agent.mjs +3190 -1544
  4. package/dist/src/acp/agent-process.d.ts +34 -0
  5. package/dist/src/acp/agent-process.js +90 -0
  6. package/dist/src/acp/agent-process.js.map +1 -0
  7. package/dist/src/acp/chat-agents.d.ts +53 -0
  8. package/dist/src/acp/chat-agents.js +120 -0
  9. package/dist/src/acp/chat-agents.js.map +1 -0
  10. package/dist/src/acp/chat-forwarder.d.ts +30 -0
  11. package/dist/src/acp/chat-forwarder.js +101 -0
  12. package/dist/src/acp/chat-forwarder.js.map +1 -0
  13. package/dist/src/acp/chat-host.d.ts +28 -0
  14. package/dist/src/acp/chat-host.js +102 -0
  15. package/dist/src/acp/chat-host.js.map +1 -0
  16. package/dist/src/acp/chat-session.d.ts +112 -0
  17. package/dist/src/acp/chat-session.js +465 -0
  18. package/dist/src/acp/chat-session.js.map +1 -0
  19. package/dist/src/acp/connection.d.ts +77 -0
  20. package/dist/src/acp/connection.js +204 -0
  21. package/dist/src/acp/connection.js.map +1 -0
  22. package/dist/src/acp/rpc.d.ts +40 -0
  23. package/dist/src/acp/rpc.js +137 -0
  24. package/dist/src/acp/rpc.js.map +1 -0
  25. package/dist/src/acp/transcript.d.ts +39 -0
  26. package/dist/src/acp/transcript.js +273 -0
  27. package/dist/src/acp/transcript.js.map +1 -0
  28. package/dist/src/acp/vendor.d.ts +21 -0
  29. package/dist/src/acp/vendor.js +137 -0
  30. package/dist/src/acp/vendor.js.map +1 -0
  31. package/dist/src/providers/acp/acp-agents.d.ts +9 -0
  32. package/dist/src/providers/acp/acp-agents.js +8 -8
  33. package/dist/src/providers/acp/acp-agents.js.map +1 -1
  34. package/dist/src/providers/acp/acp-driver.d.ts +1 -1
  35. package/dist/src/providers/acp/acp-driver.js +9 -3
  36. package/dist/src/providers/acp/acp-driver.js.map +1 -1
  37. package/dist/src/providers/chat/codex-app-server.js +5 -3
  38. package/dist/src/providers/chat/codex-app-server.js.map +1 -1
  39. package/dist/src/providers/chat/codex-goal.js +5 -6
  40. package/dist/src/providers/chat/codex-goal.js.map +1 -1
  41. package/dist/src/providers/cli/claude.js +19 -5
  42. package/dist/src/providers/cli/claude.js.map +1 -1
  43. package/dist/src/providers/cli/codex.d.ts +12 -1
  44. package/dist/src/providers/cli/codex.js +33 -2
  45. package/dist/src/providers/cli/codex.js.map +1 -1
  46. package/dist/src/providers/cli/kiro.js +3 -2
  47. package/dist/src/providers/cli/kiro.js.map +1 -1
  48. package/dist/src/providers/provider.d.ts +29 -0
  49. package/dist/src/providers/provider.js +19 -0
  50. package/dist/src/providers/provider.js.map +1 -1
  51. package/dist/src/providers/registry.d.ts +6 -1
  52. package/dist/src/providers/registry.js +24 -8
  53. package/dist/src/providers/registry.js.map +1 -1
  54. package/dist/src/runs/run-supervisor.d.ts +41 -0
  55. package/dist/src/runs/run-supervisor.js +229 -40
  56. package/dist/src/runs/run-supervisor.js.map +1 -1
  57. package/dist/src/runtime/agent-runtime.js +17 -2
  58. package/dist/src/runtime/agent-runtime.js.map +1 -1
  59. package/dist/src/session/terminal-line-sanitizer.d.ts +5 -0
  60. package/dist/src/session/terminal-line-sanitizer.js +18 -0
  61. package/dist/src/session/terminal-line-sanitizer.js.map +1 -1
  62. package/dist/src/types/protocol.d.ts +9 -0
  63. package/dist/src/types/protocol.js +16 -0
  64. package/dist/src/types/protocol.js.map +1 -1
  65. package/package.json +4 -2
  66. package/vendor/acp/claude/LICENSE +191 -0
  67. package/vendor/acp/claude/index.mjs +167 -0
  68. package/vendor/acp/claude/runtime.json +7 -0
  69. package/vendor/acp/codex/LICENSE +190 -0
  70. package/vendor/acp/codex/index.mjs +158 -0
  71. package/vendor/acp/codex/runtime.json +3 -0
@@ -2,11 +2,11 @@ import { spawn } from 'node:child_process';
2
2
  import { mkdir, realpath, stat, writeFile } from 'node:fs/promises';
3
3
  import { basename, isAbsolute, join, relative, resolve } from 'node:path';
4
4
  import { createInterface } from 'node:readline';
5
- import { fitsCommandLine, pickCreatedSession } from '../providers/provider.js';
5
+ import { accessLevel, fitsCommandLine, isAgentAccess, pickCreatedSession } from '../providers/provider.js';
6
6
  import { resolveChatProvider } from '../providers/chat/index.js';
7
7
  import { classifyCliOutput, classifySpawnError, cliFailure } from '../providers/cli-failure.js';
8
8
  import { resolveRunnableCli } from '../providers/registry.js';
9
- import { sanitizeChatText, sanitizeTerminalLine } from '../session/terminal-line-sanitizer.js';
9
+ import { sanitizeChatEvent, sanitizeChatText, sanitizeTerminalLine } from '../session/terminal-line-sanitizer.js';
10
10
  import { TerminalTailBuffer } from '../session/terminal-tail-buffer.js';
11
11
  import { codexGoalProvider } from '../providers/chat/codex-goal.js';
12
12
  import { forkCodexThread } from '../providers/cli/codex-fork.js';
@@ -14,6 +14,10 @@ import { RunRecorder } from './run-recorder.js';
14
14
  import { currentPlatform } from '../platform/index.js';
15
15
  import { killProcessTree } from './process-tree.js';
16
16
  import { prepareTaskAttachments } from './task-attachments.js';
17
+ import { acpChatSpec } from '../acp/chat-agents.js';
18
+ import { ChatEventForwarder } from '../acp/chat-forwarder.js';
19
+ import { AcpChatHost } from '../acp/chat-host.js';
20
+ import { AcpRuntimeUnavailable, agentPackageVersion } from '../acp/vendor.js';
17
21
  /**
18
22
  * Supervises headless CLI turns. One process per turn:
19
23
  *
@@ -57,6 +61,53 @@ export const STALL_CATEGORY_LABELS = {
57
61
  file: '编辑文件',
58
62
  other: '等待 CLI 输出'
59
63
  };
64
+ /** Put before the prompt on CLIs without a plan mode of their own (the turn also runs read-only). */
65
+ export const PLAN_MODE_PREFIX = '【计划模式】这一轮只做分析和计划:阅读需要的文件,给出具体方案和步骤,不要修改任何文件,也不要执行会改动环境的命令。';
66
+ const ACCESS_LABELS = { 'read-only': '只读', acceptEdits: '自动编辑', bypassPermissions: '完全访问' };
67
+ /**
68
+ * The session's permission level, plan and fast mode for this CLI. The
69
+ * owner's restricted cap always wins; a level or plan mode the CLI cannot
70
+ * enforce refuses the turn rather than running with more access than chosen.
71
+ */
72
+ export function resolveTurnSettings(payload, cli) {
73
+ const full = payload.cli_policy?.mode === 'full';
74
+ const support = cli.runSettings;
75
+ const notes = [];
76
+ let access;
77
+ const requested = payload.permission_mode?.trim() ?? '';
78
+ if (requested) {
79
+ if (!isAgentAccess(requested))
80
+ return { failure: { kind: 'hostFault', message: `不支持的权限级别:${requested},请升级设备代理` } };
81
+ if (!full) {
82
+ if (requested !== 'read-only')
83
+ notes.push(`这台电脑的所有者只允许只读,本轮按只读运行(会话选择:${ACCESS_LABELS[requested]})`);
84
+ }
85
+ else if (requested !== 'bypassPermissions') {
86
+ if (!support?.permissionModes.includes(requested)) {
87
+ return { failure: { kind: 'permissionUnsupported', message: `${cli.label} 不支持「${ACCESS_LABELS[requested]}」权限,请改为完全访问或换用其他 CLI` } };
88
+ }
89
+ access = requested;
90
+ }
91
+ }
92
+ const plan = payload.plan_mode === true;
93
+ if (plan && !support?.plan)
94
+ return { failure: { kind: 'permissionUnsupported', message: `${cli.label} 不支持计划模式,请关闭计划后再发送` } };
95
+ const planPrompt = plan && support?.plan === 'prompt';
96
+ if (planPrompt && full)
97
+ access = 'read-only';
98
+ const fast = payload.fast_mode === true && support?.fast === true;
99
+ if (payload.fast_mode === true && !fast)
100
+ notes.push(`${cli.label} 不支持快速模式,本轮按普通速度运行`);
101
+ return { ...(access ? { access } : {}), plan: plan && support?.plan === 'native', planPrompt, fast, notes };
102
+ }
103
+ /** `本轮设置:计划模式 · 只读 · 快速模式`, when the session chose any of them. */
104
+ export function turnSettingsLabel(turn, payload) {
105
+ if (!payload.permission_mode && !payload.plan_mode && !payload.fast_mode)
106
+ return '';
107
+ const level = payload.cli_policy?.mode === 'full' ? ACCESS_LABELS[turn.access ?? 'bypassPermissions'] : '只读';
108
+ const parts = [...(turn.plan || turn.planPrompt ? ['计划模式'] : []), level, ...(turn.fast ? ['快速模式'] : [])];
109
+ return `本轮设置:${parts.join(' · ')}`;
110
+ }
60
111
  function formatDuration(seconds) {
61
112
  if (seconds % 60 === 0)
62
113
  return `${seconds / 60} 分钟`;
@@ -70,23 +121,32 @@ export class RunSupervisor {
70
121
  reporter;
71
122
  orphans;
72
123
  active = new Map();
124
+ acpRuns = new Map();
73
125
  recent = new Map();
74
126
  /** Run ids whose finish report has not been acknowledged yet. */
75
127
  unreported = new Set();
76
128
  chatRunIds = new Set();
77
129
  preparing = new Map();
130
+ acpChats;
78
131
  constructor(config, logger, reporter, orphans) {
79
132
  this.config = config;
80
133
  this.logger = logger;
81
134
  this.reporter = reporter;
82
135
  this.orphans = orphans;
136
+ this.acpChats = new AcpChatHost({ logger, dataDir: config.dataDir, clientVersion: agentPackageVersion(), ...(orphans ? { orphans } : {}) });
83
137
  }
84
138
  get activeCount() {
85
- return this.active.size + this.preparing.size;
139
+ return this.active.size + this.acpRuns.size + this.preparing.size;
86
140
  }
87
141
  /** Runs to list in the heartbeat: still running, or finished but not yet reported. */
88
142
  activeRunIds() {
89
- return [...new Set([...this.active.keys(), ...this.preparing.keys(), ...this.unreported])];
143
+ return [...new Set([...this.active.keys(), ...this.acpRuns.keys(), ...this.preparing.keys(), ...this.unreported])];
144
+ }
145
+ /** Whether another turn of this session is running or preparing. */
146
+ sessionBusy(sessionKey, runId) {
147
+ return [...this.active.values()].some((run) => run.sessionKey === sessionKey)
148
+ || [...this.acpRuns.values()].some((run) => run.sessionKey === sessionKey)
149
+ || [...this.preparing].some(([id, run]) => id !== runId && run.sessionKey === sessionKey);
90
150
  }
91
151
  activeChatRunIds() {
92
152
  return this.activeRunIds().filter(id => this.chatRunIds.has(id));
@@ -99,7 +159,7 @@ export class RunSupervisor {
99
159
  this.chatRunIds.delete(runId);
100
160
  }
101
161
  recentRuns() {
102
- const running = [...this.active.values()].map((run) => ({ runId: run.runId, sessionKey: run.sessionKey, status: 'running', at: run.startedAt }));
162
+ const running = [...this.active.values(), ...this.acpRuns.values()].map((run) => ({ runId: run.runId, sessionKey: run.sessionKey, status: 'running', at: run.startedAt }));
103
163
  const done = [...this.recent.values()].map((run) => ({ runId: run.runId, sessionKey: run.sessionKey, status: run.status, at: run.finishedAt }));
104
164
  return [...running, ...done].sort((a, b) => b.at - a.at).slice(0, 30);
105
165
  }
@@ -115,7 +175,7 @@ export class RunSupervisor {
115
175
  */
116
176
  overConcurrencyCap() {
117
177
  const cap = this.config.maxConcurrentRuns;
118
- return cap > 0 && this.active.size + this.preparing.size > cap;
178
+ return cap > 0 && this.active.size + this.acpRuns.size + this.preparing.size > cap;
119
179
  }
120
180
  async start(payload) {
121
181
  if (this.preparing.has(payload.run_id))
@@ -130,7 +190,7 @@ export class RunSupervisor {
130
190
  }
131
191
  }
132
192
  async startPrepared(payload, signal) {
133
- if (this.active.has(payload.run_id) || this.recent.has(payload.run_id)) {
193
+ if (this.active.has(payload.run_id) || this.acpRuns.has(payload.run_id) || this.recent.has(payload.run_id)) {
134
194
  this.logger.info('run-duplicate-ignored', { runId: payload.run_id });
135
195
  return;
136
196
  }
@@ -143,7 +203,7 @@ export class RunSupervisor {
143
203
  this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'failed', chat: !!payload.chat_session_id });
144
204
  await this.report(payload.run_id, { status: 'failed', error: failure.message, failure_kind: failure.kind, duration_ms: 0 });
145
205
  };
146
- if ([...this.active.values()].some((run) => run.sessionKey === sessionKey) || [...this.preparing].some(([id, run]) => id !== payload.run_id && run.sessionKey === sessionKey)) {
206
+ if (this.sessionBusy(sessionKey, payload.run_id)) {
147
207
  return refuse('本机该会话已有任务在运行');
148
208
  }
149
209
  if (this.overConcurrencyCap()) {
@@ -158,6 +218,10 @@ export class RunSupervisor {
158
218
  if ('failure' in runnable)
159
219
  return refuse(runnable.failure);
160
220
  const cli = runnable.entry;
221
+ const turn = resolveTurnSettings(payload, cli);
222
+ if ('failure' in turn)
223
+ return refuse(turn.failure);
224
+ const runSettings = { ...(turn.access ? { access: turn.access } : {}), ...(turn.plan ? { plan: true } : {}), ...(turn.fast ? { fast: true } : {}) };
161
225
  let provider = cli.headless;
162
226
  let workdir;
163
227
  try {
@@ -183,15 +247,26 @@ export class RunSupervisor {
183
247
  }
184
248
  return refuse(`附件下载失败:${errorMessage(error)}`);
185
249
  }
250
+ // Plan mode on CLIs without one: read-only (above) plus this instruction.
251
+ const prompt = turn.planPrompt ? `${PLAN_MODE_PREFIX}\n\n${payload.prompt}` : payload.prompt;
186
252
  const request = {
187
253
  permissionMode,
188
- prompt: payload.prompt,
254
+ ...runSettings,
255
+ prompt,
189
256
  sessionId: payload.session_id,
190
257
  model: payload.model,
191
258
  reasoningEffort: payload.reasoning_effort,
192
259
  workdir
193
260
  };
194
261
  if (payload.chat_session_id) {
262
+ // Live chat runs on the session's long-lived ACP agent when the CLI has one.
263
+ const acpSpec = acpChatSpec(cli.id);
264
+ if (acpSpec) {
265
+ const outcome = await this.startAcpChat(payload, { spec: acpSpec, cli, sessionKey, workdir, prompt, turn, permissionMode, signal, refuse });
266
+ if (outcome === 'handled')
267
+ return;
268
+ payload = { ...payload, notice: payload.notice ? `${payload.notice};${outcome.fallback}` : outcome.fallback };
269
+ }
195
270
  try {
196
271
  if (!this.reporter.chatEvents)
197
272
  throw new Error('实时聊天转发未配置');
@@ -256,10 +331,10 @@ export class RunSupervisor {
256
331
  if (payload.goal && !payload.chat_session_id) {
257
332
  if (provider.id !== 'codex')
258
333
  return refuse('目标模式只支持 Codex');
259
- provider = codexGoalProvider({ permissionMode, prompt: payload.prompt, sessionId, model: payload.model, reasoningEffort: payload.reasoning_effort, workdir }, { objective: payload.goal.objective, ...(payload.goal.token_budget ? { tokenBudget: payload.goal.token_budget } : {}) });
334
+ provider = codexGoalProvider({ permissionMode, ...runSettings, prompt, sessionId, model: payload.model, reasoningEffort: payload.reasoning_effort, workdir }, { objective: payload.goal.objective, ...(payload.goal.token_budget ? { tokenBudget: payload.goal.token_budget } : {}) });
260
335
  }
261
336
  // Preparing a directory or attachment may yield while another command starts.
262
- if ([...this.active.values()].some(run => run.sessionKey === sessionKey))
337
+ if ([...this.active.values(), ...this.acpRuns.values()].some(run => run.sessionKey === sessionKey))
263
338
  return refuse('本机该会话已有任务在运行');
264
339
  if (this.overConcurrencyCap())
265
340
  return refuse(`本机同时运行的任务已达上限(${this.config.maxConcurrentRuns})`);
@@ -268,7 +343,8 @@ export class RunSupervisor {
268
343
  provider = provider.forTurn();
269
344
  const launch = provider.buildLaunch({
270
345
  permissionMode,
271
- prompt: payload.prompt,
346
+ ...runSettings,
347
+ prompt,
272
348
  sessionId,
273
349
  model: payload.model,
274
350
  reasoningEffort: payload.reasoning_effort,
@@ -302,7 +378,7 @@ export class RunSupervisor {
302
378
  parse: provider.createLineParser?.() ?? ((line) => provider.parseLine(line)),
303
379
  ...(sessionsBefore ? { sessionsBefore } : {}),
304
380
  ...(sessionId && !payload.chat_session_id ? { resumeRetry: payload } : {}),
305
- prompt: payload.prompt,
381
+ prompt,
306
382
  child,
307
383
  pid: child.pid ?? 0,
308
384
  startedAt: Date.now(),
@@ -334,7 +410,7 @@ export class RunSupervisor {
334
410
  }
335
411
  const recorder = RunRecorder.fromEnvironment(run.runId, {
336
412
  agent: provider.id, args: launch.args,
337
- request: { session_id: sessionId, model: payload.model, reasoning_effort: payload.reasoning_effort, permission: permissionMode, prompt: payload.prompt }
413
+ request: { session_id: sessionId, model: payload.model, reasoning_effort: payload.reasoning_effort, permission: permissionMode, ...runSettings, prompt }
338
414
  });
339
415
  if (recorder)
340
416
  run.recorder = recorder;
@@ -347,7 +423,12 @@ export class RunSupervisor {
347
423
  run.tail.append(`● ${sanitizeTerminalLine(payload.notice)}\n`);
348
424
  if (sessionNote)
349
425
  run.tail.append(sessionNote);
426
+ for (const note of turn.notes)
427
+ run.tail.append(`● ${note}\n`);
350
428
  run.tail.append(`● ${provider.id} 启动于 ${workdir}${sessionId ? `(继续会话 ${sessionId})` : ''}\n`);
429
+ const settingsRow = turnSettingsLabel(turn, payload);
430
+ if (settingsRow)
431
+ run.tail.append(`● ${settingsRow}\n`);
351
432
  this.logger.info('run-started', { runId: run.runId, agentType: provider.id, pid: run.pid, resume: Boolean(sessionId) });
352
433
  let spawnError = '';
353
434
  child.stdin?.on('error', () => undefined);
@@ -461,6 +542,122 @@ export class RunSupervisor {
461
542
  this.logger.warn('run-started-report-failed', { runId: run.runId, error: errorMessage(error) });
462
543
  });
463
544
  }
545
+ /**
546
+ * A chat turn on the session's long-lived ACP agent (acp/chat-session.ts):
547
+ * no process per turn, so "done" is the prompt's stopReason, not an exit.
548
+ * Returns `{ fallback }` when this device cannot run the CLI over ACP and
549
+ * the per-turn chat driver should answer instead.
550
+ */
551
+ async startAcpChat(payload, context) {
552
+ const { spec, cli, sessionKey, workdir, turn, signal, refuse } = context;
553
+ const runId = payload.run_id;
554
+ const access = accessLevel({ permissionMode: context.permissionMode, ...(turn.access ? { access: turn.access } : {}) });
555
+ let launch;
556
+ let attachments;
557
+ try {
558
+ if (!this.reporter.chatEvents)
559
+ throw new Error('实时聊天转发未配置');
560
+ if (!payload.prompt && !payload.attachments?.length)
561
+ throw new Error('消息内容为空');
562
+ attachments = await this.prepareChatAttachments(payload);
563
+ launch = await this.acpChats.prepare(spec, { access, reasoningEffort: payload.reasoning_effort, model: payload.model, workdir });
564
+ signal.throwIfAborted();
565
+ }
566
+ catch (error) {
567
+ if (signal.aborted) {
568
+ this.remember({ runId, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'cancelled', chat: true });
569
+ await this.report(runId, { status: 'cancelled', duration_ms: 0 });
570
+ return 'handled';
571
+ }
572
+ if (error instanceof AcpRuntimeUnavailable) {
573
+ this.logger.warn('acp-chat-unavailable', { runId, agentType: cli.id, error: error.message });
574
+ if (/^本机找不到/.test(error.message)) {
575
+ await refuse(cliFailure('cliMissing', { label: cli.label, ...(cli.installHint ? { installHint: cli.installHint } : {}) }));
576
+ return 'handled';
577
+ }
578
+ if (cli.chat)
579
+ return { fallback: `${error.message},本轮改用旧版聊天驱动` };
580
+ await refuse({ kind: 'startFailed', message: error.message });
581
+ return 'handled';
582
+ }
583
+ await refuse(errorMessage(error));
584
+ return 'handled';
585
+ }
586
+ if ([...this.active.values(), ...this.acpRuns.values()].some((run) => run.sessionKey === sessionKey)) {
587
+ await refuse('本机该会话已有任务在运行');
588
+ return 'handled';
589
+ }
590
+ const tail = new TerminalTailBuffer();
591
+ const run = { runId, sessionKey, startedAt: Date.now(), tail };
592
+ this.acpRuns.set(runId, run);
593
+ this.preparing.delete(runId);
594
+ this.unreported.add(runId);
595
+ const notes = [...(payload.notice ? [payload.notice] : []), ...turn.notes];
596
+ const settingsRow = turnSettingsLabel(turn, payload);
597
+ if (settingsRow)
598
+ notes.push(settingsRow);
599
+ this.logger.info('run-started', { runId, agentType: cli.id, driver: 'acp', resume: Boolean(payload.session_id) });
600
+ let forwardingError = '';
601
+ const forwarder = new ChatEventForwarder(runId, (id, events) => this.reporter.chatEvents(id, events), (message) => {
602
+ forwardingError = message;
603
+ this.logger.warn('chat-events-failed', { runId, error: message });
604
+ this.acpChats.cancel(runId);
605
+ });
606
+ let reported = { pid: 0, sessionId: '' };
607
+ const result = await this.acpChats.run(sessionKey, spec, {
608
+ runId,
609
+ prompt: context.prompt,
610
+ attachments,
611
+ sessionId: payload.session_id,
612
+ model: payload.model,
613
+ reasoningEffort: payload.reasoning_effort,
614
+ access,
615
+ plan: turn.plan,
616
+ fast: turn.fast,
617
+ workdir,
618
+ notes
619
+ }, {
620
+ events: (events) => forwarder.push(events),
621
+ rows: (rows) => { for (const row of rows)
622
+ tail.append(`${sanitizeTerminalLine(row)}\n`); },
623
+ started: (pid, sessionId) => {
624
+ if (reported.pid === pid && reported.sessionId === sessionId)
625
+ return;
626
+ reported = { pid, sessionId };
627
+ void this.reporter.started(runId, { ...(pid > 0 ? { pid } : {}), ...(sessionId ? { session_id: sessionId } : {}) }).catch((error) => {
628
+ this.logger.warn('run-started-report-failed', { runId, error: errorMessage(error) });
629
+ });
630
+ }
631
+ }, launch);
632
+ await forwarder.drain();
633
+ this.acpRuns.delete(runId);
634
+ const durationMs = Date.now() - run.startedAt;
635
+ let report;
636
+ if (forwardingError)
637
+ report = failedReport({ kind: 'hostFault', message: forwardingError }, durationMs);
638
+ else if (result.status === 'succeeded')
639
+ report = { status: 'succeeded', duration_ms: durationMs };
640
+ else if (result.status === 'cancelled')
641
+ report = { status: 'cancelled', duration_ms: durationMs };
642
+ else
643
+ report = failedReport(result.failure ?? cliFailure('turnFailed', { label: cli.label }), durationMs);
644
+ if (result.sessionId)
645
+ report.session_id = result.sessionId;
646
+ if (result.finalMessage)
647
+ report.final_message = sanitizeChatText(result.finalMessage);
648
+ tail.append(`● 本轮结束:${report.status}\n`);
649
+ this.remember({ runId, sessionKey, tail, finishedAt: Date.now(), status: report.status, chat: true });
650
+ this.logger.info('run-finished', { runId, status: report.status, driver: 'acp', durationMs });
651
+ await this.report(runId, report);
652
+ return 'handled';
653
+ }
654
+ /** Delivers a user message into a running chat turn (`chat.run.steer`). */
655
+ async steer(runId, steerId, prompt) {
656
+ const outcome = await this.acpChats.steer(runId, steerId, prompt, this.preparing.has(runId));
657
+ this.acpRuns.get(runId)?.tail.append(`● 收到插入消息(${outcome})\n`);
658
+ this.logger.info('run-steer', { runId, steerId, outcome });
659
+ return outcome;
660
+ }
464
661
  onStdout(run, rawLine) {
465
662
  run.recorder?.write({ stream: 'stdout', data: `${rawLine}\n` });
466
663
  // JSON-RPC replies can contain an entire restored transcript. Redacting
@@ -727,6 +924,12 @@ export class RunSupervisor {
727
924
  }
728
925
  /** Stops a run: the whole process tree, then a `cancelled` report. */
729
926
  async cancel(runId) {
927
+ const acp = this.acpRuns.get(runId);
928
+ if (acp) {
929
+ acp.tail.append('● 收到停止指令\n');
930
+ this.logger.info('run-cancel', { runId, driver: 'acp' });
931
+ return this.acpChats.cancel(runId);
932
+ }
730
933
  const run = this.active.get(runId);
731
934
  if (!run) {
732
935
  const preparing = this.preparing.get(runId);
@@ -753,15 +956,16 @@ export class RunSupervisor {
753
956
  return applied;
754
957
  }
755
958
  tail(query, limit, beforeCursor) {
756
- const byId = (id) => (id ? this.active.get(id) ?? this.recent.get(id) : undefined);
959
+ const byId = (id) => (id ? this.active.get(id) ?? this.acpRuns.get(id) ?? this.recent.get(id) : undefined);
757
960
  const bySession = (id) => {
758
961
  if (!id)
759
962
  return undefined;
760
- const live = [...this.active.values()].find((run) => run.sessionKey === id);
963
+ const live = [...this.active.values(), ...this.acpRuns.values()].find((run) => run.sessionKey === id);
761
964
  if (live)
762
965
  return live;
763
966
  return [...this.recent.values()].filter((run) => run.sessionKey === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
764
967
  };
968
+ const running = (runId) => this.active.has(runId) || this.acpRuns.has(runId);
765
969
  const empty = { lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: undefined };
766
970
  // A request for one run only ever shows that run: a run still preparing
767
971
  // (directory, attachments, session list) reads as running with no output
@@ -771,21 +975,24 @@ export class RunSupervisor {
771
975
  if (!run)
772
976
  return { ...empty, status: this.preparing.has(query.runId) ? 'running' : 'idle', run_id: query.runId };
773
977
  const read = run.tail.read(beforeCursor === undefined ? { limit } : { limit, beforeCursor });
774
- return { ...read, status: this.active.has(run.runId) ? 'running' : 'finished', run_id: run.runId };
978
+ return { ...read, status: running(run.runId) ? 'running' : 'finished', run_id: run.runId };
775
979
  }
776
980
  const target = bySession(query.taskChainId);
777
981
  if (!target)
778
982
  return { ...empty, status: 'idle' };
779
983
  const read = target.tail.read(beforeCursor === undefined ? { limit } : { limit, beforeCursor });
780
- return { ...read, status: this.active.has(target.runId) ? 'running' : 'finished', run_id: target.runId };
984
+ return { ...read, status: running(target.runId) ? 'running' : 'finished', run_id: target.runId };
781
985
  }
782
986
  async disposeAll() {
783
987
  for (const entry of this.preparing.values())
784
988
  entry.controller.abort();
785
- await Promise.all([...this.active.values()].map((run) => {
786
- run.cancelRequested = true;
787
- return killProcessTree(run.pid, 1_000);
788
- }));
989
+ await Promise.all([
990
+ ...[...this.active.values()].map((run) => {
991
+ run.cancelRequested = true;
992
+ return killProcessTree(run.pid, 1_000);
993
+ }),
994
+ this.acpChats.disposeAll()
995
+ ]);
789
996
  }
790
997
  remember(run) {
791
998
  this.recent.set(run.runId, run);
@@ -846,22 +1053,4 @@ function sessionKeyOf(payload) {
846
1053
  function errorMessage(error) {
847
1054
  return error instanceof Error ? error.message : String(error);
848
1055
  }
849
- /** Keep the protocol envelope intact while redacting only rendered content. */
850
- function sanitizeChatEvent(event) {
851
- const sanitize = (value) => {
852
- if (typeof value === 'string')
853
- return sanitizeChatText(value);
854
- if (Array.isArray(value))
855
- return value.map(sanitize);
856
- if (value && typeof value === 'object') {
857
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitize(item)]));
858
- }
859
- return value;
860
- };
861
- return {
862
- ...event,
863
- ...(event.text !== undefined ? { text: sanitizeChatText(event.text) } : {}),
864
- ...(event.item ? { item: sanitize(event.item) } : {})
865
- };
866
- }
867
1056
  //# sourceMappingURL=run-supervisor.js.map