toc-ocra 0.3.0 → 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 (86) hide show
  1. package/README.md +11 -5
  2. package/dist/cli/cli.mjs +3916 -1884
  3. package/dist/service/agent.mjs +3856 -1824
  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/config.d.ts +1 -1
  32. package/dist/src/providers/acp/acp-agents.d.ts +9 -0
  33. package/dist/src/providers/acp/acp-agents.js +8 -8
  34. package/dist/src/providers/acp/acp-agents.js.map +1 -1
  35. package/dist/src/providers/acp/acp-driver.d.ts +2 -2
  36. package/dist/src/providers/acp/acp-driver.js +9 -3
  37. package/dist/src/providers/acp/acp-driver.js.map +1 -1
  38. package/dist/src/providers/chat/codex-app-server.d.ts +1 -1
  39. package/dist/src/providers/chat/codex-app-server.js +6 -4
  40. package/dist/src/providers/chat/codex-app-server.js.map +1 -1
  41. package/dist/src/providers/chat/codex-goal.d.ts +17 -0
  42. package/dist/src/providers/chat/codex-goal.js +187 -0
  43. package/dist/src/providers/chat/codex-goal.js.map +1 -0
  44. package/dist/src/providers/cli/claude.d.ts +6 -0
  45. package/dist/src/providers/cli/claude.js +120 -8
  46. package/dist/src/providers/cli/claude.js.map +1 -1
  47. package/dist/src/providers/cli/codex-fork.d.ts +11 -0
  48. package/dist/src/providers/cli/codex-fork.js +84 -0
  49. package/dist/src/providers/cli/codex-fork.js.map +1 -0
  50. package/dist/src/providers/cli/codex.d.ts +12 -1
  51. package/dist/src/providers/cli/codex.js +33 -2
  52. package/dist/src/providers/cli/codex.js.map +1 -1
  53. package/dist/src/providers/cli/kiro.js +4 -3
  54. package/dist/src/providers/cli/kiro.js.map +1 -1
  55. package/dist/src/providers/cli-failure.js +1 -1
  56. package/dist/src/providers/provider.d.ts +46 -1
  57. package/dist/src/providers/provider.js +19 -0
  58. package/dist/src/providers/provider.js.map +1 -1
  59. package/dist/src/providers/registry.d.ts +7 -2
  60. package/dist/src/providers/registry.js +24 -8
  61. package/dist/src/providers/registry.js.map +1 -1
  62. package/dist/src/runs/run-supervisor.d.ts +53 -7
  63. package/dist/src/runs/run-supervisor.js +307 -61
  64. package/dist/src/runs/run-supervisor.js.map +1 -1
  65. package/dist/src/runtime/agent-runtime.js +26 -11
  66. package/dist/src/runtime/agent-runtime.js.map +1 -1
  67. package/dist/src/session/terminal-line-sanitizer.d.ts +5 -0
  68. package/dist/src/session/terminal-line-sanitizer.js +18 -0
  69. package/dist/src/session/terminal-line-sanitizer.js.map +1 -1
  70. package/dist/src/smoke/cli-smoke.js +1 -1
  71. package/dist/src/smoke/cli-smoke.js.map +1 -1
  72. package/dist/src/transport/gateway-client.d.ts +3 -1
  73. package/dist/src/transport/gateway-client.js +6 -0
  74. package/dist/src/transport/gateway-client.js.map +1 -1
  75. package/dist/src/types/protocol.d.ts +41 -4
  76. package/dist/src/types/protocol.js +30 -3
  77. package/dist/src/types/protocol.js.map +1 -1
  78. package/locales/en.json +1 -1
  79. package/locales/zh-CN.json +1 -1
  80. package/package.json +4 -2
  81. package/vendor/acp/claude/LICENSE +191 -0
  82. package/vendor/acp/claude/index.mjs +167 -0
  83. package/vendor/acp/claude/runtime.json +7 -0
  84. package/vendor/acp/codex/LICENSE +190 -0
  85. package/vendor/acp/codex/index.mjs +158 -0
  86. package/vendor/acp/codex/runtime.json +3 -0
