pi-subagent-manager 1.2.1 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,6 +15,7 @@ Tests run offline with no model credentials. Scripted-provider SDK tests cover n
15
15
  | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
16
16
  | `src/index.ts` | Parent-session lifecycle and extension wiring |
17
17
  | `src/orch/manager.ts` | Ownership, lifecycle, retained registry. `scope(caller)` gives tools and UI the same caller-bound `ThreadService`. |
18
+ | `src/orch/registry.ts` | Registry persistence: a full entry per attach, then deltas of changed fields |
18
19
  | `src/orch/runtime.ts` | Isolated pi SDK sessions, providers, safe turn boundaries |
19
20
  | `src/orch/paths.ts` | Canonical ancestry and context snapshots |
20
21
  | `src/orch/mailbox.ts` | Input persistence, replay, transcript reconciliation |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "1.2.1",
3
+ "version": "1.3.1",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
package/src/index.ts CHANGED
@@ -30,11 +30,11 @@ import { ChecklistMetaMirror, checklistStatus } from "./orch/checklist-integrati
30
30
  import { agentTools } from "./orch/tools.ts";
31
31
  import { editAgentTypes, updateWidget } from "./ui/ui.ts";
32
32
  import { canOpenDialog, dialogMenu } from "./ui/dialog.ts";
33
- import type { SavedThread, ThreadEvent, ThreadView } from "./types.ts";
33
+ import type { ThreadEvent, ThreadView } from "./types.ts";
34
34
  import { COST_ENTRY, CostLedger } from "./orch/cost-ledger.ts";
35
+ import { readRegistry, RegistryWriter } from "./orch/registry.ts";
35
36
  import { CostFooterController } from "./ui/cost-footer.ts";
36
37
 
37
- const REGISTRY_ENTRY = "pi-subagent:registry:v1";
38
38
  const ROOT_MAILBOX_ENTRY = "pi-subagent:root-mailbox:v1";
39
39
  const ROOT_SUMMARY_MESSAGE = "pi-subagent:final-recap";
40
40
  const ROOT_WAKE_MESSAGE = "pi-subagent:wake";
@@ -237,7 +237,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
237
237
  };
238
238
  ctx.ui.setEditorComponent(navigationEditorFactory);
239
239
  };
240
- let persistenceSignature = "";
240
+ const registryWriter = new RegistryWriter((customType, data) => pi.appendEntry(customType, data));
241
241
  let migrationRequested = false;
242
242
  let importInProgress = false;
243
243
  const importAgents = async (ctx: ExtensionContext, firstRun: boolean) => {
@@ -282,16 +282,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
282
282
  };
283
283
  const persist = () => {
284
284
  if (!manager) return;
285
- const threads = manager.saved();
286
- const signature = JSON.stringify(threads);
287
- if (signature !== persistenceSignature) {
288
- pi.appendEntry(REGISTRY_ENTRY, {
289
- version: 1,
290
- rootSessionId: requireContext().sessionManager.getSessionId(),
291
- threads,
292
- });
293
- persistenceSignature = signature;
294
- }
285
+ registryWriter.write(requireContext().sessionManager.getSessionId(), manager.saved());
295
286
  };
296
287
  const warnDelivery = (error: unknown) => {
297
288
  if (limits.subagentMode === "off") return;
@@ -592,6 +583,16 @@ export default function piSubagent(pi: ExtensionAPI): void {
592
583
  store.reload();
593
584
  if (store.diagnostics.length) context?.ui.notify(store.diagnostics.join("\n"), "warning");
594
585
  });
586
+
587
+ // The footer normally refreshes when subagents report metrics or when a root turn ends.
588
+ // Without any subagents running there are no metric events, so refresh on main-session
589
+ // turn boundaries to keep the ongoing total accurate.
590
+ pi.on("message_end", async (_event, ctx) => {
591
+ refreshCostFooter(ctx);
592
+ });
593
+ pi.on("tool_execution_end", async (_event, ctx) => {
594
+ refreshCostFooter(ctx);
595
+ });
595
596
  syncTools();
