@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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # @howaboua/pi-notes-compaction
2
2
 
3
+ ## 0.0.15
4
+
5
+ - Shared local checkpoints remain readable after workers close. Saved family lookup no longer depends on a live parent when the saved session is accessible locally.
6
+ - Saved Notes and History reads are faster in sessions with large messages or tool results.
7
+ - Shared saved-session reads no longer fail when the active session appends new entries.
8
+
9
+ ## 0.0.14
10
+
11
+ - Requires Pi 1.5 or newer.
12
+
13
+ Older checkpoints may require a fresh note save before rollover.
14
+ - Notes results in Pi's built-in codemode are now objects, matching Code and Notebook. Remove `JSON.parse` around those results.
15
+ - Agent references now derive from Pi session IDs, with existing shared-note paths retained.
16
+ - Fixed rollover rejecting successful large saves and saves in parallel tool groups. The saved-notes indicator uses the same readiness check.
17
+ - Shared-note paths and read-only warnings now match across text and structured results.
18
+ - History now defaults query-only requests to search and includes the first window's opening request.
19
+ - History now ignores read-only hints on other actions.
20
+ - Model-role guidance now identifies the current role and offers only configured roles for rollover.
21
+ - Notes help now distinguishes virtual note paths from agent references and filesystem paths.
22
+ - Added `address` and `body` aliases for note paths and write text.
23
+ - Expansion hints now use the configured keybinding.
24
+ - Removed custom changelog suppression. Updates use Pi's native notices and `collapseChangelog`.
25
+
3
26
  ## 0.0.13
4
27
 
5
28
  - Model roles are now agent-operated. Configure them in `model-roles.json`. `/roles` is read-only, and the old `enabled` flag and accept/dismiss controls no longer apply.
@@ -2,7 +2,9 @@
2
2
 
3
3
  Notes owns its four tools, local storage, family sharing, checkpoint policy and context windows. PCC is optional. Without Notes, PCC provides ordinary Pi and native provider compaction without notes tools.
4
4
 
5
- Notes uses PCC's public `code-mode`, `prompt-mode` and `developer-messages` exports. Code and Notebook defer notes/history discovery. `new_context` remains a sequential model-only tool, never a nested call. Freshness uses persisted Notes receipts and completed tool outcomes, including generic nested-call evidence through exec and wait.
5
+ Notes uses PCC's public `code-mode`, `prompt-mode` and `developer-messages` exports. Code and Notebook promote Notes' compact discovery entry and routing guidance. History remains deferred. Notes' own on-demand help describes its result fields. `new_context` remains a sequential model-only tool, never a nested call. Freshness uses persisted Notes receipts and completed tool outcomes, including generic nested-call evidence through exec and wait.
6
+
7
+ Notes declares Pi's `outputSchema` and returns its canonical payload as `structuredContent`. Pi's built-in codemode, Code and Notebook receive the same object without parsing display text. Native model-facing text remains unchanged. Shared reads preserve structured paths and availability warnings.
6
8
 
7
9
  Returned kickoff messages are annotated for developer-role delivery, not sent during preparation. Other models retain ordinary Pi custom messages. Context projection remains active for saved retirement boundaries even when Notes is disabled for the selected model.
8
10
 
package/README.md CHANGED
@@ -24,7 +24,9 @@ Ranked search is off by default. It indexes user messages and visible assistant
24
24
 
25
25
  Explicit searches of tool history, a window containing live context or another agent's history use literal substring matching. Search results identify the matching mode. Listing and reading history still includes the full transcript, including ongoing context and tool activity.
26
26
 
