pi-subagent-manager 1.9.0 → 1.11.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.
Files changed (191) hide show
  1. package/agents/architect.md +4 -4
  2. package/agents/coder.md +3 -4
  3. package/agents/researcher.md +2 -2
  4. package/agents/writer.md +2 -5
  5. package/dist/index.d.ts +3 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +836 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/orch/checklist-integration.d.ts +48 -0
  10. package/dist/orch/checklist-integration.d.ts.map +1 -0
  11. package/dist/orch/checklist-integration.js +204 -0
  12. package/dist/orch/checklist-integration.js.map +1 -0
  13. package/dist/orch/context-entries.d.ts +8 -0
  14. package/dist/orch/context-entries.d.ts.map +1 -0
  15. package/dist/orch/context-entries.js +8 -0
  16. package/dist/orch/context-entries.js.map +1 -0
  17. package/dist/orch/cost-ledger.d.ts +16 -0
  18. package/dist/orch/cost-ledger.d.ts.map +1 -0
  19. package/dist/orch/cost-ledger.js +43 -0
  20. package/dist/orch/cost-ledger.js.map +1 -0
  21. package/dist/orch/diagnostics.d.ts +13 -0
  22. package/dist/orch/diagnostics.d.ts.map +1 -0
  23. package/dist/orch/diagnostics.js +95 -0
  24. package/dist/orch/diagnostics.js.map +1 -0
  25. package/dist/orch/extensions.d.ts +15 -0
  26. package/dist/orch/extensions.d.ts.map +1 -0
  27. package/dist/orch/extensions.js +80 -0
  28. package/dist/orch/extensions.js.map +1 -0
  29. package/dist/orch/housekeeping-usage.d.ts +14 -0
  30. package/dist/orch/housekeeping-usage.d.ts.map +1 -0
  31. package/dist/orch/housekeeping-usage.js +27 -0
  32. package/dist/orch/housekeeping-usage.js.map +1 -0
  33. package/dist/orch/housekeeping.d.ts +89 -0
  34. package/dist/orch/housekeeping.d.ts.map +1 -0
  35. package/dist/orch/housekeeping.js +281 -0
  36. package/dist/orch/housekeeping.js.map +1 -0
  37. package/dist/orch/inherited-tools.d.ts +18 -0
  38. package/dist/orch/inherited-tools.d.ts.map +1 -0
  39. package/dist/orch/inherited-tools.js +71 -0
  40. package/dist/orch/inherited-tools.js.map +1 -0
  41. package/dist/orch/mailbox.d.ts +59 -0
  42. package/dist/orch/mailbox.d.ts.map +1 -0
  43. package/dist/orch/mailbox.js +196 -0
  44. package/dist/orch/mailbox.js.map +1 -0
  45. package/dist/orch/manager.d.ts +82 -0
  46. package/dist/orch/manager.d.ts.map +1 -0
  47. package/dist/orch/manager.js +1010 -0
  48. package/dist/orch/manager.js.map +1 -0
  49. package/dist/orch/paths.d.ts +7 -0
  50. package/dist/orch/paths.d.ts.map +1 -0
  51. package/dist/orch/paths.js +73 -0
  52. package/dist/orch/paths.js.map +1 -0
  53. package/dist/orch/prompt.d.ts +7 -0
  54. package/dist/orch/prompt.d.ts.map +1 -0
  55. package/dist/orch/prompt.js +34 -0
  56. package/dist/orch/prompt.js.map +1 -0
  57. package/dist/orch/registry.d.ts +49 -0
  58. package/dist/orch/registry.d.ts.map +1 -0
  59. package/dist/orch/registry.js +134 -0
  60. package/dist/orch/registry.js.map +1 -0
  61. package/dist/orch/runtime.d.ts +11 -0
  62. package/dist/orch/runtime.d.ts.map +1 -0
  63. package/dist/orch/runtime.js +882 -0
  64. package/dist/orch/runtime.js.map +1 -0
  65. package/dist/orch/tools.d.ts +6 -0
  66. package/dist/orch/tools.d.ts.map +1 -0
  67. package/dist/orch/tools.js +114 -0
  68. package/dist/orch/tools.js.map +1 -0
  69. package/dist/orch/transcript.d.ts +28 -0
  70. package/dist/orch/transcript.d.ts.map +1 -0
  71. package/dist/orch/transcript.js +176 -0
  72. package/dist/orch/transcript.js.map +1 -0
  73. package/dist/prefs/agent-import.d.ts +37 -0
  74. package/dist/prefs/agent-import.d.ts.map +1 -0
  75. package/dist/prefs/agent-import.js +196 -0
  76. package/dist/prefs/agent-import.js.map +1 -0
  77. package/dist/prefs/config.d.ts +108 -0
  78. package/dist/prefs/config.d.ts.map +1 -0
  79. package/dist/prefs/config.js +926 -0
  80. package/dist/prefs/config.js.map +1 -0
  81. package/dist/prefs/import-discovery.d.ts +28 -0
  82. package/dist/prefs/import-discovery.d.ts.map +1 -0
  83. package/dist/prefs/import-discovery.js +562 -0
  84. package/dist/prefs/import-discovery.js.map +1 -0
  85. package/dist/prefs/import-instructions.d.ts +3 -0
  86. package/dist/prefs/import-instructions.d.ts.map +1 -0
  87. package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +1 -0
  88. package/dist/prefs/import-instructions.js.map +1 -0
  89. package/dist/prefs/models.d.ts +24 -0
  90. package/dist/prefs/models.d.ts.map +1 -0
  91. package/dist/prefs/models.js +57 -0
  92. package/dist/prefs/models.js.map +1 -0
  93. package/dist/prefs/settings.d.ts +89 -0
  94. package/dist/prefs/settings.d.ts.map +1 -0
  95. package/dist/prefs/settings.js +505 -0
  96. package/dist/prefs/settings.js.map +1 -0
  97. package/dist/types.d.ts +293 -0
  98. package/dist/types.d.ts.map +1 -0
  99. package/dist/types.js +2 -0
  100. package/dist/types.js.map +1 -0
  101. package/dist/ui/agent-loader.d.ts +21 -0
  102. package/dist/ui/agent-loader.d.ts.map +1 -0
  103. package/dist/ui/agent-loader.js +73 -0
  104. package/dist/ui/agent-loader.js.map +1 -0
  105. package/dist/ui/agent-navigation-editor.d.ts +46 -0
  106. package/dist/ui/agent-navigation-editor.d.ts.map +1 -0
  107. package/dist/ui/agent-navigation-editor.js +189 -0
  108. package/dist/ui/agent-navigation-editor.js.map +1 -0
  109. package/dist/ui/cost-footer.d.ts +37 -0
  110. package/dist/ui/cost-footer.d.ts.map +1 -0
  111. package/dist/ui/cost-footer.js +215 -0
  112. package/dist/ui/cost-footer.js.map +1 -0
  113. package/dist/ui/dialog.d.ts +135 -0
  114. package/dist/ui/dialog.d.ts.map +1 -0
  115. package/dist/ui/dialog.js +533 -0
  116. package/dist/ui/dialog.js.map +1 -0
  117. package/dist/ui/import-picker.d.ts +38 -0
  118. package/dist/ui/import-picker.d.ts.map +1 -0
  119. package/dist/ui/import-picker.js +211 -0
  120. package/dist/ui/import-picker.js.map +1 -0
  121. package/dist/ui/live-agent-view.d.ts +82 -0
  122. package/dist/ui/live-agent-view.d.ts.map +1 -0
  123. package/dist/ui/live-agent-view.js +546 -0
  124. package/dist/ui/live-agent-view.js.map +1 -0
  125. package/dist/ui/model-picker.d.ts +109 -0
  126. package/dist/ui/model-picker.d.ts.map +1 -0
  127. package/dist/ui/model-picker.js +549 -0
  128. package/dist/ui/model-picker.js.map +1 -0
  129. package/dist/ui/settings-ui.d.ts +17 -0
  130. package/dist/ui/settings-ui.d.ts.map +1 -0
  131. package/dist/ui/settings-ui.js +679 -0
  132. package/dist/ui/settings-ui.js.map +1 -0
  133. package/dist/ui/status-ui.d.ts +67 -0
  134. package/dist/ui/status-ui.d.ts.map +1 -0
  135. package/dist/ui/status-ui.js +487 -0
  136. package/dist/ui/status-ui.js.map +1 -0
  137. package/dist/ui/thread-tree.d.ts +22 -0
  138. package/dist/ui/thread-tree.d.ts.map +1 -0
  139. package/dist/ui/thread-tree.js +153 -0
  140. package/dist/ui/thread-tree.js.map +1 -0
  141. package/dist/ui/tool-picker.d.ts +46 -0
  142. package/dist/ui/tool-picker.d.ts.map +1 -0
  143. package/dist/ui/tool-picker.js +334 -0
  144. package/dist/ui/tool-picker.js.map +1 -0
  145. package/dist/ui/transcript-tool.d.ts +2 -0
  146. package/dist/ui/transcript-tool.d.ts.map +1 -0
  147. package/dist/ui/transcript-tool.js +100 -0
  148. package/dist/ui/transcript-tool.js.map +1 -0
  149. package/dist/ui/ui.d.ts +41 -0
  150. package/dist/ui/ui.d.ts.map +1 -0
  151. package/dist/ui/ui.js +1047 -0
  152. package/dist/ui/ui.js.map +1 -0
  153. package/docs/default-agents.md +11 -13
  154. package/docs/development.md +2 -1
  155. package/package.json +16 -4
  156. package/src/index.ts +0 -920
  157. package/src/orch/checklist-integration.ts +0 -230
  158. package/src/orch/context-entries.ts +0 -15
  159. package/src/orch/cost-ledger.ts +0 -56
  160. package/src/orch/diagnostics.ts +0 -95
  161. package/src/orch/extensions.ts +0 -83
  162. package/src/orch/housekeeping-usage.ts +0 -47
  163. package/src/orch/housekeeping.ts +0 -348
  164. package/src/orch/inherited-tools.ts +0 -84
  165. package/src/orch/mailbox.ts +0 -261
  166. package/src/orch/manager.ts +0 -1084
  167. package/src/orch/paths.ts +0 -73
  168. package/src/orch/prompt.ts +0 -39
  169. package/src/orch/registry.ts +0 -168
  170. package/src/orch/runtime.ts +0 -1041
  171. package/src/orch/tools.ts +0 -190
  172. package/src/orch/transcript.ts +0 -186
  173. package/src/prefs/agent-import.ts +0 -245
  174. package/src/prefs/config.ts +0 -1017
  175. package/src/prefs/import-discovery.ts +0 -643
  176. package/src/prefs/models.ts +0 -74
  177. package/src/prefs/settings.ts +0 -614
  178. package/src/types.ts +0 -271
  179. package/src/ui/agent-loader.ts +0 -98
  180. package/src/ui/agent-navigation-editor.ts +0 -233
  181. package/src/ui/cost-footer.ts +0 -230
  182. package/src/ui/dialog.ts +0 -678
  183. package/src/ui/import-picker.ts +0 -231
  184. package/src/ui/live-agent-view.ts +0 -600
  185. package/src/ui/model-picker.ts +0 -701
  186. package/src/ui/settings-ui.ts +0 -830
  187. package/src/ui/status-ui.ts +0 -628
  188. package/src/ui/thread-tree.ts +0 -173
  189. package/src/ui/tool-picker.ts +0 -398
  190. package/src/ui/transcript-tool.ts +0 -142
  191. package/src/ui/ui.ts +0 -1407