@@ -2,16 +2,22 @@ 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
+ import { codexGoalProvider } from '../providers/chat/codex-goal.js';
12
+ import { forkCodexThread } from '../providers/cli/codex-fork.js';
11
13
  import { RunRecorder } from './run-recorder.js';
12
14
  import { currentPlatform } from '../platform/index.js';
13
15
  import { killProcessTree } from './process-tree.js';
14
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';
15
21
  /**
16
22
  * Supervises headless CLI turns. One process per turn:
17
23
  *
@@ -20,7 +26,7 @@ import { prepareTaskAttachments } from './task-attachments.js';
20
26
  *
21
27
  * "Done" is the process exit. If the CLI already declared the turn finished
22
28
  * but its process lingers, it is stopped after COMPLETION_EXIT_GRACE_MS, so
23
- * a finished turn can never keep the workstation busy. Stop kills the whole
29
+ * a finished turn can never keep the session busy. Stop kills the whole
24
30
  * process tree.
25
31
  */
26
32
  export const COMPLETION_EXIT_GRACE_MS = 15_000;
@@ -55,6 +61,53 @@ export const STALL_CATEGORY_LABELS = {
55
61
  file: '编辑文件',
56
62
  other: '等待 CLI 输出'
57
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
+ }
58
111
  function formatDuration(seconds) {
59
112
  if (seconds % 60 === 0)
60
113
  return `${seconds / 60} 分钟`;
@@ -68,23 +121,32 @@ export class RunSupervisor {
68
121
  reporter;
69
122
  orphans;
70
123
  active = new Map();
124
+ acpRuns = new Map();
71
125
  recent = new Map();
72
126
  /** Run ids whose finish report has not been acknowledged yet. */
73
127
  unreported = new Set();
74
128
  chatRunIds = new Set();
75
129
  preparing = new Map();
130
+ acpChats;
76
131
  constructor(config, logger, reporter, orphans) {
77
132
  this.config = config;
78
133
  this.logger = logger;
79
134
  this.reporter = reporter;
80
135
  this.orphans = orphans;
136
+ this.acpChats = new AcpChatHost({ logger, dataDir: config.dataDir, clientVersion: agentPackageVersion(), ...(orphans ? { orphans } : {}) });
81
137
  }
82
138
  get activeCount() {
83
- return this.active.size + this.preparing.size;
139
+ return this.active.size + this.acpRuns.size + this.preparing.size;
84
140
  }
85
141
  /** Runs to list in the heartbeat: still running, or finished but not yet reported. */
86
142
  activeRunIds() {
87
- 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);
88
150
  }
89
151
  activeChatRunIds() {
90
152
  return this.activeRunIds().filter(id => this.chatRunIds.has(id));
@@ -97,29 +159,29 @@ export class RunSupervisor {
97
159
  this.chatRunIds.delete(runId);
98
160
  }
99
161
  recentRuns() {
100
- const running = [...this.active.values()].map((run) => ({ runId: run.runId, workstationId: run.workstationId, status: 'running', at: run.startedAt }));
101
- const done = [...this.recent.values()].map((run) => ({ runId: run.runId, workstationId: run.workstationId, status: run.status, at: run.finishedAt }));
162
+ const running = [...this.active.values(), ...this.acpRuns.values()].map((run) => ({ runId: run.runId, sessionKey: run.sessionKey, status: 'running', at: run.startedAt }));
163
+ const done = [...this.recent.values()].map((run) => ({ runId: run.runId, sessionKey: run.sessionKey, status: run.status, at: run.finishedAt }));
102
164
  return [...running, ...done].sort((a, b) => b.at - a.at).slice(0, 30);
103
165
  }
104
166
  /**
105
- * Starts a turn. Refusals (busy workstation, concurrency limit, bad work
167
+ * Starts a turn. Refusals (busy session, concurrency limit, bad work
106
168
  * directory, unknown CLI) are reported as a failed run, never thrown.
107
169
  */
108
170
  /**
109
- * Different workstations run in parallel without a machine-wide cap by
110
- * default; each workstation still runs one turn at a time. A cap applies
171
+ * Different sessions run in parallel without a machine-wide cap by
172
+ * default; each session still runs one turn at a time. A cap applies
111
173
  * only when the operator sets TOC_OCRA_MAX_RUNS / maxConcurrentRuns.
112
174
  * The run being started is already counted in `preparing`.
113
175
  */
114
176
  overConcurrencyCap() {
115
177
  const cap = this.config.maxConcurrentRuns;
116
- return cap > 0 && this.active.size + this.preparing.size > cap;
178
+ return cap > 0 && this.active.size + this.acpRuns.size + this.preparing.size > cap;
117
179
  }
118
180
  async start(payload) {
119
181
  if (this.preparing.has(payload.run_id))
120
182
  return;
121
183
  const controller = new AbortController();
122
- this.preparing.set(payload.run_id, { workstationId: payload.workstation_id, controller });
184
+ this.preparing.set(payload.run_id, { sessionKey: sessionKeyOf(payload), controller });
123
185
  try {
124
186
  await this.startPrepared(payload, controller.signal);
125
187
  }
@@ -128,20 +190,21 @@ export class RunSupervisor {
128
190
  }
129
191
  }
130
192
  async startPrepared(payload, signal) {
131
- 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)) {
132
194
  this.logger.info('run-duplicate-ignored', { runId: payload.run_id });
133
195
  return;
134
196
  }
135
197
  if (payload.chat_session_id)
136
198
  this.chatRunIds.add(payload.run_id);
199
+ const sessionKey = sessionKeyOf(payload);
137
200
  const refuse = async (reason) => {
138
201
  const failure = typeof reason === 'string' ? { kind: 'hostFault', message: reason } : reason;
139
202
  this.logger.warn('run-refused', { runId: payload.run_id, error: failure.message, kind: failure.kind });
140
- this.remember({ runId: payload.run_id, workstationId: payload.workstation_id, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'failed', chat: !!payload.chat_session_id });
203
+ this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'failed', chat: !!payload.chat_session_id });
141
204
  await this.report(payload.run_id, { status: 'failed', error: failure.message, failure_kind: failure.kind, duration_ms: 0 });
