@howaboua/pi-notes-compaction 0.0.9 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +23 -5
  2. package/PCC-INTEGRATION.md +7 -98
  3. package/README.md +21 -13
  4. package/package.json +7 -3
  5. package/src/activation.ts +152 -0
  6. package/src/agent-identity.ts +119 -0
  7. package/src/attachment-snapshot.ts +103 -0
  8. package/src/binding-startup.ts +30 -0
  9. package/src/bridge.ts +1 -43
  10. package/src/compaction-projection.ts +88 -0
  11. package/src/context-owner.ts +103 -0
  12. package/src/context-sharing.ts +144 -0
  13. package/src/extension-hooks.ts +198 -0
  14. package/src/extension-sharing.ts +118 -0
  15. package/src/fresh-checkpoint.ts +117 -0
  16. package/src/fresh-notes.ts +141 -26
  17. package/src/history-search-protocol.ts +39 -0
  18. package/src/history-search-pruning.mjs +120 -0
  19. package/src/history-search-worker.mjs +256 -0
  20. package/src/history-search.ts +269 -0
  21. package/src/history.ts +212 -40
  22. package/src/idle-admission.ts +201 -0
  23. package/src/index.ts +71 -401
  24. package/src/integrations.ts +159 -0
  25. package/src/lifecycle.ts +63 -448
  26. package/src/note-save-marker.ts +112 -0
  27. package/src/notes-lookup.ts +112 -0
  28. package/src/notes.ts +24 -28
  29. package/src/query-executor.ts +190 -0
  30. package/src/remote.ts +357 -0
  31. package/src/rollover.ts +212 -0
  32. package/src/saved-session.ts +44 -7
  33. package/src/session-pruning-content.ts +237 -0
  34. package/src/session-pruning-plan.ts +243 -0
  35. package/src/session-pruning-policy.ts +20 -0
  36. package/src/session-pruning-screen.ts +130 -0
  37. package/src/session-pruning-source.ts +44 -0
  38. package/src/session-pruning-transaction.ts +141 -0
  39. package/src/session-pruning.ts +142 -0
  40. package/src/settings-command.ts +77 -0
  41. package/src/settings-screen.ts +84 -19
  42. package/src/settings.ts +143 -11
  43. package/src/shared-notes.ts +37 -14
  44. package/src/sharing-service.ts +348 -0
  45. package/src/store.ts +31 -0
  46. package/src/task-boundary.ts +6 -1
  47. package/src/tool-contracts.ts +279 -0
  48. package/src/tools.ts +19 -560
  49. package/src/tree-archive.ts +149 -0
  50. package/src/tree-checkpoint.ts +170 -0
  51. package/src/tree-handoff-read.ts +192 -0
  52. package/src/window-checkpoint.ts +105 -0
  53. package/src/windows.ts +25 -9
package/src/lifecycle.ts CHANGED
@@ -11,17 +11,16 @@ import type {
11
11
  SessionBeforeCompactEvent,
12
12
  SessionCompactFailedEvent,
13
13
  } from "@earendil-works/pi-coding-agent";
14
- import {
15
- buildSessionProjection,
16
- prepareBranchEntries,
17
- } from "@earendil-works/pi-coding-agent";
18
14
  import type { NotesBridge } from "./bridge.js";
15
+ import { FreshCheckpoint } from "./fresh-checkpoint.js";
19
16
  import {
20
17
  hasFreshNotes,
21
18
  hasPrecedingNoteWrite,
22
19
  NOTES_RUN_ENTRY,
23
20
  } from "./fresh-notes.js";
21
+ import { IdleAdmission } from "./idle-admission.js";
24
22
  import { noteHints, sessionRef } from "./notes.js";
23
+ import { RolloverRequests } from "./rollover.js";
25
24
  import type { IdleMinutes, NewWindowRequests } from "./settings.js";
26
25
  import { savedNotesIdentity } from "./shared-notes.js";
27
26
  import type { NotesStore } from "./store.js";
@@ -33,28 +32,7 @@ import {
33
32
  windowMessage,
34
33
  } from "./windows.js";
35
34
 
