@howaboua/pi-notes-compaction 0.0.14 → 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.
@@ -1,50 +1,8 @@
1
- import { type FileHandle, open } from "node:fs/promises";
2
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
3
2
  import { Type } from "typebox";
4
3
  import { Check } from "typebox/value";
5
- import {
6
- isTreeArchiveManifestData,
7
- MAX_ARCHIVE_DEPTH,
8
- TREE_ARCHIVE_ENTRY_TYPE,
9
- } from "./tree-archive.js";
10
-
11
- const SessionHeader = Type.Object({
12
- type: Type.Literal("session"),
13
- id: Type.String(),
14
- });
15
- const RecordHeader = Type.Object({
16
- type: Type.String(),
17
- id: Type.String(),
18
- parentId: Type.Union([Type.String(), Type.Null()]),
19
- timestamp: Type.String(),
20
- });
21
- const Custom = Type.Object({
22
- ...RecordHeader.properties,
23
- type: Type.Literal("custom"),
24
- customType: Type.String(),
25
- data: Type.Unknown(),
26
- });
27
- const Handoff = Type.Object({
28
- ...RecordHeader.properties,
29
- type: Type.Literal("branch_summary"),
30
- fromId: Type.String(),
31
- summary: Type.String(),
32
- details: Type.Object({ codexContextNoteHandoff: Type.Unknown() }),
33
- });
34
- const NOTE_ENTRIES = new Set([
35
- "notes-compaction:note:v1",
36
- "codex-context-note",
37
- "codex-context-note-snapshot",
38
- ]);
39
- const SHARING_ENTRIES = new Set([
40
- "codex-context-agent",
41
- "codex-context-backend",
42
- "herdr-context-child",
43
- "shepherdr-attachment-route",
44
- "shepherdr-attachment-owner",
45
- "shepherdr-attachment-detached",
46
- ]);
47
4
 