142
205
  };
143
- if ([...this.active.values()].some((run) => run.workstationId === payload.workstation_id) || [...this.preparing].some(([id, run]) => id !== payload.run_id && run.workstationId === payload.workstation_id)) {
144
- return refuse('本机该工位已有任务在运行');
206
+ if (this.sessionBusy(sessionKey, payload.run_id)) {
207
+ return refuse('本机该会话已有任务在运行');
145
208
  }
146
209
  if (this.overConcurrencyCap()) {
147
210
  return refuse(`本机同时运行的任务已达上限(${this.config.maxConcurrentRuns})`);
@@ -155,11 +218,15 @@ export class RunSupervisor {
155
218
  if ('failure' in runnable)
156
219
  return refuse(runnable.failure);
157
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 } : {}) };
158
225
  let provider = cli.headless;
159
226
  let workdir;
160
227
  try {
161
228
  if (payload.task_attachments?.length && !payload.workdir)
162
- throw new Error('附件需要配置设备默认目录或工位工作目录');
229
+ throw new Error('附件需要配置设备默认目录或会话工作目录');
163
230
  workdir = payload.chat_session_id && !payload.workdir
164
231
  ? await this.defaultChatWorkdir()
165
232
  : await this.validateWorkdir(payload.workdir || this.config.allowedRoots[0]);
@@ -174,21 +241,32 @@ export class RunSupervisor {
174
241
  }
175
242
  catch (error) {
176
243
  if (signal.aborted) {
177
- this.remember({ runId: payload.run_id, workstationId: payload.workstation_id, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'cancelled', chat: !!payload.chat_session_id });
244
+ this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'cancelled', chat: !!payload.chat_session_id });
178
245
  await this.report(payload.run_id, { status: 'cancelled', error: '附件准备已取消', duration_ms: 0 });
179
246
  return;
180
247
  }
