@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,14 +1,12 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
2
  import { Check } from "typebox/value";
3
3
  import { contextStorageAgentName } from "./agent-identity.js";
4
+ import type { SavedSessionLocator } from "./context-sharing.js";
4
5
  import { useHistory } from "./history.js";
5
6
  import type { HistorySearch } from "./history-search.js";
6
7
  import { normalizeNoteParams, readNotes } from "./note-query.js";
7
8
  import { collectNotes } from "./notes.js";
8
- import {
9
- readSavedNotesSession,
10
- type SavedNotesSession,
11
- } from "./saved-session.js";
9
+ import { type SavedNotesSession } from "./saved-session.js";
12
10
  import {
13
11
  type Identity,
14
12
  Snapshot,
@@ -24,18 +22,38 @@ export function createSharedSessionReader(
24
22
  | { namespace: "history"; search: HistorySearch },
25
23
  outputAgent: string,
26
24
  signal: AbortSignal | undefined,
25
+ load: (locator: SavedSessionLocator) => Promise<SavedNotesSession>,
27
26
  resolve: (
28
27
  session: SavedNotesSession,
29
28
  destination: string,
30
29
  query: Record<string, unknown>,
31
30
  ) => Promise<Record<string, unknown> | undefined>,
31
+ unavailable: (error: unknown) => boolean,
32
32
  ) {
33
33
  const { namespace } = access;
34
34
  async function read(
35
35
  session: SavedNotesSession,
36
36
  query: Record<string, unknown>,
37
37
  native: string,
38
- ) {
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
+ }
39
57
  return {
40
58
  ...(access.namespace === "history"
41
59
  ? await useHistory(
@@ -67,25 +85,19 @@ export function createSharedSessionReader(
67
85
  identity: Identity,
68
86
  destination: string,
69
87
  query: Record<string, unknown>,
70
- file: string | undefined,
88
+ locator: SavedSessionLocator | undefined,
71
89
  retained?: unknown,
72
90
  detached = false,
73
91
  ): Promise<Record<string, unknown> | undefined> {
74
- if (file && (!detached || namespace === "history")) {
92
+ if (locator && (!detached || namespace === "history")) {
75
93
  let saved: SavedNotesSession | undefined;
76
94
  try {
77
- saved = await readSavedNotesSession(
78
- file,
79
- signal,
80
- namespace === "history",
81
- );
95
+ saved = await load(locator);
82
96
  } catch (error) {
83
97
  signal?.throwIfAborted();
84
98
  if (
85
99
  !(
86
- error instanceof Error &&
87
- "code" in error &&
88
- error.code === "ENOENT" &&
100
+ unavailable(error) &&
89
101
  retained !== undefined &&
90
102
  namespace === "notes"
91
103
  )
@@ -19,6 +19,7 @@ import {
19
19
  CONTEXT_SHARING_REQUEST,
20
20
  type ContextRouter,
21
21
  type ContextSharingService,
22
+ type SavedSessionLoader,
22
23
  type SharedContextRequest,
23
24
  type SharedContextResult,
24
25
  } from "./context-sharing.js";
@@ -35,8 +36,9 @@ export function registerContextSharingService(
35
36
  ): Promise<SharedContextResult>;
36
37
  owner(): NotesOwner;
37
38
  },
38
- ): ContextRouter {
39
+ ): ContextRouter & { loadSavedSession: SavedSessionLoader } {
39
40
  let router: ContextRouter | undefined;
41
+ let savedSessionLoader: SavedSessionLoader | undefined;
40
42
  const describe: ContextSharingService["describe"] = (ctx) => {
41
43
  const storageMode = config.enabled(ctx);
42
44
  if (!storageMode) return undefined;
@@ -212,6 +214,14 @@ export function registerContextSharingService(
212
214
  return config.execute(ctx, request, signal);
213
215
  },
214
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
+ },
215
225
  registerRouter(next) {
216
226
  if (router && router !== next)
217
227
  throw new Error("A context router is already registered");
@@ -228,6 +238,7 @@ export function registerContextSharingService(
228
238
  pi.on("session_shutdown", () => {
229
239
  off();
230
240
  router = undefined;
241
+ savedSessionLoader = undefined;
231
242
  });
232
243
  return Object.assign(
233
244
  async (
@@ -244,6 +255,26 @@ export function registerContextSharingService(
244
255
  return router(ctx, request, signal);
245
256
  },
246
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
+ ),
247
278
  requiresRemoteScope: (ctx: ExtensionContext) =>
248
279
  router?.requiresRemoteScope?.(ctx) ?? false,
249
280
  },
package/src/store.ts CHANGED
@@ -132,6 +132,16 @@ export class NotesStore {
132
132
  ?.prepare("UPDATE sessions SET file_path = ? WHERE id = ?")
133
133
  .run(session.file, session.id);
134
134
  }
135
+ /** Exact native thread lookup only. The JSONL header and binding remain authoritative. */
136
+ sessionFile(threadId: string): string | undefined {
137
+ return (
138
+ this.open()
139
+ ?.prepare<[string], { file_path: string | null }>(
140
+ "SELECT file_path FROM sessions WHERE id = ?",
141
+ )
142
+ .get(threadId)?.file_path ?? undefined
143
+ );
144
+ }
135
145
  cache(session: SessionRef, responses: readonly CachedResponse[]): void {
136
146
  if (!responses.length) return;
137
147
  for (const response of responses) {
@@ -0,0 +1,27 @@
1
+ /** @typedef {import("./tree-archive.js").TreeArchiveManifestData} TreeArchiveManifestData */
2
+ export const TREE_ARCHIVE_ENTRY_TYPE = "codex-context-tree-archive";
3
+ const TREE_ARCHIVE_PROTOCOL = 1;
4
+ export const MAX_ARCHIVE_DEPTH = 50_000;
5
+
6
+ /** @param {unknown} value @returns {value is TreeArchiveManifestData} */
7
+ export function isTreeArchiveManifestData(value) {
8
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
9
+ const manifest = /** @type {Record<string, unknown>} */ (value);
10
+ return (
11
+ manifest["protocol"] === TREE_ARCHIVE_PROTOCOL &&
12
+ manifest["strategy"] === "codex-context-tree" &&
13
+ nonEmptyString(manifest["windowId"]) &&
14
+ nonEmptyString(manifest["boundaryEntryId"]) &&
15
+ nonEmptyString(manifest["summaryEntryId"]) &&
16
+ nonEmptyString(manifest["archivedLeafId"]) &&
17
+ (manifest["compactionEntryId"] === undefined ||
18
+ nonEmptyString(manifest["compactionEntryId"])) &&
19
+ (manifest["branchBaseId"] === null ||
20
+ nonEmptyString(manifest["branchBaseId"]))
21
+ );
22
+ }
23
+
24
+ /** @param {unknown} value @returns {value is string} */
25
+ function nonEmptyString(value) {
26
+ return typeof value === "string" && value !== "";
27
+ }
@@ -2,11 +2,14 @@ import type {
2
2
  BranchSummaryEntry,
3
3
  SessionEntry,
4
4
  } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ isTreeArchiveManifestData,
7
+ MAX_ARCHIVE_DEPTH,
8
+ TREE_ARCHIVE_ENTRY_TYPE,
9
+ } from "./tree-archive-manifest.mjs";
5
10
  import { windowDetails } from "./windows.js";
6
11
 
7
- export const TREE_ARCHIVE_ENTRY_TYPE = "codex-context-tree-archive";
8
- const TREE_ARCHIVE_PROTOCOL = 1;
9
- export const MAX_ARCHIVE_DEPTH = 50_000;
12
+ export { TREE_ARCHIVE_ENTRY_TYPE } from "./tree-archive-manifest.mjs";
10
13
 
11
14
  export interface TreeArchiveManifestData {
12
15
  protocol: 1;
@@ -112,29 +115,6 @@ function archivedPath(
112
115
  return reverse.reverse();
113
116
  }
114
117
 
115
- export function isTreeArchiveManifestData(
116
- value: unknown,
117
- ): value is TreeArchiveManifestData {
118
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
119
- const manifest = value as Record<string, unknown>;
120
- return (
121
- manifest["protocol"] === TREE_ARCHIVE_PROTOCOL &&
122
- manifest["strategy"] === "codex-context-tree" &&
123
- nonEmptyString(manifest["windowId"]) &&
124
- nonEmptyString(manifest["boundaryEntryId"]) &&
125
- nonEmptyString(manifest["summaryEntryId"]) &&
126
- nonEmptyString(manifest["archivedLeafId"]) &&
127
- (manifest["compactionEntryId"] === undefined ||
128
- nonEmptyString(manifest["compactionEntryId"])) &&
129
- (manifest["branchBaseId"] === null ||
130
- nonEmptyString(manifest["branchBaseId"]))
131
- );
132
- }
133
-
134
- function nonEmptyString(value: unknown): value is string {
135
- return typeof value === "string" && value !== "";
136
- }
137
-
138
118
  export function hasTreeArchiveSuccessor(
139
119
  entries: readonly SessionEntry[],
140
120
  windowId: string,