pi-subagent-manager 0.7.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.
@@ -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. */
@@ -4,6 +4,8 @@ import { existsSync } from "node:fs";
4
4
  import { mkdir, readFile, realpath } from "node:fs/promises";
5
5
  import {
6
6
  createAgentSession,
7
+ createCodemodeExtension,
8
+ createToolSearchExtension,
7
9
  DefaultResourceLoader,
8
10
  getAgentDir,
9
11
  ModelRuntime,
@@ -19,6 +21,8 @@ import {
19
21
  DurableMailbox,
20
22
  } from "./mailbox.ts";
21
23
  import { selectTools } from "../prefs/config.ts";
24
+ import { TranscriptChannel } from "./transcript.ts";
25
+ import type { InheritedToolSource } from "./inherited-tools.ts";
22
26
  import type { ModelSelectionMode, ToolFilteringMode } from "../prefs/settings.ts";
23
27
  import { modelIdentity, getModelPreferences, selectPreferredModel } from "../prefs/models.ts";
24
28
  import {
@@ -131,11 +135,12 @@ async function assertAcceptedSessionFile(
131
135
  }
132
136
  }
133
137
 
134
- /** Isolated SDK sessions; neither external extensions nor the CLI's MCP factories are loaded. */
138
+ /** Isolated SDK sessions with filtered root tool bridges, not reloaded root extensions. */
135
139
  export function createDriverFactory(
136
140
  getRootContext: () => ExtensionContext,
137
141
  getModelSelection: () => ModelSelectionMode = () => "pick-first-scoped",
138
142
  getToolFiltering: () => ToolFilteringMode = () => "allowed",
143
+ getInheritedTools: () => InheritedToolSource = () => ({ tools: [], activeNames: [] }),
139
144
  ): DriverFactory {
140
145
  // Keep resolved settings even after disposal: descendants inherit settings, not the caller's history.
141
146
  const resolved = new Map<string, { provider: string; id: string; thinking: ThinkingLevel }>();
@@ -181,6 +186,7 @@ export function createDriverFactory(
181
186
  sessionManager.appendCustomEntry(THREAD_OWNERSHIP_TYPE, {
182
187
  rootId,
183
188
  threadPath: options.path,
189
+ inheritedCount: options.inherited.length,
184
190
  });
185
191
  for (const message of options.inherited) {
186
192
  // Summary messages are projections, not appendable SDK session entries.
@@ -316,12 +322,23 @@ export function createDriverFactory(
316
322
  : undefined;
317
323
  const thinkingLevel =
318
324
  savedThinking ?? options.type.thinkingLevel ?? parent?.thinking ?? ctx.thinkingLevel ?? "off";
325
+ const inherited = getInheritedTools();
326
+ const localNames = new Set([...BUILTINS, ...options.tools.map((tool) => tool.name)]);
327
+ const externalTools = inherited.tools.filter((tool) => !localNames.has(tool.name));
319
328
  const toolNames = selectTools(
320
329
  options.type.tools,
321
- [...BUILTINS, ...options.tools.map((tool) => tool.name)],
330
+ [...localNames, ...externalTools.map((tool) => tool.name)],
322
331
  toolFiltering,
323
332
  );
324
333
  const allowed = new Set(toolNames);
334
+ const rootActive = new Set(inherited.activeNames);
335
+ // Preserve deferred/codemode exposure rather than flooding model declarations with MCP tools.
336
+ const activeToolNames = toolNames.filter(
337
+ (name) => localNames.has(name) || rootActive.has(name) || options.type.tools?.allow?.includes(name) && toolFiltering === "allowed",
338
+ );
339
+ const customTools = [...options.tools, ...externalTools].filter(
340
+ (tool) => allowed.has(tool.name) && tool.name !== "codemode" && tool.name !== "tool_search",
341
+ );
325
342
  const settingsManager = SettingsManager.inMemory({ cacheWarming: "off" });
326
343
  let parkQueue = () => {};
327
344
  const pauseBoundary = () => {
@@ -354,6 +371,10 @@ export function createDriverFactory(
354
371
  ].join("\n\n"),
355
372
  appendSystemPromptOverride: () => [],
356
373
  extensionFactories: [
374
+ // These orchestrators must see the CHILD loadout. Forwarding root codemode would
375
+ // let scripts discover/call tools outside the child's allow/block policy.
376
+ ...(allowed.has("codemode") ? [createCodemodeExtension()] : []),
377
+ ...(allowed.has("tool_search") ? [createToolSearchExtension()] : []),
357
378
  (pi) => {
358
379
  pi.on("turn_end", pauseBoundary);
359
380
  pi.on("agent_before_settle", pauseBoundary);
@@ -378,8 +399,10 @@ export function createDriverFactory(
378
399
  settingsManager,
379
400
  resourceLoader: loader,
380
401
  sessionManager,
402
+ // SDK `tools` is both a registry allowlist and an initial active list.
403
+ // Register every permitted deferred tool, then narrow declarations after bind.
381
404
  tools: toolNames,
382
- customTools: options.tools.filter((tool) => allowed.has(tool.name)),
405
+ customTools,
383
406
  });
384
407
  let lastScopedModelsKey = "";
385
408
  const updateResolved = () => {
@@ -448,6 +471,7 @@ export function createDriverFactory(
448
471
  await enforceScopedModelPolicy();
449
472
  options.signal.throwIfAborted();
450
473
  await session.bindExtensions({ mode: "print" });
474
+ session.setActiveToolsByName(activeToolNames);
451
475
  options.signal.throwIfAborted();
452
476
  } catch (error) {
453
477
  session.dispose();
@@ -541,7 +565,26 @@ export function createDriverFactory(
541
565
  return { input, output, reported: input + output + usage.totalTokens > 0 };
542
566
  };
543
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
+ );
544
586
  const unsubscribe = session.subscribe((event) => {
587
+ transcript.accept(event);
545
588
  if (event.type === "tool_execution_start") emit("activity", `Tool: ${event.toolName}`);
546
589
  if (event.type === "tool_execution_end")
547
590
  emit(
@@ -631,6 +674,10 @@ export function createDriverFactory(
631
674
  snapshot() {
632
675
  return structuredClone(session.messages);
633
676
  },
677
+ observeTranscript(listener) {
678
+ assertOpen();
679
+ return transcript.observe(listener);
680
+ },
634
681
  output() {
635
682
  return finalOutput;
636
683
  },
@@ -649,6 +696,7 @@ export function createDriverFactory(
649
696
  disposed = true;
650
697
  aborted = true;
651
698
  restoreAppends();
699
+ transcript.dispose();
652
700
  unsubscribe();
653
701
  session.dispose();
654
702
  },
@@ -669,6 +717,7 @@ export function createDriverFactory(
669
717
  { triggerTurn: false },
670
718
  );
671
719
  mailbox.markEnqueued(accepted.id);
720
+ transcript.reconcile();
672
721
  } catch (error) {
673
722
  emit("error", error instanceof Error ? error.message : String(error));
674
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,