@howaboua/pi-notes-compaction 0.0.8 → 0.0.10
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.
- package/CHANGELOG.md +31 -5
- package/PCC-INTEGRATION.md +7 -98
- package/README.md +22 -14
- package/package.json +7 -3
- package/src/activation.ts +152 -0
- package/src/agent-identity.ts +119 -0
- package/src/attachment-snapshot.ts +103 -0
- package/src/binding-startup.ts +30 -0
- package/src/bridge.ts +1 -43
- package/src/compaction-projection.ts +88 -0
- package/src/context-owner.ts +103 -0
- package/src/context-sharing.ts +144 -0
- package/src/extension-hooks.ts +198 -0
- package/src/extension-sharing.ts +118 -0
- package/src/fresh-checkpoint.ts +117 -0
- package/src/fresh-notes.ts +141 -26
- package/src/history-search-protocol.ts +39 -0
- package/src/history-search-pruning.mjs +120 -0
- package/src/history-search-worker.mjs +256 -0
- package/src/history-search.ts +269 -0
- package/src/history.ts +219 -48
- package/src/idle-admission.ts +201 -0
- package/src/index.ts +71 -401
- package/src/integrations.ts +159 -0
- package/src/lifecycle.ts +63 -448
- package/src/note-save-marker.ts +112 -0
- package/src/notes-lookup.ts +112 -0
- package/src/notes.ts +25 -30
- package/src/query-executor.ts +190 -0
- package/src/remote.ts +357 -0
- package/src/rollover.ts +212 -0
- package/src/saved-session.ts +44 -7
- package/src/session-pruning-content.ts +237 -0
- package/src/session-pruning-plan.ts +243 -0
- package/src/session-pruning-policy.ts +20 -0
- package/src/session-pruning-screen.ts +130 -0
- package/src/session-pruning-source.ts +44 -0
- package/src/session-pruning-transaction.ts +141 -0
- package/src/session-pruning.ts +142 -0
- package/src/settings-command.ts +77 -0
- package/src/settings-screen.ts +89 -20
- package/src/settings.ts +152 -15
- package/src/shared-notes.ts +37 -14
- package/src/sharing-service.ts +348 -0
- package/src/store.ts +31 -0
- package/src/task-boundary.ts +6 -1
- package/src/tool-contracts.ts +279 -0
- package/src/tools.ts +19 -556
- package/src/tree-archive.ts +149 -0
- package/src/tree-checkpoint.ts +170 -0
- package/src/tree-handoff-read.ts +192 -0
- package/src/window-checkpoint.ts +105 -0
- package/src/windows.ts +28 -8
package/src/settings.ts
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { dirname } from "node:path";
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
export
|
|
4
|
+
// Hour presets store their effective duration, with five minutes of headroom.
|
|
5
|
+
export const IDLE_MINUTES = [0, 25, 55, 115, 355, 715] as const;
|
|
6
|
+
export type IdleMinutes = (typeof IDLE_MINUTES)[number] | 5 | 15;
|
|
6
7
|
export const NEW_WINDOW_REQUESTS = [
|
|
7
8
|
"off",
|
|
8
9
|
"pi-limits",
|
|
9
10
|
"unrestricted",
|
|
10
11
|
] as const;
|
|
11
12
|
export type NewWindowRequests = (typeof NEW_WINDOW_REQUESTS)[number];
|
|
12
|
-
|
|
13
|
+
const DEFAULT_MODEL_WHITELIST = [
|
|
13
14
|
"gpt-6-astra",
|
|
14
15
|
"gpt-6-sol",
|
|
15
16
|
"gpt-6-luna",
|
|
@@ -19,25 +20,40 @@ export interface NotesSettings {
|
|
|
19
20
|
active: "all" | "whitelist";
|
|
20
21
|
modelWhitelist: string[];
|
|
21
22
|
normalCompaction: boolean;
|
|
23
|
+
noteSaveMarkers: boolean;
|
|
24
|
+
rankedHistorySearch: boolean;
|
|
25
|
+
shareSubagentContext: boolean;
|
|
22
26
|
newWindowRequests: NewWindowRequests;
|
|
23
27
|
idleMinutes: IdleMinutes;
|
|
24
28
|
taskBoundaryReminder: number;
|
|
25
29
|
}
|
|
26
30
|
|
|
27
|
-
export function readSettings(
|
|
31
|
+
export function readSettings(
|
|
32
|
+
path: string,
|
|
33
|
+
legacyPaths: readonly string[] = [],
|
|
34
|
+
): NotesSettings {
|
|
35
|
+
let legacy: ReturnType<typeof readLegacyPreferences> | undefined;
|
|
36
|
+
const preferences = () => (legacy ??= readLegacyPreferences(legacyPaths));
|
|
28
37
|
let source: string;
|
|
29
38
|
try {
|
|
30
39
|
source = readFileSync(path, "utf8");
|
|
31
40
|
} catch (error) {
|
|
32
|
-
if ((error as NodeJS.ErrnoException).code === "ENOENT")
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
42
|
+
const migrated = readLegacySettings(preferences());
|
|
43
|
+
return (
|
|
44
|
+
migrated ?? {
|
|
45
|
+
active: "all",
|
|
46
|
+
modelWhitelist: [...DEFAULT_MODEL_WHITELIST],
|
|
47
|
+
normalCompaction: false,
|
|
48
|
+
rankedHistorySearch: false,
|
|
49
|
+
noteSaveMarkers: preferences().noteSaveMarkers,
|
|
50
|
+
shareSubagentContext: false,
|
|
51
|
+
newWindowRequests: "unrestricted",
|
|
52
|
+
idleMinutes: 0,
|
|
53
|
+
taskBoundaryReminder: 0,
|
|
54
|
+
}
|
|
55
|
+
);
|
|
56
|
+
}
|
|
41
57
|
throw error;
|
|
42
58
|
}
|
|
43
59
|
const settings: unknown = JSON.parse(source);
|
|
@@ -67,6 +83,12 @@ export function readSettings(path: string): NotesSettings {
|
|
|
67
83
|
`Invalid modelWhitelist in ${path}. Use an array of model ID strings, then reload Pi.`,
|
|
68
84
|
);
|
|
69
85
|
const idleMinutes = "idleMinutes" in settings ? settings.idleMinutes : 0;
|
|
86
|
+
const rankedHistorySearch =
|
|
87
|
+
"rankedHistorySearch" in settings ? settings.rankedHistorySearch : false;
|
|
88
|
+
if (typeof rankedHistorySearch !== "boolean")
|
|
89
|
+
throw new Error(
|
|
90
|
+
`Invalid rankedHistorySearch in ${path}. Use true or false, then reload Pi.`,
|
|
91
|
+
);
|
|
70
92
|
const newWindowRequests =
|
|
71
93
|
"newWindowRequests" in settings
|
|
72
94
|
? settings.newWindowRequests
|
|
@@ -85,14 +107,27 @@ export function readSettings(path: string): NotesSettings {
|
|
|
85
107
|
throw new Error(
|
|
86
108
|
"Invalid task-boundary reminder setting. Save a setting in /notes, then reload Pi.",
|
|
87
109
|
);
|
|
88
|
-
if (
|
|
110
|
+
if (
|
|
111
|
+
idleMinutes !== 5 &&
|
|
112
|
+
idleMinutes !== 15 &&
|
|
113
|
+
!IDLE_MINUTES.some((value) => value === idleMinutes)
|
|
114
|
+
)
|
|
89
115
|
throw new Error(
|
|
90
|
-
"Invalid idle rollover interval.
|
|
116
|
+
"Invalid idle rollover interval. Set idleMinutes to 0, 25, 55, 115, 355 or 715, then reload Pi.",
|
|
91
117
|
);
|
|
92
118
|
return {
|
|
93
119
|
active,
|
|
94
120
|
modelWhitelist,
|
|
95
121
|
normalCompaction: settings.normalCompaction,
|
|
122
|
+
rankedHistorySearch,
|
|
123
|
+
noteSaveMarkers:
|
|
124
|
+
"noteSaveMarkers" in settings
|
|
125
|
+
? settings.noteSaveMarkers === true
|
|
126
|
+
: preferences().noteSaveMarkers,
|
|
127
|
+
shareSubagentContext:
|
|
128
|
+
"shareSubagentContext" in settings
|
|
129
|
+
? settings.shareSubagentContext === true
|
|
130
|
+
: preferences().compaction["shareSubagentContext"] === true,
|
|
96
131
|
newWindowRequests: newWindowRequests as NewWindowRequests,
|
|
97
132
|
idleMinutes: idleMinutes as IdleMinutes,
|
|
98
133
|
taskBoundaryReminder,
|
|
@@ -117,3 +152,105 @@ export function writeSettings(path: string, settings: NotesSettings): void {
|
|
|
117
152
|
});
|
|
118
153
|
renameSync(temporary, path);
|
|
119
154
|
}
|
|
155
|
+
|
|
156
|
+
/** Import only on first use. An existing Notes settings file always wins. */
|
|
157
|
+
function readLegacySettings(
|
|
158
|
+
preferences: ReturnType<typeof readLegacyPreferences>,
|
|
159
|
+
): NotesSettings | undefined {
|
|
160
|
+
const value = preferences.compaction;
|
|
161
|
+
if (!["notes", "notes-and-compaction"].includes(String(value["continuity"])))
|
|
162
|
+
return;
|
|
163
|
+
const oldIdle = value["idleNotesRollover"];
|
|
164
|
+
const idle = oldIdle === true ? 25 : oldIdle === false ? 0 : (oldIdle ?? 0);
|
|
165
|
+
const requests =
|
|
166
|
+
"newWindowRequests" in value ? value["newWindowRequests"] : "unrestricted";
|
|
167
|
+
const reminder =
|
|
168
|
+
"taskBoundaryReminder" in value ? value["taskBoundaryReminder"] : 0;
|
|
169
|
+
return {
|
|
170
|
+
active: "all",
|
|
171
|
+
modelWhitelist: [...DEFAULT_MODEL_WHITELIST],
|
|
172
|
+
normalCompaction: value["continuity"] === "notes-and-compaction",
|
|
173
|
+
rankedHistorySearch: false,
|
|
174
|
+
noteSaveMarkers: preferences.noteSaveMarkers,
|
|
175
|
+
shareSubagentContext:
|
|
176
|
+
"shareSubagentContext" in value && value["shareSubagentContext"] === true,
|
|
177
|
+
newWindowRequests: NEW_WINDOW_REQUESTS.some((item) => item === requests)
|
|
178
|
+
? (requests as NewWindowRequests)
|
|
179
|
+
: "unrestricted",
|
|
180
|
+
idleMinutes: [...IDLE_MINUTES, 5, 15].some((item) => item === idle)
|
|
181
|
+
? (idle as IdleMinutes)
|
|
182
|
+
: 0,
|
|
183
|
+
taskBoundaryReminder:
|
|
184
|
+
typeof reminder === "number" &&
|
|
185
|
+
Number.isSafeInteger(reminder) &&
|
|
186
|
+
reminder >= 0
|
|
187
|
+
? reminder
|
|
188
|
+
: 0,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Global first, then the trusted project's explicitly configured values. */
|
|
193
|
+
function readLegacyPreferences(paths: readonly string[]): {
|
|
194
|
+
compaction: Record<string, unknown>;
|
|
195
|
+
noteSaveMarkers: boolean;
|
|
196
|
+
} {
|
|
197
|
+
const compaction: Record<string, unknown> = {};
|
|
198
|
+
let noteSaveMarkers = false;
|
|
199
|
+
for (const path of paths) {
|
|
200
|
+
let document: unknown;
|
|
201
|
+
try {
|
|
202
|
+
document = JSON.parse(readFileSync(path, "utf8"));
|
|
203
|
+
} catch (error) {
|
|
204
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
|
|
205
|
+
throw error;
|
|
206
|
+
}
|
|
207
|
+
if (!document || typeof document !== "object" || Array.isArray(document))
|
|
208
|
+
continue;
|
|
209
|
+
if (
|
|
210
|
+
"compaction" in document &&
|
|
211
|
+
document.compaction &&
|
|
212
|
+
typeof document.compaction === "object" &&
|
|
213
|
+
!Array.isArray(document.compaction)
|
|
214
|
+
) {
|
|
215
|
+
// Old PCC releases migrated these axes in memory only. Translate each
|
|
216
|
+
// scope before layering so project opt-outs and current fields win.
|
|
217
|
+
const value = document.compaction as Record<string, unknown>;
|
|
218
|
+
const mode = value["contextManagement"];
|
|
219
|
+
const modeOverride =
|
|
220
|
+
mode === "off" ||
|
|
221
|
+
mode === "local" ||
|
|
222
|
+
mode === "tree" ||
|
|
223
|
+
mode === "remote";
|
|
224
|
+
const inheritedNotes =
|
|
225
|
+
compaction["continuity"] === "notes" ||
|
|
226
|
+
compaction["continuity"] === "notes-and-compaction";
|
|
227
|
+
const notes = modeOverride ? mode !== "off" : inheritedNotes;
|
|
228
|
+
const hybrid =
|
|
229
|
+
typeof value["hybridCompaction"] === "boolean"
|
|
230
|
+
? value["hybridCompaction"]
|
|
231
|
+
: compaction["continuity"] === "notes-and-compaction";
|
|
232
|
+
if (
|
|
233
|
+
modeOverride ||
|
|
234
|
+
(notes && typeof value["hybridCompaction"] === "boolean")
|
|
235
|
+
)
|
|
236
|
+
compaction["continuity"] = notes
|
|
237
|
+
? hybrid
|
|
238
|
+
? "notes-and-compaction"
|
|
239
|
+
: "notes"
|
|
240
|
+
: "compaction";
|
|
241
|
+
Object.assign(compaction, document.compaction);
|
|
242
|
+
}
|
|
243
|
+
for (const key of ["display", "ui"]) {
|
|
244
|
+
const section = (document as Record<string, unknown>)[key];
|
|
245
|
+
if (
|
|
246
|
+
section &&
|
|
247
|
+
typeof section === "object" &&
|
|
248
|
+
"noteSaveMarkers" in section
|
|
249
|
+
) {
|
|
250
|
+
noteSaveMarkers = section.noteSaveMarkers === true;
|
|
251
|
+
break;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return { compaction, noteSaveMarkers };
|
|
256
|
+
}
|
package/src/shared-notes.ts
CHANGED
|
@@ -6,6 +6,7 @@ import type {
|
|
|
6
6
|
import { type Static, Type } from "typebox";
|
|
7
7
|
import { Check } from "typebox/value";
|
|
8
8
|
import { useHistory } from "./history.js";
|
|
9
|
+
import type { HistorySearch } from "./history-search.js";
|
|
9
10
|
import { collectNotes, normalizeNoteParams, readNotes } from "./notes.js";
|
|
10
11
|
import {
|
|
11
12
|
readSavedNotesSession,
|
|
@@ -154,25 +155,35 @@ export async function readSharedNotes(
|
|
|
154
155
|
params: Record<string, unknown>,
|
|
155
156
|
signal?: AbortSignal,
|
|
156
157
|
): Promise<Record<string, unknown> | undefined> {
|
|
157
|
-
return readSharedSession(ctx, store, params, "notes", signal);
|
|
158
|
+
return readSharedSession(ctx, store, params, { namespace: "notes" }, signal);
|
|
158
159
|
}
|
|
159
160
|
|
|
160
161
|
export async function readSharedHistory(
|
|
161
162
|
ctx: ExtensionContext,
|
|
162
163
|
store: Pick<NotesStore, "read">,
|
|
164
|
+
search: HistorySearch,
|
|
163
165
|
params: Record<string, unknown>,
|
|
164
166
|
signal?: AbortSignal,
|
|
165
167
|
): Promise<Record<string, unknown> | undefined> {
|
|
166
|
-
return readSharedSession(
|
|
168
|
+
return readSharedSession(
|
|
169
|
+
ctx,
|
|
170
|
+
store,
|
|
171
|
+
params,
|
|
172
|
+
{ namespace: "history", search },
|
|
173
|
+
signal,
|
|
174
|
+
);
|
|
167
175
|
}
|
|
168
176
|
|
|
169
177
|
async function readSharedSession(
|
|
170
178
|
ctx: ExtensionContext,
|
|
171
179
|
store: Pick<NotesStore, "read">,
|
|
172
180
|
params: Record<string, unknown>,
|
|
173
|
-
|
|
181
|
+
access:
|
|
182
|
+
| { namespace: "notes" }
|
|
183
|
+
| { namespace: "history"; search: HistorySearch },
|
|
174
184
|
signal?: AbortSignal,
|
|
175
185
|
): Promise<Record<string, unknown> | undefined> {
|
|
186
|
+
const { namespace } = access;
|
|
176
187
|
if (
|
|
177
188
|
namespace === "notes" &&
|
|
178
189
|
!["read_file", "list_files_by_prefix", "search_contents"].includes(
|
|
@@ -201,22 +212,33 @@ async function readSharedSession(
|
|
|
201
212
|
if (savedNotesIdentity(current).agentName === target) return;
|
|
202
213
|
const visited = new Set<string>();
|
|
203
214
|
|
|
204
|
-
function read(
|
|
215
|
+
async function read(
|
|
205
216
|
session: SavedNotesSession,
|
|
206
217
|
query: Record<string, unknown>,
|
|
207
218
|
native: string,
|
|
208
219
|
) {
|
|
209
220
|
return {
|
|
210
|
-
...(namespace === "history"
|
|
211
|
-
? useHistory(
|
|
221
|
+
...(access.namespace === "history"
|
|
222
|
+
? await useHistory(
|
|
223
|
+
session.branch,
|
|
224
|
+
query,
|
|
225
|
+
session.threadId,
|
|
226
|
+
access.search,
|
|
227
|
+
session.entries,
|
|
228
|
+
signal,
|
|
229
|
+
)
|
|
212
230
|
: readNotes(
|
|
213
231
|
collectNotes(store, session.branch),
|
|
214
232
|
normalizeNoteParams(query, native),
|
|
215
233
|
outputAgent,
|
|
216
234
|
)),
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
235
|
+
...(namespace === "notes"
|
|
236
|
+
? {
|
|
237
|
+
read_only: true,
|
|
238
|
+
warning:
|
|
239
|
+
"Only saved notes are included; other notes may be missing",
|
|
240
|
+
}
|
|
241
|
+
: {}),
|
|
220
242
|
...(session.savedAt === undefined
|
|
221
243
|
? {}
|
|
222
244
|
: { saved_at: new Date(session.savedAt).toISOString() }),
|
|
@@ -277,14 +299,15 @@ async function readSharedSession(
|
|
|
277
299
|
},
|
|
278
300
|
};
|
|
279
301
|
return {
|
|
280
|
-
...read(
|
|
302
|
+
...(await read(
|
|
281
303
|
{ threadId: identity.threadId, entries: [], branch: [entry] },
|
|
282
304
|
query,
|
|
283
305
|
identity.agentName,
|
|
284
|
-
),
|
|
285
|
-
source: "retained-checkpoints",
|
|
306
|
+
)),
|
|
286
307
|
captured_at: new Date(retained.timestamp).toISOString(),
|
|
287
|
-
|
|
308
|
+
warning: detached
|
|
309
|
+
? "Read-only notes captured when sharing ended; later changes are not included"
|
|
310
|
+
: "The latest notes are unavailable; this read-only copy may be outdated",
|
|
288
311
|
};
|
|
289
312
|
}
|
|
290
313
|
async function resolve(
|
|
@@ -413,7 +436,7 @@ async function readSharedSession(
|
|
|
413
436
|
["ENOENT", "EACCES", "EPERM"].includes(String(error.code))
|
|
414
437
|
)
|
|
415
438
|
throw new Error(
|
|
416
|
-
|
|
439
|
+
`Saved shared ${namespace} are unavailable on this machine. Restore access to the saved Pi JSONL session, then retry.`,
|
|
417
440
|
{ cause: error },
|
|
418
441
|
);
|
|
419
442
|
throw error;
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3
|
+
import type {
|
|
4
|
+
ExtensionAPI,
|
|
5
|
+
ExtensionContext,
|
|
6
|
+
SessionEntry,
|
|
7
|
+
} from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import {
|
|
9
|
+
CONTEXT_AGENT_ENTRY,
|
|
10
|
+
contextAgentIdentity,
|
|
11
|
+
contextTargetAgent,
|
|
12
|
+
parseContextAgentBinding,
|
|
13
|
+
} from "./agent-identity.js";
|
|
14
|
+
import {
|
|
15
|
+
readAttachmentSnapshot,
|
|
16
|
+
readRemoteNoteReference,
|
|
17
|
+
} from "./attachment-snapshot.js";
|
|
18
|
+
import { bindingStartupEntries } from "./binding-startup.js";
|
|
19
|
+
import type { NotesOwner } from "./bridge.js";
|
|
20
|
+
import {
|
|
21
|
+
CONTEXT_SHARING_AVAILABLE,
|
|
22
|
+
CONTEXT_SHARING_REQUEST,
|
|
23
|
+
type ContextRouter,
|
|
24
|
+
type ContextSharingService,
|
|
25
|
+
type SharedContextRequest,
|
|
26
|
+
type SharedContextResult,
|
|
27
|
+
} from "./context-sharing.js";
|
|
28
|
+
import { exportNotesSnapshot } from "./notes.js";
|
|
29
|
+
|
|
30
|
+
export function registerContextSharingService(
|
|
31
|
+
pi: ExtensionAPI,
|
|
32
|
+
config: {
|
|
33
|
+
enabled(ctx: ExtensionContext): boolean;
|
|
34
|
+
shareSubagentContext(ctx: ExtensionContext): boolean;
|
|
35
|
+
execute(
|
|
36
|
+
ctx: ExtensionContext,
|
|
37
|
+
request: SharedContextRequest,
|
|
38
|
+
signal?: AbortSignal,
|
|
39
|
+
): Promise<SharedContextResult>;
|
|
40
|
+
owner(): NotesOwner;
|
|
41
|
+
},
|
|
42
|
+
): ContextRouter {
|
|
43
|
+
let router: ContextRouter | undefined;
|
|
44
|
+
const describe: ContextSharingService["describe"] = (ctx) => {
|
|
45
|
+
const storageMode = config.enabled(ctx);
|
|
46
|
+
if (!storageMode) return undefined;
|
|
47
|
+
const identity = contextAgentIdentity(ctx);
|
|
48
|
+
// Saved attachment identities are immutable even after their writer retires.
|
|
49
|
+
const storage = identity.storage ?? "session";
|
|
50
|
+
return { ...identity, storage };
|
|
51
|
+
};
|
|
52
|
+
const inspectAttachment: NonNullable<
|
|
53
|
+
ContextSharingService["inspectAttachment"]
|
|
54
|
+
> = (ctx, standalone = true) => {
|
|
55
|
+
const check = () => {
|
|
56
|
+
const identity = describe(ctx);
|
|
57
|
+
if (!identity)
|
|
58
|
+
throw new Error("Context attachment requires notes-based continuity");
|
|
59
|
+
if (standalone && !ctx.isIdle())
|
|
60
|
+
throw new Error("Attach context only after the target settles");
|
|
61
|
+
if (!ctx.sessionManager.getSessionFile())
|
|
62
|
+
throw new Error("Context attachment requires a saved Pi session");
|
|
63
|
+
if (standalone && contextAgentIdentity(ctx).storage)
|
|
64
|
+
throw new Error("Target already belongs to a shared context family");
|
|
65
|
+
if (!router)
|
|
66
|
+
throw new Error(
|
|
67
|
+
"Context attachment requires an available context router",
|
|
68
|
+
);
|
|
69
|
+
return identity;
|
|
70
|
+
};
|
|
71
|
+
const identity = check();
|
|
72
|
+
return identity;
|
|
73
|
+
};
|
|
74
|
+
const service: ContextSharingService = {
|
|
75
|
+
protocol: 1,
|
|
76
|
+
canCreateChild: (ctx) => config.shareSubagentContext(ctx),
|
|
77
|
+
describe,
|
|
78
|
+
async verify() {},
|
|
79
|
+
async createChild(ctx, options) {
|
|
80
|
+
if (!service.canCreateChild(ctx))
|
|
81
|
+
throw new Error(
|
|
82
|
+
"Shared subagent context is disabled; enable it in /notes",
|
|
83
|
+
);
|
|
84
|
+
const parent = describe(ctx);
|
|
85
|
+
if (!parent)
|
|
86
|
+
throw new Error("Shared context requires notes-based continuity");
|
|
87
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(options.name))
|
|
88
|
+
throw new Error("Invalid context agent name");
|
|
89
|
+
if (!router || options.routing === undefined)
|
|
90
|
+
throw new Error("Local sharing requires a registered context router");
|
|
91
|
+
|
|
92
|
+
if (ctx.sessionManager.getSessionId() !== parent.threadId)
|
|
93
|
+
throw new Error(
|
|
94
|
+
"Controller session changed while preparing shared context",
|
|
95
|
+
);
|
|
96
|
+
const binding = {
|
|
97
|
+
protocol: 1 as const,
|
|
98
|
+
sessionId: parent.sessionId,
|
|
99
|
+
agentName: `${parent.agentName}/${options.name}-${randomUUID()}`,
|
|
100
|
+
storage: "session" as const,
|
|
101
|
+
...(parent.accountScope ? { accountScope: parent.accountScope } : {}),
|
|
102
|
+
...(parent.backendUrl ? { backendUrl: parent.backendUrl } : {}),
|
|
103
|
+
...(options.routing === undefined ? {} : { routing: options.routing }),
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
binding,
|
|
107
|
+
async adopt() {
|
|
108
|
+
const current = describe(ctx);
|
|
109
|
+
if (
|
|
110
|
+
!current ||
|
|
111
|
+
current.threadId !== parent.threadId ||
|
|
112
|
+
current.sessionId !== parent.sessionId ||
|
|
113
|
+
current.agentName !== parent.agentName ||
|
|
114
|
+
current.storage !== parent.storage ||
|
|
115
|
+
(current.accountScope !== undefined &&
|
|
116
|
+
current.accountScope !== parent.accountScope)
|
|
117
|
+
)
|
|
118
|
+
throw new Error(
|
|
119
|
+
"Controller context changed while binding shared context",
|
|
120
|
+
);
|
|
121
|
+
if (!contextAgentIdentity(ctx).storage)
|
|
122
|
+
pi.appendEntry(CONTEXT_AGENT_ENTRY, parent);
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
},
|
|
126
|
+
async bind(ctx, input, options) {
|
|
127
|
+
const binding = parseContextAgentBinding(input);
|
|
128
|
+
if (binding.agentName === "/root")
|
|
129
|
+
throw new Error("Shared context binding requires a child agent path");
|
|
130
|
+
const identity = {
|
|
131
|
+
...binding,
|
|
132
|
+
threadId: ctx.sessionManager.getSessionId(),
|
|
133
|
+
};
|
|
134
|
+
const check = () => {
|
|
135
|
+
if (ctx.sessionManager.getSessionId() !== identity.threadId)
|
|
136
|
+
throw new Error(
|
|
137
|
+
"Worker session changed while binding shared context",
|
|
138
|
+
);
|
|
139
|
+
const current = describe(ctx);
|
|
140
|
+
if (!current || current.storage !== binding.storage)
|
|
141
|
+
throw new Error(
|
|
142
|
+
"Shared context binding requires matching history storage",
|
|
143
|
+
);
|
|
144
|
+
if (contextAgentIdentity(ctx).storage) {
|
|
145
|
+
if (!isDeepStrictEqual(current, identity))
|
|
146
|
+
throw new Error("An existing context identity cannot be rebound");
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
const owner = config.owner();
|
|
150
|
+
const entries = bindingStartupEntries(ctx, options);
|
|
151
|
+
if (!ctx.isIdle() || !owner.canBind?.(ctx, entries))
|
|
152
|
+
throw new Error(
|
|
153
|
+
"Shared context requires an idle child before its first turn; inherited fork history needs an explicit boundary",
|
|
154
|
+
);
|
|
155
|
+
if (binding.storage === "session" && !router)
|
|
156
|
+
throw new Error("Local sharing requires a registered context router");
|
|
157
|
+
return false;
|
|
158
|
+
};
|
|
159
|
+
check();
|
|
160
|
+
if (binding.storage === "remote")
|
|
161
|
+
throw new Error("New shared agents require local Notes storage");
|
|
162
|
+
// Auth can yield to input or a session switch; the live owner commits only while still fresh.
|
|
163
|
+
if (!check()) pi.appendEntry(CONTEXT_AGENT_ENTRY, identity);
|
|
164
|
+
return identity;
|
|
165
|
+
},
|
|
166
|
+
inspectAttachment,
|
|
167
|
+
retainAttachmentIdentity(ctx) {
|
|
168
|
+
const native = describe(ctx);
|
|
169
|
+
if (!native || !router || !ctx.sessionManager.getSessionFile())
|
|
170
|
+
throw new Error(
|
|
171
|
+
"Context attachment requires a saved owner and live router",
|
|
172
|
+
);
|
|
173
|
+
const identity = native;
|
|
174
|
+
if (!contextAgentIdentity(ctx).storage)
|
|
175
|
+
pi.appendEntry(CONTEXT_AGENT_ENTRY, identity);
|
|
176
|
+
return identity;
|
|
177
|
+
},
|
|
178
|
+
async execute(ctx, request, signal) {
|
|
179
|
+
signal?.throwIfAborted();
|
|
180
|
+
const identity = describe(ctx);
|
|
181
|
+
if (
|
|
182
|
+
!identity ||
|
|
183
|
+
identity.sessionId !== request.sessionId ||
|
|
184
|
+
identity.agentName !== request.agentName ||
|
|
185
|
+
(request.namespace !== "notes" && request.namespace !== "history") ||
|
|
186
|
+
!request.params ||
|
|
187
|
+
typeof request.params !== "object" ||
|
|
188
|
+
Array.isArray(request.params) ||
|
|
189
|
+
contextTargetAgent(
|
|
190
|
+
request.namespace,
|
|
191
|
+
request.params,
|
|
192
|
+
identity.agentName,
|
|
193
|
+
) !== identity.agentName
|
|
194
|
+
)
|
|
195
|
+
throw new Error("Shared context request does not belong to this agent");
|
|
196
|
+
if (request.encryptedArguments)
|
|
197
|
+
throw new Error(
|
|
198
|
+
"Encrypted Remote arguments cannot execute against Local storage; use Code or Notebook history/notes with ordinary query/text",
|
|
199
|
+
);
|
|
200
|
+
return config.execute(ctx, request, signal);
|
|
201
|
+
},
|
|
202
|
+
exportAttachmentNotes(ctx) {
|
|
203
|
+
const identity = describe(ctx);
|
|
204
|
+
if (!identity)
|
|
205
|
+
throw new Error("Checkpoint export requires notes-based continuity");
|
|
206
|
+
if (identity.storage === "remote") {
|
|
207
|
+
if (!identity.backendUrl)
|
|
208
|
+
throw new Error("Saved remote context has no backend address");
|
|
209
|
+
return {
|
|
210
|
+
protocol: 1,
|
|
211
|
+
storage: "remote",
|
|
212
|
+
timestamp: Date.now(),
|
|
213
|
+
identity,
|
|
214
|
+
baseUrl: identity.backendUrl,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const snapshot = exportNotesSnapshot(
|
|
219
|
+
ctx.sessionManager.getBranch(),
|
|
220
|
+
identity.agentName,
|
|
221
|
+
);
|
|
222
|
+
return {
|
|
223
|
+
...snapshot,
|
|
224
|
+
files: snapshot.files.filter(
|
|
225
|
+
(file) =>
|
|
226
|
+
contextTargetAgent(
|
|
227
|
+
"notes",
|
|
228
|
+
{ path: file.path },
|
|
229
|
+
identity.agentName,
|
|
230
|
+
) === identity.agentName,
|
|
231
|
+
),
|
|
232
|
+
};
|
|
233
|
+
},
|
|
234
|
+
validateAttachmentNotes(snapshot, identity) {
|
|
235
|
+
if (identity.storage === "remote") {
|
|
236
|
+
if (
|
|
237
|
+
!isDeepStrictEqual(
|
|
238
|
+
readRemoteNoteReference(snapshot).identity,
|
|
239
|
+
identity,
|
|
240
|
+
)
|
|
241
|
+
)
|
|
242
|
+
throw new Error("Remote checkpoint owner changed");
|
|
243
|
+
} else
|
|
244
|
+
readAttachmentSnapshot(snapshot, {
|
|
245
|
+
action: "list_files_by_prefix",
|
|
246
|
+
prefix: `${identity.agentName}/notes`,
|
|
247
|
+
});
|
|
248
|
+
},
|
|
249
|
+
async verifyAttachmentAccess(ctx, snapshot) {
|
|
250
|
+
if (
|
|
251
|
+
!snapshot ||
|
|
252
|
+
typeof snapshot !== "object" ||
|
|
253
|
+
!("storage" in snapshot) ||
|
|
254
|
+
snapshot.storage !== "remote"
|
|
255
|
+
)
|
|
256
|
+
return;
|
|
257
|
+
const { verifyRemoteReference } = await import("./remote.js");
|
|
258
|
+
await verifyRemoteReference(ctx, readRemoteNoteReference(snapshot));
|
|
259
|
+
},
|
|
260
|
+
async executeRemoteAttachment(ctx, snapshot, request, signal) {
|
|
261
|
+
if (request.namespace === "history")
|
|
262
|
+
throw new Error(
|
|
263
|
+
"History is unavailable from a saved remote notes attachment. Open its saved Pi JSONL session on this machine, then retry.",
|
|
264
|
+
);
|
|
265
|
+
const { executeRemoteAttachment } = await import("./remote.js");
|
|
266
|
+
return executeRemoteAttachment(
|
|
267
|
+
ctx,
|
|
268
|
+
readRemoteNoteReference(snapshot),
|
|
269
|
+
request,
|
|
270
|
+
signal,
|
|
271
|
+
);
|
|
272
|
+
},
|
|
273
|
+
parseAttachmentNotes(input, identity) {
|
|
274
|
+
if (!Array.isArray(input))
|
|
275
|
+
throw new Error("Invalid persisted checkpoint entries");
|
|
276
|
+
const entries: SessionEntry[] = input.map((entry: unknown) => {
|
|
277
|
+
if (
|
|
278
|
+
!entry ||
|
|
279
|
+
typeof entry !== "object" ||
|
|
280
|
+
!("type" in entry) ||
|
|
281
|
+
!(
|
|
282
|
+
(entry.type === "custom" &&
|
|
283
|
+
"customType" in entry &&
|
|
284
|
+
typeof entry.customType === "string" &&
|
|
285
|
+
"data" in entry) ||
|
|
286
|
+
(entry.type === "branch_summary" && "details" in entry)
|
|
287
|
+
)
|
|
288
|
+
)
|
|
289
|
+
throw new Error("Invalid persisted checkpoint entry");
|
|
290
|
+
return entry as SessionEntry;
|
|
291
|
+
});
|
|
292
|
+
const snapshot = exportNotesSnapshot(entries, identity.agentName);
|
|
293
|
+
return {
|
|
294
|
+
...snapshot,
|
|
295
|
+
files: snapshot.files.filter(
|
|
296
|
+
(file) =>
|
|
297
|
+
contextTargetAgent(
|
|
298
|
+
"notes",
|
|
299
|
+
{ path: file.path },
|
|
300
|
+
identity.agentName,
|
|
301
|
+
) === identity.agentName,
|
|
302
|
+
),
|
|
303
|
+
};
|
|
304
|
+
},
|
|
305
|
+
readAttachmentNotes(snapshot, params) {
|
|
306
|
+
const details = readAttachmentSnapshot(snapshot, params);
|
|
307
|
+
return {
|
|
308
|
+
content: [{ type: "text", text: JSON.stringify(details) }],
|
|
309
|
+
details: { codexHistoryNotes: details },
|
|
310
|
+
};
|
|
311
|
+
},
|
|
312
|
+
registerRouter(next) {
|
|
313
|
+
if (router && router !== next)
|
|
314
|
+
throw new Error("A context router is already registered");
|
|
315
|
+
router = next;
|
|
316
|
+
return () => {
|
|
317
|
+
if (router === next) router = undefined;
|
|
318
|
+
};
|
|
319
|
+
},
|
|
320
|
+
};
|
|
321
|
+
const off = pi.events.on(CONTEXT_SHARING_REQUEST, () =>
|
|
322
|
+
pi.events.emit(CONTEXT_SHARING_AVAILABLE, service),
|
|
323
|
+
);
|
|
324
|
+
pi.events.emit(CONTEXT_SHARING_AVAILABLE, service);
|
|
325
|
+
pi.on("session_shutdown", () => {
|
|
326
|
+
off();
|
|
327
|
+
router = undefined;
|
|
328
|
+
});
|
|
329
|
+
return Object.assign(
|
|
330
|
+
async (
|
|
331
|
+
ctx: ExtensionContext,
|
|
332
|
+
request: SharedContextRequest,
|
|
333
|
+
signal?: AbortSignal,
|
|
334
|
+
) => {
|
|
335
|
+
describe(ctx);
|
|
336
|
+
if (!router) {
|
|
337
|
+
throw new Error(
|
|
338
|
+
"Cross-agent context requires an available context router",
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
return router(ctx, request, signal);
|
|
342
|
+
},
|
|
343
|
+
{
|
|
344
|
+
requiresRemoteScope: (ctx: ExtensionContext) =>
|
|
345
|
+
router?.requiresRemoteScope?.(ctx) ?? false,
|
|
346
|
+
},
|
|
347
|
+
);
|
|
348
|
+
}
|