toc-ocra 0.2.38 → 0.3.1

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 (93) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +147 -139
  3. package/assets/icon.svg +1 -1
  4. package/dist/cli/cli.mjs +3586 -2565
  5. package/dist/plugin/renderer.css.map +1 -1
  6. package/dist/plugin/renderer.js.map +1 -1
  7. package/dist/service/agent.mjs +1901 -1001
  8. package/dist/src/config.d.ts +4 -2
  9. package/dist/src/config.js +6 -6
  10. package/dist/src/config.js.map +1 -1
  11. package/dist/src/health/server.js +8 -8
  12. package/dist/src/index.js +43 -1
  13. package/dist/src/index.js.map +1 -1
  14. package/dist/src/providers/acp/acp-agents.d.ts +5 -0
  15. package/dist/src/providers/acp/acp-agents.js +55 -0
  16. package/dist/src/providers/acp/acp-agents.js.map +1 -0
  17. package/dist/src/providers/acp/acp-driver.d.ts +60 -0
  18. package/dist/src/providers/acp/acp-driver.js +317 -0
  19. package/dist/src/providers/acp/acp-driver.js.map +1 -0
  20. package/dist/src/providers/chat/codex-app-server.d.ts +1 -1
  21. package/dist/src/providers/chat/codex-app-server.js +4 -3
  22. package/dist/src/providers/chat/codex-app-server.js.map +1 -1
  23. package/dist/src/providers/chat/codex-goal.d.ts +17 -0
  24. package/dist/src/providers/chat/codex-goal.js +188 -0
  25. package/dist/src/providers/chat/codex-goal.js.map +1 -0
  26. package/dist/src/providers/chat/index.d.ts +4 -2
  27. package/dist/src/providers/chat/index.js +7 -8
  28. package/dist/src/providers/chat/index.js.map +1 -1
  29. package/dist/src/providers/cli/claude.d.ts +6 -0
  30. package/dist/src/providers/cli/claude.js +107 -5
  31. package/dist/src/providers/cli/claude.js.map +1 -1
  32. package/dist/src/providers/cli/codex-fork.d.ts +11 -0
  33. package/dist/src/providers/cli/codex-fork.js +84 -0
  34. package/dist/src/providers/cli/codex-fork.js.map +1 -0
  35. package/dist/src/providers/cli/codex.js +5 -1
  36. package/dist/src/providers/cli/codex.js.map +1 -1
  37. package/dist/src/providers/cli/gemini.js +3 -1
  38. package/dist/src/providers/cli/gemini.js.map +1 -1
  39. package/dist/src/providers/cli/grok.js +3 -1
  40. package/dist/src/providers/cli/grok.js.map +1 -1
  41. package/dist/src/providers/cli/kiro.d.ts +10 -4
  42. package/dist/src/providers/cli/kiro.js +38 -38
  43. package/dist/src/providers/cli/kiro.js.map +1 -1
  44. package/dist/src/providers/cli/opencode.js +3 -1
  45. package/dist/src/providers/cli/opencode.js.map +1 -1
  46. package/dist/src/providers/cli-failure.d.ts +66 -0
  47. package/dist/src/providers/cli-failure.js +128 -0
  48. package/dist/src/providers/cli-failure.js.map +1 -0
  49. package/dist/src/providers/cli-specs.d.ts +58 -0
  50. package/dist/src/providers/cli-specs.js +37 -0
  51. package/dist/src/providers/cli-specs.js.map +1 -0
  52. package/dist/src/providers/codex-quota.js +3 -2
  53. package/dist/src/providers/codex-quota.js.map +1 -1
  54. package/dist/src/providers/kiro-quota.js +3 -2
  55. package/dist/src/providers/kiro-quota.js.map +1 -1
  56. package/dist/src/providers/model-catalog-collector.d.ts +1 -1
  57. package/dist/src/providers/model-catalog-collector.js +3 -3
  58. package/dist/src/providers/model-catalog-collector.js.map +1 -1
  59. package/dist/src/providers/model-catalog.d.ts +0 -2
  60. package/dist/src/providers/model-catalog.js +12 -13
  61. package/dist/src/providers/model-catalog.js.map +1 -1
  62. package/dist/src/providers/provider.d.ts +38 -46
  63. package/dist/src/providers/provider.js +6 -4
  64. package/dist/src/providers/provider.js.map +1 -1
  65. package/dist/src/providers/quota-reader.d.ts +1 -1
  66. package/dist/src/providers/quota-reader.js +5 -10
  67. package/dist/src/providers/quota-reader.js.map +1 -1
  68. package/dist/src/providers/registry.d.ts +46 -9
  69. package/dist/src/providers/registry.js +73 -21
  70. package/dist/src/providers/registry.js.map +1 -1
  71. package/dist/src/runs/run-recorder.d.ts +32 -0
  72. package/dist/src/runs/run-recorder.js +27 -0
  73. package/dist/src/runs/run-recorder.js.map +1 -0
  74. package/dist/src/runs/run-supervisor.d.ts +23 -5
  75. package/dist/src/runs/run-supervisor.js +205 -81
  76. package/dist/src/runs/run-supervisor.js.map +1 -1
  77. package/dist/src/runtime/agent-runtime.js +10 -10
  78. package/dist/src/runtime/agent-runtime.js.map +1 -1
  79. package/dist/src/smoke/cli-smoke.d.ts +30 -0
  80. package/dist/src/smoke/cli-smoke.js +92 -0
  81. package/dist/src/smoke/cli-smoke.js.map +1 -0
  82. package/dist/src/transport/gateway-client.d.ts +3 -1
  83. package/dist/src/transport/gateway-client.js +6 -0
  84. package/dist/src/transport/gateway-client.js.map +1 -1
  85. package/dist/src/types/protocol.d.ts +35 -4
  86. package/dist/src/types/protocol.js +14 -3
  87. package/dist/src/types/protocol.js.map +1 -1
  88. package/locales/en.json +202 -202
  89. package/locales/zh-CN.json +202 -202
  90. package/package.json +102 -102
  91. package/scripts/installation.cjs +260 -260
  92. package/scripts/postinstall.cjs +22 -22
  93. package/scripts/service.mjs +253 -253
