pi-subagent-manager 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -68,11 +68,11 @@ They inherit your current model until you set preferences. Details: [docs/defaul
68
68
  | ---------------- | ------------------------------------------------------ |
69
69
  | `/agents` | Settings (mode, limits, model picking, tool filtering) |
70
70
  | `/agents types` | Agent-type browser and editor |
71
- | `/agents tree` | Live tree of all agents (`/agents status` is an alias) |
71
+ | `/agents tree` | Fullscreen tree and read-only live watcher (`/agents status` is an alias) |
72
72
  | `/agents import` | Import agents from other subagent extensions |
73
73
  | `/agents reload` | Reload definitions and settings |
74
74
 
75
- A compact live **Agents** tree also sits above the input box.
75
+ A compact live **Agents** tree also sits above the input box. In the fullscreen tree, **Enter** watches an agent, **Escape** returns, and **i** opens existing thread actions. Optional exhausted-Down editor entry is experimental: set `PI_SUBAGENT_NAVIGATION_EDITOR=1`. See [live navigation](docs/tools-and-ui.md#live-agent-navigation-read-only) for controls and compatibility.
76
76
 
77
77
  ## Docs
78
78
 
@@ -49,16 +49,48 @@ Then `agent_wait` or `agent_status` on `/root/controller-security-research`.
49
49
  | ↑↓ | Select |
50
50
  | ←→ | Collapse / expand |
51
51
  | PgUp / PgDn | Scroll |
52
- | Enter | Inspect thread |
53
- | Esc | Close |
52
+ | Enter | Watch thread; Main returns to the editor |
53
+ | i | Existing actions: steer, stop, output, transcript |
54
+ | Esc | Watcher → saved tree → Main |
55
+ | Ctrl+Q | Return directly to Main |
54
56
 
55
- Refreshes every second and keeps your selection.
57
+ Refreshes every second and keeps your selection, collapse state and scroll position.
58
+
59
+ ### Live agent navigation (read-only)
60
+
61
+ The fullscreen watcher shows steer and agent messages in full, including the in-progress assistant reply. Tool calls, results, and other metadata show their name/status and only the first three wrapped lines of each arguments/output preview, followed by `...` when more is hidden. Use **i → Transcript** from the tree for retained tool details. Thinking is initially hidden (**t** toggles it). It never sends a prompt, switches sessions, or changes model/tool/resource ownership. Inherited context is initially collapsed (**c** toggles it). Unsupported/custom content and images use safe text placeholders rather than native rich rendering. Legacy sessions without reliable inherited-prefix metadata show their whole transcript.
62
+
63
+ - **Up/Down, PageUp/PageDown, Home** scroll and pause following.
64
+ - **End** or **l** resumes following the live tail. Scroll/follow state is remembered per agent.
65
+ - **r** retries an unavailable observation without starting a turn. Starting threads are watchable; stopped/completed threads remain readable.
66
+ - Frames are sanitized, viewport-bounded and coalesced during bursts. Exit, root replacement and shutdown release observers/timers. Streaming deltas never enter persisted thread events.
67
+
68
+ #### Experimental exhausted-Down entry
69
+
70
+ Set `PI_SUBAGENT_NAVIGATION_EDITOR=1` before starting Pi to open the tree when focused physical **Down** has exhausted native history/cursor movement at the end of the draft. Native editing runs first; autocomplete, jumps, paste, configured shortcuts, duplicate history entries and changed drafts do not count as exhausted boundaries. Navigating preserves the main draft/cursor and does not require the root to be idle.
71
+
72
+ The editor adapter is **opt-in** pending the full real-terminal acceptance matrix. Unset the variable or use `PI_SUBAGENT_NAVIGATION_EDITOR=0` to leave the editor slot untouched; command entry still works. Pi has one custom-editor slot: installation is skipped if another factory owns it or an existing draft is nonempty, since the host cannot transfer cursor/undo/expanded-paste state. Load order can still let a later editor replace ours. Initial startup uses Pi's history hydration; replacement installations seed history once. Session-tree rebuilds keep the existing editor instance.
73
+
74
+ While navigation is open, the host fullscreen search shortcut is temporarily disabled through public keybindings to avoid stacking a second host overlay. The prior binding owner is restored only if no other extension replaced it. **Known host limitation:** if an unrelated extension stacks another overlay above navigation, Pi's custom-UI completion can close the newer overlay instead. Avoid concurrent extension-owned overlays; a host identity-targeted completion API is needed to remove this limitation. No private host access or unsupported overlay-lifecycle workaround is used.
75
+
76
+ Run `python3 scripts/live-agent-navigation-smoke.py` after `npm install` for credential-free, offline POSIX PTY checks in regular/fullscreen mode (entry, root return, draft restoration, resize and host-search suppression). No model prompts are submitted. Broader manual acceptance (concurrent live turns, autocomplete/paste/undo interactions, remapped shortcuts and rich custom content) is still required before making the editor gesture default.
56
77
 
57
78
  ## Agents widget
58
79
 
59
- A compact tree above the input editor, at most ten lines.
80
+ A compact tree above the input editor, at most twelve lines including two help lines.
60
81
 
61
82
  - Each row: colored type pill, path, state, task, active time, input `↑` / output `↓` tokens.
62
83
  - A second, indented line shows latest activity.
63
84
  - Active branches are shown first; overflow is counted, not listed.
64
85
  - Time freezes while paused and resumes on continue.
86
+ - The footer always shows tree navigation and the default interrupt keys, including when agents overflow.
87
+
88
+ ### Interrupts and stopping agents
89
+
90
+ With the main input focused (default keybindings):
91
+
92
+ - **Esc** aborts the main turn (including a pending `agent_wait` or foreground spawn wait), **not the subagents**. Already-started subagents keep running.
93
+ - **Ctrl+C** clears the input; it does not stop the main turn or subagents.
94
+ - **Ctrl+C twice quickly** (within 500 ms) exits Pi. Session shutdown cooperatively stops all agents, retaining their sessions.
95
+
96
+ Inside the tree/watcher, **Esc** returns to the previous view without stopping an agent. To stop one subtree without exiting Pi, open **`/agents tree`**, select an agent, press **i**, and choose **Stop**. This stops that agent and its working descendants; other branches continue. Cancellation is cooperative, not a guarantee of killing external processes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
package/src/index.ts CHANGED
@@ -7,7 +7,8 @@ import { IMPORT_REQUEST_PREFIX, markImportOffered, offerAgentImport } from "./pr
7
7
  import { ThreadManager } from "./orch/manager.ts";
8
8
  import { loadManagerSettings } from "./prefs/settings.ts";
9
9
  import { configureAgents } from "./ui/settings-ui.ts";
10
- import { showAgentStatus, showAgentTree } from "./ui/status-ui.ts";
10
+ import { AgentNavigationController, showAgentStatus } from "./ui/status-ui.ts";
11
+ import { AgentNavigationEditor } from "./ui/agent-navigation-editor.ts";
11
12
  import { createDriverFactory } from "./orch/runtime.ts";
12
13
  import { createInheritedToolSource } from "./orch/inherited-tools.ts";
13
14
  import { subagentPrompt } from "./orch/prompt.ts";
@@ -47,6 +48,49 @@ export default function piSubagent(pi: ExtensionAPI): void {
47
48
  return loaded.diagnostics;
48
49
  };
49
50
  let generation = 0;
51
+ let navigation = new AgentNavigationController();
52
+ let navigationEditor: AgentNavigationEditor | undefined;
53
+ let navigationEditorFactory: Parameters<ExtensionContext["ui"]["setEditorComponent"]>[0];
54
+ let navigationGeneration = 0;
55
+ const closeNavigation = (disposeEditor = false) => {
56
+ navigationGeneration++;
57
+ navigation.close();
58
+ if (disposeEditor) {
59
+ navigationEditor?.dispose();
60
+ navigationEditor = undefined;
61
+ }
62
+ };
63
+ const installNavigationEditor = (ctx: ExtensionContext, seedHistory: boolean) => {
64
+ // Pi has one custom-editor slot: integrations owning it can opt out explicitly.
65
+ if (!ctx.hasUI || ctx.mode !== "tui" || !ctx.ui.setEditorComponent ||
66
+ process.env.PI_SUBAGENT_NAVIGATION_EDITOR !== "1") return;
67
+ const existingFactory = ctx.ui.getEditorComponent?.();
68
+ if (existingFactory && existingFactory !== navigationEditorFactory) return;
69
+ // The host only transfers raw text, not cursor/undo/expanded-paste state.
70
+ if (ctx.ui.getEditorText?.()) return;
71
+ const history = buildSessionContext(ctx.sessionManager.getBranch()).messages.flatMap((message) => {
72
+ if (message.role !== "user") return [];
73
+ const content = message.content;
74
+ return [typeof content === "string" ? content : content
75
+ .filter((block) => block.type === "text").map((block) => block.text).join("")];
76
+ });
77
+ navigationEditorFactory = (tui, theme, keys) => {
78
+ const editor = new AgentNavigationEditor(tui, theme, keys, {
79
+ // Initial startup hydrates after session_start; replacement editors do not.
80
+ initialHistory: seedHistory ? history : undefined,
81
+ generation: () => navigationGeneration,
82
+ canOpen: () => manager !== undefined && context?.mode === "tui" &&
83
+ limits.subagentMode !== "off" && !navigation.isOpen,
84
+ openTree: () => manager && context
85
+ ? navigation.open(context, manager.scope("/root")) : undefined,
86
+ onError: (error) => context?.ui.notify(
87
+ error instanceof Error ? error.message : String(error), "error"),
88
+ });
89
+ navigationEditor = editor;
90
+ return editor;
91
+ };
92
+ ctx.ui.setEditorComponent(navigationEditorFactory);
93
+ };
50
94
  let persistenceSignature = "";
51
95
  let migrationRequested = false;
52
96
  let importInProgress = false;
@@ -213,8 +257,10 @@ export default function piSubagent(pi: ExtensionAPI): void {
213
257
  };
214
258
  });
