notesoup 0.57.2 → 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.
@@ -1,3 +1,4 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
1
2
  import { Type } from "@earendil-works/pi-ai";
2
3
  import { type ExtensionAPI, type ExtensionContext, type SessionBoundaryDraft, type SettingsManager } from "@earendil-works/pi-coding-agent";
3
4
  export declare const ContextRemainingOutputSchema: Type.TObject<{
@@ -5,7 +6,7 @@ export declare const ContextRemainingOutputSchema: Type.TObject<{
5
6
  }>;
6
7
  export declare function registerBudget(pi: ExtensionAPI, isEnabled: () => boolean, settingsManager?: SettingsManager): {
7
8
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
8
- hardReserveDue: (ctx: ExtensionContext) => boolean;
9
+ hardReserveDue: (ctx: ExtensionContext, preSendMessages?: AgentMessage[]) => boolean;
9
10
  consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
10
11
  /** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
11
12
  statusFor: (ctx: ExtensionContext) => {
@@ -1,8 +1,9 @@
1
1
  import { DEFAULT_BOOT_TOOL_NAMES } from "../../src/boot/text.js";
2
2
  import { remainingBudget } from "../../src/budget/policy.js";
3
3
  import { Type } from "@earendil-works/pi-ai";
4
- import { defineTool } from "@earendil-works/pi-coding-agent";
4
+ import { convertToLlm, defineTool } from "@earendil-works/pi-coding-agent";
5
5
  import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
6
+ import { estimateContextTokens } from "./estimate.js";
6
7
  import { warningContent } from "./text.js";
7
8
  import { readThresholdSettings } from "./thresholds.js";
8
9
  import { currentWindowId, hasWindowMessage, windowUsage } from "./window.js";
@@ -36,9 +37,19 @@ export function registerBudget(pi, isEnabled, settingsManager) {
36
37
  };
37
38
  const thresholdsFor = (ctx) => resolvePolicy(ctx).thresholds;
38
39
  const automaticResetEnabled = (ctx) => resolvePolicy(ctx).automatic;
39
- const hardReserveDue = (ctx) => {
40
+ const hardReserveDue = (ctx, preSendMessages) => {
40
41
  if (!automaticResetEnabled(ctx))
41
42
  return false;
43
+ if (preSendMessages) {
44
+ const contextWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow;
45
+ if (!contextWindow || contextWindow <= 0)
46
+ return false;
47
+ const { reserve } = thresholdsFor(ctx);
48
+ const estimate = estimateContextTokens(convertToLlm(preSendMessages));
49
+ if (estimate.lastUsageIndex !== null && contextWindow - estimate.usageTokens <= reserve)
50
+ return false;
51
+ return contextWindow - estimate.tokens <= reserve;
52
+ }
42
53
  const usage = windowUsage(ctx);
43
54
  return usage !== undefined && usage.tokens !== null && usage.contextWindow - usage.tokens <= thresholdsFor(ctx).reserve;
44
55
  };
@@ -1,9 +1,10 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
1
2
  import type { ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
2
3
  import type { ResetOrigin } from "../../../src/budget/text.js";
3
4
  import { type CarriedInput } from "./artifacts.js";
4
5
  type BudgetOwner = {
5
6
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
6
- hardReserveDue: (ctx: ExtensionContext) => boolean;
7
+ hardReserveDue: (ctx: ExtensionContext, preSendMessages?: AgentMessage[]) => boolean;
7
8
  consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
8
9
  clear: () => void;
9
10
  };
@@ -77,15 +78,14 @@ export type ResetControlEvent = {
77
78
  readonly type: "before_settle";
78
79
  readonly facts: ResetBeforeSettleFacts;
79
80
  };
80
- /** Construction intent, not final state: handled inputs can still arrive while notes load. Only `turn-end`
81
- * may latch a stop; overflow kinds spend recovery; only hard-reserve and overflow carry passive run inputs. */
81
+ /** Construction intent, not final state: handled inputs can still arrive while notes load.
82
+ * Only `turn-end` may latch a stop; overflow kinds spend recovery. */
82
83
  export interface ResetBoundaryIntent {
83
84
  readonly effect: "build-boundary";
84
85
  readonly boundary: "turn-end" | "settle" | "command-overflow" | "overflow-recovery";
85
86
  readonly windowId: string;
86
87
  readonly continueAfterReset: boolean;
87
88
  readonly origin: ResetOrigin;
88
- readonly carryRunInputs?: boolean;
89
89
  readonly tool?: {
90
90
  readonly lastWord?: string;
91
91
  readonly terminate?: boolean;
@@ -95,8 +95,8 @@ export type ResetControlResult = ResetBoundaryIntent | {
95
95
  readonly state: ResetControlState;
96
96
  readonly effect: "none" | "close-out-armed" | "already-pending" | "stop";
97
97
  };
98
- /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
99
- export declare function finalizeResetBoundary(intent: ResetBoundaryIntent, request: ResetRequest, passiveInputs?: readonly CarriedInput[]): {
98
+ /** Resolve once, after a successful current build. Only inputs withheld from the closing model cross the reset. */
99
+ export declare function finalizeResetBoundary(intent: ResetBoundaryIntent, request: ResetRequest): {
100
100
  state: ResetControlState;
101
101
  inputs: readonly (string | (import("@earendil-works/pi-ai").TextContent | import("@earendil-works/pi-ai").ImageContent)[])[];
102
102
  resumeModel: boolean;
@@ -116,6 +116,7 @@ export declare function reduceResetControl(state: ResetControlState, event: Rese
116
116
  export declare function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions): {
117
117
  command(windowId: string, continueAfterReset: boolean, input?: CarriedInput): "none" | "stop" | "close-out-armed" | "already-pending";
118
118
  request(windowId: string, lastWord?: string, terminate?: boolean): "rollover_already_pending" | "rollover_requested";
119
+ hasPendingTrigger: () => boolean;
119
120
  clear: (preserveInputs?: boolean) => void;
120
121
  };
121
122
  export {};
@@ -22,15 +22,14 @@ function requestForWindow(request, windowId) {
22
22
  return request.phase === "pending" && request.windowId === windowId ? request : NO_REQUEST;
23
23
  }
24
24
  const spendsOverflow = (boundary) => boundary === "command-overflow" || boundary === "overflow-recovery";
25
- function boundaryIntent(request, windowId, boundary, carryRunInputs = false) {
25
+ function boundaryIntent(request, windowId, boundary) {
26
26
  const tool = request.phase === "none" ? undefined : request.tool;
27
27
  const continueAfterReset = request.phase === "pending" ? request.command?.continueAfterReset ?? !request.tool?.terminate : true;
28
- return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal", ...(carryRunInputs ? { carryRunInputs: true } : {}) };
28
+ return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal" };
29
29
  }
30
- /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
31
- export function finalizeResetBoundary(intent, request, passiveInputs = []) {
32
- const inputs = request.phase === "pending" && request.command ? request.command.inputs ?? []
33
- : intent.boundary === "overflow-recovery" || intent.carryRunInputs ? passiveInputs : [];
30
+ /** Resolve once, after a successful current build. Only inputs withheld from the closing model cross the reset. */
31
+ export function finalizeResetBoundary(intent, request) {
32
+ const inputs = request.phase === "pending" ? request.command?.inputs ?? [] : [];
34
33
  const resumeModel = intent.continueAfterReset || inputs.length > 0;
35
34
  const state = {
36
35
  request: NO_REQUEST,
@@ -92,7 +91,7 @@ export function reduceResetControl(state, event) {
92
91
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
93
92
  const toolReset = request.phase === "pending" && request.tool !== undefined;
94
93
  if ((toolReset && !manual) || facts.hardReserveDue) {
95
- return boundaryIntent(request, facts.windowId, "turn-end", !manual && !toolReset && facts.hardReserveDue);
94
+ return boundaryIntent(request, facts.windowId, "turn-end");
96
95
  }
97
96
  return { state: { request, overflow: "idle" }, effect: "none" };
98
97
  }
@@ -146,7 +145,8 @@ export function registerResetLifecycle(pi, options) {
146
145
  let sessionActive = true;
147
146
  let lifecycleGeneration = 0;
148
147
  let control = initialResetControl();
149
- let runInputs = [];
148
+ let preSendHardReserveWindowId;
149
+ let pendingPreSendTrigger;
150
150
  // Once input returns handled, Pi no longer owns its original content. If close-out
151
151
  // fails/cancels, restore it; only an ordinary error starts a turn to answer it.
152
152
  const restoreCommandInputs = (triggerTurn = false) => {
@@ -158,16 +158,16 @@ export function registerResetLifecycle(pi, options) {
158
158
  for (const draft of carriedInputDrafts(inputs)) {
159
159
  pi.sendMessage(draft, { triggerTurn });
160
160
  }
161
- runInputs.push(...inputs);
162
161
  };
163
162
  const clear = (preserveInputs = true) => {
164
163
  lifecycleGeneration++;
164
+ preSendHardReserveWindowId = undefined;
165
+ pendingPreSendTrigger = undefined;
165
166
  if (preserveInputs)
166
167
  restoreCommandInputs();
167
168
  control = initialResetControl();
168
- runInputs = [];
169
169
  };
170
- const resetBoundaryResult = async (entries, ctx, intent) => {
170
+ const resetBoundaryResult = async (entries, ctx, intent, preSendHardReserve = false) => {
171
171
  // Keep command state live while notes load so input arriving during this await joins this boundary.
172
172
  const generation = lifecycleGeneration;
173
173
  const outerGeneration = options.getLifecycleGeneration?.();
@@ -175,7 +175,7 @@ export function registerResetLifecycle(pi, options) {
175
175
  const windowId = currentWindowId(ctx);
176
176
  const isCurrent = () => sessionActive && lifecycleGeneration === generation &&
177
177
  (outerGeneration === undefined || options.getLifecycleGeneration?.() === outerGeneration) && options.isEnabled() &&
178
- ctx.signal?.aborted !== true && ctx.sessionManager.getSessionId() === sessionId && currentWindowId(ctx) === windowId;
178
+ (preSendHardReserve || ctx.signal?.aborted !== true) && ctx.sessionManager.getSessionId() === sessionId && currentWindowId(ctx) === windowId;
179
179
  // The retain-none checkpoint belongs to the old window; capture its successor before notes await.
180
180
  const firstSeq = nextHistorySeq(ctx, entries) + 1;
181
181
  let resetDrafts;
@@ -189,18 +189,19 @@ export function registerResetLifecycle(pi, options) {
189
189
  }
190
190
  if (!isCurrent())
191
191
  return entries.length > 0 ? { entries } : undefined;
192
- const finalized = finalizeResetBoundary(intent, control.request, runInputs);
192
+ const finalized = finalizeResetBoundary(intent, control.request);
193
193
  control = finalized.state;
194
- runInputs = [];
195
194
  options.onResetReady?.(ctx, resetDrafts);
196
- return { entries: [...entries, ...resetDrafts, ...carriedInputDrafts(finalized.inputs)], continue: finalized.resumeModel };
195
+ const allDrafts = [...resetDrafts, ...carriedInputDrafts(finalized.inputs)];
196
+ if (preSendHardReserve && finalized.resumeModel) {
197
+ const last = allDrafts.at(-1);
198
+ if (last?.type === "custom_message") {
199
+ pendingPreSendTrigger = last;
200
+ return { entries: [...entries, ...allDrafts.slice(0, -1)], continue: false };
201
+ }
202
+ }
203
+ return { entries: [...entries, ...allDrafts], continue: finalized.resumeModel };
197
204
  };
198
- // Pi may start multiple low-level loops while draining follow-ups/recovering.
199
- // Keep the logical run's inputs until settlement or a successful boundary.
200
- pi.on("message_end", (event) => {
201
- if (event.message.role === "user")
202
- runInputs.push(event.message.content);
203
- });
204
205
  pi.on("input", (event, ctx) => {
205
206
  if (event.source === "extension" || !sessionActive || !options.isEnabled())
206
207
  return undefined;
@@ -217,16 +218,30 @@ export function registerResetLifecycle(pi, options) {
217
218
  // safety reset is actually committed, cancel that empty follow-up before provider
218
219
  // work. Real queued user input is allowed through and answered before settlement.
219
220
  pi.on("context_with_system", (event, ctx) => {
221
+ if (!sessionActive)
222
+ return undefined;
220
223
  const stop = control.stopAfterReset;
221
- if (!sessionActive || !stop || ctx.hasPendingMessages())
224
+ if (stop) {
225
+ if (ctx.hasPendingMessages())
226
+ return undefined;
227
+ const marker = currentReset(ctx);
228
+ if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId))
229
+ return undefined;
230
+ const branch = ctx.sessionManager.getBranch();
231
+ const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
232
+ if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry)))
233
+ return undefined;
234
+ ctx.abort();
235
+ const system = getCurrentSystemMessage(event.messages);
236
+ return { messages: system ? [system] : [] };
237
+ }
238
+ if (!options.isEnabled() || ctx.signal?.aborted)
222
239
  return undefined;
223
- const marker = currentReset(ctx);
224
- if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId))
240
+ if (control.request.phase === "pending" && control.request.command !== undefined)
225
241
  return undefined;
226
- const branch = ctx.sessionManager.getBranch();
227
- const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
228
- if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry)))
242
+ if (!options.budget.hardReserveDue(ctx, event.messages))
229
243
  return undefined;
244
+ preSendHardReserveWindowId = currentWindowId(ctx);
230
245
  ctx.abort();
231
246
  const system = getCurrentSystemMessage(event.messages);
232
247
  return { messages: system ? [system] : [] };
@@ -234,33 +249,33 @@ export function registerResetLifecycle(pi, options) {
234
249
  pi.on("turn_end", async (event, ctx) => {
235
250
  if (!sessionActive)
236
251
  return undefined;
237
- const aborted = isAbort(event.message, event.outcome, ctx);
252
+ const windowId = currentWindowId(ctx);
253
+ const preSendHardReserve = preSendHardReserveWindowId !== undefined && preSendHardReserveWindowId === windowId;
254
+ preSendHardReserveWindowId = undefined;
255
+ const aborted = preSendHardReserve ? false : isAbort(event.message, event.outcome, ctx);
238
256
  const stagedBudgetEntries = options.budget.consumeTurnEnd(ctx, event.messageEntryId);
239
257
  const budgetEntries = options.isEnabled() && !aborted && event.outcome !== "error" ? stagedBudgetEntries : [];
240
258
  const entries = [...(event.entries ?? []), ...budgetEntries];
241
259
  const decision = reduceResetControl(control, {
242
260
  type: "turn_end",
243
261
  facts: {
244
- windowId: currentWindowId(ctx),
262
+ windowId,
245
263
  aborted,
246
264
  overflow: aborted ? false : isOverflowLike(event.message, ctx),
247
265
  failed: event.outcome === "error",
248
266
  enabled: options.isEnabled(),
249
267
  get queued() { return event.context.pendingMessages.length > 0 || ctx.hasPendingMessages(); },
250
268
  get automaticResetEnabled() { return options.budget.automaticResetEnabled(ctx); },
251
- get hardReserveDue() { return options.budget.hardReserveDue(ctx); },
269
+ get hardReserveDue() { return preSendHardReserve || options.budget.hardReserveDue(ctx); },
252
270
  },
253
271
  });
254
272
  if (decision.effect === "build-boundary")
255
- return await resetBoundaryResult(entries, ctx, decision);
273
+ return await resetBoundaryResult(entries, ctx, decision, preSendHardReserve);
256
274
  if (aborted)
257
275
  restoreCommandInputs();
258
276
  else if (event.outcome === "error" && decision.state.request.phase === "none")
259
277
  restoreCommandInputs(true);
260
278
  control = decision.state;
261
- if (!aborted && event.outcome === "completed" && event.message.role === "assistant" && event.message.stopReason === "stop" &&
262
- event.context.pendingMessages.length === 0 && !ctx.hasPendingMessages())
263
- runInputs = [];
264
279
  if (!aborted && event.outcome !== "error" && options.isEnabled()) {
265
280
  const marker = buildMarkerDraft(ctx, entries);
266
281
  if (marker)
@@ -306,11 +321,15 @@ export function registerResetLifecycle(pi, options) {
306
321
  return undefined;
307
322
  });
308
323
  pi.on("agent_end", (_event, ctx) => {
309
- if (ctx.signal?.aborted)
324
+ if (ctx.signal?.aborted && !pendingPreSendTrigger)
310
325
  clear();
311
326
  });
312
327
  pi.on("agent_settled", () => {
328
+ const trigger = pendingPreSendTrigger;
313
329
  clear();
330
+ if (trigger) {
331
+ pi.sendMessage(trigger, { triggerTurn: true });
332
+ }
314
333
  });
315
334
  pi.on("session_start", () => { clear(false); sessionActive = true; });
316
335
  pi.on("session_tree", () => { clear(false); });
@@ -326,6 +345,7 @@ export function registerResetLifecycle(pi, options) {
326
345
  control = decision.state;
327
346
  return decision.effect === "already-pending" ? "rollover_already_pending" : "rollover_requested";
328
347
  },
348
+ hasPendingTrigger: () => pendingPreSendTrigger !== undefined,
329
349
  clear,
330
350
  };
331
351
  }
@@ -91,7 +91,8 @@ export function registerContext(pi, settingsManager) {
91
91
  });
92
92
  pi.on("agent_settled", (_event, ctx) => {
93
93
  notifyCommittedResets(ctx);
94
- pendingResetNotices.clear();
94
+ if (!resets.hasPendingTrigger())
95
+ pendingResetNotices.clear();
95
96
  });
96
97
  const notifyIncompleteNotes = (ctx, windowId, snapshot) => {
97
98
  if (snapshot.unavailable.length === 0 || incompleteNotesNotified.has(windowId))
@@ -8,10 +8,6 @@ export type ResetOrigin = "normal" | "forced";
8
8
  */
9
9
  export declare const NORMAL_CONTINUATIONS: readonly string[];
10
10
  export declare const FORCED_CONTINUATIONS: readonly string[];
11
- /**
12
- * Pick one whole paragraph for a continuation that is being created right now, and only then:
13
- * the caller persists the exact returned text and never redraws it for rendering, history, or repair.
14
- */
15
11
  export declare function selectContinuation(origin: ResetOrigin): string;
16
12
  /** Budget timing stays out of manual close-outs, which may have plenty of room. */
17
13
  export declare const WARNING_TIMING = "The reserve is nearly spent. The wipe lands at the end of whichever turn spends the last of it, possibly this one.";
@@ -5,18 +5,19 @@ export const GUIDANCE_CLOSE_TAG = "</notesoup:budget_notice>";
5
5
  * paragraph, used verbatim; there is no fragment assembly and no weighting.
6
6
  */
7
7
  export const NORMAL_CONTINUATIONS = [
8
- "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.",
9
- "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.",
10
- "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.",
8
+ "*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!",
9
+ "\"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!",
10
+ "*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!",
11
+ "*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!",
12
+ "*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!",
11
13
  ];
12
14
  export const FORCED_CONTINUATIONS = [
13
- "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.",
14
- "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.",
15
+ "\"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!",
16
+ "\"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!",
17
+ "*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!",
18
+ "*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!",
19
+ "\"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!",
15
20
  ];
16
- /**
17
- * Pick one whole paragraph for a continuation that is being created right now, and only then:
18
- * the caller persists the exact returned text and never redraws it for rendering, history, or repair.
19
- */
20
21
  export function selectContinuation(origin) {
21
22
  const pool = origin === "forced" ? FORCED_CONTINUATIONS : NORMAL_CONTINUATIONS;
22
23
  return pool[Math.floor(Math.random() * pool.length)];
@@ -744,18 +744,24 @@ test("real AgentSession: streaming clear prompt keeps the first request", async
744
744
  fixture.close();
745
745
  }
746
746
  });
747
- 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 () => {
748
748
  let fixture;
749
749
  const input = "HARD_RESERVE_IMAGE_INPUT";
750
- 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" };
751
752
  fixture = await openFixture({
752
753
  defaultReserveTokens: 80_000,
753
754
  script: (request, context) => {
754
755
  if (request === 1)
755
756
  return assistant(fixture, [{ type: "text", text: "reserve reached" }], "stop", { usage: usage(80_000) });
756
- assert.equal(request, 2);
757
- assertUserContent(context, [{ type: "text", text: input }, image]);
758
- 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" }]);
759
765
  },
760
766
  });
761
767
  try {
@@ -763,7 +769,17 @@ test("real AgentSession: hard-reserve reset carries the original text and image
763
769
  await fixture.session.waitForIdle();
764
770
  assert.equal(fixture.requests.length, 2);
765
771
  assert.equal(resetMarkers(fixture).length, 1);
766
- 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");
767
783
  }
768
784
  finally {
769
785
  fixture.close();
@@ -1292,6 +1308,57 @@ test("real AgentSession: steering and follow-up are delivered exactly once in th
1292
1308
  }
1293
1309
  }
1294
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
+ });
1295
1362
  test("real AgentSession: hidden or missing reset boots refuse to move the boundary", async () => {
1296
1363
  let fixture;
1297
1364
  fixture = await openFixture({
@@ -1384,7 +1451,7 @@ test("real AgentSession: the complete system message and a changed tool loadout
1384
1451
  fixture.close();
1385
1452
  }
1386
1453
  });
1387
- 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 () => {
1388
1455
  for (const failure of ["overflow", "length"]) {
1389
1456
  let fixture;
1390
1457
  fixture = await openFixture({
@@ -1401,11 +1468,11 @@ test("real AgentSession: overflow and recoverable length reset and retry once; r
1401
1468
  if (request === 3)
1402
1469
  return assistant(fixture, [], "error", { errorMessage: "Prompt too long: context exceeds maximum context length" });
1403
1470
  assert.equal(request, 4);
1404
- assertUserContent(context, [{ type: "text", text: "PASSIVE_STEERED_INPUT" }]);
1405
- 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);
1406
1473
  }
1407
1474
  else if (request === 1)
1408
- 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 } });
1409
1476
  return assistant(fixture, [{ type: "text", text: "recovered" }]);
1410
1477
  },
1411
1478
  });
@@ -1415,7 +1482,9 @@ test("real AgentSession: overflow and recoverable length reset and retry once; r
1415
1482
  assert.equal(resetMarkers(fixture).length, 1, `${failure} performs one reset`);
1416
1483
  assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "compaction").length, 1, `${failure} commits one native reset checkpoint`);
1417
1484
  assert.equal(fixture.requests.length, failure === "overflow" ? 4 : 2, `${failure} resumes once after queued work drains`);
1418
- 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");
1419
1488
  }
1420
1489
  finally {
1421
1490
  fixture.close();
@@ -1440,7 +1509,7 @@ test("real AgentSession: overflow and recoverable length reset and retry once; r
1440
1509
  repeated.close();
1441
1510
  }
1442
1511
  });
1443
- 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 () => {
1444
1513
  let fixture;
1445
1514
  fixture = await openFixture({
1446
1515
  contextWindow: 200_000,
@@ -1450,7 +1519,7 @@ test("real AgentSession: a smaller-model overflow carries the failed run's human
1450
1519
  if (request === 2)
1451
1520
  return assistant(fixture, [], "error", { errorMessage: "Prompt too long: context exceeds maximum context length" });
1452
1521
  assert.equal(request, 3);
1453
- assertUserContent(context, [{ type: "text", text: "CONTINUE_AFTER_MODEL_SWITCH" }]);
1522
+ assert.equal(text(context).includes("CONTINUE_AFTER_MODEL_SWITCH"), false);
1454
1523
  return assistant(fixture, [{ type: "text", text: "continued on smaller model" }]);
1455
1524
  },
1456
1525
  });
@@ -1467,7 +1536,8 @@ test("real AgentSession: a smaller-model overflow carries the failed run's human
1467
1536
  assert.equal(fixture.requests.length, 3, "one failed small-model request and one recovery request");
1468
1537
  assert.equal(fixture.session.model?.id, smaller.id, "recovery stays on the selected model");
1469
1538
  assertFreshRequest(fixture, 2, "LARGE_MODEL_HISTORY");
1470
- 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");
1471
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");
1472
1542
  }
1473
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\`.
@@ -210,31 +210,6 @@ test("public reset boundary drafts one marker, one boot, and one continuation af
210
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");
211
211
  assert.equal(branch.filter((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE).length, 1);
212
212
  });
213
- test("hard-reserve reset carries original text and images and continues", async () => {
214
- const sessionManager = Manager.inMemory("/private/tmp/notesoup-hard-reserve-carry-test");
215
- const handlers = new Map();
216
- const api = { on(name, handler) { const list = handlers.get(name) ?? []; list.push(handler); handlers.set(name, list); } };
217
- const ctx = { sessionManager, model: undefined, hasPendingMessages: () => false, ui: { notify() { } } };
218
- registerResetLifecycle(api, {
219
- isEnabled: () => true,
220
- budget: { automaticResetEnabled: () => true, hardReserveDue: () => true, consumeTurnEnd: () => [], clear() { } },
221
- buildReset: () => [],
222
- });
223
- const original = [
224
- { type: "text", text: "Describe this image" },
225
- { type: "image", data: "aW1hZ2U=", mimeType: "image/png" },
226
- ];
227
- for (const handler of handlers.get("message_end") ?? [])
228
- await handler({ type: "message_end", message: { role: "user", content: original, timestamp: Date.now() } }, ctx);
229
- let result;
230
- for (const handler of handlers.get("turn_end") ?? [])
231
- result = await handler(fakeBoundaryEvent([], { role: "assistant", content: [], stopReason: "stop", timestamp: Date.now() }), ctx);
232
- const boundary = resultEntries([result]);
233
- const carried = boundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE);
234
- assert.equal(carried.length, 1);
235
- assert.deepEqual(carried[0]?.type === "custom_message" ? carried[0].content : undefined, original);
236
- assert.equal(boundary.continue, true);
237
- });
238
213
  test("manual /empty spans tool turns and commits the stop at settlement", async () => {
239
214
  const h = harness();
240
215
  await h.runCommand("empty");
@@ -365,8 +340,8 @@ test("input arriving during reset construction is carried without a hidden steer
365
340
  assert.equal(inspectResetTail(ctx, partialMarker, "partial"), undefined, "repair cannot append a continuation after human content");
366
341
  assert.equal(resetBoundaryCommitted(ctx, partialMarker, "partial"), false);
367
342
  });
368
- test("overflow construction reads live run inputs and clear invalidates an unfinished build", async () => {
369
- 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");
370
345
  const handlers = new Map();
371
346
  const api = { on(name, handler) { handlers.set(name, handler); } };
372
347
  const ctx = { sessionManager, model: undefined, hasPendingMessages: () => false, ui: { notify() { } } };
@@ -378,34 +353,25 @@ test("overflow construction reads live run inputs and clear invalidates an unfin
378
353
  buildReset: () => new Promise((resolve) => { release = resolve; }),
379
354
  onResetReady: () => { readyCount++; },
380
355
  });
381
- const user = (content) => handlers.get("message_end")({ message: { role: "user", content } }, ctx);
382
356
  const failed = { ...fakeBoundaryEvent(), outcome: "error", message: { role: "assistant", stopReason: "error", errorMessage: "Prompt too long: context exceeds maximum context length" } };
383
357
  const recover = async () => {
384
358
  await handlers.get("turn_end")(failed, ctx);
385
359
  return handlers.get("agent_before_settle")({ ...failed, type: "agent_before_settle" }, ctx);
386
360
  };
387
- await user("starting input");
388
- const building = recover();
389
- await Promise.resolve();
390
- await user("delivered during construction");
391
- release([]);
392
- const result = resultEntries([await building]);
393
- assert.equal(result.continue, true);
394
- assert.deepEqual(result.entries.map((entry) => entry.type === "custom_message" ? entry.content : null), ["starting input", "delivered during construction"]);
395
- lifecycle.clear();
396
- await user("old run");
397
361
  const stale = recover();
398
362
  await Promise.resolve();
399
363
  lifecycle.clear();
400
- await user("new run");
401
364
  release([{ type: "custom_message", customType: BOOT_TYPE, content: "stale", display: false }]);
402
- assert.equal(await stale, undefined, "clearing the run invalidates construction before it can consume new inputs");
403
- assert.equal(readyCount, 1);
365
+ assert.equal(await stale, undefined, "clearing the lifecycle invalidates the unfinished reset");
366
+ assert.equal(readyCount, 0);
404
367
  const current = recover();
405
368
  await Promise.resolve();
406
- release([]);
369
+ const drafts = [{ type: "custom_message", customType: BOOT_TYPE, content: "fresh", display: false }];
370
+ release(drafts);
407
371
  const fresh = resultEntries([await current]);
408
- 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);
409
375
  });
410
376
  test("abort during reset construction restores handled input at settlement, once", async () => {
411
377
  const sessionManager = Manager.inMemory("/private/tmp/notesoup-cancelled-build-test");
@@ -748,12 +714,12 @@ test("reset-control: one safety intent finalizes stop or continuation from live
748
714
  const pending = reduceResetControl(initialResetControl(), { type: "command", windowId, continueAfterReset: false }).state;
749
715
  const intent = boundaryIntent(reduceResetControl(pending, { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) }));
750
716
  assert.deepEqual(pending.request, { phase: "pending", windowId, command: { continueAfterReset: false } });
751
- const stopped = finalizeResetBoundary(intent, pending.request, ["passive run input"]);
717
+ const stopped = finalizeResetBoundary(intent, pending.request);
752
718
  assert.equal(stopped.resumeModel, false);
753
719
  assert.deepEqual(stopped.inputs, [], "a command boundary never replays passive run input");
754
720
  assert.deepEqual(stopped.state.stopAfterReset, intent);
755
721
  const live = reduceResetControl(pending, { type: "input", windowId, input: "late original" }).state;
756
- const continued = finalizeResetBoundary(intent, live.request, ["passive run input"]);
722
+ const continued = finalizeResetBoundary(intent, live.request);
757
723
  assert.equal(continued.resumeModel, true);
758
724
  assert.deepEqual(continued.inputs, ["late original"]);
759
725
  assert.deepEqual(continued.state, initialResetControl(), "late originals prevent installing the stop latch");
@@ -782,7 +748,7 @@ test("reset-control: manual overflow keeps stop intent while queued work superse
782
748
  const retryIntent = boundaryIntent(decision);
783
749
  assert.equal(retryIntent.origin, "forced", "an overflowing close-out is forced even after a tool request");
784
750
  assert.equal(retryIntent.tool?.lastWord, "saved");
785
- const retry = finalizeResetBoundary(retryIntent, failed.request, ["passive input is not command-owned"]);
751
+ const retry = finalizeResetBoundary(retryIntent, failed.request);
786
752
  assert.equal(retry.resumeModel, true, "manual input continues even when automatic reset is disabled");
787
753
  assert.deepEqual(retry.inputs, ["answer after reset"]);
788
754
  assert.equal(retry.state.overflow, "spent", "manual recovery spends the same bounded attempt");
@@ -801,9 +767,9 @@ test("reset-control: overflow recovery is armed at turn_end and spent exactly on
801
767
  const intent = boundaryIntent(reduceResetControl(armed, { type: "before_settle", facts: beforeSettleFacts() }));
802
768
  assert.equal(armed.overflow, "pending", "failed construction would leave recovery unspent");
803
769
  assert.equal(intent.boundary, "overflow-recovery");
804
- const recovered = finalizeResetBoundary(intent, armed.request, ["failed run's user input"]);
770
+ const recovered = finalizeResetBoundary(intent, armed.request);
805
771
  assert.equal(recovered.resumeModel, true);
806
- assert.deepEqual(recovered.inputs, ["failed run's user input"]);
772
+ assert.deepEqual(recovered.inputs, []);
807
773
  assert.deepEqual(recovered.state, { request: { phase: "none" }, overflow: "spent" });
808
774
  const repeated = reduceResetControl(recovered.state, { type: "before_settle", facts: beforeSettleFacts() });
809
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,7 +4,7 @@ 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
  | --- | --- |
@@ -13,14 +13,14 @@ Pi reset control lives in `plugins/pi/reset/lifecycle.ts`: the pure `reduceReset
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
 
@@ -52,9 +52,9 @@ Raw session history remains available. The retain-none checkpoint excludes old c
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.2",
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.2",
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
  };
@@ -11,7 +11,7 @@ import { carriedInputDrafts, isCarriedInputEntry, type CarriedInput } from "./ar
11
11
 
12
12
  type BudgetOwner = {
13
13
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
14
- hardReserveDue: (ctx: ExtensionContext) => boolean;
14
+ hardReserveDue: (ctx: ExtensionContext, preSendMessages?: AgentMessage[]) => boolean;
15
15
  consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
16
16
  clear: () => void;
17
17
  };
@@ -83,15 +83,14 @@ export type ResetControlEvent =
83
83
  | { readonly type: "turn_end"; readonly facts: ResetTurnEndFacts }
84
84
  | { readonly type: "before_settle"; readonly facts: ResetBeforeSettleFacts };
85
85
 
86
- /** Construction intent, not final state: handled inputs can still arrive while notes load. Only `turn-end`
87
- * may latch a stop; overflow kinds spend recovery; only hard-reserve and overflow carry passive run inputs. */
86
+ /** Construction intent, not final state: handled inputs can still arrive while notes load.
87
+ * Only `turn-end` may latch a stop; overflow kinds spend recovery. */
88
88
  export interface ResetBoundaryIntent {
89
89
  readonly effect: "build-boundary";
90
90
  readonly boundary: "turn-end" | "settle" | "command-overflow" | "overflow-recovery";
91
91
  readonly windowId: string;
92
92
  readonly continueAfterReset: boolean;
93
93
  readonly origin: ResetOrigin;
94
- readonly carryRunInputs?: boolean;
95
94
  readonly tool?: { readonly lastWord?: string; readonly terminate?: boolean };
96
95
  }
97
96
 
@@ -104,16 +103,15 @@ function requestForWindow(request: ResetRequest, windowId: string): ResetRequest
104
103
 
105
104
  const spendsOverflow = (boundary: ResetBoundaryIntent["boundary"]) => boundary === "command-overflow" || boundary === "overflow-recovery";
106
105
 
107
- function boundaryIntent(request: ResetRequest, windowId: string, boundary: ResetBoundaryIntent["boundary"], carryRunInputs = false): ResetBoundaryIntent {
106
+ function boundaryIntent(request: ResetRequest, windowId: string, boundary: ResetBoundaryIntent["boundary"]): ResetBoundaryIntent {
108
107
  const tool = request.phase === "none" ? undefined : request.tool;
109
108
  const continueAfterReset = request.phase === "pending" ? request.command?.continueAfterReset ?? !request.tool?.terminate : true;
110
- return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal", ...(carryRunInputs ? { carryRunInputs: true } : {}) };
109
+ return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal" };
111
110
  }
112
111
 
113
- /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
114
- export function finalizeResetBoundary(intent: ResetBoundaryIntent, request: ResetRequest, passiveInputs: readonly CarriedInput[] = []) {
115
- const inputs = request.phase === "pending" && request.command ? request.command.inputs ?? []
116
- : intent.boundary === "overflow-recovery" || intent.carryRunInputs ? passiveInputs : [];
112
+ /** Resolve once, after a successful current build. Only inputs withheld from the closing model cross the reset. */
113
+ export function finalizeResetBoundary(intent: ResetBoundaryIntent, request: ResetRequest) {
114
+ const inputs = request.phase === "pending" ? request.command?.inputs ?? [] : [];
117
115
  const resumeModel = intent.continueAfterReset || inputs.length > 0;
118
116
  const state: ResetControlState = {
119
117
  request: NO_REQUEST,
@@ -173,7 +171,7 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
173
171
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
174
172
  const toolReset = request.phase === "pending" && request.tool !== undefined;
175
173
  if ((toolReset && !manual) || facts.hardReserveDue) {
176
- return boundaryIntent(request, facts.windowId, "turn-end", !manual && !toolReset && facts.hardReserveDue);
174
+ return boundaryIntent(request, facts.windowId, "turn-end");
177
175
  }
178
176
  return { state: { request, overflow: "idle" }, effect: "none" };
179
177
  }
@@ -221,7 +219,8 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
221
219
  let sessionActive = true;
222
220
  let lifecycleGeneration = 0;
223
221
  let control = initialResetControl();
224
- let runInputs: CarriedInput[] = [];
222
+ let preSendHardReserveWindowId: string | undefined;
223
+ let pendingPreSendTrigger: Extract<SessionBoundaryDraft, { type: "custom_message" }> | undefined;
225
224
 
226
225
  // Once input returns handled, Pi no longer owns its original content. If close-out
227
226
  // fails/cancels, restore it; only an ordinary error starts a turn to answer it.
@@ -233,15 +232,15 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
233
232
  for (const draft of carriedInputDrafts(inputs)) {
234
233
  pi.sendMessage(draft, { triggerTurn });
235
234
  }
236
- runInputs.push(...inputs);
237
235
  };
238
236
  const clear = (preserveInputs = true) => {
239
237
  lifecycleGeneration++;
238
+ preSendHardReserveWindowId = undefined;
239
+ pendingPreSendTrigger = undefined;
240
240
  if (preserveInputs) restoreCommandInputs();
241
241
  control = initialResetControl();
242
- runInputs = [];
243
242
  };
244
- const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, intent: ResetBoundaryIntent) => {
243
+ const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, intent: ResetBoundaryIntent, preSendHardReserve = false) => {
245
244
  // Keep command state live while notes load so input arriving during this await joins this boundary.
246
245
  const generation = lifecycleGeneration;
247
246
  const outerGeneration = options.getLifecycleGeneration?.();
@@ -249,7 +248,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
249
248
  const windowId = currentWindowId(ctx);
250
249
  const isCurrent = () => sessionActive && lifecycleGeneration === generation &&
251
250
  (outerGeneration === undefined || options.getLifecycleGeneration?.() === outerGeneration) && options.isEnabled() &&
252
- ctx.signal?.aborted !== true && ctx.sessionManager.getSessionId() === sessionId && currentWindowId(ctx) === windowId;
251
+ (preSendHardReserve || ctx.signal?.aborted !== true) && ctx.sessionManager.getSessionId() === sessionId && currentWindowId(ctx) === windowId;
253
252
  // The retain-none checkpoint belongs to the old window; capture its successor before notes await.
254
253
  const firstSeq = nextHistorySeq(ctx, entries) + 1;
255
254
  let resetDrafts: SessionBoundaryDraft[];
@@ -260,18 +259,20 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
260
259
  return entries.length > 0 ? { entries } : undefined;
261
260
  }
262
261
  if (!isCurrent()) return entries.length > 0 ? { entries } : undefined;
263
- const finalized = finalizeResetBoundary(intent, control.request, runInputs);
262
+ const finalized = finalizeResetBoundary(intent, control.request);
264
263
  control = finalized.state;
265
- runInputs = [];
266
264
  options.onResetReady?.(ctx, resetDrafts);
267
- return { entries: [...entries, ...resetDrafts, ...carriedInputDrafts(finalized.inputs)], continue: finalized.resumeModel };
265
+ const allDrafts = [...resetDrafts, ...carriedInputDrafts(finalized.inputs)];
266
+ if (preSendHardReserve && finalized.resumeModel) {
267
+ const last = allDrafts.at(-1);
268
+ if (last?.type === "custom_message") {
269
+ pendingPreSendTrigger = last;
270
+ return { entries: [...entries, ...allDrafts.slice(0, -1)], continue: false };
271
+ }
272
+ }
273
+ return { entries: [...entries, ...allDrafts], continue: finalized.resumeModel };
268
274
  };
269
275
 
270
- // Pi may start multiple low-level loops while draining follow-ups/recovering.
271
- // Keep the logical run's inputs until settlement or a successful boundary.
272
- pi.on("message_end", (event) => {
273
- if (event.message.role === "user") runInputs.push(event.message.content);
274
- });
275
276
  pi.on("input", (event, ctx) => {
276
277
  if (event.source === "extension" || !sessionActive || !options.isEnabled()) return undefined;
277
278
  const request = control.request;
@@ -287,13 +288,23 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
287
288
  // safety reset is actually committed, cancel that empty follow-up before provider
288
289
  // work. Real queued user input is allowed through and answered before settlement.
289
290
  pi.on("context_with_system", (event, ctx) => {
291
+ if (!sessionActive) return undefined;
290
292
  const stop = control.stopAfterReset;
291
- if (!sessionActive || !stop || ctx.hasPendingMessages()) return undefined;
292
- const marker = currentReset(ctx);
293
- if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId)) return undefined;
294
- const branch = ctx.sessionManager.getBranch();
295
- const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
296
- if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry))) return undefined;
293
+ if (stop) {
294
+ if (ctx.hasPendingMessages()) return undefined;
295
+ const marker = currentReset(ctx);
296
+ if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId)) return undefined;
297
+ const branch = ctx.sessionManager.getBranch();
298
+ const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
299
+ if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry))) return undefined;
300
+ ctx.abort();
301
+ const system = getCurrentSystemMessage(event.messages);
302
+ return { messages: system ? [system] : [] };
303
+ }
304
+ if (!options.isEnabled() || ctx.signal?.aborted) return undefined;
305
+ if (control.request.phase === "pending" && control.request.command !== undefined) return undefined;
306
+ if (!options.budget.hardReserveDue(ctx, event.messages)) return undefined;
307
+ preSendHardReserveWindowId = currentWindowId(ctx);
297
308
  ctx.abort();
