toc-ocra 0.3.2 → 0.3.4

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 (59) hide show
  1. package/README.md +10 -1
  2. package/dist/cli/cli.mjs +3144 -1727
  3. package/dist/service/agent.mjs +4790 -3373
  4. package/dist/src/acp/ask-user-question.d.ts +99 -0
  5. package/dist/src/acp/ask-user-question.js +333 -0
  6. package/dist/src/acp/ask-user-question.js.map +1 -0
  7. package/dist/src/acp/chat-agents.d.ts +19 -1
  8. package/dist/src/acp/chat-agents.js +7 -3
  9. package/dist/src/acp/chat-agents.js.map +1 -1
  10. package/dist/src/acp/chat-host.d.ts +7 -1
  11. package/dist/src/acp/chat-host.js +11 -0
  12. package/dist/src/acp/chat-host.js.map +1 -1
  13. package/dist/src/acp/chat-session.d.ts +41 -1
  14. package/dist/src/acp/chat-session.js +164 -11
  15. package/dist/src/acp/chat-session.js.map +1 -1
  16. package/dist/src/acp/connection.d.ts +16 -4
  17. package/dist/src/acp/connection.js +25 -11
  18. package/dist/src/acp/connection.js.map +1 -1
  19. package/dist/src/acp/rpc.d.ts +8 -2
  20. package/dist/src/acp/rpc.js +19 -1
  21. package/dist/src/acp/rpc.js.map +1 -1
  22. package/dist/src/acp/transcript.d.ts +55 -0
  23. package/dist/src/acp/transcript.js +67 -14
  24. package/dist/src/acp/transcript.js.map +1 -1
  25. package/dist/src/acp/vendor.d.ts +5 -2
  26. package/dist/src/acp/vendor.js +6 -3
  27. package/dist/src/acp/vendor.js.map +1 -1
  28. package/dist/src/index.js +0 -0
  29. package/dist/src/memory/providers.d.ts +79 -0
  30. package/dist/src/memory/providers.js +130 -0
  31. package/dist/src/memory/providers.js.map +1 -0
  32. package/dist/src/providers/acp/acp-driver.d.ts +2 -0
  33. package/dist/src/providers/acp/acp-driver.js +38 -15
  34. package/dist/src/providers/acp/acp-driver.js.map +1 -1
  35. package/dist/src/providers/cli/claude.d.ts +11 -0
  36. package/dist/src/providers/cli/claude.js +158 -5
  37. package/dist/src/providers/cli/claude.js.map +1 -1
  38. package/dist/src/providers/cli/codex.d.ts +9 -1
  39. package/dist/src/providers/cli/codex.js +114 -8
  40. package/dist/src/providers/cli/codex.js.map +1 -1
  41. package/dist/src/runs/run-supervisor.d.ts +45 -5
  42. package/dist/src/runs/run-supervisor.js +182 -51
  43. package/dist/src/runs/run-supervisor.js.map +1 -1
  44. package/dist/src/runs/run-transcript.d.ts +182 -0
  45. package/dist/src/runs/run-transcript.js +550 -0
  46. package/dist/src/runs/run-transcript.js.map +1 -0
  47. package/dist/src/runtime/agent-runtime.js +34 -3
  48. package/dist/src/runtime/agent-runtime.js.map +1 -1
  49. package/dist/src/types/protocol.d.ts +31 -0
  50. package/dist/src/types/protocol.js +32 -1
  51. package/dist/src/types/protocol.js.map +1 -1
  52. package/package.json +1 -2
  53. package/scripts/installation.cjs +14 -1
  54. /package/{vendor → assets}/acp/claude/LICENSE +0 -0
  55. /package/{vendor → assets}/acp/claude/index.mjs +0 -0
  56. /package/{vendor → assets}/acp/claude/runtime.json +0 -0
  57. /package/{vendor → assets}/acp/codex/LICENSE +0 -0
  58. /package/{vendor → assets}/acp/codex/index.mjs +0 -0
  59. /package/{vendor → assets}/acp/codex/runtime.json +0 -0
@@ -11,6 +11,7 @@ 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';
13
13
  import { RunRecorder } from './run-recorder.js';
14
+ import { RunTranscript, TranscriptStore } from './run-transcript.js';
14
15
  import { currentPlatform } from '../platform/index.js';
15
16
  import { killProcessTree } from './process-tree.js';
16
17
  import { prepareTaskAttachments } from './task-attachments.js';
@@ -18,6 +19,7 @@ import { acpChatSpec } from '../acp/chat-agents.js';
18
19
  import { ChatEventForwarder } from '../acp/chat-forwarder.js';
19
20
  import { AcpChatHost } from '../acp/chat-host.js';
20
21
  import { AcpRuntimeUnavailable, agentPackageVersion } from '../acp/vendor.js';