181
248
  return refuse(`附件下载失败:${errorMessage(error)}`);
182
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;
183
252
  const request = {
184
253
  permissionMode,
185
- prompt: payload.prompt,
254
+ ...runSettings,
255
+ prompt,
186
256
  sessionId: payload.session_id,
187
257
  model: payload.model,
188
258
  reasoningEffort: payload.reasoning_effort,
189
259
  workdir
190
260
  };
191
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
+ }
192
270
  try {
193
271
  if (!this.reporter.chatEvents)
194
272
  throw new Error('实时聊天转发未配置');
@@ -204,7 +282,7 @@ export class RunSupervisor {
204
282
  if (!payload.prompt && !payload.attachments?.length)
205
283
  return refuse('消息内容为空');
206
284
  // Providers that never print their session id: snapshot the folder's saved
207
- // chats. A workstation only resumes a chat that exists there; otherwise it
285
+ // chats. A session only resumes a chat that exists there; otherwise it
208
286
  // starts fresh and adopts the one chat this turn adds (never "the newest").
209
287
  let sessionId = payload.session_id;
210
288
  let sessionsBefore;
@@ -238,9 +316,26 @@ export class RunSupervisor {
238
316
  sessionsBefore = new Set(saved.map((session) => session.id));
239
317
  }
240
318
  }
319
+ // CLI fork (分叉) of Codex: copy the source thread into a new one first;
320
+ // this turn and the next ones continue the copy. Claude forks in its launch.
321
+ const fork = payload.fork && !payload.chat_session_id ? { sourceSessionId: payload.fork.source_session_id, keepTurns: payload.fork.keep_turns } : undefined;
322
+ if (fork && provider.id === 'codex' && !sessionId) {
323
+ try {
324
+ sessionId = await forkCodexThread({ sourceThreadId: fork.sourceSessionId, keepTurns: fork.keepTurns, workdir, permissionMode });
325
+ sessionNote += `● 已从会话 ${fork.sourceSessionId} 分叉${fork.keepTurns > 0 ? `(保留前 ${fork.keepTurns} 轮)` : ''},新会话 ${sessionId}\n`;
326
+ }
327
+ catch (error) {
328
+ return refuse({ kind: 'startFailed', message: `分叉 Codex 会话失败:${errorMessage(error)}` });
329
+ }
330
+ }
331
+ if (payload.goal && !payload.chat_session_id) {
332
+ if (provider.id !== 'codex')
333
+ return refuse('目标模式只支持 Codex');
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 } : {}) });
335
+ }
241
336
  // Preparing a directory or attachment may yield while another command starts.
242
- if ([...this.active.values()].some(run => run.workstationId === payload.workstation_id))
243
- return refuse('本机该工位已有任务在运行');
337
+ if ([...this.active.values(), ...this.acpRuns.values()].some(run => run.sessionKey === sessionKey))
338
+ return refuse('本机该会话已有任务在运行');
244
339
  if (this.overConcurrencyCap())
245
340
  return refuse(`本机同时运行的任务已达上限(${this.config.maxConcurrentRuns})`);
246
341
  // Providers with per-turn protocol state (ACP) get their own instance.