5
+ export { readSavedNotesSession } from "./saved-session.mjs";
48
6
  export interface SavedNotesSession {
49
7
  threadId: string;
50
8
  entries: readonly SessionEntry[];
@@ -52,118 +10,42 @@ export interface SavedNotesSession {
52
10
  savedAt?: number;
53
11
  }
54
12
 
55
- async function* reverseLines(file: FileHandle, size: number) {
56
- let position = size;
57
- let partial = Buffer.alloc(0);
58
- while (position > 0) {
59
- const length = Math.min(64 * 1024, position);
60
- position -= length;
61
- const chunk = Buffer.allocUnsafe(length);
62
- const { bytesRead } = await file.read(chunk, 0, length, position);
63
- const data = Buffer.concat([chunk.subarray(0, bytesRead), partial]);
64
- let end = data.length;
65
- for (let index = data.length - 1; index >= 0; index--) {
66
- if (data[index] !== 10) continue;
67
- yield data.subarray(index + 1, end);
68
- end = index;
69
- }
70
- partial = data.subarray(0, end);
71
- }
72
- yield partial;
73
- }
13
+ const SavedEntry = Type.Object({
14
+ type: Type.String(),
15
+ id: Type.String(),
16
+ parentId: Type.Union([Type.String(), Type.Null()]),
17
+ timestamp: Type.String(),
18
+ });
19
+ const SavedSession = Type.Object({
20
+ threadId: Type.String({ minLength: 1 }),
21
+ entries: Type.Array(SavedEntry),
22
+ branch: Type.Array(SavedEntry),
23
+ savedAt: Type.Optional(Type.Number()),
24
+ });
74
25
 
75
- /** Read only recorded session paths. Identity is session-wide; notes follow the active parent chain. */
76
- export async function readSavedNotesSession(
77
- path: string,
78
- signal?: AbortSignal,
79
- history = false,
80
- ): Promise<SavedNotesSession> {
81
- signal?.throwIfAborted();
82
- const file = await open(path, "r");
83
- try {
84
- const before = await file.stat();
85
- const entries: SessionEntry[] = [];
86
- const branch: SessionEntry[] = [];
87
- const archived = new Map<
88
- string,
89
- { base: string | null; depth: number }[]
90
- >();
91
- let threadId: string | undefined;
92
- let target: string | null | undefined;
93
- for await (const line of reverseLines(file, before.size)) {
94
- signal?.throwIfAborted();
95
- if (!line.length) continue;
96
- let entry: unknown;
97
- try {
98
- entry = JSON.parse(line.toString("utf8"));
99
- } catch {
100
- throw new Error(
101
- "Saved notes are being updated. Retry after the session settles.",
102
- );
103
- }
104
- if (Check(SessionHeader, entry)) {
105
- threadId = entry.id;
106
- continue;
107
- }
108
- if (!Check(RecordHeader, entry))
109
- throw new Error("Invalid saved session record");
110
- if (target === undefined) target = entry.id;
111
- const active = entry.id === target;
112
- if (active) target = entry.parentId;
113
- if (history) {
114
- // Pi appends descendants after their parents, including Tree manifests
115
- // after their archived leaves. Follow only active manifests' ancestry.
116
- const paths = archived.get(entry.id) ?? [];
117
- archived.delete(entry.id);
118
- for (const path of paths) {
119
- if (++path.depth >= MAX_ARCHIVE_DEPTH || entry.parentId === path.base)
120
- continue;
121
- if (entry.parentId !== null) {
122
- const parents = archived.get(entry.parentId) ?? [];
123
- parents.push(path);
124
- archived.set(entry.parentId, parents);
125
- }
126
- }
127
- if (
128
- active &&
129
- Check(Custom, entry) &&
130
- entry.customType === TREE_ARCHIVE_ENTRY_TYPE &&
131
- isTreeArchiveManifestData(entry.data) &&
132
- entry.data.archivedLeafId !== entry.data.branchBaseId
133
- ) {
134
- const paths = archived.get(entry.data.archivedLeafId) ?? [];
135
- paths.push({ base: entry.data.branchBaseId, depth: 0 });
136
- archived.set(entry.data.archivedLeafId, paths);
137
- }
138
- if (
139
- active ||
140
- paths.length ||
141
- (Check(Custom, entry) && SHARING_ENTRIES.has(entry.customType))
142
- )
143
- entries.push(entry as SessionEntry);
144
- if (active) branch.push(entry as SessionEntry);
145
- continue;
146
- }
147
- if (Check(Custom, entry)) {
148
- if (SHARING_ENTRIES.has(entry.customType)) entries.push(entry);
149
- else if (active && NOTE_ENTRIES.has(entry.customType))
150
- branch.push(entry);
151
- else continue;
152
- } else if (active && Check(Handoff, entry)) branch.push(entry);
153
- else continue;
154
- }
155
- const after = await file.stat();
156
- if (before.size !== after.size || before.mtimeMs !== after.mtimeMs)
157
- throw new Error("Saved notes changed during the read. Retry the lookup.");
158
- if (!threadId || (target !== undefined && target !== null))
159
- throw new Error("Saved notes have an incomplete session branch");
160
- return {
161
- threadId,
162
- entries: entries.reverse(),
163
- branch: branch.reverse(),
164
- savedAt: before.mtimeMs,
165
- };
166
- } finally {
167
- await file.close();
26
+ /** Remote loaders carry data, not authority. Native identity is checked by the graph reader. */
27
+ export function validateSavedNotesSession(value: unknown): SavedNotesSession {
28
+ if (!Check(SavedSession, value))
29
+ throw new Error(
30
+ "Saved session response is invalid. Update Notes on the other machine and retry.",
31
+ );
32
+ for (const entry of [...value.entries, ...value.branch]) {
33
+ if (
34
+ entry.type === "custom" &&
35
+ (!("customType" in entry) ||
36
+ typeof entry.customType !== "string" ||
37
+ !("data" in entry))
38
+ )
39
+ throw new Error("Invalid saved session custom record");
40
+ if (
41
+ entry.type === "message" &&
42
+ (!("message" in entry) ||
43
+ !entry.message ||
44
+ typeof entry.message !== "object")
45
+ )
46
+ throw new Error("Invalid saved session message record");
168
47
  }
48
+ // The same persisted entry envelope is accepted by the Node reader. Feature readers
49
+ // validate their own custom data, including ownership and note receipts.
50
+ return value as SavedNotesSession;
169
51
  }
@@ -38,6 +38,7 @@ export const Plan = Type.Object({
38
38
  alias: Agent,
39
39
  controllerAlias: Agent,
40
40
  controllerFile: Type.Optional(Type.String()),
41
+ controllerMachine: Type.Optional(Type.String()),
41
42
  controllerNotes: Type.Unknown(),
42
43
  targetNotes: Type.Unknown(),
43
44
  }),
@@ -75,9 +76,31 @@ export const Snapshot = Type.Object({
75
76
  export const Parent = Type.Object({
76
77
  transport: Type.Literal("shepherdr"),
77
78
  parent: Type.String(),
79
+ savedParent: Type.Optional(
80
+ Type.Object({ machine: Type.String(), sessionFile: Type.String() }),
81
+ ),
78
82
  });
79
83
  export type Identity = Static<typeof Identity>;
80
84
 
85
+ /** Ordinary family membership is immutable, explicit and native-session owned. */
86
+ export function savedFamilyIdentity(
87
+ session: Pick<SavedNotesSession, "threadId" | "entries">,
88
+ ): Identity | undefined {
89
+ const identity = savedNotesIdentity(session);
90
+ if (
91
+ identity.storage === undefined ||
92
+ !session.entries.some(
93
+ (entry) =>
94
+ entry.type === "custom" &&
95
+ entry.customType === "codex-context-agent" &&
96
+ Check(Identity, entry.data) &&
97
+ entry.data.threadId === session.threadId,
98
+ )
99
+ )
100
+ return;
101
+ return identity;
102
+ }
103
+
81
104
  /** Persisted sharing is session-scoped. Forks never inherit the source agent's address. */
82
105
  export function savedNotesIdentity(
83
106
  session: Pick<SavedNotesSession, "threadId" | "entries">,
@@ -9,11 +9,10 @@ import {
9
9
  contextTargetAgent,
10
10
  isContextAgentName,
11
11
  } from "./agent-identity.js";
12
+ import type { SavedSessionLoader } from "./context-sharing.js";
12
13
  import type { HistorySearch } from "./history-search.js";
13
- import {
14
- readSavedNotesSession,
15
- type SavedNotesSession,
16
- } from "./saved-session.js";
14
+ import type { SavedNotesSession } from "./saved-session.js";
15
+ import { createSavedSessionAccess } from "./saved-session-access.js";
17
16
  import {
18
17
  Detachment,
19
18
  Member,
@@ -21,6 +20,7 @@ import {
21
20
  Plan,
22
21
  Route,
23
22
  sameOwner,
23
+ savedFamilyIdentity,
24
24
  savedNotesIdentity,
25
25
  } from "./saved-sharing-records.js";
26
26
  import { createSharedSessionReader } from "./shared-session-reader.js";
@@ -57,28 +57,48 @@ function remap(
57
57
  export function sharedNotesUnavailable(error: unknown): boolean {
58
58
  return (
59
59
  error instanceof Error &&
60
- /^(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(
61
- error.message,
62
- )
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
+ ))
63
74
  );
64
75
  }
65
76
 
66
77
  /** Saved local notes do not need PCC, a router, or a running owner. Writes still belong to the live session. */
67
78
  export async function readSharedNotes(
68
79
  ctx: ExtensionContext,
69
- store: Pick<NotesStore, "read">,
80
+ store: Pick<NotesStore, "read" | "sessionFile">,
70
81
  params: Record<string, unknown>,
71
82
  signal?: AbortSignal,
83
+ loader?: SavedSessionLoader,
72
84
  ): Promise<Record<string, unknown> | undefined> {
73
- 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
+ );
74
93
  }
75
94
 
76
95
  export async function readSharedHistory(
77
96
  ctx: ExtensionContext,
78
- store: Pick<NotesStore, "read">,
97
+ store: Pick<NotesStore, "read" | "sessionFile">,
79
98
  search: HistorySearch,
80
99
  params: Record<string, unknown>,
81
100
  signal?: AbortSignal,
101
+ loader?: SavedSessionLoader,
82
102
  ): Promise<Record<string, unknown> | undefined> {
83
103
  return readSharedSession(
84
104
  ctx,
@@ -86,17 +106,19 @@ export async function readSharedHistory(
86
106
  params,
87
107
  { namespace: "history", search },
88
108
  signal,
109
+ loader,
89
110
  );
90
111
  }
91
112
 
92
113
  async function readSharedSession(
93
114
  ctx: ExtensionContext,
94
- store: Pick<NotesStore, "read">,
115
+ store: Pick<NotesStore, "read" | "sessionFile">,
95
116
  params: Record<string, unknown>,
96
117
  access:
97
118
  | { namespace: "notes" }
98
119
  | { namespace: "history"; search: HistorySearch },
99
120
  signal?: AbortSignal,
121
+ loader?: SavedSessionLoader,
100
122
  ): Promise<Record<string, unknown> | undefined> {
101
123
  const { namespace } = access;
102
124
  if (
@@ -130,13 +152,29 @@ async function readSharedSession(
130
152
  };
131
153
  if (contextAgentNames(savedNotesIdentity(current)).includes(target)) return;
132
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
+ }
133
169
 
134
170
  const { read, reference } = createSharedSessionReader(
135
171
  store,
136
172
  access,
137
173
  outputAgent,
138
174
  signal,
175
+ load,
139
176
  resolve,
177
+ sharedNotesUnavailable,
140
178
  );
141
179
  async function resolve(
142
180
  session: SavedNotesSession,
@@ -144,20 +182,12 @@ async function readSharedSession(
144
182
  query: Record<string, unknown>,
145
183
  ): Promise<Record<string, unknown> | undefined> {
146
184
  signal?.throwIfAborted();
147
- if (visited.has(session.threadId)) return;
148
- visited.add(session.threadId);
185
+ const key = `${containingMachine(session)}\0${session.threadId}`;
186
+ if (visited.has(key)) return;
187
+ visited.add(key);
149
188
  const identity = savedNotesIdentity(session);
150
189
  if (contextAgentNames(identity).includes(destination)) {
151
- if (
152
- namespace === "notes" &&
153
- identity.storage === "remote" &&
154
- !session.branch.some(
155
- (entry) =>
156
- entry.type === "custom" &&
157
- entry.customType === "notes-compaction:note:v1",
158
- )
159
- )
160
- return;
190
+ targetReached = true;
161
191
  return read(session, query, destination);
162
192
  }
163
193
  const routes = new Map<string, Static<typeof Route>>();
@@ -167,7 +197,21 @@ async function readSharedSession(
167
197
  value.plan.controllerSessionId === identity.threadId
168
198
  )
169
199
  routes.set(`${value.machine}\0${value.sessionFile}`, value);
170
- for (const route of routes.values()) {
200
+ const matching = [...routes.values()].filter((route) => {
201
+ const link = route.plan.context;
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;
171
215
  const link = route.plan.context;
172
216
  if (route.phase !== "ready" || !link) continue;
173
217
  const alias =
@@ -181,7 +225,7 @@ async function readSharedSession(
181
225
  link.target,
182
226
  `${link.target.agentName}${destination.slice(alias.length)}`,
183
227
  remap(query, alias, link.target.agentName),
184
- route.machine === "local" ? route.sessionFile : undefined,
228
+ locator(session, route.machine, route.sessionFile),
185
229
  route.detached?.context ?? link.targetNotes,
186
230
  route.detached?.context !== undefined,
187
231
  );
@@ -196,6 +240,7 @@ async function readSharedSession(
196
240
  (inside(destination, owner.context.controllerAlias) ||
197
241
  destination === canonicalAgentName(owner.context.controller.threadId))
198
242
  ) {
243
+ targetReached = true;
199
244
  const link = owner.context;
200
245
  const alias =
201
246
  destination === canonicalAgentName(link.controller.threadId)
@@ -217,26 +262,51 @@ async function readSharedSession(
217
262
  link.controller,
218
263
  `${link.controller.agentName}${destination.slice(alias.length)}`,
219
264
  remap(query, alias, link.controller.agentName),
220
- link.controllerFile,
265
+ link.controllerFile
266
+ ? locator(
267
+ session,
268
+ link.controllerMachine ?? "local",
269
+ link.controllerFile,
270
+ )
271
+ : undefined,
221
272
  snapshot ?? link.controllerNotes,
222
273
  snapshot !== undefined,
223
274
  );
224
275
  }
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;
225
290
  const members = records(session, "herdr-context-child").filter(
226
291
  (value) =>
227
292
  Check(Member, value) &&
228
293
  value.threadId === identity.threadId &&
229
294
  value.sessionId === identity.sessionId,
230
295
  );
231
- for (const member of members) {
232
- if (!Check(Member, member) || member.machine !== "local") continue;
233
- const saved = await readSavedNotesSession(
234
- member.sessionFile,
235
- signal,
236
- namespace === "history",
237
- );
238
- 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);
239
308
  if (
309
+ !child ||
240
310
  child.sessionId !== identity.sessionId ||
241
311
  (child.agentName !== member.agentName &&
242
312
  contextStorageAgentName(child) !== member.agentName)
@@ -244,46 +314,97 @@ async function readSharedSession(
244
314
  throw new Error(
245
315
  "Saved shared notes belong to a different agent family",
246
316
  );
247
- const result = await resolve(saved, destination, query);
248
- if (result) return result;
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
+ }
249
325
  }
326
+ if (direct.length) return result;
250
327
  const routing = identity.routing;
251
328
  const suffix = ".jsonl.shepherdr-context.json";
252
- if (Check(Parent, routing) && routing.parent.endsWith(suffix)) {
253
- const saved = await readSavedNotesSession(
254
- routing.parent.slice(0, -".shepherdr-context.json".length),
255
- signal,
256
- namespace === "history",
257
- );
258
- const parent = savedNotesIdentity(saved);
259
- if (
260
- parent.sessionId !== identity.sessionId ||
261
- !records(saved, "herdr-context-child").some(
262
- (value) =>
263
- Check(Member, value) &&
264
- value.threadId === parent.threadId &&
265
- value.sessionId === parent.sessionId &&
266
- [identity.agentName, contextStorageAgentName(identity)].includes(
267
- value.agentName,
268
- ),
269
- )
270
- )
271
- throw new Error("Saved shared notes parent identity changed");
272
- 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
+ }
273
356
  }
274
- return undefined;
357
+ return result;
275
358
  }
276
359
  try {
277
- 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;
278
396
  } catch (error) {
279
397
  if (
280
398
  error instanceof Error &&
281
399
  "code" in error &&
282
400
  ["ENOENT", "EACCES", "EPERM"].includes(String(error.code))
283
401
  )
284
- throw new Error(
285
- `Saved shared ${namespace} are unavailable on this machine. Restore access to the saved Pi JSONL session, then retry.`,
286
- { 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" },
287
408
  );
288
409
  throw error;
289
410
  }