package/src/orch/paths.ts DELETED
@@ -1,73 +0,0 @@
1
- import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
-
3
- const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
4
- export function canonicalPath(value: string, caller = "/root"): string {
5
- if (!value || value !== value.trim())
6
- throw new Error("Agent path must not be empty or contain surrounding whitespace");
7
- const path = value.startsWith("/") ? value : `${caller}/${value}`;
8
- const parts = path.slice(1).split("/");
9
- if (!parts.every((part) => SEGMENT.test(part)) || parts.length > 32) {
10
- throw new Error(
11
- "Agent paths require slash-separated names (letters, digits, - or _); no dot segments, escapes, empty segments or trailing slash",
12
- );
13
- }
14
- return path;
15
- }
16
- export function parentPath(path: string): string | null {
17
- canonicalPath(path);
18
- const last = path.lastIndexOf("/");
19
- return last === 0 ? null : path.slice(0, last);
20
- }
21
- export function isDescendant(path: string, ancestor: string): boolean {
22
- return path.startsWith(`${ancestor}/`);
23
- }
24
-
25
- /** Snapshot conversation, not the parent's prompt/loadout; retain only matched tool exchanges. */
26
- export function inheritContext(messages: readonly AgentMessage[]): AgentMessage[] {
27
- const copy = structuredClone(messages);
28
- const matchedCalls = new Set<string>();
29
- const matchedResults = new Set<number>();
30
- const pending = new Map<string, { messageIndex: number; blockIndex: number }[]>();
31
-
32
- for (const [messageIndex, message] of copy.entries()) {
33
- if (message.role === "assistant") {
34
- if (message.stopReason === "error" || message.stopReason === "aborted") continue;
35
- for (const [blockIndex, block] of message.content.entries()) {
36
- if (block.type !== "toolCall") continue;
37
- const queue = pending.get(block.id);
38
- const occurrence = { messageIndex, blockIndex };
39
- if (queue) queue.push(occurrence);
40
- else pending.set(block.id, [occurrence]);
41
- }
42
- continue;
43
- }
44
- if (message.role !== "toolResult") continue;
45
- const queue = pending.get(message.toolCallId);
46
- const occurrence = queue?.shift();
47
- if (!occurrence) continue;
48
- matchedCalls.add(`${occurrence.messageIndex}:${occurrence.blockIndex}`);
49
- matchedResults.add(messageIndex);
50
- if (queue && !queue.length) pending.delete(message.toolCallId);
51
- }
52
-
53
- return copy.flatMap((message, messageIndex): AgentMessage[] => {
54
- // Only the system prompt/loadout is replaced; custom and shell messages are real conversation context.
55
- if (message.role === "system") return [];
56
- if (message.role === "assistant") {
57
- if (message.stopReason === "error" || message.stopReason === "aborted") return [];
58
- message.content = message.content.filter(
59
- (block, blockIndex) =>
60
- block.type !== "toolCall" || matchedCalls.has(`${messageIndex}:${blockIndex}`),
61
- );
62
- if (!message.content.length) return [];
63
- // A tools-only assistant without remaining calls should not claim a toolUse stop.
64
- if (
65
- message.stopReason === "toolUse" &&
66
- !message.content.some((block) => block.type === "toolCall")
67
- )
68
- message.stopReason = "stop";
69
- }
70
- if (message.role === "toolResult" && !matchedResults.has(messageIndex)) return [];
71
- return [message];
72
- });
73
- }
@@ -1,39 +0,0 @@
1
- import type { ManagerSettings } from "../prefs/settings.ts";
2
- import { checklistGuidance } from "./checklist-integration.ts";
3
-
4
- export function delegationGuidance(canSpawnChildren: boolean): string {
5
- return canSpawnChildren
6
- ? "You may spawn subagents of your own if useful, subject to your tools, assigned scope, and shared concurrency limits."
7
- : "You are at the maximum agent depth and cannot spawn any more subagents. Complete your assigned work yourself.";
8
- }
9
-
10
- /** Root-only guidance: child SDK sessions use their own worker prompt. */
11
- export function subagentPrompt(
12
- settings: ManagerSettings,
13
- /** Caller-verified pi-checklist eligibility; ignored unless the Labs opt-in is also on. */
14
- checklistEligible = false,
15
- ): string | undefined {
16
- if (settings.subagentMode === "off") return undefined;
17
- const policy =
18
- settings.subagentMode === "orchestration"
19
- ? "Orchestration mode: /root only coordinates. Delegate every user task to subagents, even small or sequential tasks. Do not inspect/edit files, run commands, research, or execute task work yourself. Only plan, assign, monitor, clarify, and synthesize subagent results for the user. This restriction applies only to /root; subagents execute the work."
20
- : "Opportunistic mode: do ordinary tasks yourself. Delegate only when work can be parallelized, is long-running, or is very large; do not spawn agents for small, quick, straightforward tasks.";
21
- const waitingPolicy =
22
- settings.subagentMode === "orchestration"
23
- ? "As an orchestrator, you must NEVER be blocked waiting for subagents. ALWAYS start every subagent in async/background mode with wait:false, even for small or sequential tasks. NEVER call agent_wait or use a foreground spawn. End your turn after assigning work so you remain free to talk to the user while subagents work. Check agent_status and collect available results with agent_output without blocking; if results are not ready, report that and leave the conversation free."
24
- : "For independent parallel work, spawn all siblings with wait:false before agent_wait. Only await synchronous tasks whose results are needed in the current turn. For long-running tasks, create background agents with wait:false and do not immediately call agent_wait; end your turn so you remain free to talk to the user while they work. Await background results when the user asks you to collect them.";
25
- return [
26
- "## pi-subagent",
27
- "You are /root, the main conversation (L1).",
28
- policy,
29
- "Call agent_types before choosing a type. Use task-based kebab-case paths, not type names. Choose context via agent_spawn path: /root/task forks the lexical parent's conversation; /task starts fresh with no inherited history. Use fresh agents for adversarial review or clean-slate research; give them a self-contained task without the current thread's conclusions.",
30
- waitingPolicy,
31
- 'Use agent_status to inspect and agent_output for full results. Completion, failure or stop of a wait:false agent is delivered to you as a message event that starts a new turn when you are idle (with Final Recap on, once after all outstanding async agents have finished). Pass timeoutMs to agent_spawn to get a status event if a child runs long; the child is not killed. Valid range 30000–300000 ms; omit for no timeout. To extend a running background agent\'s reporting timer, before or after a timeout event, call agent_steer({path: "/root/task", timeoutMs: 120000}) with message omitted entirely. This resets the timer from now (replacing any pending timer), without sending input, interrupting or resuming the agent; it requires the agent to still be running. After re-arming, end your turn to remain available while it works. For other timeout responses, follow the waiting policy above, send steering input or stop the agent.',
32
- "Use agent_steer to send input or resume retained sessions. Paused agents have no final answer; completed agents hand back results. Both retain their session.",
33
- `Maximum depth: ${settings.maxLevels} levels including L1. Shared concurrency: ${settings.maxConcurrent} active threads; waiting parents count.`,
34
- delegationGuidance(settings.maxLevels > 1),
35
- ...(settings.checklistIntegration && checklistEligible
36
- ? [checklistGuidance(settings.subagentMode)]
37
- : []),
38
- ].join("\n");
39
- }
@@ -1,168 +0,0 @@
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
- }