27
- Previously shared local notes and history remain readable after the other agent closes or Shepherdr is removed. Notes follows the saved family relationships and attachment aliases without requiring PCC. Reads use the other session's saved branch and preserve its history IDs. When only a retained attachment snapshot is available, notes identify it as detached or potentially stale. Snapshots do not contain history. Cross-agent writes still require their live routing service. History reads Pi JSONL sessions locally or through a live shared agent, including agents on another machine. Without live access, make the saved session available locally.
27
+ Previously shared local notes and history remain readable from accessible saved sessions after the other agent closes or Shepherdr is removed. Notes follows saved family relationships and attachment aliases without requiring PCC or a live parent. Reads use the other session's selected branch and preserve its history IDs. When only a retained attachment snapshot is available, notes identify it as detached or potentially stale. Snapshots do not contain history. Cross-agent writes still require live routing.
28
+
29
+ Shepherdr 0.2.27 remains supported for live sharing, including across connected machines. Reading a closed agent's saved session on another machine requires a saved-session transport that this Shepherdr version does not provide. Resume the shared agent and reconnect its machine, or make its saved Pi JSONL session available locally. Saved reads do not replace hybrid lookup or its encrypted cache with local-only results. History uses Pi JSONL, never remote notes or cached responses.
28
30
 
29
31
  In Code Mode and Notebook, plaintext notes and history return ordinary JavaScript values. Encrypted notes return delivery receipts instead of exposing their contents to JavaScript.
30
32
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-notes-compaction",
3
- "version": "0.0.13",
3
+ "version": "0.0.15",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -13,7 +13,6 @@
13
13
  "src",
14
14
  "README.md",
15
15
  "PCC-INTEGRATION.md",
16
- "changelog.ts",
17
16
  "CHANGELOG.md"
18
17
  ],
19
18
  "engines": {
@@ -24,7 +23,6 @@
24
23
  "license": "MIT",
25
24
  "pi": {
26
25
  "extensions": [
27
- "./changelog.ts",
28
26
  "./src/index.ts"
29
27
  ]
30
28
  },
@@ -39,15 +37,15 @@
39
37
  "better-sqlite3": "13.0.3"
40
38
  },
41
39
  "devDependencies": {
42
- "@howaboua/pi-codex-conversion": "4.0.6",
40
+ "@howaboua/pi-codex-conversion": "4.0.9",
43
41
  "@types/better-sqlite3": "9.6.0"
44
42
  },
45
43
  "peerDependencies": {
46
- "@earendil-works/pi-coding-agent": ">=1.2.0",
44
+ "@earendil-works/pi-coding-agent": ">=1.5.0",
47
45
  "@earendil-works/pi-agent-core": ">=1.0.4",
48
46
  "@earendil-works/pi-ai": ">=1.0.4",
49
47
  "@earendil-works/pi-tui": ">=1.0.4",
50
- "@howaboua/pi-codex-conversion": ">=4.0.6",
48
+ "@howaboua/pi-codex-conversion": ">=4.0.9",
51
49
  "typebox": "*"
52
50
  },
53
51
  "peerDependenciesMeta": {
@@ -57,6 +55,8 @@
57
55
  },
58
56
  "exports": {
59
57
  ".": "./src/index.ts",
60
- "./context-sharing": "./src/context-sharing.ts"
58
+ "./context-sharing": "./src/context-sharing.ts",
59
+ "./saved-session": "./src/saved-session.mjs",
60
+ "./saved-session-index": "./src/saved-session-index.mjs"
61
61
  }
62
62
  }
@@ -1,4 +1,7 @@
1
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
1
+ import type {
2
+ ExtensionContext,
3
+ SessionEntry,
4
+ } from "@earendil-works/pi-coding-agent";
2
5
 
3
6
  export const CONTEXT_AGENT_ENTRY = "codex-context-agent";
4
7
  const CONTEXT_BACKEND_ENTRY = "codex-context-backend";
@@ -8,6 +11,8 @@ export interface ContextAgentIdentity {
8
11
  sessionId: string;
9
12
  threadId: string;
10
13
  agentName: string;
14
+ /** Original persisted Notes address; never changes authenticated remote ownership. */
15
+ storageAgentName?: string;
11
16
  storage?: "remote" | "session";
12
17
  accountScope?: string;
13
18
  backendUrl?: string;
@@ -21,6 +26,61 @@ export type ContextAgentBinding = Omit<
21
26
  storage: "remote" | "session";
22
27
  };
23
28
 