22
+ import { memoryEnvironment } from '../memory/providers.js';
21
23
  /**
22
24
  * Supervises headless CLI turns. One process per turn:
23
25
  *
@@ -61,50 +63,71 @@ export const STALL_CATEGORY_LABELS = {
61
63
  file: '编辑文件',
62
64
  other: '等待 CLI 输出'
63
65
  };
64
- /** Put before the prompt on CLIs without a plan mode of their own (the turn also runs read-only). */
66
+ /** Put after the prompt on CLIs without a plan mode of their own (the turn also runs read-only), so a message that is a CLI command stays first. */
65
67
  export const PLAN_MODE_PREFIX = '【计划模式】这一轮只做分析和计划:阅读需要的文件,给出具体方案和步骤,不要修改任何文件,也不要执行会改动环境的命令。';
66
- const ACCESS_LABELS = { 'read-only': '只读', acceptEdits: '自动编辑', bypassPermissions: '完全访问' };
68
+ const ACCESS_LABELS = { default: '每次询问', 'read-only': '只读', acceptEdits: '自动编辑', bypassPermissions: '完全访问' };
67
69
  /**
68
70
  * The session's permission level, plan and fast mode for this CLI. The
69
71
  * owner's restricted cap always wins; a level or plan mode the CLI cannot
70
72
  * enforce refuses the turn rather than running with more access than chosen.
73
+ *
74
+ * Chat turns (`chat`): a server that sends `permission_mode` for them answers
75
+ * requests from the phone (`cli_chat.features: permission`), so the level
76
+ * also says what the user is asked (`prompts`), and `default` (每次询问) is
77
+ * a level too. Task chains keep the three auto-answered levels.
71
78
  */