@@ -4,9 +4,13 @@ import { basename, isAbsolute, join, relative, resolve } from 'node:path';
4
4
  import { createInterface } from 'node:readline';
5
5
  import { fitsCommandLine, pickCreatedSession } from '../providers/provider.js';
6
6
  import { resolveChatProvider } from '../providers/chat/index.js';
7
- import { resolveHeadlessProvider } from '../providers/registry.js';
7
+ import { classifyCliOutput, classifySpawnError, cliFailure } from '../providers/cli-failure.js';
8
+ import { resolveRunnableCli } from '../providers/registry.js';
8
9
  import { sanitizeChatText, sanitizeTerminalLine } from '../session/terminal-line-sanitizer.js';
9
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';
13
+ import { RunRecorder } from './run-recorder.js';
10
14
  import { currentPlatform } from '../platform/index.js';
11
15
  import { killProcessTree } from './process-tree.js';
12
16
  import { prepareTaskAttachments } from './task-attachments.js';
@@ -18,7 +22,7 @@ import { prepareTaskAttachments } from './task-attachments.js';
18
22
  *
19
23
  * "Done" is the process exit. If the CLI already declared the turn finished
20
24
  * but its process lingers, it is stopped after COMPLETION_EXIT_GRACE_MS, so
21
- * a finished turn can never keep the workstation busy. Stop kills the whole
25
+ * a finished turn can never keep the session busy. Stop kills the whole
22
26
  * process tree.
23
27
  */
24
28
  export const COMPLETION_EXIT_GRACE_MS = 15_000;
@@ -27,6 +31,8 @@ export const EXIT_OUTPUT_GRACE_MS = 2_000;
27
31
  const RECENT_RUN_TTL_MS = 10 * 60_000;
28
32
  const MAX_RECENT_RUNS = 100;
29
33
  const MAX_ERROR_ROWS = 40;
34
+ /** How long a protocol CLI may take to open its session (MCP servers start first). */
35
+ export const SESSION_START_TIMEOUT_MS = 120_000;
30
36
  /** How often a run with a stall policy is checked for silence. */
31
37
  export const STALL_CHECK_INTERVAL_MS = 5_000;
32
38
  /** Run-log row markers (see the providers' display rows) → broad step kind. */
@@ -93,19 +99,29 @@ export class RunSupervisor {
93
99
  this.chatRunIds.delete(runId);
94
100
  }
95
101
  recentRuns() {
96
- const running = [...this.active.values()].map((run) => ({ runId: run.runId, workstationId: run.workstationId, status: 'running', at: run.startedAt }));
97
- const done = [...this.recent.values()].map((run) => ({ runId: run.runId, workstationId: run.workstationId, status: run.status, at: run.finishedAt }));
102
+ const running = [...this.active.values()].map((run) => ({ runId: run.runId, sessionKey: run.sessionKey, status: 'running', at: run.startedAt }));
103
+ const done = [...this.recent.values()].map((run) => ({ runId: run.runId, sessionKey: run.sessionKey, status: run.status, at: run.finishedAt }));
98
104
  return [...running, ...done].sort((a, b) => b.at - a.at).slice(0, 30);
99
105
  }
100
106
  /**
101
- * Starts a turn. Refusals (busy workstation, concurrency limit, bad work
107
+ * Starts a turn. Refusals (busy session, concurrency limit, bad work
102
108
  * directory, unknown CLI) are reported as a failed run, never thrown.
103
109
  */