29
+ export const CONTEXT_AGENT_PATTERN =
30
+ "^/[a-zA-Z0-9_-][a-zA-Z0-9_.-]*(?:/[a-zA-Z0-9_-][a-zA-Z0-9_.-]*)*$";
31
+
32
+ export function isContextAgentName(value: unknown): value is string {
33
+ return (
34
+ typeof value === "string" && new RegExp(CONTEXT_AGENT_PATTERN).test(value)
35
+ );
36
+ }
37
+
38
+ export function canonicalAgentName(threadId: string): string {
39
+ if (threadId === "root")
40
+ throw new Error(
41
+ "Pi session ID root conflicts with the legacy /root reference; start a session with another ID",
42
+ );
43
+ const name = `/${threadId}`;
44
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(threadId))
45
+ throw new Error("Invalid Pi session identity");
46
+ return name;
47
+ }
48
+
49
+ export function contextStorageAgentName(
50
+ identity: Pick<ContextAgentIdentity, "agentName" | "storageAgentName">,
51
+ ): string {
52
+ return identity.storageAgentName ?? identity.agentName;
53
+ }
54
+
55
+ /** /root is a local compatibility alias, never an authenticated storage address. */
56
+ export function contextAgentNames(
57
+ identity: Pick<
58
+ ContextAgentIdentity,
59
+ "agentName" | "storageAgentName" | "threadId" | "sessionId"
60
+ >,
61
+ ): string[] {
62
+ return [
63
+ ...new Set([
64
+ identity.agentName,
65
+ contextStorageAgentName(identity),
66
+ ...(identity.threadId === identity.sessionId ? ["/root"] : []),
67
+ ]),
68
+ ];
69
+ }
70
+
71
+ export function canonicalContextIdentity<T extends ContextAgentIdentity>(
72
+ identity: T,
73
+ ): T {
74
+ const agentName = canonicalAgentName(identity.threadId);
75
+ return {
76
+ ...identity,
77
+ agentName,
78
+ ...(contextStorageAgentName(identity) === agentName
79
+ ? {}
80
+ : { storageAgentName: contextStorageAgentName(identity) }),
81
+ };
82
+ }
83
+
24
84
  export function parseContextAgentBinding(input: unknown): ContextAgentBinding {
25
85
  const value = input as Partial<ContextAgentBinding> | undefined;
26
86
  if (
@@ -28,7 +88,9 @@ export function parseContextAgentBinding(input: unknown): ContextAgentBinding {
28
88
  typeof value.sessionId !== "string" ||
29
89
  !value.sessionId ||
30
90
  typeof value.agentName !== "string" ||
31
- !/^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(value.agentName) ||
91
+ !isContextAgentName(value.agentName) ||
92
+ (value.storageAgentName !== undefined &&
93
+ !isContextAgentName(value.storageAgentName)) ||
32
94
  (value.storage !== "remote" && value.storage !== "session") ||
33
95
  (value.backendUrl !== undefined &&
34
96
  (typeof value.backendUrl !== "string" || !value.backendUrl)) ||
@@ -41,6 +103,9 @@ export function parseContextAgentBinding(input: unknown): ContextAgentBinding {
41
103
  protocol: 1,
42
104
  sessionId: value.sessionId,
43
105
  agentName: value.agentName,
106
+ ...(value.storageAgentName === undefined
107
+ ? {}
108
+ : { storageAgentName: value.storageAgentName }),
44
109
  storage: value.storage,
45
110
  ...(value.accountScope === undefined
46
111
  ? {}
@@ -50,6 +115,37 @@ export function parseContextAgentBinding(input: unknown): ContextAgentBinding {
50
115
  };
51
116
  }
52
117
 
118
+ /** Older standalone remote owners may have a backend pin without a family binding. */
119
+ export function pinnedContextIdentity(
120
+ threadId: string,
121
+ entries: readonly SessionEntry[],
122
+ ): ContextAgentIdentity | undefined {
123
+ let identity: ContextAgentIdentity | undefined;
124
+ for (const entry of entries) {
125
+ if (entry.type !== "custom" || entry.customType !== CONTEXT_BACKEND_ENTRY)
126
+ continue;
127
+ const pin = entry.data as Partial<ContextAgentIdentity> | undefined;
128
+ if (pin?.threadId !== threadId) continue;
129
+ const binding = parseContextAgentBinding({
130
+ ...pin,
131
+ protocol: 1,
132
+ storage: "remote",
133
+ });
134
+ if (!binding.backendUrl)
135
+ throw new Error("Saved remote context has no backend address");
136
+ if (
137
+ identity &&
138
+ (identity.sessionId !== binding.sessionId ||
139
+ identity.agentName !== binding.agentName ||
140
+ identity.accountScope !== binding.accountScope ||
141
+ identity.backendUrl !== binding.backendUrl)
142
+ )
143
+ throw new Error("Conflicting persisted Remote context backend");
144
+ identity = { ...binding, threadId };
145
+ }
146
+ return identity;
147
+ }
148
+
53
149
  export function contextAgentIdentity(
54
150
  ctx: Pick<ExtensionContext, "sessionManager">,
55
151
  ): ContextAgentIdentity {
@@ -65,6 +161,7 @@ export function contextAgentIdentity(
65
161
  throw new Error("Conflicting persisted Codex context identities");
66
162
  identity = { ...parseContextAgentBinding(value), threadId };
67
163
  }
164
+ identity ??= pinnedContextIdentity(threadId, ctx.sessionManager.getEntries());
68
165
  if (identity?.storage === "remote") {
69
166
  for (const entry of ctx.sessionManager.getEntries()) {
70
167
  if (entry.type !== "custom" || entry.customType !== CONTEXT_BACKEND_ENTRY)
@@ -73,7 +170,8 @@ export function contextAgentIdentity(
73
170
  if (pin?.threadId !== threadId) continue;
74
171
  if (
75
172
  pin.sessionId !== identity.sessionId ||
76
- pin.agentName !== identity.agentName ||
173
+ (pin.storageAgentName ?? pin.agentName) !==
174
+ contextStorageAgentName(identity) ||
77
175
  pin.accountScope !== identity.accountScope ||
78
176
  typeof pin.backendUrl !== "string" ||
79
177
  !pin.backendUrl ||
@@ -83,13 +181,13 @@ export function contextAgentIdentity(
83
181
  identity.backendUrl = pin.backendUrl;
84
182
  }
85
183
  }
86
- return (
184
+ return canonicalContextIdentity(
87
185
  identity ?? {
88
186
  protocol: 1,
89
187
  sessionId: threadId,
90
188
  threadId,
91
- agentName: "/root",
92
- }
189
+ agentName: canonicalAgentName(threadId),
190
+ },
93
191
  );
94
192
  }
95
193
 
@@ -107,13 +205,17 @@ export function contextTargetAgent(
107
205
  throw new Error("Context path must be a string");
108
206
  if (namespace === "notes") {
109
207
  if (!value.startsWith("/")) return agentName;
110
- const match = /^(\/root(?:\/[a-zA-Z0-9_-]+)*?)\/notes(?:\/|$)/.exec(value);
111
- if (!match)
208
+ const boundary = /\/notes(?:\/|$)/.exec(value)?.index ?? -1;
209
+ const target = boundary < 0 ? "" : value.slice(0, boundary);
210
+ if (
211
+ !isContextAgentName(target) ||
212
+ !/^\/notes(?:\/|$)/.test(value.slice(boundary))
213
+ )
112
214
  throw new Error("Absolute note paths must use <agent>/notes[/path]");
113
- return match[1]!;
215
+ return target;
114
216
  }
115
217
  const target = value.startsWith("/") ? value : `${agentName}/${value}`;
116
- if (!/^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(target))
218
+ if (!isContextAgentName(target))
117
219
  throw new Error("Invalid history agent name");
118
220
  return target;
119
221
  }
@@ -1,11 +1,16 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
2
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
3
- import { contextTargetAgent } from "./agent-identity.js";
3
+ import {
4
+ canonicalContextIdentity,
5
+ contextStorageAgentName,
6
+ contextTargetAgent,
7
+ } from "./agent-identity.js";
4
8
  import {
5
9
  readAttachmentSnapshot,
6
10
  readRemoteNoteReference,
7
11
  } from "./attachment-snapshot.js";
8
12
  import type { ContextSharingService } from "./context-sharing.js";
13
+ import { noteResult } from "./note-result.js";
9
14
  import { exportNotesSnapshot } from "./notes.js";
10
15
 
11
16
  export function createAttachmentSharing(
@@ -48,16 +53,42 @@ export function createAttachmentSharing(
48
53
  if (identity.storage === "remote") {
49
54
  if (
50
55
  !isDeepStrictEqual(
51
- readRemoteNoteReference(snapshot).identity,
52
- identity,
56
+ canonicalContextIdentity(
57
+ readRemoteNoteReference(snapshot).identity,
58
+ ),
59
+ canonicalContextIdentity(identity),
53
60
  )
54
61
  )
55
62
  throw new Error("Remote checkpoint owner changed");
56
- } else
63
+ } else {
57
64
  readAttachmentSnapshot(snapshot, {
58
65
  action: "list_files_by_prefix",
59
66
  prefix: `${identity.agentName}/notes`,
60
67
  });
68
+ if (
69
+ !snapshot ||
70
+ typeof snapshot !== "object" ||
71
+ !("files" in snapshot) ||
72
+ !Array.isArray(snapshot.files) ||
73
+ snapshot.files.some(
74
+ (file: unknown) =>
75
+ !file ||
76
+ typeof file !== "object" ||
77
+ !("path" in file) ||
78
+ typeof file.path !== "string" ||
79
+ ![identity.agentName, contextStorageAgentName(identity)].includes(
80
+ contextTargetAgent(
81
+ "notes",
82
+ { path: file.path },
83
+ identity.agentName,
84
+ ),
85
+ ),
86
+ )
87
+ )
88
+ throw new Error(
89
+ "Retained checkpoint belongs to a different notes owner",
90
+ );
91
+ }
61
92
  },
62
93
  async verifyAttachmentAccess(ctx, snapshot) {
63
94
  if (
@@ -115,10 +146,10 @@ export function createAttachmentSharing(
115
146
  ),
116
147
  };
117
148
  },
118
- readAttachmentNotes(snapshot, params) {
149
+ readAttachmentNotes(snapshot, params, annotation) {
119
150
  const details = readAttachmentSnapshot(snapshot, params);
120
151
  return {
121
- content: [{ type: "text", text: JSON.stringify(details) }],
152
+ ...noteResult({ ...details, ...annotation }),
122
153
  details: { codexHistoryNotes: details },
123
154
  };
124
155
  },
@@ -1,5 +1,6 @@
1
1
  import { Type } from "typebox";
2
2
  import { Check } from "typebox/value";
3
+ import { contextTargetAgent, isContextAgentName } from "./agent-identity.js";
3
4
  import type { RemoteNoteReference } from "./context-sharing.js";
4
5
  import { normalizeNoteParams, readNotes } from "./notes.js";
5
6
  import type { NoteRevision } from "./store.js";
@@ -39,14 +40,21 @@ export function readAttachmentSnapshot(
39
40
  "Retained checkpoints are read-only; resume the attached owner to write notes",
40
41
  );
41
42
  const path = params["path"] ?? params["prefix"] ?? params["path_prefix"];
43
+ const owner = snapshot.files[0]
44
+ ? contextTargetAgent("notes", { path: snapshot.files[0].path }, "/root")
45
+ : "/root";
42
46
  const agent =
43
- typeof path === "string"
44
- ? (/^(\/root(?:\/[a-zA-Z0-9_-]+)*?)\/notes(?:\/|$)/.exec(path)?.[1] ??
45
- "/root")
46
- : "/root";
47
+ typeof path === "string" && path.startsWith("/")
48
+ ? contextTargetAgent("notes", { path }, "/root")
49
+ : owner;
47
50
  const notes = new Map<string, NoteRevision>();
48
51
  for (const file of snapshot.files) {
49
- if (!/^\/root(?:\/[a-zA-Z0-9_-]+)*?\/notes\/.+/.test(file.path))
52
+ if (
53
+ !isContextAgentName(
54
+ contextTargetAgent("notes", { path: file.path }, agent),
55
+ ) ||
56
+ !file.path.includes("/notes/")
57
+ )
50
58
  throw new Error("Invalid retained note path");
51
59
  if (!file.path.startsWith(`${agent}/notes/`)) continue;
52
60
  const local = file.path.slice(`${agent}/notes/`.length);
@@ -93,7 +101,9 @@ export function readRemoteNoteReference(input: unknown): RemoteNoteReference {
93
101
  identity.sessionId.length > 512 ||
94
102
  typeof identity.agentName !== "string" ||
95
103
  identity.agentName.length > 4096 ||
96
- !/^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(identity.agentName) ||
104
+ !isContextAgentName(identity.agentName) ||
105
+ (identity.storageAgentName !== undefined &&
106
+ !isContextAgentName(identity.storageAgentName)) ||
97
107
  typeof identity.accountScope !== "string" ||
98
108
  !/^[a-f0-9]{64}$/.test(identity.accountScope) ||
99
109
  identity.backendUrl !== input.baseUrl
package/src/bridge.ts CHANGED
@@ -85,6 +85,7 @@ export interface NotesOwner {
85
85
 
86
86
  export interface NotesBridge {
87
87
  protocol: 1;
88
+ loadSavedSession?: import("./context-sharing.js").SavedSessionLoader;
88
89
  /** Preserve the owner's chronological entry while enabling developer-role delivery. */
89
90
  prepareReminder?(entry: CustomMessageEntryDraft): CustomMessageEntryDraft;
90
91
  lookup?(
@@ -13,6 +13,14 @@ export type {
13
13
  ContextAgentBinding,
14
14
  ContextAgentIdentity,
15
15
  } from "./agent-identity.js";
16
+ export {
17
+ canonicalAgentName,
18
+ canonicalContextIdentity,
19
+ contextAgentNames,
20
+ contextStorageAgentName,
21
+ contextTargetAgent,
22
+ isContextAgentName,
23
+ } from "./agent-identity.js";
16
24
  export type { ContextFamilyBindingOptions } from "./binding-startup.js";
17
25
  export type { NoteSnapshotData } from "./bridge.js";
18
26
 
@@ -38,6 +46,20 @@ export type ContextRouter = ((
38
46
  requiresRemoteScope?(ctx: ExtensionContext): boolean;
39
47
  };
40
48
 
49
+ export interface SavedSessionLocator {
50
+ machine: string;
51
+ sessionFile: string;
52
+ }
53
+
54
+ export type SavedSessionLoader = ((
55
+ locator: SavedSessionLocator,
56
+ history: boolean,
57
+ signal?: AbortSignal,
58
+ ) => Promise<unknown>) & {
59
+ /** Exact native-thread discovery only; returned locators are untrusted hints. */
60
+ find?(threadId: string, signal?: AbortSignal): Promise<unknown>;
61
+ };
62
+
41
63
  /** Remote checkpoints retain an authenticated address, never decrypted note contents. */
42
64
  export interface RemoteNoteReference {
43
65
  protocol: 1;
@@ -55,7 +77,7 @@ export interface ContextSharingService {
55
77
  verify(ctx: ExtensionContext): Promise<void>;
56
78
  createChild(
57
79
  ctx: ExtensionContext,
58
- options: { name: string; routing?: unknown },
80
+ options: { threadId: string; routing?: unknown },
59
81
  ): Promise<{
60
82
  binding: ContextAgentBinding;
61
83
  adopt(): Promise<void>;
@@ -97,6 +119,12 @@ export interface ContextSharingService {
97
119
  readAttachmentNotes?(
98
120
  snapshot: unknown,
99
121
  params: Record<string, unknown>,
122
+ annotation?: {
123
+ read_only: true;
124
+ captured_at: string;
125
+ saved_at?: string;
126
+ warning: string;
127
+ },
100
128
  ): SharedContextResult;
101
129
  execute(
102
130
  ctx: ExtensionContext,
@@ -104,6 +132,7 @@ export interface ContextSharingService {
104
132
  signal?: AbortSignal,
105
133
  ): Promise<SharedContextResult>;
106
134
  registerRouter(router: ContextRouter): () => void;
135
+ registerSavedSessionLoader?(loader: SavedSessionLoader): () => void;
107
136
  }
108
137
 
109
138
  export const CONTEXT_SHARING_AVAILABLE =
@@ -63,12 +63,24 @@ export async function registerNotesHooks(
63
63
  return;
64
64
  const input = event.args as { action?: unknown } | undefined;
65
65
  if (!isNoteWrite(input)) return;
66
- nestedWrites.set(event.toolCallId, {
66
+ const write = {
67
67
  runId: lifecycle.runId,
68
68
  windowId: lifecycle.windows.current.currentWindowId,
69
69
  parentCallId: event.parentToolCallId,
70
70
  sessionId: ctx.sessionManager.getSessionId(),
71
- });
71
+ };
72
+ // Persist before execution: even a call omitted from Pi's bounded record
73
+ // must prevent rollover until its completion arrives.
74
+ pi.appendEntry(NESTED_NOTE_OUTCOME, {
75
+ protocol: 1,
76
+ runId: write.runId,
77
+ windowId: write.windowId,
78
+ callId: event.toolCallId,
79
+ parentCallId: write.parentCallId,
80
+ pending: true,
81
+ saved: false,
82
+ } satisfies NestedNoteOutcome);
83
+ nestedWrites.set(event.toolCallId, write);
72
84
  });
73
85
  pi.on("tool_execution_end", (event, ctx) => {
74
86
  const write = nestedWrites.get(event.toolCallId);
@@ -81,6 +93,7 @@ export async function registerNotesHooks(
81
93
  windowId: write.windowId,
82
94
  callId: event.toolCallId,
83
95
  parentCallId: write.parentCallId,
96
+ pending: false,
84
97
  ...(details?.notesCompactionRouted === true
85
98
  ? { origin: "routed" as const }
86
99
  : {}),
@@ -4,10 +4,15 @@ import type {
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
6
  import type { NotesActivation } from "./activation.js";
7
- import { contextAgentIdentity, contextTargetAgent } from "./agent-identity.js";
7
+ import {
8
+ contextAgentIdentity,
9
+ contextAgentNames,
10
+ contextTargetAgent,
11
+ } from "./agent-identity.js";
8
12
  import { type NotesOwner, OWNER_CHANNEL, type OwnerRequest } from "./bridge.js";
9
13
  import { optionalPccMissing } from "./integrations.js";
10
14
  import type { NotesLifecycle } from "./lifecycle.js";
15
+ import { noteResult } from "./note-result.js";
11
16
  import { modelIsActive } from "./settings.js";
12
17
  import { registerContextSharingService } from "./sharing-service.js";
13
18
 
@@ -43,6 +48,7 @@ export async function registerNotesSharing(
43
48
  const family = {
44
49
  ...remote,
45
50
  protocol: 1 as const,
51
+ loadSavedSession: route.loadSavedSession,
46
52
  agentName: (ctx: ExtensionContext) => contextAgentIdentity(ctx).agentName,
47
53
  route: async (
48
54
  query: import("./bridge.js").LookupQuery,
@@ -56,7 +62,7 @@ export async function registerNotesSharing(
56
62
  query.params,
57
63
  identity.agentName,
58
64
  );
59
- if (target === identity.agentName) return undefined;
65
+ if (contextAgentNames(identity).includes(target)) return undefined;
60
66
  const result = await route(
61
67
  ctx,
62
68
  { ...query, sessionId: identity.sessionId, agentName: target },
@@ -73,18 +79,27 @@ export async function registerNotesSharing(
73
79
  );
74
80
  if (!result?.details.externalNotesResponses?.length) return result;
75
81
  const { externalNotesResponses, ...details } = result.details;
76
- if (!remote.projectResult || remote.canProject?.(ctx) === false)
82
+ if (!remote.projectResult || remote.canProject?.(ctx) === false) {
83
+ const warning =
84
+ "Shared encrypted contents are unavailable on this model. Local results remain available. Use a compatible Codex model with PCC for remote contents.";
85
+ const data = result.structuredContent;
86
+ if (!data || typeof data !== "object" || Array.isArray(data))
87
+ throw new Error(
88
+ "Shared Notes data is invalid. Update Notes on the other agent and retry.",
89
+ );
77
90
  return {
78
- ...result,
91
+ ...noteResult({
92
+ ...data,
93
+ warnings: [
94
+ ...("warnings" in data && Array.isArray(data["warnings"])
95
+ ? data["warnings"]
96
+ : []),
97
+ warning,
98
+ ],
99
+ }),
79
100
  details,
80
- content: [
81
- ...result.content,
82
- {
83
- type: "text" as const,
84
- text: "Shared encrypted contents are unavailable on this model. Local results remain available. Use a compatible Codex model with PCC for remote contents.",
85
- },
86
- ],
87
101
  };
102
+ }
88
103
  return remote.projectResult(
89
104
  { ...result, details },
90
105
  externalNotesResponses.map(({ bytesBase64, ...response }) => ({
@@ -3,10 +3,36 @@ import type {
3
3
  AgentSettledEvent,
4
4
  BeforeAgentStartEvent,
5
5
  CustomMessageEntryDraft,
6
+ ExtensionAPI,
6
7
  ExtensionContext,
7
8
  } from "@earendil-works/pi-coding-agent";
9
+ import { Text } from "@earendil-works/pi-tui";
8
10
  import type { NotesLifecycle } from "./lifecycle.js";
9
11
 
12
+ const CHECKPOINT_MESSAGE = "notes-compaction:checkpoint:v1";
13
+
14
+ export function registerCheckpointRenderer(pi: ExtensionAPI): void {
15
+ pi.registerMessageRenderer<{ instructions?: string }>(
16
+ CHECKPOINT_MESSAGE,
17
+ (message, _options, theme) => {
18
+ const instructions =
19
+ message.details?.instructions ??
20
+ (typeof message.content === "string"
21
+ ? message.content
22
+ .split("\n\nCheckpoint guidance:\n")
23
+ .slice(1)
24
+ .join("\n\nCheckpoint guidance:\n")
25
+ : "");
26
+ return new Text(
27
+ theme.fg("customMessageLabel", "Context checkpoint") +
28
+ (instructions ? `\n${instructions}` : ""),
29
+ 0,
30
+ 0,
31
+ );
32
+ },
33
+ );
34
+ }
35
+
10
36
  interface Checkpoint {
11
37
  sessionId: string;
12
38
  windowId: string;
@@ -45,7 +71,7 @@ export class FreshCheckpoint {
45
71
  if (
46
72
  this.checkpoint &&
47
73
  event.messageType === "custom" &&
48
- event.message.customType === "notes-compaction:checkpoint:v1" &&
74
+ event.message.customType === CHECKPOINT_MESSAGE &&
49
75
  (event.message.details as { requestId?: string } | undefined)
50
76
  ?.requestId === this.checkpoint.requestId
51
77
  )
@@ -69,9 +95,9 @@ export class FreshCheckpoint {
69
95
  try {
70
96
  this.sendMessage(
71
97
  {
72
- customType: "notes-compaction:checkpoint:v1",
73
- details: { requestId },
74
- content: `<context_window_reminder>\nSave the task state in notes, then finish your reply. A new window opens automatically after your reply; do not call new_context. If saving fails, report the error.\n</context_window_reminder>${instructions?.trim() ? `\n\nCheckpoint guidance:\n${instructions}` : ""}`,
98
+ customType: CHECKPOINT_MESSAGE,
99
+ details: { requestId, instructions: instructions?.trim() },
100
+ content: `<context_window_reminder>\nSave task state in notes, then finish reply. New window opens automatically after reply; do not call new_context.\n</context_window_reminder>${instructions?.trim() ? `\n\nCheckpoint guidance:\n${instructions}` : ""}`,
75
101
  display: true,
76
102
  },
77
103
  { triggerTurn: true },