36
- interface Checkpoint {
37
- sessionId: string;
38
- windowId: string;
39
- requestId: string;
40
- runId: string | undefined;
41
- outcome: "completed" | "aborted" | "error" | undefined;
42
- }
43
- interface HeldInput {
44
- sessionId: string;
45
- phase: "failed" | "rolling" | "releasing" | "draining";
46
- releasePrompt: string;
47
- admissions: ((result: InputEventResult) => void)[];
48
- }
49
- type Rollover = {
50
- sessionId: string;
51
- windowId: string | undefined;
52
- triggerTurn: boolean;
53
- } & (
54
- | { phase: "scheduled" | "compacting" }
55
- | { phase: "checking"; accepted?: AbortSignal }
56
- );
57
-
35
+ // Public event coordinator owns window identity and orders settlement before admissions.
58
36
  export class NotesLifecycle {
59
37
  readonly windows = new Windows();
60
38
  gptPromptMode = () => false;
@@ -64,24 +42,34 @@ export class NotesLifecycle {
64
42
  idleMinutes: IdleMinutes = 0;
65
43
  taskBoundaryReminder = 0;
66
44
  bridge: NotesBridge | undefined;
45
+ prepareReminder: NotesBridge["prepareReminder"];
46
+ prepareWindow: ((ctx: ExtensionContext) => Promise<void>) | undefined;
67
47
  runId = "";
68
- private checkpoint: Checkpoint | undefined;
69
- private held: HeldInput | undefined;
70
- private rollover: Rollover | undefined;
71
- private customAdmission: Promise<void> | undefined;
72
- private cancelledCompact:
73
- | {
74
- sessionId: string;
75
- signal: AbortSignal;
76
- instructions: string | undefined;
77
- }
78
- | undefined;
48
+ private readonly checkpoint: FreshCheckpoint;
49
+ private readonly admission: IdleAdmission;
50
+ private readonly requests: RolloverRequests;
79
51
 
80
52
  private readonly pi: ExtensionAPI;
81
53
  private readonly store: NotesStore;
82
54
  constructor(pi: ExtensionAPI, store: NotesStore) {
83
55
  this.pi = pi;
84
56
  this.store = store;
57
+ this.checkpoint = new FreshCheckpoint(this, (message, options) =>
58
+ this.sendMessage(message, options),
59
+ );
60
+ this.requests = new RolloverRequests(
61
+ this,
62
+ (ctx, triggerTurn, trim) => this.openWindow(ctx, triggerTurn, trim),
63
+ (message, options) => this.sendMessage(message, options),
64
+ (ctx, instructions) => this.checkpoint.start(ctx, instructions),
65
+ );
66
+ this.admission = new IdleAdmission(
67
+ this,
68
+ pi,
69
+ (ctx, triggerTurn) => this.requests.roll(ctx, triggerTurn),
70
+ () => this.requests.pending,
71
+ () => this.checkpoint.pending,
72
+ );
85
73
  }
86
74
  private sendMessage(
87
75
  message: Omit<CustomMessageEntryDraft, "type">,
@@ -92,10 +80,7 @@ export class NotesLifecycle {
92
80
  ...message,
93
81
  details: message.details ?? {},
94
82
  };
95
- this.pi.sendMessage(
96
- this.bridge?.prepareReminder?.(draft) ?? draft,
97
- options,
98
- );
83
+ this.pi.sendMessage(this.prepareReminder?.(draft) ?? draft, options);
99
84
  }
100
85
  agent(ctx: ExtensionContext): string {
101
86
  return (
@@ -107,13 +92,9 @@ export class NotesLifecycle {
107
92
  );
108
93
  }
109
94
  reset(ctx?: ExtensionContext): void {
110
- this.customAdmission = undefined;
111
- this.checkpoint = undefined;
112
- this.rollover = undefined;
113
- this.cancelledCompact = undefined;
114
- for (const admit of this.held?.admissions ?? [])
115
- admit({ action: "handled" });
116
- this.held = undefined;
95
+ this.admission.reset();
96
+ this.checkpoint.reset();
97
+ this.requests.reset();
117
98
  this.runId = "";
118
99
  this.windows.restore(ctx?.sessionManager.getBranch() ?? []);
119
100
  }
@@ -171,37 +152,11 @@ export class NotesLifecycle {
171
152
  else message = this.initialize(ctx);
172
153
  this.runId = randomUUID();
173
154
  this.pi.appendEntry(NOTES_RUN_ENTRY, { runId: this.runId });
174
- if (
175
- this.checkpoint &&
176
- event.messageType === "custom" &&
177
- event.message.customType === "notes-compaction:checkpoint:v1" &&
178
- (event.message.details as { requestId?: string } | undefined)
179
- ?.requestId === this.checkpoint.requestId
180
- )
181
- this.checkpoint.runId = this.runId;
155
+ this.checkpoint.bind(event, this.runId);
182
156
  return message
183
- ? { message: this.bridge?.prepareReminder?.(message) ?? message }
157
+ ? { message: this.prepareReminder?.(message) ?? message }
184
158
  : undefined;
185
159
  }
186
- prepareCustomTurn(ctx: ExtensionContext): Promise<void> | undefined {
187
- if (this.customAdmission) return this.customAdmission;
188
- if (!this.active || !this.idleDue(ctx) || !this.fresh(ctx)) return;
189
- const sessionId = ctx.sessionManager.getSessionId();
190
- const preparation = this.roll(ctx, false)
191
- .then(() => {
192
- if (!this.active || sessionId !== ctx.sessionManager.getSessionId())
193
- throw new Error("Session changed during custom kickoff admission");
194
- })
195
- .finally(() => {
196
- if (this.customAdmission === preparation)
197
- this.customAdmission = undefined;
198
- });
199
- this.customAdmission = preparation;
200
- return preparation;
201
- }
202
- outcome(outcome: "completed" | "aborted" | "error"): void {
203
- if (this.checkpoint) this.checkpoint.outcome = outcome;
204
- }
205
160
  fresh(ctx: ExtensionContext, runId?: string): boolean {
206
161
  return hasFreshNotes(
207
162
  ctx.sessionManager.getBranch(),
@@ -214,8 +169,8 @@ export class NotesLifecycle {
214
169
  throw new Error(
215
170
  "New window requests are disabled. Continue in the current window.",
216
171
  );
217
- if (this.checkpoint || this.held) return false;
218
- if (this.rollover) return false;
172
+ if (this.checkpoint.pending || this.admission.pending) return false;
173
+ if (this.requests.pending) return false;
219
174
  if (
220
175
  !hasPrecedingNoteWrite(
221
176
  ctx.sessionManager.getBranch(),
@@ -225,14 +180,9 @@ export class NotesLifecycle {
225
180
  )
226
181
  )
227
182
  throw new Error(
228
- "Save your progress with notes, wait for the write to succeed, then call new_context next.",
183
+ "Save your progress in your own notes using a relative path, wait for the write to succeed, then call new_context next. Writing another agent's notes does not save your checkpoint.",
229
184
  );
230
- this.rollover = {
231
- sessionId: ctx.sessionManager.getSessionId(),
232
- windowId: this.windows.current?.currentWindowId,
233
- phase: "scheduled",
234
- triggerTurn: true,
235
- };
185
+ this.requests.schedule(ctx);
236
186
  return true;
237
187
  }
238
188
  private async openWindow(
@@ -243,8 +193,14 @@ export class NotesLifecycle {
243
193
  if (!ctx.isIdle())
244
194
  throw new Error("Wait for the current run to settle before rollover");
245
195
  const sessionId = ctx.sessionManager.getSessionId();
246
- await this.bridge?.beforeWindow?.(ctx);
247
- if (sessionId !== ctx.sessionManager.getSessionId() || !this.active)
196
+ const windowId = this.windows.current?.currentWindowId;
197
+ if (trim) await this.prepareWindow?.(ctx);
198
+ if (
199
+ !ctx.isIdle() ||
200
+ sessionId !== ctx.sessionManager.getSessionId() ||
201
+ windowId !== this.windows.current?.currentWindowId ||
202
+ !this.active
203
+ )
248
204
  throw new Error("Session changed before rollover");
249
205
  const ids = this.windows.next();
250
206
  const hint = noteHints(this.store, ctx, this.agent(ctx));
@@ -258,347 +214,42 @@ export class NotesLifecycle {
258
214
  );
259
215
  this.windows.current = ids;
260
216
  if (triggerTurn)
261
- message.content = `${message.content}\n\nRead your saved notes and resume the task.`;
217
+ message.content = `${message.content}\n\n${this.gptPromptMode() ? "Saved notes→notes tool→resume task" : "Read your saved notes with the notes tool and resume the task."}`;
262
218
  this.sendMessage(message, { triggerTurn });
263
219
  }
264
- private async roll(
265
- ctx: ExtensionContext,
266
- triggerTurn: boolean,
267
- ): Promise<void> {
268
- const policy = triggerTurn ? this.newWindowRequests : undefined;
269
- const checkOnly = !this.normalCompaction && policy === "pi-limits";
270
- if (!this.normalCompaction && !checkOnly) {
271
- await this.openWindow(ctx, triggerTurn, true);
272
- return;
273
- }
274
- const pending: Rollover = {
275
- sessionId: ctx.sessionManager.getSessionId(),
276
- windowId: this.windows.current?.currentWindowId,
277
- phase: checkOnly ? "checking" : "compacting",
278
- triggerTurn,
279
- };
280
- this.rollover = pending;
281
- await new Promise<void>((resolve, reject) => {
282
- const current = () =>
283
- this.active &&
284
- this.rollover === pending &&
285
- pending.sessionId === ctx.sessionManager.getSessionId() &&
286
- pending.windowId === this.windows.current?.currentWindowId;
287
- const finish = (trim: boolean) => {
288
- this.rollover = undefined;
289
- void this.openWindow(ctx, triggerTurn, trim).then(resolve, reject);
290
- };
291
- ctx.compact({
292
- onComplete: () => {
293
- if (!current()) {
294
- reject(new Error("Session changed during compaction"));
295
- return;
296
- }
297
- finish(false);
298
- },
299
- onError: (error) => {
300
- if (current()) {
301
- // Only our own accepted gate cancels a summary in favour of notes-only rollover.
302
- if (
303
- pending.phase === "checking" &&
304
- pending.accepted &&
305
- !pending.accepted.aborted &&
306
- error.message === "Compaction cancelled"
307
- ) {
308
- finish(true);
309
- return;
310
- }
311
- if (
312
- error.message === "Nothing to compact (session too small)" ||
313
- error.message === "Already compacted"
314
- ) {
315
- if (policy === "unrestricted") {
316
- // A new identity need not retire history when Pi has no summary work.
317
- finish(false);
318
- return;
319
- }
320
- this.rollover = undefined;
321
- try {
322
- if (triggerTurn)
323
- this.sendMessage(
324
- {
325
- customType: "notes-compaction:continuation",
326
- content:
327
- "Not enough history to compact. Continue here; wait for more conversation before calling new_context again.",
328
- display: true,
329
- },
330
- { triggerTurn: true },
331
- );
332
- resolve();
333
- } catch (error) {
334
- reject(error);
335
- }
336
- return;
337
- }
338
- }
339
- if (this.rollover === pending) this.rollover = undefined;
340
- reject(error);
341
- },
342
- });
343
- });
344
- }
345
- private startCheckpoint(ctx: ExtensionContext, instructions?: string): void {
346
- if (!ctx.isIdle() || !this.windows.current || this.checkpoint)
347
- throw new Error("A checkpoint cannot start until the session settles");
348
- const requestId = randomUUID();
349
- this.checkpoint = {
350
- sessionId: ctx.sessionManager.getSessionId(),
351
- windowId: this.windows.current.currentWindowId,
352
- requestId,
353
- runId: undefined,
354
- outcome: undefined,
355
- };
356
- try {
357
- this.sendMessage(
358
- {
359
- customType: "notes-compaction:checkpoint:v1",
360
- details: { requestId },
361
- content: `<context_window_reminder>\nSave the task state in notes, then finish your reply. A new window opens automatically after your reply; do not call new_context. If saving fails, report the error.\n</context_window_reminder>${instructions?.trim() ? `\n\nCheckpoint guidance:\n${instructions}` : ""}`,
362
- display: true,
363
- },
364
- { triggerTurn: true },
365
- );
366
- } catch (error) {
367
- this.checkpoint = undefined;
368
- throw error;
369
- }
220
+
221
+ prepareCustomTurn(ctx: ExtensionContext): Promise<void> | undefined {
222
+ return this.admission.prepareCustomTurn(ctx);
370
223
  }
371
- private idleDue(ctx: ExtensionContext): boolean {
372
- if (
373
- this.idleMinutes === 0 ||
374
- !ctx.isIdle() ||
375
- !this.windows.current ||
376
- this.rollover ||
377
- this.checkpoint
378
- )
379
- return false;
380
- const branch = ctx.sessionManager.getBranch();
381
- const terminal = branch.findLast(
382
- (entry) => entry.type === "message" && entry.message.role !== "system",
383
- );
384
- if (!terminal) return false;
385
- const settlement = ctx.sessionManager
386
- .getEntries()
387
- .findLast(
388
- (entry) =>
389
- entry.type === "custom" &&
390
- entry.customType === SETTLEMENT_ENTRY &&
391
- entry.data &&
392
- typeof entry.data === "object" &&
393
- "completedEntryId" in entry.data &&
394
- entry.data.completedEntryId === terminal.id,
395
- );
396
- if (
397
- settlement?.type !== "custom" ||
398
- !settlement.data ||
399
- typeof settlement.data !== "object"
400
- )
401
- return false;
402
- const data = settlement.data;
403
- return (
404
- !("aborted" in data && data.aborted === true) &&
405
- "windowId" in data &&
406
- data.windowId === this.windows.current.currentWindowId &&
407
- "settledAt" in data &&
408
- typeof data.settledAt === "number" &&
409
- Number.isFinite(data.settledAt) &&
410
- Date.now() - data.settledAt >= this.idleMinutes * 60_000
411
- );
224
+ outcome(outcome: "completed" | "aborted" | "error"): void {
225
+ this.checkpoint.outcome(outcome);
412
226
  }
413
- async input(
227
+ input(
414
228
  event: InputEvent,
415
229
  ctx: ExtensionContext,
416
230
  ): Promise<InputEventResult | undefined> {
417
- const releasing = this.held;
418
- if (
419
- releasing?.phase === "releasing" &&
420
- event.source === "extension" &&
421
- event.text === releasing.releasePrompt
422
- ) {
423
- const admit = releasing.admissions.shift();
424
- if (releasing.admissions.length) releasing.phase = "draining";
425
- else this.held = undefined;
426
- admit?.({ action: "continue" });
427
- return { action: "handled" };
428
- }
429
- if (!this.held && (!this.idleDue(ctx) || !this.fresh(ctx))) return;
430
- const held =
431
- this.held ??
432
- ({
433
- sessionId: ctx.sessionManager.getSessionId(),
434
- phase: "failed",
435
- releasePrompt: `Admit saved input: ${randomUUID()}`,
436
- admissions: [],
437
- } satisfies HeldInput);
438
- this.held = held;
439
- const admission = new Promise<InputEventResult>((resolve) =>
440
- held.admissions.push(resolve),
441
- );
442
- if (held.phase !== "failed") return admission;
443
- held.phase = "rolling";
444
- void Promise.resolve().then(async () => {
445
- try {
446
- if (
447
- this.held !== held ||
448
- held.sessionId !== ctx.sessionManager.getSessionId()
449
- )
450
- return;
451
- await this.finishHeld(ctx, held);
452
- } catch (error) {
453
- this.failHeld(ctx, held, error);
454
- }
455
- });
456
- return admission;
457
- }
458
- private failHeld(
459
- ctx: ExtensionContext,
460
- held: HeldInput,
461
- error: unknown,
462
- ): void {
463
- if (this.held !== held) return;
464
- held.phase = "failed";
465
- ctx.ui.notify(
466
- `Idle rollover failed: ${error instanceof Error ? error.message : String(error)}. Input and attachments remain pending. Submit another prompt to retry, or reload to cancel.`,
467
- "error",
468
- );
469
- }
470
- private async finishHeld(
471
- ctx: ExtensionContext,
472
- held: HeldInput,
473
- ): Promise<void> {
474
- held.phase = "rolling";
475
- await this.roll(ctx, false);
476
- if (
477
- this.held !== held ||
478
- held.sessionId !== ctx.sessionManager.getSessionId()
479
- )
480
- return;
481
- held.phase = "releasing";
482
- // Pi defers this user kickoff until EVERY agent_settled handler returns.
483
- // Its input-only admission releases the original SDK calls, preserving images/options.
484
- this.pi.sendUserMessage(held.releasePrompt);
231
+ return this.admission.input(event, ctx);
485
232
  }
486
233
  beforeCompact(
487
234
  event: SessionBeforeCompactEvent,
488
235
  ctx: ExtensionContext,
489
236
  ): { cancel: true } | undefined {
490
- if (this.rollover?.phase === "checking" && event.reason === "manual") {
491
- this.rollover.accepted = event.signal;
492
- return { cancel: true };
493
- }
494
- if (this.allowsCompaction(event.reason)) {
495
- // PCC owns preparation when bridged, including native checkpoint routes.
496
- if (this.bridge) return;
497
- try {
498
- const branch = this.windows.projectBranch(event.branchEntries);
499
- if (branch.length === event.branchEntries.length) return;
500
- const physicalCut = event.branchEntries.findIndex(
501
- (entry) => entry.id === event.preparation.firstKeptEntryId,
502
- );
503
- if (physicalCut < 0)
504
- throw new Error("Compaction kept boundary is missing");
505
- const keptIds = new Set(
506
- event.branchEntries.slice(physicalCut).map((entry) => entry.id),
507
- );
508
- const projection = buildSessionProjection(branch);
509
- const projected = projection.entries;
510
- const summary = projection.messages.find(
511
- (message) => message.role === "compactionSummary",
512
- );
513
- const cut = projected.findIndex((entry) =>
514
- keptIds.has(entry.sourceEntry.id),
515
- );
516
- if (cut < 0)
517
- throw new Error("Current context kept boundary is missing");
518
- const summarized = projected.slice(0, cut);
519
- const messages = summarized
520
- .flatMap((entry) => entry.messages)
521
- .filter(
522
- (message) =>
523
- message.role !== "system" && message.role !== "compactionSummary",
524
- );
525
- if (!messages.length) {
526
- ctx.ui.notify(
527
- "Nothing to compact in the current context window. The existing context remains.",
528
- "warning",
529
- );
530
- return { cancel: true };
531
- }
532
- // Pi retains this object for its default summarizer after every hook.
533
- // Keep that route's auth, provider hooks and retries, and physical kept IDs.
534
- delete event.preparation.previousSummary;
535
- Object.assign(event.preparation, {
536
- firstKeptEntryId: projected[cut]!.sourceEntry.id,
537
- ...(summary ? { previousSummary: summary.summary } : {}),
538
- messagesToSummarize: messages,
539
- turnPrefixMessages: [],
540
- isSplitTurn: false,
541
- fileOps: prepareBranchEntries(
542
- summarized.flatMap((entry) =>
543
- entry.messages.map((message) => ({
544
- ...entry.sourceEntry,
545
- type: "message" as const,
546
- message,
547
- })),
548
- ),
549
- ).fileOps,
550
- });
551
- } catch (error) {
552
- ctx.ui.notify(
553
- `Compaction failed: ${error instanceof Error ? error.message : String(error)}. The existing context remains.`,
554
- "error",
555
- );
556
- return { cancel: true };
557
- }
558
- return;
559
- }
560
- if (event.reason === "manual")
561
- this.cancelledCompact = {
562
- sessionId: ctx.sessionManager.getSessionId(),
563
- signal: event.signal,
564
- instructions: event.customInstructions,
565
- };
566
- return { cancel: true };
237
+ return this.requests.beforeCompact(event, ctx);
567
238
  }
568
239
  allowsCompaction(reason: SessionBeforeCompactEvent["reason"]): boolean {
569
- if (this.rollover?.phase === "checking" && reason === "manual")
570
- return false;
571
- return (
572
- !this.active ||
573
- this.normalCompaction ||
574
- this.rollover?.phase === "compacting" ||
575
- reason === "overflow"
576
- );
240
+ return this.requests.allowsCompaction(reason);
577
241
  }
578
- async compactFailed(
242
+ compactFailed(
579
243
  event: SessionCompactFailedEvent,
580
244
  ctx: ExtensionContext,
581
245
  ): Promise<void> {
582
- const pending = this.cancelledCompact;
583
- this.cancelledCompact = undefined;
584
- if (
585
- !pending ||
586
- event.reason !== "manual" ||
587
- !event.aborted ||
588
- pending.signal.aborted ||
589
- pending.sessionId !== ctx.sessionManager.getSessionId()
590
- )
591
- return;
592
- if (!pending.instructions?.trim() && this.fresh(ctx))
593
- await this.roll(ctx, false);
594
- else this.startCheckpoint(ctx, pending.instructions);
246
+ return this.requests.compactFailed(event, ctx);
595
247
  }
596
248
  async settled(
597
249
  event: AgentSettledEvent,
598
250
  ctx: ExtensionContext,
599
251
  ): Promise<void> {
600
- const checkpoint = this.checkpoint;
601
- this.checkpoint = undefined;
252
+ const checkpoint = this.checkpoint.take();
602
253
  try {
603
254
  this.store.updateFile(sessionRef(ctx));
604
255
  const terminal = ctx.sessionManager
@@ -616,7 +267,7 @@ export class NotesLifecycle {
616
267
  aborted: event.aborted,
617
268
  });
618
269
  } catch (error) {
619
- this.rollover = undefined;
270
+ this.requests.clear();
620
271
  if (
621
272
  checkpoint &&
622
273
  (event.aborted ||
@@ -627,53 +278,17 @@ export class NotesLifecycle {
627
278
  "Checkpoint cancelled. The old context remains.",
628
279
  "warning",
629
280
  );
630
- } else if (this.held) this.failHeld(ctx, this.held, error);
281
+ } else if (this.admission.pending) this.admission.fail(ctx, error);
631
282
  else throw error;
632
283
  return;
633
284
  }
634
285
  if (checkpoint) {
635
- const valid =
636
- checkpoint.sessionId === ctx.sessionManager.getSessionId() &&
637
- checkpoint.windowId === this.windows.current?.currentWindowId;
638
- const aborted =
639
- event.aborted ||
640
- checkpoint.outcome === "aborted" ||
641
- checkpoint.outcome === undefined;
642
- if (!valid || aborted) {
643
- ctx.ui.notify(
644
- "Checkpoint cancelled. The old context remains.",
645
- "warning",
646
- );
647
- return;
648
- }
649
- if (
650
- checkpoint.outcome !== "completed" ||
651
- !checkpoint.runId ||
652
- !this.fresh(ctx, checkpoint.runId)
653
- ) {
654
- ctx.ui.notify(
655
- "Rollover did not start. No fresh note was saved in the completed checkpoint. The old context remains.",
656
- "warning",
657
- );
658
- return;
659
- }
660
- await this.roll(ctx, false);
286
+ if (!this.checkpoint.permitsRollover(checkpoint, event, ctx)) return;
287
+ await this.requests.roll(ctx, false);
661
288
  return;
662
289
  }
663
- if (this.held?.phase === "draining") {
664
- // Retry admissions are original SDK calls too. Releasing all at once races Agent.prompt.
665
- this.held.phase = "releasing";
666
- this.pi.sendUserMessage(this.held.releasePrompt);
667
- return;
668
- }
669
- const rollover = this.rollover;
670
- if (
671
- rollover?.phase === "scheduled" &&
672
- rollover.sessionId === ctx.sessionManager.getSessionId() &&
673
- rollover.windowId === this.windows.current?.currentWindowId
674
- ) {
675
- this.rollover = undefined;
676
- await this.roll(ctx, rollover.triggerTurn);
677
- }
290
+ if (this.admission.drain()) return;
291
+ const rollover = this.requests.settled(ctx);
292
+ if (rollover) await rollover;
678
293
  }
679
294
  }