110
+ /**
111
+ * Different sessions run in parallel without a machine-wide cap by
112
+ * default; each session still runs one turn at a time. A cap applies
113
+ * only when the operator sets TOC_OCRA_MAX_RUNS / maxConcurrentRuns.
114
+ * The run being started is already counted in `preparing`.
115
+ */
116
+ overConcurrencyCap() {
117
+ const cap = this.config.maxConcurrentRuns;
118
+ return cap > 0 && this.active.size + this.preparing.size > cap;
119
+ }
104
120
  async start(payload) {
105
121
  if (this.preparing.has(payload.run_id))
106
122
  return;
107
123
  const controller = new AbortController();
108
- this.preparing.set(payload.run_id, { workstationId: payload.workstation_id, controller });
124
+ this.preparing.set(payload.run_id, { sessionKey: sessionKeyOf(payload), controller });
109
125
  try {
110
126
  await this.startPrepared(payload, controller.signal);
111
127
  }
@@ -120,28 +136,33 @@ export class RunSupervisor {
120
136
  }
121
137
  if (payload.chat_session_id)
122
138
  this.chatRunIds.add(payload.run_id);
123
- const refuse = async (error) => {
124
- this.logger.warn('run-refused', { runId: payload.run_id, error });
125
- this.remember({ runId: payload.run_id, workstationId: payload.workstation_id, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'failed', chat: !!payload.chat_session_id });
126
- await this.report(payload.run_id, { status: 'failed', error, duration_ms: 0 });
139
+ const sessionKey = sessionKeyOf(payload);
140
+ const refuse = async (reason) => {
141
+ const failure = typeof reason === 'string' ? { kind: 'hostFault', message: reason } : reason;
142
+ this.logger.warn('run-refused', { runId: payload.run_id, error: failure.message, kind: failure.kind });
143
+ this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'failed', chat: !!payload.chat_session_id });
144
+ await this.report(payload.run_id, { status: 'failed', error: failure.message, failure_kind: failure.kind, duration_ms: 0 });
127
145
  };
128
- 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)) {
129
- return refuse('本机该工位已有任务在运行');
146
+ if ([...this.active.values()].some((run) => run.sessionKey === sessionKey) || [...this.preparing].some(([id, run]) => id !== payload.run_id && run.sessionKey === sessionKey)) {
147
+ return refuse('本机该会话已有任务在运行');
130
148
  }
131
- if (this.active.size + this.preparing.size > this.config.maxConcurrentRuns) {
149
+ if (this.overConcurrencyCap()) {
132
150
  return refuse(`本机同时运行的任务已达上限(${this.config.maxConcurrentRuns})`);
133
151
  }
134
152
  if (!payload.cli_policy?.enabled || payload.cli_policy.version !== 1)
135
153
  return refuse('这台电脑尚未授权远程执行,请在 Echo 的电脑执行权限中开启并升级服务端');
136
- if (payload.cli_policy.mode !== 'full' && !['codex', 'claude', 'claude-code', 'kiro'].includes(payload.agent_type.toLowerCase()))
137
- return refuse('此 CLI 尚未支持受限权限,请由电脑所有者明确选择完整权限后再执行');
138
154
  const permissionMode = payload.cli_policy.mode;
139
- let provider;
155
+ // Whether this CLI runs here at all (OS, chat, restricted permission) is
156
+ // declared in cli-specs.ts / registry.ts, never by naming CLIs here.
157
+ const runnable = resolveRunnableCli(payload.agent_type, { chat: Boolean(payload.chat_session_id), permissionMode });
158
+ if ('failure' in runnable)
159
+ return refuse(runnable.failure);
160
+ const cli = runnable.entry;
161
+ let provider = cli.headless;
140
162
  let workdir;
141
163
  try {
142
- provider = resolveHeadlessProvider(payload.agent_type);
143
164
  if (payload.task_attachments?.length && !payload.workdir)
144
- throw new Error('附件需要配置设备默认目录或工位工作目录');
165
+ throw new Error('附件需要配置设备默认目录或会话工作目录');
145
166
  workdir = payload.chat_session_id && !payload.workdir
146
167
  ? await this.defaultChatWorkdir()
147
168
  : await this.validateWorkdir(payload.workdir || this.config.allowedRoots[0]);
@@ -156,7 +177,7 @@ export class RunSupervisor {
156
177
  }
157
178
  catch (error) {
158
179
  if (signal.aborted) {
159
- this.remember({ runId: payload.run_id, workstationId: payload.workstation_id, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'cancelled', chat: !!payload.chat_session_id });
180
+ this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'cancelled', chat: !!payload.chat_session_id });
160
181
  await this.report(payload.run_id, { status: 'cancelled', error: '附件准备已取消', duration_ms: 0 });
161
182
  return;
162
183
  }
@@ -181,15 +202,16 @@ export class RunSupervisor {
181
202
  return refuse(errorMessage(error));
182
203
  }
183
204
  }
205
+ if (!provider)
206
+ return refuse(cliFailure('cliUnsupported', { label: cli.label }));
184
207
  if (!payload.prompt && !payload.attachments?.length)
185
208
  return refuse('消息内容为空');
186
209
  // Providers that never print their session id: snapshot the folder's saved
187
- // chats. A workstation only resumes a chat that exists there; otherwise it
210
+ // chats. A session only resumes a chat that exists there; otherwise it
188
211
  // starts fresh and adopts the one chat this turn adds (never "the newest").
189
212
  let sessionId = payload.session_id;
190
213
  let sessionsBefore;
191
214
  let sessionNote = '';
192
- let unverifiedResume = false;
193
215
  if (!payload.chat_session_id && provider.listSessions) {
194
216
  let saved;
195
217
  let listError = '';
@@ -204,7 +226,6 @@ export class RunSupervisor {
204
226
  // The CLI rejects a missing session explicitly; only then go fresh.
205
227
  this.logger.warn('list-sessions-failed', { runId: payload.run_id, agentType: provider.id, error: listError });
206
228
  if (sessionId) {
207
- unverifiedResume = true;
208
229
  sessionNote = `● 无法读取 ${provider.id} 的已保存会话(${listError}),继续使用原会话\n`;
209
230
  }
210
231
  else {
@@ -220,21 +241,42 @@ export class RunSupervisor {
220
241
  sessionsBefore = new Set(saved.map((session) => session.id));
221
242
  }
222
243
  }
244
+ // CLI fork (分叉) of Codex: copy the source thread into a new one first;
245
+ // this turn and the next ones continue the copy. Claude forks in its launch.
246
+ const fork = payload.fork && !payload.chat_session_id ? { sourceSessionId: payload.fork.source_session_id, keepTurns: payload.fork.keep_turns } : undefined;
247
+ if (fork && provider.id === 'codex' && !sessionId) {
248
+ try {
249
+ sessionId = await forkCodexThread({ sourceThreadId: fork.sourceSessionId, keepTurns: fork.keepTurns, workdir, permissionMode });
250
+ sessionNote += `● 已从会话 ${fork.sourceSessionId} 分叉${fork.keepTurns > 0 ? `(保留前 ${fork.keepTurns} 轮)` : ''},新会话 ${sessionId}\n`;
251
+ }
252
+ catch (error) {
253
+ return refuse({ kind: 'startFailed', message: `分叉 Codex 会话失败:${errorMessage(error)}` });
254
+ }
255
+ }
256
+ if (payload.goal && !payload.chat_session_id) {
257
+ if (provider.id !== 'codex')
258
+ 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 } : {}) });
260
+ }
223
261
  // Preparing a directory or attachment may yield while another command starts.
