notesoup 0.57.2 → 0.57.4

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)];
@@ -37,7 +37,7 @@ export type EditOptions = {
37
37
  renameTo?: string;
38
38
  };
39
39
  /** Omitted/null/empty glob or bare @default selects current notebooks; explicit globs match full addresses.
40
- * Only the current session also matches its bare-path alias (e.g. *.md or deep/**).
40
+ * A pattern without `@` or `/` matches filenames at any depth; relative paths with `/` match the current session.
41
41
  */
42
42
  export type NotesQuery = {
43
43
  glob?: string | null;
@@ -126,10 +126,12 @@ async function namespacesForPattern(pattern, identity, status) {
126
126
  }
127
127
  return namespaces;
128
128
  }
129
- /** Relative pattern heads resolve to canonical names, so they match canonical addresses. */
129
+ /** Relative pattern heads resolve to canonical names; slashless bare patterns match filenames at any depth. */
130
130
  function normalizePattern(pattern, identity) {
131
131
  if (!pattern)
132
132
  return pattern;
133
+ if (!pattern.startsWith("@") && !pattern.includes("/"))
134
+ return `**/${pattern}`;
133
135
  if (pattern.startsWith("@project/"))
134
136
  return `@projects/${identity.projectKey}/${pattern.slice("@project/".length)}`;
135
137
  if (pattern.startsWith("@self/"))
@@ -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\`.