@@ -248,11 +343,13 @@ export class RunSupervisor {
248
343
  provider = provider.forTurn();
249
344
  const launch = provider.buildLaunch({
250
345
  permissionMode,
251
- prompt: payload.prompt,
346
+ ...runSettings,
347
+ prompt,
252
348
  sessionId,
253
349
  model: payload.model,
254
350
  reasoningEffort: payload.reasoning_effort,
255
- workdir
351
+ workdir,
352
+ ...(fork ? { fork } : {})
256
353
  });
257
354
  if (!fitsCommandLine(launch))
258
355
  return refuse(cliFailure('promptTooLong', { label: cli.label }));
@@ -274,14 +371,14 @@ export class RunSupervisor {
274
371
  chat: Boolean(payload.chat_session_id), chatReady: false, eventSequence: 0,
275
372
  pendingEvents: [], eventTail: Promise.resolve(), pendingBytes: 0, queuedBytes: 0, forwardingFailed: false,
276
373
  runId: payload.run_id,
277
- workstationId: payload.workstation_id,
374
+ sessionKey,
278
375
  agentType: provider.id,
279
376
  cli: { label: cli.label, ...(cli.installHint ? { installHint: cli.installHint } : {}) },
280
377
  provider,
281
378
  parse: provider.createLineParser?.() ?? ((line) => provider.parseLine(line)),
282
379
  ...(sessionsBefore ? { sessionsBefore } : {}),
283
380
  ...(sessionId && !payload.chat_session_id ? { resumeRetry: payload } : {}),
284
- prompt: payload.prompt,
381
+ prompt,
285
382
  child,
286
383
  pid: child.pid ?? 0,
287
384
  startedAt: Date.now(),
@@ -296,7 +393,8 @@ export class RunSupervisor {
296
393
  timedOut: false,
297
394
  tail: new TerminalTailBuffer(),
298
395
  timers: [],
299
- ...(payload.stall_policy && !payload.chat_session_id
396
+ // A goal run waits between turns while the CLI decides; no stall check.
397
+ ...(payload.stall_policy && !payload.chat_session_id && !payload.goal
300
398
  ? { stallPolicy: { idleSeconds: payload.stall_policy.idle_seconds, categorySeconds: (payload.stall_policy.category_seconds ?? {}) } }
301
399
  : {}),
302
400
  lastCategory: 'other',
@@ -312,7 +410,7 @@ export class RunSupervisor {
312
410
  }
313
411
  const recorder = RunRecorder.fromEnvironment(run.runId, {
314
412
  agent: provider.id, args: launch.args,
315
- 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 }
316
414
  });
317
415
  if (recorder)
318
416
  run.recorder = recorder;
@@ -325,7 +423,12 @@ export class RunSupervisor {
325
423
  run.tail.append(`● ${sanitizeTerminalLine(payload.notice)}\n`);
326
424
  if (sessionNote)
327
425
  run.tail.append(sessionNote);
426
+ for (const note of turn.notes)
427
+ run.tail.append(`● ${note}\n`);
328
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`);
329
432
  this.logger.info('run-started', { runId: run.runId, agentType: provider.id, pid: run.pid, resume: Boolean(sessionId) });
330
433
  let spawnError = '';
331
434
  child.stdin?.on('error', () => undefined);
@@ -420,6 +523,15 @@ export class RunSupervisor {
420
523
  void killProcessTree(run.pid);
421
524
  }, this.config.maxRunSeconds * 1_000));
422
525
  }
526
+ if (provider.tick) {
527
+ const ticker = setInterval(() => {
528
+ const parsed = this.active.has(run.runId) ? run.provider.tick?.() : undefined;
529
+ if (parsed)
530
+ this.applyParsed(run, parsed, '');
531
+ }, STALL_CHECK_INTERVAL_MS);
532
+ ticker.unref?.();
533
+ run.timers.push(ticker);
534
+ }
423
535
  if (run.stallPolicy) {
424
536
  const watchdog = setInterval(() => this.checkStall(run), STALL_CHECK_INTERVAL_MS);
425
537
  watchdog.unref?.();
@@ -430,6 +542,122 @@ export class RunSupervisor {
430
542
  this.logger.warn('run-started-report-failed', { runId: run.runId, error: errorMessage(error) });
431
543
  });
432
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
+ }
433
661
  onStdout(run, rawLine) {
434
662
  run.recorder?.write({ stream: 'stdout', data: `${rawLine}\n` });
435
663
  // JSON-RPC replies can contain an entire restored transcript. Redacting
@@ -456,6 +684,14 @@ export class RunSupervisor {
456
684
  run.lastOutputAt = Date.now();
457
685
  if (parsed.message !== undefined)
458
686
  run.finalMessage = sanitizeTerminalLine(parsed.message);
687
+ if (parsed.goal) {
688
+ const goal = { ...parsed.goal, objective: sanitizeChatText(parsed.goal.objective) };
689
+ void this.reporter.goal?.(run.runId, goal).catch((error) => this.logger.warn('goal-report-failed', { runId: run.runId, error: errorMessage(error) }));
690
+ }
691
+ if (parsed.goalTurn) {
692
+ const turn = { turn_id: parsed.goalTurn.turnId, message: sanitizeChatText(parsed.goalTurn.message) };
693
+ void this.reporter.goalTurn?.(run.runId, turn).catch((error) => this.logger.warn('goal-turn-report-failed', { runId: run.runId, error: errorMessage(error) }));
694
+ }
459
695
  if (parsed.turnError) {
460
696
  run.turnError = sanitizeTerminalLine(parsed.turnError);
461
697
  if (parsed.failureKind)
@@ -476,7 +712,7 @@ export class RunSupervisor {
476
712
  }
477
713
  if ((parsed.turnCompleted || parsed.turnError) && !run.turnCompleted) {
478
714
  run.turnCompleted = true;
479
- // The turn is over; do not let a lingering process hold the workstation.
715
+ // The turn is over; do not let a lingering process hold the session.
480
716
  run.timers.push(setTimeout(() => {
481
717
  if (!this.active.has(run.runId))
482
718
  return;
@@ -579,7 +815,7 @@ export class RunSupervisor {
579
815
  report.final_message = run.finalMessage;
580
816
  run.tail.append(`● 进程已退出:${report.status}${code !== null ? `(exit ${code})` : ''}\n`);
581
817
  run.recorder?.write({ result: { ...report, duration_ms: 0 }, log: run.tail.read({ limit: 2_000 }).lines });
582
- this.remember({ runId: run.runId, workstationId: run.workstationId, tail: run.tail, finishedAt: Date.now(), status: report.status, chat: !!run.chat });
818
+ this.remember({ runId: run.runId, sessionKey: run.sessionKey, tail: run.tail, finishedAt: Date.now(), status: report.status, chat: !!run.chat });
583
819
  this.logger.info('run-finished', { runId: run.runId, status: report.status, code, durationMs });
584
820
  await this.report(run.runId, report);
585
821
  }
@@ -688,6 +924,12 @@ export class RunSupervisor {
688
924
  }
689
925
  /** Stops a run: the whole process tree, then a `cancelled` report. */
690
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
+ }
691
933
  const run = this.active.get(runId);
692
934
  if (!run) {
693
935
  const preparing = this.preparing.get(runId);
@@ -703,40 +945,54 @@ export class RunSupervisor {
703
945
  await killProcessTree(run.pid);
704
946
  return true;
705
947
  }
948
+ /** Pauses or clears the goal of a running goal run; false when there is none. */
949
+ controlGoal(runId, action) {
950
+ const run = this.active.get(runId);
951
+ if (!run?.provider.controlGoal)
952
+ return false;
953
+ const applied = run.provider.controlGoal(action);
954
+ if (applied)
955
+ run.tail.append(`● 收到${action === 'pause' ? '暂停' : '清除'}目标指令\n`);
956
+ return applied;
957
+ }
706
958
  tail(query, limit, beforeCursor) {
707
- const byId = (id) => (id ? this.active.get(id) ?? this.recent.get(id) : undefined);
708
- const byWorkstation = (id) => {
959
+ const byId = (id) => (id ? this.active.get(id) ?? this.acpRuns.get(id) ?? this.recent.get(id) : undefined);
960
+ const bySession = (id) => {
709
961
  if (!id)
710
962
  return undefined;
711
- const live = [...this.active.values()].find((run) => run.workstationId === id);
963
+ const live = [...this.active.values(), ...this.acpRuns.values()].find((run) => run.sessionKey === id);
712
964
  if (live)
713
965
  return live;
714
- return [...this.recent.values()].filter((run) => run.workstationId === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
966
+ return [...this.recent.values()].filter((run) => run.sessionKey === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
715
967
  };
968
+ const running = (runId) => this.active.has(runId) || this.acpRuns.has(runId);
716
969
  const empty = { lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: undefined };
717
970
  // A request for one run only ever shows that run: a run still preparing
718
971
  // (directory, attachments, session list) reads as running with no output
719
- // yet, never as the workstation's previous run.
972
+ // yet, never as the session's previous run.
720
973
  if (query.runId) {
721
974
  const run = byId(query.runId);
722
975
  if (!run)
723
976
  return { ...empty, status: this.preparing.has(query.runId) ? 'running' : 'idle', run_id: query.runId };
724
977
  const read = run.tail.read(beforeCursor === undefined ? { limit } : { limit, beforeCursor });
725
- 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 };
726
979
  }
727
- const target = byWorkstation(query.workstationId);
980
+ const target = bySession(query.taskChainId);
728
981
  if (!target)
729
982
  return { ...empty, status: 'idle' };
730
983
  const read = target.tail.read(beforeCursor === undefined ? { limit } : { limit, beforeCursor });
731
- 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 };
732
985
  }
733
986
  async disposeAll() {
734
987
  for (const entry of this.preparing.values())
735
988
  entry.controller.abort();
736
- await Promise.all([...this.active.values()].map((run) => {
737
- run.cancelRequested = true;
738
- return killProcessTree(run.pid, 1_000);
739
- }));
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
+ ]);
740
996
  }
741
997
  remember(run) {
742
998
  this.recent.set(run.runId, run);
@@ -777,7 +1033,7 @@ export class RunSupervisor {
777
1033
  }
778
1034
  async prepareTaskFiles(payload, signal = AbortSignal.timeout(15 * 60_000), workdir) {
779
1035
  if (!payload.workdir)
780
- throw new Error('请先配置设备默认目录或工位工作目录');
1036
+ throw new Error('请先配置设备默认目录或会话工作目录');
781
1037
  if (!this.reporter.taskFile)
782
1038
  throw new Error('任务附件下载未配置');
783
1039
  return prepareTaskAttachments(payload, workdir ?? await this.validateWorkdir(payload.workdir), this.reporter.taskFile, AbortSignal.any([signal, AbortSignal.timeout(15 * 60_000)]));
@@ -786,25 +1042,15 @@ export class RunSupervisor {
786
1042
  function failedReport(failure, durationMs) {
787
1043
  return { status: 'failed', error: failure.message, failure_kind: failure.kind, duration_ms: durationMs };
788
1044
  }
1045
+ /**
1046
+ * The busy key of a run: one run at a time per session. A task-chain run is
1047
+ * keyed by its task_chain_id; a CLI-chat-page run (no task chain) by its
1048
+ * chat_session_id; a run with neither falls back to its own run_id.
1049
+ */
1050
+ function sessionKeyOf(payload) {
1051
+ return payload.task_chain_id || payload.chat_session_id || payload.run_id;
1052
+ }
789
1053
  function errorMessage(error) {
790
1054
  return error instanceof Error ? error.message : String(error);
791
1055
  }
792
- /** Keep the protocol envelope intact while redacting only rendered content. */
793
- function sanitizeChatEvent(event) {
794
- const sanitize = (value) => {
795
- if (typeof value === 'string')
796
- return sanitizeChatText(value);
797
- if (Array.isArray(value))
798
- return value.map(sanitize);
799
- if (value && typeof value === 'object') {
800
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitize(item)]));
801
- }
802
- return value;
803
- };
804
- return {
805
- ...event,
806
- ...(event.text !== undefined ? { text: sanitizeChatText(event.text) } : {}),
807
- ...(event.item ? { item: sanitize(event.item) } : {})
808
- };
809
- }
810
1056
  //# sourceMappingURL=run-supervisor.js.map