224
- if ([...this.active.values()].some(run => run.workstationId === payload.workstation_id))
225
- return refuse('本机该工位已有任务在运行');
226
- if (this.active.size + this.preparing.size > this.config.maxConcurrentRuns)
227
- return refuse('本机同时运行的任务已达上限');
262
+ if ([...this.active.values()].some(run => run.sessionKey === sessionKey))
263
+ return refuse('本机该会话已有任务在运行');
264
+ if (this.overConcurrencyCap())
265
+ return refuse(`本机同时运行的任务已达上限(${this.config.maxConcurrentRuns})`);
266
+ // Providers with per-turn protocol state (ACP) get their own instance.
267
+ if (provider.forTurn)
268
+ provider = provider.forTurn();
228
269
  const launch = provider.buildLaunch({
229
270
  permissionMode,
230
271
  prompt: payload.prompt,
231
272
  sessionId,
232
273
  model: payload.model,
233
274
  reasoningEffort: payload.reasoning_effort,
234
- workdir
275
+ workdir,
276
+ ...(fork ? { fork } : {})
235
277
  });
236
278
  if (!fitsCommandLine(launch))
237
- return refuse(`消息过长,超出本机命令行长度上限,${provider.id} 暂不支持从标准输入读取提示词,请缩短消息后重试`);
279
+ return refuse(cliFailure('promptTooLong', { label: cli.label }));
238
280
  let child;