72
- export function resolveTurnSettings(payload, cli) {
79
+ export function resolveTurnSettings(payload, cli, options = {}) {
73
80
  const full = payload.cli_policy?.mode === 'full';
74
81
  const support = cli.runSettings;
75
82
  const notes = [];
76
83
  let access;
84
+ let prompts;
77
85
  const requested = payload.permission_mode?.trim() ?? '';
78
86
  if (requested) {
79
- if (!isAgentAccess(requested))
87
+ const chosen = requested === 'default' ? 'default' : isAgentAccess(requested) ? requested : undefined;
88
+ if (!chosen)
80
89
  return { failure: { kind: 'hostFault', message: `不支持的权限级别:${requested},请升级设备代理` } };
90
+ if (chosen === 'default' && !options.chat)
91
+ return { failure: { kind: 'permissionUnsupported', message: '任务链运行不能等待授权,请把会话权限改为只读、自动编辑或完全访问' } };
81
92
  if (!full) {
82
- if (requested !== 'read-only')
83
- notes.push(`这台电脑的所有者只允许只读,本轮按只读运行(会话选择:${ACCESS_LABELS[requested]})`);
93
+ if (chosen !== 'read-only')
94
+ notes.push(`这台电脑的所有者只允许只读,本轮按只读运行(会话选择:${ACCESS_LABELS[chosen]})`);
84
95
  }
85
- else if (requested !== 'bypassPermissions') {
86
- if (!support?.permissionModes.includes(requested)) {
87
- return { failure: { kind: 'permissionUnsupported', message: `${cli.label} 不支持「${ACCESS_LABELS[requested]}」权限,请改为完全访问或换用其他 CLI` } };
96
+ else {
97
+ if (options.chat)
98
+ prompts = { permissions: chosen === 'default' ? 'all' : chosen === 'acceptEdits' ? 'non-edit' : 'none' };
99
+ // 每次询问 on a driver that cannot ask: nothing the user did not approve runs.
100
+ const level = chosen === 'default' ? 'read-only' : chosen;
101
+ if (level !== 'bypassPermissions') {
102
+ if (!support?.permissionModes.includes(level)) {
103
+ return { failure: { kind: 'permissionUnsupported', message: `${cli.label} 不支持「${ACCESS_LABELS[chosen]}」权限,请改为完全访问或换用其他 CLI` } };
104
+ }
105
+ access = level;
88
106
  }
89
- access = requested;
90
107
  }
91
108
  }
92
109
  const plan = payload.plan_mode === true;
93
110
  if (plan && !support?.plan)
94
111
  return { failure: { kind: 'permissionUnsupported', message: `${cli.label} 不支持计划模式,请关闭计划后再发送` } };
95
112
  const planPrompt = plan && support?.plan === 'prompt';
96
- if (planPrompt && full)
113
+ if (planPrompt && full) {
114
+ // Plan by instruction runs read-only: its policy answers; questions still reach the user.
97
115
  access = 'read-only';
116
+ if (prompts)
117
+ prompts = { permissions: 'none' };
118
+ }
98
119
  const fast = payload.fast_mode === true && support?.fast === true;
99
120
  if (payload.fast_mode === true && !fast)
100
121
  notes.push(`${cli.label} 不支持快速模式,本轮按普通速度运行`);
101
- return { ...(access ? { access } : {}), plan: plan && support?.plan === 'native', planPrompt, fast, notes };
122
+ return { ...(access ? { access } : {}), ...(prompts ? { prompts } : {}), plan: plan && support?.plan === 'native', planPrompt, fast, notes };
102
123
  }
103
124
  /** `本轮设置:计划模式 · 只读 · 快速模式`, when the session chose any of them. */
104
125
  export function turnSettingsLabel(turn, payload) {
105
126
  if (!payload.permission_mode && !payload.plan_mode && !payload.fast_mode)
106
127
  return '';
107
- const level = payload.cli_policy?.mode === 'full' ? ACCESS_LABELS[turn.access ?? 'bypassPermissions'] : '只读';
128
+ const level = payload.cli_policy?.mode !== 'full' ? '只读'
129
+ : turn.prompts?.permissions === 'all' ? ACCESS_LABELS.default
130
+ : ACCESS_LABELS[turn.access ?? 'bypassPermissions'];
108
131
  const parts = [...(turn.plan || turn.planPrompt ? ['计划模式'] : []), level, ...(turn.fast ? ['快速模式'] : [])];
109
132
  return `本轮设置:${parts.join(' · ')}`;
110
133
  }
@@ -128,12 +151,17 @@ export class RunSupervisor {
128
151
  chatRunIds = new Set();
129
152
  preparing = new Map();
130
153
  acpChats;
154
+ transcripts;
155
+ /** Every run's transcript from the start command until the run is remembered as finished. */
156
+ liveTranscripts = new Map();
131
157
  constructor(config, logger, reporter, orphans) {
132
158
  this.config = config;
133
159
  this.logger = logger;
134
160
  this.reporter = reporter;
135
161
  this.orphans = orphans;
136
162
  this.acpChats = new AcpChatHost({ logger, dataDir: config.dataDir, clientVersion: agentPackageVersion(), ...(orphans ? { orphans } : {}) });
163
+ this.transcripts = new TranscriptStore(config.dataDir, logger);
164
+ void this.transcripts.prune();
137
165
  }
138
166
  get activeCount() {
139
167
  return this.active.size + this.acpRuns.size + this.preparing.size;
@@ -185,6 +213,15 @@ export class RunSupervisor {
185
213
  try {
186
214
  await this.startPrepared(payload, controller.signal);
187
215
  }
216
+ catch (error) {
217
+ // A start that threw (not a refusal) leaves no run behind, so no transcript either.
218
+ const transcript = this.liveTranscripts.get(payload.run_id);
219
+ if (transcript && !this.active.has(payload.run_id) && !this.acpRuns.has(payload.run_id)) {
220
+ this.liveTranscripts.delete(payload.run_id);
221
+ this.transcripts.discard(transcript);
222
+ }
223
+ throw error;
224
+ }
188
225
  finally {
189
226
  this.preparing.delete(payload.run_id);
190
227
  }
@@ -197,10 +234,12 @@ export class RunSupervisor {
197
234
  if (payload.chat_session_id)
198
235
  this.chatRunIds.add(payload.run_id);
199
236
  const sessionKey = sessionKeyOf(payload);
237
+ const transcript = this.openTranscript(payload, sessionKey);
200
238
  const refuse = async (reason) => {
201
239
  const failure = typeof reason === 'string' ? { kind: 'hostFault', message: reason } : reason;
202
240
  this.logger.warn('run-refused', { runId: payload.run_id, error: failure.message, kind: failure.kind });
203
- this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'failed', chat: !!payload.chat_session_id });
241
+ await this.settleTranscript(transcript, 'failed');
242
+ this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), transcript, finishedAt: Date.now(), status: 'failed', chat: !!payload.chat_session_id });
204
243
  await this.report(payload.run_id, { status: 'failed', error: failure.message, failure_kind: failure.kind, duration_ms: 0 });
205
244
  };
206
245
  if (this.sessionBusy(sessionKey, payload.run_id)) {
@@ -218,10 +257,18 @@ export class RunSupervisor {
218
257
  if ('failure' in runnable)
219
258
  return refuse(runnable.failure);
220
259
  const cli = runnable.entry;
221
- const turn = resolveTurnSettings(payload, cli);
260
+ const turn = resolveTurnSettings(payload, cli, { chat: Boolean(payload.chat_session_id) });
222
261
  if ('failure' in turn)
223
262
  return refuse(turn.failure);
224
263
  const runSettings = { ...(turn.access ? { access: turn.access } : {}), ...(turn.plan ? { plan: true } : {}), ...(turn.fast ? { fast: true } : {}) };
264
+ // The session's memory identity becomes the CLI's environment (Nowledge Mem: NMEM_AGENT_ID).
265
+ let memoryEnv;
266
+ try {
267
+ memoryEnv = memoryEnvironment(payload.memory);
268
+ }
269
+ catch (error) {
270
+ return refuse({ kind: 'hostFault', message: `${errorMessage(error)},请升级设备代理` });
271
+ }
225
272
  let provider = cli.headless;
226
273
  let workdir;
227
274
  try {
@@ -241,14 +288,16 @@ export class RunSupervisor {
241
288
  }
242
289
  catch (error) {
243
290
  if (signal.aborted) {
244
- this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'cancelled', chat: !!payload.chat_session_id });
291
+ await this.settleTranscript(transcript, 'cancelled');
292
+ this.remember({ runId: payload.run_id, sessionKey, tail: new TerminalTailBuffer(), transcript, finishedAt: Date.now(), status: 'cancelled', chat: !!payload.chat_session_id });
245
293
  await this.report(payload.run_id, { status: 'cancelled', error: '附件准备已取消', duration_ms: 0 });
246
294
  return;
247
295
  }
248
296
  return refuse(`附件下载失败:${errorMessage(error)}`);
249
297
  }
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;
298
+ // Plan mode on CLIs without one: read-only (above) plus this instruction,
299
+ // after the message so a message that is a CLI command stays first.
300
+ const prompt = turn.planPrompt ? `${payload.prompt}\n\n${PLAN_MODE_PREFIX}` : payload.prompt;
252
301
  const request = {
253
302
  permissionMode,
254
303
  ...runSettings,
@@ -262,10 +311,12 @@ export class RunSupervisor {
262
311
  // Live chat runs on the session's long-lived ACP agent when the CLI has one.
263
312
  const acpSpec = acpChatSpec(cli.id);
264
313
  if (acpSpec) {
265
- const outcome = await this.startAcpChat(payload, { spec: acpSpec, cli, sessionKey, workdir, prompt, turn, permissionMode, signal, refuse });
314
+ const outcome = await this.startAcpChat(payload, { spec: acpSpec, cli, sessionKey, workdir, prompt, turn, permissionMode, memoryEnv, signal, refuse, transcript });
266
315
  if (outcome === 'handled')
267
316
  return;
268
- payload = { ...payload, notice: payload.notice ? `${payload.notice};${outcome.fallback}` : outcome.fallback };
317
+ // The per-turn drivers answer every request themselves (每次询问 runs read-only there).
318
+ const fallback = turn.prompts?.permissions === 'all' ? `${outcome.fallback},该驱动不能等待授权,按只读运行` : outcome.fallback;
319
+ payload = { ...payload, notice: payload.notice ? `${payload.notice};${fallback}` : fallback };
269
320
  }
270
321
  try {
271
322
  if (!this.reporter.chatEvents)
@@ -357,7 +408,7 @@ export class RunSupervisor {
357
408
  try {
358
409
  child = spawn(launch.executable, launch.args, {
359
410
  cwd: workdir,
360
- env: launch.env,
411
+ env: Object.keys(memoryEnv).length ? { ...launch.env, ...memoryEnv } : launch.env,
361
412
  detached: currentPlatform.runsInOwnProcessGroup,
362
413
  shell: false,
363
414
  windowsHide: true,
@@ -392,6 +443,7 @@ export class RunSupervisor {
392
443
  killedAfterCompletion: false,
393
444
  timedOut: false,
394
445
  tail: new TerminalTailBuffer(),
446
+ transcript,
395
447
  timers: [],
396
448
  // A goal run waits between turns while the CLI decides; no stall check.
397
449
  ...(payload.stall_policy && !payload.chat_session_id && !payload.goal
@@ -401,6 +453,8 @@ export class RunSupervisor {
401
453
  lastLine: '',
402
454
  lastOutputAt: Date.now()
403
455
  };
456
+ transcript.agentType = provider.id;
457
+ transcript.startedAt = run.startedAt;
404
458
  if (provider.createRunParser) {
405
459
  run.stream = provider.createRunParser({
406
460
  workdir, sessionId, startedAt: run.startedAt,
@@ -420,15 +474,17 @@ export class RunSupervisor {
420
474
  if (run.pid > 1)
421
475
  this.orphans?.add({ runId: run.runId, pid: run.pid, executable: launch.executable, startedAt: run.startedAt });
422
476
  if (payload.notice)
423
- run.tail.append(`● ${sanitizeTerminalLine(payload.notice)}\n`);
477
+ this.log(run, `● ${sanitizeTerminalLine(payload.notice)}\n`);
424
478
  if (sessionNote)
425
- run.tail.append(sessionNote);
479
+ this.log(run, sessionNote);
426
480
  for (const note of turn.notes)
427
- run.tail.append(`● ${note}\n`);
428
- run.tail.append(`● ${provider.id} 启动于 ${workdir}${sessionId ? `(继续会话 ${sessionId})` : ''}\n`);
481
+ this.log(run, `● ${note}\n`);
482
+ this.log(run, `● ${provider.id} 启动于 ${workdir}${sessionId ? `(继续会话 ${sessionId})` : ''}\n`);
429
483
  const settingsRow = turnSettingsLabel(turn, payload);
430
484
  if (settingsRow)
431
- run.tail.append(`● ${settingsRow}\n`);
485
+ this.log(run, `● ${settingsRow}\n`);
486
+ if (payload.memory)
487
+ this.log(run, `● 记忆身份:${payload.memory.memory_id}(${payload.memory.provider_id})\n`);
432
488
  this.logger.info('run-started', { runId: run.runId, agentType: provider.id, pid: run.pid, resume: Boolean(sessionId) });
433
489
  let spawnError = '';
434
490
  child.stdin?.on('error', () => undefined);
@@ -465,7 +521,7 @@ export class RunSupervisor {
465
521
  for (const row of provider.stderrDisplay ? provider.stderrDisplay(line) : [clean]) {
466
522
  const shown = sanitizeTerminalLine(row);
467
523
  if (shown.trim()) {
468
- run.tail.append(`${shown}\n`);
524
+ this.log(run, `${shown}\n`);
469
525
  this.noteOutput(run, shown);
470
526
  }
471
527
  }
@@ -519,7 +575,7 @@ export class RunSupervisor {
519
575
  if (this.config.maxRunSeconds > 0) {
520
576
  run.timers.push(setTimeout(() => {
521
577
  run.timedOut = true;
522
- run.tail.append(`✗ 超过最长运行时间 ${this.config.maxRunSeconds} 秒,已终止\n`);
578
+ this.log(run, `✗ 超过最长运行时间 ${this.config.maxRunSeconds} 秒,已终止\n`);
523
579
  void killProcessTree(run.pid);
524
580
  }, this.config.maxRunSeconds * 1_000));
525
581
  }
@@ -549,9 +605,10 @@ export class RunSupervisor {
549
605
  * the per-turn chat driver should answer instead.
550
606
  */
551
607
  async startAcpChat(payload, context) {
552
- const { spec, cli, sessionKey, workdir, turn, signal, refuse } = context;
608
+ const { spec, cli, sessionKey, workdir, turn, memoryEnv, signal, refuse, transcript } = context;
553
609
  const runId = payload.run_id;
554
- const access = accessLevel({ permissionMode: context.permissionMode, ...(turn.access ? { access: turn.access } : {}) });
610
+ // 每次询问: the agent's asking mode (Claude `default`, Codex `read-only`, Kiro / Gemini without trust-all).
611
+ const access = turn.prompts?.permissions === 'all' ? 'default' : accessLevel({ permissionMode: context.permissionMode, ...(turn.access ? { access: turn.access } : {}) });
555
612
  let launch;
556
613
  let attachments;
557
614
  try {
@@ -561,11 +618,19 @@ export class RunSupervisor {
561
618
  throw new Error('消息内容为空');
562
619
  attachments = await this.prepareChatAttachments(payload);
563
620
  launch = await this.acpChats.prepare(spec, { access, reasoningEffort: payload.reasoning_effort, model: payload.model, workdir });
621
+ // A running process's environment cannot change: another identity is another launch.
622
+ if (Object.keys(memoryEnv).length) {
623
+ launch = {
624
+ launch: { ...launch.launch, env: { ...launch.launch.env, ...memoryEnv } },
625
+ fingerprint: `${launch.fingerprint}|memory:${payload.memory?.provider_id}/${payload.memory?.memory_id}`
626
+ };
627
+ }
564
628
  signal.throwIfAborted();
565
629
  }
566
630
  catch (error) {
567
631
  if (signal.aborted) {
568
- this.remember({ runId, sessionKey, tail: new TerminalTailBuffer(), finishedAt: Date.now(), status: 'cancelled', chat: true });
632
+ await this.settleTranscript(transcript, 'cancelled');
633
+ this.remember({ runId, sessionKey, tail: new TerminalTailBuffer(), transcript, finishedAt: Date.now(), status: 'cancelled', chat: true });
569
634
  await this.report(runId, { status: 'cancelled', duration_ms: 0 });
570
635
  return 'handled';
571
636
  }
@@ -588,7 +653,9 @@ export class RunSupervisor {
588
653
  return 'handled';
589
654
  }
590
655
  const tail = new TerminalTailBuffer();
591
- const run = { runId, sessionKey, startedAt: Date.now(), tail };
656
+ const run = { runId, sessionKey, startedAt: Date.now(), tail, transcript };
657
+ transcript.agentType = cli.id;
658
+ transcript.startedAt = run.startedAt;
592
659
  this.acpRuns.set(runId, run);
593
660
  this.preparing.delete(runId);
594
661
  this.unreported.add(runId);
@@ -596,6 +663,8 @@ export class RunSupervisor {
596
663
  const settingsRow = turnSettingsLabel(turn, payload);
597
664
  if (settingsRow)
598
665
  notes.push(settingsRow);
666
+ if (payload.memory)
667
+ notes.push(`记忆身份:${payload.memory.memory_id}(${payload.memory.provider_id})`);
599
668
  this.logger.info('run-started', { runId, agentType: cli.id, driver: 'acp', resume: Boolean(payload.session_id) });
600
669
  let forwardingError = '';
601
670
  const forwarder = new ChatEventForwarder(runId, (id, events) => this.reporter.chatEvents(id, events), (message) => {
@@ -615,11 +684,16 @@ export class RunSupervisor {
615
684
  plan: turn.plan,
616
685
  fast: turn.fast,
617
686
  workdir,
618
- notes
687
+ notes,
688
+ ...(turn.prompts ? { prompts: turn.prompts } : {})
619
689
  }, {
620
- events: (events) => forwarder.push(events),
690
+ events: (events) => {
691
+ forwarder.push(events);
692
+ for (const event of events)
693
+ transcript.fold(sanitizeChatEvent(event));
694
+ },
621
695
  rows: (rows) => { for (const row of rows)
622
- tail.append(`${sanitizeTerminalLine(row)}\n`); },
696
+ this.log(run, `${sanitizeTerminalLine(row)}\n`); },
623
697
  started: (pid, sessionId) => {
624
698
  if (reported.pid === pid && reported.sessionId === sessionId)
625
699
  return;
@@ -645,8 +719,9 @@ export class RunSupervisor {
645
719
  report.session_id = result.sessionId;
646
720
  if (result.finalMessage)
647
721
  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 });
722
+ this.log(run, `● 本轮结束:${report.status}\n`);
723
+ await this.settleTranscript(transcript, report.status);
724
+ this.remember({ runId, sessionKey, tail, transcript, finishedAt: Date.now(), status: report.status, chat: true });
650
725
  this.logger.info('run-finished', { runId, status: report.status, driver: 'acp', durationMs });
651
726
  await this.report(runId, report);
652
727
  return 'handled';
@@ -654,10 +729,25 @@ export class RunSupervisor {
654
729
  /** Delivers a user message into a running chat turn (`chat.run.steer`). */
655
730
  async steer(runId, steerId, prompt) {
656
731
  const outcome = await this.acpChats.steer(runId, steerId, prompt, this.preparing.has(runId));
657
- this.acpRuns.get(runId)?.tail.append(`● 收到插入消息(${outcome})\n`);
732
+ const acp = this.acpRuns.get(runId);
733
+ if (acp)
734
+ this.log(acp, `● 收到插入消息(${outcome})\n`);
658
735
  this.logger.info('run-steer', { runId, steerId, outcome });
659
736
  return outcome;
660
737
  }
738
+ /**
739
+ * The user's answer to a request waiting on a running chat turn
740
+ * (`chat.run.permission`). Runs still preparing, task-chain runs and
741
+ * per-turn chat drivers have no open requests: `not-found`.
742
+ */
743
+ answerPermission(runId, requestId, outcome) {
744
+ const answer = this.acpChats.answerPermission(runId, requestId, outcome);
745
+ const acp = this.acpRuns.get(runId);
746
+ if (acp && answer.row)
747
+ this.log(acp, `● ${answer.row}\n`);
748
+ this.logger.info('run-permission', { runId, requestId, outcome: answer.outcome });
749
+ return answer.outcome;
750
+ }
661
751
  onStdout(run, rawLine) {
662
752
  run.recorder?.write({ stream: 'stdout', data: `${rawLine}\n` });
663
753
  // JSON-RPC replies can contain an entire restored transcript. Redacting
@@ -666,16 +756,20 @@ export class RunSupervisor {
666
756
  this.applyParsed(run, run.parse(rawLine), rawLine);
667
757
  }
668
758
  applyParsed(run, parsed, rawLine) {
759
+ const events = parsed.chatEvents?.length ? parsed.chatEvents.map((event) => sanitizeChatEvent(event)) : [];
760
+ // Every run keeps its items (task-chain runs too); only chat runs forward them.
761
+ for (const event of events)
762
+ run.transcript.fold(event);
669
763
  if (run.chat && !run.forwardingFailed) {
670
- for (const event of parsed.chatEvents ?? [])
671
- this.queueChatEvent(run, sanitizeChatEvent(event));
764
+ for (const event of events)
765
+ this.queueChatEvent(run, event);
672
766
  }
673
767
  // A protocol session (app-server, ACP) is ready once it names its session.
674
768
  if (parsed.sessionId)
675
769
  run.chatReady = true;
676
770
  for (const row of parsed.display) {
677
771
  const shown = sanitizeTerminalLine(row);
678
- run.tail.append(`${shown}\n`);
772
+ this.log(run, `${shown}\n`);
679
773
  if (shown.trim())
680
774
  this.noteOutput(run, shown);
681
775
  }
@@ -717,7 +811,7 @@ export class RunSupervisor {
717
811
  if (!this.active.has(run.runId))
718
812
  return;
719
813
  run.killedAfterCompletion = true;
720
- run.tail.append('● 本轮已完成但进程未退出,已结束进程\n');
814
+ this.log(run, '● 本轮已完成但进程未退出,已结束进程\n');
721
815
  void killProcessTree(run.pid);
722
816
  }, COMPLETION_EXIT_GRACE_MS));
723
817
  }
@@ -757,7 +851,7 @@ export class RunSupervisor {
757
851
  run.turnError = sanitizeTerminalLine(hidden.message);
758
852
  run.turnFailure = hidden.kind;
759
853
  if (hidden.rule.showInLog)
760
- run.tail.append(`✗ ${run.turnError}\n`);
854
+ this.log(run, `✗ ${run.turnError}\n`);
761
855
  }
762
856
  }
763
857
  // A fresh turn of a CLI that never prints its session id adopts the chat
@@ -769,14 +863,14 @@ export class RunSupervisor {
769
863
  after = await run.provider.listSessions(run.workdir);
770
864
  }
771
865
  catch (error) {
772
- run.tail.append(`● 无法读取 ${run.agentType} 的已保存会话(${errorMessage(error)}),本轮会话未能记录,下轮将开始新会话\n`);
866
+ this.log(run, `● 无法读取 ${run.agentType} 的已保存会话(${errorMessage(error)}),本轮会话未能记录,下轮将开始新会话\n`);
773
867
  this.logger.warn('list-sessions-failed', { runId: run.runId, agentType: run.agentType, error: errorMessage(error) });
774
868
  }
775
869
  const created = after ? pickCreatedSession(run.sessionsBefore, after, run.prompt) : undefined;
776
870
  if (created)
777
871
  run.sessionId = created;
778
872
  else if (after?.some((session) => !run.sessionsBefore.has(session.id))) {
779
- run.tail.append('● 同目录有其他会话同时新建,无法确认本轮会话,下轮将开始新会话\n');
873
+ this.log(run, '● 同目录有其他会话同时新建,无法确认本轮会话,下轮将开始新会话\n');
780
874
  this.logger.warn('session-ambiguous', { runId: run.runId, agentType: run.agentType });
781
875
  }
782
876
  }
@@ -813,9 +907,10 @@ export class RunSupervisor {
813
907
  report.session_id = run.sessionId;
814
908
  if (run.finalMessage)
815
909
  report.final_message = run.finalMessage;
816
- run.tail.append(`● 进程已退出:${report.status}${code !== null ? `(exit ${code})` : ''}\n`);
910
+ this.log(run, `● 进程已退出:${report.status}${code !== null ? `(exit ${code})` : ''}\n`);
817
911
  run.recorder?.write({ result: { ...report, duration_ms: 0 }, log: run.tail.read({ limit: 2_000 }).lines });
818
- this.remember({ runId: run.runId, sessionKey: run.sessionKey, tail: run.tail, finishedAt: Date.now(), status: report.status, chat: !!run.chat });
912
+ await this.settleTranscript(run.transcript, report.status, code);
913
+ this.remember({ runId: run.runId, sessionKey: run.sessionKey, tail: run.tail, transcript: run.transcript, finishedAt: Date.now(), status: report.status, chat: !!run.chat });
819
914
  this.logger.info('run-finished', { runId: run.runId, status: report.status, code, durationMs });
820
915
  await this.report(run.runId, report);
821
916
  }
@@ -852,7 +947,7 @@ export class RunSupervisor {
852
947
  if (idle < limit)
853
948
  return;
854
949
  run.stalled = { category: run.lastCategory, idle_seconds: idle, limit_seconds: limit, last_line: run.lastLine };
855
- run.tail.append(`✗ 已 ${formatDuration(idle)}没有新输出(卡在:${STALL_CATEGORY_LABELS[run.lastCategory]}${run.lastLine ? `(${run.lastLine})` : ''}),判定为卡住,正在停止进程\n`);
950
+ this.log(run, `✗ 已 ${formatDuration(idle)}没有新输出(卡在:${STALL_CATEGORY_LABELS[run.lastCategory]}${run.lastLine ? `(${run.lastLine})` : ''}),判定为卡住,正在停止进程\n`);
856
951
  this.logger.warn('run-stalled', { runId: run.runId, category: run.lastCategory, idleSeconds: idle, limitSeconds: limit });
857
952
  void killProcessTree(run.pid);
858
953
  }
@@ -926,7 +1021,7 @@ export class RunSupervisor {
926
1021
  async cancel(runId) {
927
1022
  const acp = this.acpRuns.get(runId);
928
1023
  if (acp) {
929
- acp.tail.append('● 收到停止指令\n');
1024
+ this.log(acp, '● 收到停止指令\n');
930
1025
  this.logger.info('run-cancel', { runId, driver: 'acp' });
931
1026
  return this.acpChats.cancel(runId);
932
1027
  }
@@ -940,7 +1035,7 @@ export class RunSupervisor {
940
1035
  return false;
941
1036
  }
942
1037
  run.cancelRequested = true;
943
- run.tail.append('● 收到停止指令,正在结束进程树\n');
1038
+ this.log(run, '● 收到停止指令,正在结束进程树\n');
944
1039
  this.logger.info('run-cancel', { runId, pid: run.pid });
945
1040
  await killProcessTree(run.pid);
946
1041
  return true;
@@ -952,7 +1047,7 @@ export class RunSupervisor {
952
1047
  return false;
953
1048
  const applied = run.provider.controlGoal(action);
954
1049
  if (applied)
955
- run.tail.append(`● 收到${action === 'pause' ? '暂停' : '清除'}目标指令\n`);
1050
+ this.log(run, `● 收到${action === 'pause' ? '暂停' : '清除'}目标指令\n`);
956
1051
  return applied;
957
1052
  }
958
1053
  tail(query, limit, beforeCursor) {
@@ -983,6 +1078,18 @@ export class RunSupervisor {
983
1078
  const read = target.tail.read(beforeCursor === undefined ? { limit } : { limit, beforeCursor });
984
1079
  return { ...read, status: running(target.runId) ? 'running' : 'finished', run_id: target.runId };
985
1080
  }
1081
+ /**
1082
+ * A run's 执行过程 (`run.transcript`): structured items and run-log rows,
1083
+ * from memory while the run is running or recently finished, then from
1084
+ * this device's transcript files.
1085
+ */
1086
+ async transcript(runId, options = {}) {
1087
+ const live = this.liveTranscripts.get(runId) ?? this.recent.get(runId)?.transcript;
1088
+ if (live)
1089
+ return live.read(options);
1090
+ const stored = await this.transcripts.load(runId);
1091
+ return stored ? stored.read(options) : { run_id: runId, found: false };
1092
+ }
986
1093
  async disposeAll() {
987
1094
  for (const entry of this.preparing.values())
988
1095
  entry.controller.abort();
@@ -993,8 +1100,32 @@ export class RunSupervisor {
993
1100
  }),
994
1101
  this.acpChats.disposeAll()
995
1102
  ]);
1103
+ // Runs still finishing keep what they had so far on disk.
1104
+ await this.transcripts.flushAll();
1105
+ }
1106
+ /** Run-log text for the live tail and the run's transcript. */
1107
+ log(run, text) {
1108
+ run.tail.append(text);
1109
+ run.transcript.appendLog(text);
1110
+ }
1111
+ /** A transcript for a run being started; a run started again under its id replaces the old one. */
1112
+ openTranscript(payload, sessionKey) {
1113
+ const previous = this.liveTranscripts.get(payload.run_id);
1114
+ if (previous)
1115
+ this.transcripts.discard(previous);
1116
+ const transcript = new RunTranscript({ runId: payload.run_id, sessionKey, agentType: payload.agent_type, chat: Boolean(payload.chat_session_id) });
1117
+ this.liveTranscripts.set(payload.run_id, transcript);
1118
+ this.transcripts.track(transcript);
1119
+ return transcript;
1120
+ }
1121
+ /** The run's final status, written to disk before the run is remembered (disk errors only log). */
1122
+ async settleTranscript(transcript, status, exitCode = null) {
1123
+ transcript.finish(status, exitCode);
1124
+ await this.transcripts.flush(transcript);
996
1125
  }
997
1126
  remember(run) {
1127
+ if (this.liveTranscripts.get(run.runId) === run.transcript)
1128
+ this.liveTranscripts.delete(run.runId);
998
1129
  this.recent.set(run.runId, run);
999
1130
  const cutoff = Date.now() - RECENT_RUN_TTL_MS;
1000
1131
  for (const [id, item] of this.recent) {