215
259
 
216
- const attachSession = async (ctx: ExtensionContext) => {
260
+ const attachSession = async (ctx: ExtensionContext, installEditor = false, seedHistory = true) => {
217
261
  const token = ++generation;
262
+ closeNavigation(installEditor);
263
+ navigation = new AgentNavigationController();
218
264
  // session_start already belongs to the replacement session: never append the old registry here.
219
265
  if (manager) await manager.shutdown();
220
266
  inheritedTools.reset();
@@ -246,6 +292,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
246
292
  },
247
293
  });
248
294
  manager = instance;
295
+ if (installEditor) installNavigationEditor(ctx, seedHistory);
249
296
  const entries = ctx.sessionManager.getBranch();
250
297
  const entry = [...entries]
251
298
  .reverse()
@@ -274,12 +321,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
274
321
  if (limits.subagentMode !== "off" && diagnostics.length)
275
322
  ctx.ui.notify(diagnostics.join("\n"), "warning");
276
323
  };
277
- pi.on("session_start", async (_event, ctx) => {
278
- await attachSession(ctx);
324
+ pi.on("session_start", async (event, ctx) => {
325
+ await attachSession(ctx, true, event.reason !== "startup");
279
326
  if (limits.subagentMode !== "off") await importAgents(ctx, true);
280
327
  });
281
328
  pi.on("session_tree", async (_event, ctx) => attachSession(ctx));
282
329
  const stopWorkingThreads = async () => {
330
+ closeNavigation();
283
331
  if (!manager) return;
284
332
  for (const thread of manager.list()) {
285
333
  const state = manager.get(thread.path).state;
@@ -292,6 +340,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
292
340
  pi.on("session_before_fork", stopWorkingThreads);
293
341
  pi.on("session_shutdown", async () => {
294
342
  generation++;
343
+ closeNavigation(true);
295
344
  await manager?.shutdown();
296
345
  persist();
297
346
  if (context?.hasUI) context.ui.setWidget("pi-subagent", undefined);
@@ -357,7 +406,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
357
406
  } else if (command === "status") {
358
407
  await showAgentStatus(ctx, requireManager().scope("/root"));
359
408
  } else if (command === "tree") {
360
- await showAgentTree(ctx, requireManager().scope("/root"), rest.join(" ") || undefined);
409
+ await navigation.open(ctx, requireManager().scope("/root"), rest.join(" ") || undefined);
361
410
  } else
362
411
  ctx.ui.notify(
363
412
  "Usage: /agents [tree [path] | status | settings | types | import | reload]",
@@ -8,7 +8,11 @@ import type {
8
8
  SavedThreadView,
9
9
  ThreadService,
10
10
  ThreadView,
11
+ TranscriptListener,
12
+ TranscriptObservation,
13
+ TranscriptSnapshot,
11
14
  } from "../types.ts";
15
+ import { immutableTranscriptValue } from "./transcript.ts";
12
16
  import { canonicalPath, inheritContext, isDescendant, parentPath } from "./paths.ts";
13
17
  import { DEFAULT_MANAGER_SETTINGS, type ManagerSettings } from "../prefs/settings.ts";
14
18
 
@@ -31,6 +35,12 @@ interface Record {
31
35
  liveOutputTokens?: number;
32
36
  pauseRequested: boolean;
33
37
  stopRequested: boolean;
38
+ observationRevision?: number;
39
+ driverGeneration?: number;
40
+ transcriptSource?: TranscriptSnapshot;
41
+ transcriptListeners?: Set<TranscriptListener>;
42
+ detachTranscript?: () => void;
43
+ observationError?: string;
34
44
  }
35
45
  const active = (view: Pick<ThreadView, "state">) =>
36
46
  view.state === "starting" || view.state === "running";
@@ -85,6 +95,7 @@ export class ThreadManager {
85
95
  get: (path) => this.get(path, caller),
86
96
  output: (path) => this.output(path, caller),
87
97
  transcript: (path) => this.transcript(caller, path),
98
+ observeTranscript: (path, listener) => this.observeTranscript(caller, path, listener),
88
99
  spawn: (args, signal) => this.spawn(caller, args, signal),
89
100
  steer: (path, message) => this.steer(caller, path, message),
90
101
  wait: (path, timeoutMs, signal) => this.wait(caller, path, timeoutMs, signal),
@@ -389,6 +400,43 @@ export class ThreadManager {
389
400
  const driver = await this.ensureDriver(this.record(path), true);
390
401
  return JSON.stringify(driver.snapshot(), null, 2);
391
402
  }
403
+ async observeTranscript(
404
+ caller: string,
405
+ path: string,
406
+ listener: TranscriptListener,
407
+ ): Promise<TranscriptObservation> {
408
+ this.assertLive();
409
+ path = canonicalPath(path, caller);
410
+ this.assertAccess(caller, path, true);
411
+ if (path === "/root") throw new Error("Main is not a child transcript observation target");
412
+ const record = this.record(path);
413
+ // Idle/restored history may be lazily loaded, but attachment never prompts/resumes a turn.
414
+ if (!active(record.view)) await this.ensureDriver(record, true);
415
+ this.assertLive();
416
+ const listeners = (record.transcriptListeners ??= new Set());
417
+ const registered: TranscriptListener = (snapshot) => listener(snapshot);
418
+ listeners.add(registered);
419
+ if (record.driver) this.attachTranscript(record, record.driver);
420
+ else {
421
+ // A starting child gets a placeholder immediately; existing startup supplies the live source.
422
+ void this.ensureDriver(record, true).catch((error) => {
423
+ if (this.disposed || !listeners.has(registered)) return;
424
+ record.observationError = errorText(error);
425
+ this.publishTranscript(record);
426
+ });
427
+ }
428
+ return {
429
+ snapshot: this.transcriptSnapshot(record),
430
+ unsubscribe: () => {
431
+ listeners.delete(registered);
432
+ if (!listeners.size) {
433
+ record.detachTranscript?.();
434
+ record.detachTranscript = undefined;
435
+ record.transcriptSource = undefined;
436
+ }
437
+ },
438
+ };
439
+ }
392
440
  async deliver(path: string, content: string): Promise<void> {
393
441
  // Restored parents may be idle and unopened; reports still belong in their retained transcript.
394
442
  const driver = await this.ensureDriver(this.record(path), true);
@@ -399,6 +447,10 @@ export class ThreadManager {
399
447
  this.epoch++;
400
448
  const records = [...this.records.values()];
401
449
  for (const record of records) {
450
+ record.detachTranscript?.();
451
+ record.detachTranscript = undefined;
452
+ record.transcriptSource = undefined;
453
+ record.transcriptListeners?.clear();
402
454
  record.stopRequested = true;
403
455
  record.startup.abort();
404
456
  }
@@ -524,6 +576,9 @@ export class ThreadManager {
524
576
  throw new Error("Driver startup cancelled");
525
577
  }
526
578
  record.driver = driver;
579
+ record.driverGeneration = (record.driverGeneration ?? 0) + 1;
580
+ record.observationError = undefined;
581
+ if (record.transcriptListeners?.size) this.attachTranscript(record, driver);
527
582
  record.usageCursor = { input: 0, output: 0 };
528
583
  record.liveInputTokens = 0;
529
584
  record.liveOutputTokens = 0;
@@ -541,8 +596,49 @@ export class ThreadManager {
541
596
  }
542
597
  return record.initializing;
543
598
  }
599
+ private attachTranscript(record: Record, driver: AgentDriver): void {
600
+ if (record.detachTranscript || !record.transcriptListeners?.size) return;
601
+ const observation = driver.observeTranscript?.((snapshot) => {
602
+ if (this.disposed || record.driver !== driver || !record.transcriptListeners?.size) return;
603
+ record.transcriptSource = snapshot;
604
+ this.publishTranscript(record);
605
+ });
606
+ if (observation) {
607
+ record.transcriptSource = observation.snapshot;
608
+ record.detachTranscript = observation.unsubscribe;
609
+ }
610
+ }
611
+ private transcriptSnapshot(record: Record): TranscriptSnapshot {
612
+ const source = record.transcriptSource;
613
+ return Object.freeze({
614
+ revision: record.observationRevision ?? 0,
615
+ generation: record.driverGeneration ?? 0,
616
+ messages:
617
+ source?.messages ?? immutableTranscriptValue(record.driver?.snapshot() ?? record.inherited),
618
+ assistant: source?.assistant ?? null,
619
+ tools: source?.tools ?? Object.freeze([]),
620
+ inheritedCount: source?.inheritedCount ?? record.inherited.length,
621
+ thread: immutableTranscriptValue(this.view(record)),
622
+ ...(record.observationError || source?.error
623
+ ? { error: record.observationError ?? source?.error }
624
+ : {}),
625
+ });
626
+ }
627
+ private publishTranscript(record: Record): void {
628
+ if (this.disposed || !record.transcriptListeners?.size) return;
629
+ record.observationRevision = (record.observationRevision ?? 0) + 1;
630
+ const snapshot = this.transcriptSnapshot(record);
631
+ for (const listener of record.transcriptListeners) {
632
+ try {
633
+ listener(snapshot);
634
+ } catch {
635
+ /* UI failure must not affect execution. */
636
+ }
637
+ }
638
+ }
544
639
  private touch(record: Record): void {
545
640
  record.view.updatedAt = Date.now();
641
+ this.publishTranscript(record);
546
642
  if (!this.disposed) this.options.onEvent?.({ kind: "change", thread: this.view(record) });
547
643
  }
548
644
  /** Fold driver-cumulative usage into persisted totals. Partials only refresh the live view. */
@@ -21,6 +21,7 @@ import {
21
21
  DurableMailbox,
22
22
  } from "./mailbox.ts";
23
23
  import { selectTools } from "../prefs/config.ts";
24
+ import { TranscriptChannel } from "./transcript.ts";
24
25
  import type { InheritedToolSource } from "./inherited-tools.ts";
25
26
  import type { ModelSelectionMode, ToolFilteringMode } from "../prefs/settings.ts";
26
27
  import { modelIdentity, getModelPreferences, selectPreferredModel } from "../prefs/models.ts";
@@ -185,6 +186,7 @@ export function createDriverFactory(
185
186
  sessionManager.appendCustomEntry(THREAD_OWNERSHIP_TYPE, {
186
187
  rootId,
187
188
  threadPath: options.path,
189
+ inheritedCount: options.inherited.length,
188
190
  });
189
191
  for (const message of options.inherited) {
190
192
  // Summary messages are projections, not appendable SDK session entries.
@@ -563,7 +565,26 @@ export function createDriverFactory(
563
565
  return { input, output, reported: input + output + usage.totalTokens > 0 };
564
566
  };
565
567
 
568
+ const ownership = sessionManager
569
+ .getBranch()
570
+ .find((entry) => entry.type === "custom" && entry.customType === THREAD_OWNERSHIP_TYPE);
571
+ const inheritedMetadata =
572
+ ownership?.type === "custom"
573
+ ? (ownership.data as { inheritedCount?: unknown })?.inheritedCount
574
+ : undefined;
575
+ const inheritedCount =
576
+ typeof inheritedMetadata === "number" &&
577
+ Number.isInteger(inheritedMetadata) &&
578
+ inheritedMetadata >= 0
579
+ ? inheritedMetadata
580
+ : options.inherited.length;
581
+ const transcript = new TranscriptChannel(
582
+ () => session.messages,
583
+ // A restored compaction has replaced the original inherited prefix.
584
+ session.messages.some((message) => message.role === "compactionSummary") ? 0 : inheritedCount,
585
+ );
566
586
  const unsubscribe = session.subscribe((event) => {
587
+ transcript.accept(event);
567
588
  if (event.type === "tool_execution_start") emit("activity", `Tool: ${event.toolName}`);
568
589
  if (event.type === "tool_execution_end")
569
590
  emit(
@@ -653,6 +674,10 @@ export function createDriverFactory(
653
674
  snapshot() {
654
675
  return structuredClone(session.messages);
655
676
  },
677
+ observeTranscript(listener) {
678
+ assertOpen();
679
+ return transcript.observe(listener);
680
+ },
656
681
  output() {
657
682
  return finalOutput;
658
683
  },
@@ -671,6 +696,7 @@ export function createDriverFactory(
671
696
  disposed = true;
672
697
  aborted = true;
673
698
  restoreAppends();
699
+ transcript.dispose();
674
700
  unsubscribe();
675
701
  session.dispose();
676
702
  },
@@ -691,6 +717,7 @@ export function createDriverFactory(
691
717
  { triggerTurn: false },
692
718
  );
693
719
  mailbox.markEnqueued(accepted.id);
720
+ transcript.reconcile();
694
721
  } catch (error) {
695
722
  emit("error", error instanceof Error ? error.message : String(error));
696
723
  throw error;
@@ -0,0 +1,186 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
3
+ import type {
4
+ TranscriptListener,
5
+ TranscriptObservation,
6
+ TranscriptSnapshot,
7
+ TranscriptToolState,
8
+ } from "../types.ts";
9
+
10
+ /** Clone once at the ownership boundary, then share immutable state across observers. */
11
+ export function immutableTranscriptValue<T>(value: T): T {
12
+ const copy = structuredClone(value);
13
+ const seen = new WeakSet<object>();
14
+ const freeze = (item: unknown): void => {
15
+ if (!item || typeof item !== "object" || seen.has(item)) return;
16
+ seen.add(item);
17
+ for (const child of Object.values(item)) freeze(child);
18
+ // Freezing populated typed-array views throws. Their storage was already cloned.
19
+ if (!ArrayBuffer.isView(item)) Object.freeze(item);
20
+ };
21
+ freeze(copy);
22
+ return copy;
23
+ }
24
+
25
+ /** SDK event projection. Committed history is copied at boundaries, never for each token. */
26
+ export class TranscriptChannel {
27
+ private revision = 0;
28
+ private messages: readonly AgentMessage[];
29
+ private assistant: AgentMessage | null = null;
30
+ private tools = new Map<string, TranscriptToolState>();
31
+ private listeners = new Set<TranscriptListener>();
32
+ private current: TranscriptSnapshot;
33
+ private disposed = false;
34
+ private error: string | undefined;
35
+
36
+ constructor(
37
+ private readMessages: () => readonly AgentMessage[],
38
+ private inheritedCount: number,
39
+ ) {
40
+ this.messages = immutableTranscriptValue(readMessages());
41
+ this.current = this.snapshot();
42
+ }
43
+
44
+ observe(listener: TranscriptListener): TranscriptObservation {
45
+ if (this.disposed) throw new Error("Transcript channel is disposed");
46
+ // No await between registration and snapshot: a finalization cannot fall in a gap.
47
+ const registered: TranscriptListener = (snapshot) => listener(snapshot);
48
+ this.listeners.add(registered);
49
+ return { snapshot: this.current, unsubscribe: () => this.listeners.delete(registered) };
50
+ }
51
+
52
+ accept(event: AgentSessionEvent): void {
53
+ if (this.disposed) return;
54
+ try {
55
+ this.reduce(event);
56
+ } catch (error) {
57
+ // Custom tool details can be non-cloneable. Observation must still never fail the run.
58
+ this.error = error instanceof Error ? error.message : String(error);
59
+ this.publish();
60
+ }
61
+ }
62
+
63
+ private reduce(event: AgentSessionEvent): void {
64
+ this.error = undefined;
65
+ switch (event.type) {
66
+ case "message_start":
67
+ case "message_update":
68
+ if (event.message.role !== "assistant") return;
69
+ this.assistant = immutableTranscriptValue(event.message);
70
+ break;
71
+ case "message_end":
72
+ if (event.message.role === "assistant") this.assistant = null;
73
+ if (event.message.role === "toolResult") this.tools.delete(event.message.toolCallId);
74
+ this.messages = immutableTranscriptValue(this.readMessages());
75
+ break;
76
+ case "tool_execution_start":
77
+ this.tools.set(
78
+ event.toolCallId,
79
+ immutableTranscriptValue({
80
+ toolCallId: event.toolCallId,
81
+ toolName: event.toolName,
82
+ parentToolCallId: event.parentToolCallId,
83
+ args: event.args,
84
+ state: "running" as const,
85
+ }),
86
+ );
87
+ break;
88
+ case "tool_execution_update":
89
+ this.tools.set(
90
+ event.toolCallId,
91
+ immutableTranscriptValue({
92
+ ...this.tools.get(event.toolCallId),
93
+ toolCallId: event.toolCallId,
94
+ toolName: event.toolName,
95
+ parentToolCallId: event.parentToolCallId,
96
+ args: event.args,
97
+ result: event.partialResult,
98
+ state: "running" as const,
99
+ }),
100
+ );
101
+ break;
102
+ case "tool_execution_end":
103
+ this.tools.set(
104
+ event.toolCallId,
105
+ immutableTranscriptValue({
106
+ ...this.tools.get(event.toolCallId),
107
+ toolCallId: event.toolCallId,
108
+ toolName: event.toolName,
109
+ parentToolCallId: event.parentToolCallId,
110
+ args: this.tools.get(event.toolCallId)?.args,
111
+ result: event.result,
112
+ isError: event.isError,
113
+ state: "completed" as const,
114
+ }),
115
+ );
116
+ // Nested calls have no transcript message. Bound their transient completed retention.
117
+ for (const [id, tool] of this.tools) {
118
+ if (this.tools.size <= 128) break;
119
+ if (tool.state === "completed") this.tools.delete(id);
120
+ }
121
+ break;
122
+ case "compaction_end":
123
+ // Compaction may replace/reorder history; do not approximate it with append-only deltas.
124
+ if (event.result && !event.aborted) this.inheritedCount = 0;
125
+ this.messages = immutableTranscriptValue(this.readMessages());
126
+ break;
127
+ case "agent_end":
128
+ case "agent_settled":
129
+ this.assistant = null;
130
+ this.tools.clear();
131
+ this.messages = immutableTranscriptValue(this.readMessages());
132
+ break;
133
+ case "auto_retry_start":
134
+ case "auto_retry_end":
135
+ this.messages = immutableTranscriptValue(this.readMessages());
136
+ break;
137
+ default:
138
+ return;
139
+ }
140
+ this.publish();
141
+ }
142
+
143
+ /** Non-turn custom delivery is not guaranteed to use core message events. */
144
+ reconcile(): void {
145
+ if (this.disposed) return;
146
+ try {
147
+ this.messages = immutableTranscriptValue(this.readMessages());
148
+ this.error = undefined;
149
+ } catch (error) {
150
+ this.error = error instanceof Error ? error.message : String(error);
151
+ }
152
+ this.publish();
153
+ }
154
+
155
+ dispose(): void {
156
+ this.disposed = true;
157
+ this.listeners.clear();
158
+ this.tools.clear();
159
+ this.assistant = null;
160
+ }
161
+
162
+ private snapshot(): TranscriptSnapshot {
163
+ return Object.freeze({
164
+ revision: this.revision,
165
+ generation: 0,
166
+ messages: this.messages,
167
+ assistant: this.assistant,
168
+ tools: Object.freeze([...this.tools.values()]),
169
+ inheritedCount: Math.min(this.inheritedCount, this.messages.length),
170
+ ...(this.error ? { error: this.error } : {}),
171
+ });
172
+ }
173
+
174
+ private publish(): void {
175
+ this.revision++;
176
+ this.current = this.snapshot();
177
+ for (const listener of this.listeners) {
178
+ // Watching is read-only: a broken renderer must not fail the agent's execution.
179
+ try {
180
+ listener(this.current);
181
+ } catch {
182
+ /* observer owns its error reporting */
183
+ }
184
+ }
185
+ }
186
+ }
package/src/types.ts CHANGED
@@ -59,10 +59,38 @@ export type DriverEvent =
59
59
  /** Streaming message_update snapshot. Omit for authoritative message_end. */
60
60
  partial?: boolean;
61
61
  };
62
+ /** Ephemeral read-only transcript state; never part of registry/delivery events. */
63
+ export interface TranscriptToolState {
64
+ toolCallId: string;
65
+ toolName: string;
66
+ parentToolCallId?: string;
67
+ args: unknown;
68
+ result?: unknown;
69
+ isError?: boolean;
70
+ state: "running" | "completed";
71
+ }
72
+ export interface TranscriptSnapshot {
73
+ revision: number;
74
+ /** Changes when a driver is replaced; revisions remain monotonic within the manager. */
75
+ generation: number;
76
+ messages: readonly AgentMessage[];
77
+ assistant: AgentMessage | null;
78
+ tools: readonly TranscriptToolState[];
79
+ inheritedCount: number;
80
+ thread?: ThreadView;
81
+ error?: string;
82
+ }
83
+ export interface TranscriptObservation {
84
+ snapshot: TranscriptSnapshot;
85
+ unsubscribe(): void;
86
+ }
87
+ export type TranscriptListener = (snapshot: TranscriptSnapshot) => void;
88
+
62
89
  export interface AgentDriver {
63
90
  prompt(message: string): Promise<void>;
64
91
  steer(message: string): Promise<void>;
65
92
  snapshot(): AgentMessage[];
93
+ observeTranscript?(listener: TranscriptListener): TranscriptObservation;
66
94
  output(): string;
67
95
  abort(): Promise<void>;
68
96
  dispose(): void;
@@ -114,6 +142,8 @@ export interface ThreadService {
114
142
  get(path: string): ThreadView;
115
143
  output(path: string): string;
116
144
  transcript(path: string): Promise<string>;
145
+ /** Optional for portable adapters; the runtime manager always implements this. */
146
+ observeTranscript?(path: string, listener: TranscriptListener): Promise<TranscriptObservation>;
117
147
  spawn(
118
148
  args: { path: string; type: string; task: string; wait?: boolean },
119
149
  signal?: AbortSignal,