596
597
  pi.on("before_agent_start", async (event, ctx) => {
597
598
  // Re-verify on every turn: the Labs opt-in AND live checklist eligibility must both hold.
@@ -647,7 +648,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
647
648
  agentDir: getAgentDir(),
648
649
  includeProject: ctx.isProjectTrusted(),
649
650
  });
650
- persistenceSignature = "";
651
+ registryWriter.reset();
651
652
  const settingsDiagnostics = loadLimits(ctx);
652
653
  syncTools();
653
654
  driverFactory = makeDriverFactory();
@@ -682,27 +683,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
682
683
  });
683
684
  manager = instance;
684
685
  if (installEditor) installNavigationEditor(ctx, seedHistory);
685
- const entries = ctx.sessionManager.getBranch();
686
- const entry = [...entries]
687
- .reverse()
688
- .find((item) => item.type === "custom" && item.customType === REGISTRY_ENTRY);
689
- if (entry?.type === "custom") {
690
- try {
691
- const data = entry.data as {
692
- version: number;
693
- rootSessionId: string;
694
- threads: SavedThread[];
695
- };
696
- if (data.version !== 1 || !Array.isArray(data.threads))
697
- throw new Error("Invalid registry format");
698
- // Forked parents own a new registry; they must not share writable child transcripts.
699
- if (data.rootSessionId === ctx.sessionManager.getSessionId())
700
- instance.restore(data.threads);
701
- else persist();
702
- } catch (error) {
703
- if (limits.subagentMode !== "off")
704
- ctx.ui.notify(`Could not restore subagent registry: ${String(error)}`, "error");
705
- }
686
+ try {
687
+ const saved = readRegistry(ctx.sessionManager.getBranch());
688
+ // Forked parents own a new registry; they must not share writable child transcripts.
689
+ if (saved?.rootSessionId === ctx.sessionManager.getSessionId())
690
+ instance.restore(saved.threads);
691
+ else if (saved) persist();
692
+ } catch (error) {
693
+ if (limits.subagentMode !== "off")
694
+ ctx.ui.notify(`Could not restore subagent registry: ${String(error)}`, "error");
706
695
  }
707
696
  // Recover a persisted settlement whose ledger append was interrupted, including runs paused on reload.
708
697
  for (const saved of instance.saved()) rollupCost({ ...saved.view, updatedAt: Date.now() });
@@ -745,6 +734,8 @@ export default function piSubagent(pi: ExtensionAPI): void {
745
734
  closeNavigation(true);
746
735
  await manager?.shutdown();
747
736
  costFooter.clear();
737
+ // A clean close leaves an exact checkpoint for releases that cannot read deltas.
738
+ registryWriter.reset();
748
739
  persist();
749
740
  if (context?.hasUI) context.ui.setWidget("pi-subagent", undefined);
750
741
  manager = undefined;
@@ -0,0 +1,168 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ import type { SavedThread, SavedThreadView } from "../types.ts";
3
+
4
+ /** Every retained thread. Written first after each attach and whenever threads are removed. */
5
+ export const REGISTRY_ENTRY = "pi-subagent:registry:v1";
6
+ /**
7
+ * What changed since the previous registry entry on the branch. Each child checkpoint changes a
8
+ * few view fields of one thread; rewriting the whole registry for each grew root sessions by
9
+ * gigabytes, and Pi holds every session entry in memory.
10
+ */
11
+ export const REGISTRY_DELTA_ENTRY = "pi-subagent:registry-delta:v1";
12
+
13
+ export interface SavedRegistry {
14
+ version: 1;
15
+ rootSessionId: string;
16
+ threads: SavedThread[];
17
+ }
18
+
19
+ /** A change to one thread since the previous registry entry on the branch. */
20
+ export type ThreadChange =
21
+ /** An added thread, or one whose definition or inherited context changed. */
22
+ | { thread: SavedThread }
23
+ /** Only these view fields changed or were cleared. */
24
+ | { path: string; view: Partial<SavedThreadView>; cleared?: (keyof SavedThreadView)[] };
25
+
26
+ export interface RegistryDelta {
27
+ version: 1;
28
+ rootSessionId: string;
29
+ /** In registry order. Added threads follow every existing thread. */
30
+ changes: ThreadChange[];
31
+ }
32
+
33
+ /**
34
+ * The registry saved on a branch: its last full entry with every later delta applied in order.
35
+ * Returns undefined when the branch has no registry. Throws on malformed entries.
36
+ */
37
+ export function readRegistry(branch: readonly SessionEntry[]): SavedRegistry | undefined {
38
+ const deltas: unknown[] = [];
39
+ for (let index = branch.length - 1; index >= 0; index--) {
40
+ const entry = branch[index]!;
41
+ if (entry.type !== "custom") continue;
42
+ if (entry.customType === REGISTRY_DELTA_ENTRY) deltas.push(entry.data);
43
+ else if (entry.customType === REGISTRY_ENTRY)
44
+ return applyDeltas(parseRegistry(entry.data), deltas.reverse());
45
+ }
46
+ if (deltas.length) throw new Error("Invalid registry format: delta without a full registry");
47
+ return undefined;
48
+ }
49
+
50
+ function parseRegistry(data: unknown): SavedRegistry {
51
+ const registry = data as Partial<SavedRegistry> | undefined;
52
+ if (registry?.version !== 1 || !Array.isArray(registry.threads))
53
+ throw new Error("Invalid registry format");
54
+ return registry as SavedRegistry;
55
+ }
56
+
57
+ function parseDelta(data: unknown, rootSessionId: string): RegistryDelta {
58
+ const delta = data as Partial<RegistryDelta> | undefined;
59
+ if (delta?.version !== 1 || !Array.isArray(delta.changes))
60
+ throw new Error("Invalid registry format");
61
+ if (delta.rootSessionId !== rootSessionId)
62
+ throw new Error("Invalid registry format: delta belongs to another root session");
63
+ return delta as RegistryDelta;
64
+ }
65
+
66
+ function applyDeltas(base: SavedRegistry, deltas: readonly unknown[]): SavedRegistry {
67
+ if (!deltas.length) return base;
68
+ // Map insertion order is registry order: changes replace in place, added threads append.
69
+ const threads = new Map(base.threads.map((thread) => [thread.view.path, thread]));
70
+ if (threads.size !== base.threads.length)
71
+ throw new Error("Invalid registry format: duplicate thread path");
72
+ for (const data of deltas) {
73
+ for (const change of parseDelta(data, base.rootSessionId).changes) {
74
+ if ("thread" in change) {
75
+ threads.set(change.thread.view.path, change.thread);
76
+ continue;
77
+ }
78
+ const current = threads.get(change.path);
79
+ if (!current) throw new Error(`Invalid registry format: unknown thread ${change.path}`);
80
+ const view = { ...current.view, ...change.view };
81
+ for (const field of change.cleared ?? []) delete view[field];
82
+ threads.set(change.path, { ...current, view });
83
+ }
84
+ }
85
+ return { ...base, threads: [...threads.values()] };
86
+ }
87
+
88
+ /** A thread as last written: each defined view field and the rest of the record, serialized. */
89
+ interface WrittenThread {
90
+ view: Map<string, string>;
91
+ rest: string;
92
+ }
93
+
94
+ function serialize(thread: SavedThread): WrittenThread {
95
+ const { view, ...rest } = thread;
96
+ const fields = Object.entries(view).flatMap(([field, value]): [string, string][] =>
97
+ // JSON omits undefined fields, so they read back as cleared.
98
+ value === undefined ? [] : [[field, JSON.stringify(value)]],
99
+ );
100
+ return { view: new Map(fields), rest: JSON.stringify(rest) };
101
+ }
102
+
103
+ function threadChange(
104
+ thread: SavedThread,
105
+ next: WrittenThread,
106
+ previous: WrittenThread | undefined,
107
+ ): ThreadChange | undefined {
108
+ if (!previous || previous.rest !== next.rest) return { thread };
109
+ const view: Record<string, unknown> = {};
110
+ for (const [field, value] of next.view) {
111
+ if (previous.view.get(field) !== value)
112
+ view[field] = thread.view[field as keyof SavedThreadView];
113
+ }
114
+ const cleared = [...previous.view.keys()].filter((field) => !next.view.has(field));
115
+ if (!Object.keys(view).length && !cleared.length) return undefined;
116
+ return {
117
+ path: thread.view.path,
118
+ view,
119
+ ...(cleared.length ? { cleared: cleared as (keyof SavedThreadView)[] } : {}),
120
+ };
121
+ }
122
+
123
+ /** Appends registry entries so that readRegistry() on the current branch returns the last write. */
124
+ export class RegistryWriter {
125
+ /** The threads, in order, that readRegistry() returns for the current branch. */
126
+ private persisted: { rootSessionId: string; threads: Map<string, WrittenThread> } | undefined;
127
+
128
+ constructor(
129
+ private readonly append: (customType: string, data: SavedRegistry | RegistryDelta) => void,
130
+ ) {}
131
+
132
+ /** The session or branch changed: the next write must be a full registry. */
133
+ reset(): void {
134
+ this.persisted = undefined;
135
+ }
136
+
137
+ write(rootSessionId: string, threads: SavedThread[]): void {
138
+ const next = new Map(threads.map((thread) => [thread.view.path, serialize(thread)]));
139
+ const persisted = this.persisted;
140
+ if (
141
+ persisted &&
142
+ persisted.rootSessionId === rootSessionId &&
143
+ keepsOrder(persisted.threads, threads)
144
+ ) {
145
+ const changes = threads.flatMap((thread) => {
146
+ const path = thread.view.path;
147
+ const change = threadChange(thread, next.get(path)!, persisted.threads.get(path));
148
+ return change ? [change] : [];
149
+ });
150
+ if (!changes.length) return;
151
+ this.append(REGISTRY_DELTA_ENTRY, { version: 1, rootSessionId, changes });
152
+ } else {
153
+ this.append(REGISTRY_ENTRY, { version: 1, rootSessionId, threads });
154
+ }
155
+ // After the append: a failed write must not become the base for the next delta.
156
+ this.persisted = { rootSessionId, threads: next };
157
+ }
158
+ }
159
+
160
+ /** A delta cannot remove or reorder threads: every persisted path must keep its position. */
161
+ function keepsOrder(persisted: ReadonlyMap<string, unknown>, threads: readonly SavedThread[]) {
162
+ let index = 0;
163
+ for (const path of persisted.keys()) {
164
+ if (threads[index]?.view.path !== path) return false;
165
+ index++;
166
+ }
167
+ return true;
168
+ }
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
2
- import { basename } from "node:path";
2
+ import { basename, dirname } from "node:path";
3
3
  import { discoverSubagentExtensions } from "../orch/extensions.ts";
4
4
  import type { ConfigStore } from "../prefs/config.ts";
5
5
  import {
@@ -226,7 +226,7 @@ async function configureSubagentExtensions(
226
226
  [
227
227
  ...files.map((file) => ({
228
228
  id: file,
229
- label: `${selected.has(file) ? "[x]" : "[ ]"} ${basename(file)}`,
229
+ label: `${selected.has(file) ? "[x]" : "[ ]"} ${/^index\.[cm]?[jt]s$/.test(basename(file)) ? basename(dirname(file)) : basename(file)}`,
230
230
  value: available.includes(file) ? (selected.has(file) ? "On" : "Off") : "Unavailable",
231
231
  help: `${file}\n${available.includes(file) ? "Reload this extension in newly opened subagent sessions." : "Not currently discoverable/trusted; will not load. Toggle Off to remove the saved selection."}\nSpace/Enter toggles. Changes are saved only with outer Save and apply.`,
232
232
  })),