@narumitw/pi-context-management 0.1.0 → 0.1.1

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/dist/index.ts ADDED
@@ -0,0 +1,1925 @@
1
+ // @generated by scripts/build-runtime.mjs; do not edit.
2
+ // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
+ import {
4
+ terminalText
5
+ } from "./chunks/chunk-K6TRB5OJ.ts";
6
+
7
+ // src/context-management.ts
8
+ import { randomUUID as randomUUID2 } from "node:crypto";
9
+ import { realpathSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import {
13
+ sessionEntryToContextMessages as sessionEntryToContextMessages3
14
+ } from "@earendil-works/pi-coding-agent";
15
+
16
+ // src/context-tools.ts
17
+ import { StringEnum } from "@earendil-works/pi-ai";
18
+ import { Type } from "typebox";
19
+
20
+ // src/context-window.ts
21
+ import { randomUUID } from "node:crypto";
22
+ import { buildContextEntries, sessionEntryToContextMessages } from "@earendil-works/pi-coding-agent";
23
+
24
+ // src/fingerprint.ts
25
+ import { createHash } from "node:crypto";
26
+ var MAX_FINGERPRINT_DEPTH = 512;
27
+ var MAX_FINGERPRINT_OPERATION_UNITS = 4 * 1024 * 1024;
28
+ var MAX_FINGERPRINT_OPERATION_BYTES = 8 * 1024 * 1024;
29
+ function createFingerprintBudget() {
30
+ return {
31
+ remainingUnits: MAX_FINGERPRINT_OPERATION_UNITS,
32
+ remainingBytes: MAX_FINGERPRINT_OPERATION_BYTES
33
+ };
34
+ }
35
+ function failLimit() {
36
+ throw new Error("Context message fingerprint exceeded its traversal limit");
37
+ }
38
+ function assign(parent, key, value) {
39
+ if (Array.isArray(parent)) parent[key] = value;
40
+ else parent[String(key)] = value;
41
+ }
42
+ function stableValue(value, operationBudget) {
43
+ const root = {};
44
+ const tasks = [{ source: value, parent: root, key: "value", depth: 0 }];
45
+ let remainingUnits = MAX_FINGERPRINT_OPERATION_UNITS;
46
+ const consume = (units) => {
47
+ if (!Number.isSafeInteger(units) || units < 0 || units > remainingUnits || units > operationBudget.remainingUnits) {
48
+ failLimit();
49
+ }
50
+ remainingUnits -= units;
51
+ operationBudget.remainingUnits -= units;
52
+ };
53
+ while (tasks.length > 0) {
54
+ const task = tasks.pop();
55
+ if (!task) break;
56
+ consume(1);
57
+ const source = task.source;
58
+ if (typeof source === "string") consume(source.length);
59
+ if (typeof source !== "object" || source === null) {
60
+ if (typeof source === "bigint") throw new Error("Context message fingerprint cannot serialize bigint values");
61
+ assign(task.parent, task.key, source);
62
+ continue;
63
+ }
64
+ if (task.depth >= MAX_FINGERPRINT_DEPTH) failLimit();
65
+ if (Array.isArray(source)) {
66
+ consume(source.length);
67
+ const target2 = new Array(source.length);
68
+ assign(task.parent, task.key, target2);
69
+ for (let index = source.length - 1; index >= 0; index -= 1) {
70
+ tasks.push({ source: source[index], parent: target2, key: index, depth: task.depth + 1 });
71
+ }
72
+ continue;
73
+ }
74
+ const keys = [];
75
+ for (const key in source) {
76
+ if (!Object.hasOwn(source, key)) continue;
77
+ consume(1 + key.length);
78
+ keys.push(key);
79
+ }
80
+ keys.sort((left, right) => left < right ? -1 : left > right ? 1 : 0);
81
+ const target = {};
82
+ assign(task.parent, task.key, target);
83
+ for (let index = keys.length - 1; index >= 0; index -= 1) {
84
+ const key = keys[index];
85
+ tasks.push({
86
+ source: source[key],
87
+ parent: target,
88
+ key,
89
+ depth: task.depth + 1
90
+ });
91
+ }
92
+ }
93
+ return root.value;
94
+ }
95
+ function fingerprintMessage(message, operationBudget = createFingerprintBudget()) {
96
+ const serialized = JSON.stringify(stableValue(message, operationBudget));
97
+ if (serialized === void 0) failLimit();
98
+ const bytes2 = Buffer.byteLength(serialized, "utf8");
99
+ if (bytes2 > MAX_FINGERPRINT_OPERATION_BYTES || bytes2 > operationBudget.remainingBytes) failLimit();
100
+ operationBudget.remainingBytes -= bytes2;
101
+ return createHash("sha256").update(serialized).digest("hex");
102
+ }
103
+
104
+ // src/context-window.ts
105
+ var CONTEXT_STATE_ENTRY_TYPE = "pi-context-management-state";
106
+ var CONTEXT_CONTRACT_MESSAGE_TYPE = "pi-context-management-contract";
107
+ var CONTEXT_DEACTIVATION_MESSAGE_TYPE = "pi-context-management-deactivation";
108
+ var CONTEXT_DETAILS_KIND = "pi-context-management-window";
109
+ var CONTEXT_VERSION = 1;
110
+ var MAX_DETAILS_BYTES = 8 * 1024 * 1024;
111
+ var MAX_FINGERPRINTS = 1e5;
112
+ var MAX_CONTEXT_BRANCH_ENTRY_VISITS = 1e5;
113
+ var MAX_CONTEXT_BRANCH_SCAN_UNITS = 8 * 1024 * 1024;
114
+ function createContextBranchScanBudget() {
115
+ return {
116
+ remainingVisits: MAX_CONTEXT_BRANCH_ENTRY_VISITS,
117
+ remainingScanUnits: MAX_CONTEXT_BRANCH_SCAN_UNITS
118
+ };
119
+ }
120
+ function visitContextBranchEntry(budget) {
121
+ if (budget.remainingVisits <= 0) {
122
+ throw new Error("context_management context branch traversal exceeded its entry limit");
123
+ }
124
+ budget.remainingVisits -= 1;
125
+ }
126
+ function consumeContextBranchScan(budget, units) {
127
+ if (!Number.isSafeInteger(units) || units < 0 || units > budget.remainingScanUnits) {
128
+ throw new Error("context_management context branch traversal exceeded its scan limit");
129
+ }
130
+ budget.remainingScanUnits -= units;
131
+ }
132
+ function isRecord(value) {
133
+ return typeof value === "object" && value !== null && !Array.isArray(value);
134
+ }
135
+ function isIdentifier(value) {
136
+ return typeof value === "string" && value.length >= 8 && value.length <= 128;
137
+ }
138
+ function parseLineage(value) {
139
+ if (!isIdentifier(value.firstWindowId) || !isIdentifier(value.currentWindowId)) return void 0;
140
+ if (value.previousWindowId !== void 0 && !isIdentifier(value.previousWindowId)) return void 0;
141
+ return {
142
+ firstWindowId: value.firstWindowId,
143
+ ...typeof value.previousWindowId === "string" ? { previousWindowId: value.previousWindowId } : {},
144
+ currentWindowId: value.currentWindowId
145
+ };
146
+ }
147
+ function parseContextState(value) {
148
+ if (!isRecord(value)) return void 0;
149
+ const lineage = parseLineage(value);
150
+ if (!lineage || value.kind !== CONTEXT_DETAILS_KIND || value.version !== CONTEXT_VERSION || value.previousWindowId !== void 0 || lineage.firstWindowId !== lineage.currentWindowId) {
151
+ return void 0;
152
+ }
153
+ return { kind: CONTEXT_DETAILS_KIND, version: CONTEXT_VERSION, ...lineage };
154
+ }
155
+ function parseContextManagementDetails(value, budget) {
156
+ if (!isRecord(value) || value.kind !== CONTEXT_DETAILS_KIND || value.version !== CONTEXT_VERSION) return void 0;
157
+ const lineage = parseLineage(value);
158
+ if (!lineage?.previousWindowId || lineage.currentWindowId === lineage.previousWindowId || value.reason !== "manual" && value.reason !== "threshold" && value.reason !== "overflow" || value.requestId !== void 0 && !isIdentifier(value.requestId) || !Array.isArray(value.keptMessageFingerprints) || value.keptMessageFingerprints.length > MAX_FINGERPRINTS || value.retryResponseFingerprint !== void 0 && (typeof value.retryResponseFingerprint !== "string" || value.retryResponseFingerprint.length !== 64) || typeof value.createdAt !== "string" || value.createdAt.length > 64) {
159
+ return void 0;
160
+ }
161
+ const scanUnits = 1 + lineage.firstWindowId.length + lineage.previousWindowId.length + lineage.currentWindowId.length + value.createdAt.length + (typeof value.requestId === "string" ? value.requestId.length : 0) + (typeof value.retryResponseFingerprint === "string" ? value.retryResponseFingerprint.length : 0) + value.keptMessageFingerprints.length + value.keptMessageFingerprints.reduce(
162
+ (total, fingerprint) => total + (typeof fingerprint === "string" ? fingerprint.length : 1),
163
+ 0
164
+ );
165
+ const scanBudget = budget ?? createContextBranchScanBudget();
166
+ try {
167
+ consumeContextBranchScan(scanBudget, scanUnits);
168
+ } catch (error) {
169
+ if (budget) throw error;
170
+ return void 0;
171
+ }
172
+ if (!value.keptMessageFingerprints.every(
173
+ (fingerprint) => typeof fingerprint === "string" && /^[a-f0-9]{64}$/.test(fingerprint)
174
+ ) || typeof value.retryResponseFingerprint === "string" && !/^[a-f0-9]{64}$/.test(value.retryResponseFingerprint)) {
175
+ return void 0;
176
+ }
177
+ const details = {
178
+ kind: CONTEXT_DETAILS_KIND,
179
+ version: CONTEXT_VERSION,
180
+ ...lineage,
181
+ reason: value.reason,
182
+ ...typeof value.requestId === "string" ? { requestId: value.requestId } : {},
183
+ keptMessageFingerprints: [...value.keptMessageFingerprints],
184
+ ...typeof value.retryResponseFingerprint === "string" ? { retryResponseFingerprint: value.retryResponseFingerprint } : {},
185
+ createdAt: value.createdAt
186
+ };
187
+ return Buffer.byteLength(JSON.stringify(details), "utf8") <= MAX_DETAILS_BYTES ? details : void 0;
188
+ }
189
+ function parseContextManagementCompaction(entry, budget) {
190
+ const details = parseContextManagementDetails(entry.details, budget);
191
+ return details && entry.summary === contextContract(details) ? details : void 0;
192
+ }
193
+ function createInitialContextState(windowId = randomUUID()) {
194
+ return {
195
+ kind: CONTEXT_DETAILS_KIND,
196
+ version: CONTEXT_VERSION,
197
+ firstWindowId: windowId,
198
+ currentWindowId: windowId
199
+ };
200
+ }
201
+ function loadContextLineage(entries, budget = createContextBranchScanBudget()) {
202
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
203
+ visitContextBranchEntry(budget);
204
+ const entry = entries[index];
205
+ if (entry.type === "compaction") {
206
+ const details = parseContextManagementCompaction(entry, budget);
207
+ if (details) return details;
208
+ continue;
209
+ }
210
+ if (entry.type === "custom" && entry.customType === CONTEXT_STATE_ENTRY_TYPE) {
211
+ const state = parseContextState(entry.data);
212
+ if (state) return state;
213
+ }
214
+ }
215
+ return void 0;
216
+ }
217
+ function activeContextManagementCompaction(entries, budget = createContextBranchScanBudget()) {
218
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
219
+ visitContextBranchEntry(budget);
220
+ const entry = entries[index];
221
+ if (entry.type !== "compaction") continue;
222
+ const details = parseContextManagementCompaction(entry, budget);
223
+ return details ? { entry, details } : void 0;
224
+ }
225
+ return void 0;
226
+ }
227
+ function contextContract(lineage) {
228
+ return [
229
+ `[PI_CONTEXT_MANAGEMENT_WINDOW:${lineage.currentWindowId}]`,
230
+ "Experimental Pi-native context management is active.",
231
+ lineage.previousWindowId ? `The previous context window was ${lineage.previousWindowId}.` : "This is the first context window in this session.",
232
+ "Use context_management_get_context_remaining to inspect capacity, context_management_recall_context to retrieve older history or notes, and context_management_update_notes to preserve durable working memory.",
233
+ "Call context_management_start_new_context when a fresh context is needed. Important information is not summarized automatically."
234
+ ].join("\n");
235
+ }
236
+ function contextDeactivation() {
237
+ return [
238
+ "Experimental Pi-native context management is no longer active.",
239
+ "Its context tools are unavailable. Continue with Pi's active compaction strategy and do not call context_management_start_new_context, context_management_get_context_remaining, context_management_recall_context, or context_management_update_notes."
240
+ ].join("\n");
241
+ }
242
+ function latestContextMode(entries, budget = createContextBranchScanBudget()) {
243
+ let mode;
244
+ for (const _entry of entries) visitContextBranchEntry(budget);
245
+ const leafId = entries.at(-1)?.id ?? null;
246
+ for (const entry of buildContextEntries([...entries], leafId)) {
247
+ if (entry.type === "compaction" && parseContextManagementCompaction(entry, budget)) mode = "active";
248
+ for (const message of sessionEntryToContextMessages(entry)) {
249
+ if (message.role !== "custom") continue;
250
+ if (message.customType === CONTEXT_CONTRACT_MESSAGE_TYPE) mode = "active";
251
+ if (message.customType === CONTEXT_DEACTIVATION_MESSAGE_TYPE && message.content === contextDeactivation()) {
252
+ mode = "inactive";
253
+ }
254
+ }
255
+ }
256
+ return mode;
257
+ }
258
+ function createContextContractMessage(lineage) {
259
+ return {
260
+ role: "custom",
261
+ customType: CONTEXT_CONTRACT_MESSAGE_TYPE,
262
+ content: contextContract(lineage),
263
+ display: false,
264
+ details: {
265
+ kind: CONTEXT_DETAILS_KIND,
266
+ version: CONTEXT_VERSION,
267
+ currentWindowId: lineage.currentWindowId
268
+ },
269
+ timestamp: 0
270
+ };
271
+ }
272
+ function hasContextContract(messages, lineage) {
273
+ const expected = contextContract(lineage);
274
+ return messages.some(
275
+ (message) => message.role === "custom" && message.customType === CONTEXT_CONTRACT_MESSAGE_TYPE && message.content === expected || message.role === "compactionSummary" && message.summary === expected
276
+ );
277
+ }
278
+ function reconcileContextContract(messages, lineage) {
279
+ if (hasContextContract(messages, lineage)) return [...messages];
280
+ return [...messages, createContextContractMessage(lineage)];
281
+ }
282
+ function compactionRetainedContext(event, fingerprintBudget = createFingerprintBudget()) {
283
+ const leafId = event.branchEntries.at(-1)?.id ?? null;
284
+ const contextEntries = buildContextEntries(event.branchEntries, leafId);
285
+ const keptIndex = contextEntries.findIndex((entry) => entry.id === event.preparation.firstKeptEntryId);
286
+ if (keptIndex < 0) {
287
+ throw new Error("Pi compaction cut point is not present in the active context");
288
+ }
289
+ const keptMessages = contextEntries.slice(keptIndex).flatMap(sessionEntryToContextMessages);
290
+ const lastMessage = keptMessages.at(-1);
291
+ if (event.willRetry && lastMessage?.role === "assistant" && (lastMessage.stopReason === "error" || lastMessage.stopReason === "length")) {
292
+ return {
293
+ keptMessages: keptMessages.slice(0, -1),
294
+ retryResponseFingerprint: fingerprintMessage(lastMessage, fingerprintBudget)
295
+ };
296
+ }
297
+ return { keptMessages };
298
+ }
299
+ function createContextManagementDetails(input, fingerprintBudget = createFingerprintBudget()) {
300
+ const currentWindowId = input.windowId ?? randomUUID();
301
+ const details = {
302
+ kind: CONTEXT_DETAILS_KIND,
303
+ version: CONTEXT_VERSION,
304
+ firstWindowId: input.lineage.firstWindowId,
305
+ previousWindowId: input.lineage.currentWindowId,
306
+ currentWindowId,
307
+ reason: input.reason,
308
+ ...input.requestId ? { requestId: input.requestId } : {},
309
+ keptMessageFingerprints: input.keptMessages.map((message) => fingerprintMessage(message, fingerprintBudget)),
310
+ ...input.retryResponseFingerprint ? { retryResponseFingerprint: input.retryResponseFingerprint } : {},
311
+ createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
312
+ };
313
+ const parsed = parseContextManagementDetails(details);
314
+ if (!parsed) throw new Error("Created invalid context-management details");
315
+ return parsed;
316
+ }
317
+ function isOlderCompactionSummary(message, timestamp) {
318
+ return message.role === "compactionSummary" && Number.isFinite(message.timestamp) && Number.isFinite(timestamp) && message.timestamp < timestamp;
319
+ }
320
+ function projectContextManagementContext(messages, entry, details) {
321
+ const fingerprintBudget = createFingerprintBudget();
322
+ const expectedSummary = contextContract(details);
323
+ if (entry.summary !== expectedSummary) return void 0;
324
+ const summaryIndex = messages.findIndex(
325
+ (message) => message.role === "compactionSummary" && message.summary === expectedSummary
326
+ );
327
+ if (summaryIndex < 0) return void 0;
328
+ const timestamp = messages[summaryIndex].timestamp;
329
+ let messageIndex = summaryIndex + 1;
330
+ let fingerprintIndex = 0;
331
+ while (fingerprintIndex < details.keptMessageFingerprints.length) {
332
+ if (messageIndex >= messages.length) return void 0;
333
+ const message = messages[messageIndex];
334
+ if (fingerprintMessage(message, fingerprintBudget) === details.keptMessageFingerprints[fingerprintIndex]) {
335
+ messageIndex += 1;
336
+ fingerprintIndex += 1;
337
+ continue;
338
+ }
339
+ if (isOlderCompactionSummary(message, timestamp)) {
340
+ messageIndex += 1;
341
+ continue;
342
+ }
343
+ return void 0;
344
+ }
345
+ while (messageIndex < messages.length && isOlderCompactionSummary(messages[messageIndex], timestamp)) {
346
+ messageIndex += 1;
347
+ }
348
+ if (details.retryResponseFingerprint && messageIndex < messages.length && fingerprintMessage(messages[messageIndex], fingerprintBudget) === details.retryResponseFingerprint) {
349
+ messageIndex += 1;
350
+ }
351
+ return [...messages.slice(0, summaryIndex + 1), ...messages.slice(messageIndex)];
352
+ }
353
+
354
+ // src/notes-state.ts
355
+ import { stripVTControlCharacters } from "node:util";
356
+ var NOTES_ENTRY_TYPE = "pi-context-management-note";
357
+ var NOTES_VERSION = 1;
358
+ var MAX_NOTE_NAME_LENGTH = 128;
359
+ var MAX_NOTE_MUTATION_BYTES = 16 * 1024;
360
+ var MAX_NOTE_COUNT = 64;
361
+ var MAX_NOTES_BYTES = 256 * 1024;
362
+ var MAX_NOTE_BRANCH_ENTRY_VISITS = 1e5;
363
+ var MAX_NOTE_REPLAY_SCAN_UNITS = 4 * 1024 * 1024;
364
+ function isRecord2(value) {
365
+ return typeof value === "object" && value !== null && !Array.isArray(value);
366
+ }
367
+ function bytes(value) {
368
+ return Buffer.byteLength(value, "utf8");
369
+ }
370
+ function validNoteName(value) {
371
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_NOTE_NAME_LENGTH && value.trim() === value && stripVTControlCharacters(value) === value && !Array.from(value).some((character) => {
372
+ const codePoint = character.codePointAt(0) ?? 0;
373
+ return codePoint < 32 || codePoint >= 127 && codePoint <= 159;
374
+ });
375
+ }
376
+ function parseNoteMutation(value) {
377
+ if (!isRecord2(value)) return void 0;
378
+ if (value.version !== NOTES_VERSION || value.action !== "write" && value.action !== "append" || !validNoteName(value.note) || typeof value.content !== "string" || value.content.length === 0 || value.content.length > MAX_NOTE_MUTATION_BYTES || bytes(value.content) > MAX_NOTE_MUTATION_BYTES) {
379
+ return void 0;
380
+ }
381
+ return {
382
+ version: NOTES_VERSION,
383
+ action: value.action,
384
+ note: value.note,
385
+ content: value.content
386
+ };
387
+ }
388
+ function loadNotes(entries) {
389
+ const notes = /* @__PURE__ */ new Map();
390
+ const noteContentBytes = /* @__PURE__ */ new Map();
391
+ let totalBytes = 0;
392
+ let remainingEntries = MAX_NOTE_BRANCH_ENTRY_VISITS;
393
+ let remainingScanUnits = MAX_NOTE_REPLAY_SCAN_UNITS;
394
+ for (const entry of entries) {
395
+ if (remainingEntries <= 0) {
396
+ throw new Error("context_management notes branch traversal exceeded its entry limit");
397
+ }
398
+ remainingEntries -= 1;
399
+ if (entry.type !== "custom" || entry.customType !== NOTES_ENTRY_TYPE) continue;
400
+ const data = entry.data;
401
+ const scanUnits = 1 + (isRecord2(data) && typeof data.note === "string" ? data.note.length : 0) + (isRecord2(data) && typeof data.content === "string" ? data.content.length : 0);
402
+ if (scanUnits > remainingScanUnits) {
403
+ throw new Error("context_management notes replay exceeded its scan limit");
404
+ }
405
+ remainingScanUnits -= scanUnits;
406
+ const mutation = parseNoteMutation(data);
407
+ if (!mutation) continue;
408
+ const previous = notes.get(mutation.note);
409
+ const previousContentBytes = noteContentBytes.get(mutation.note) ?? 0;
410
+ const nameBytes = bytes(mutation.note);
411
+ const mutationContentBytes = bytes(mutation.content);
412
+ const nextContentBytes = mutation.action === "append" ? previousContentBytes + mutationContentBytes : mutationContentBytes;
413
+ const nextTotalBytes = totalBytes - (previous === void 0 ? 0 : nameBytes + previousContentBytes) + nameBytes + nextContentBytes;
414
+ if (previous === void 0 && notes.size >= MAX_NOTE_COUNT || nextTotalBytes > MAX_NOTES_BYTES) continue;
415
+ notes.set(mutation.note, mutation.action === "append" ? `${previous ?? ""}${mutation.content}` : mutation.content);
416
+ noteContentBytes.set(mutation.note, nextContentBytes);
417
+ totalBytes = nextTotalBytes;
418
+ }
419
+ return notes;
420
+ }
421
+ function totalNotesBytes(notes) {
422
+ let total = 0;
423
+ for (const [name, content] of notes) total += bytes(name) + bytes(content);
424
+ return total;
425
+ }
426
+ function createNoteMutation(entries, input) {
427
+ const mutation = parseNoteMutation({ version: NOTES_VERSION, ...input });
428
+ if (!mutation) {
429
+ throw new Error(
430
+ `Invalid note mutation; names must be 1-${MAX_NOTE_NAME_LENGTH} characters without terminal controls and content must be 1-${MAX_NOTE_MUTATION_BYTES} UTF-8 bytes`
431
+ );
432
+ }
433
+ const notes = loadNotes(entries);
434
+ const exists = notes.has(mutation.note);
435
+ const next = mutation.action === "append" ? `${notes.get(mutation.note) ?? ""}${mutation.content}` : mutation.content;
436
+ if (!exists && notes.size >= MAX_NOTE_COUNT) {
437
+ throw new Error(`Context notes are limited to ${MAX_NOTE_COUNT} names`);
438
+ }
439
+ notes.set(mutation.note, next);
440
+ if (totalNotesBytes(notes) > MAX_NOTES_BYTES) {
441
+ throw new Error(`Context notes exceed the ${MAX_NOTES_BYTES}-byte active-state limit`);
442
+ }
443
+ return { mutation, notes };
444
+ }
445
+ function sortedNotes(entries) {
446
+ return [...loadNotes(entries)].map(([name, content]) => ({ name, content })).sort((left, right) => left.name.localeCompare(right.name));
447
+ }
448
+
449
+ // src/recall-context.ts
450
+ import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
451
+ import { sessionEntryToContextMessages as sessionEntryToContextMessages2 } from "@earendil-works/pi-coding-agent";
452
+ var MAX_RECALL_QUERY_LENGTH = 512;
453
+ var MAX_RECALL_RESULT_BYTES = 32 * 1024;
454
+ var MAX_RECALL_MATCHES = 20;
455
+ var MAX_HISTORY_BRANCH_ENTRY_VISITS = 1e5;
456
+ var MAX_INDEXED_MESSAGE_CHARS = 256 * 1024;
457
+ var MAX_SCANNED_MESSAGE_UNITS = 4 * MAX_INDEXED_MESSAGE_CHARS;
458
+ var MAX_HISTORY_SEARCH_SCAN_UNITS = 4 * MAX_SCANNED_MESSAGE_UNITS;
459
+ var MAX_HISTORY_READ_SCAN_UNITS = MAX_HISTORY_SEARCH_SCAN_UNITS;
460
+ var MAX_HISTORY_READ_DEPTH = 512;
461
+ var READ_CHUNK_BYTES = 12 * 1024;
462
+ function visitHistoryEntry(budget) {
463
+ if (budget.remainingVisits <= 0) {
464
+ throw new Error("context_management_recall_context history branch traversal exceeded its entry limit");
465
+ }
466
+ budget.remainingVisits -= 1;
467
+ }
468
+ function parseCursor(cursor) {
469
+ if (cursor === void 0) return 0;
470
+ if (!/^\d{1,12}$/.test(cursor)) throw new Error("context_management_recall_context cursor is invalid");
471
+ return Number.parseInt(cursor, 10);
472
+ }
473
+ function messagePayload(message) {
474
+ switch (message.role) {
475
+ case "compactionSummary":
476
+ return { summary: message.summary };
477
+ case "branchSummary":
478
+ return { summary: message.summary };
479
+ case "custom":
480
+ return { customType: message.customType, content: message.content };
481
+ case "toolResult":
482
+ return {
483
+ toolName: message.toolName,
484
+ toolCallId: message.toolCallId,
485
+ content: message.content,
486
+ isError: message.isError
487
+ };
488
+ default: {
489
+ const candidate = message;
490
+ return Object.hasOwn(candidate, "content") ? { content: candidate.content } : {
491
+ command: candidate.command,
492
+ output: candidate.output,
493
+ exitCode: candidate.exitCode
494
+ };
495
+ }
496
+ }
497
+ }
498
+ function serializeMessage(message) {
499
+ let remainingUnits = MAX_HISTORY_READ_SCAN_UNITS;
500
+ const depths = /* @__PURE__ */ new WeakMap();
501
+ const serialized = JSON.stringify(
502
+ messagePayload(message),
503
+ function boundedReplacer(key, value) {
504
+ const holderDepth = typeof this === "object" && this !== null ? depths.get(this) : void 0;
505
+ const depth = key === "" && holderDepth === void 0 ? 0 : (holderDepth ?? -1) + 1;
506
+ const units = 1 + key.length + (typeof value === "string" ? value.length : 0);
507
+ if (depth > MAX_HISTORY_READ_DEPTH || units > remainingUnits) {
508
+ throw new Error("context_management_recall_context history read exceeded its scan limit");
509
+ }
510
+ remainingUnits -= units;
511
+ if (typeof value === "object" && value !== null) depths.set(value, depth);
512
+ return value;
513
+ }
514
+ );
515
+ if (serialized === void 0) {
516
+ throw new Error("context_management_recall_context selected history payload is not serializable");
517
+ }
518
+ return JSON.stringify(sanitizeJsonValue(JSON.parse(serialized)));
519
+ }
520
+ function isRecord3(value) {
521
+ return typeof value === "object" && value !== null && !Array.isArray(value);
522
+ }
523
+ var INDEXED_CONTENT = /* @__PURE__ */ Symbol("pi-context-management-indexed-content");
524
+ function indexedContent(value) {
525
+ return { [INDEXED_CONTENT]: true, value };
526
+ }
527
+ function isIndexedContent(value) {
528
+ return typeof value === "object" && value !== null && value[INDEXED_CONTENT] === true;
529
+ }
530
+ function indexedBlock(block) {
531
+ if (!isRecord3(block)) return block;
532
+ switch (block.type) {
533
+ case "text":
534
+ return { type: block.type, text: block.text };
535
+ case "image":
536
+ return { type: block.type, mimeType: block.mimeType };
537
+ case "thinking":
538
+ return {
539
+ type: block.type,
540
+ thinking: block.thinking,
541
+ ...typeof block.redacted === "boolean" ? { redacted: block.redacted } : {}
542
+ };
543
+ case "toolCall":
544
+ return {
545
+ type: block.type,
546
+ id: block.id,
547
+ name: block.name,
548
+ ...block.name === "context_management_recall_context" ? {} : { arguments: block.arguments },
549
+ ...typeof block.namespace === "string" ? { namespace: block.namespace } : {}
550
+ };
551
+ default:
552
+ return block;
553
+ }
554
+ }
555
+ function messageIndexPayload(message) {
556
+ if (message.role === "toolResult" && message.toolName === "context_management_recall_context") {
557
+ return {
558
+ toolName: message.toolName,
559
+ toolCallId: message.toolCallId,
560
+ isError: message.isError
561
+ };
562
+ }
563
+ const payload = messagePayload(message);
564
+ if (!isRecord3(payload) || !Object.hasOwn(payload, "content")) return payload;
565
+ return { ...payload, content: indexedContent(payload.content) };
566
+ }
567
+ function isExcludedFromModelContext(message) {
568
+ return message.role === "bashExecution" && message.excludeFromContext === true;
569
+ }
570
+ function* historyMessageItems(entries, budget, firstWindowId, detailScanBudget) {
571
+ let windowId = firstWindowId;
572
+ for (const entry of entries) {
573
+ visitHistoryEntry(budget);
574
+ if (entry.type === "compaction") {
575
+ const details = parseContextManagementCompaction(entry, detailScanBudget);
576
+ if (details) windowId = details.currentWindowId;
577
+ }
578
+ const messages = sessionEntryToContextMessages2(entry);
579
+ for (let index = 0; index < messages.length; index += 1) {
580
+ const message = messages[index];
581
+ if (isExcludedFromModelContext(message)) continue;
582
+ yield {
583
+ id: messages.length === 1 ? entry.id : `${entry.id}:${index}`,
584
+ ...windowId ? { windowId } : {},
585
+ role: message.role,
586
+ message
587
+ };
588
+ }
589
+ }
590
+ }
591
+ function isActiveToolCallMessage(message, toolCallId) {
592
+ return toolCallId !== void 0 && message.role === "assistant" && message.content.some((block) => block.type === "toolCall" && block.id === toolCallId);
593
+ }
594
+ function displayText(value) {
595
+ return Array.from(stripVTControlCharacters2(value), (character) => {
596
+ const codePoint = character.codePointAt(0) ?? 0;
597
+ if (codePoint === 9 || codePoint === 10 || codePoint === 13) return character;
598
+ return codePoint < 32 || codePoint >= 127 && codePoint <= 159 ? " " : character;
599
+ }).join("");
600
+ }
601
+ function normalizedSearchQuery(input) {
602
+ if (!input.query || input.query.length > MAX_RECALL_QUERY_LENGTH || input.id !== void 0) {
603
+ throw new Error(
604
+ `context_management_recall_context search requires a query of 1-${MAX_RECALL_QUERY_LENGTH} characters and does not accept id`
605
+ );
606
+ }
607
+ const query = displayText(input.query).trim().toLowerCase();
608
+ if (!query) throw new Error("context_management_recall_context search query contains no visible text");
609
+ return query;
610
+ }
611
+ function preview(value) {
612
+ const compact = displayText(value).replace(/\s+/g, " ").trim();
613
+ const characters = Array.from(compact);
614
+ return characters.length > 240 ? `${characters.slice(0, 239).join("")}\u2026` : compact;
615
+ }
616
+ function* ownEntries(value) {
617
+ for (const key in value) {
618
+ if (Object.hasOwn(value, key)) yield [key, value[key]];
619
+ }
620
+ }
621
+ function boundedPayloadText(value, searchBudget) {
622
+ let scannedUnits = 0;
623
+ let text = "";
624
+ const consume = (requestedUnits) => {
625
+ const allowedByMessage = Math.min(requestedUnits, MAX_SCANNED_MESSAGE_UNITS - scannedUnits);
626
+ const consumedUnits = Math.min(allowedByMessage, searchBudget?.remainingUnits ?? allowedByMessage);
627
+ scannedUnits += consumedUnits;
628
+ if (searchBudget) {
629
+ searchBudget.remainingUnits -= consumedUnits;
630
+ if (consumedUnits < allowedByMessage) searchBudget.exceeded = true;
631
+ }
632
+ return consumedUnits;
633
+ };
634
+ const append = (value2) => {
635
+ const part = value2.slice(0, consume(value2.length));
636
+ text += displayText(part).slice(0, MAX_INDEXED_MESSAGE_CHARS - text.length);
637
+ };
638
+ const frames = [{ kind: "value", value }];
639
+ while (frames.length > 0 && scannedUnits < MAX_SCANNED_MESSAGE_UNITS && text.length < MAX_INDEXED_MESSAGE_CHARS && !searchBudget?.exceeded) {
640
+ const frame = frames.pop();
641
+ if (!frame) break;
642
+ if (frame.kind === "text") {
643
+ append(frame.value);
644
+ continue;
645
+ }
646
+ if (frame.kind === "array") {
647
+ if (frame.index < frame.value.length) {
648
+ frames.push(
649
+ { kind: "array", value: frame.value, index: frame.index + 1 },
650
+ { kind: "value", value: frame.value[frame.index] }
651
+ );
652
+ }
653
+ continue;
654
+ }
655
+ if (frame.kind === "indexed-content") {
656
+ if (frame.index < frame.value.length && consume(1) === 1) {
657
+ frames.push(
658
+ { kind: "indexed-content", value: frame.value, index: frame.index + 1 },
659
+ { kind: "value", value: indexedBlock(frame.value[frame.index]) }
660
+ );
661
+ }
662
+ continue;
663
+ }
664
+ if (frame.kind === "object") {
665
+ const next = frame.entries.next();
666
+ if (!next.done) {
667
+ const [key, item2] = next.value;
668
+ frames.push(
669
+ frame,
670
+ { kind: "text", value: "\n" },
671
+ { kind: "value", value: item2 },
672
+ { kind: "text", value: `${key} ` }
673
+ );
674
+ }
675
+ continue;
676
+ }
677
+ if (consume(1) < 1) continue;
678
+ const item = frame.value;
679
+ if (typeof item === "string") {
680
+ append(item);
681
+ } else if (typeof item !== "object" || item === null) {
682
+ if (item !== void 0 && typeof item !== "function" && typeof item !== "symbol") {
683
+ append(String(item));
684
+ }
685
+ } else if (isIndexedContent(item)) {
686
+ if (Array.isArray(item.value)) frames.push({ kind: "indexed-content", value: item.value, index: 0 });
687
+ else frames.push({ kind: "value", value: item.value });
688
+ } else if (Array.isArray(item)) {
689
+ frames.push({ kind: "array", value: item, index: 0 });
690
+ } else {
691
+ frames.push({ kind: "object", entries: ownEntries(item) });
692
+ }
693
+ }
694
+ return text;
695
+ }
696
+ function boundedMessageText(message, searchBudget) {
697
+ return boundedPayloadText(messageIndexPayload(message), searchBudget);
698
+ }
699
+ function paged(values, offset) {
700
+ const items = values.slice(offset, offset + MAX_RECALL_MATCHES);
701
+ const next = offset + items.length;
702
+ return {
703
+ items,
704
+ ...next < values.length ? { nextCursor: String(next) } : {}
705
+ };
706
+ }
707
+ function searchPage(values, offset, matches) {
708
+ const items = [];
709
+ let matchIndex = 0;
710
+ for (const value of values) {
711
+ if (!matches(value)) continue;
712
+ if (matchIndex >= offset) items.push(value);
713
+ matchIndex += 1;
714
+ if (items.length > MAX_RECALL_MATCHES) break;
715
+ }
716
+ const hasMore = items.length > MAX_RECALL_MATCHES;
717
+ return {
718
+ items: items.slice(0, MAX_RECALL_MATCHES),
719
+ ...hasMore ? { nextCursor: String(offset + MAX_RECALL_MATCHES) } : {}
720
+ };
721
+ }
722
+ function readChunk(value, offset) {
723
+ if (offset > value.length) throw new Error("context_management_recall_context cursor exceeds the selected item");
724
+ if (offset > 0 && offset < value.length && /[\uDC00-\uDFFF]/.test(value[offset]) && /[\uD800-\uDBFF]/.test(value[offset - 1])) {
725
+ throw new Error("context_management_recall_context cursor splits a Unicode code point");
726
+ }
727
+ let bytes2 = 0;
728
+ let next = offset;
729
+ for (const character of value.slice(offset)) {
730
+ const characterBytes = Buffer.byteLength(character, "utf8");
731
+ if (bytes2 + characterBytes > READ_CHUNK_BYTES) break;
732
+ bytes2 += characterBytes;
733
+ next += character.length;
734
+ }
735
+ const chunk = value.slice(offset, next);
736
+ return {
737
+ chunk,
738
+ ...next < value.length ? { nextCursor: String(next) } : {}
739
+ };
740
+ }
741
+ function sanitizeJsonValue(value) {
742
+ if (typeof value === "string") return displayText(value);
743
+ if (Array.isArray(value)) return value.map(sanitizeJsonValue);
744
+ if (typeof value !== "object" || value === null) return value;
745
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [displayText(key), sanitizeJsonValue(item)]));
746
+ }
747
+ function safeJson(value) {
748
+ const text = JSON.stringify(sanitizeJsonValue(value), null, 2);
749
+ if (Buffer.byteLength(text, "utf8") > MAX_RECALL_RESULT_BYTES) {
750
+ throw new Error("context_management_recall_context result exceeded its output limit");
751
+ }
752
+ if (text.split("\n").length > 1e3) {
753
+ throw new Error("context_management_recall_context result exceeded its line limit");
754
+ }
755
+ return text;
756
+ }
757
+ function recallContext(entries, input, activeToolCallId, limits = {}) {
758
+ if (input.source !== "history" && input.source !== "notes") {
759
+ throw new Error("context_management_recall_context source must be history or notes");
760
+ }
761
+ if (input.action !== "list" && input.action !== "read" && input.action !== "search") {
762
+ throw new Error("context_management_recall_context action must be list, read, or search");
763
+ }
764
+ const offset = parseCursor(input.cursor);
765
+ if (input.action === "read" && (!input.id || input.query !== void 0)) {
766
+ throw new Error("context_management_recall_context read requires id and does not accept query");
767
+ }
768
+ const searchQuery = input.action === "search" ? normalizedSearchQuery(input) : "";
769
+ if (input.action === "list" && (input.id !== void 0 || input.query !== void 0)) {
770
+ throw new Error("context_management_recall_context list does not accept id or query");
771
+ }
772
+ if (input.source === "notes") {
773
+ const notes = sortedNotes(entries);
774
+ if (input.action === "list") {
775
+ const page3 = paged(
776
+ notes.map((note) => ({ id: note.name, bytes: Buffer.byteLength(note.content, "utf8") })),
777
+ offset
778
+ );
779
+ return { text: safeJson({ source: "notes", action: "list", ...page3 }), details: page3 };
780
+ }
781
+ if (input.action === "read") {
782
+ const note = notes.find((candidate) => candidate.name === input.id);
783
+ if (!note) throw new Error(`Context note ${JSON.stringify(displayText(input.id ?? ""))} was not found`);
784
+ const page3 = readChunk(displayText(note.content), offset);
785
+ return {
786
+ text: safeJson({ source: "notes", action: "read", id: note.name, ...page3 }),
787
+ details: { source: "notes", id: note.name, ...page3 }
788
+ };
789
+ }
790
+ const matches2 = searchPage(
791
+ notes,
792
+ offset,
793
+ (note) => displayText(`${note.name}
794
+ ${note.content.slice(0, MAX_INDEXED_MESSAGE_CHARS)}`).toLowerCase().includes(searchQuery)
795
+ );
796
+ const page2 = {
797
+ ...matches2,
798
+ items: matches2.items.map((note) => ({ id: note.name, preview: preview(note.content) }))
799
+ };
800
+ return { text: safeJson({ source: "notes", action: "search", ...page2 }), details: page2 };
801
+ }
802
+ const detailScanBudget = createContextBranchScanBudget();
803
+ if (limits.historyDetailScanUnits !== void 0) {
804
+ detailScanBudget.remainingScanUnits = limits.historyDetailScanUnits;
805
+ }
806
+ const history = historyMessageItems(
807
+ entries,
808
+ { remainingVisits: MAX_HISTORY_BRANCH_ENTRY_VISITS },
809
+ limits.firstWindowId,
810
+ detailScanBudget
811
+ );
812
+ if (input.action === "list") {
813
+ const selected = searchPage(history, offset, () => true);
814
+ const page2 = {
815
+ ...selected,
816
+ items: selected.items.map((item) => ({
817
+ id: item.id,
818
+ ...item.windowId ? { windowId: item.windowId } : {},
819
+ role: item.role,
820
+ preview: preview(boundedMessageText(item.message))
821
+ }))
822
+ };
823
+ return { text: safeJson({ source: "history", action: "list", ...page2 }), details: page2 };
824
+ }
825
+ if (input.action === "read") {
826
+ let item;
827
+ for (const candidate of history) {
828
+ if (candidate.id !== input.id) continue;
829
+ item = candidate;
830
+ break;
831
+ }
832
+ if (!item) throw new Error(`History item ${JSON.stringify(displayText(input.id ?? ""))} was not found`);
833
+ const content = serializeMessage(item.message);
834
+ const page2 = readChunk(content, offset);
835
+ return {
836
+ text: safeJson({
837
+ source: "history",
838
+ action: "read",
839
+ id: item.id,
840
+ ...item.windowId ? { windowId: item.windowId } : {},
841
+ role: item.role,
842
+ ...page2
843
+ }),
844
+ details: { source: "history", id: item.id, ...page2 }
845
+ };
846
+ }
847
+ const searchBudget = {
848
+ remainingUnits: limits.historySearchScanUnits ?? MAX_HISTORY_SEARCH_SCAN_UNITS,
849
+ exceeded: false
850
+ };
851
+ const indexedText = /* @__PURE__ */ new Map();
852
+ const matches = searchPage(history, offset, (item) => {
853
+ if (isActiveToolCallMessage(item.message, activeToolCallId)) return false;
854
+ const text = boundedMessageText(item.message, searchBudget);
855
+ if (searchBudget.exceeded) {
856
+ throw new Error("context_management_recall_context history search exceeded its scan limit");
857
+ }
858
+ indexedText.set(item.id, text);
859
+ return text.toLowerCase().includes(searchQuery);
860
+ });
861
+ const page = {
862
+ ...matches,
863
+ items: matches.items.map((item) => ({
864
+ id: item.id,
865
+ ...item.windowId ? { windowId: item.windowId } : {},
866
+ role: item.role,
867
+ preview: preview(indexedText.get(item.id) ?? "")
868
+ }))
869
+ };
870
+ return { text: safeJson({ source: "history", action: "search", ...page }), details: page };
871
+ }
872
+
873
+ // src/context-tools.ts
874
+ var CONTEXT_MANAGEMENT_TOOL_NAMES = [
875
+ "context_management_start_new_context",
876
+ "context_management_get_context_remaining",
877
+ "context_management_recall_context",
878
+ "context_management_update_notes"
879
+ ];
880
+ var CONTEXT_MANAGEMENT_TOOL_DESCRIPTIONS = {
881
+ context_management_start_new_context: "Request a fresh summary-free context window after the current agent run settles. Save important durable information with context_management_update_notes first. This tool changes context state but does not read or write memory itself.",
882
+ context_management_get_context_remaining: "Inspect the active model context window and estimated remaining tokens without changing context state.",
883
+ context_management_recall_context: "Read-only access to branch-local conversation history or context notes. List items, read one stable item ID, or search text. Use the returned cursor to continue bounded results.",
884
+ context_management_update_notes: "Write or append one branch-local context note. This tool changes notes only; use context_management_recall_context with source notes to read them."
885
+ };
886
+ var RECALL_SOURCES = ["history", "notes"];
887
+ var RECALL_ACTIONS = ["list", "read", "search"];
888
+ var NOTE_ACTIONS = ["write", "append"];
889
+ function requireEnabled(runtime, ctx) {
890
+ if (!runtime.isEnabled(ctx)) {
891
+ throw new Error("Experimental context management is disabled; enable it in pi-context-management settings first");
892
+ }
893
+ }
894
+ function throwIfAborted(signal) {
895
+ if (signal?.aborted) throw new DOMException("Context tool operation aborted", "AbortError");
896
+ }
897
+ function result(value, details) {
898
+ return {
899
+ content: [{ type: "text", text: terminalText(JSON.stringify(value, null, 2)) }],
900
+ details
901
+ };
902
+ }
903
+ function registerContextManagementTools(pi, runtime) {
904
+ pi.registerTool({
905
+ name: "context_management_start_new_context",
906
+ label: "Start New Context",
907
+ description: CONTEXT_MANAGEMENT_TOOL_DESCRIPTIONS.context_management_start_new_context,
908
+ parameters: Type.Object(
909
+ {
910
+ reason: Type.Optional(
911
+ Type.String({
912
+ description: "Short reason for starting a fresh context window",
913
+ maxLength: 512
914
+ })
915
+ )
916
+ },
917
+ { additionalProperties: false }
918
+ ),
919
+ executionMode: "sequential",
920
+ async execute(toolCallId, params, signal, _onUpdate, ctx) {
921
+ requireEnabled(runtime, ctx);
922
+ throwIfAborted(signal);
923
+ const requested = runtime.requestNewContext(ctx, {
924
+ toolCallId,
925
+ ...params.reason ? { reason: params.reason } : {}
926
+ });
927
+ throwIfAborted(signal);
928
+ return {
929
+ ...result(
930
+ {
931
+ status: "scheduled",
932
+ requestId: requested.requestId,
933
+ currentWindowId: requested.currentWindowId,
934
+ message: "The current run will end before rollover. A hidden continuation follows the compaction attempt unless a later successful turn already continued the work."
935
+ },
936
+ {
937
+ kind: CONTEXT_DETAILS_KIND,
938
+ version: CONTEXT_VERSION,
939
+ ...requested,
940
+ status: "scheduled"
941
+ }
942
+ ),
943
+ terminate: true
944
+ };
945
+ }
946
+ });
947
+ pi.registerTool({
948
+ name: "context_management_get_context_remaining",
949
+ label: "Get Context Remaining",
950
+ description: CONTEXT_MANAGEMENT_TOOL_DESCRIPTIONS.context_management_get_context_remaining,
951
+ parameters: Type.Object({}, { additionalProperties: false }),
952
+ async execute(_toolCallId, _params, signal, _onUpdate, ctx) {
953
+ requireEnabled(runtime, ctx);
954
+ throwIfAborted(signal);
955
+ const usage = ctx.getContextUsage();
956
+ const lineage = loadContextLineage(ctx.sessionManager.getBranch());
957
+ if (!usage) {
958
+ return result({
959
+ available: false,
960
+ ...lineage ? { currentWindowId: lineage.currentWindowId } : {}
961
+ });
962
+ }
963
+ const remainingTokens = usage.tokens === null ? null : Math.max(0, usage.contextWindow - usage.tokens);
964
+ return result({
965
+ available: usage.tokens !== null,
966
+ ...lineage ? { currentWindowId: lineage.currentWindowId } : {},
967
+ contextWindow: usage.contextWindow,
968
+ usedTokens: usage.tokens,
969
+ remainingTokens,
970
+ remainingPercent: usage.percent === null ? null : Math.max(0, 100 - usage.percent)
971
+ });
972
+ }
973
+ });
974
+ pi.registerTool({
975
+ name: "context_management_recall_context",
976
+ label: "Recall Context",
977
+ description: CONTEXT_MANAGEMENT_TOOL_DESCRIPTIONS.context_management_recall_context,
978
+ parameters: Type.Object(
979
+ {
980
+ source: StringEnum(RECALL_SOURCES, {
981
+ description: "Read conversation history or context notes"
982
+ }),
983
+ action: StringEnum(RECALL_ACTIONS, {
984
+ description: "List items, read one ID, or search text"
985
+ }),
986
+ id: Type.Optional(Type.String({ description: "Stable history item ID or note name", maxLength: 256 })),
987
+ query: Type.Optional(Type.String({ description: "Case-insensitive search text", maxLength: 512 })),
988
+ cursor: Type.Optional(Type.String({ description: "Cursor returned by an earlier result", maxLength: 12 }))
989
+ },
990
+ { additionalProperties: false }
991
+ ),
992
+ async execute(toolCallId, params, signal, _onUpdate, ctx) {
993
+ requireEnabled(runtime, ctx);
994
+ throwIfAborted(signal);
995
+ const recalled = recallContext(ctx.sessionManager.getBranch(), params, toolCallId, {
996
+ firstWindowId: runtime.firstWindowId(ctx)
997
+ });
998
+ throwIfAborted(signal);
999
+ return {
1000
+ content: [{ type: "text", text: recalled.text }],
1001
+ details: recalled.details
1002
+ };
1003
+ }
1004
+ });
1005
+ pi.registerTool({
1006
+ name: "context_management_update_notes",
1007
+ label: "Update Context Notes",
1008
+ description: CONTEXT_MANAGEMENT_TOOL_DESCRIPTIONS.context_management_update_notes,
1009
+ parameters: Type.Object(
1010
+ {
1011
+ action: StringEnum(NOTE_ACTIONS, {
1012
+ description: "Replace a note or append content exactly as supplied"
1013
+ }),
1014
+ note: Type.String({ description: "Note name", minLength: 1, maxLength: 128 }),
1015
+ content: Type.String({
1016
+ description: "Note content written or appended exactly as supplied",
1017
+ minLength: 1,
1018
+ maxLength: 16384
1019
+ })
1020
+ },
1021
+ { additionalProperties: false }
1022
+ ),
1023
+ executionMode: "sequential",
1024
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
1025
+ requireEnabled(runtime, ctx);
1026
+ throwIfAborted(signal);
1027
+ const updated = createNoteMutation(ctx.sessionManager.getBranch(), params);
1028
+ throwIfAborted(signal);
1029
+ pi.appendEntry(NOTES_ENTRY_TYPE, updated.mutation);
1030
+ return result(
1031
+ {
1032
+ status: "updated",
1033
+ action: updated.mutation.action,
1034
+ note: updated.mutation.note,
1035
+ bytes: Buffer.byteLength(updated.notes.get(updated.mutation.note) ?? "", "utf8")
1036
+ },
1037
+ {
1038
+ version: updated.mutation.version,
1039
+ action: updated.mutation.action,
1040
+ note: updated.mutation.note
1041
+ }
1042
+ );
1043
+ }
1044
+ });
1045
+ }
1046
+
1047
+ // src/context-management.ts
1048
+ var CONTINUATION_MESSAGE_TYPE = "pi-context-management-continuation";
1049
+ var ROLLOVER_STATE_ENTRY_TYPE = "pi-context-management-rollover";
1050
+ var START_NEW_CONTEXT_TOOL_NAME = "context_management_start_new_context";
1051
+ var EXTENSION_ENTRY_PATH = realpathSync(join(fileURLToPath(new URL(".", import.meta.url)), "index.ts"));
1052
+ function sameNames(left, right) {
1053
+ return left.length === right.length && left.every((name, index) => name === right[index]);
1054
+ }
1055
+ function isOwnedToolSource(tool) {
1056
+ if (!tool || tool.sourceInfo.path.startsWith("<")) return false;
1057
+ try {
1058
+ return realpathSync(tool.sourceInfo.path) === EXTENSION_ENTRY_PATH;
1059
+ } catch {
1060
+ return false;
1061
+ }
1062
+ }
1063
+ function isRecord4(value) {
1064
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1065
+ }
1066
+ function isIdentifier2(value) {
1067
+ return typeof value === "string" && value.length >= 8 && value.length <= 128;
1068
+ }
1069
+ function contractMessage(lineage) {
1070
+ return {
1071
+ customType: CONTEXT_CONTRACT_MESSAGE_TYPE,
1072
+ content: contextContract(lineage),
1073
+ display: false,
1074
+ details: {
1075
+ kind: CONTEXT_DETAILS_KIND,
1076
+ version: CONTEXT_VERSION,
1077
+ currentWindowId: lineage.currentWindowId
1078
+ }
1079
+ };
1080
+ }
1081
+ function deactivationMessage() {
1082
+ return {
1083
+ customType: CONTEXT_DEACTIVATION_MESSAGE_TYPE,
1084
+ content: contextDeactivation(),
1085
+ display: false,
1086
+ details: { kind: CONTEXT_DETAILS_KIND, version: CONTEXT_VERSION }
1087
+ };
1088
+ }
1089
+ function deactivationAgentMessage() {
1090
+ return {
1091
+ role: "custom",
1092
+ ...deactivationMessage(),
1093
+ timestamp: 0
1094
+ };
1095
+ }
1096
+ function latestAssistantStopReason(messages) {
1097
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
1098
+ const message = messages[index];
1099
+ if (message.role === "assistant") return message.stopReason;
1100
+ }
1101
+ return void 0;
1102
+ }
1103
+ function terminalRolloverRequestId(entry) {
1104
+ if (entry.type === "custom" && entry.customType === ROLLOVER_STATE_ENTRY_TYPE) {
1105
+ const data = entry.data;
1106
+ return isRecord4(data) && data.kind === CONTEXT_DETAILS_KIND && data.version === CONTEXT_VERSION && (data.status === "cancelled" || data.status === "suppressed") && isIdentifier2(data.requestId) ? data.requestId : void 0;
1107
+ }
1108
+ const message = entry.type === "message" && entry.message.role === "custom" ? entry.message : void 0;
1109
+ const customMessage = entry.type === "custom_message" ? entry : message;
1110
+ if (customMessage?.customType === CONTINUATION_MESSAGE_TYPE && isRecord4(customMessage.details) && customMessage.details.kind === CONTEXT_DETAILS_KIND && customMessage.details.version === CONTEXT_VERSION && isIdentifier2(customMessage.details.requestId)) {
1111
+ return customMessage.details.requestId;
1112
+ }
1113
+ return void 0;
1114
+ }
1115
+ function restoredRollover(entries, sessionId, generation, budget = createContextBranchScanBudget()) {
1116
+ const terminalRequests = /* @__PURE__ */ new Set();
1117
+ const completedRequests = /* @__PURE__ */ new Map();
1118
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
1119
+ visitContextBranchEntry(budget);
1120
+ const entry = entries[index];
1121
+ const terminalRequestId = terminalRolloverRequestId(entry);
1122
+ if (terminalRequestId) terminalRequests.add(terminalRequestId);
1123
+ if (entry.type === "compaction") {
1124
+ const details2 = parseContextManagementCompaction(entry, budget);
1125
+ if (details2?.requestId) completedRequests.set(details2.requestId, details2.currentWindowId);
1126
+ continue;
1127
+ }
1128
+ if (entry.type !== "message") continue;
1129
+ const message = entry.message;
1130
+ if (message.role !== "toolResult" || message.toolName !== START_NEW_CONTEXT_TOOL_NAME) continue;
1131
+ const details = message.details;
1132
+ if (!isRecord4(details) || details.kind !== CONTEXT_DETAILS_KIND || details.version !== CONTEXT_VERSION || details.status !== "scheduled" || !isIdentifier2(details.requestId) || !isIdentifier2(details.currentWindowId) || !isIdentifier2(details.nextWindowId) || details.reason !== void 0 && (typeof details.reason !== "string" || details.reason.length > 512)) {
1133
+ continue;
1134
+ }
1135
+ if (terminalRequests.has(details.requestId)) return void 0;
1136
+ const completedWindowId = completedRequests.get(details.requestId);
1137
+ return {
1138
+ requestId: details.requestId,
1139
+ nextWindowId: completedWindowId ?? details.nextWindowId,
1140
+ sessionId,
1141
+ generation,
1142
+ status: completedWindowId ? "completed" : "requested",
1143
+ turnStartedAfterRequest: false,
1144
+ successfulTurnAfterRequest: false,
1145
+ ...typeof details.reason === "string" ? { reason: details.reason } : {}
1146
+ };
1147
+ }
1148
+ return void 0;
1149
+ }
1150
+ function boundedContextMessages(entries) {
1151
+ const budget = createContextBranchScanBudget();
1152
+ const messages = [];
1153
+ for (const entry of entries) {
1154
+ visitContextBranchEntry(budget);
1155
+ messages.push(...sessionEntryToContextMessages3(entry));
1156
+ }
1157
+ return messages;
1158
+ }
1159
+ function branchContainsEntry(entries, entryId) {
1160
+ const budget = createContextBranchScanBudget();
1161
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
1162
+ visitContextBranchEntry(budget);
1163
+ if (entries[index].id === entryId) return true;
1164
+ }
1165
+ return false;
1166
+ }
1167
+ function createContextManager(pi, settingsRuntime) {
1168
+ const states = /* @__PURE__ */ new Map();
1169
+ let nextGeneration = 0;
1170
+ const isConfigured = () => settingsRuntime.get().settings.enabled;
1171
+ const stateFor = (ctx) => {
1172
+ const state = states.get(ctx.sessionManager);
1173
+ return state && !state.controller.signal.aborted && state.sessionId === ctx.sessionManager.getSessionId() ? state : void 0;
1174
+ };
1175
+ const inspectToolUnit = () => {
1176
+ const available = new Map(pi.getAllTools().map((tool) => [tool.name, tool]));
1177
+ const ownedNames = new Set(
1178
+ CONTEXT_MANAGEMENT_TOOL_NAMES.filter((name) => isOwnedToolSource(available.get(name)))
1179
+ );
1180
+ const activeNames = new Set(pi.getActiveTools());
1181
+ const unavailableNames = CONTEXT_MANAGEMENT_TOOL_NAMES.filter((name) => !ownedNames.has(name));
1182
+ const inactiveNames = CONTEXT_MANAGEMENT_TOOL_NAMES.filter(
1183
+ (name) => ownedNames.has(name) && !activeNames.has(name)
1184
+ );
1185
+ return {
1186
+ ownedNames,
1187
+ unavailableNames,
1188
+ inactiveNames,
1189
+ complete: unavailableNames.length === 0 && inactiveNames.length === 0
1190
+ };
1191
+ };
1192
+ const enabledFor = (state) => (isConfigured() || state.removeToolsAtSettlement) && state.toolsAvailable && inspectToolUnit().complete;
1193
+ const isOwned = (state, ctx, request) => stateFor(ctx) === state && (!request || request.sessionId === state.sessionId && request.generation === state.generation && state.pending?.requestId === request.requestId);
1194
+ const removeOwnedTools = (ownedNames) => {
1195
+ const current = pi.getActiveTools();
1196
+ const next = current.filter((name) => !ownedNames.has(name));
1197
+ if (!sameNames(current, next)) pi.setActiveTools(next);
1198
+ for (const state of states.values()) state.toolsAvailable = false;
1199
+ };
1200
+ const warnToolUnitUnavailable = (state, ctx, unavailableNames, inactiveNames) => {
1201
+ if (state.warnedUnavailableTools || !ctx.hasUI) return;
1202
+ state.warnedUnavailableTools = true;
1203
+ const names = [...unavailableNames, ...inactiveNames];
1204
+ ctx.ui.notify(
1205
+ `Experimental context management could not activate because these tool names are unavailable, inactive, or owned by another extension: ${names.join(", ")}. Pi-native compaction remains active.`,
1206
+ "warning"
1207
+ );
1208
+ };
1209
+ const hasDeferredToolRemoval = () => [...states.values()].some((state) => state.removeToolsAtSettlement);
1210
+ const reconcileTools = (state, activate, ctx) => {
1211
+ const inspection = inspectToolUnit();
1212
+ const available = activate && inspection.unavailableNames.length === 0;
1213
+ const current = pi.getActiveTools();
1214
+ const next = available ? [...current, ...inspection.inactiveNames] : current.filter((name) => !inspection.ownedNames.has(name));
1215
+ if (!sameNames(current, next)) pi.setActiveTools(next);
1216
+ for (const candidate of states.values()) {
1217
+ candidate.toolsAvailable = available && !candidate.lineageFailed && (candidate === state || candidate.lineage !== void 0);
1218
+ }
1219
+ if (activate && !available) {
1220
+ warnToolUnitUnavailable(state, ctx, inspection.unavailableNames, inspection.inactiveNames);
1221
+ }
1222
+ return available;
1223
+ };
1224
+ const deactivateIncompleteToolUnit = (state, ctx, publishCurrentDeactivation = true) => {
1225
+ const inspection = inspectToolUnit();
1226
+ if (inspection.complete) return false;
1227
+ let branchIsActive = false;
1228
+ for (const candidate of states.values()) {
1229
+ if (candidate.controller.signal.aborted || candidate.sessionId !== candidate.key.getSessionId()) continue;
1230
+ const candidateBranchIsActive = latestContextMode(candidate.key.getBranch()) === "active";
1231
+ if (candidate === state) branchIsActive = candidateBranchIsActive;
1232
+ candidate.fallbackDeactivationPending = candidateBranchIsActive;
1233
+ candidate.fallbackActivationPending = false;
1234
+ candidate.removeToolsAtSettlement = false;
1235
+ if (candidate.pending?.status === "requested" || candidate.pending?.status === "compacting") {
1236
+ candidate.pending.status = "failed";
1237
+ candidate.pending.errorMessage = "Experimental context management tool unit became incomplete during rollover.";
1238
+ }
1239
+ }
1240
+ if (branchIsActive && publishCurrentDeactivation) {
1241
+ pi.sendMessage(deactivationMessage(), { triggerTurn: false });
1242
+ }
1243
+ removeOwnedTools(inspection.ownedNames);
1244
+ warnToolUnitUnavailable(state, ctx, inspection.unavailableNames, inspection.inactiveNames);
1245
+ return branchIsActive;
1246
+ };
1247
+ const ensureLineage = (state, ctx) => {
1248
+ let lineage;
1249
+ try {
1250
+ const persisted = state.lineage ?? loadContextLineage(ctx.sessionManager.getBranch());
1251
+ if (persisted) {
1252
+ lineage = persisted;
1253
+ } else {
1254
+ const initial = createInitialContextState();
1255
+ pi.appendEntry(CONTEXT_STATE_ENTRY_TYPE, initial);
1256
+ lineage = initial;
1257
+ }
1258
+ } catch (error) {
1259
+ state.lineageFailed = true;
1260
+ state.toolsAvailable = false;
1261
+ throw error;
1262
+ }
1263
+ state.lineage = lineage;
1264
+ state.lineageFailed = false;
1265
+ state.toolsAvailable = (isConfigured() || state.removeToolsAtSettlement) && inspectToolUnit().complete;
1266
+ return lineage;
1267
+ };
1268
+ const warnEnabled = (state, ctx) => {
1269
+ if (state.warned || !ctx.hasUI) return;
1270
+ state.warned = true;
1271
+ ctx.ui.notify(
1272
+ "Experimental context management is active. Context rollover does not create a summary; preserve important information with context_management_update_notes.",
1273
+ "warning"
1274
+ );
1275
+ };
1276
+ const applySettings = (ctx) => {
1277
+ const state = stateFor(ctx);
1278
+ if (!state) return;
1279
+ const branch = ctx.sessionManager.getBranch();
1280
+ const runIsActive = state.agentRunActive || ctx.signal !== void 0;
1281
+ state.agentRunActive = runIsActive;
1282
+ if (!isConfigured()) {
1283
+ const inspection = inspectToolUnit();
1284
+ for (const candidate of states.values()) {
1285
+ candidate.fallbackActivationPending = false;
1286
+ const candidateRunIsActive = candidate === state ? runIsActive : candidate.agentRunActive;
1287
+ if (candidateRunIsActive && candidate.toolsAvailable && inspection.complete) {
1288
+ candidate.removeToolsAtSettlement = true;
1289
+ candidate.fallbackDeactivationPending = false;
1290
+ continue;
1291
+ }
1292
+ candidate.removeToolsAtSettlement = false;
1293
+ const branchIsActive = !candidate.controller.signal.aborted && candidate.sessionId === candidate.key.getSessionId() && latestContextMode(candidate.key.getBranch()) === "active";
1294
+ candidate.fallbackDeactivationPending = branchIsActive && (candidate !== state || candidateRunIsActive);
1295
+ if (branchIsActive && candidate === state && !candidateRunIsActive) {
1296
+ pi.sendMessage(deactivationMessage(), { triggerTurn: false });
1297
+ }
1298
+ }
1299
+ reconcileTools(state, hasDeferredToolRemoval(), ctx);
1300
+ return;
1301
+ }
1302
+ const contractAlreadyActiveOrQueued = state.removeToolsAtSettlement && !state.fallbackDeactivationPending;
1303
+ const deactivationAlreadyPending = state.fallbackDeactivationPending;
1304
+ const toolsWereAvailable = state.toolsAvailable;
1305
+ for (const candidate of states.values()) {
1306
+ candidate.removeToolsAtSettlement = false;
1307
+ candidate.fallbackDeactivationPending = false;
1308
+ candidate.fallbackActivationPending = false;
1309
+ }
1310
+ if (!reconcileTools(state, true, ctx)) {
1311
+ deactivateIncompleteToolUnit(state, ctx);
1312
+ if (runIsActive && (toolsWereAvailable || contractAlreadyActiveOrQueued || deactivationAlreadyPending)) {
1313
+ state.fallbackDeactivationPending = true;
1314
+ }
1315
+ return;
1316
+ }
1317
+ let activeLineage;
1318
+ try {
1319
+ activeLineage = ensureLineage(state, ctx);
1320
+ } catch (error) {
1321
+ state.toolsAvailable = false;
1322
+ const healthySessionRemains = [...states.values()].some(
1323
+ (candidate) => candidate !== state && candidate.toolsAvailable && !candidate.controller.signal.aborted && candidate.sessionId === candidate.key.getSessionId()
1324
+ );
1325
+ if (!healthySessionRemains) reconcileTools(state, false, ctx);
1326
+ throw error;
1327
+ }
1328
+ for (const candidate of states.values()) {
1329
+ if (candidate !== state && candidate.lineage !== void 0 && !candidate.controller.signal.aborted && candidate.sessionId === candidate.key.getSessionId() && latestContextMode(candidate.key.getBranch()) !== "active") {
1330
+ candidate.fallbackActivationPending = true;
1331
+ }
1332
+ }
1333
+ const messages = boundedContextMessages(branch);
1334
+ if (deactivationAlreadyPending || !contractAlreadyActiveOrQueued && (latestContextMode(branch) !== "active" || !hasContextContract(messages, activeLineage))) {
1335
+ pi.sendMessage(contractMessage(activeLineage), { triggerTurn: false });
1336
+ }
1337
+ state.fallbackActivationPending = false;
1338
+ warnEnabled(state, ctx);
1339
+ };
1340
+ const requestNewContext = (ctx, input) => {
1341
+ const state = stateFor(ctx);
1342
+ if (!state) throw new Error("The context session was replaced; retry in the active session");
1343
+ if (!isConfigured()) {
1344
+ throw new Error("Experimental context management is deactivating; retry after enabling it");
1345
+ }
1346
+ if (state.pending) throw new Error("A context rollover is already pending");
1347
+ const activeLineage = ensureLineage(state, ctx);
1348
+ state.pending = {
1349
+ requestId: randomUUID2(),
1350
+ nextWindowId: randomUUID2(),
1351
+ sessionId: state.sessionId,
1352
+ generation: state.generation,
1353
+ status: "requested",
1354
+ turnStartedAfterRequest: false,
1355
+ successfulTurnAfterRequest: false,
1356
+ ...input.reason ? { reason: input.reason } : {}
1357
+ };
1358
+ return {
1359
+ requestId: state.pending.requestId,
1360
+ currentWindowId: activeLineage.currentWindowId,
1361
+ nextWindowId: state.pending.nextWindowId,
1362
+ ...state.pending.reason ? { reason: state.pending.reason } : {}
1363
+ };
1364
+ };
1365
+ registerContextManagementTools(pi, {
1366
+ isEnabled(ctx) {
1367
+ const state = stateFor(ctx);
1368
+ return state ? enabledFor(state) : false;
1369
+ },
1370
+ firstWindowId(ctx) {
1371
+ return stateFor(ctx)?.lineage?.firstWindowId;
1372
+ },
1373
+ requestNewContext
1374
+ });
1375
+ const continueAfterRollover = (state, ctx, request) => {
1376
+ if (!isOwned(state, ctx, request) || request.status !== "completed") return;
1377
+ const current = state.lineage;
1378
+ const contextToolsAvailable = enabledFor(state);
1379
+ state.pending = void 0;
1380
+ if (!current) return;
1381
+ pi.sendMessage(
1382
+ {
1383
+ customType: CONTINUATION_MESSAGE_TYPE,
1384
+ content: [
1385
+ `Context window ${current.currentWindowId} is now active.`,
1386
+ request.reason ? `Rollover reason: ${request.reason}` : void 0,
1387
+ contextToolsAvailable ? "Continue the interrupted task. Use context_management_recall_context for older details and do not assume an automatic summary exists." : "Continue the interrupted task. The experimental context tools became unavailable; do not assume an automatic summary or local recall is available."
1388
+ ].filter((line) => Boolean(line)).join("\n"),
1389
+ display: false,
1390
+ details: {
1391
+ kind: CONTEXT_DETAILS_KIND,
1392
+ version: CONTEXT_VERSION,
1393
+ requestId: request.requestId,
1394
+ currentWindowId: current.currentWindowId
1395
+ }
1396
+ },
1397
+ { triggerTurn: true }
1398
+ );
1399
+ };
1400
+ const failRollover = (state, ctx, request, message) => {
1401
+ if (!isOwned(state, ctx, request)) return;
1402
+ state.pending = void 0;
1403
+ const safeMessage = terminalText(message).slice(0, 2e3);
1404
+ if (ctx.hasUI) ctx.ui.notify(safeMessage, "warning");
1405
+ pi.sendMessage(
1406
+ {
1407
+ customType: CONTINUATION_MESSAGE_TYPE,
1408
+ content: `The requested experimental context rollover failed. Continue with Pi's active fallback context. ${safeMessage}`,
1409
+ display: false,
1410
+ details: {
1411
+ kind: CONTEXT_DETAILS_KIND,
1412
+ version: CONTEXT_VERSION,
1413
+ requestId: request.requestId,
1414
+ failed: true
1415
+ }
1416
+ },
1417
+ request.successfulTurnAfterRequest ? { triggerTurn: false } : ctx.isIdle() ? { triggerTurn: true } : { triggerTurn: true, deliverAs: "followUp" }
1418
+ );
1419
+ };
1420
+ const finishRolloverWithoutContinuation = (state, ctx, request, status) => {
1421
+ if (!isOwned(state, ctx, request)) return;
1422
+ pi.appendEntry(ROLLOVER_STATE_ENTRY_TYPE, {
1423
+ kind: CONTEXT_DETAILS_KIND,
1424
+ version: CONTEXT_VERSION,
1425
+ requestId: request.requestId,
1426
+ status
1427
+ });
1428
+ if (isOwned(state, ctx, request)) state.pending = void 0;
1429
+ };
1430
+ const settle = (state, ctx) => {
1431
+ if (!isOwned(state, ctx)) return;
1432
+ state.agentRunActive = ctx.signal !== void 0;
1433
+ if (state.agentRunActive) return;
1434
+ if (state.removeToolsAtSettlement || state.fallbackDeactivationPending) {
1435
+ state.removeToolsAtSettlement = false;
1436
+ state.fallbackDeactivationPending = false;
1437
+ if (!isConfigured()) {
1438
+ if (latestContextMode(ctx.sessionManager.getBranch()) !== "inactive") {
1439
+ pi.sendMessage(deactivationMessage(), { triggerTurn: false });
1440
+ }
1441
+ reconcileTools(state, hasDeferredToolRemoval(), ctx);
1442
+ }
1443
+ }
1444
+ const request = state.pending;
1445
+ if (!request || !isOwned(state, ctx, request)) return;
1446
+ if (!isConfigured() && (request.status === "requested" || request.status === "compacting")) {
1447
+ request.status = "failed";
1448
+ request.errorMessage = "Experimental context management was disabled before rollover completed.";
1449
+ }
1450
+ if (request.status === "completed") {
1451
+ if (request.successfulTurnAfterRequest) {
1452
+ finishRolloverWithoutContinuation(state, ctx, request, "suppressed");
1453
+ } else {
1454
+ continueAfterRollover(state, ctx, request);
1455
+ }
1456
+ return;
1457
+ }
1458
+ if (request.status === "failed") {
1459
+ failRollover(state, ctx, request, request.errorMessage ?? "Compaction failed.");
1460
+ return;
1461
+ }
1462
+ if (request.status !== "requested") return;
1463
+ request.status = "compacting";
1464
+ ctx.compact({
1465
+ onComplete: (result2) => {
1466
+ if (!isOwned(state, ctx, request)) return;
1467
+ if (request.status === "failed") {
1468
+ failRollover(
1469
+ state,
1470
+ ctx,
1471
+ request,
1472
+ request.errorMessage ?? "Compaction completed without the requested context marker."
1473
+ );
1474
+ return;
1475
+ }
1476
+ const details = parseContextManagementCompaction(result2);
1477
+ if (request.status !== "completed" || !details || details.requestId !== request.requestId) {
1478
+ failRollover(state, ctx, request, "Compaction completed without the requested context marker.");
1479
+ return;
1480
+ }
1481
+ state.lineage = details;
1482
+ if (request.successfulTurnAfterRequest) {
1483
+ finishRolloverWithoutContinuation(state, ctx, request, "suppressed");
1484
+ } else {
1485
+ continueAfterRollover(state, ctx, request);
1486
+ }
1487
+ },
1488
+ onError: (error) => failRollover(state, ctx, request, error.message)
1489
+ });
1490
+ };
1491
+ return {
1492
+ isEnabled(ctx) {
1493
+ const state = stateFor(ctx);
1494
+ return state ? enabledFor(state) : false;
1495
+ },
1496
+ startSession(ctx) {
1497
+ const previous = states.get(ctx.sessionManager);
1498
+ previous?.controller.abort();
1499
+ const generation = ++nextGeneration;
1500
+ const branch = ctx.sessionManager.getBranch();
1501
+ const sessionId = ctx.sessionManager.getSessionId();
1502
+ const recoveryBudget = createContextBranchScanBudget();
1503
+ const state = {
1504
+ key: ctx.sessionManager,
1505
+ generation,
1506
+ sessionId,
1507
+ lineage: loadContextLineage(branch, recoveryBudget),
1508
+ lineageFailed: false,
1509
+ pending: restoredRollover(branch, sessionId, generation, recoveryBudget),
1510
+ warned: false,
1511
+ warnedUnavailableTools: false,
1512
+ warnedProjectionFailure: false,
1513
+ toolsAvailable: false,
1514
+ removeToolsAtSettlement: false,
1515
+ fallbackDeactivationPending: false,
1516
+ fallbackActivationPending: false,
1517
+ agentRunActive: false,
1518
+ controller: new AbortController()
1519
+ };
1520
+ states.set(ctx.sessionManager, state);
1521
+ applySettings(ctx);
1522
+ if (state.pending && ctx.isIdle()) settle(state, ctx);
1523
+ },
1524
+ onSessionTree(ctx) {
1525
+ const previous = stateFor(ctx);
1526
+ if (!previous) return;
1527
+ previous.controller.abort();
1528
+ const generation = ++nextGeneration;
1529
+ const branch = ctx.sessionManager.getBranch();
1530
+ const recoveryBudget = createContextBranchScanBudget();
1531
+ const state = {
1532
+ ...previous,
1533
+ generation,
1534
+ lineage: loadContextLineage(branch, recoveryBudget),
1535
+ lineageFailed: false,
1536
+ pending: restoredRollover(branch, previous.sessionId, generation, recoveryBudget),
1537
+ removeToolsAtSettlement: false,
1538
+ fallbackDeactivationPending: false,
1539
+ fallbackActivationPending: false,
1540
+ agentRunActive: false,
1541
+ controller: new AbortController()
1542
+ };
1543
+ states.set(ctx.sessionManager, state);
1544
+ applySettings(ctx);
1545
+ if (state.pending && ctx.isIdle()) settle(state, ctx);
1546
+ },
1547
+ applySettings,
1548
+ onInput(ctx) {
1549
+ const state = stateFor(ctx);
1550
+ if (!state || !ctx.isIdle()) return;
1551
+ if (isConfigured() && state.fallbackActivationPending && enabledFor(state)) {
1552
+ const activeLineage = ensureLineage(state, ctx);
1553
+ if (latestContextMode(ctx.sessionManager.getBranch()) !== "active") {
1554
+ pi.sendMessage(contractMessage(activeLineage), { triggerTurn: false });
1555
+ }
1556
+ state.fallbackActivationPending = false;
1557
+ return;
1558
+ }
1559
+ if (isConfigured() || !state.fallbackDeactivationPending) return;
1560
+ if (latestContextMode(ctx.sessionManager.getBranch()) !== "inactive") {
1561
+ pi.sendMessage(deactivationMessage(), { triggerTurn: false });
1562
+ }
1563
+ state.fallbackDeactivationPending = false;
1564
+ },
1565
+ beforeCompact(event, ctx) {
1566
+ const state = stateFor(ctx);
1567
+ if (!state || event.signal.aborted) return void 0;
1568
+ if (state.toolsAvailable && !inspectToolUnit().complete) deactivateIncompleteToolUnit(state, ctx);
1569
+ if (!enabledFor(state)) return void 0;
1570
+ const request = state.pending?.status === "requested" || state.pending?.status === "compacting" ? state.pending : void 0;
1571
+ try {
1572
+ const activeLineage = ensureLineage(state, ctx);
1573
+ const fingerprintBudget = createFingerprintBudget();
1574
+ const details = createContextManagementDetails(
1575
+ {
1576
+ lineage: activeLineage,
1577
+ ...compactionRetainedContext(event, fingerprintBudget),
1578
+ reason: event.reason,
1579
+ ...request ? { requestId: request.requestId, windowId: request.nextWindowId } : {}
1580
+ },
1581
+ fingerprintBudget
1582
+ );
1583
+ if (request) request.status = "compacting";
1584
+ return {
1585
+ compaction: {
1586
+ summary: contextContract(details),
1587
+ firstKeptEntryId: event.preparation.firstKeptEntryId,
1588
+ tokensBefore: event.preparation.tokensBefore,
1589
+ details
1590
+ }
1591
+ };
1592
+ } catch (error) {
1593
+ const message = terminalText(error instanceof Error ? error.message : String(error)).slice(0, 2e3);
1594
+ if (request && isOwned(state, ctx, request)) {
1595
+ request.status = "failed";
1596
+ request.errorMessage = message;
1597
+ }
1598
+ if (ctx.hasUI) ctx.ui.notify(`Experimental context compaction was cancelled. ${message}`, "warning");
1599
+ return { cancel: true };
1600
+ }
1601
+ },
1602
+ projectContext(messages, ctx) {
1603
+ const state = stateFor(ctx);
1604
+ if (!state) return void 0;
1605
+ if (state.toolsAvailable && !inspectToolUnit().complete) {
1606
+ deactivateIncompleteToolUnit(state, ctx, false);
1607
+ }
1608
+ if (!enabledFor(state)) {
1609
+ if (state.fallbackDeactivationPending) {
1610
+ if (latestContextMode(ctx.sessionManager.getBranch()) !== "inactive") {
1611
+ pi.sendMessage(deactivationMessage(), { triggerTurn: false });
1612
+ state.fallbackDeactivationPending = false;
1613
+ return [...messages, deactivationAgentMessage()];
1614
+ }
1615
+ state.fallbackDeactivationPending = false;
1616
+ }
1617
+ return void 0;
1618
+ }
1619
+ const branch = ctx.sessionManager.getBranch();
1620
+ try {
1621
+ const activationPending = state.fallbackActivationPending && latestContextMode(branch) !== "active";
1622
+ const activeLineage = state.lineage ?? loadContextLineage(branch);
1623
+ if (!activeLineage) return void 0;
1624
+ const compaction = activeContextManagementCompaction(branch);
1625
+ if (compaction) {
1626
+ const projected = projectContextManagementContext(messages, compaction.entry, compaction.details);
1627
+ if (!projected) return void 0;
1628
+ state.fallbackActivationPending = false;
1629
+ if (activationPending) {
1630
+ pi.sendMessage(contractMessage(compaction.details), { triggerTurn: false });
1631
+ return [...projected, createContextContractMessage(compaction.details)];
1632
+ }
1633
+ return reconcileContextContract(projected, compaction.details);
1634
+ }
1635
+ state.fallbackActivationPending = false;
1636
+ if (activationPending) {
1637
+ pi.sendMessage(contractMessage(activeLineage), { triggerTurn: false });
1638
+ return [...messages, createContextContractMessage(activeLineage)];
1639
+ }
1640
+ return hasContextContract(messages, activeLineage) ? void 0 : reconcileContextContract(messages, activeLineage);
1641
+ } catch (error) {
1642
+ if (!state.warnedProjectionFailure && ctx.hasUI) {
1643
+ state.warnedProjectionFailure = true;
1644
+ ctx.ui.notify(
1645
+ `Experimental context projection kept Pi's persisted context unchanged. ${terminalText(error instanceof Error ? error.message : String(error))}`,
1646
+ "warning"
1647
+ );
1648
+ }
1649
+ return void 0;
1650
+ }
1651
+ },
1652
+ onCompact(event, ctx) {
1653
+ const state = stateFor(ctx);
1654
+ if (!state || !branchContainsEntry(ctx.sessionManager.getBranch(), event.compactionEntry.id)) {
1655
+ return;
1656
+ }
1657
+ const details = parseContextManagementCompaction(event.compactionEntry);
1658
+ const request = state.pending;
1659
+ if (request?.status !== "compacting" || !isOwned(state, ctx, request)) {
1660
+ if (details) state.lineage = details;
1661
+ return;
1662
+ }
1663
+ if (!details || details.requestId !== request.requestId) {
1664
+ request.status = "failed";
1665
+ request.errorMessage = "Compaction completed without the requested context marker.";
1666
+ return;
1667
+ }
1668
+ state.lineage = details;
1669
+ request.status = "completed";
1670
+ },
1671
+ onCompactFailed(event, ctx) {
1672
+ const state = stateFor(ctx);
1673
+ const request = state?.pending;
1674
+ if (!state || request?.status !== "compacting" || !isOwned(state, ctx, request)) return;
1675
+ if (event.aborted) {
1676
+ finishRolloverWithoutContinuation(state, ctx, request, "cancelled");
1677
+ return;
1678
+ }
1679
+ request.status = "failed";
1680
+ request.errorMessage = event.errorMessage ?? "Compaction failed.";
1681
+ },
1682
+ onAgentStart(ctx) {
1683
+ const state = stateFor(ctx);
1684
+ if (state) state.agentRunActive = true;
1685
+ },
1686
+ onAgentEnd(event, ctx) {
1687
+ const state = stateFor(ctx);
1688
+ const request = state?.pending;
1689
+ if (!state || !request || !isOwned(state, ctx, request)) return;
1690
+ const stopReason = latestAssistantStopReason(event.messages);
1691
+ if (ctx.signal?.aborted || stopReason === "aborted") {
1692
+ finishRolloverWithoutContinuation(state, ctx, request, "cancelled");
1693
+ return;
1694
+ }
1695
+ if (request.turnStartedAfterRequest && (stopReason === "stop" || stopReason === "toolUse")) {
1696
+ request.successfulTurnAfterRequest = true;
1697
+ }
1698
+ },
1699
+ onTurnStart(ctx) {
1700
+ const state = stateFor(ctx);
1701
+ const request = state?.pending;
1702
+ if (state && request && isOwned(state, ctx, request)) request.turnStartedAfterRequest = true;
1703
+ },
1704
+ onAgentSettled(ctx) {
1705
+ const state = stateFor(ctx);
1706
+ if (state) settle(state, ctx);
1707
+ },
1708
+ shutdown(ctx) {
1709
+ const state = states.get(ctx.sessionManager);
1710
+ if (!state) return;
1711
+ state.controller.abort();
1712
+ states.delete(ctx.sessionManager);
1713
+ if (!isConfigured()) reconcileTools(state, hasDeferredToolRemoval(), ctx);
1714
+ }
1715
+ };
1716
+ }
1717
+
1718
+ // src/settings.ts
1719
+ import { randomUUID as randomUUID3 } from "node:crypto";
1720
+ import { constants } from "node:fs";
1721
+ import { mkdir, open, rename, rm, writeFile } from "node:fs/promises";
1722
+ import { basename, dirname, join as join2 } from "node:path";
1723
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
1724
+ var CONTEXT_MANAGEMENT_SETTINGS_FILE = "pi-context-management.json";
1725
+ var MAX_SETTINGS_BYTES = 64 * 1024;
1726
+ var DEFAULT_CONTEXT_MANAGEMENT_SETTINGS = Object.freeze({
1727
+ enabled: false
1728
+ });
1729
+ function isRecord5(value) {
1730
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1731
+ }
1732
+ function normalizeContextManagementSettings(value) {
1733
+ if (!isRecord5(value)) return void 0;
1734
+ if (Object.hasOwn(value, "enabled") && typeof value.enabled !== "boolean") return void 0;
1735
+ return {
1736
+ enabled: typeof value.enabled === "boolean" ? value.enabled : DEFAULT_CONTEXT_MANAGEMENT_SETTINGS.enabled
1737
+ };
1738
+ }
1739
+ function contextManagementSettingsPath() {
1740
+ return join2(getAgentDir(), CONTEXT_MANAGEMENT_SETTINGS_FILE);
1741
+ }
1742
+ function aborted(signal) {
1743
+ if (signal?.aborted) throw new DOMException("Settings operation aborted", "AbortError");
1744
+ }
1745
+ async function loadContextManagementSettings(path = contextManagementSettingsPath(), signal) {
1746
+ aborted(signal);
1747
+ try {
1748
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
1749
+ let text;
1750
+ try {
1751
+ const stats = await handle.stat();
1752
+ aborted(signal);
1753
+ if (!stats.isFile()) throw new Error("settings path is not a regular file");
1754
+ if (stats.size > MAX_SETTINGS_BYTES) throw new Error("settings file exceeds 64 KiB");
1755
+ text = await handle.readFile("utf8");
1756
+ } finally {
1757
+ await handle.close();
1758
+ }
1759
+ aborted(signal);
1760
+ const document = JSON.parse(text);
1761
+ const settings = normalizeContextManagementSettings(document);
1762
+ if (!settings || !isRecord5(document)) throw new Error("invalid settings shape");
1763
+ return { kind: "loaded", path, settings, document };
1764
+ } catch (error) {
1765
+ if (signal?.aborted) throw error;
1766
+ if (isNodeError(error) && error.code === "ENOENT") {
1767
+ return {
1768
+ kind: "missing",
1769
+ path,
1770
+ settings: { ...DEFAULT_CONTEXT_MANAGEMENT_SETTINGS },
1771
+ document: {}
1772
+ };
1773
+ }
1774
+ return {
1775
+ kind: "invalid",
1776
+ path,
1777
+ settings: { ...DEFAULT_CONTEXT_MANAGEMENT_SETTINGS },
1778
+ issue: isNodeError(error) && error.code === "ELOOP" ? "symbolic links are not accepted" : error instanceof Error ? error.message : String(error)
1779
+ };
1780
+ }
1781
+ }
1782
+ async function savePatch(path, patch, signal) {
1783
+ const latest = await loadContextManagementSettings(path, signal);
1784
+ if (latest.kind === "invalid") {
1785
+ throw new Error("Cannot overwrite an invalid pi-context-management.json; repair it and reload first");
1786
+ }
1787
+ const document = { ...latest.document, ...patch };
1788
+ const settings = normalizeContextManagementSettings(document);
1789
+ if (!settings) throw new Error("Refusing to save invalid context management settings");
1790
+ const temporaryPath = join2(dirname(path), `.${basename(path)}.${randomUUID3()}.tmp`);
1791
+ await mkdir(dirname(path), { recursive: true });
1792
+ aborted(signal);
1793
+ try {
1794
+ await writeFile(temporaryPath, `${JSON.stringify(document, null, 2)}
1795
+ `, {
1796
+ encoding: "utf8",
1797
+ flag: "wx",
1798
+ mode: 384
1799
+ });
1800
+ aborted(signal);
1801
+ const current = await loadContextManagementSettings(path, signal);
1802
+ if (current.kind === "invalid" || current.kind !== latest.kind || JSON.stringify(current.document) !== JSON.stringify(latest.document)) {
1803
+ throw new Error("pi-context-management.json changed while saving; reopen settings and retry");
1804
+ }
1805
+ await rename(temporaryPath, path);
1806
+ } finally {
1807
+ await rm(temporaryPath, { force: true }).catch(() => void 0);
1808
+ }
1809
+ return { kind: "loaded", path, settings, document };
1810
+ }
1811
+ function createContextManagementSettingsRuntime(path = contextManagementSettingsPath()) {
1812
+ let state = {
1813
+ kind: "missing",
1814
+ path,
1815
+ settings: { ...DEFAULT_CONTEXT_MANAGEMENT_SETTINGS },
1816
+ document: {}
1817
+ };
1818
+ let queue = Promise.resolve();
1819
+ const enqueue = (operation) => {
1820
+ const result2 = queue.then(operation, operation);
1821
+ queue = result2.then(
1822
+ () => void 0,
1823
+ () => void 0
1824
+ );
1825
+ return result2;
1826
+ };
1827
+ return {
1828
+ get: () => structuredClone(state),
1829
+ reload: (signal) => enqueue(async () => {
1830
+ state = await loadContextManagementSettings(path, signal);
1831
+ return structuredClone(state);
1832
+ }),
1833
+ update: (patch, signal) => enqueue(async () => {
1834
+ state = await savePatch(path, patch, signal);
1835
+ return structuredClone(state);
1836
+ }),
1837
+ flush: () => queue
1838
+ };
1839
+ }
1840
+ function isNodeError(error) {
1841
+ return error instanceof Error && "code" in error;
1842
+ }
1843
+
1844
+ // src/pi-context-management.ts
1845
+ function createContextManagementExtension(options = {}) {
1846
+ return (pi) => {
1847
+ const settingsRuntime = options.settingsRuntime ?? createContextManagementSettingsRuntime();
1848
+ const manager = createContextManager(pi, settingsRuntime);
1849
+ const sessions = /* @__PURE__ */ new Map();
1850
+ let nextGeneration = 0;
1851
+ pi.registerCommand("context-management", {
1852
+ description: "Configure experimental summary-free context management",
1853
+ handler: async (args, ctx) => {
1854
+ if (args.trim()) throw new Error("Usage: /context-management");
1855
+ const owner = sessions.get(ctx.sessionManager);
1856
+ const controller = owner?.controller ?? new AbortController();
1857
+ const { showContextManagementMenu } = await import("./chunks/settings-menu-WBYIMN23.ts");
1858
+ if (owner && (sessions.get(ctx.sessionManager) !== owner || controller.signal.aborted)) return;
1859
+ await showContextManagementMenu(settingsRuntime, ctx, {
1860
+ signal: controller.signal,
1861
+ isCurrent: () => owner ? sessions.get(ctx.sessionManager) === owner && !controller.signal.aborted : !controller.signal.aborted,
1862
+ isActive: () => manager.isEnabled(ctx),
1863
+ onSettingsChanged: () => manager.applySettings(ctx)
1864
+ });
1865
+ }
1866
+ });
1867
+ pi.on("session_start", async (_event, ctx) => {
1868
+ sessions.get(ctx.sessionManager)?.controller.abort();
1869
+ const owner = {
1870
+ controller: new AbortController(),
1871
+ generation: ++nextGeneration
1872
+ };
1873
+ sessions.set(ctx.sessionManager, owner);
1874
+ const sessionId = ctx.sessionManager.getSessionId();
1875
+ let state;
1876
+ try {
1877
+ state = await settingsRuntime.reload(owner.controller.signal);
1878
+ } catch (error) {
1879
+ if (owner.controller.signal.aborted || sessions.get(ctx.sessionManager) !== owner) return;
1880
+ state = settingsRuntime.get();
1881
+ if (ctx.hasUI) {
1882
+ ctx.ui.notify(
1883
+ `Could not load pi-context-management.json; using defaults. ${terminalText(error instanceof Error ? error.message : String(error))}`,
1884
+ "warning"
1885
+ );
1886
+ }
1887
+ }
1888
+ if (owner.controller.signal.aborted || sessions.get(ctx.sessionManager) !== owner || ctx.sessionManager.getSessionId() !== sessionId) {
1889
+ return;
1890
+ }
1891
+ if (ctx.hasUI && state.kind === "invalid") {
1892
+ ctx.ui.notify(
1893
+ `Invalid pi-context-management.json; using defaults without overwriting it. ${terminalText(state.issue ?? "unknown validation error")}`,
1894
+ "warning"
1895
+ );
1896
+ }
1897
+ manager.startSession(ctx);
1898
+ });
1899
+ pi.on("input", (_event, ctx) => manager.onInput(ctx));
1900
+ pi.on("session_before_compact", (event, ctx) => manager.beforeCompact(event, ctx));
1901
+ pi.on("context", (event, ctx) => {
1902
+ const messages = manager.projectContext(event.messages, ctx);
1903
+ return messages ? { messages } : void 0;
1904
+ });
1905
+ pi.on("session_tree", (_event, ctx) => manager.onSessionTree(ctx));
1906
+ pi.on("session_compact", (event, ctx) => manager.onCompact(event, ctx));
1907
+ pi.on("session_compact_failed", (event, ctx) => manager.onCompactFailed(event, ctx));
1908
+ pi.on("agent_start", (_event, ctx) => manager.onAgentStart(ctx));
1909
+ pi.on("agent_end", (event, ctx) => manager.onAgentEnd(event, ctx));
1910
+ pi.on("turn_start", (_event, ctx) => manager.onTurnStart(ctx));
1911
+ pi.on("agent_settled", (_event, ctx) => manager.onAgentSettled(ctx));
1912
+ pi.on("session_shutdown", async (_event, ctx) => {
1913
+ const owner = sessions.get(ctx.sessionManager);
1914
+ owner?.controller.abort();
1915
+ if (sessions.get(ctx.sessionManager) === owner) sessions.delete(ctx.sessionManager);
1916
+ manager.shutdown(ctx);
1917
+ await settingsRuntime.flush();
1918
+ });
1919
+ };
1920
+ }
1921
+ var pi_context_management_default = createContextManagementExtension();
1922
+ export {
1923
+ pi_context_management_default as default
1924
+ };
1925
+ //# sourceMappingURL=index.ts.map