@howaboua/pi-notes-compaction 0.0.13 → 0.0.15

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 (43) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/PCC-INTEGRATION.md +3 -1
  3. package/README.md +3 -1
  4. package/package.json +7 -7
  5. package/src/agent-identity.ts +112 -10
  6. package/src/attachment-sharing.ts +37 -6
  7. package/src/attachment-snapshot.ts +16 -6
  8. package/src/bridge.ts +1 -0
  9. package/src/context-sharing.ts +30 -1
  10. package/src/extension-hooks.ts +15 -2
  11. package/src/extension-sharing.ts +26 -11
  12. package/src/fresh-checkpoint.ts +30 -4
  13. package/src/fresh-notes.ts +44 -33
  14. package/src/history-search.ts +1 -1
  15. package/src/history-windows.ts +12 -2
  16. package/src/history.ts +7 -1
  17. package/src/index.ts +3 -0
  18. package/src/integrations.ts +24 -24
  19. package/src/model-roles.ts +28 -4
  20. package/src/note-result.ts +70 -0
  21. package/src/note-save-marker.ts +23 -9
  22. package/src/notes-lookup.ts +5 -2
  23. package/src/notes.ts +8 -3
  24. package/src/query-executor.ts +58 -19
  25. package/src/query-input.ts +12 -1
  26. package/src/remote.ts +26 -7
  27. package/src/saved-session-access.ts +117 -0
  28. package/src/saved-session-index.mjs +83 -0
  29. package/src/saved-session.mjs +241 -0
  30. package/src/saved-session.ts +37 -154
  31. package/src/saved-sharing-records.ts +41 -9
  32. package/src/shared-notes.ts +219 -69
  33. package/src/shared-session-reader.ts +35 -19
  34. package/src/sharing-service.ts +57 -9
  35. package/src/store.ts +10 -0
  36. package/src/task-boundary.ts +1 -1
  37. package/src/tool-contracts.ts +40 -27
  38. package/src/tools.ts +21 -7
  39. package/src/tree-archive-manifest.mjs +27 -0
  40. package/src/tree-archive.ts +6 -26
  41. package/src/window-message.ts +19 -8
  42. package/src/windows.ts +2 -2
  43. package/changelog.ts +0 -337
@@ -2,11 +2,17 @@ import { isDeepStrictEqual } from "node:util";
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import type { Static } from "typebox";
4
4
  import { Check } from "typebox/value";
