pi-context-kit 0.0.0-stage → 0.2.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.
@@ -0,0 +1,509 @@
1
+ import {
2
+ type Api,
3
+ type Message,
4
+ type Model,
5
+ Type,
6
+ } from "@earendil-works/pi-ai";
7
+ import {
8
+ convertToLlm,
9
+ type ExtensionAPI,
10
+ type ExtensionContext,
11
+ findCutPoint,
12
+ generateSummaryWithUsage,
13
+ getLatestCompactionEntry,
14
+ type SessionEntry,
15
+ SettingsManager,
16
+ } from "@earendil-works/pi-coding-agent";
17
+ import {
18
+ BackgroundHandoff,
19
+ type BackgroundNote,
20
+ firstEntryAfter,
21
+ type Note,
22
+ } from "../src/background.ts";
23
+ import {
24
+ type ContextKitConfig,
25
+ type Method,
26
+ ownThreshold,
27
+ readConfig,
28
+ speculationLead,
29
+ } from "../src/config.ts";
30
+ import {
31
+ applyEdits,
32
+ contextTokens,
33
+ editedEntryIds,
34
+ projectedMessages,
35
+ toDrafts,
36
+ } from "../src/context.ts";
37
+ import { handoffSummary } from "../src/handoff.ts";
38
+ import { planMaintenance } from "../src/maintain.ts";
39
+ import { requestNote } from "../src/note.ts";
40
+ import { readEntry, searchEntries } from "../src/recall.ts";
41
+
42
+ // One closure per session: Pi and pi-subagents load the extension once per session in the same process.
43
+ export default function contextKit(pi: ExtensionAPI): void {
44
+ const background = new BackgroundHandoff();
45
+ let reported = "";
46
+ /** The compaction epoch in which a threshold note failed, so it is not retried every turn. */
47
+ let failedEpoch: string | null | undefined;
48
+ /** The same for Pi's summary at the extension's own threshold. */
49
+ let softFailedEpoch: string | null | undefined;
50
+
51
+ /** Reads `contextKit` from Pi's settings on each use, so `/reload` and project settings apply. */
52
+ const settings = (ctx: ExtensionContext): ContextKitConfig => {
53
+ const { config, problems } = readConfig(
54
+ Reflect.get(pi.getSettings(), "contextKit"),
55
+ );
56
+ const message = problems.join("; ");
57
+ if (message && message !== reported)
58
+ ctx.ui.notify(
59
+ `pi-context-kit: invalid settings, defaults used (${message}).`,
60
+ "warning",
61
+ );
62
+ reported = message;
63
+ return config;
64
+ };
65
+
66
+ const reasoning = () => {
67
+ const level = pi.getThinkingLevel();
68
+ return level === "off" ? undefined : level;
69
+ };
70
+
71
+ const compactionSettings = (model: Model<Api>) =>
72
+ SettingsManager.inMemory(pi.getSettings()).getCompactionSettings(model);
73
+
74
+ /** Pi compacts above this many tokens, using the same settings lookup as Pi. */
75
+ const piThreshold = (model: Model<Api> | undefined): number => {
76
+ if (!model || model.contextWindow <= 0) return Number.POSITIVE_INFINITY;
77
+ const compaction = compactionSettings(model);
78
+ return compaction.enabled
79
+ ? model.contextWindow - compaction.reserveTokens
80
+ : Number.POSITIVE_INFINITY;
81
+ };
82
+
83
+ /** Pi still compacts at its own threshold, so a configured threshold can only come earlier. */
84
+ const threshold = (
85
+ model: Model<Api> | undefined,
86
+ config: ContextKitConfig,
87
+ ): number => {
88
+ const piLimit = piThreshold(model);
89
+ return model && piLimit < Number.POSITIVE_INFINITY
90
+ ? Math.min(piLimit, ownThreshold(config, model.contextWindow))
91
+ : piLimit;
92
+ };
93
+
94
+ const epoch = (branch: SessionEntry[]) =>
95
+ getLatestCompactionEntry(branch)?.id ?? null;
96
+
97
+ const warn = (
98
+ ctx: ExtensionContext,
99
+ error: unknown,
100
+ fallback: string,
101
+ what = "handoff note",
102
+ ) => {
103
+ const message = error instanceof Error ? error.message : String(error);
104
+ ctx.ui.notify(
105
+ `pi-context-kit: ${what} failed (${message}). ${fallback}`,
106
+ "warning",
107
+ );
108
+ };
109
+
110
+ /** Pi's summary at the extension's threshold, because Pi's own hook waits for Pi's threshold. */
111
+ const soft = async (input: {
112
+ ctx: ExtensionContext;
113
+ model: Model<Api>;
114
+ config: ContextKitConfig;
115
+ branch: SessionEntry[];
116
+ entries: Parameters<typeof projectedMessages>[0];
117
+ limit: number;
118
+ }) => {
119
+ const { ctx, model, config, limit } = input;
120
+ const { keepRecentTokens, reserveTokens } = compactionSettings(model);
121
+ const keptEntryId = recentStart(ctx, keepRecentTokens);
122
+ if (!keptEntryId) return undefined;
123
+ const retained = keptTokens(ctx, keptEntryId);
124
+ if (!fits("", retained, limit, config.progressRatio)) return undefined;
125
+ const start = input.entries.findIndex(
126
+ (entry) => entry.sourceEntry.id === keptEntryId,
127
+ );
128
+ // As in Pi, the previous summary goes to the update prompt, not into the history.
129
+ const previous = input.entries.findIndex(
130
+ (entry) =>
131
+ entry.sourceEntry.type === "compaction" && entry.messages.length > 0,
132
+ );
133
+ if (start <= previous + 1) return undefined;
134
+ const source = input.entries[previous]?.sourceEntry;
135
+ const { text, usage } = await generateSummaryWithUsage(
136
+ projectedMessages(input.entries.slice(previous + 1, start)),
137
+ model,
138
+ reserveTokens,
139
+ undefined,
140
+ undefined,
141
+ ctx.signal,
142
+ undefined,
143
+ source?.type === "compaction" ? source.summary : undefined,
144
+ pi.getThinkingLevel(),
145
+ // The registry resolves auth per request, as for handoff notes.
146
+ (model, context, options) =>
147
+ ctx.modelRegistry.streamSimple(model, context, options),
148
+ undefined,
149
+ undefined,
150
+ undefined,
151
+ ctx.sessionManager.getSessionId(),
152
+ );
153
+ const summary = handoffSummary(text, input.branch);
154
+ return fits(summary.summary, retained, limit, config.progressRatio)
155
+ ? { ...summary, firstKeptEntryId: keptEntryId, usage }
156
+ : undefined;
157
+ };
158
+
159
+ /**
160
+ * Builds a handoff compaction. A background note keeps everything after its leaf. A new note
161
+ * covers the whole context and keeps from `keptEntryId`, so the latest work stays visible.
162
+ */
163
+ const handoff = async (input: {
164
+ ctx: ExtensionContext;
165
+ model: Model<Api>;
166
+ config: ContextKitConfig;
167
+ branch: SessionEntry[];
168
+ ready: BackgroundNote | undefined;
169
+ keptEntryId: string;
170
+ limit: number;
171
+ /** Undefined when only the background note may be used. */
172
+ messages: Message[] | undefined;
173
+ focus?: string;
174
+ signal: AbortSignal;
175
+ cancelBackground: () => void;
176
+ }) => {
177
+ const { ctx, branch, ready } = input;
178
+ const compaction = (note: Note, firstKeptEntryId: string) => ({
179
+ ...handoffSummary(note.note, branch),
180
+ firstKeptEntryId,
181
+ usage: note.usage,
182
+ });
183
+ if (ready) {
184
+ const result = compaction(
185
+ ready,
186
+ firstEntryAfter(branch, ready.leafId) ?? input.keptEntryId,
187
+ );
188
+ const kept = keptTokens(ctx, result.firstKeptEntryId);
189
+ if (fits(result.summary, kept, input.limit, input.config.progressRatio))
190
+ return result;
191
+ }
192
+ const retained = keptTokens(ctx, input.keptEntryId);
193
+ const availableTokens = Math.floor(
194
+ input.limit * input.config.progressRatio - retained,
195
+ );
196
+ if (!input.messages || availableTokens <= 0) {
197
+ input.cancelBackground();
198
+ return undefined;
199
+ }
200
+ input.cancelBackground();
201
+ const note = await requestNote({
202
+ registry: ctx.modelRegistry,
203
+ model: input.model,
204
+ sessionId: ctx.sessionManager.getSessionId(),
205
+ messages: input.messages,
206
+ reasoning: reasoning(),
207
+ focus: input.focus,
208
+ signal: input.signal,
209
+ maxTokens: Math.min(input.model.maxTokens, availableTokens),
210
+ });
211
+ if (!note) return undefined;
212
+ const result = compaction(note, input.keptEntryId);
213
+ return fits(
214
+ result.summary,
215
+ retained,
216
+ input.limit,
217
+ input.config.progressRatio,
218
+ )
219
+ ? result
220
+ : undefined;
221
+ };
222
+
223
+ pi.on("turn_end", async (event, ctx) => {
224
+ const config = settings(ctx);
225
+ if (!config.enabled) return undefined;
226
+ const model = ctx.model;
227
+ const limit = threshold(model, config);
228
+ const methods = config.methodOrder;
229
+ const entries = event.context.contextEntries;
230
+ const branch = ctx.sessionManager.getBranch();
231
+ const edited = editedEntryIds(branch);
232
+ const tokens =
233
+ ctx.getContextUsage()?.tokens ??
234
+ contextTokens(projectedMessages(entries));
235
+ const plan = (shake: boolean) =>
236
+ planMaintenance({
237
+ entries,
238
+ edited,
239
+ options: { ...config, shake: shake ? config.shake : undefined },
240
+ tokens,
241
+ threshold: limit,
242
+ });
243
+ const shakeFirst = before(methods, "shake", "handoff");
244
+ let result = plan(shakeFirst);
245
+ const drafts = () => toDrafts(result.edits);
246
+
247
+ const leafId = ctx.sessionManager.getLeafId();
248
+ const current = epoch(branch);
249
+ background.invalidate(current, branch);
250
+ // Try ordered strategies at Pi's threshold before its native hook can compact.
251
+ const own = result.tokens > limit;
252
+ if (model && leafId && before(methods, "handoff", "soft")) {
253
+ const messages = () =>
254
+ convertToLlm(projectedMessages(applyEdits(entries, result.edits)));
255
+ const keepRecentTokens = compactionSettings(model).keepRecentTokens;
256
+ const keptEntryId = own ? recentStart(ctx, keepRecentTokens) : undefined;
257
+ const speculativeKeptId = recentStart(ctx, keepRecentTokens);
258
+ const speculativeBudget = speculativeKeptId
259
+ ? Math.floor(
260
+ limit * config.progressRatio - keptTokens(ctx, speculativeKeptId),
261
+ )
262
+ : 0;
263
+ if (
264
+ config.asyncEnabled &&
265
+ speculativeBudget > 0 &&
266
+ result.tokens > limit - speculationLead(limit) &&
267
+ result.tokens <= limit
268
+ ) {
269
+ const context = messages();
270
+ const maxTokens = Math.min(model.maxTokens, speculativeBudget);
271
+ background.start(
272
+ current,
273
+ leafId,
274
+ (signal) =>
275
+ requestNote({
276
+ registry: ctx.modelRegistry,
277
+ model,
278
+ sessionId: ctx.sessionManager.getSessionId(),
279
+ messages: context,
280
+ reasoning: reasoning(),
281
+ signal,
282
+ maxTokens,
283
+ }),
284
+ (error) => warn(ctx, error, "A new note is written at compaction."),
285
+ );
286
+ }
287
+ if (own && keptEntryId && failedEpoch !== current) {
288
+ const writing = background.writing(current);
289
+ if (writing && limit < piThreshold(model)) return { entries: drafts() };
290
+ const signal = ctx.signal ?? new AbortController().signal;
291
+ try {
292
+ const compaction = await handoff({
293
+ ctx,
294
+ model,
295
+ config,
296
+ branch,
297
+ ready: await background.takeReady(current, branch),
298
+ keptEntryId,
299
+ limit,
300
+ messages: writing ? undefined : messages(),
301
+ signal,
302
+ cancelBackground: () => background.cancel(),
303
+ });
304
+ if (compaction) {
305
+ background.cancel();
306
+ return {
307
+ entries: [...drafts(), { type: "compaction", ...compaction }],
308
+ };
309
+ }
310
+ failedEpoch = current;
311
+ } catch (error) {
312
+ failedEpoch = current;
313
+ if (!signal.aborted)
314
+ warn(ctx, error, "The remaining methods in methodOrder are tried.");
315
+ }
316
+ }
317
+ }
318
+ const shakeAfterHandoff = !shakeFirst && before(methods, "shake", "soft");
319
+ if (tokens > limit && shakeAfterHandoff) result = plan(true);
320
+ const softDue =
321
+ model &&
322
+ result.tokens > limit &&
323
+ limit < piThreshold(model) &&
324
+ methods.includes("soft") &&
325
+ softFailedEpoch !== current;
326
+ if (softDue) {
327
+ try {
328
+ const compaction = await soft({
329
+ ctx,
330
+ model,
331
+ config,
332
+ branch,
333
+ entries: applyEdits(entries, result.edits),
334
+ limit,
335
+ });
336
+ if (compaction)
337
+ return {
338
+ entries: [...drafts(), { type: "compaction", ...compaction }],
339
+ };
340
+ } catch (error) {
341
+ if (!ctx.signal?.aborted)
342
+ warn(ctx, error, "Pi compacts at its own threshold.", "Pi's summary");
343
+ }
344
+ softFailedEpoch = current;
345
+ }
346
+ return result.edits.length > 0 ? { entries: drafts() } : undefined;
347
+ });
348
+
349
+ pi.on("session_before_compact", async (event, ctx) => {
350
+ const model = ctx.model;
351
+ const config = settings(ctx);
352
+ if (
353
+ !model ||
354
+ !config.enabled ||
355
+ !before(config.methodOrder, "handoff", "soft")
356
+ )
357
+ return undefined;
358
+ const { preparation, branchEntries, signal } = event;
359
+ const currentEpoch = epoch(branchEntries);
360
+ if (event.reason === "threshold" && failedEpoch === currentEpoch)
361
+ return undefined;
362
+ const limit = Math.min(threshold(model, config), model.contextWindow);
363
+ try {
364
+ const current = currentEpoch;
365
+ background.invalidate(current, branchEntries);
366
+ if (event.customInstructions) background.cancel();
367
+ const writing = !event.customInstructions && background.writing(current);
368
+ const compaction = await handoff({
369
+ ctx,
370
+ model,
371
+ config,
372
+ branch: branchEntries,
373
+ // A focused /compact needs a note written for that focus.
374
+ ready: event.customInstructions
375
+ ? undefined
376
+ : await background.takeReady(current, branchEntries),
377
+ keptEntryId: preparation.firstKeptEntryId,
378
+ limit,
379
+ // The live context no longer fits the model after an overflow.
380
+ messages:
381
+ event.reason === "overflow" || writing
382
+ ? undefined
383
+ : liveMessages(ctx),
384
+ focus: event.customInstructions,
385
+ signal,
386
+ cancelBackground: () => background.cancel(),
387
+ });
388
+ return (
389
+ compaction && {
390
+ compaction: { ...compaction, tokensBefore: preparation.tokensBefore },
391
+ }
392
+ );
393
+ } catch (error) {
394
+ if (!signal.aborted) warn(ctx, error, "Pi's summary is used instead.");
395
+ return undefined;
396
+ }
397
+ });
398
+
399
+ pi.on("session_compact", () => background.cancel());
400
+ pi.on("session_shutdown", () => background.cancel());
401
+
402
+ pi.registerTool({
403
+ name: "recall",
404
+ label: "Recall",
405
+ description:
406
+ "Search or read the full session history, including messages removed by compaction and tool outputs that were pruned or elided. " +
407
+ "Pass `query` to list matching entries with their IDs, newest first. Pass `entryId` to read one entry in full.",
408
+ parameters: Type.Object({
409
+ query: Type.Optional(
410
+ Type.String({ description: "Text to find, case-insensitive." }),
411
+ ),
412
+ regex: Type.Optional(
413
+ Type.Boolean({ description: "Treat query as a regular expression." }),
414
+ ),
415
+ entryId: Type.Optional(
416
+ Type.String({ description: "ID of the entry to read." }),
417
+ ),
418
+ offset: Type.Optional(
419
+ Type.Number({
420
+ description:
421
+ "Matches or characters to skip, as given in the previous result.",
422
+ }),
423
+ ),
424
+ limit: Type.Optional(
425
+ Type.Number({
426
+ description: "Maximum matches or characters to return.",
427
+ }),
428
+ ),
429
+ }),
430
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
431
+ const branch = ctx.sessionManager.getBranch();
432
+ let text: string;
433
+ if (params.entryId) text = readEntry(branch, params.entryId, params);
434
+ else if (params.query)
435
+ text = await searchEntries(
436
+ branch,
437
+ { ...params, query: params.query },
438
+ signal,
439
+ );
440
+ else throw new Error("Pass query or entryId.");
441
+ return { content: [{ type: "text", text }], details: undefined };
442
+ },
443
+ });
444
+ }
445
+
446
+ function liveMessages(ctx: ExtensionContext): Message[] {
447
+ return convertToLlm(ctx.sessionManager.buildSessionProjection().messages);
448
+ }
449
+
450
+ /** Tokens of the system prompt plus the projected context from `firstKeptEntryId` on. */
451
+ function keptTokens(ctx: ExtensionContext, firstKeptEntryId: string): number {
452
+ const entries = ctx.sessionManager.buildSessionProjection().entries;
453
+ const start = entries.findIndex(
454
+ (entry) => entry.sourceEntry.id === firstKeptEntryId,
455
+ );
456
+ if (start < 0) return Number.POSITIVE_INFINITY;
457
+ const system = projectedMessages(entries)
458
+ .filter((message) => message.role === "system")
459
+ .at(-1);
460
+ return contextTokens([
461
+ ...(system ? [system] : []),
462
+ ...projectedMessages(entries.slice(start)),
463
+ ]);
464
+ }
465
+
466
+ function fits(
467
+ summary: string,
468
+ kept: number,
469
+ limit: number,
470
+ ratio: number,
471
+ ): boolean {
472
+ return Math.ceil(summary.length / 4) + kept <= limit * ratio;
473
+ }
474
+
475
+ /** Soft ends the extension's strategy chain, even when other methods follow it. */
476
+ function before(methods: readonly Method[], a: Method, b: Method): boolean {
477
+ const index = methods.indexOf(a);
478
+ const other = methods.indexOf(b);
479
+ const soft = methods.indexOf("soft");
480
+ const stop = Math.min(
481
+ other >= 0 ? other : Number.POSITIVE_INFINITY,
482
+ soft >= 0 ? soft : Number.POSITIVE_INFINITY,
483
+ );
484
+ return index >= 0 && index < stop;
485
+ }
486
+
487
+ /** Finds the retained boundary from model-visible entries, including prior compaction tails and edits. */
488
+ function recentStart(
489
+ ctx: ExtensionContext,
490
+ keepRecentTokens: number,
491
+ ): string | undefined {
492
+ const entries: SessionEntry[] = [];
493
+ for (const projected of ctx.sessionManager.buildSessionProjection().entries) {
494
+ const source = projected.sourceEntry;
495
+ if (source.type === "compaction") continue;
496
+ for (const message of projected.messages) {
497
+ if (message.role === "system") continue;
498
+ entries.push({
499
+ type: "message",
500
+ id: source.id,
501
+ parentId: source.parentId,
502
+ timestamp: source.timestamp,
503
+ message,
504
+ });
505
+ }
506
+ }
507
+ const cut = findCutPoint(entries, 0, entries.length, keepRecentTokens);
508
+ return entries[cut.firstKeptEntryIndex]?.id;
509
+ }
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "pi-context-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "Context maintenance for Pi: stale read replacement, pruning, handoff compaction with background notes, and recall.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "HugoLopes45 (https://github.com/HugoLopes45)",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/HugoLopes45/pi-context-kit.git"
11
+ },
12
+ "homepage": "https://github.com/HugoLopes45/pi-context-kit#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/HugoLopes45/pi-context-kit/issues"
15
+ },
16
+ "keywords": [
17
+ "pi-package",
18
+ "pi-extension",
19
+ "pi",
20
+ "compaction",
21
+ "context",
22
+ "handoff"
23
+ ],
24
+ "files": [
25
+ "extensions",
26
+ "src",
27
+ "CHANGELOG.md"
28
+ ],
29
+ "pi": {
30
+ "extensions": [
31
+ "./extensions/index.ts"
32
+ ]
33
+ },
34
+ "scripts": {
35
+ "check": "node scripts/release.ts check && tsc --noEmit && vitest --run",
36
+ "test": "vitest --run",
37
+ "release": "node scripts/release.ts prepare",
38
+ "prepublishOnly": "test -n \"$GITHUB_ACTIONS\" || test \"$(npm whoami)\" = hugolopes45 || { echo 'Publish only as the npm user hugolopes45.' >&2; exit 1; }; npm run check"
39
+ },
40
+ "peerDependencies": {
41
+ "@earendil-works/pi-ai": "*",
42
+ "@earendil-works/pi-coding-agent": "*"
43
+ },
44
+ "devDependencies": {
45
+ "@earendil-works/pi-ai": "^1.0.3",
46
+ "@earendil-works/pi-coding-agent": "^1.0.3",
47
+ "@types/node": "^26.6.4",
48
+ "typescript": "^7.0.2",
49
+ "vitest": "^5.0.3"
50
+ }
51
+ }
@@ -0,0 +1,104 @@
1
+ import type { Usage } from "@earendil-works/pi-ai";
2
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
3
+
4
+ export interface Note {
5
+ note: string;
6
+ usage?: Usage;
7
+ }
8
+
9
+ export interface BackgroundNote extends Note {
10
+ /** The last entry the note covers. */
11
+ leafId: string;
12
+ }
13
+
14
+ interface Job {
15
+ /** ID of the latest compaction when the job started, or null before the first one. */
16
+ epoch: string | null;
17
+ leafId: string;
18
+ controller: AbortController;
19
+ note: Promise<Note | undefined>;
20
+ settled: boolean;
21
+ }
22
+
23
+ /** One speculative handoff note per compaction epoch, written while the agent keeps working. */
24
+ export class BackgroundHandoff {
25
+ #job: Job | undefined;
26
+
27
+ /** Starts a job unless one already ran in this epoch. */
28
+ start(
29
+ epoch: string | null,
30
+ leafId: string,
31
+ run: (signal: AbortSignal) => Promise<Note | undefined>,
32
+ onError: (error: unknown) => void,
33
+ ): boolean {
34
+ if (this.#job?.epoch === epoch) return false;
35
+ this.cancel();
36
+ const controller = new AbortController();
37
+ const note = run(controller.signal)
38
+ .catch((error: unknown) => {
39
+ if (!controller.signal.aborted) onError(error);
40
+ return undefined;
41
+ })
42
+ .finally(() => {
43
+ job.settled = true;
44
+ });
45
+ const job: Job = { epoch, leafId, controller, note, settled: false };
46
+ this.#job = job;
47
+ return true;
48
+ }
49
+
50
+ /** Whether the note of this epoch is still being written. */
51
+ writing(epoch: string | null): boolean {
52
+ return this.#job?.epoch === epoch && !this.#job.settled;
53
+ }
54
+
55
+ /** Returns a finished note only when it still covers a prefix of the branch. */
56
+ async takeReady(
57
+ epoch: string | null,
58
+ branch: readonly SessionEntry[],
59
+ ): Promise<BackgroundNote | undefined> {
60
+ const job = this.#job;
61
+ if (
62
+ !job ||
63
+ !job.settled ||
64
+ job.epoch !== epoch ||
65
+ !branch.some((entry) => entry.id === job.leafId)
66
+ ) {
67
+ return undefined;
68
+ }
69
+ const note = await job.note;
70
+ return note && { ...note, leafId: job.leafId };
71
+ }
72
+
73
+ /** Cancels work tied to a branch that is no longer active. */
74
+ invalidate(epoch: string | null, branch: readonly SessionEntry[]): void {
75
+ if (
76
+ this.#job &&
77
+ (this.#job.epoch !== epoch ||
78
+ !branch.some((entry) => entry.id === this.#job?.leafId))
79
+ ) {
80
+ this.cancel();
81
+ }
82
+ }
83
+
84
+ cancel(): void {
85
+ this.#job?.controller.abort();
86
+ this.#job = undefined;
87
+ }
88
+ }
89
+
90
+ /** The first entry after `leafId` that may start the kept part of a context. */
91
+ export function firstEntryAfter(
92
+ branch: readonly SessionEntry[],
93
+ leafId: string,
94
+ ): string | undefined {
95
+ const index = branch.findIndex((entry) => entry.id === leafId);
96
+ if (index < 0) return undefined;
97
+ return branch
98
+ .slice(index + 1)
99
+ .find(
100
+ (entry) =>
101
+ entry.type === "custom_message" ||
102
+ (entry.type === "message" && entry.message.role !== "toolResult"),
103
+ )?.id;
104
+ }