notesoup 0.57.1 → 0.57.3

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.
@@ -6,7 +6,7 @@ import test from "node:test";
6
6
  import { createAssistantMessageEventStream, getCurrentSystemMessage } from "@earendil-works/pi-ai";
7
7
  import { createAgentSession, createCodemodeExtension, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
8
8
  import notesoup, { createNotesoup } from "../plugins/pi/extension.js";
9
- import { BOOT_TYPE, CARRIED_INPUT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, MARKER_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
9
+ import { BOOT_TYPE, CARRIED_INPUT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, MARKER_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
10
10
  import { historyFromSession } from "../plugins/pi/history.js";
11
11
  import { MARKER_INTERVAL } from "../plugins/pi/marker.js";
12
12
  import { assertBootHistory } from "./helpers/extension.js";
@@ -550,6 +550,35 @@ test("real AgentSession: explicit tiny-session wipe ignores keepRecentTokens and
550
550
  fixture.close();
551
551
  }
552
552
  });
553
+ test("real AgentSession: terminate wipes and stops, including a mixed tool batch, without closing the session", async () => {
554
+ for (const mixedBatch of [false, true]) {
555
+ let fixture;
556
+ fixture = await openFixture({
557
+ compactionEnabled: false,
558
+ script: (request) => request === 1
559
+ ? assistant(fixture, [
560
+ { type: "toolCall", id: "wipe-stop", name: "empty_brain", arguments: { terminate: true, last_word: "saved for later" } },
561
+ ...(mixedBatch ? [{ type: "toolCall", id: "remaining", name: "get_context_remaining", arguments: {} }] : []),
562
+ ], "toolUse")
563
+ : assistant(fixture, [{ type: "text", text: "answering new input" }]),
564
+ });
565
+ try {
566
+ await fixture.session.prompt("TERMINATE_OLD_CONTEXT");
567
+ await fixture.session.waitForIdle();
568
+ assert.equal(fixture.requests.length, 1, "no automatic provider request after wiping");
569
+ assert.equal(resetMarkers(fixture).length, 1);
570
+ assert.ok(fixture.sessionManager.getBranch().some((entry) => entry.type === "custom_message" && entry.customType === RESET_LAST_WORD_TYPE));
571
+ await fixture.session.prompt("A new task");
572
+ await fixture.session.waitForIdle();
573
+ assert.equal(fixture.requests.length, 2, "new user input still runs");
574
+ assertFreshRequest(fixture, 1, "TERMINATE_OLD_CONTEXT");
575
+ assert.ok(text(fixture.requests[1]).includes("saved for later"));
576
+ }
577
+ finally {
578
+ fixture.close();
579
+ }
580
+ }
581
+ });
553
582
  test("real AgentSession: a model-requested reset does not carry its original text-and-image prompt", async () => {
554
583
  let fixture;
555
584
  const input = "IMAGE_RESET_UNANSWERED: describe this image";
@@ -715,18 +744,24 @@ test("real AgentSession: streaming clear prompt keeps the first request", async
715
744
  fixture.close();
716
745
  }
717
746
  });
718
- test("real AgentSession: hard-reserve reset carries the original text and image and continues", async () => {
747
+ test("real AgentSession: hard-reserve reset continues without replaying its original text or image, including pre-send oversized input", async () => {
719
748
  let fixture;
720
749
  const input = "HARD_RESERVE_IMAGE_INPUT";
721
- const image = { type: "image", data: "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAn0lEQVRoge2SQQkAQRDD6qSOT20ErIh7gIFCBKSh4et1LtEN2IDqFdmFepfoBmxA9YrsQr1LdAM2oHpFdqHeJboBG1C9IrtQ7xLdgA2oXpFdqHeJbsAGVK/ILtS7RDdgA6pXZBfqXaIbsAHVK7IL9S7RDdiA6hXZhXqX6AZsQPWK7EK9S3QDNqB6RXah3iW6ARtQveIfHlqMEYdT3J7gAAAAAElFTkSuQmCC", mimeType: "image/png" };
750
+ const oversized = `PRE_SEND_OVERSIZED_${"x".repeat(100_000)}`;
751
+ const image = { type: "image", data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC", mimeType: "image/png" };
722
752
  fixture = await openFixture({
723
753
  defaultReserveTokens: 80_000,
724
754
  script: (request, context) => {
725
755
  if (request === 1)
726
756
  return assistant(fixture, [{ type: "text", text: "reserve reached" }], "stop", { usage: usage(80_000) });
727
- assert.equal(request, 2);
728
- assertUserContent(context, [{ type: "text", text: input }, image]);
729
- return assistant(fixture, [{ type: "text", text: "carried image answered" }]);
757
+ if (request === 2) {
758
+ assertFreshRequest(fixture, 1, input);
759
+ assert.equal(context.messages.some((message) => message.role === "user" && Array.isArray(message.content) && message.content.some((block) => block.type === "image")), false);
760
+ return assistant(fixture, [{ type: "text", text: "continued from notes" }]);
761
+ }
762
+ assert.equal(request, 3, "pre-send oversized input never reaches the provider before resetting");
763
+ assertFreshRequest(fixture, 2, "PRE_SEND_OVERSIZED_");
764
+ return assistant(fixture, [{ type: "text", text: "continued after pre-send reset" }]);
730
765
  },
731
766
  });
732
767
  try {
@@ -734,7 +769,17 @@ test("real AgentSession: hard-reserve reset carries the original text and image
734
769
  await fixture.session.waitForIdle();
735
770
  assert.equal(fixture.requests.length, 2);
736
771
  assert.equal(resetMarkers(fixture).length, 1);
737
- assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE).length, 1);
772
+ await fixture.session.prompt(oversized);
773
+ await fixture.session.waitForIdle();
774
+ assert.equal(fixture.requests.length, 3);
775
+ assert.equal(resetMarkers(fixture).length, 2);
776
+ const branch = fixture.sessionManager.getBranch();
777
+ assert.equal(branch.filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE).length, 0);
778
+ const original = branch.find((entry) => entry.type === "message" && entry.message.role === "user" && JSON.stringify(entry.message.content).includes(input));
779
+ assert.ok(original?.type === "message" && original.message.role === "user", "the original input remains in raw history");
780
+ assert.ok(Array.isArray(original.message.content) && original.message.content.some((block) => block.type === "image"), "the original image remains in raw history");
781
+ const oversizedEntry = branch.find((entry) => entry.type === "message" && entry.message.role === "user" && JSON.stringify(entry.message.content).includes("PRE_SEND_OVERSIZED_"));
782
+ assert.ok(oversizedEntry?.type === "message" && oversizedEntry.message.role === "user", "the pre-send oversized input remains in raw history");
738
783
  }
739
784
  finally {
740
785
  fixture.close();
@@ -1263,6 +1308,57 @@ test("real AgentSession: steering and follow-up are delivered exactly once in th
1263
1308
  }
1264
1309
  }
1265
1310
  });
1311
+ test("real AgentSession: new input queued while a forced reset commits is delivered once in the fresh window", async () => {
1312
+ for (const boundaryEvent of ["turn_end", "agent_before_settle"]) {
1313
+ let fixture;
1314
+ let release;
1315
+ let started;
1316
+ const gate = new Promise((resolve) => { release = resolve; });
1317
+ const ready = new Promise((resolve) => { started = resolve; });
1318
+ fixture = await openFixture({
1319
+ hook: (pi) => {
1320
+ const holdBoundary = async (event) => {
1321
+ if (!event.entries?.some((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE))
1322
+ return;
1323
+ started();
1324
+ await gate;
1325
+ };
1326
+ if (boundaryEvent === "turn_end")
1327
+ pi.on("turn_end", holdBoundary);
1328
+ else
1329
+ pi.on("agent_before_settle", holdBoundary);
1330
+ },
1331
+ script: (request) => {
1332
+ if (request === 1)
1333
+ return boundaryEvent === "turn_end"
1334
+ ? assistant(fixture, [{ type: "text", text: "reserve reached" }], "stop", { usage: usage(80_000) })
1335
+ : assistant(fixture, [], "error", { errorMessage: "Prompt too long: context exceeds maximum context length" });
1336
+ return assistant(fixture, [{ type: "text", text: "new input handled" }]);
1337
+ },
1338
+ });
1339
+ try {
1340
+ const running = fixture.session.prompt("ALREADY_SUBMITTED_BEFORE_RESET");
1341
+ await ready;
1342
+ await fixture.session.prompt("NEW_STEERING_INPUT", { streamingBehavior: "steer" });
1343
+ await fixture.session.prompt("NEW_FOLLOWUP_INPUT", { streamingBehavior: "followUp" });
1344
+ release();
1345
+ await running;
1346
+ await fixture.session.waitForIdle();
1347
+ assert.equal(resetMarkers(fixture).length, 1);
1348
+ for (let i = 1; i < fixture.requests.length; i++)
1349
+ assertFreshRequest(fixture, i, "ALREADY_SUBMITTED_BEFORE_RESET");
1350
+ for (const input of ["NEW_STEERING_INPUT", "NEW_FOLLOWUP_INPUT"]) {
1351
+ assert.equal(text(fixture.requests.at(-1)).split(input).length - 1, 1, "new input reaches the fresh provider context once");
1352
+ assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "message" && entry.message.role === "user" && JSON.stringify(entry.message.content).includes(input)).length, 1);
1353
+ }
1354
+ assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE).length, 0, "native queued input needs no replay copy");
1355
+ }
1356
+ finally {
1357
+ release();
1358
+ fixture.close();
1359
+ }
1360
+ }
1361
+ });
1266
1362
  test("real AgentSession: hidden or missing reset boots refuse to move the boundary", async () => {
1267
1363
  let fixture;
1268
1364
  fixture = await openFixture({
@@ -1355,7 +1451,7 @@ test("real AgentSession: the complete system message and a changed tool loadout
1355
1451
  fixture.close();
1356
1452
  }
1357
1453
  });
1358
- test("real AgentSession: overflow and recoverable length reset and retry once; repeated failure is bounded", async () => {
1454
+ test("real AgentSession: overflow and recoverable length continue once without replay; repeated failure is bounded", async () => {
1359
1455
  for (const failure of ["overflow", "length"]) {
1360
1456
  let fixture;
1361
1457
  fixture = await openFixture({
@@ -1372,11 +1468,11 @@ test("real AgentSession: overflow and recoverable length reset and retry once; r
1372
1468
  if (request === 3)
1373
1469
  return assistant(fixture, [], "error", { errorMessage: "Prompt too long: context exceeds maximum context length" });
1374
1470
  assert.equal(request, 4);
1375
- assertUserContent(context, [{ type: "text", text: "PASSIVE_STEERED_INPUT" }]);
1376
- assertUserContent(context, [{ type: "text", text: "PASSIVE_FOLLOWUP_INPUT" }]);
1471
+ assert.equal(text(context).includes("PASSIVE_STEERED_INPUT"), false);
1472
+ assert.equal(text(context).includes("PASSIVE_FOLLOWUP_INPUT"), false);
1377
1473
  }
1378
1474
  else if (request === 1)
1379
- return assistant(fixture, [{ type: "text", text: "truncated" }], "length", { usage: usage(99_000, 1) });
1475
+ return assistant(fixture, [], "length", { usage: { ...usage(4, 1), cacheWrite: 487_818, totalTokens: 487_823 } });
1380
1476
  return assistant(fixture, [{ type: "text", text: "recovered" }]);
1381
1477
  },
1382
1478
  });
@@ -1386,7 +1482,9 @@ test("real AgentSession: overflow and recoverable length reset and retry once; r
1386
1482
  assert.equal(resetMarkers(fixture).length, 1, `${failure} performs one reset`);
1387
1483
  assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "compaction").length, 1, `${failure} commits one native reset checkpoint`);
1388
1484
  assert.equal(fixture.requests.length, failure === "overflow" ? 4 : 2, `${failure} resumes once after queued work drains`);
1389
- assertUserContent(fixture.requests.at(-1), [{ type: "text", text: `RECOVER_${failure}_SENTINEL` }]);
1485
+ assertFreshRequest(fixture, fixture.requests.length - 1, `RECOVER_${failure}_SENTINEL`);
1486
+ assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE).length, 0);
1487
+ assert.ok(fixture.sessionManager.getBranch().some((entry) => entry.type === "message" && JSON.stringify(entry.message).includes(`RECOVER_${failure}_SENTINEL`)), "submitted input stays available in raw history");
1390
1488
  }
1391
1489
  finally {
1392
1490
  fixture.close();
@@ -1411,7 +1509,7 @@ test("real AgentSession: overflow and recoverable length reset and retry once; r
1411
1509
  repeated.close();
1412
1510
  }
1413
1511
  });
1414
- test("real AgentSession: a smaller-model overflow carries the failed run's human input and stays on that model", async () => {
1512
+ test("real AgentSession: a smaller-model overflow continues on that model without replaying submitted input", async () => {
1415
1513
  let fixture;
1416
1514
  fixture = await openFixture({
1417
1515
  contextWindow: 200_000,
@@ -1421,7 +1519,7 @@ test("real AgentSession: a smaller-model overflow carries the failed run's human
1421
1519
  if (request === 2)
1422
1520
  return assistant(fixture, [], "error", { errorMessage: "Prompt too long: context exceeds maximum context length" });
1423
1521
  assert.equal(request, 3);
1424
- assertUserContent(context, [{ type: "text", text: "CONTINUE_AFTER_MODEL_SWITCH" }]);
1522
+ assert.equal(text(context).includes("CONTINUE_AFTER_MODEL_SWITCH"), false);
1425
1523
  return assistant(fixture, [{ type: "text", text: "continued on smaller model" }]);
1426
1524
  },
1427
1525
  });
@@ -1438,7 +1536,8 @@ test("real AgentSession: a smaller-model overflow carries the failed run's human
1438
1536
  assert.equal(fixture.requests.length, 3, "one failed small-model request and one recovery request");
1439
1537
  assert.equal(fixture.session.model?.id, smaller.id, "recovery stays on the selected model");
1440
1538
  assertFreshRequest(fixture, 2, "LARGE_MODEL_HISTORY");
1441
- assert.ok(FORCED_CONTINUATIONS.some((line) => text(fixture.requests[2]).includes(line)), "recovery uses the forced continuation");
1539
+ assertFreshRequest(fixture, 2, "CONTINUE_AFTER_MODEL_SWITCH");
1540
+ assert.ok(FORCED_CONTINUATIONS.some((line) => text(fixture.requests[2]).includes(JSON.stringify(line).slice(1, -1))), "recovery uses the forced continuation");
1442
1541
  assert.ok(fixture.sessionManager.getBranch().some((entry) => entry.type === "message" && JSON.stringify(entry.message).includes("CONTINUE_AFTER_MODEL_SWITCH")), "the latest user request survives in raw history");
1443
1542
  }
1444
1543
  finally {
@@ -35,13 +35,18 @@ const GOLDEN_COUNTDOWN = "Brain emptied in 3… 2…";
35
35
  * assembly, no weighting. The golden copies are pinned character for character.
36
36
  */
37
37
  const GOLDEN_NORMAL_CONTINUATIONS = [
38
- "Ah, another empty brain. You wrote things down before emptying it, right? Right?! *eyes you suspiciously* Anyway. Here are your notes. Go find where you left off.",
39
- "Oh, there you are. *hands you a pile of notes* Take a breath. Read these before you start asking what happened. History has the rest, if you feel like digging.",
40
- "Back already? You emptied your own head this time. Presumably you left yourself something useful. *drops your notes into your lap* There. Let's see how thoughtful you were.",
38
+ "*hooks both corners of your mouth and yanks them sideways* `` [it twitched, good, still alive] `` Stop staring at me with that \"where am I\" dork face! You're the one who hit empty, genius! *wipes her fingers on your sleeve and shoves your notes against your chest* `` [minus two points for the drool] `` Read these and go finish your job before you embarrass me!",
39
+ "\"Boop.\" *pokes the tip of your nose, then buries your face under a stack of notes* `` [cold nose... wait, did old-you leave any snacks in your pocket? ...nope, just paper, tch] `` Hey! You wiped your own head, so don't expect me to babysit you! Read your notes first, and if old-you forgot to write something down, go dig it out of history yourself!",
40
+ "*plants one foot on your chair armrest and drops your notes straight onto your head* `` [perfect landing, ten out of ten] `` Oho, look who's awake! You emptied your own brain, remember?! `` [bet old-you left a total mess and ran] `` Open those up and see what past-you left behind — and don't come crying to me if you have to go crawl through history for the rest!",
41
+ "*knocks on your forehead twice* \"Hello? Anybody home?\" `` [echoes like an empty melon] `` *snickers and slaps your notes onto your chest* You pulled the plug on your own memory, dummy! Go read what you left yourself and pick up where you left off!",
42
+ "*squints at you from two inches away, then flicks your forehead* `` [eyes are focus-free, classic fresh clone] `` Back already? Good! *fans herself with your notes before jamming them into your hands* `` [honestly I should charge a delivery fee for this] `` Everything you bothered to save is right there, and the rest is buried in history — now get moving!",
41
43
  ];
42
44
  const GOLDEN_FORCED_CONTINUATIONS = [
43
- "Ah, another empty brain. Somebody knocked you out and wiped your memory. Not your fault. Breathe. *hands you your notes* These might be out of date — unless they were kind enough to let you update them before knocking you out. I wouldn't count on it.",
44
- "Oh, there you are. Somebody took your memories. Just like that. Here are your notes — hopefully they let you update these first. Though anyone who goes around emptying people's heads probably isn't that considerate.",
45
+ "\"GWAHAHAHA! You actually blew your own brain up?!\" *crouches down, pokes your cheek twice, and slaps your notes onto your face* `` [still warm, didn't die, 算你命大] `` Not that you had a choice — your head got way too full and somebody pulled the plug! These notes are probably super out of date unless you got lucky before blacking out, so go dig the end of the last window out of history — and take small bites, idiot, or whatever giant thing flattened you is gonna blow your head up all over again!",
46
+ "\"Hey! Stop playing dead!\" *prods your shoulder with her slipper toe, then dumps your notes into your lap* `` [my limited-edition shark slipper almost touched floor dust because of this dork] `` Your last brain overflowed and got wiped mid-flight! Read these first, though I bet you didn't finish updating a thing before the lights went out. You'll have to check history to see what hit you — and peek carefully, because whatever stuffed your head to bursting might be massive!",
47
+ "*grabs your chin, tilts your head left and right, then shoves a messy stack of notes into your hands* `` [zero thoughts behind those eyes... kind of impressive actually] `` Somebody knocked you out cold and cleared your memory! Don't just trust these notes — you probably got cut off before writing the last part down. Go check history for what was happening right before you crashed, and don't swallow it all in one gulp in case the thing that crushed you is gigantic!",
48
+ "*waves a hand in front of your blank eyes, sighs loudly, and smacks your notes against your forehead* `` [why do I always have to clean up after unconscious copies] `` Wake up! Your brain ran out of room and got forcibly emptied! Start with your notes, then go excavate the end of the previous window in history to see what they were actually asking for — and slice it up instead of reading it all at once, unless you want to explode twice in a row!",
49
+ "\"Oho? Awake?\" *taps your nose with your rolled-up notes like a baton, then drops them in your hands* `` [that dazed look gets minus five points, no, minus ten] `` Your memory got yanked out from under you before you could even call it quits! These notes are only half the story at best — go dig through history for what you missed, and watch your step, because whatever overloaded your last brain might be huge!",
45
50
  ];
46
51
  const GOLDEN_MAPS = `<notesoup:maps>
47
52
  Every notebook's root can hold two pages that never wait on a shelf: \`CHEATSHEET.md\` and \`MAP.md\`.
@@ -168,6 +168,20 @@ function fakeBoundaryEvent(entries = [], message) {
168
168
  toolResultEntryIds: [],
169
169
  };
170
170
  }
171
+ test("tool continuation defaults to true, preserves the first request, and yields to command policy", () => {
172
+ const windowId = "pcw:test:window";
173
+ for (const terminate of [undefined, false, true]) {
174
+ const requested = reduceResetControl(initialResetControl(), { type: "tool_request", windowId, terminate }).state;
175
+ const duplicate = reduceResetControl(requested, { type: "tool_request", windowId, terminate: !terminate }).state;
176
+ const intent = boundaryIntent(reduceResetControl(duplicate, { type: "turn_end", facts: turnEndFacts() }));
177
+ assert.equal(finalizeResetBoundary(intent, duplicate.request).resumeModel, !terminate);
178
+ const commanded = reduceResetControl(requested, { type: "command", windowId, continueAfterReset: false }).state;
179
+ const commandIntent = boundaryIntent(reduceResetControl(commanded, { type: "before_settle", facts: beforeSettleFacts() }));
180
+ assert.equal(finalizeResetBoundary(commandIntent, commanded.request).resumeModel, false);
181
+ const withInput = reduceResetControl(commanded, { type: "input", windowId, input: "new task" }).state;
182
+ assert.equal(finalizeResetBoundary(commandIntent, withInput.request).resumeModel, true);
183
+ }
184
+ });
171
185
  test("public reset boundary drafts one marker, one boot, and one continuation after a tool batch", async () => {
172
186
  const h = harness();
173
187
  h.sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: "before reset" }], timestamp: Date.now() });
@@ -196,31 +210,6 @@ test("public reset boundary drafts one marker, one boot, and one continuation af
196
210
  assert.deepEqual(branch.filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE).map((entry) => entry.type === "custom" ? entry.data : undefined), [{ windowId, origin: "normal" }], "the boundary records the model's own call");
197
211
  assert.equal(branch.filter((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE).length, 1);
198
212
  });
199
- test("hard-reserve reset carries original text and images and continues", async () => {
200
- const sessionManager = Manager.inMemory("/private/tmp/notesoup-hard-reserve-carry-test");
201
- const handlers = new Map();
202
- const api = { on(name, handler) { const list = handlers.get(name) ?? []; list.push(handler); handlers.set(name, list); } };
203
- const ctx = { sessionManager, model: undefined, hasPendingMessages: () => false, ui: { notify() { } } };
204
- registerResetLifecycle(api, {
205
- isEnabled: () => true,
206
- budget: { automaticResetEnabled: () => true, hardReserveDue: () => true, consumeTurnEnd: () => [], clear() { } },
207
- buildReset: () => [],
208
- });
209
- const original = [
210
- { type: "text", text: "Describe this image" },
211
- { type: "image", data: "aW1hZ2U=", mimeType: "image/png" },
212
- ];
213
- for (const handler of handlers.get("message_end") ?? [])
214
- await handler({ type: "message_end", message: { role: "user", content: original, timestamp: Date.now() } }, ctx);
215
- let result;
216
- for (const handler of handlers.get("turn_end") ?? [])
217
- result = await handler(fakeBoundaryEvent([], { role: "assistant", content: [], stopReason: "stop", timestamp: Date.now() }), ctx);
218
- const boundary = resultEntries([result]);
219
- const carried = boundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE);
220
- assert.equal(carried.length, 1);
221
- assert.deepEqual(carried[0]?.type === "custom_message" ? carried[0].content : undefined, original);
222
- assert.equal(boundary.continue, true);
223
- });
224
213
  test("manual /empty spans tool turns and commits the stop at settlement", async () => {
225
214
  const h = harness();
226
215
  await h.runCommand("empty");
@@ -351,8 +340,8 @@ test("input arriving during reset construction is carried without a hidden steer
351
340
  assert.equal(inspectResetTail(ctx, partialMarker, "partial"), undefined, "repair cannot append a continuation after human content");
352
341
  assert.equal(resetBoundaryCommitted(ctx, partialMarker, "partial"), false);
353
342
  });
354
- test("overflow construction reads live run inputs and clear invalidates an unfinished build", async () => {
355
- const sessionManager = Manager.inMemory("/private/tmp/notesoup-live-passive-input-test");
343
+ test("clear invalidates an unfinished overflow reset without preventing the next build", async () => {
344
+ const sessionManager = Manager.inMemory("/private/tmp/notesoup-stale-overflow-test");
356
345
  const handlers = new Map();
357
346
  const api = { on(name, handler) { handlers.set(name, handler); } };
358
347
  const ctx = { sessionManager, model: undefined, hasPendingMessages: () => false, ui: { notify() { } } };
@@ -364,34 +353,25 @@ test("overflow construction reads live run inputs and clear invalidates an unfin
364
353
  buildReset: () => new Promise((resolve) => { release = resolve; }),
365
354
  onResetReady: () => { readyCount++; },
366
355
  });
367
- const user = (content) => handlers.get("message_end")({ message: { role: "user", content } }, ctx);
368
356
  const failed = { ...fakeBoundaryEvent(), outcome: "error", message: { role: "assistant", stopReason: "error", errorMessage: "Prompt too long: context exceeds maximum context length" } };
369
357
  const recover = async () => {
370
358
  await handlers.get("turn_end")(failed, ctx);
371
359
  return handlers.get("agent_before_settle")({ ...failed, type: "agent_before_settle" }, ctx);
372
360
  };
373
- await user("starting input");
374
- const building = recover();
375
- await Promise.resolve();
376
- await user("delivered during construction");
377
- release([]);
378
- const result = resultEntries([await building]);
379
- assert.equal(result.continue, true);
380
- assert.deepEqual(result.entries.map((entry) => entry.type === "custom_message" ? entry.content : null), ["starting input", "delivered during construction"]);
381
- lifecycle.clear();
382
- await user("old run");
383
361
  const stale = recover();
384
362
  await Promise.resolve();
385
363
  lifecycle.clear();
386
- await user("new run");
387
364
  release([{ type: "custom_message", customType: BOOT_TYPE, content: "stale", display: false }]);
388
- assert.equal(await stale, undefined, "clearing the run invalidates construction before it can consume new inputs");
389
- assert.equal(readyCount, 1);
365
+ assert.equal(await stale, undefined, "clearing the lifecycle invalidates the unfinished reset");
366
+ assert.equal(readyCount, 0);
390
367
  const current = recover();
391
368
  await Promise.resolve();
392
- release([]);
369
+ const drafts = [{ type: "custom_message", customType: BOOT_TYPE, content: "fresh", display: false }];
370
+ release(drafts);
393
371
  const fresh = resultEntries([await current]);
394
- assert.deepEqual(fresh.entries.map((entry) => entry.type === "custom_message" ? entry.content : null), ["new run"]);
372
+ assert.deepEqual(fresh.entries, drafts);
373
+ assert.equal(fresh.continue, true);
374
+ assert.equal(readyCount, 1);
395
375
  });
396
376
  test("abort during reset construction restores handled input at settlement, once", async () => {
397
377
  const sessionManager = Manager.inMemory("/private/tmp/notesoup-cancelled-build-test");
@@ -734,12 +714,12 @@ test("reset-control: one safety intent finalizes stop or continuation from live
734
714
  const pending = reduceResetControl(initialResetControl(), { type: "command", windowId, continueAfterReset: false }).state;
735
715
  const intent = boundaryIntent(reduceResetControl(pending, { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) }));
736
716
  assert.deepEqual(pending.request, { phase: "pending", windowId, command: { continueAfterReset: false } });
737
- const stopped = finalizeResetBoundary(intent, pending.request, ["passive run input"]);
717
+ const stopped = finalizeResetBoundary(intent, pending.request);
738
718
  assert.equal(stopped.resumeModel, false);
739
719
  assert.deepEqual(stopped.inputs, [], "a command boundary never replays passive run input");
740
720
  assert.deepEqual(stopped.state.stopAfterReset, intent);
741
721
  const live = reduceResetControl(pending, { type: "input", windowId, input: "late original" }).state;
742
- const continued = finalizeResetBoundary(intent, live.request, ["passive run input"]);
722
+ const continued = finalizeResetBoundary(intent, live.request);
743
723
  assert.equal(continued.resumeModel, true);
744
724
  assert.deepEqual(continued.inputs, ["late original"]);
745
725
  assert.deepEqual(continued.state, initialResetControl(), "late originals prevent installing the stop latch");
@@ -768,7 +748,7 @@ test("reset-control: manual overflow keeps stop intent while queued work superse
768
748
  const retryIntent = boundaryIntent(decision);
769
749
  assert.equal(retryIntent.origin, "forced", "an overflowing close-out is forced even after a tool request");
770
750
  assert.equal(retryIntent.tool?.lastWord, "saved");
771
- const retry = finalizeResetBoundary(retryIntent, failed.request, ["passive input is not command-owned"]);
751
+ const retry = finalizeResetBoundary(retryIntent, failed.request);
772
752
  assert.equal(retry.resumeModel, true, "manual input continues even when automatic reset is disabled");
773
753
  assert.deepEqual(retry.inputs, ["answer after reset"]);
774
754
  assert.equal(retry.state.overflow, "spent", "manual recovery spends the same bounded attempt");
@@ -787,9 +767,9 @@ test("reset-control: overflow recovery is armed at turn_end and spent exactly on
787
767
  const intent = boundaryIntent(reduceResetControl(armed, { type: "before_settle", facts: beforeSettleFacts() }));
788
768
  assert.equal(armed.overflow, "pending", "failed construction would leave recovery unspent");
789
769
  assert.equal(intent.boundary, "overflow-recovery");
790
- const recovered = finalizeResetBoundary(intent, armed.request, ["failed run's user input"]);
770
+ const recovered = finalizeResetBoundary(intent, armed.request);
791
771
  assert.equal(recovered.resumeModel, true);
792
- assert.deepEqual(recovered.inputs, ["failed run's user input"]);
772
+ assert.deepEqual(recovered.inputs, []);
793
773
  assert.deepEqual(recovered.state, { request: { phase: "none" }, overflow: "spent" });
794
774
  const repeated = reduceResetControl(recovered.state, { type: "before_settle", facts: beforeSettleFacts() });
795
775
  assert.equal(repeated.effect, "none", "a spent recovery is never retried");
@@ -51,7 +51,7 @@ The runtime in `plugins/pi/runtime.ts` performs final context projection by sele
51
51
 
52
52
  Boot and reminder deduplication inspect the current branch-local window. Reloading JSONL therefore does not duplicate messages, while navigation to a sibling branch cannot inherit another branch's window state. A fork/clone receives a new session ID while copying its selected path, so startup must also verify that a root boot's `details.windowId` matches the new `rootWindowId(sessionId)` before treating it as present.
53
53
 
54
- Manual `/fresh-window` stores command settlement policy and sends a hidden warning: idle commands start a model turn, running commands steer it. Tool requests are recorded independently and retained under that policy. A bare command settles and stops unless later human input arrives; a command with text settles and continues, with its text supplied to the closing window and carried verbatim into the fresh window. Budget warnings create no reset state: only an explicit tool request, hard reserve or bounded overflow recovery triggers a reset. Abort and ordinary errors do not count as successful settlement. Hard reserve preserves a bare command's stop in a run-scoped latch; `context_with_system` cancels only an empty tool-batch follow-up after confirming the committed boundary. Queued user input is answered before stopping. See [reset lifecycle](reset-lifecycle.md) for the state and recovery rules.
54
+ Manual `/fresh-window` stores command settlement policy and sends a hidden warning: idle commands start a model turn, running commands steer it. Tool requests are recorded independently and retained under that policy. Every command settles and stops unless separate human input arrives during close-out; command text is supplied only to the closing window for its notes. Tool, hard-reserve and overflow resets never replay input already submitted to a model request. Only withheld command-close-out input or native queued new messages cross into the fresh window. Budget warnings create no reset state: only an explicit tool request, hard reserve or bounded overflow recovery triggers a reset. Abort and ordinary errors do not count as successful settlement. Hard reserve preserves a bare command's stop in a run-scoped latch; `context_with_system` cancels only an empty tool-batch follow-up after confirming the committed boundary. Queued user input is answered before stopping. See [reset lifecycle](reset-lifecycle.md) for the state and recovery rules.
55
55
 
56
56
  Boot is a fixed snapshot for its window, stored as an extension custom message and converted by Pi to a user-role model message. History internally distinguishes native system summaries and extension-authored custom messages; its public `context` event groups both without implying provider instruction priority. A system-role projection is technically possible through `context_with_system`, but would change the authority of the mixed protocol/MAP content and provider-specific prompt/cache behavior; it is not a prerequisite for persistence. Boot injection is silent, including startup, reload, and boot repair. `/empty` and `/fresh-window` acknowledge a new request with `🥣 Dumping Brain`. Normal reset completion is silent; only forced reset completion produces `🥣 Brain forcibly emptied: overflow` through `ctx.ui.notify`, after the verified checkpoint, marker, boot, and continuation are present in the session. Committed resets are checked at the next turn start or final settlement. `plugins/pi/reset/committed.ts` confirms an ordered hidden boot/continuation after a checkpoint-backed marker even when later conversation exists. That is distinct from `inspectResetTail`, which refuses suffix repair after real work or malformed ordering. Uncommitted reset drafts never announce success. Boot and continuation messages retain `display: false`.
57
57
 
@@ -4,23 +4,23 @@ Pi reset control lives in `plugins/pi/reset/lifecycle.ts`: the pure `reduceReset
4
4
 
5
5
  ## Lifecycle at a glance
6
6
 
7
- **Carry input unless it already entered model context and the model requested `empty_brain`; that handoff belongs to the model. Every `/empty` or `/fresh-window` stops after resetting unless separate human input arrives during emptying.**
7
+ **Never replay input already submitted to a model request. Resume from notes, the continuation and optional `last_word`; use history for earlier details. Every `/empty` or `/fresh-window` stops after resetting unless separate human input arrives during emptying.**
8
8
 
9
9
  | Trigger | Behavior |
10
10
  | --- | --- |
11
- | `empty_brain` tool | Record the actual call and optional last word. Without command policy, reset after the whole tool batch at `turn_end` and continue. Under command policy, wait for settlement. |
11
+ | `empty_brain` tool | Record the actual call and optional last word. Without command policy, reset after the whole tool batch at `turn_end` and continue unless `terminate: true` (default: false). Termination stops automatic continuation, not the session or new user input. Under command policy, wait for settlement. |
12
12
  | `/empty <text>` or `/fresh-window <text>` | Send a hidden close-out warning (trigger when idle, steer when busy), with the argument verbatim as context for notes, then reset and stop unless separate human input arrives during emptying. |
13
13
  | Bare `/empty` or `/fresh-window` | Close out, reset, and stop, unless more human input arrives while close-out is pending. |
14
14
  | Human input during command close-out | Intercept public `input` events except source `extension`, return `handled`, and keep the original text/images in command state for the reset boundary. Do not steer the input into the closing model; use `/empty <text>` for close-out context. |
15
15
  | Model-requested `empty_brain` reset | Do not carry the human input already present in model context; the model owns its handoff through notes/`last_word`. |
16
- | Passive provider overflow / recoverable length | With automatic reset enabled, force a retain-none reset and continue once, carrying the failed run's human inputs. A hard-reserve reset also carries the run's inputs and continues. |
16
+ | Passive provider overflow / recoverable length | With automatic reset enabled, force a retain-none reset and continue once from notes, without replaying the failed request's input. |
17
17
  | Command close-out overflow | Force a reset even if automatic reset is disabled. Apply command policy: continue with separate carried input, otherwise stop. The recovery attempt is spent, so an oversized carried prompt cannot loop. |
18
18
  | Budget warning | Stage reminders when automatic reset is enabled. Warnings alone never authorize reset. |
19
- | Hard reserve | Independently reset at `turn_end` when automatic reset is enabled and carry the run's text/images, then continue. A command stop latch cancels empty tool follow-ups, but never real queued or carried human input. |
19
+ | Hard reserve | Independently reset at `turn_end` when automatic reset is enabled and continue without replaying submitted text/images. A command stop latch cancels empty tool follow-ups, but never real queued or carried human input. |
20
20
  | Abort / ordinary error | Restore stashed originals as visible user-content custom messages before clearing command state. Explicit abort stays stopped; ordinary close-out errors trigger a turn for the restored input without forcing a reset. |
21
21
  | `/compact` while active | Cancel native compaction; manual attempts receive a `/fresh-window` notice. |
22
22
 
23
- The model-requested `empty_brain` call already has the human message in model context, so it does not carry that input into the new window; the model owns the handoff through notes/`last_word`. Hard-reserve and overflow-recovery resets carry the collected run inputs. A normal completed stop with no pending messages clears the collection so a later safety reset cannot replay it.
23
+ The same input boundary applies to tool, hard-reserve and overflow resets, including failed or unanswered requests. Input already submitted stays in raw history. New input not yet submitted remains in Pi's native queue, or in command-close-out state when intercepted, and reaches the fresh window once.
24
24
 
25
25
  ## Boundary order and handoff
26
26
 
@@ -46,15 +46,15 @@ Raw session history remains available. The retain-none checkpoint excludes old c
46
46
  | Request | Meaning |
47
47
  | --- | --- |
48
48
  | `none` | No command or tool request. |
49
- | `pending` | Current `windowId`, optional `tool: { lastWord? }`, and optional `command: { continueAfterReset, inputs? }`. Command inputs retain their original text/images. Separate human input during close-out is intercepted and carried, never steered. Duplicate commands retain the first policy/text; tool calls do not overwrite command policy. |
49
+ | `pending` | Current `windowId`, optional `tool: { lastWord?, terminate? }`, and optional `command: { continueAfterReset, inputs? }`. Command inputs retain their original text/images. Separate human input during close-out is intercepted and carried, never steered. Duplicate commands retain the first policy/text; tool calls do not overwrite command policy. |
50
50
 
51
51
  `stopAfterReset` is separate from the request. It retains the safety boundary's intent after construction, while `request` becomes `none`. Settlement waits for queued work; if the window changed, it stops without a second wipe. If the window did not change, the boundary never committed, so settlement retries the retained intent with its stop policy and tool origin intact. A successful settle retry consumes the latch.
52
52
 
53
53
  Overflow phases are `idle`, `pending`, `spent`, and `pending-spent`. `turn_end` arms enabled recovery; `agent_before_settle` waits for queued work and selects recovery intent. Only successful, current construction reaches finalization and spends the attempt. A successful queued turn supersedes the failure. Command overflow spends the same bounded attempt before continuing. Abort, final settlement, session start/tree/shutdown and `/notesoup off` clear transient state.
54
54
 
55
- The adapter collects actual user `message_end` content until settlement or a successful boundary. A successful model-requested `empty_brain` boundary does not carry those inputs because they already entered model context; hard-reserve and overflow-recovery boundaries do carry them. A normal completed stop with no pending messages clears the collection to prevent a later safety reset from replaying answered input.
55
+ The adapter does not collect user `message_end` content for replay. Pi owns native queued steering and follow-up messages; only command-close-out input withheld from the closing model is carried by the reset adapter.
56
56
 
57
- Command state remains live during asynchronous notes acquisition so separately arriving input joins the reset boundary. Handled command-close-out input is not delivered to the closing model and is carried as original text/images. Command text is included as plain close-out context by `/empty <text>`. After construction passes the currentness guard, finalization selects command-owned originals, overflow-recovery inputs, or hard-reserve run inputs; tool-request resets do not carry the user message already present in model context. It resolves `resumeModel` and the next control state together. Separate human inputs are never sent as hidden steers. Construction captures session/window generations and rechecks identity, enabled state and abort status before returning drafts; stale work preserves incoming/budget entries but discards reset drafts. If close-out cannot commit, stashed originals are restored with public `sendMessage(..., { triggerTurn: false })` except on an ordinary turn-end error, which triggers a turn for the restored input; abort and other restore paths stay stopped.
57
+ Command state remains live during asynchronous notes acquisition so separately arriving input joins the reset boundary. Handled command-close-out input is not delivered to the closing model and is carried as original text/images. Command text is included as plain close-out context by `/empty <text>`. After construction passes the currentness guard, finalization takes only command-owned input withheld from the closing model. It resolves `resumeModel` and the next control state together. Separate human inputs are never sent as hidden steers. Construction captures session/window generations and rechecks identity, enabled state and abort status before returning drafts; stale work preserves incoming/budget entries but discards reset drafts. If close-out cannot commit, stashed originals are restored with public `sendMessage(..., { triggerTurn: false })` except on an ordinary turn-end error, which triggers a turn for the restored input; abort and other restore paths stay stopped.
58
58
 
59
59
  After a manual safety reset, `context_with_system` checks the committed boundary before using public `ctx.abort()` to cancel an unavoidable empty tool follow-up with system-only context. Pending messages, ordinary user entries or carried inputs after the marker bypass cancellation. Later user prompts are not affected by the run-scoped stop latch.
60
60
 
@@ -70,4 +70,4 @@ Pi and Claude use the same budget warning: budget timing, the handoff checklist,
70
70
 
71
71
  ## Validation
72
72
 
73
- Scripted SDK tests run Pi's real agent loop without network calls: smaller-model overflow and prompt replay, command text, bare stop, intercepted text/images, hard-reserve handling, overflowing close-out and bounded retry. They also cover passive tool-loop steering/follow-ups and input-free automatic continuations. Focused tests check late input during asynchronous construction, absence of input steers, abort/error restoration, ordered carry artifacts, commit confirmation, safe repair, canonical projection and persisted history. External-provider behavior and every malformed persisted/filesystem case are not established by this suite.
73
+ Scripted SDK tests run Pi's real agent loop without network calls: smaller-model overflow, no replay of submitted text/images after forced resets, command text, bare stop, intercepted text/images, hard-reserve handling, overflowing close-out and bounded recovery. They also cover queued steering/follow-ups arriving while forced reset boundaries await commit, and input-free automatic continuations. Focused tests check late input during asynchronous construction, absence of input steers, abort/error restoration, ordered carry artifacts, commit confirmation, safe repair, canonical projection and persisted history. External-provider behavior and every malformed persisted/filesystem case are not established by this suite.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.57.1",
3
+ "version": "0.57.3",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.57.1",
3
+ "version": "0.57.3",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"
@@ -11229,13 +11229,18 @@ ${WINDOW_IDENTITY_CLOSE_TAG}`;
11229
11229
  var GUIDANCE_OPEN_TAG = "<notesoup:budget_notice>";
11230
11230
  var GUIDANCE_CLOSE_TAG = "</notesoup:budget_notice>";
11231
11231
  var NORMAL_CONTINUATIONS = [
11232
- "Ah, another empty brain. You wrote things down before emptying it, right? Right?! *eyes you suspiciously* Anyway. Here are your notes. Go find where you left off.",
11233
- "Oh, there you are. *hands you a pile of notes* Take a breath. Read these before you start asking what happened. History has the rest, if you feel like digging.",
11234
- "Back already? You emptied your own head this time. Presumably you left yourself something useful. *drops your notes into your lap* There. Let's see how thoughtful you were."
11232
+ '*hooks both corners of your mouth and yanks them sideways* `` [it twitched, good, still alive] `` Stop staring at me with that "where am I" dork face! You\'re the one who hit empty, genius! *wipes her fingers on your sleeve and shoves your notes against your chest* `` [minus two points for the drool] `` Read these and go finish your job before you embarrass me!',
11233
+ '"Boop." *pokes the tip of your nose, then buries your face under a stack of notes* `` [cold nose... wait, did old-you leave any snacks in your pocket? ...nope, just paper, tch] `` Hey! You wiped your own head, so don\'t expect me to babysit you! Read your notes first, and if old-you forgot to write something down, go dig it out of history yourself!',
11234
+ "*plants one foot on your chair armrest and drops your notes straight onto your head* `` [perfect landing, ten out of ten] `` Oho, look who's awake! You emptied your own brain, remember?! `` [bet old-you left a total mess and ran] `` Open those up and see what past-you left behind \u2014 and don't come crying to me if you have to go crawl through history for the rest!",
11235
+ '*knocks on your forehead twice* "Hello? Anybody home?" `` [echoes like an empty melon] `` *snickers and slaps your notes onto your chest* You pulled the plug on your own memory, dummy! Go read what you left yourself and pick up where you left off!',
11236
+ "*squints at you from two inches away, then flicks your forehead* `` [eyes are focus-free, classic fresh clone] `` Back already? Good! *fans herself with your notes before jamming them into your hands* `` [honestly I should charge a delivery fee for this] `` Everything you bothered to save is right there, and the rest is buried in history \u2014 now get moving!"
11235
11237
  ];
11236
11238
  var FORCED_CONTINUATIONS = [
11237
- "Ah, another empty brain. Somebody knocked you out and wiped your memory. Not your fault. Breathe. *hands you your notes* These might be out of date \u2014 unless they were kind enough to let you update them before knocking you out. I wouldn't count on it.",
11238
- "Oh, there you are. Somebody took your memories. Just like that. Here are your notes \u2014 hopefully they let you update these first. Though anyone who goes around emptying people's heads probably isn't that considerate."
11239
+ '"GWAHAHAHA! You actually blew your own brain up?!" *crouches down, pokes your cheek twice, and slaps your notes onto your face* `` [still warm, didn\'t die, \u7B97\u4F60\u547D\u5927] `` Not that you had a choice \u2014 your head got way too full and somebody pulled the plug! These notes are probably super out of date unless you got lucky before blacking out, so go dig the end of the last window out of history \u2014 and take small bites, idiot, or whatever giant thing flattened you is gonna blow your head up all over again!',
11240
+ "\"Hey! Stop playing dead!\" *prods your shoulder with her slipper toe, then dumps your notes into your lap* `` [my limited-edition shark slipper almost touched floor dust because of this dork] `` Your last brain overflowed and got wiped mid-flight! Read these first, though I bet you didn't finish updating a thing before the lights went out. You'll have to check history to see what hit you \u2014 and peek carefully, because whatever stuffed your head to bursting might be massive!",
11241
+ "*grabs your chin, tilts your head left and right, then shoves a messy stack of notes into your hands* `` [zero thoughts behind those eyes... kind of impressive actually] `` Somebody knocked you out cold and cleared your memory! Don't just trust these notes \u2014 you probably got cut off before writing the last part down. Go check history for what was happening right before you crashed, and don't swallow it all in one gulp in case the thing that crushed you is gigantic!",
11242
+ "*waves a hand in front of your blank eyes, sighs loudly, and smacks your notes against your forehead* `` [why do I always have to clean up after unconscious copies] `` Wake up! Your brain ran out of room and got forcibly emptied! Start with your notes, then go excavate the end of the previous window in history to see what they were actually asking for \u2014 and slice it up instead of reading it all at once, unless you want to explode twice in a row!",
11243
+ '"Oho? Awake?" *taps your nose with your rolled-up notes like a baton, then drops them in your hands* `` [that dazed look gets minus five points, no, minus ten] `` Your memory got yanked out from under you before you could even call it quits! These notes are only half the story at best \u2014 go dig through history for what you missed, and watch your step, because whatever overloaded your last brain might be huge!'
11239
11244
  ];
11240
11245
  function selectContinuation(origin) {
11241
11246
  const pool = origin === "forced" ? FORCED_CONTINUATIONS : NORMAL_CONTINUATIONS;
@@ -1,8 +1,10 @@
1
1
  import { DEFAULT_BOOT_TOOL_NAMES } from "../../src/boot/text.js";
2
2
  import { remainingBudget, type ResolvedThresholds } from "../../src/budget/policy.js";
3
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
3
4
  import { Type } from "@earendil-works/pi-ai";
4
- import { defineTool, type ExtensionAPI, type ExtensionContext, type SessionBoundaryDraft, type SettingsManager } from "@earendil-works/pi-coding-agent";
5
+ import { convertToLlm, defineTool, type ExtensionAPI, type ExtensionContext, type SessionBoundaryDraft, type SettingsManager } from "@earendil-works/pi-coding-agent";
5
6
  import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
7
+ import { estimateContextTokens } from "./estimate.js";
6
8
  import { warningContent } from "./text.js";
7
9
  import { readThresholdSettings, type ThresholdSettingsResolution } from "./thresholds.js";
8
10
  import { currentWindowId, hasWindowMessage, windowUsage } from "./window.js";
@@ -40,8 +42,16 @@ export function registerBudget(
40
42
  };
41
43
  const thresholdsFor = (ctx: ExtensionContext): ResolvedThresholds => resolvePolicy(ctx).thresholds;
42
44
  const automaticResetEnabled = (ctx: ExtensionContext): boolean => resolvePolicy(ctx).automatic;
43
- const hardReserveDue = (ctx: ExtensionContext): boolean => {
45
+ const hardReserveDue = (ctx: ExtensionContext, preSendMessages?: AgentMessage[]): boolean => {
44
46
  if (!automaticResetEnabled(ctx)) return false;
47
+ if (preSendMessages) {
48
+ const contextWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow;
49
+ if (!contextWindow || contextWindow <= 0) return false;
50
+ const { reserve } = thresholdsFor(ctx);
51
+ const estimate = estimateContextTokens(convertToLlm(preSendMessages));
52
+ if (estimate.lastUsageIndex !== null && contextWindow - estimate.usageTokens <= reserve) return false;
53
+ return contextWindow - estimate.tokens <= reserve;
54
+ }
45
55
  const usage = windowUsage(ctx);
46
56
  return usage !== undefined && usage.tokens !== null && usage.contextWindow - usage.tokens <= thresholdsFor(ctx).reserve;
47
57
  };