pi-subagent-manager 0.8.0 → 0.10.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 live **Agents** widget sits above the input box. Choose **Full** (the existing tree) or **Minimal** (colored status counts and running-agent token totals, plus the browser hint) under **Status Widget** in `/agents` settings. In the fullscreen tree, **Enter** watches an agent, **Escape** returns, and **i** opens existing thread actions. A status strip below the previews shows how many agents are running and **Press ← to open subagent browser**. Press **Left** at the start of the main draft to open it; normal cursor movement is unchanged. See [live navigation](docs/tools-and-ui.md#live-agent-navigation-read-only) for controls and compatibility.
76
76
 
77
77
  ## Docs
78
78
 
package/docs/settings.md CHANGED
@@ -14,6 +14,7 @@ All keys are optional. Defaults:
14
14
  ```json
15
15
  {
16
16
  "subagentMode": "opportunistic",
17
+ "widgetMode": "full",
17
18
  "modelSelection": "pick-first-scoped",
18
19
  "toolFiltering": "allowed",
19
20
  "maxLevels": 3,
@@ -41,6 +42,17 @@ How much the main model is encouraged to delegate.
41
42
  - Orchestration is a prompt policy, not a tool restriction. Workers don't inherit the root-only rule.
42
43
  - Agent import needs `opportunistic` (it uses the main thread's file tools).
43
44
 
45
+ ## Status Widget (`widgetMode`)
46
+
47
+ Controls the subagent status display above the input box. Choose **Status Widget** in `/agents` settings and save with **Ctrl+S**.
48
+
49
+ | Option | Display |
50
+ | ------------------ | ------- |
51
+ | `full` (default) | The existing multi-line tree with agent details, activity and navigation hints. |
52
+ | `minimal` | One line of theme-colored status counts plus cumulative input `↑` / output `↓` tokens for agents currently starting or running. |
53
+
54
+ Minimal mode groups starting agents with running agents and excludes the main conversation. Token totals exclude completed, stopped, failed and paused agents. The fullscreen tree remains available via `/agents tree` in either mode.
55
+
44
56
  ## Model Picking (`modelSelection`)
45
57
 
46
58
  Which model an agent gets when its session starts.
@@ -49,16 +49,53 @@ 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
+ #### Left-arrow entry
69
+
70
+ Press physical **Left (←)** at the beginning of the main draft (or in an empty input) to open the subagent browser. Elsewhere, Left retains normal cursor movement. Down is always native editing/history navigation. Autocomplete, jumps, paste and configured shortcuts take precedence. Navigating preserves the main draft/cursor and does not require the root to be idle.
71
+
72
+ Left-arrow entry is enabled by default in the TUI; `/agents tree` remains available everywhere. 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 covers concurrent live turns, autocomplete/paste/undo interactions, remapped shortcuts and rich custom content.
56
77
 
57
78
  ## Agents widget
58
79
 
59
- A compact tree above the input editor, at most ten lines.
80
+ The widget above the input editor has two display modes, selected with **Status Widget** in `/agents` settings:
81
+
82
+ - **Full** (default): the existing compact tree, at most twelve lines.
83
+ - **Minimal**: a summary line such as `3 running, 2 stopped, 1 failed, 1 paused ↑12k ↓3k`, with semantic theme colors. Starting agents count as running; completed agents are counted when present. Token totals include only currently starting/running agents, not the main conversation or settled threads. Use `/agents tree` for details.
84
+
85
+ In full mode:
60
86
 
61
87
  - Each row: colored type pill, path, state, task, active time, input `↑` / output `↓` tokens.
62
88
  - A second, indented line shows latest activity.
63
- - Active branches are shown first; overflow is counted, not listed.
89
+ - Active branches are shown first; the most recent agents within each state are preferred when previews overflow. Overflow is counted, not listed.
64
90
  - Time freezes while paused and resumes on continue.
91
+ - A small status strip below the previews shows the running count (including starting agents) and **Press ← to open subagent browser**, including when agents overflow. Minimal mode also shows the hint. RPC output omits the keyboard hint.
92
+
93
+ ### Interrupts and stopping agents
94
+
95
+ With the main input focused (default keybindings):
96
+
97
+ - **Esc** aborts the main turn (including a pending `agent_wait` or foreground spawn wait), **not the subagents**. Already-started subagents keep running.
98
+ - **Ctrl+C** clears the input; it does not stop the main turn or subagents.
99
+ - **Ctrl+C twice quickly** (within 500 ms) exits Pi. Session shutdown cooperatively stops all agents, retaining their sessions.
100
+
101
+ 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.10.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,48 @@ 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: do not replace another integration.
65
+ if (!ctx.hasUI || ctx.mode !== "tui" || !ctx.ui.setEditorComponent) return;
66
+ const existingFactory = ctx.ui.getEditorComponent?.();
67
+ if (existingFactory && existingFactory !== navigationEditorFactory) return;
68
+ // The host only transfers raw text, not cursor/undo/expanded-paste state.
69
+ if (ctx.ui.getEditorText?.()) return;
70
+ const history = buildSessionContext(ctx.sessionManager.getBranch()).messages.flatMap((message) => {
71
+ if (message.role !== "user") return [];
72
+ const content = message.content;
73
+ return [typeof content === "string" ? content : content
74
+ .filter((block) => block.type === "text").map((block) => block.text).join("")];
75
+ });
76
+ navigationEditorFactory = (tui, theme, keys) => {
77
+ const editor = new AgentNavigationEditor(tui, theme, keys, {
78
+ // Initial startup hydrates after session_start; replacement editors do not.
79
+ initialHistory: seedHistory ? history : undefined,
80
+ generation: () => navigationGeneration,
81
+ canOpen: () => manager !== undefined && context?.mode === "tui" &&
82
+ limits.subagentMode !== "off" && !navigation.isOpen,
83
+ openTree: () => manager && context
84
+ ? navigation.open(context, manager.scope("/root")) : undefined,
85
+ onError: (error) => context?.ui.notify(
86
+ error instanceof Error ? error.message : String(error), "error"),
87
+ });
88
+ navigationEditor = editor;
89
+ return editor;
90
+ };
91
+ ctx.ui.setEditorComponent(navigationEditorFactory);
92
+ };
50
93
  let persistenceSignature = "";
51
94
  let migrationRequested = false;
52
95
  let importInProgress = false;
@@ -195,7 +238,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
195
238
  const refreshWidget = (ctx: ExtensionContext) => {
196
239
  if (limits.subagentMode === "off") {
197
240
  if (ctx.hasUI) ctx.ui.setWidget("pi-subagent", undefined);
198
- } else updateWidget(ctx, requireManager().list());
241
+ } else updateWidget(ctx, requireManager().list(), limits.widgetMode);
199
242
  };
200
243
  syncTools();
201
244
  pi.on("before_agent_start", async (event, ctx) => {
@@ -213,8 +256,10 @@ export default function piSubagent(pi: ExtensionAPI): void {
213
256
  };
214
257
  });
215
258
 
216
- const attachSession = async (ctx: ExtensionContext) => {
259
+ const attachSession = async (ctx: ExtensionContext, installEditor = false, seedHistory = true) => {
217
260
  const token = ++generation;
261
+ closeNavigation(installEditor);
262
+ navigation = new AgentNavigationController();
218
263
  // session_start already belongs to the replacement session: never append the old registry here.
219
264
  if (manager) await manager.shutdown();
220
265
  inheritedTools.reset();
@@ -246,6 +291,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
246
291
  },
247
292
  });
248
293
  manager = instance;
294
+ if (installEditor) installNavigationEditor(ctx, seedHistory);
249
295
  const entries = ctx.sessionManager.getBranch();
250
296
  const entry = [...entries]
251
297
  .reverse()
@@ -274,12 +320,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
274
320
  if (limits.subagentMode !== "off" && diagnostics.length)
275
321
  ctx.ui.notify(diagnostics.join("\n"), "warning");
276
322
  };
277
- pi.on("session_start", async (_event, ctx) => {
278
- await attachSession(ctx);
323
+ pi.on("session_start", async (event, ctx) => {
324
+ await attachSession(ctx, true, event.reason !== "startup");
279
325
  if (limits.subagentMode !== "off") await importAgents(ctx, true);
280
326
  });
281
327
  pi.on("session_tree", async (_event, ctx) => attachSession(ctx));
282
328
  const stopWorkingThreads = async () => {
329
+ closeNavigation();
283
330
  if (!manager) return;
284
331
  for (const thread of manager.list()) {
285
332
  const state = manager.get(thread.path).state;
@@ -292,6 +339,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
292
339
  pi.on("session_before_fork", stopWorkingThreads);
293
340
  pi.on("session_shutdown", async () => {
294
341
  generation++;
342
+ closeNavigation(true);
295
343
  await manager?.shutdown();
296
344
  persist();
297
345
  if (context?.hasUI) context.ui.setWidget("pi-subagent", undefined);
@@ -357,7 +405,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
357
405
  } else if (command === "status") {
358
406
  await showAgentStatus(ctx, requireManager().scope("/root"));
359
407
  } else if (command === "tree") {
360
- await showAgentTree(ctx, requireManager().scope("/root"), rest.join(" ") || undefined);
408
+ await navigation.open(ctx, requireManager().scope("/root"), rest.join(" ") || undefined);
361
409
  } else
362
410
  ctx.ui.notify(
363
411
  "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
+ }