5
- import type { HistorySearch } from "./history-search.js";
6
5
  import {
7
- readSavedNotesSession,
8
- type SavedNotesSession,
9
- } from "./saved-session.js";
6
+ canonicalAgentName,
7
+ contextAgentNames,
8
+ contextStorageAgentName,
9
+ contextTargetAgent,
10
+ isContextAgentName,
11
+ } from "./agent-identity.js";
12
+ import type { SavedSessionLoader } from "./context-sharing.js";
13
+ import type { HistorySearch } from "./history-search.js";
14
+ import type { SavedNotesSession } from "./saved-session.js";
15
+ import { createSavedSessionAccess } from "./saved-session-access.js";
10
16
  import {
11
17
  Detachment,
12
18
  Member,
@@ -14,6 +20,7 @@ import {
14
20
  Plan,
15
21
  Route,
16
22
  sameOwner,
23
+ savedFamilyIdentity,
17
24
  savedNotesIdentity,
18
25
  } from "./saved-sharing-records.js";
19
26
  import { createSharedSessionReader } from "./shared-session-reader.js";
@@ -50,28 +57,48 @@ function remap(
50
57
  export function sharedNotesUnavailable(error: unknown): boolean {
51
58
  return (
52
59
  error instanceof Error &&
53
- /^(Cross-agent (?:context requires an available context router|notes (?:are unavailable here|owner is unavailable))|Shared context (?:owner|controller) is unavailable|Shared context response was lost|Herdr machine .* is (?:unavailable|disconnected)|remote Shepherdr bridge (?:is unavailable|closed|exited\b)|remote Shepherdr context timed out)/.test(
54
- error.message,
55
- )
60
+ (("code" in error &&
61
+ [
62
+ "ENOENT",
63
+ "EACCES",
64
+ "EPERM",
65
+ "SAVED_SESSION_UNAVAILABLE",
66
+ "ECONNREFUSED",
67
+ "ECONNRESET",
68
+ "EPIPE",
69
+ "ETIMEDOUT",
70
+ ].includes(String(error.code))) ||
71
+ /^(No shared context agent\b|Cross-agent (?:context requires an available context router|notes (?:are unavailable here|owner is unavailable))|Shared context (?:owner|controller) is unavailable|Shared context response was lost|Herdr machine .* is (?:unavailable|disconnected)|remote Shepherdr bridge (?:is unavailable|closed|exited\b)|remote Shepherdr context timed out|Unknown Core machine |Core machine .* is (?:unavailable|connecting)\b|Core is unavailable\b|Remote connection (?:closed|is not ready)\b|Remote request timed out\b)/.test(
72
+ error.message,
73
+ ))
56
74
  );
57
75
  }
58
76
 
59
77
  /** Saved local notes do not need PCC, a router, or a running owner. Writes still belong to the live session. */
60
78
  export async function readSharedNotes(
61
79
  ctx: ExtensionContext,
62
- store: Pick<NotesStore, "read">,
80
+ store: Pick<NotesStore, "read" | "sessionFile">,
63
81
  params: Record<string, unknown>,
64
82
  signal?: AbortSignal,
83
+ loader?: SavedSessionLoader,
65
84
  ): Promise<Record<string, unknown> | undefined> {
66
- return readSharedSession(ctx, store, params, { namespace: "notes" }, signal);
85
+ return readSharedSession(
86
+ ctx,
87
+ store,
88
+ params,
89
+ { namespace: "notes" },
90
+ signal,
91
+ loader,
92
+ );
67
93
  }
68
94
 
69
95
  export async function readSharedHistory(
70
96
  ctx: ExtensionContext,
71
- store: Pick<NotesStore, "read">,
97
+ store: Pick<NotesStore, "read" | "sessionFile">,
72
98
  search: HistorySearch,
73
99
  params: Record<string, unknown>,
74
100
  signal?: AbortSignal,
101
+ loader?: SavedSessionLoader,
75
102
  ): Promise<Record<string, unknown> | undefined> {
76
103
  return readSharedSession(
77
104
  ctx,
@@ -79,17 +106,19 @@ export async function readSharedHistory(
79
106
  params,
80
107
  { namespace: "history", search },
81
108
  signal,
109
+ loader,
82
110
  );
83
111
  }
84
112
 
85
113
  async function readSharedSession(
86
114
  ctx: ExtensionContext,
87
- store: Pick<NotesStore, "read">,
115
+ store: Pick<NotesStore, "read" | "sessionFile">,
88
116
  params: Record<string, unknown>,
89
117
  access:
90
118
  | { namespace: "notes" }
91
119
  | { namespace: "history"; search: HistorySearch },
92
120
  signal?: AbortSignal,
121
+ loader?: SavedSessionLoader,
93
122
  ): Promise<Record<string, unknown> | undefined> {
94
123
  const { namespace } = access;
95
124
  if (
@@ -106,10 +135,14 @@ async function readSharedSession(
106
135
  if (typeof path !== "string" || !path.startsWith("/")) return;
107
136
  const target =
108
137
  namespace === "history"
109
- ? /^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(path)
138
+ ? isContextAgentName(path)
110
139
  ? path
111
140
  : undefined
112
- : /^(\/root(?:\/[a-zA-Z0-9_-]+)*?)\/notes(?:\/|$)/.exec(path)?.[1];
141
+ : contextTargetAgent(
142
+ "notes",
143
+ { path },
144
+ canonicalAgentName(ctx.sessionManager.getSessionId()),
145
+ );
113
146
  if (!target) return;
114
147
  const outputAgent = target;
115
148
  const current: SavedNotesSession = {
@@ -117,15 +150,31 @@ async function readSharedSession(
117
150
  entries: ctx.sessionManager.getEntries(),
118
151
  branch: ctx.sessionManager.getBranch(),
119
152
  };
120
- if (savedNotesIdentity(current).agentName === target) return;
153
+ if (contextAgentNames(savedNotesIdentity(current)).includes(target)) return;
121
154
  const visited = new Set<string>();
155
+ const { containingMachine, locator, load, indexed, find } =
156
+ createSavedSessionAccess(store, namespace, loader, signal);
157
+ let unavailable: unknown;
158
+ let targetReached = false;
159
+ async function exploratoryLoad(location: Parameters<typeof load>[0]) {
160
+ try {
161
+ return await load(location);
162
+ } catch (error) {
163
+ signal?.throwIfAborted();
164
+ if (!sharedNotesUnavailable(error)) throw error;
165
+ unavailable ??= error;
166
+ return undefined;
167
+ }
168
+ }
122
169
 
123
170
  const { read, reference } = createSharedSessionReader(
124
171
  store,
125
172
  access,
126
173
  outputAgent,
127
174
  signal,
175
+ load,
128
176
  resolve,
177
+ sharedNotesUnavailable,
129
178
  );
130
179
  async function resolve(
131
180
  session: SavedNotesSession,
@@ -133,21 +182,13 @@ async function readSharedSession(
133
182
  query: Record<string, unknown>,
134
183
  ): Promise<Record<string, unknown> | undefined> {
135
184
  signal?.throwIfAborted();
136
- if (visited.has(session.threadId)) return;
137
- visited.add(session.threadId);
185
+ const key = `${containingMachine(session)}\0${session.threadId}`;
186
+ if (visited.has(key)) return;
187
+ visited.add(key);
138
188
  const identity = savedNotesIdentity(session);
139
- if (identity.agentName === destination) {
140
- if (
141
- namespace === "notes" &&
142
- identity.storage === "remote" &&
143
- !session.branch.some(
144
- (entry) =>
145
- entry.type === "custom" &&
146
- entry.customType === "notes-compaction:note:v1",
147
- )
148
- )
149
- return;
150
- return read(session, query, identity.agentName);
189
+ if (contextAgentNames(identity).includes(destination)) {
190
+ targetReached = true;
191
+ return read(session, query, destination);
151
192
  }
152
193
  const routes = new Map<string, Static<typeof Route>>();
153
194
  for (const value of records(session, "shepherdr-attachment-route"))
@@ -156,17 +197,35 @@ async function readSharedSession(
156
197
  value.plan.controllerSessionId === identity.threadId
157
198
  )
158
199
  routes.set(`${value.machine}\0${value.sessionFile}`, value);
159
- for (const route of routes.values()) {
200
+ const matching = [...routes.values()].filter((route) => {
160
201
  const link = route.plan.context;
161
- if (route.phase !== "ready" || !link || !inside(destination, link.alias))
162
- continue;
202
+ return (
203
+ route.phase === "ready" &&
204
+ link &&
205
+ (destination === canonicalAgentName(link.target.threadId) ||
206
+ inside(destination, link.alias))
207
+ );
208
+ });
209
+ if (matching.length > 1)
210
+ throw new Error(
211
+ "Saved shared address is ambiguous across machines. Use a unique attached alias, then retry.",
212
+ );
213
+ for (const route of matching) {
214
+ targetReached = true;
215
+ const link = route.plan.context;
216
+ if (route.phase !== "ready" || !link) continue;
217
+ const alias =
218
+ destination === canonicalAgentName(link.target.threadId)
219
+ ? destination
220
+ : link.alias;
221
+ if (!inside(destination, alias)) continue;
163
222
  if (!sameOwner(identity, link.controller))
164
223
  throw new Error("Saved shared notes identity changed");
165
224
  return reference(
166
225
  link.target,
167
- `${link.target.agentName}${destination.slice(link.alias.length)}`,
168
- remap(query, link.alias, link.target.agentName),
169
- route.machine === "local" ? route.sessionFile : undefined,
226
+ `${link.target.agentName}${destination.slice(alias.length)}`,
227
+ remap(query, alias, link.target.agentName),
228
+ locator(session, route.machine, route.sessionFile),
170
229
  route.detached?.context ?? link.targetNotes,
171
230
  route.detached?.context !== undefined,
172
231
  );
@@ -178,9 +237,15 @@ async function readSharedSession(
178
237
  if (
179
238
  Check(Plan, owner) &&
180
239
  owner.context &&
181
- inside(destination, owner.context.controllerAlias)
240
+ (inside(destination, owner.context.controllerAlias) ||
241
+ destination === canonicalAgentName(owner.context.controller.threadId))
182
242
  ) {
243
+ targetReached = true;
183
244
  const link = owner.context;
245
+ const alias =
246
+ destination === canonicalAgentName(link.controller.threadId)
247
+ ? destination
248
+ : link.controllerAlias;
184
249
  if (!sameOwner(identity, link.target))
185
250
  throw new Error("Saved shared notes identity changed");
186
251
  const detached = records(
@@ -195,66 +260,151 @@ async function readSharedSession(
195
260
  : undefined;
196
261
  return reference(
197
262
  link.controller,
198
- `${link.controller.agentName}${destination.slice(link.controllerAlias.length)}`,
199
- remap(query, link.controllerAlias, link.controller.agentName),
200
- link.controllerFile,
263
+ `${link.controller.agentName}${destination.slice(alias.length)}`,
264
+ remap(query, alias, link.controller.agentName),
265
+ link.controllerFile
266
+ ? locator(
267
+ session,
268
+ link.controllerMachine ?? "local",
269
+ link.controllerFile,
270
+ )
271
+ : undefined,
201
272
  snapshot ?? link.controllerNotes,
202
273
  snapshot !== undefined,
203
274
  );
204
275
  }
205
- const member = records(session, "herdr-context-child").findLast(
276
+ // Explicit attachment routes (including detach snapshots) own their addresses.
277
+ if (session === current) {
278
+ let saved: SavedNotesSession | undefined;
279
+ try {
280
+ saved = await indexed(current, destination);
281
+ } catch (error) {
282
+ signal?.throwIfAborted();
283
+ if (!sharedNotesUnavailable(error)) throw error;
284
+ unavailable ??= error;
285
+ }
286
+ if (saved) return resolve(saved, destination, query);
287
+ }
288
+ if (!savedFamilyIdentity(session)) return;
289
+ let result: Record<string, unknown> | undefined;
290
+ const members = records(session, "herdr-context-child").filter(
206
291
  (value) =>
207
292
  Check(Member, value) &&
208
293
  value.threadId === identity.threadId &&
209
- value.sessionId === identity.sessionId &&
210
- inside(destination, value.agentName),
294
+ value.sessionId === identity.sessionId,
211
295
  );
212
- if (Check(Member, member)) {
213
- if (member.machine !== "local") return;
214
- const saved = await readSavedNotesSession(
215
- member.sessionFile,
216
- signal,
217
- namespace === "history",
218
- );
219
- const child = savedNotesIdentity(saved);
296
+ const direct = members.filter(
297
+ (member) => Check(Member, member) && member.agentName === destination,
298
+ );
299
+ for (const member of direct.length ? direct : members) {
300
+ if (!Check(Member, member)) continue;
301
+ const location = locator(session, member.machine, member.sessionFile);
302
+ // Only exploratory edges may be skipped. A recorded target must report its failure.
303
+ const saved = await (direct.length
304
+ ? load(location)
305
+ : exploratoryLoad(location));
306
+ if (!saved) continue;
307
+ const child = savedFamilyIdentity(saved);
220
308
  if (
309
+ !child ||
221
310
  child.sessionId !== identity.sessionId ||
222
- child.agentName !== member.agentName
311
+ (child.agentName !== member.agentName &&
312
+ contextStorageAgentName(child) !== member.agentName)
223
313
  )
224
314
  throw new Error(
225
315
  "Saved shared notes belong to a different agent family",
226
316
  );
227
- return resolve(saved, destination, query);
317
+ const candidate = await resolve(saved, destination, query);
318
+ if (candidate) {
319
+ if (result)
320
+ throw new Error(
321
+ "Saved shared address is ambiguous across machines. Use a unique attached alias, then retry.",
322
+ );
323
+ result = candidate;
324
+ }
228
325
  }
326
+ if (direct.length) return result;
229
327
  const routing = identity.routing;
230
328
  const suffix = ".jsonl.shepherdr-context.json";
231
- if (Check(Parent, routing) && routing.parent.endsWith(suffix)) {
232
- const saved = await readSavedNotesSession(
233
- routing.parent.slice(0, -".shepherdr-context.json".length),
234
- signal,
235
- namespace === "history",
236
- );
237
- const parent = savedNotesIdentity(saved);
238
- if (
239
- parent.sessionId !== identity.sessionId ||
240
- !identity.agentName.startsWith(`${parent.agentName}/`)
241
- )
242
- throw new Error("Saved shared notes parent identity changed");
243
- return resolve(saved, destination, query);
329
+ if (Check(Parent, routing)) {
330
+ const parentLocator = routing.savedParent
331
+ ? locator(
332
+ session,
333
+ routing.savedParent.machine,
334
+ routing.savedParent.sessionFile,
335
+ )
336
+ : routing.parent.endsWith(suffix)
337
+ ? locator(
338
+ session,
339
+ "local",
340
+ routing.parent.slice(0, -".shepherdr-context.json".length),
341
+ )
342
+ : undefined;
343
+ if (parentLocator) {
344
+ const saved = await exploratoryLoad(parentLocator);
345
+ if (!saved) return result;
346
+ const parent = savedFamilyIdentity(saved);
347
+ if (!parent || parent.sessionId !== identity.sessionId)
348
+ throw new Error("Saved shared notes parent identity changed");
349
+ const candidate = await resolve(saved, destination, query);
350
+ if (candidate && result)
351
+ throw new Error(
352
+ "Saved shared address is ambiguous across machines. Use a unique attached alias, then retry.",
353
+ );
354
+ result = candidate ?? result;
355
+ }
244
356
  }
245
- return undefined;
357
+ return result;
246
358
  }
247
359
  try {
248
- return await resolve(current, target, params);
360
+ let result: Record<string, unknown> | undefined;
361
+ try {
362
+ result = await resolve(current, target, params);
363
+ } catch (error) {
364
+ signal?.throwIfAborted();
365
+ if (!sharedNotesUnavailable(error)) throw error;
366
+ unavailable ??= error;
367
+ }
368
+ // Legacy remote children may record only a now-dead relay parent. Find the
369
+ // requested native thread once, never aliases or intermediate graph nodes.
370
+ const family = savedFamilyIdentity(current);
371
+ if (!result && !targetReached && family) {
372
+ const candidates: SavedNotesSession[] = [];
373
+ for (const location of await find(target)) {
374
+ const saved = await exploratoryLoad(location);
375
+ if (!saved) continue;
376
+ if (saved.threadId !== target.slice(1))
377
+ throw new Error(
378
+ "Saved session discovery returned a different thread",
379
+ );
380
+ const member = savedFamilyIdentity(saved);
381
+ if (
382
+ member?.storage === "session" &&
383
+ member.sessionId === family.sessionId &&
384
+ member.agentName === target
385
+ )
386
+ candidates.push(saved);
387
+ }
388
+ if (candidates.length > 1)
389
+ throw new Error(
390
+ "Saved shared address is ambiguous across machines. Use a unique attached alias, then retry.",
391
+ );
392
+ if (candidates[0]) result = await read(candidates[0], params, target);
393
+ }
394
+ if (!result && unavailable) throw unavailable;
395
+ return result;
249
396
  } catch (error) {
250
397
  if (
251
398
  error instanceof Error &&
252
399
  "code" in error &&
253
400
  ["ENOENT", "EACCES", "EPERM"].includes(String(error.code))
254
401
  )
255
- throw new Error(
256
- `Saved shared ${namespace} are unavailable on this machine. Restore access to the saved Pi JSONL session, then retry.`,
257
- { cause: error },
402
+ throw Object.assign(
403
+ new Error(
404
+ `Saved shared ${namespace} are unavailable on this machine. Restore access to the saved Pi JSONL session, then retry.`,
405
+ { cause: error },
406
+ ),
407
+ { code: "SAVED_SESSION_UNAVAILABLE" },
258
408
  );
259
409
  throw error;
260
410
  }
@@ -1,13 +1,12 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
2
  import { Check } from "typebox/value";
3
+ import { contextStorageAgentName } from "./agent-identity.js";
4
+ import type { SavedSessionLocator } from "./context-sharing.js";
3
5
  import { useHistory } from "./history.js";
4
6
  import type { HistorySearch } from "./history-search.js";
5
7
  import { normalizeNoteParams, readNotes } from "./note-query.js";
6
8
  import { collectNotes } from "./notes.js";
7
- import {
8
- readSavedNotesSession,
9
- type SavedNotesSession,
10
- } from "./saved-session.js";
9
+ import { type SavedNotesSession } from "./saved-session.js";
11
10
  import {
12
11
  type Identity,
13
12
  Snapshot,
@@ -23,18 +22,38 @@ export function createSharedSessionReader(
23
22
  | { namespace: "history"; search: HistorySearch },
24
23
  outputAgent: string,
25
24
  signal: AbortSignal | undefined,
25
+ load: (locator: SavedSessionLocator) => Promise<SavedNotesSession>,
26
26
  resolve: (
27
27
  session: SavedNotesSession,
28
28
  destination: string,
29
29
  query: Record<string, unknown>,
30
30
  ) => Promise<Record<string, unknown> | undefined>,
31
+ unavailable: (error: unknown) => boolean,
31
32
  ) {
32
33
  const { namespace } = access;
33
34
  async function read(
34
35
  session: SavedNotesSession,
35
36
  query: Record<string, unknown>,
36
37
  native: string,
37
- ) {
38
+ ): Promise<Record<string, unknown> | undefined> {
39
+ if (namespace === "notes") {
40
+ const normalized = normalizeNoteParams(query, native);
41
+ const replacement =
42
+ normalized["action"] === "read_file" &&
43
+ collectNotes(store, session.branch).get(String(normalized["path"]))
44
+ ?.mode === "replace";
45
+ // Never replace a merged hybrid read with a local-only saved branch.
46
+ if (
47
+ !replacement &&
48
+ (savedNotesIdentity(session).storage === "remote" ||
49
+ session.branch.some(
50
+ (entry) =>
51
+ entry.type === "custom" &&
52
+ entry.customType === "notes-compaction:cache:v1",
53
+ ))
54
+ )
55
+ return;
56
+ }
38
57
  return {
39
58
  ...(access.namespace === "history"
40
59
  ? await useHistory(
@@ -66,25 +85,19 @@ export function createSharedSessionReader(
66
85
  identity: Identity,
67
86
  destination: string,
68
87
  query: Record<string, unknown>,
69
- file: string | undefined,
88
+ locator: SavedSessionLocator | undefined,
70
89
  retained?: unknown,
71
90
  detached = false,
72
91
  ): Promise<Record<string, unknown> | undefined> {
73
- if (file && (!detached || namespace === "history")) {
92
+ if (locator && (!detached || namespace === "history")) {
74
93
  let saved: SavedNotesSession | undefined;
75
94
  try {
76
- saved = await readSavedNotesSession(
77
- file,
78
- signal,
79
- namespace === "history",
80
- );
95
+ saved = await load(locator);
81
96
  } catch (error) {
82
97
  signal?.throwIfAborted();
83
98
  if (
84
99
  !(
85
- error instanceof Error &&
86
- "code" in error &&
87
- error.code === "ENOENT" &&
100
+ unavailable(error) &&
88
101
  retained !== undefined &&
89
102
  namespace === "notes"
90
103
  )
@@ -99,7 +112,8 @@ export function createSharedSessionReader(
99
112
  }
100
113
  if (
101
114
  namespace === "history" ||
102
- destination !== identity.agentName ||
115
+ (destination !== identity.agentName &&
116
+ destination !== contextStorageAgentName(identity)) ||
103
117
  !Check(Snapshot, retained)
104
118
  )
105
119
  return;
@@ -111,8 +125,10 @@ export function createSharedSessionReader(
111
125
  customType: "codex-context-note-snapshot",
112
126
  data: {
113
127
  ...retained,
114
- files: retained.files.filter((file) =>
115
- file.path.startsWith(`${identity.agentName}/notes/`),
128
+ files: retained.files.filter(
129
+ (file) =>
130
+ file.path.startsWith(`${identity.agentName}/notes/`) ||
131
+ file.path.startsWith(`${contextStorageAgentName(identity)}/notes/`),
116
132
  ),
117
133
  },
118
134
  };
@@ -120,7 +136,7 @@ export function createSharedSessionReader(
120
136
  ...(await read(
121
137
  { threadId: identity.threadId, entries: [], branch: [entry] },
122
138
  query,
123
- identity.agentName,
139
+ destination,
124
140
  )),
125
141
  captured_at: new Date(retained.timestamp).toISOString(),
126
142
  warning: detached
@@ -1,4 +1,3 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import { isDeepStrictEqual } from "node:util";
3
2
  import type {
4
3
  ExtensionAPI,
@@ -6,7 +5,9 @@ import type {
6
5
  } from "@earendil-works/pi-coding-agent";
7
6
  import {
8
7
  CONTEXT_AGENT_ENTRY,
8
+ canonicalAgentName,
9
9
  contextAgentIdentity,
10
+ contextAgentNames,
10
11
  contextTargetAgent,
11
12
  parseContextAgentBinding,
12
13
  } from "./agent-identity.js";
@@ -18,6 +19,7 @@ import {
18
19
  CONTEXT_SHARING_REQUEST,
19
20
  type ContextRouter,
20
21
  type ContextSharingService,
22
+ type SavedSessionLoader,
21
23
  type SharedContextRequest,
22
24
  type SharedContextResult,
23
25
  } from "./context-sharing.js";
@@ -34,8 +36,9 @@ export function registerContextSharingService(
34
36
  ): Promise<SharedContextResult>;
35
37
  owner(): NotesOwner;
36
38
  },
37
- ): ContextRouter {
39
+ ): ContextRouter & { loadSavedSession: SavedSessionLoader } {
38
40
  let router: ContextRouter | undefined;
41
+ let savedSessionLoader: SavedSessionLoader | undefined;
39
42
  const describe: ContextSharingService["describe"] = (ctx) => {
40
43
  const storageMode = config.enabled(ctx);
41
44
  if (!storageMode) return undefined;
@@ -79,8 +82,14 @@ export function registerContextSharingService(
79
82
  const parent = describe(ctx);
80
83
  if (!parent)
81
84
  throw new Error("Shared context requires notes-based continuity");
82
- if (!/^[a-zA-Z0-9_-]+$/.test(options.name))
83
- throw new Error("Invalid context agent name");
85
+ if (
86
+ options.threadId === parent.threadId ||
87
+ options.threadId === parent.sessionId
88
+ )
89
+ throw new Error(
90
+ "Child Pi session ID conflicts with its controller or family root; start a session with another ID",
91
+ );
92
+ const agentName = canonicalAgentName(options.threadId);
84
93
  if (!router || options.routing === undefined)
85
94
  throw new Error("Local sharing requires a registered context router");
86
95
 
@@ -91,7 +100,7 @@ export function registerContextSharingService(
91
100
  const binding = {
92
101
  protocol: 1 as const,
93
102
  sessionId: parent.sessionId,
94
- agentName: `${parent.agentName}/${options.name}-${randomUUID()}`,
103
+ agentName,
95
104
  storage: "session" as const,
96
105
  ...(parent.accountScope ? { accountScope: parent.accountScope } : {}),
97
106
  ...(parent.backendUrl ? { backendUrl: parent.backendUrl } : {}),
@@ -120,8 +129,18 @@ export function registerContextSharingService(
120
129
  },
121
130
  async bind(ctx, input, options) {
122
131
  const binding = parseContextAgentBinding(input);
123
- if (binding.agentName === "/root")
124
- throw new Error("Shared context binding requires a child agent path");
132
+ if (ctx.sessionManager.getSessionId() === binding.sessionId)
133
+ throw new Error(
134
+ "Child Pi session ID conflicts with its family root; start a session with another ID",
135
+ );
136
+ if (
137
+ binding.agentName !==
138
+ canonicalAgentName(ctx.sessionManager.getSessionId()) ||
139
+ binding.storageAgentName !== undefined
140
+ )
141
+ throw new Error(
142
+ "Shared context binding must use this Pi session identity",
143
+ );
125
144
  const identity = {
126
145
  ...binding,
127
146
  threadId: ctx.sessionManager.getSessionId(),
@@ -176,7 +195,7 @@ export function registerContextSharingService(
176
195
  if (
177
196
  !identity ||
178
197
  identity.sessionId !== request.sessionId ||
179
- identity.agentName !== request.agentName ||
198
+ !contextAgentNames(identity).includes(request.agentName) ||
180
199
  (request.namespace !== "notes" && request.namespace !== "history") ||
181
200
  !request.params ||
182
201
  typeof request.params !== "object" ||
@@ -185,7 +204,7 @@ export function registerContextSharingService(
185
204
  request.namespace,
186
205
  request.params,
187
206
  identity.agentName,
188
- ) !== identity.agentName
207
+ ) !== request.agentName
189
208
  )
190
209
  throw new Error("Shared context request does not belong to this agent");
191
210
  if (request.encryptedArguments)
@@ -195,6 +214,14 @@ export function registerContextSharingService(
195
214
  return config.execute(ctx, request, signal);
196
215
  },
197
216
  ...createAttachmentSharing(describe),
217
+ registerSavedSessionLoader(next) {
218
+ if (savedSessionLoader && savedSessionLoader !== next)
219
+ throw new Error("A saved session loader is already registered");
220
+ savedSessionLoader = next;
221
+ return () => {
222
+ if (savedSessionLoader === next) savedSessionLoader = undefined;
223
+ };
224
+ },
198
225
  registerRouter(next) {
199
226
  if (router && router !== next)
200
227
  throw new Error("A context router is already registered");
@@ -211,6 +238,7 @@ export function registerContextSharingService(
211
238
  pi.on("session_shutdown", () => {
212
239
  off();
213
240
  router = undefined;
241
+ savedSessionLoader = undefined;
214
242
  });
215
243
  return Object.assign(
216
244
  async (
@@ -227,6 +255,26 @@ export function registerContextSharingService(
227
255
  return router(ctx, request, signal);
228
256
  },
229
257
  {
258
+ loadSavedSession: Object.defineProperty(
259
+ (
260
+ locator: import("./context-sharing.js").SavedSessionLocator,
261
+ history: boolean,
262
+ signal?: AbortSignal,
263
+ ) => {
264
+ if (!savedSessionLoader)
265
+ throw Object.assign(
266
+ new Error(
267
+ "Saved shared sessions on that machine are unavailable. Resume the shared agent and reconnect its machine, or make its saved Pi JSONL session available locally.",
268
+ ),
269
+ { code: "SAVED_SESSION_UNAVAILABLE" },
270
+ );
271
+ return savedSessionLoader(locator, history, signal);
272
+ },
273
+ "find",
274
+ {
275
+ get: () => savedSessionLoader?.find?.bind(savedSessionLoader),
276
+ },
277
+ ),
230
278
  requiresRemoteScope: (ctx: ExtensionContext) =>
231
279
  router?.requiresRemoteScope?.(ctx) ?? false,
232
280
  },