239
281
  try {
240
282
  child = spawn(launch.executable, launch.args, {
@@ -247,18 +289,19 @@ export class RunSupervisor {
247
289
  });
248
290
  }
249
291
  catch (error) {
250
- return refuse(`无法启动 ${provider.id}:${errorMessage(error)}`);
292
+ return refuse(classifySpawnError(errorMessage(error), cli));
251
293
  }
252
294
  const run = {
253
295
  chat: Boolean(payload.chat_session_id), chatReady: false, eventSequence: 0,
254
296
  pendingEvents: [], eventTail: Promise.resolve(), pendingBytes: 0, queuedBytes: 0, forwardingFailed: false,
255
297
  runId: payload.run_id,
256
- workstationId: payload.workstation_id,
298
+ sessionKey,
257
299
  agentType: provider.id,
300
+ cli: { label: cli.label, ...(cli.installHint ? { installHint: cli.installHint } : {}) },
258
301
  provider,
259
302
  parse: provider.createLineParser?.() ?? ((line) => provider.parseLine(line)),
260
303
  ...(sessionsBefore ? { sessionsBefore } : {}),
261
- ...(unverifiedResume ? { unverifiedResume: payload } : {}),
304
+ ...(sessionId && !payload.chat_session_id ? { resumeRetry: payload } : {}),
262
305
  prompt: payload.prompt,
263
306
  child,
264
307
  pid: child.pid ?? 0,
@@ -274,7 +317,8 @@ export class RunSupervisor {
274
317
  timedOut: false,
275
318
  tail: new TerminalTailBuffer(),
276
319
  timers: [],
277
- ...(payload.stall_policy && !payload.chat_session_id
320
+ // A goal run waits between turns while the CLI decides; no stall check.
321
+ ...(payload.stall_policy && !payload.chat_session_id && !payload.goal
278
322
  ? { stallPolicy: { idleSeconds: payload.stall_policy.idle_seconds, categorySeconds: (payload.stall_policy.category_seconds ?? {}) } }
279
323
  : {}),
280
324
  lastCategory: 'other',
@@ -288,6 +332,12 @@ export class RunSupervisor {
288
332
  this.applyParsed(run, parsed, ''); }
289
333
  });
290
334
  }
335
+ const recorder = RunRecorder.fromEnvironment(run.runId, {
336
+ agent: provider.id, args: launch.args,
337
+ request: { session_id: sessionId, model: payload.model, reasoning_effort: payload.reasoning_effort, permission: permissionMode, prompt: payload.prompt }
338
+ });
339
+ if (recorder)
340
+ run.recorder = recorder;
291
341
  this.active.set(run.runId, run);
292
342
  this.preparing.delete(run.runId);
293
343
  this.unreported.add(run.runId);
@@ -302,19 +352,25 @@ export class RunSupervisor {
302
352
  let spawnError = '';
303
353
  child.stdin?.on('error', () => undefined);
304
354
  // Prompt too long for this OS's command line: the CLI reads it from stdin.
305
- if (launch.stdin !== undefined && !provider.startInput)
355
+ if (launch.stdin !== undefined && !provider.startInput) {
356
+ run.recorder?.write({ stream: 'stdin', data: launch.stdin });
306
357
  child.stdin?.end(launch.stdin, 'utf8');
358
+ }
307
359
  child.once('error', (error) => {
308
360
  spawnError = error.message;
309
361
  });
310
362
  if (run.stream) {
311
363
  child.stdout.setEncoding('utf8');
312
- child.stdout.on('data', (chunk) => this.applyParsed(run, run.stream.stdout(chunk), chunk));
364
+ child.stdout.on('data', (chunk) => {
365
+ run.recorder?.write({ stream: 'stdout', data: chunk });
366
+ this.applyParsed(run, run.stream.stdout(chunk), chunk);
367
+ });
313
368
  }
314
369
  else {
315
370
  createInterface({ input: child.stdout }).on('line', (line) => this.onStdout(run, line));
316
371
  }
317
372
  createInterface({ input: child.stderr }).on('line', (line) => {
373
+ run.recorder?.write({ stream: 'stderr', data: line });
318
374
  const clean = sanitizeTerminalLine(line);
319
375
  if (!clean.trim())
320
376
  return;
@@ -358,26 +414,43 @@ export class RunSupervisor {
358
414
  if (provider.startInput) {
359
415
  child.once('spawn', () => {
360
416
  try {
361
- provider.startInput?.(message => { child.stdin?.write(message); });
417
+ provider.startInput?.(message => {
418
+ run.recorder?.write({ stream: 'stdin', data: message });
419
+ child.stdin?.write(message);
420
+ });
362
421
  }
363
422
  catch (error) {
364
423
  run.turnError = errorMessage(error);
424
+ run.turnFailure = 'startFailed';
365
425
  void killProcessTree(run.pid);
366
426
  }
367
427
  });
368
428
  run.timers.push(setTimeout(() => {
369
429
  if (!run.chatReady && this.active.has(run.runId)) {
370
- run.turnError = 'CLI 实时会话初始化超时';
430
+ run.turnError = `${run.cli.label} 会话初始化超时`;
431
+ run.turnFailure = 'startFailed';
371
432
  void killProcessTree(run.pid);
372
433
  }
373
- }, 60_000));
434
+ }, SESSION_START_TIMEOUT_MS));
435
+ }
436
+ // No time limit unless the operator sets one: a long task runs to the
437
+ // end. A CLI that stops printing is caught by the stall policy instead.
438
+ if (this.config.maxRunSeconds > 0) {
439
+ run.timers.push(setTimeout(() => {
440
+ run.timedOut = true;
441
+ run.tail.append(`✗ 超过最长运行时间 ${this.config.maxRunSeconds} 秒,已终止\n`);
442
+ void killProcessTree(run.pid);
443
+ }, this.config.maxRunSeconds * 1_000));
444
+ }
445
+ if (provider.tick) {
446
+ const ticker = setInterval(() => {
447
+ const parsed = this.active.has(run.runId) ? run.provider.tick?.() : undefined;
448
+ if (parsed)
449
+ this.applyParsed(run, parsed, '');
450
+ }, STALL_CHECK_INTERVAL_MS);
451
+ ticker.unref?.();
452
+ run.timers.push(ticker);
374
453
  }
375
- const maxMs = this.config.maxRunSeconds * 1_000;
376
- run.timers.push(setTimeout(() => {
377
- run.timedOut = true;
378
- run.tail.append(`✗ 超过最长运行时间 ${this.config.maxRunSeconds} 秒,已终止\n`);
379
- void killProcessTree(run.pid);
380
- }, maxMs));
381
454
  if (run.stallPolicy) {
382
455
  const watchdog = setInterval(() => this.checkStall(run), STALL_CHECK_INTERVAL_MS);
383
456
  watchdog.unref?.();
@@ -389,6 +462,7 @@ export class RunSupervisor {
389
462
  });
390
463
  }
391
464
  onStdout(run, rawLine) {
465
+ run.recorder?.write({ stream: 'stdout', data: `${rawLine}\n` });
392
466
  // JSON-RPC replies can contain an entire restored transcript. Redacting
393
467
  // the serialized line first can swallow quotes and invalidate the reply.
394
468
  // Parse the wire format intact; only sanitize values that leave the device.
@@ -398,9 +472,10 @@ export class RunSupervisor {
398
472
  if (run.chat && !run.forwardingFailed) {
399
473
  for (const event of parsed.chatEvents ?? [])
400
474
  this.queueChatEvent(run, sanitizeChatEvent(event));
401
- if (parsed.sessionId)
402
- run.chatReady = true;
403
475
  }
476
+ // A protocol session (app-server, ACP) is ready once it names its session.
477
+ if (parsed.sessionId)
478
+ run.chatReady = true;
404
479
  for (const row of parsed.display) {
405
480
  const shown = sanitizeTerminalLine(row);
406
481
  run.tail.append(`${shown}\n`);
@@ -412,8 +487,19 @@ export class RunSupervisor {
412
487
  run.lastOutputAt = Date.now();
413
488
  if (parsed.message !== undefined)
414
489
  run.finalMessage = sanitizeTerminalLine(parsed.message);
415
- if (parsed.turnError)
490
+ if (parsed.goal) {
491
+ const goal = { ...parsed.goal, objective: sanitizeChatText(parsed.goal.objective) };
492
+ void this.reporter.goal?.(run.runId, goal).catch((error) => this.logger.warn('goal-report-failed', { runId: run.runId, error: errorMessage(error) }));
493
+ }
494
+ if (parsed.goalTurn) {
495
+ const turn = { turn_id: parsed.goalTurn.turnId, message: sanitizeChatText(parsed.goalTurn.message) };
496
+ void this.reporter.goalTurn?.(run.runId, turn).catch((error) => this.logger.warn('goal-turn-report-failed', { runId: run.runId, error: errorMessage(error) }));
497
+ }
498
+ if (parsed.turnError) {
416
499
  run.turnError = sanitizeTerminalLine(parsed.turnError);
500
+ if (parsed.failureKind)
501
+ run.turnFailure = parsed.failureKind;
502
+ }
417
503
  if (parsed.sessionId && parsed.sessionId !== run.sessionId) {
418
504
  run.sessionId = parsed.sessionId;
419
505
  void this.reporter.started(run.runId, { session_id: parsed.sessionId }).catch(() => undefined);
@@ -429,7 +515,7 @@ export class RunSupervisor {
429
515
  }
430
516
  if ((parsed.turnCompleted || parsed.turnError) && !run.turnCompleted) {
431
517
  run.turnCompleted = true;
432
- // The turn is over; do not let a lingering process hold the workstation.
518
+ // The turn is over; do not let a lingering process hold the session.
433
519
  run.timers.push(setTimeout(() => {
434
520
  if (!this.active.has(run.runId))
435
521
  return;
@@ -443,6 +529,7 @@ export class RunSupervisor {
443
529
  for (const timer of run.timers)
444
530
  clearTimeout(timer);
445
531
  run.timers = [];
532
+ run.recorder?.write({ exit: code });
446
533
  if (run.stream)
447
534
  this.applyParsed(run, await run.stream.end(), '');
448
535
  this.active.delete(run.runId);
@@ -451,32 +538,29 @@ export class RunSupervisor {
451
538
  clearTimeout(run.eventTimer);
452
539
  this.flushChatEvents(run);
453
540
  await run.eventTail;
454
- // Resumed a chat the folder listing could not confirm, and the CLI says
455
- // it is gone: start this same turn again as a fresh chat.
456
- const retry = run.unverifiedResume;
457
- if (retry && code !== 0 && !run.cancelRequested && !spawnError && !run.timedOut && !run.stalled && run.provider.isMissingSession?.(run.stderr)) {
541
+ // Resumed a session the CLI says is gone (not on this computer, deleted,
542
+ // another account): run this same turn again as a fresh session.
543
+ const retry = run.resumeRetry;
544
+ const missing = retry && (code !== 0 || run.turnError) && !run.cancelRequested && !spawnError && !run.timedOut && !run.stalled
545
+ && classifyCliOutput([...run.stderr, run.turnError], run.provider.failureRules, run.cli)?.kind === 'sessionMissing';
546
+ if (retry && missing) {
458
547
  this.logger.warn('resume-session-missing', { runId: run.runId, agentType: run.agentType, sessionId: run.sessionId });
459
548
  const { task_attachments: _prepared, ...rest } = retry;
460
- const missing = `原会话 ${run.sessionId} 已不存在,本轮改为开始新会话`;
461
- const notice = retry.notice ? `${retry.notice};${missing}` : missing;
549
+ const gone = `原会话 ${retry.session_id} 已不存在,本轮改为开始新会话`;
550
+ const notice = retry.notice ? `${retry.notice};${gone}` : gone;
462
551
  await this.start({ ...rest, session_id: '', notice });
463
552
  return;
464
553
  }
465
- // Post-exit inspection for CLIs whose stdout is not machine readable: a
466
- // business error hidden behind exit 0 (quota, auth). Only for non-chat
467
- // turns; chat uses app-server.
468
- if (!run.chat && !run.cancelRequested && !spawnError && !run.timedOut && !run.stalled && run.provider.inspectExit) {
469
- try {
470
- const inspection = await run.provider.inspectExit({ exitCode: code, stderr: run.stderr, workdir: run.workdir, sessionId: run.sessionId });
471
- if (inspection.turnError && !run.turnError)
472
- run.turnError = sanitizeTerminalLine(inspection.turnError);
473
- for (const row of inspection.display ?? [])
474
- run.tail.append(`${sanitizeTerminalLine(row)}\n`);
475
- if (inspection.sessionId && inspection.sessionId !== run.sessionId)
476
- run.sessionId = inspection.sessionId;
477
- }
478
- catch (error) {
479
- this.logger.warn('inspect-exit-failed', { runId: run.runId, error: errorMessage(error) });
554
+ // A business error hidden behind exit 0 (quota, auth): only the
555
+ // provider's `evenOnSuccess` rules, so a CLI that logged a retried 429
556
+ // and then answered is not failed. Only for non-chat turns.
557
+ if (!run.chat && !run.turnError && !run.cancelRequested && !spawnError && !run.timedOut && !run.stalled) {
558
+ const hidden = classifyCliOutput(run.stderr, run.provider.failureRules, run.cli, { successfulExit: true });
559
+ if (hidden) {
560
+ run.turnError = sanitizeTerminalLine(hidden.message);
561
+ run.turnFailure = hidden.kind;
562
+ if (hidden.rule.showInLog)
563
+ run.tail.append(`✗ ${run.turnError}\n`);
480
564
  }
481
565
  }
482
566
  // A fresh turn of a CLI that never prints its session id adopts the chat
@@ -505,27 +589,26 @@ export class RunSupervisor {
505
589
  report = { status: 'cancelled', duration_ms: durationMs };
506
590
  }
507
591
  else if (spawnError) {
508
- report = { status: 'failed', error: `无法启动 ${run.agentType}:${spawnError}`, duration_ms: durationMs };
592
+ report = failedReport(classifySpawnError(spawnError, run.cli), durationMs);
509
593
  }
510
594
  else if (run.stalled) {
511
595
  const stall = run.stalled;
512
596
  report = {
513
- status: 'failed', failure_reason: 'stalled', stall, duration_ms: durationMs,
597
+ status: 'failed', failure_reason: 'stalled', failure_kind: 'stalled', stall, duration_ms: durationMs,
514
598
  error: `CLI 已 ${formatDuration(stall.idle_seconds)}没有新输出(卡在:${STALL_CATEGORY_LABELS[stall.category]}${stall.last_line ? `(${stall.last_line})` : ''}),已自动停止`
515
599
  };
516
600
  }
517
601
  else if (run.timedOut) {
518
- report = { status: 'failed', error: `超过最长运行时间 ${this.config.maxRunSeconds} 秒`, duration_ms: durationMs };
602
+ report = failedReport(cliFailure('timedOut', { label: run.cli.label, seconds: this.config.maxRunSeconds }), durationMs);
519
603
  }
520
604
  else if (run.turnError) {
521
- report = { status: 'failed', error: run.turnError, duration_ms: durationMs };
605
+ report = failedReport(this.turnFailure(run), durationMs);
522
606
  }
523
607
  else if (code === 0 || run.killedAfterCompletion) {
524
608
  report = { status: 'succeeded', duration_ms: durationMs };
525
609
  }
526
610
  else {
527
- const detail = run.stderr.slice(-8).join('\n').trim();
528
- report = { status: 'failed', error: detail || `${run.agentType} 异常退出${signal ? `(${signal})` : ''}`, duration_ms: durationMs };
611
+ report = failedReport(this.exitFailure(run, signal), durationMs);
529
612
  }
530
613
  if (code !== null)
531
614
  report.exit_code = code;
@@ -534,10 +617,28 @@ export class RunSupervisor {
534
617
  if (run.finalMessage)
535
618
  report.final_message = run.finalMessage;
536
619
  run.tail.append(`● 进程已退出:${report.status}${code !== null ? `(exit ${code})` : ''}\n`);
537
- this.remember({ runId: run.runId, workstationId: run.workstationId, tail: run.tail, finishedAt: Date.now(), status: report.status, chat: !!run.chat });
620
+ run.recorder?.write({ result: { ...report, duration_ms: 0 }, log: run.tail.read({ limit: 2_000 }).lines });
621
+ this.remember({ runId: run.runId, sessionKey: run.sessionKey, tail: run.tail, finishedAt: Date.now(), status: report.status, chat: !!run.chat });
538
622
  this.logger.info('run-finished', { runId: run.runId, status: report.status, code, durationMs });
539
623
  await this.report(run.runId, report);
540
624
  }
625
+ /** The CLI declared the turn failed: name the kind, keep its own words. */
626
+ turnFailure(run) {
627
+ if (run.turnFailure)
628
+ return { kind: run.turnFailure, message: run.turnError };
629
+ const known = classifyCliOutput(run.turnError, run.provider.failureRules, run.cli);
630
+ if (!known)
631
+ return { kind: 'turnFailed', message: run.turnError };
632
+ return known.rule.message ? known : cliFailure(known.kind, { ...run.cli, detail: run.turnError });
633
+ }
634
+ /** Non-zero exit with no declared error: classify stderr, else show its tail. */
635
+ exitFailure(run, signal) {
636
+ const known = classifyCliOutput(run.stderr, run.provider.failureRules, run.cli);
637
+ if (known)
638
+ return known;
639
+ const detail = run.stderr.slice(-8).join('\n').trim();
640
+ return cliFailure('exited', { label: run.cli.label, detail: detail || (signal ? `(${signal})` : '') });
641
+ }
541
642
  noteOutput(run, row) {
542
643
  run.lastOutputAt = Date.now();
543
644
  run.lastCategory = rowCategory(row);
@@ -563,6 +664,7 @@ export class RunSupervisor {
563
664
  if (run.queuedBytes + bytes > 8 * 1024 * 1024) {
564
665
  run.forwardingFailed = true;
565
666
  run.turnError = '实时输出转发积压,请检查设备网络';
667
+ run.turnFailure = 'hostFault';
566
668
  void killProcessTree(run.pid);
567
669
  return;
568
670
  }
@@ -593,6 +695,7 @@ export class RunSupervisor {
593
695
  }).catch(error => {
594
696
  run.forwardingFailed = true;
595
697
  run.turnError = `实时输出转发失败:${errorMessage(error)}`;
698
+ run.turnFailure = 'hostFault';
596
699
  this.logger.warn('chat-events-failed', { runId: run.runId, error: errorMessage(error) });
597
700
  if (this.active.has(run.runId))
598
701
  void killProcessTree(run.pid);
@@ -639,20 +742,30 @@ export class RunSupervisor {
639
742
  await killProcessTree(run.pid);
640
743
  return true;
641
744
  }
745
+ /** Pauses or clears the goal of a running goal run; false when there is none. */
746
+ controlGoal(runId, action) {
747
+ const run = this.active.get(runId);
748
+ if (!run?.provider.controlGoal)
749
+ return false;
750
+ const applied = run.provider.controlGoal(action);
751
+ if (applied)
752
+ run.tail.append(`● 收到${action === 'pause' ? '暂停' : '清除'}目标指令\n`);
753
+ return applied;
754
+ }
642
755
  tail(query, limit, beforeCursor) {
643
756
  const byId = (id) => (id ? this.active.get(id) ?? this.recent.get(id) : undefined);
644
- const byWorkstation = (id) => {
757
+ const bySession = (id) => {
645
758
  if (!id)
646
759
  return undefined;
647
- const live = [...this.active.values()].find((run) => run.workstationId === id);
760
+ const live = [...this.active.values()].find((run) => run.sessionKey === id);
648
761
  if (live)
649
762
  return live;
650
- return [...this.recent.values()].filter((run) => run.workstationId === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
763
+ return [...this.recent.values()].filter((run) => run.sessionKey === id).sort((a, b) => b.finishedAt - a.finishedAt)[0];
651
764
  };
652
765
  const empty = { lines: [], startCursor: 0, nextCursor: 0, oldestCursor: 0, latestCursor: 0, hasMore: false, truncated: false, limited: false, idleMs: undefined };
653
766
  // A request for one run only ever shows that run: a run still preparing
654
767
  // (directory, attachments, session list) reads as running with no output
655
- // yet, never as the workstation's previous run.
768
+ // yet, never as the session's previous run.
656
769
  if (query.runId) {
657
770
  const run = byId(query.runId);
658
771
  if (!run)
@@ -660,7 +773,7 @@ export class RunSupervisor {
660
773
  const read = run.tail.read(beforeCursor === undefined ? { limit } : { limit, beforeCursor });
661
774
  return { ...read, status: this.active.has(run.runId) ? 'running' : 'finished', run_id: run.runId };
662
775
  }
663
- const target = byWorkstation(query.workstationId);
776
+ const target = bySession(query.taskChainId);
664
777
  if (!target)
665
778
  return { ...empty, status: 'idle' };
666
779
  const read = target.tail.read(beforeCursor === undefined ? { limit } : { limit, beforeCursor });
@@ -713,12 +826,23 @@ export class RunSupervisor {
713
826
  }
714
827
  async prepareTaskFiles(payload, signal = AbortSignal.timeout(15 * 60_000), workdir) {
715
828
  if (!payload.workdir)
716
- throw new Error('请先配置设备默认目录或工位工作目录');
829
+ throw new Error('请先配置设备默认目录或会话工作目录');
717
830
  if (!this.reporter.taskFile)
718
831
  throw new Error('任务附件下载未配置');
719
832
  return prepareTaskAttachments(payload, workdir ?? await this.validateWorkdir(payload.workdir), this.reporter.taskFile, AbortSignal.any([signal, AbortSignal.timeout(15 * 60_000)]));
720
833
  }
721
834
  }
835
+ function failedReport(failure, durationMs) {
836
+ return { status: 'failed', error: failure.message, failure_kind: failure.kind, duration_ms: durationMs };
837
+ }
838
+ /**
839
+ * The busy key of a run: one run at a time per session. A task-chain run is
840
+ * keyed by its task_chain_id; a CLI-chat-page run (no task chain) by its
841
+ * chat_session_id; a run with neither falls back to its own run_id.
842
+ */
843
+ function sessionKeyOf(payload) {
844
+ return payload.task_chain_id || payload.chat_session_id || payload.run_id;
845
+ }
722
846
  function errorMessage(error) {
723
847
  return error instanceof Error ? error.message : String(error);
724
848
  }