pi-subagent-manager 0.0.0-stage → 0.1.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/src/index.ts ADDED
@@ -0,0 +1,216 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { buildSessionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { ConfigStore } from "./config.ts";
5
+ import { ThreadManager } from "./manager.ts";
6
+ import { createDriverFactory } from "./runtime.ts";
7
+ import { agentTools } from "./tools.ts";
8
+ import { editAgentTypes, showThreads, updateWidget } from "./ui.ts";
9
+ import type { SavedThread, ThreadEvent } from "./types.ts";
10
+
11
+ const REGISTRY_ENTRY = "pi-subagent:registry:v1";
12
+ const ROOT_MAILBOX_ENTRY = "pi-subagent:root-mailbox:v1";
13
+ type RootNotification = {
14
+ rootSessionId: string;
15
+ content: string;
16
+ details: { mailboxId: string; path: string; state: string };
17
+ };
18
+
19
+ export default function piSubagent(pi: ExtensionAPI): void {
20
+ let context: ExtensionContext | undefined;
21
+ let store = new ConfigStore({
22
+ cwd: process.cwd(),
23
+ agentDir: getAgentDir(),
24
+ includeProject: false,
25
+ });
26
+ let manager: ThreadManager | undefined;
27
+ let generation = 0;
28
+ let persistenceSignature = "";
29
+ const requireManager = () => {
30
+ if (!manager) throw new Error("Subagent threads are not initialized; start a Pi session first");
31
+ return manager;
32
+ };
33
+ const requireContext = () => {
34
+ if (!context) throw new Error("No active Pi session");
35
+ return context;
36
+ };
37
+ const persist = () => {
38
+ if (!manager) return;
39
+ const threads = manager.saved();
40
+ const signature = JSON.stringify(threads);
41
+ if (signature !== persistenceSignature) {
42
+ pi.appendEntry(REGISTRY_ENTRY, {
43
+ version: 1,
44
+ rootSessionId: requireContext().sessionManager.getSessionId(),
45
+ threads,
46
+ });
47
+ persistenceSignature = signature;
48
+ }
49
+ };
50
+ const warnDelivery = (error: unknown) => {
51
+ const message = error instanceof Error ? error.message : String(error);
52
+ context?.ui.notify(`Subagent delivery failed: ${message}`, "warning");
53
+ };
54
+ const sendRootNotification = (notification: RootNotification) =>
55
+ pi.sendMessage(
56
+ {
57
+ customType: "pi-subagent:update",
58
+ content: notification.content,
59
+ display: true,
60
+ details: notification.details,
61
+ },
62
+ { triggerTurn: false },
63
+ );
64
+ const restoreRootMailbox = (ctx: ExtensionContext) => {
65
+ const entries = ctx.sessionManager.getBranch();
66
+ const delivered = new Set(
67
+ entries.flatMap((entry) => {
68
+ if (entry.type !== "custom_message" || entry.customType !== "pi-subagent:update") return [];
69
+ const id = (entry.details as { mailboxId?: unknown } | undefined)?.mailboxId;
70
+ return typeof id === "string" ? [id] : [];
71
+ }),
72
+ );
73
+ for (const entry of entries) {
74
+ if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY) continue;
75
+ const notification = entry.data as RootNotification | undefined;
76
+ if (
77
+ notification?.rootSessionId === ctx.sessionManager.getSessionId() &&
78
+ typeof notification.content === "string" &&
79
+ typeof notification.details?.mailboxId === "string" &&
80
+ !delivered.has(notification.details.mailboxId)
81
+ ) {
82
+ sendRootNotification(notification);
83
+ delivered.add(notification.details.mailboxId);
84
+ }
85
+ }
86
+ };
87
+ const delivery = (event: ThreadEvent) => {
88
+ if (event.kind === "change") return;
89
+ const thread = event.thread;
90
+ const message =
91
+ event.kind === "update"
92
+ ? `Progress from ${thread.path}: ${event.message}`
93
+ : thread.state === "completed"
94
+ ? `Agent ${thread.path} completed. Final answer:\n${thread.output?.slice(0, 16000) ?? "(no text)"}${(thread.output?.length ?? 0) > 16000 ? "\n[Output truncated; use agent_output for more.]" : ""}`
95
+ : `Agent ${thread.path} is ${thread.state}: ${thread.status}. ${thread.state === "paused" ? "No answer handback; send input to resume the same session." : "Session retained for further input."}`;
96
+ try {
97
+ if (event.recipient === "/root") {
98
+ const notification: RootNotification = {
99
+ rootSessionId: requireContext().sessionManager.getSessionId(),
100
+ content: message,
101
+ details: { mailboxId: randomUUID(), path: thread.path, state: thread.state },
102
+ };
103
+ // Root sendMessage can defer while streaming too. Accept durably before queueing;
104
+ // the eventual transcript message carries its ID for branch-local recovery.
105
+ pi.appendEntry(ROOT_MAILBOX_ENTRY, notification);
106
+ sendRootNotification(notification);
107
+ } else void requireManager().deliver(event.recipient, message).catch(warnDelivery);
108
+ } catch (error) {
109
+ warnDelivery(error);
110
+ }
111
+ };
112
+
113
+ for (const tool of agentTools(requireManager, "/root", () => store.list())) pi.registerTool(tool);
114
+ pi.on("before_agent_start", async (event) => ({
115
+ systemPrompt: `${event.systemPrompt}\n\n## pi-subagent\nYou are /root. Thread paths determine context ancestry, independently of agent type. Children can pause WITHOUT handing back an answer; completed and paused sessions can both receive more work via agent_steer. Working child threads appear above the footer. Available types:\n${store
116
+ .list()
117
+ .map((type) => `- ${type.name}: ${type.description}`)
118
+ .join(
119
+ "\n",
120
+ )}\nUse agent_status to inspect and agent_wait to wait. Detached notifications do not automatically resume your turn.`,
121
+ }));
122
+
123
+ const attachSession = async (ctx: ExtensionContext) => {
124
+ const token = ++generation;
125
+ // session_start already belongs to the replacement session: never append the old registry here.
126
+ if (manager) await manager.shutdown();
127
+ context = ctx;
128
+ store = new ConfigStore({
129
+ cwd: ctx.cwd,
130
+ agentDir: getAgentDir(),
131
+ includeProject: ctx.isProjectTrusted(),
132
+ });
133
+ persistenceSignature = "";
134
+ const instance = new ThreadManager({
135
+ createDriver: createDriverFactory(requireContext),
136
+ rootSnapshot: () => buildSessionContext(requireContext().sessionManager.getBranch()).messages,
137
+ getType: (name) => store.get(name),
138
+ toolsFor: (path) => agentTools(requireManager, path, () => store.list()),
139
+ onEvent: (event) => {
140
+ if (token !== generation) return;
141
+ updateWidget(requireContext(), requireManager().list());
142
+ persist();
143
+ delivery(event);
144
+ },
145
+ });
146
+ manager = instance;
147
+ const entries = ctx.sessionManager.getBranch();
148
+ const entry = [...entries]
149
+ .reverse()
150
+ .find((item) => item.type === "custom" && item.customType === REGISTRY_ENTRY);
151
+ if (entry?.type === "custom") {
152
+ try {
153
+ const data = entry.data as {
154
+ version: number;
155
+ rootSessionId: string;
156
+ threads: SavedThread[];
157
+ };
158
+ if (data.version !== 1 || !Array.isArray(data.threads))
159
+ throw new Error("Invalid registry format");
160
+ // Forked parents own a new registry; they must not share writable child transcripts.
161
+ if (data.rootSessionId === ctx.sessionManager.getSessionId())
162
+ instance.restore(data.threads);
163
+ else persist();
164
+ } catch (error) {
165
+ ctx.ui.notify(`Could not restore subagent registry: ${String(error)}`, "error");
166
+ }
167
+ }
168
+ restoreRootMailbox(ctx);
169
+ updateWidget(ctx, requireManager().list());
170
+ if (store.diagnostics.length) ctx.ui.notify(store.diagnostics.join("\n"), "warning");
171
+ };
172
+ pi.on("session_start", async (_event, ctx) => attachSession(ctx));
173
+ pi.on("session_tree", async (_event, ctx) => attachSession(ctx));
174
+ const stopWorkingThreads = async () => {
175
+ if (!manager) return;
176
+ for (const thread of manager.list()) {
177
+ const state = manager.get(thread.path).state;
178
+ if (state === "starting" || state === "running") await manager.stop("/root", thread.path);
179
+ }
180
+ };
181
+ // Finish old-thread cancellation while appendEntry still points to the old branch/session.
182
+ pi.on("session_before_tree", stopWorkingThreads);
183
+ pi.on("session_before_switch", stopWorkingThreads);
184
+ pi.on("session_before_fork", stopWorkingThreads);
185
+ pi.on("session_shutdown", async () => {
186
+ persist();
187
+ generation++;
188
+ await manager?.shutdown();
189
+ manager = undefined;
190
+ context = undefined;
191
+ });
192
+ pi.registerCommand("agents", {
193
+ description: "Inspect/resume retained threads, edit agent types or reload configuration",
194
+ getArgumentCompletions: (prefix) =>
195
+ ["types", "reload", "thread"]
196
+ .filter((value) => value.startsWith(prefix))
197
+ .map((value) => ({ value, label: value })),
198
+ handler: async (args, ctx) => {
199
+ const [command, ...rest] = args.trim().split(/\s+/);
200
+ if (command === "types") {
201
+ await editAgentTypes(ctx, store);
202
+ store.reload();
203
+ } else if (command === "reload") {
204
+ store.reload();
205
+ ctx.ui.notify(
206
+ store.diagnostics.length
207
+ ? store.diagnostics.join("\n")
208
+ : `Loaded ${store.list().length} agent types`,
209
+ store.diagnostics.length ? "warning" : "info",
210
+ );
211
+ } else if (!command || command === "thread") {
212
+ await showThreads(ctx, requireManager().scope("/root"), rest.join(" ") || undefined);
213
+ } else ctx.ui.notify("Usage: /agents [types | reload | thread /root/name]", "warning");
214
+ },
215
+ });
216
+ }
package/src/mailbox.ts ADDED
@@ -0,0 +1,261 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { SessionEntry, SessionManager } from "@earendil-works/pi-coding-agent";
3
+
4
+ export const LEGACY_QUEUE_TYPE = "pi-subagent:queue:v1";
5
+ const ACCEPTED_TYPE = "pi-subagent:mailbox:accepted:v2";
6
+ const CONSUMED_TYPE = "pi-subagent:mailbox:consumed:v2";
7
+ const MIGRATION_TYPE = "pi-subagent:mailbox:migration:v2";
8
+ export const MAILBOX_FIELD = "piSubagentMailbox";
9
+ export const BOOTSTRAP_MESSAGE = "Subagent session initialized; awaiting parent input.";
10
+
11
+ export type AcceptedKind = "steer" | "followUp" | "update";
12
+
13
+ export interface AcceptedLedgerEntry {
14
+ id: string;
15
+ kind: AcceptedKind;
16
+ content: string;
17
+ timestamp: number;
18
+ }
19
+
20
+ interface ConsumedLedgerEntry {
21
+ id: string;
22
+ messageEntryId: string;
23
+ }
24
+
25
+ interface LegacyQueueSnapshot {
26
+ steering?: unknown;
27
+ followUp?: unknown;
28
+ }
29
+
30
+ interface MigrationMarker {
31
+ sourceEntryId: string;
32
+ }
33
+
34
+ interface MailboxMarker {
35
+ id: string;
36
+ kind: AcceptedKind | "bootstrap";
37
+ }
38
+
39
+ const isObject = (value: unknown): value is Record<string, unknown> =>
40
+ typeof value === "object" && value !== null;
41
+
42
+ const isAcceptedEntry = (
43
+ entry: SessionEntry,
44
+ ): entry is SessionEntry & { data: AcceptedLedgerEntry } =>
45
+ entry.type === "custom" &&
46
+ entry.customType === ACCEPTED_TYPE &&
47
+ isAcceptedLedgerEntry(entry.data);
48
+
49
+ const isConsumedEntry = (
50
+ entry: SessionEntry,
51
+ ): entry is SessionEntry & { data: ConsumedLedgerEntry } =>
52
+ entry.type === "custom" &&
53
+ entry.customType === CONSUMED_TYPE &&
54
+ isConsumedLedgerEntry(entry.data);
55
+
56
+ const isMigrationEntry = (entry: SessionEntry, sourceEntryId: string): boolean =>
57
+ entry.type === "custom" &&
58
+ entry.customType === MIGRATION_TYPE &&
59
+ isObject(entry.data) &&
60
+ entry.data.sourceEntryId === sourceEntryId;
61
+
62
+ const isAcceptedKind = (value: unknown): value is AcceptedKind =>
63
+ value === "steer" || value === "followUp" || value === "update";
64
+
65
+ const isAcceptedLedgerEntry = (value: unknown): value is AcceptedLedgerEntry =>
66
+ isObject(value) &&
67
+ typeof value.id === "string" &&
68
+ isAcceptedKind(value.kind) &&
69
+ typeof value.content === "string" &&
70
+ typeof value.timestamp === "number";
71
+
72
+ const isConsumedLedgerEntry = (value: unknown): value is ConsumedLedgerEntry =>
73
+ isObject(value) && typeof value.id === "string" && typeof value.messageEntryId === "string";
74
+
75
+ const getMailboxMarker = (value: unknown): MailboxMarker | undefined => {
76
+ if (!isObject(value)) return undefined;
77
+ const marker = value[MAILBOX_FIELD];
78
+ if (!isObject(marker) || typeof marker.id !== "string") return undefined;
79
+ if (
80
+ marker.kind !== "steer" &&
81
+ marker.kind !== "followUp" &&
82
+ marker.kind !== "update" &&
83
+ marker.kind !== "bootstrap"
84
+ )
85
+ return undefined;
86
+ return { id: marker.id, kind: marker.kind };
87
+ };
88
+
89
+ const normalizeLegacyQueue = (
90
+ value: unknown,
91
+ ): { steering: string[]; followUp: string[] } | undefined => {
92
+ if (!isObject(value)) return undefined;
93
+ const steering = value.steering;
94
+ const followUp = value.followUp;
95
+ if (
96
+ !Array.isArray(steering) ||
97
+ !steering.every((text) => typeof text === "string") ||
98
+ !Array.isArray(followUp) ||
99
+ !followUp.every((text) => typeof text === "string")
100
+ ) {
101
+ return undefined;
102
+ }
103
+ return { steering: [...steering], followUp: [...followUp] };
104
+ };
105
+
106
+ const getAcceptedIdFromEntry = (entry: SessionEntry): string | undefined => {
107
+ if (entry.type === "message" && entry.message.role === "user") {
108
+ return getMailboxMarker(entry.message)?.id;
109
+ }
110
+ if (entry.type === "custom_message") {
111
+ return getMailboxMarker(entry.details)?.id;
112
+ }
113
+ return undefined;
114
+ };
115
+
116
+ export const buildQueuedUserMessage = (entry: AcceptedLedgerEntry) => ({
117
+ role: "user" as const,
118
+ content: [{ type: "text" as const, text: entry.content }],
119
+ timestamp: entry.timestamp,
120
+ [MAILBOX_FIELD]: { id: entry.id, kind: entry.kind },
121
+ });
122
+
123
+ export const buildUpdateDetails = (entry: AcceptedLedgerEntry) => ({
124
+ [MAILBOX_FIELD]: { id: entry.id, kind: entry.kind },
125
+ });
126
+
127
+ export const buildBootstrapMessage = (timestamp = Date.now()) => ({
128
+ role: "user" as const,
129
+ content: [{ type: "text" as const, text: BOOTSTRAP_MESSAGE }],
130
+ timestamp,
131
+ [MAILBOX_FIELD]: { id: `bootstrap:${timestamp}`, kind: "bootstrap" as const },
132
+ });
133
+
134
+ export class DurableMailbox {
135
+ private readonly accepted = new Map<string, AcceptedLedgerEntry>();
136
+ private readonly consumed = new Set<string>();
137
+ private readonly enqueued = new Set<string>();
138
+
139
+ constructor(private readonly sessionManager: SessionManager) {
140
+ this.migrateLegacyQueue();
141
+ this.restore();
142
+ }
143
+
144
+ accept(kind: AcceptedKind, content: string, timestamp = Date.now()): AcceptedLedgerEntry {
145
+ return this.appendAccepted({ id: randomUUID(), kind, content, timestamp });
146
+ }
147
+
148
+ pending(): AcceptedLedgerEntry[] {
149
+ return [...this.accepted.values()].filter((entry) => !this.consumed.has(entry.id));
150
+ }
151
+
152
+ replayablePending(): AcceptedLedgerEntry[] {
153
+ return this.pending().filter((entry) => !this.enqueued.has(entry.id));
154
+ }
155
+
156
+ markEnqueued(id: string): void {
157
+ this.enqueued.add(id);
158
+ }
159
+
160
+ clearQueuedInputs(): void {
161
+ for (const entry of this.accepted.values()) {
162
+ if (entry.kind === "steer" || entry.kind === "followUp") this.enqueued.delete(entry.id);
163
+ }
164
+ }
165
+
166
+ private consumeAppended(messageEntryId: string, markerSource: unknown): void {
167
+ const id = getMailboxMarker(markerSource)?.id;
168
+ if (!id || !this.accepted.has(id) || this.consumed.has(id)) return;
169
+ this.sessionManager.appendCustomEntry(CONSUMED_TYPE, { id, messageEntryId });
170
+ this.consumed.add(id);
171
+ this.enqueued.delete(id);
172
+ }
173
+
174
+ wrapAppends(onCheckpoint: () => void): () => void {
175
+ const originalAppendMessage = this.sessionManager.appendMessage.bind(this.sessionManager);
176
+ const originalAppendCustomMessageEntry = this.sessionManager.appendCustomMessageEntry.bind(
177
+ this.sessionManager,
178
+ );
179
+
180
+ this.sessionManager.appendMessage = (message) => {
181
+ const entryId = originalAppendMessage(message);
182
+ this.consumeAppended(entryId, message);
183
+ onCheckpoint();
184
+ return entryId;
185
+ };
186
+
187
+ this.sessionManager.appendCustomMessageEntry = (customType, content, display, details) => {
188
+ const entryId = originalAppendCustomMessageEntry(customType, content, display, details);
189
+ this.consumeAppended(entryId, details);
190
+ onCheckpoint();
191
+ return entryId;
192
+ };
193
+
194
+ return () => {
195
+ this.sessionManager.appendMessage = originalAppendMessage;
196
+ this.sessionManager.appendCustomMessageEntry = originalAppendCustomMessageEntry;
197
+ };
198
+ }
199
+
200
+ private appendAccepted(entry: AcceptedLedgerEntry): AcceptedLedgerEntry {
201
+ this.sessionManager.appendCustomEntry(ACCEPTED_TYPE, entry);
202
+ this.accepted.set(entry.id, entry);
203
+ return entry;
204
+ }
205
+
206
+ private migrateLegacyQueue(): void {
207
+ const branch = this.sessionManager.getBranch();
208
+ const legacy = [...branch]
209
+ .reverse()
210
+ .find((entry) => entry.type === "custom" && entry.customType === LEGACY_QUEUE_TYPE);
211
+ if (!legacy || branch.some((entry) => isMigrationEntry(entry, legacy.id))) return;
212
+ const queue = normalizeLegacyQueue(
213
+ (legacy as SessionEntry & { data?: LegacyQueueSnapshot }).data,
214
+ );
215
+ if (!queue) return;
216
+ const existingIds = new Set<string>();
217
+ for (const entry of branch) {
218
+ if (isAcceptedEntry(entry) || isConsumedEntry(entry)) existingIds.add(entry.data.id);
219
+ const acceptedId = getAcceptedIdFromEntry(entry);
220
+ if (acceptedId) existingIds.add(acceptedId);
221
+ }
222
+ const appendLegacyAccepted = (kind: AcceptedKind, content: string, occurrenceIndex: number) => {
223
+ const accepted = {
224
+ id: `legacy:${legacy.id}:${kind}:${occurrenceIndex}`,
225
+ kind,
226
+ content,
227
+ timestamp: Date.parse(legacy.timestamp),
228
+ } satisfies AcceptedLedgerEntry;
229
+ if (existingIds.has(accepted.id)) return;
230
+ this.appendAccepted(accepted);
231
+ existingIds.add(accepted.id);
232
+ };
233
+ queue.steering.forEach((content, occurrenceIndex) => {
234
+ appendLegacyAccepted("steer", content, occurrenceIndex);
235
+ });
236
+ queue.followUp.forEach((content, occurrenceIndex) => {
237
+ appendLegacyAccepted("followUp", content, occurrenceIndex);
238
+ });
239
+ this.sessionManager.appendCustomEntry(MIGRATION_TYPE, {
240
+ sourceEntryId: legacy.id,
241
+ } satisfies MigrationMarker);
242
+ }
243
+
244
+ private restore(): void {
245
+ this.accepted.clear();
246
+ this.consumed.clear();
247
+ this.enqueued.clear();
248
+ for (const entry of this.sessionManager.getBranch()) {
249
+ if (isAcceptedEntry(entry)) {
250
+ this.accepted.set(entry.data.id, entry.data);
251
+ continue;
252
+ }
253
+ if (isConsumedEntry(entry)) {
254
+ this.consumed.add(entry.data.id);
255
+ continue;
256
+ }
257
+ const transcriptId = getAcceptedIdFromEntry(entry);
258
+ if (transcriptId) this.consumed.add(transcriptId);
259
+ }
260
+ }
261
+ }