@howaboua/pi-shepherdr 0.2.11 → 0.2.13

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,188 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import type {
4
+ ContextSharingService,
5
+ SharedContextRequest,
6
+ SharedContextResult,
7
+ } from "@howaboua/pi-codex-conversion/context-sharing";
8
+ import type { AttachmentNotes } from "./attachment-notes.js";
9
+ import {
10
+ type AttachmentRoute,
11
+ attachmentOwner,
12
+ attachmentRoutes,
13
+ detachment,
14
+ inside,
15
+ remap,
16
+ remapParams,
17
+ remapResult,
18
+ } from "./attachment-protocol.js";
19
+ import {
20
+ requestContext,
21
+ sessionContextPath,
22
+ } from "./remote/shepherdr-context.mjs";
23
+
24
+ /** Routes counterpart aliases and preserves read-only checkpoint recovery policy. */
25
+ export class AttachmentRouting {
26
+ private readonly getService: () => ContextSharingService | undefined;
27
+ private readonly notes: AttachmentNotes;
28
+ constructor(
29
+ getService: () => ContextSharingService | undefined,
30
+ notes: AttachmentNotes,
31
+ ) {
32
+ this.getService = getService;
33
+ this.notes = notes;
34
+ }
35
+ async route(
36
+ ctx: ExtensionContext,
37
+ request: SharedContextRequest,
38
+ visited: string[],
39
+ send: (route: AttachmentRoute, request: unknown) => Promise<unknown>,
40
+ signal?: AbortSignal,
41
+ ): Promise<SharedContextResult | undefined> {
42
+ const native = this.getService()?.describe(ctx);
43
+ if (!native || request.sessionId !== native.sessionId) return undefined;
44
+ const child = attachmentRoutes(ctx).find(
45
+ (route) =>
46
+ route.phase === "ready" &&
47
+ route.plan.context &&
48
+ inside(request.agentName, route.plan.context.alias),
49
+ );
50
+ if (child?.plan.context) {
51
+ const link = child.plan.context;
52
+ if (!isDeepStrictEqual(native, link.controller))
53
+ throw new Error(
54
+ "Shared notes are unavailable. Use messages to exchange the context you need.",
55
+ );
56
+ const next = {
57
+ ...request,
58
+ sessionId: link.target.sessionId,
59
+ agentName: remap(request.agentName, link.alias, link.target.agentName),
60
+ params: remapParams(request.params, link.alias, link.target.agentName),
61
+ };
62
+ let result: SharedContextResult;
63
+ if (link.target.storage === "remote") {
64
+ if (child.detached?.context && !this.notes.canRead(next))
65
+ throw new Error(
66
+ "Detached counterpart checkpoints are read-only; native history is unchanged",
67
+ );
68
+ result = await this.notes.remote(
69
+ ctx,
70
+ child.detached?.context ?? link.targetNotes,
71
+ next,
72
+ signal,
73
+ );
74
+ } else if (!child.detached?.context) {
75
+ try {
76
+ result = (await send(child, {
77
+ operation: "context",
78
+ request: next,
79
+ visited,
80
+ })) as SharedContextResult;
81
+ } catch (error) {
82
+ signal?.throwIfAborted();
83
+ if (!this.notes.canRead(next) || !this.notes.unavailable(error))
84
+ throw error;
85
+ result = await this.notes.read(
86
+ next,
87
+ link.target,
88
+ link.targetNotes,
89
+ false,
90
+ () =>
91
+ send(child, {
92
+ operation: "attachment-persisted-notes",
93
+ identity: link.target,
94
+ }),
95
+ error,
96
+ );
97
+ }
98
+ } else
99
+ result = await this.notes.read(
100
+ next,
101
+ link.target,
102
+ child.detached.context,
103
+ true,
104
+ async () => undefined,
105
+ );
106
+ return remapResult(result, link.target.agentName, link.alias);
107
+ }
108
+ const owner = attachmentOwner(ctx);
109
+ const link = owner?.context;
110
+ if (owner && link && inside(request.agentName, link.controllerAlias)) {
111
+ if (!isDeepStrictEqual(native, link.target))
112
+ throw new Error(
113
+ "Shared notes are unavailable. Use messages to exchange the context you need.",
114
+ );
115
+ const next = {
116
+ ...request,
117
+ sessionId: link.controller.sessionId,
118
+ agentName: remap(
119
+ request.agentName,
120
+ link.controllerAlias,
121
+ link.controller.agentName,
122
+ ),
123
+ params: remapParams(
124
+ request.params,
125
+ link.controllerAlias,
126
+ link.controller.agentName,
127
+ ),
128
+ };
129
+ const detached = detachment(ctx, owner)?.context;
130
+ let result: SharedContextResult;
131
+ if (link.controller.storage === "remote") {
132
+ if (detached && !this.notes.canRead(next))
133
+ throw new Error(
134
+ "Detached counterpart checkpoints are read-only; native history is unchanged",
135
+ );
136
+ result = await this.notes.remote(
137
+ ctx,
138
+ detached ?? link.controllerNotes,
139
+ next,
140
+ signal,
141
+ );
142
+ } else if (!detached) {
143
+ try {
144
+ result = (await requestContext(
145
+ owner.upstream,
146
+ { operation: "context", request: next, visited },
147
+ signal,
148
+ )) as SharedContextResult;
149
+ } catch (error) {
150
+ signal?.throwIfAborted();
151
+ if (!this.notes.canRead(next) || !this.notes.unavailable(error))
152
+ throw error;
153
+ result = await this.notes.read(
154
+ next,
155
+ link.controller,
156
+ link.controllerNotes,
157
+ false,
158
+ () =>
159
+ requestContext(
160
+ link.controllerFile
161
+ ? sessionContextPath(link.controllerFile)
162
+ : owner.upstream,
163
+ {
164
+ operation: "attachment-persisted-notes",
165
+ identity: link.controller,
166
+ },
167
+ signal,
168
+ ),
169
+ error,
170
+ );
171
+ }
172
+ } else
173
+ result = await this.notes.read(
174
+ next,
175
+ link.controller,
176
+ detached,
177
+ true,
178
+ async () => undefined,
179
+ );
180
+ return remapResult(
181
+ result,
182
+ link.controller.agentName,
183
+ link.controllerAlias,
184
+ );
185
+ }
186
+ return undefined;
187
+ }
188
+ }
@@ -0,0 +1,321 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import type { ContextSharingService } from "@howaboua/pi-codex-conversion/context-sharing";
7
+ import type { Static } from "typebox";
8
+ import { Check } from "typebox/value";
9
+ import { AttachmentNotes } from "./attachment-notes.js";
10
+ import {
11
+ type AttachmentPlan,
12
+ attachmentOwner,
13
+ attachmentRoutes,
14
+ DETACHED,
15
+ Detachment,
16
+ detachment,
17
+ Identity,
18
+ OWNER,
19
+ Plan,
20
+ } from "./attachment-protocol.js";
21
+ import type { AgentBoard } from "./board/host.js";
22
+ import { binding } from "./board/identity.js";
23
+ import { sendPolicyMessage } from "./delivery.js";
24
+ import { attachmentMessage, detachmentMessage } from "./messages.js";
25
+
26
+ /** Validates and commits attachment membership in the settled target session. */
27
+ export class AttachmentTarget {
28
+ private readonly pi: ExtensionAPI;
29
+ private readonly board: AgentBoard;
30
+ private readonly getService: () => ContextSharingService | undefined;
31
+ private readonly notes: AttachmentNotes;
32
+ constructor(
33
+ pi: ExtensionAPI,
34
+ board: AgentBoard,
35
+ getService: () => ContextSharingService | undefined,
36
+ notes: AttachmentNotes,
37
+ ) {
38
+ this.pi = pi;
39
+ this.board = board;
40
+ this.getService = getService;
41
+ this.notes = notes;
42
+ }
43
+ async context(ctx: ExtensionContext, target: boolean) {
44
+ const service = this.getService();
45
+ if (!service?.inspectAttachment || !service.retainAttachmentIdentity)
46
+ throw new Error("Update Codex Conversion to attach existing context");
47
+ const identity = await service.inspectAttachment(ctx, target);
48
+ if (!identity || !Check(Identity, identity))
49
+ throw new Error(
50
+ "Context attachment requires notes-based continuity on both agents",
51
+ );
52
+ return identity as Static<typeof Identity>;
53
+ }
54
+ retainIdentity(ctx: ExtensionContext) {
55
+ const service = this.getService();
56
+ if (!service?.retainAttachmentIdentity)
57
+ throw new Error(
58
+ "Context attachment support became unavailable; reload and retry",
59
+ );
60
+ return service.retainAttachmentIdentity(ctx);
61
+ }
62
+ private async inspect(ctx: ExtensionContext) {
63
+ if (!ctx.isIdle()) throw new Error("Attach only after the target settles");
64
+ if (!ctx.sessionManager.getSessionFile())
65
+ throw new Error("Attachment requires a saved target session");
66
+ let context: Static<typeof Identity> | undefined;
67
+ let contextError: string | undefined;
68
+ let boardError: string | undefined;
69
+ try {
70
+ context = await this.context(ctx, true);
71
+ if (
72
+ attachmentRoutes(ctx).some((route) => route.plan.context) ||
73
+ ctx.sessionManager
74
+ .getEntries()
75
+ .some(
76
+ (entry) =>
77
+ entry.type === "custom" &&
78
+ entry.customType === "herdr-context-child" &&
79
+ (entry.data as { threadId?: unknown } | undefined)?.threadId ===
80
+ context?.threadId,
81
+ )
82
+ )
83
+ throw new Error("Target already controls a context family");
84
+ } catch (error) {
85
+ context = undefined;
86
+ contextError = String(error);
87
+ }
88
+ try {
89
+ this.board.membership.inspectAttachment(ctx);
90
+ } catch (error) {
91
+ boardError = String(error);
92
+ }
93
+ return {
94
+ sessionId: ctx.sessionManager.getSessionId(),
95
+ board: binding(ctx),
96
+ ...(context ? { context, notes: await this.notes.export(ctx) } : {}),
97
+ ...(contextError ? { contextError } : {}),
98
+ ...(boardError ? { boardError } : {}),
99
+ };
100
+ }
101
+ async handle(
102
+ ctx: ExtensionContext,
103
+ input: unknown,
104
+ signal?: AbortSignal,
105
+ ): Promise<unknown> {
106
+ signal?.throwIfAborted();
107
+ if (!input || typeof input !== "object" || !("operation" in input))
108
+ throw new Error("Invalid attachment request");
109
+ if (input.operation === "attach-inspect") return this.inspect(ctx);
110
+ if (input.operation === "attachment-export-notes") {
111
+ if (
112
+ !("plan" in input) ||
113
+ !Check(Plan, input.plan) ||
114
+ !isDeepStrictEqual(attachmentOwner(ctx), input.plan)
115
+ )
116
+ throw new Error("Invalid checkpoint owner");
117
+ return this.notes.export(ctx);
118
+ }
119
+ if (input.operation === "detach-commit")
120
+ return this.commitDetach(ctx, input, signal);
121
+ if (
122
+ input.operation !== "attach-commit" ||
123
+ !("plan" in input) ||
124
+ !Check(Plan, input.plan)
125
+ )
126
+ throw new Error("Invalid attachment request");
127
+ const plan = input.plan as AttachmentPlan;
128
+ if (
129
+ (!plan.context && !plan.board) ||
130
+ plan.controllerSessionId === plan.targetSessionId ||
131
+ (plan.context &&
132
+ (plan.context.controller.threadId !== plan.controllerSessionId ||
133
+ plan.context.target.threadId !== plan.targetSessionId ||
134
+ !plan.context.alias.startsWith(
135
+ `${plan.context.controller.agentName}/`,
136
+ ) ||
137
+ !plan.context.controllerAlias.startsWith(
138
+ `${plan.context.target.agentName}/`,
139
+ ))) ||
140
+ (plan.board &&
141
+ (plan.board.controller.sessionId !== plan.controllerSessionId ||
142
+ plan.board.previous.sessionId !== plan.targetSessionId ||
143
+ !isDeepStrictEqual(plan.board.desired, {
144
+ ...plan.board.controller,
145
+ agentName: plan.board.desired.agentName,
146
+ upstream: plan.upstream,
147
+ }) ||
148
+ !plan.board.desired.agentName.startsWith(
149
+ `${plan.board.controller.agentName}/`,
150
+ )))
151
+ )
152
+ throw new Error("Invalid attachment identities or routes");
153
+ if (
154
+ !ctx.isIdle() ||
155
+ ctx.sessionManager.getSessionId() !== plan.targetSessionId
156
+ )
157
+ throw new Error(
158
+ "Target changed or started work during attachment; retry after it settles",
159
+ );
160
+ const owner = attachmentOwner(ctx);
161
+ if (owner && detachment(ctx, owner))
162
+ throw new Error("Attachment was detached; reattachment is unsupported");
163
+ if (owner && !isDeepStrictEqual(owner, plan))
164
+ throw new Error(
165
+ "Target is already attached; another controller or different attachment choices are unsupported",
166
+ );
167
+ if (!owner) {
168
+ const current = await this.inspect(ctx);
169
+ if (
170
+ plan.context &&
171
+ (!current.context ||
172
+ !isDeepStrictEqual(current.context, plan.context.target))
173
+ )
174
+ throw new Error(
175
+ current.contextError ?? "Target context changed during attachment",
176
+ );
177
+ if (plan.board && current.boardError) throw new Error(current.boardError);
178
+ if (plan.board && !isDeepStrictEqual(current.board, plan.board.previous))
179
+ throw new Error("Target board changed during attachment");
180
+ // Authentication completes before either membership mutation.
181
+ if (plan.context) {
182
+ await this.notes.verify(
183
+ ctx,
184
+ plan.context.controllerNotes,
185
+ plan.context.controller,
186
+ );
187
+ this.notes.validate(plan.context.targetNotes, plan.context.target);
188
+ }
189
+ if (plan.context) {
190
+ const identity = await this.context(ctx, true);
191
+ signal?.throwIfAborted();
192
+ if (
193
+ !ctx.isIdle() ||
194
+ ctx.sessionManager.getSessionId() !== plan.targetSessionId ||
195
+ !isDeepStrictEqual(identity, plan.context.target) ||
196
+ (plan.board && !isDeepStrictEqual(binding(ctx), plan.board.previous))
197
+ )
198
+ throw new Error(
199
+ "Target changed during attachment authentication; retry after it settles",
200
+ );
201
+ this.retainIdentity(ctx);
202
+ }
203
+ signal?.throwIfAborted();
204
+ if (
205
+ !ctx.isIdle() ||
206
+ ctx.sessionManager.getSessionId() !== plan.targetSessionId
207
+ )
208
+ throw new Error(
209
+ "Target changed during attachment; retry after it settles",
210
+ );
211
+ if (plan.board)
212
+ this.board.membership.commitAttachment(
213
+ ctx,
214
+ plan.board.previous,
215
+ plan.board.desired,
216
+ );
217
+ this.pi.appendEntry(OWNER, plan);
218
+ sendPolicyMessage(
219
+ this.pi,
220
+ attachmentMessage(
221
+ plan.context?.controllerAlias,
222
+ plan.board?.desired.agentName,
223
+ ),
224
+ { triggerTurn: false },
225
+ );
226
+ } else {
227
+ if (
228
+ plan.context &&
229
+ !isDeepStrictEqual(await this.context(ctx, false), plan.context.target)
230
+ )
231
+ throw new Error(
232
+ "Shared notes are unavailable. Use messages to exchange the context you need.",
233
+ );
234
+ if (
235
+ plan.board &&
236
+ !isDeepStrictEqual(binding(ctx), {
237
+ ...plan.board.desired,
238
+ sessionId: plan.targetSessionId,
239
+ })
240
+ )
241
+ throw new Error("Attached board changed; resolve the target again");
242
+ }
243
+ if (plan.board) await this.board.refresh(ctx);
244
+ if (ctx.sessionManager.getSessionId() !== plan.targetSessionId)
245
+ throw new Error(
246
+ "Target session changed after attachment; resume it and retry",
247
+ );
248
+ return plan;
249
+ }
250
+ private async commitDetach(
251
+ ctx: ExtensionContext,
252
+ input: unknown,
253
+ signal?: AbortSignal,
254
+ ) {
255
+ if (!Check(Detachment, input)) throw new Error("Invalid detach request");
256
+ const requested = input as Static<typeof Detachment>;
257
+ const { plan } = requested;
258
+ if (
259
+ !isDeepStrictEqual(attachmentOwner(ctx), plan) ||
260
+ ctx.sessionManager.getSessionId() !== plan.targetSessionId ||
261
+ !ctx.isIdle()
262
+ )
263
+ throw new Error("Detach requires the original settled target session");
264
+ if (
265
+ (!requested.context && !requested.board) ||
266
+ (requested.context && !plan.context) ||
267
+ (requested.board && !plan.board)
268
+ )
269
+ throw new Error("Invalid detach choices");
270
+ const previous = detachment(ctx, plan);
271
+ if (requested.context && plan.context) {
272
+ if (
273
+ !isDeepStrictEqual(await this.context(ctx, false), plan.context.target)
274
+ )
275
+ throw new Error("Target context changed before detach");
276
+ this.notes.validate(requested.context, plan.context.controller);
277
+ await this.notes.verify(
278
+ ctx,
279
+ requested.context,
280
+ plan.context.controller,
281
+ true,
282
+ );
283
+ }
284
+ const ownNotes = requested.context
285
+ ? await this.notes.export(ctx)
286
+ : undefined;
287
+ if (ownNotes) this.notes.checkTransport(ownNotes);
288
+ signal?.throwIfAborted();
289
+ if (
290
+ !ctx.isIdle() ||
291
+ ctx.sessionManager.getSessionId() !== plan.targetSessionId ||
292
+ !isDeepStrictEqual(attachmentOwner(ctx), plan)
293
+ )
294
+ throw new Error(
295
+ "Target changed during detach authentication; retry after it settles",
296
+ );
297
+ if (requested.board && plan.board && !previous?.board)
298
+ this.board.membership.detachTarget(
299
+ ctx,
300
+ plan.board.desired,
301
+ plan.board.previous,
302
+ );
303
+ this.pi.appendEntry(DETACHED, { ...previous, ...requested });
304
+ const contextAlias =
305
+ requested.context && !previous?.context
306
+ ? plan.context?.controllerAlias
307
+ : undefined;
308
+ const restoredBoard =
309
+ requested.board && !previous?.board ? plan.board?.previous : undefined;
310
+ if (contextAlias || restoredBoard)
311
+ sendPolicyMessage(
312
+ this.pi,
313
+ detachmentMessage(contextAlias, restoredBoard),
314
+ { triggerTurn: false },
315
+ );
316
+ if (requested.board) await this.board.refresh(ctx);
317
+ if (ctx.sessionManager.getSessionId() !== plan.targetSessionId)
318
+ throw new Error("Target changed after detach; resume it and retry");
319
+ return { detached: true, ...(ownNotes ? { notes: ownNotes } : {}) };
320
+ }
321
+ }