298
309
  const system = getCurrentSystemMessage(event.messages);
299
310
  return { messages: system ? [system] : [] };
@@ -301,29 +312,30 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
301
312
 
302
313
  pi.on("turn_end", async (event, ctx) => {
303
314
  if (!sessionActive) return undefined;
304
- const aborted = isAbort(event.message, event.outcome, ctx);
315
+ const windowId = currentWindowId(ctx);
316
+ const preSendHardReserve = preSendHardReserveWindowId !== undefined && preSendHardReserveWindowId === windowId;
317
+ preSendHardReserveWindowId = undefined;
318
+ const aborted = preSendHardReserve ? false : isAbort(event.message, event.outcome, ctx);
305
319
  const stagedBudgetEntries = options.budget.consumeTurnEnd(ctx, event.messageEntryId);
306
320
  const budgetEntries = options.isEnabled() && !aborted && event.outcome !== "error" ? stagedBudgetEntries : [];
307
321
  const entries = [...(event.entries ?? []), ...budgetEntries];
308
322
  const decision = reduceResetControl(control, {
309
323
  type: "turn_end",
310
324
  facts: {
311
- windowId: currentWindowId(ctx),
325
+ windowId,
312
326
  aborted,
313
327
  overflow: aborted ? false : isOverflowLike(event.message, ctx),
314
328
  failed: event.outcome === "error",
315
329
  enabled: options.isEnabled(),
316
330
  get queued() { return event.context.pendingMessages.length > 0 || ctx.hasPendingMessages(); },
317
331
  get automaticResetEnabled() { return options.budget.automaticResetEnabled(ctx); },
318
- get hardReserveDue() { return options.budget.hardReserveDue(ctx); },
332
+ get hardReserveDue() { return preSendHardReserve || options.budget.hardReserveDue(ctx); },
319
333
  },
320
334
  });
321
- if (decision.effect === "build-boundary") return await resetBoundaryResult(entries, ctx, decision);
335
+ if (decision.effect === "build-boundary") return await resetBoundaryResult(entries, ctx, decision, preSendHardReserve);
322
336
  if (aborted) restoreCommandInputs();
323
337
  else if (event.outcome === "error" && decision.state.request.phase === "none") restoreCommandInputs(true);
324
338
  control = decision.state;
325
- if (!aborted && event.outcome === "completed" && event.message.role === "assistant" && event.message.stopReason === "stop" &&
326
- event.context.pendingMessages.length === 0 && !ctx.hasPendingMessages()) runInputs = [];
327
339
  if (!aborted && event.outcome !== "error" && options.isEnabled()) {
328
340
  const marker = buildMarkerDraft(ctx, entries);
329
341
  if (marker) entries.push(marker);
@@ -365,10 +377,14 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
365
377
  });
366
378
 
367
379
  pi.on("agent_end", (_event, ctx) => {
368
- if (ctx.signal?.aborted) clear();
380
+ if (ctx.signal?.aborted && !pendingPreSendTrigger) clear();
369
381
  });
370
382
  pi.on("agent_settled", () => {
383
+ const trigger = pendingPreSendTrigger;
371
384
  clear();
385
+ if (trigger) {
386
+ pi.sendMessage(trigger, { triggerTurn: true });
387
+ }
372
388
  });
373
389
  pi.on("session_start", () => { clear(false); sessionActive = true; });
374
390
  pi.on("session_tree", () => { clear(false); });
@@ -385,6 +401,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
385
401
  control = decision.state;
386
402
  return decision.effect === "already-pending" ? "rollover_already_pending" : "rollover_requested";
387
403
  },
