@howaboua/pi-shepherdr 0.2.6 → 0.2.7

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.
@@ -0,0 +1,283 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import type {
6
+ ContextSharingService,
7
+ SharedContextRequest,
8
+ SharedContextResult,
9
+ } from "@howaboua/pi-codex-conversion/context-sharing";
10
+ import type { AgentFleet, ConnectedMachine } from "./fleet.js";
11
+ import { sessionPath } from "./herdr.js";
12
+ import {
13
+ listenContext,
14
+ requestContext,
15
+ sessionContextPath,
16
+ } from "./remote/shepherdr-context.mjs";
17
+ import type { PaneInfo } from "./types.js";
18
+
19
+ const MEMBER_ENTRY = "herdr-context-child";
20
+ interface Member {
21
+ agentName: string;
22
+ sessionId: string;
23
+ threadId: string;
24
+ machine: string;
25
+ sessionFile: string;
26
+ }
27
+ interface Routing {
28
+ transport: "shepherdr";
29
+ parent: string;
30
+ }
31
+ interface ContextEnvelope {
32
+ operation: "context";
33
+ request: SharedContextRequest;
34
+ visited: string[];
35
+ }
36
+
37
+ export class SharedAgentContext {
38
+ private readonly pi: ExtensionAPI;
39
+ private readonly fleet: AgentFleet;
40
+ private readonly getService: () => ContextSharingService | undefined;
41
+ private running = false;
42
+
43
+ constructor(
44
+ pi: ExtensionAPI,
45
+ fleet: AgentFleet,
46
+ getService: () => ContextSharingService | undefined,
47
+ ) {
48
+ this.pi = pi;
49
+ this.fleet = fleet;
50
+ this.getService = getService;
51
+ pi.on("agent_start", () => {
52
+ this.running = true;
53
+ });
54
+ pi.on("agent_settled", () => {
55
+ this.running = false;
56
+ });
57
+ }
58
+
59
+ async handle(
60
+ ctx: ExtensionContext,
61
+ value: unknown,
62
+ signal?: AbortSignal,
63
+ ): Promise<unknown> {
64
+ if (!value || typeof value !== "object")
65
+ throw new Error("Invalid shared context request");
66
+ const service = this.getService();
67
+ const identity = service?.describe(ctx);
68
+ if ("operation" in value && value.operation === "bind") {
69
+ if (!service || !identity) return null;
70
+ return service.bind(ctx, "binding" in value ? value.binding : undefined);
71
+ }
72
+ if (!identity || !service)
73
+ throw new Error("Context sharing is unavailable in this session");
74
+ const envelope = value as Partial<ContextEnvelope>;
75
+ const request = envelope.request;
76
+ if (
77
+ envelope.operation !== "context" ||
78
+ !request ||
79
+ request.sessionId !== identity.sessionId ||
80
+ typeof request.agentName !== "string" ||
81
+ !Array.isArray(envelope.visited) ||
82
+ envelope.visited.some((item) => typeof item !== "string") ||
83
+ envelope.visited.length >= 64 ||
84
+ envelope.visited.includes(identity.threadId)
85
+ )
86
+ throw new Error("Invalid shared context route or session family");
87
+ if (identity.agentName === request.agentName) {
88
+ if (!ctx.isIdle() && !this.running)
89
+ throw new Error(
90
+ "Context owner is changing branches; retry after it settles",
91
+ );
92
+ return service.execute(ctx, request, signal);
93
+ }
94
+ const forwarded = {
95
+ ...envelope,
96
+ visited: [...envelope.visited, identity.threadId],
97
+ };
98
+ const member = ctx.sessionManager.getEntries().findLast((entry) => {
99
+ if (entry.type !== "custom" || entry.customType !== MEMBER_ENTRY)
100
+ return false;
101
+ const candidate = entry.data as Member;
102
+ return (
103
+ candidate?.threadId === identity.threadId &&
104
+ candidate.sessionId === identity.sessionId &&
105
+ typeof candidate.agentName === "string" &&
106
+ (request.agentName === candidate.agentName ||
107
+ request.agentName.startsWith(`${candidate.agentName}/`))
108
+ );
109
+ });
110
+ if (member?.type === "custom") {
111
+ const child = member.data as Member;
112
+ if (
113
+ typeof child.machine !== "string" ||
114
+ typeof child.sessionFile !== "string" ||
115
+ !child.sessionFile
116
+ )
117
+ throw new Error("Invalid saved shared context route");
118
+ const runtime = this.fleet.connected(child.machine);
119
+ return runtime.client.requestContext(
120
+ sessionContextPath(child.sessionFile),
121
+ forwarded,
122
+ signal,
123
+ );
124
+ }
125
+ const routing = identity.routing as Partial<Routing> | undefined;
126
+ if (
127
+ routing?.transport === "shepherdr" &&
128
+ typeof routing.parent === "string"
129
+ )
130
+ return requestContext(routing.parent, forwarded, signal);
131
+ throw new Error(
132
+ `No shared context agent ${request.agentName} in this session family`,
133
+ );
134
+ }
135
+
136
+ async prepare(
137
+ ctx: ExtensionContext,
138
+ runtime: ConnectedMachine,
139
+ name: string,
140
+ args: readonly string[] = [],
141
+ ) {
142
+ const service = this.getService();
143
+ if (!service?.canCreateChild(ctx)) return undefined;
144
+ const parent = service.describe(ctx);
145
+ if (!parent) return undefined;
146
+ if (
147
+ args.some((arg) =>
148
+ /^(?:--(?:session(?:-id)?|continue|resume|no-session|fork)(?:=|$)|-[cr]$)/.test(
149
+ arg,
150
+ ),
151
+ )
152
+ )
153
+ throw new Error(
154
+ "Shared context spawn cannot use profile session-selection arguments; use assign for existing agents",
155
+ );
156
+ const parentFile = ctx.sessionManager.getSessionFile();
157
+ if (!parentFile)
158
+ throw new Error(
159
+ "Shared context spawn requires a saved controller session",
160
+ );
161
+ const routing: Routing | undefined =
162
+ parent.storage === "session"
163
+ ? {
164
+ transport: "shepherdr",
165
+ parent: runtime.local
166
+ ? sessionContextPath(parentFile)
167
+ : runtime.client.contextRelayPath(),
168
+ }
169
+ : undefined;
170
+ const { binding, adopt } = await service.createChild(ctx, {
171
+ name,
172
+ ...(routing ? { routing } : {}),
173
+ });
174
+ return {
175
+ accept: async (agent: PaneInfo) => {
176
+ const sessionFile = sessionPath(agent);
177
+ if (!sessionFile)
178
+ throw new Error("Spawned agent has no native Pi session path");
179
+ const value = await runtime.client.requestContext(
180
+ sessionContextPath(sessionFile),
181
+ { operation: "bind", binding },
182
+ );
183
+ if (!value)
184
+ return {
185
+ warning:
186
+ "Spawned without shared context: the target needs Codex conversion with notes-based continuity",
187
+ };
188
+ if (
189
+ typeof value !== "object" ||
190
+ !("sessionId" in value) ||
191
+ value.sessionId !== binding.sessionId ||
192
+ !("agentName" in value) ||
193
+ value.agentName !== binding.agentName ||
194
+ !("storage" in value) ||
195
+ value.storage !== binding.storage ||
196
+ (binding.accountScope !== undefined &&
197
+ (!("accountScope" in value) ||
198
+ value.accountScope !== binding.accountScope))
199
+ )
200
+ throw new Error(
201
+ "Spawned agent did not adopt its shared context identity and storage mode",
202
+ );
203
+ if (ctx.sessionManager.getSessionId() !== parent.threadId)
204
+ throw new Error("Controller session changed during spawn");
205
+ await adopt();
206
+ this.pi.appendEntry<Member>(MEMBER_ENTRY, {
207
+ agentName: binding.agentName,
208
+ sessionId: parent.sessionId,
209
+ threadId: parent.threadId,
210
+ machine: runtime.machine,
211
+ sessionFile,
212
+ });
213
+ return { agentName: binding.agentName };
214
+ },
215
+ };
216
+ }
217
+ }
218
+
219
+ export async function registerSharedAgentContext(
220
+ pi: ExtensionAPI,
221
+ fleet: AgentFleet,
222
+ ): Promise<SharedAgentContext> {
223
+ let api:
224
+ | typeof import("@howaboua/pi-codex-conversion/context-sharing")
225
+ | undefined;
226
+ try {
227
+ api = await import("@howaboua/pi-codex-conversion/context-sharing");
228
+ } catch (error) {
229
+ const failure = error as { code?: string; message?: string };
230
+ const missing = failure.message?.match(
231
+ /Cannot find (?:package|module) ['"]([^'"]+)['"]/,
232
+ )?.[1];
233
+ const module = "@howaboua/pi-codex-conversion/context-sharing";
234
+ const unavailable =
235
+ ((failure.code === "ERR_MODULE_NOT_FOUND" ||
236
+ failure.code === "MODULE_NOT_FOUND") &&
237
+ (missing === "@howaboua/pi-codex-conversion" ||
238
+ missing === module ||
239
+ missing?.endsWith(`/${module}`))) ||
240
+ (failure.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" &&
241
+ failure.message?.includes("@howaboua/pi-codex-conversion") &&
242
+ failure.message.includes("./context-sharing"));
243
+ if (!unavailable)
244
+ throw new Error(
245
+ "Update pi-codex-conversion to use shared agent context",
246
+ { cause: error },
247
+ );
248
+ }
249
+ const connection = api?.connectCodexContextSharing(pi);
250
+ const shared = new SharedAgentContext(pi, fleet, () => connection?.service);
251
+ let close: (() => Promise<void>) | undefined;
252
+ let unregister: (() => void) | undefined;
253
+ pi.on("session_start", async (_event, ctx) => {
254
+ await close?.();
255
+ close = undefined;
256
+ unregister?.();
257
+ unregister = connection?.service?.registerRouter(
258
+ async (context, request, signal) =>
259
+ shared.handle(
260
+ context,
261
+ { operation: "context", request, visited: [] },
262
+ signal,
263
+ ) as Promise<SharedContextResult>,
264
+ );
265
+ const file = ctx.sessionManager.getSessionFile();
266
+ if (file)
267
+ close = await listenContext(
268
+ sessionContextPath(file),
269
+ (request: unknown, signal: AbortSignal) =>
270
+ shared.handle(ctx, request, signal),
271
+ );
272
+ });
273
+ pi.on("session_shutdown", async () => {
274
+ unregister?.();
275
+ await close?.();
276
+ connection?.dispose();
277
+ });
278
+ if (connection)
279
+ fleet.setContextRelay((ctx, request, signal) =>
280
+ shared.handle(ctx, request, signal),
281
+ );
282
+ return shared;
283
+ }