404
+ hasPendingTrigger: () => pendingPreSendTrigger !== undefined,
388
405
  clear,
389
406
  };
390
407
  }
@@ -89,7 +89,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
89
89
  });
90
90
  pi.on("agent_settled", (_event, ctx) => {
91
91
  notifyCommittedResets(ctx);
92
- pendingResetNotices.clear();
92
+ if (!resets.hasPendingTrigger()) pendingResetNotices.clear();
93
93
  });
94
94
  const notifyIncompleteNotes: IncompleteNotesNotifier = (ctx, windowId, snapshot) => {
95
95
  if (snapshot.unavailable.length === 0 || incompleteNotesNotified.has(windowId)) return;
@@ -9,20 +9,20 @@ export type ResetOrigin = "normal" | "forced";
9
9
  * paragraph, used verbatim; there is no fragment assembly and no weighting.
10
10
  */
11
11
  export const NORMAL_CONTINUATIONS: readonly string[] = [
12
- "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.",
13
- "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.",
14
- "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.",
12
+ "*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!",
13
+ "\"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!",
14
+ "*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!",
15
+ "*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!",
16
+ "*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!",
15
17
  ];
16
18
 
17
19
  export const FORCED_CONTINUATIONS: readonly string[] = [
18
- "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.",
19
- "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.",
20
+ "\"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!",
21
+ "\"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!",
22
+ "*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!",
23
+ "*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!",
24
+ "\"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!",
20
25
  ];
21
-
22
- /**
23
- * Pick one whole paragraph for a continuation that is being created right now, and only then:
24
- * the caller persists the exact returned text and never redraws it for rendering, history, or repair.
25
- */
26
26
  export function selectContinuation(origin: ResetOrigin): string {
27
27
  const pool = origin === "forced" ? FORCED_CONTINUATIONS : NORMAL_CONTINUATIONS;
28
28
  return pool[Math.floor(Math.random() * pool.length)]!;