notesoup 0.57.0 → 0.57.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,5 +6,4 @@ export declare const RESET_MARKER_TYPE = "notesoup/reset-marker";
6
6
  export declare const CONTINUATION_TYPE = "notesoup/continuation";
7
7
  export declare const RESET_LAST_WORD_TYPE = "notesoup/reset-last-word";
8
8
  export declare const CARRIED_INPUT_TYPE = "notesoup/carried-input";
9
- export declare const NEXT_WINDOW_PROMPT_TYPE = "notesoup/next-window-prompt";
10
9
  export declare const MARKER_TYPE = "notesoup/marker";
@@ -6,5 +6,4 @@ export const RESET_MARKER_TYPE = "notesoup/reset-marker";
6
6
  export const CONTINUATION_TYPE = "notesoup/continuation";
7
7
  export const RESET_LAST_WORD_TYPE = "notesoup/reset-last-word";
8
8
  export const CARRIED_INPUT_TYPE = "notesoup/carried-input";
9
- export const NEXT_WINDOW_PROMPT_TYPE = "notesoup/next-window-prompt";
10
9
  export const MARKER_TYPE = "notesoup/marker";
@@ -76,13 +76,14 @@ export type ResetControlEvent = {
76
76
  readonly facts: ResetBeforeSettleFacts;
77
77
  };
78
78
  /** Construction intent, not final state: handled inputs can still arrive while notes load. Only `turn-end`
79
- * may latch a stop; overflow kinds spend recovery; only `overflow-recovery` carries passive run inputs. */
79
+ * may latch a stop; overflow kinds spend recovery; only hard-reserve and overflow carry passive run inputs. */
80
80
  export interface ResetBoundaryIntent {
81
81
  readonly effect: "build-boundary";
82
82
  readonly boundary: "turn-end" | "settle" | "command-overflow" | "overflow-recovery";
83
83
  readonly windowId: string;
84
84
  readonly continueAfterReset: boolean;
85
85
  readonly origin: ResetOrigin;
86
+ readonly carryRunInputs?: boolean;
86
87
  readonly tool?: {
87
88
  readonly lastWord?: string;
88
89
  };
@@ -1,4 +1,3 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
3
2
  import { currentReset, currentWindowId } from "../window.js";
4
3
  import { nextHistorySeq } from "../history.js";
@@ -6,8 +5,6 @@ import { buildMarkerDraft } from "../marker.js";
6
5
  import { resetBoundaryCommitted } from "./committed.js";
7
6
  import { errorMessage } from "../../../src/error-message.js";
8
7
  import { carriedInputDrafts, isCarriedInputEntry } from "./artifacts.js";
9
- import { NEXT_WINDOW_PROMPT_TYPE } from "../entries.js";
10
- import { promptBlock } from "../text.js";
11
8
  function isAbort(message, outcome, ctx) {
12
9
  return outcome === "aborted" || (message.role === "assistant" && message.stopReason === "aborted") || ctx.signal?.aborted === true;
13
10
  }
@@ -25,15 +22,15 @@ function requestForWindow(request, windowId) {
25
22
  return request.phase === "pending" && request.windowId === windowId ? request : NO_REQUEST;
26
23
  }
27
24
  const spendsOverflow = (boundary) => boundary === "command-overflow" || boundary === "overflow-recovery";
28
- function boundaryIntent(request, windowId, boundary) {
25
+ function boundaryIntent(request, windowId, boundary, carryRunInputs = false) {
29
26
  const tool = request.phase === "none" ? undefined : request.tool;
30
27
  const continueAfterReset = request.phase === "pending" ? request.command?.continueAfterReset ?? true : true;
31
- return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal" };
28
+ return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal", ...(carryRunInputs ? { carryRunInputs: true } : {}) };
32
29
  }
33
30
  /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
34
31
  export function finalizeResetBoundary(intent, request, passiveInputs = []) {
35
32
  const inputs = request.phase === "pending" && request.command ? request.command.inputs ?? []
36
- : intent.boundary === "overflow-recovery" ? passiveInputs : [];
33
+ : intent.boundary === "overflow-recovery" || intent.carryRunInputs ? passiveInputs : [];
37
34
  const resumeModel = intent.continueAfterReset || inputs.length > 0;
38
35
  const state = {
39
36
  request: NO_REQUEST,
@@ -90,8 +87,9 @@ export function reduceResetControl(state, event) {
90
87
  }
91
88
  // A direct tool request commits after the whole tool batch. The budget cutoff is
92
89
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
93
- if ((request.phase === "pending" && request.tool && !manual) || facts.hardReserveDue) {
94
- return boundaryIntent(request, facts.windowId, "turn-end");
90
+ const toolReset = request.phase === "pending" && request.tool !== undefined;
91
+ if ((toolReset && !manual) || facts.hardReserveDue) {
92
+ return boundaryIntent(request, facts.windowId, "turn-end", !manual && !toolReset && facts.hardReserveDue);
95
93
  }
96
94
  return { state: { request, overflow: "idle" }, effect: "none" };
97
95
  }
@@ -146,17 +144,16 @@ export function registerResetLifecycle(pi, options) {
146
144
  let lifecycleGeneration = 0;
147
145
  let control = initialResetControl();
148
146
  let runInputs = [];
149
- let commandId;
150
147
  // Once input returns handled, Pi no longer owns its original content. If close-out
151
- // fails/cancels, return that content to the transcript without starting another run.
152
- const restoreCommandInputs = () => {
148
+ // fails/cancels, restore it; only an ordinary error starts a turn to answer it.
149
+ const restoreCommandInputs = (triggerTurn = false) => {
153
150
  const request = control.request;
154
151
  if (request.phase !== "pending" || !request.command?.inputs?.length)
155
152
  return;
156
153
  const inputs = request.command.inputs;
157
154
  control = { ...control, request: { ...request, command: { ...request.command, inputs: [] } } };
158
155
  for (const draft of carriedInputDrafts(inputs)) {
159
- pi.sendMessage(draft, { triggerTurn: false });
156
+ pi.sendMessage(draft, { triggerTurn });
160
157
  }
161
158
  runInputs.push(...inputs);
162
159
  };
@@ -166,11 +163,9 @@ export function registerResetLifecycle(pi, options) {
166
163
  restoreCommandInputs();
167
164
  control = initialResetControl();
168
165
  runInputs = [];
169
- commandId = undefined;
170
166
  };
171
167
  const resetBoundaryResult = async (entries, ctx, intent) => {
172
- // Keep command state live while notes load: input arriving during this await must
173
- // join this very boundary even if its steer cannot reach the closing model.
168
+ // Keep command state live while notes load so input arriving during this await joins this boundary.
174
169
  const generation = lifecycleGeneration;
175
170
  const outerGeneration = options.getLifecycleGeneration?.();
176
171
  const sessionId = ctx.sessionManager.getSessionId();
@@ -213,37 +208,22 @@ export function registerResetLifecycle(pi, options) {
213
208
  ? [{ type: "text", text: event.text }, ...event.images]
214
209
  : event.text;
215
210
  control = reduceResetControl(control, { type: "input", windowId: request.windowId, input: content }).state;
216
- const steerContent = event.images?.length
217
- ? [{ type: "text", text: promptBlock(event.text) }, ...event.images]
218
- : promptBlock(event.text);
219
- pi.sendMessage({ customType: NEXT_WINDOW_PROMPT_TYPE, content: steerContent, display: false, details: { windowId: request.windowId, commandId } }, { deliverAs: "steer" });
220
211
  return { action: "handled" };
221
212
  });
222
213
  // Boundary continue:false is not a veto of Pi's tool-batch follow-up. Once the
223
214
  // safety reset is actually committed, cancel that empty follow-up before provider
224
215
  // work. Real queued user input is allowed through and answered before settlement.
225
216
  pi.on("context_with_system", (event, ctx) => {
226
- const request = control.request;
227
- // Steering can be queued during buildReset's await and arrive after the boundary.
228
- // It is closing-model context only; originals already live in the carried entries.
229
- const messages = event.messages.filter((message) => {
230
- if (message.role !== "custom" || message.customType !== NEXT_WINDOW_PROMPT_TYPE)
231
- return true;
232
- const details = message.details;
233
- return request.phase === "pending" && request.command !== undefined &&
234
- request.windowId === currentWindowId(ctx) && details?.windowId === request.windowId && commandId !== undefined && details?.commandId === commandId;
235
- });
236
- const filtered = messages.length === event.messages.length ? undefined : { messages };
237
217
  const stop = control.stopAfterReset;
238
218
  if (!sessionActive || !stop || ctx.hasPendingMessages())
239
- return filtered;
219
+ return undefined;
240
220
  const marker = currentReset(ctx);
241
221
  if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId))
242
- return filtered;
222
+ return undefined;
243
223
  const branch = ctx.sessionManager.getBranch();
244
224
  const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
245
225
  if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry)))
246
- return filtered;
226
+ return undefined;
247
227
  ctx.abort();
248
228
  const system = getCurrentSystemMessage(event.messages);
249
229
  return { messages: system ? [system] : [] };
@@ -270,9 +250,14 @@ export function registerResetLifecycle(pi, options) {
270
250
  });
271
251
  if (decision.effect === "build-boundary")
272
252
  return await resetBoundaryResult(entries, ctx, decision);
273
- if (aborted || (event.outcome === "error" && decision.state.request.phase === "none"))
253
+ if (aborted)
274
254
  restoreCommandInputs();
255
+ else if (event.outcome === "error" && decision.state.request.phase === "none")
256
+ restoreCommandInputs(true);
275
257
  control = decision.state;
258
+ if (!aborted && event.outcome === "completed" && event.message.role === "assistant" && event.message.stopReason === "stop" &&
259
+ event.context.pendingMessages.length === 0 && !ctx.hasPendingMessages())
260
+ runInputs = [];
276
261
  if (!aborted && event.outcome !== "error" && options.isEnabled()) {
277
262
  const marker = buildMarkerDraft(ctx, entries);
278
263
  if (marker)
@@ -331,8 +316,6 @@ export function registerResetLifecycle(pi, options) {
331
316
  command(windowId, continueAfterReset, input) {
332
317
  const decision = reduceResetControl(control, { type: "command", windowId, continueAfterReset, ...(input !== undefined ? { input } : {}) });
333
318
  control = decision.state;
334
- if (decision.effect === "close-out-armed")
335
- commandId = randomUUID();
336
319
  return decision.effect;
337
320
  },
338
321
  request(windowId, lastWord) {
@@ -3,7 +3,7 @@ import { resetBoundaryCommitted } from "./reset/committed.js";
3
3
  import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
4
4
  import { VERSION, defineTool } from "@earendil-works/pi-coding-agent";
5
5
  import { registerBudget } from "./budget.js";
6
- import { output } from "./tool-result.js";
6
+ import { DREAM_NAMESPACE, HISTORY_NAMESPACE, NOTES_NAMESPACE, output } from "./tool-result.js";
7
7
  import { emptyBrainRenderers } from "./render.js";
8
8
  import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, markerResetOrigin, projectRootWindow, projectWindow, rootWindowId } from "./window.js";
9
9
  import { registerResetLifecycle } from "./reset/lifecycle.js";
@@ -26,6 +26,9 @@ function readPackageVersion() {
26
26
  return "dev";
27
27
  }
28
28
  const buildLabel = `v${readPackageVersion()}`;
29
+ const notesoupTools = [NOTES_NAMESPACE, HISTORY_NAMESPACE, DREAM_NAMESPACE]
30
+ .map(({ name, description }) => `${name}: ${description}`)
31
+ .join("\n") + "\nDiscover deferred tools through codemode or tool_search when available.";
29
32
  function branchHasWindowMarker(ctx, fromId) {
30
33
  return ctx.sessionManager.getBranch(fromId).some((entry) => isWindowMarker(entry));
31
34
  }
@@ -78,7 +81,8 @@ export function registerContext(pi, settingsManager) {
78
81
  ctx.ui.notify("🥣 Brain forcibly emptied: overflow", "warning");
79
82
  }
80
83
  };
81
- pi.on("before_agent_start", (_event, ctx) => {
84
+ pi.on("before_agent_start", (event, ctx) => {
85
+ event.systemPromptOptions.sections.notesoup_tools = notesoupTools;
82
86
  if (enabled)
83
87
  maybeSendMarker(pi, ctx);
84
88
  });
@@ -8,8 +8,6 @@ export declare const PI_PRE_RESET_HINTS = "Anything you say here is erased with
8
8
  export { warningNotice as warningContent } from "../../src/budget/text.js";
9
9
  /** Odometer breadcrumb: the marker names its own seq, so history paging reads the landscape directly. */
10
10
  export declare function markerContent(seq: number): string;
11
- /** The closing model sees deferred input as a bare next-window prompt block. */
12
- export declare function promptBlock(commandLine: string): string;
13
11
  /** Approved manual close-out notices; both variants live here. */
14
12
  export declare const COMMAND_NOTICE: {
15
13
  prompted: string;
@@ -12,10 +12,6 @@ export { warningNotice as warningContent } from "../../src/budget/text.js";
12
12
  export function markerContent(seq) {
13
13
  return `<notesoup:marker seq="${seq}" />`;
14
14
  }
15
- /** The closing model sees deferred input as a bare next-window prompt block. */
16
- export function promptBlock(commandLine) {
17
- return `<notesoup:next_window_prompt>\n${commandLine}\n</notesoup:next_window_prompt>`;
18
- }
19
15
  /** Approved manual close-out notices; both variants live here. */
20
16
  export const COMMAND_NOTICE = {
21
17
  prompted: "The human ran /empty. Save your notes now and call `empty_brain` immediately. Anything you say here will be erased afterward — put the handoff in your notes. The command below is context for your notes, not a task for the fresh window. Anything the human sends separately from now on should be handled after the reset.",
@@ -24,5 +20,5 @@ export const COMMAND_NOTICE = {
24
20
  /** Manual orders omit budget timing hints; deferred work sits outside the notice. */
25
21
  export function commandWarningContent(commandLine) {
26
22
  const notice = commandLine ? COMMAND_NOTICE.prompted : COMMAND_NOTICE.bare;
27
- return `${GUIDANCE_OPEN_TAG}\n${notice}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}${commandLine ? `\n${promptBlock(commandLine)}` : ""}`;
23
+ return `${GUIDANCE_OPEN_TAG}\n${notice}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}${commandLine ? `\n${commandLine}` : ""}`;
28
24
  }
@@ -6,16 +6,14 @@ import test from "node:test";
6
6
  import { createAssistantMessageEventStream, getCurrentSystemMessage } from "@earendil-works/pi-ai";
7
7
  import { createAgentSession, createCodemodeExtension, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
8
8
  import notesoup, { createNotesoup } from "../plugins/pi/extension.js";
9
- import { BOOT_TYPE, CARRIED_INPUT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, MARKER_TYPE, NEXT_WINDOW_PROMPT_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
9
+ import { BOOT_TYPE, CARRIED_INPUT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, MARKER_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
10
10
  import { historyFromSession } from "../plugins/pi/history.js";
11
11
  import { MARKER_INTERVAL } from "../plugins/pi/marker.js";
12
12
  import { assertBootHistory } from "./helpers/extension.js";
13
13
  import { NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
14
14
  import { FORCED_CONTINUATIONS, GUIDANCE_OPEN_TAG, NORMAL_CONTINUATIONS, warningPrompt } from "../src/budget/text.js";
15
- import { commandWarningContent, promptBlock } from "../plugins/pi/text.js";
16
- import { registerResetLifecycle } from "../plugins/pi/reset/lifecycle.js";
17
- import { buildResetDrafts } from "../plugins/pi/reset/artifacts.js";
18
- import { currentWindowId } from "../plugins/pi/window.js";
15
+ import { commandWarningContent } from "../plugins/pi/text.js";
16
+ import { DREAM_NAMESPACE, HISTORY_NAMESPACE, NOTES_NAMESPACE } from "../plugins/pi/tool-result.js";
19
17
  async function openFixture(options) {
20
18
  const dir = options.cwd ?? mkdtempSync(join(tmpdir(), "notesoup-agent-loop-"));
21
19
  const ownsDir = options.cwd === undefined;
@@ -278,6 +276,49 @@ test("real AgentSession: turn-end markers reach tool continuations and allow one
278
276
  }
279
277
  }
280
278
  });
279
+ test("real AgentSession: notesoup tool directory is a stable system section across requests and reset", async () => {
280
+ let fixture;
281
+ let directory;
282
+ const activeTools = ["empty_brain", "get_context_remaining", "notes_write"];
283
+ const namespaces = [NOTES_NAMESPACE, HISTORY_NAMESPACE, DREAM_NAMESPACE];
284
+ fixture = await openFixture({
285
+ compactionEnabled: false,
286
+ tools: activeTools,
287
+ hook: (pi) => pi.on("before_agent_start", (event) => {
288
+ event.systemPromptOptions.sections.host_context = "Host-owned context";
289
+ }),
290
+ script: (request, context) => {
291
+ const system = getCurrentSystemMessage(context.messages);
292
+ const section = system?.sections?.notesoup_tools;
293
+ assert.equal(typeof section, "string", "the directory reaches the model as a named system section");
294
+ for (const { name, description } of namespaces)
295
+ assert.ok(section.includes(`${name}: ${description}`));
296
+ assert.ok(system?.sections?.preamble?.includes("Use the tools as requested."), "the host prompt is preserved");
297
+ assert.ok(system?.sections?.host_context?.includes("Host-owned context"), "other sections are preserved");
298
+ assert.deepEqual(system?.toolsAdded?.map((tool) => tool.name).sort(), activeTools, "discovery does not activate tools");
299
+ if (directory === undefined)
300
+ directory = section;
301
+ else
302
+ assert.equal(section, directory, "the directory is unchanged across requests and reset");
303
+ assert.equal(context.messages.filter((message) => message.role === "system" && message.sections?.notesoup_tools !== undefined).length, 1, "unchanged content adds no section delta");
304
+ return request === 2
305
+ ? assistant(fixture, [{ type: "toolCall", id: "directory-reset", name: "empty_brain", arguments: {} }], "toolUse")
306
+ : assistant(fixture, [{ type: "text", text: "directory available" }]);
307
+ },
308
+ });
309
+ try {
310
+ await fixture.session.prompt("Read the directory.");
311
+ await fixture.session.waitForIdle();
312
+ await fixture.session.prompt("DIRECTORY_RESET_SENTINEL");
313
+ await fixture.session.waitForIdle();
314
+ assert.equal(fixture.requests.length, 3, "two prompts and one reset continuation");
315
+ assert.equal(resetMarkers(fixture).length, 1);
316
+ assertFreshRequest(fixture, 2, "DIRECTORY_RESET_SENTINEL");
317
+ }
318
+ finally {
319
+ fixture.close();
320
+ }
321
+ });
281
322
  test("real Pi codemode receives typed notes/history outcomes, including expected errors", async () => {
282
323
  let fixture;
283
324
  fixture = await openFixture({
@@ -509,6 +550,31 @@ test("real AgentSession: explicit tiny-session wipe ignores keepRecentTokens and
509
550
  fixture.close();
510
551
  }
511
552
  });
553
+ test("real AgentSession: a model-requested reset does not carry its original text-and-image prompt", async () => {
554
+ let fixture;
555
+ const input = "IMAGE_RESET_UNANSWERED: describe this image";
556
+ const image = { type: "image", data: "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAn0lEQVRoge2SQQkAQRDD6qSOT20ErIh7hIFCBKSh4etpohuwAdUrsgv1LtEN2IDqFdmFepfoBmxA9YrsQr1LdAM2oHpFdqHeJboBG1C9IrtQ7xLdgA2oXpFdqHeJbsAGVK/ILtS7RDdgA6pXZBfqXaIbsAHVK7IL9S7RDdiA6hXZhXqX6AZsQPWK7EK9S3QDNqB6RXah3iW6ARtQveIfHlqMEYdT3J7gAAAAAElFTkSuQmCC", mimeType: "image/png" };
557
+ fixture = await openFixture({
558
+ compactionEnabled: false,
559
+ script: (request, context) => {
560
+ if (request === 1)
561
+ return assistant(fixture, [{ type: "toolCall", id: "wipe-image-input", name: "empty_brain", arguments: {} }], "toolUse");
562
+ assert.equal(request, 2);
563
+ assert.equal(JSON.stringify(context.messages).includes(input) || JSON.stringify(context.messages).includes(image.data), false, "the model-requested reset does not replay the input it already received");
564
+ return assistant(fixture, [{ type: "text", text: "image prompt answered" }]);
565
+ },
566
+ });
567
+ try {
568
+ await fixture.session.prompt(input, { images: [image] });
569
+ await fixture.session.waitForIdle();
570
+ assert.equal(fixture.requests.length, 2);
571
+ const carried = fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE);
572
+ assert.equal(carried.length, 0, "a model-requested reset owns its handoff through notes and last_word");
573
+ }
574
+ finally {
575
+ fixture.close();
576
+ }
577
+ });
512
578
  test("real AgentSession: manual command spans its tool batch and stops at settlement", async () => {
513
579
  let fixture;
514
580
  fixture = await openFixture({
@@ -566,7 +632,7 @@ test("real AgentSession: /empty text is close-out context and stops after reset"
566
632
  if (request === 1)
567
633
  return assistant(fixture, [{ type: "text", text: "initial work" }]);
568
634
  if (request === 2) {
569
- assert.ok(text(context).includes(JSON.stringify(promptBlock(`/empty ${prompt}`)).slice(1, -1)));
635
+ assert.ok(text(context).includes(JSON.stringify(`/empty ${prompt}`).slice(1, -1)));
570
636
  return assistant(fixture, [{ type: "toolCall", id: "prompt-wipe", name: "empty_brain", arguments: { last_word: "saved" } }], "toolUse");
571
637
  }
572
638
  throw new Error("command argument must not start fresh-window work");
@@ -624,7 +690,7 @@ test("real AgentSession: streaming clear prompt keeps the first request", async
624
690
  // The close-out embeds the human's command line verbatim, so the closing turn sees
625
691
  // the command context. Only the accepted command appears.
626
692
  if (request === 2) {
627
- assert.ok(text(context).includes(JSON.stringify(promptBlock("/fresh-window FIRST_RESET_PROMPT")).slice(1, -1)), "the close-out carries the original command line");
693
+ assert.ok(text(context).includes(JSON.stringify("/fresh-window FIRST_RESET_PROMPT").slice(1, -1)), "the close-out carries the original command line as plain text");
628
694
  assert.equal(text(context).includes("IGNORED_RESET_PROMPT"), false, "the refused repeat never enters the close-out");
629
695
  }
630
696
  assert.ok(request <= 2);
@@ -649,6 +715,31 @@ test("real AgentSession: streaming clear prompt keeps the first request", async
649
715
  fixture.close();
650
716
  }
651
717
  });
718
+ test("real AgentSession: hard-reserve reset carries the original text and image and continues", async () => {
719
+ let fixture;
720
+ const input = "HARD_RESERVE_IMAGE_INPUT";
721
+ const image = { type: "image", data: "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAn0lEQVRoge2SQQkAQRDD6qSOT20ErIh7gIFCBKSh4et1LtEN2IDqFdmFepfoBmxA9YrsQr1LdAM2oHpFdqHeJboBG1C9IrtQ7xLdgA2oXpFdqHeJbsAGVK/ILtS7RDdgA6pXZBfqXaIbsAHVK7IL9S7RDdiA6hXZhXqX6AZsQPWK7EK9S3QDNqB6RXah3iW6ARtQveIfHlqMEYdT3J7gAAAAAElFTkSuQmCC", mimeType: "image/png" };
722
+ fixture = await openFixture({
723
+ defaultReserveTokens: 80_000,
724
+ script: (request, context) => {
725
+ if (request === 1)
726
+ return assistant(fixture, [{ type: "text", text: "reserve reached" }], "stop", { usage: usage(80_000) });
727
+ assert.equal(request, 2);
728
+ assertUserContent(context, [{ type: "text", text: input }, image]);
729
+ return assistant(fixture, [{ type: "text", text: "carried image answered" }]);
730
+ },
731
+ });
732
+ try {
733
+ await fixture.session.prompt(input, { images: [image] });
734
+ await fixture.session.waitForIdle();
735
+ assert.equal(fixture.requests.length, 2);
736
+ assert.equal(resetMarkers(fixture).length, 1);
737
+ assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE).length, 1);
738
+ }
739
+ finally {
740
+ fixture.close();
741
+ }
742
+ });
652
743
  test("real AgentSession: manual hard-reserve reset stops clean and mixed-tool turns without fresh provider work", async () => {
653
744
  for (const mixed of [false, true]) {
654
745
  let fixture;
@@ -835,98 +926,48 @@ test("real AgentSession: user abort, synthetic aborted response, and generic err
835
926
  }
836
927
  }
837
928
  });
838
- test("real AgentSession: input during prompted /empty is hidden-steered, carried with images, and answered after a safety reset", async () => {
929
+ test("real AgentSession: input during prompted /empty is carried with images and answered after reset", async () => {
839
930
  let fixture;
840
- let started;
841
- let release;
842
- const ready = new Promise((resolve) => { started = resolve; });
843
- const gate = new Promise((resolve) => { release = resolve; });
931
+ let closeoutStarted;
932
+ let releaseCloseout;
933
+ const closeoutReady = new Promise((resolve) => { closeoutStarted = resolve; });
934
+ const closeoutGate = new Promise((resolve) => { releaseCloseout = resolve; });
844
935
  const input = "DEFERRED_HUMAN_INPUT\n verbatim";
845
936
  const image = { type: "image", data: "aGVsbG8=", mimeType: "image/png" };
846
937
  fixture = await openFixture({
847
938
  script: async (request, context) => {
848
939
  if (request === 1) {
849
- started();
850
- await gate;
851
- return assistant(fixture, [{ type: "text", text: "saving notes" }]);
940
+ closeoutStarted();
941
+ await closeoutGate;
942
+ assert.ok(text(context).includes(JSON.stringify(commandWarningContent("/empty CLOSE_OUT_CONTEXT")).slice(1, -1)));
943
+ assert.equal(text(context).includes(input), false, "the separate input is not sent to the closing model");
944
+ assert.equal(text(context).includes("next_window_prompt"), false, "no hidden steer reaches the provider");
945
+ return assistant(fixture, [{ type: "text", text: "close-out ready for reset" }], "stop", { usage: usage(80_000) });
852
946
  }
853
- if (request === 2) {
854
- assertUserContent(context, [{ type: "text", text: promptBlock(input) }, image]);
855
- return assistant(fixture, [{ type: "toolCall", id: "deferred-pressure", name: "notes_write", arguments: { address: "deferred.md", content: "saved" } }], "toolUse", { usage: usage(80_000) });
856
- }
857
- assert.equal(request, 3, "carried input continues despite command stop policy");
858
- assertFreshRequest(fixture, 2, "saving notes");
947
+ assert.equal(request, 2, "the intercepted input resumes in the fresh window");
859
948
  assertUserContent(context, [{ type: "text", text: input }, image]);
949
+ assert.equal(text(context).includes("CLOSE_OUT_CONTEXT"), false, "the fresh window excludes old-window close-out text");
950
+ assert.equal(text(context).includes("next_window_prompt"), false, "the fresh provider request contains no hidden steer");
860
951
  return assistant(fixture, [{ type: "text", text: "deferred input answered" }]);
861
952
  },
862
953
  });
863
954
  try {
864
- const command = fixture.session.prompt("/empty CLOSE_OUT_CONTEXT");
865
- await ready;
955
+ const closing = fixture.session.prompt("/empty CLOSE_OUT_CONTEXT");
956
+ await closeoutReady;
866
957
  await fixture.session.prompt(input, { images: [image], streamingBehavior: "followUp" });
867
- release();
868
- await command;
869
- await fixture.session.waitForIdle();
870
- assert.equal(fixture.requests.length, 3);
871
- assert.equal(resetMarkers(fixture).length, 1);
872
- const branch = fixture.sessionManager.getBranch();
873
- const steer = branch.find((entry) => entry.type === "custom_message" && entry.customType === NEXT_WINDOW_PROMPT_TYPE);
874
- assert.ok(steer?.type === "custom_message");
875
- assert.equal(steer.display, false);
876
- assert.deepEqual(steer.content, [{ type: "text", text: promptBlock(input) }, image], "the bare block and original images reach the closing model");
877
- assert.equal(branch.filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE).length, 1);
878
- assert.equal(fixture.streamSignals.at(-1), false, "the stop-pending safeguard cannot swallow carried input");
879
- }
880
- finally {
881
- release();
882
- fixture.close();
883
- }
884
- });
885
- test("real AgentSession: a hidden steer queued during reset construction is not replayed beside carried input", async () => {
886
- let fixture;
887
- let started;
888
- let release;
889
- const building = new Promise((resolve) => { started = resolve; });
890
- const gate = new Promise((resolve) => { release = resolve; });
891
- const input = "LATE_BUILD_INPUT";
892
- fixture = await openFixture({
893
- tools: [],
894
- extensionFactory: (pi) => {
895
- const lifecycle = registerResetLifecycle(pi, {
896
- isEnabled: () => true,
897
- budget: { automaticResetEnabled: () => false, hardReserveDue: () => false, consumeTurnEnd: () => [], clear() { } },
898
- async buildReset(ctx, isCurrent, lastWord, firstSeq, origin) {
899
- started();
900
- await gate;
901
- return buildResetDrafts(ctx, undefined, isCurrent, lastWord, firstSeq, origin);
902
- },
903
- });
904
- pi.on("before_agent_start", (_event, ctx) => { lifecycle.command(currentWindowId(ctx), false); });
905
- },
906
- script: (request, context) => {
907
- if (request === 1)
908
- return assistant(fixture, [{ type: "text", text: "closing old window" }]);
909
- assert.equal(request, 2);
910
- assertUserContent(context, [{ type: "text", text: input }]);
911
- assert.equal(text(context).includes("notesoup:next_window_prompt"), false, "the stale queued steer must not duplicate the carried input");
912
- return assistant(fixture, [{ type: "text", text: "late input answered" }]);
913
- },
914
- });
915
- try {
916
- const closing = fixture.session.prompt("close out");
917
- await building;
918
- await fixture.session.prompt(input, { streamingBehavior: "steer" });
919
- release();
958
+ releaseCloseout();
920
959
  await closing;
921
960
  await fixture.session.waitForIdle();
922
961
  assert.equal(fixture.requests.length, 2);
923
- assert.equal(text(fixture.requests[1]).includes("notesoup:next_window_prompt"), false);
924
962
  const branch = fixture.sessionManager.getBranch();
925
- const markerIndex = branch.findIndex((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE);
926
- assert.ok(branch.slice(markerIndex + 1).some((entry) => entry.type === "custom_message" && entry.customType === NEXT_WINDOW_PROMPT_TYPE), "Pi really delivered the queued steer after committing the boundary");
963
+ assert.equal(branch.some((entry) => entry.type === "custom_message" && JSON.stringify(entry).includes("next-window-prompt")), false, "the branch contains no next-window steer");
964
+ assert.equal(resetMarkers(fixture).length, 1, "one reset marker commits at settlement");
965
+ const carried = branch.filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE);
966
+ assert.equal(carried.length, 1);
967
+ assert.deepEqual(carried[0]?.type === "custom_message" ? carried[0].content : undefined, [{ type: "text", text: input }, image]);
927
968
  }
928
969
  finally {
929
- release();
970
+ releaseCloseout();
930
971
  fixture.close();
931
972
  }
932
973
  });
@@ -948,7 +989,6 @@ test("real AgentSession: abort after handled input preserves originals without f
948
989
  }
949
990
  assert.equal(request, 2);
950
991
  assertUserContent(context, original);
951
- assert.equal(text(context).includes("notesoup:next_window_prompt"), false);
952
992
  return assistant(fixture, [{ type: "text", text: "resumed after abort" }]);
953
993
  },
954
994
  });
@@ -973,7 +1013,7 @@ test("real AgentSession: abort after handled input preserves originals without f
973
1013
  fixture.close();
974
1014
  }
975
1015
  });
976
- test("real AgentSession: a close-out error does not discard handled input", async () => {
1016
+ test("real AgentSession: a close-out error answers handled input without resetting", async () => {
977
1017
  let fixture;
978
1018
  let started;
979
1019
  let release;
@@ -989,7 +1029,7 @@ test("real AgentSession: a close-out error does not discard handled input", asyn
989
1029
  }
990
1030
  assert.equal(request, 2);
991
1031
  assertUserContent(context, [{ type: "text", text: "ERROR_HANDLED_INPUT" }]);
992
- assert.equal(text(context).includes("notesoup:next_window_prompt"), false);
1032
+ assert.equal(text(context).includes("next_window_prompt"), false, "no hidden steer reaches the provider");
993
1033
  return assistant(fixture, [{ type: "text", text: "handled input answered without reset" }]);
994
1034
  },
995
1035
  });
@@ -1000,11 +1040,12 @@ test("real AgentSession: a close-out error does not discard handled input", asyn
1000
1040
  release();
1001
1041
  await closing;
1002
1042
  await fixture.session.waitForIdle();
1003
- const originals = fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE);
1004
- assert.equal(originals.length, 1);
1005
1043
  assert.equal(fixture.requests.length, 2);
1006
1044
  assertUserContent(fixture.requests[1], [{ type: "text", text: "ERROR_HANDLED_INPUT" }]);
1007
- assert.equal(resetMarkers(fixture).length, 0, "ordinary errors still do not force a reset");
1045
+ const originals = fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE);
1046
+ assert.equal(originals.length, 1, "the failed close-out restores one visible copy");
1047
+ assert.deepEqual(originals[0]?.type === "custom_message" ? originals[0].content : undefined, "ERROR_HANDLED_INPUT");
1048
+ assert.equal(resetMarkers(fixture).length, 0, "ordinary errors do not force a reset");
1008
1049
  }
1009
1050
  finally {
1010
1051
  release();
@@ -1167,7 +1208,7 @@ test("real AgentSession: two retain-none checkpoints survive session-file reopen
1167
1208
  assert.equal(branch.filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE).length, 2);
1168
1209
  assert.ok(JSON.stringify(branch).includes("PERSISTED_OLD_WINDOW_SENTINEL"), "raw history survives disk reopen");
1169
1210
  const canonical = reopened.buildSessionProjection().messages;
1170
- assert.equal(JSON.stringify(canonical).includes("PERSISTED_OLD_WINDOW_SENTINEL"), false, "disk-loaded canonical context agrees with the fresh request");
1211
+ assert.equal(JSON.stringify(canonical).includes("PERSISTED_OLD_WINDOW_SENTINEL"), false, "model-requested resets do not carry the original prompt");
1171
1212
  assert.ok(canonical.some((message) => message.role === "compactionSummary"), "the accepted empty-summary wrapper survives reload");
1172
1213
  const system = getCurrentSystemMessage(canonical);
1173
1214
  assert.ok(JSON.stringify(system).includes("Use the tools as requested."), "the complete system prompt survives the checkpoint");
@@ -1364,7 +1405,7 @@ test("real AgentSession: overflow and recoverable length reset and retry once; r
1364
1405
  assert.equal(repeated.sessionManager.getBranch().filter((entry) => entry.type === "compaction").length, 2);
1365
1406
  assert.equal(repeated.requests.length, 3, "an automatic continuation still gets only one recovery request");
1366
1407
  assertFreshRequest(repeated, 2, "REPEATED_OVERFLOW_SENTINEL");
1367
- assert.equal(repeated.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE).length, 0, "our own automatic continuation has no human input to carry");
1408
+ assert.equal(repeated.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE).length, 0, "model-owned reset and its input-free continuation do not carry the original prompt");
1368
1409
  }
1369
1410
  finally {
1370
1411
  repeated.close();
@@ -10,7 +10,7 @@ test.beforeEach(env.beforeEach);
10
10
  test.afterEach(env.afterEach);
11
11
  test.after(env.dispose);
12
12
  function beforeAgentStart(captured, ctx) {
13
- return runHandlers(captured, "before_agent_start", { type: "before_agent_start" }, ctx);
13
+ return runHandlers(captured, "before_agent_start", { type: "before_agent_start", systemPromptOptions: { sections: {} } }, ctx);
14
14
  }
15
15
  test("marker stamps its own seq at run start once the interval is reached, never mid-turn", async () => {
16
16
  const sessionManager = managerWithMessages(99);
@@ -98,10 +98,9 @@ test("the countdown closes the second-tier notice only, in both hosts", () => {
98
98
  assert.equal(CLAUDE_WARNING_PROMPT, pi, "Pi and Claude receive identical copy");
99
99
  assert.equal(pi.split(COUNTDOWN_LINE).length - 1, 1, "the second tier carries the countdown exactly once");
100
100
  const prompted = commandWarningContent("/empty keep going");
101
- assert.ok(prompted.includes("<notesoup:next_window_prompt>\n/empty keep going\n</notesoup:next_window_prompt>"));
102
- assert.ok(prompted.includes(`\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}\n<notesoup:next_window_prompt>`), "the prompt block follows the closed notice");
101
+ assert.equal(prompted, `${GUIDANCE_OPEN_TAG}\n${COMMAND_NOTICE.prompted}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}\n/empty keep going`);
103
102
  assert.equal(commandWarningContent(), `${GUIDANCE_OPEN_TAG}\n${COMMAND_NOTICE.bare}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}`);
104
- assert.equal(prompted, `${GUIDANCE_OPEN_TAG}\n${COMMAND_NOTICE.prompted}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}\n<notesoup:next_window_prompt>\n/empty keep going\n</notesoup:next_window_prompt>`);
103
+ assert.ok(prompted.endsWith("\n/empty keep going"), "command text remains plain close-out context");
105
104
  assert.equal(prompted.includes(PI_PRE_RESET_HINTS), false, "manual commands own reset timing");
106
105
  assert.ok(CLAUDE_WARNING_PROMPT.endsWith(`\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}`));
107
106
  assert.equal(prompted.includes(WARNING_TIMING), false, "manual requests replace the budget opening");
@@ -196,6 +196,31 @@ test("public reset boundary drafts one marker, one boot, and one continuation af
196
196
  assert.deepEqual(branch.filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE).map((entry) => entry.type === "custom" ? entry.data : undefined), [{ windowId, origin: "normal" }], "the boundary records the model's own call");
197
197
  assert.equal(branch.filter((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE).length, 1);
198
198
  });
199
+ test("hard-reserve reset carries original text and images and continues", async () => {
200
+ const sessionManager = Manager.inMemory("/private/tmp/notesoup-hard-reserve-carry-test");
201
+ const handlers = new Map();
202
+ const api = { on(name, handler) { const list = handlers.get(name) ?? []; list.push(handler); handlers.set(name, list); } };
203
+ const ctx = { sessionManager, model: undefined, hasPendingMessages: () => false, ui: { notify() { } } };
204
+ registerResetLifecycle(api, {
205
+ isEnabled: () => true,
206
+ budget: { automaticResetEnabled: () => true, hardReserveDue: () => true, consumeTurnEnd: () => [], clear() { } },
207
+ buildReset: () => [],
208
+ });
209
+ const original = [
210
+ { type: "text", text: "Describe this image" },
211
+ { type: "image", data: "aW1hZ2U=", mimeType: "image/png" },
212
+ ];
213
+ for (const handler of handlers.get("message_end") ?? [])
214
+ await handler({ type: "message_end", message: { role: "user", content: original, timestamp: Date.now() } }, ctx);
215
+ let result;
216
+ for (const handler of handlers.get("turn_end") ?? [])
217
+ result = await handler(fakeBoundaryEvent([], { role: "assistant", content: [], stopReason: "stop", timestamp: Date.now() }), ctx);
218
+ const boundary = resultEntries([result]);
219
+ const carried = boundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE);
220
+ assert.equal(carried.length, 1);
221
+ assert.deepEqual(carried[0]?.type === "custom_message" ? carried[0].content : undefined, original);
222
+ assert.equal(boundary.continue, true);
223
+ });
199
224
  test("manual /empty spans tool turns and commits the stop at settlement", async () => {
200
225
  const h = harness();
201
226
  await h.runCommand("empty");
@@ -276,7 +301,7 @@ test("manual /empty with a prompt shows the human's command line in the close-ou
276
301
  CONTINUATION_TYPE,
277
302
  ], "the reset tail contains no command argument");
278
303
  });
279
- test("input arriving during reset construction survives even when the hidden steer is never delivered", async () => {
304
+ test("input arriving during reset construction is carried without a hidden steer", async () => {
280
305
  const sessionManager = Manager.inMemory("/private/tmp/notesoup-late-input-test");
281
306
  const handlers = new Map();
282
307
  const steers = [];
@@ -308,14 +333,14 @@ test("input arriving during reset construction survives even when the hidden ste
308
333
  const boundary = resultEntries([await pending]);
309
334
  assert.equal(boundary.continue, true, "late input overrides the bare command's stop");
310
335
  assert.deepEqual(boundary.entries.slice(-2).map((entry) => entry.type === "custom_message" ? entry.content : null), [" first\ninput ", "second"]);
311
- assert.equal(steers.length, 2, "steers were queued but never delivered by this host");
336
+ assert.equal(steers.length, 0, "handled inputs are not steered to the closing model");
312
337
  appendDrafts(sessionManager, boundary.entries);
313
338
  const marker = sessionManager.getBranch().find((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE);
314
339
  const windowId = marker.data.windowId;
315
340
  assert.equal(resetBoundaryCommitted(ctx, marker.id, windowId), true);
316
341
  assert.deepEqual(inspectResetTail(ctx, marker.id, windowId), { boot: true, continuation: true }, "last word and trailing inputs form a complete ordered boundary");
317
342
  await repairResetTail(api, ctx, marker);
318
- assert.equal(steers.length, 2, "repair never duplicates a complete boundary with carried inputs");
343
+ assert.equal(steers.length, 0, "reset repair does not send prompt steers");
319
344
  sessionManager.appendCustomMessageEntry(BOOT_TYPE, "late boot", false, { windowId });
320
345
  assert.equal(inspectResetTail(ctx, marker.id, windowId), undefined, "artifacts cannot restart after carried input");
321
346
  assert.equal(resetBoundaryCommitted(ctx, marker.id, windowId), true, "later malformed work does not undo a committed prefix");
@@ -396,10 +421,27 @@ test("abort during reset construction restores handled input at settlement, once
396
421
  await handlers.get("agent_settled")({}, ctx);
397
422
  const restored = sent.filter((item) => item.message.customType === CARRIED_INPUT_TYPE);
398
423
  assert.deepEqual(restored, [{ message: { type: "custom_message", customType: CARRIED_INPUT_TYPE, content: "cancelled during construction", display: true }, options: { triggerTurn: false } }]);
399
- // A later command in the same window must not revive the cancelled command's steer.
424
+ });
425
+ test("close-out error restores intercepted input and triggers its answer turn", async () => {
426
+ const sessionManager = Manager.inMemory("/private/tmp/notesoup-error-input-restore-test");
427
+ const handlers = new Map();
428
+ const sent = [];
429
+ const api = {
430
+ on(name, handler) { handlers.set(name, handler); },
431
+ sendMessage(message, options) { sent.push({ message, options }); },
432
+ };
433
+ const ctx = { sessionManager, hasPendingMessages: () => false, ui: { notify() { } } };
434
+ const lifecycle = registerResetLifecycle(api, {
435
+ isEnabled: () => true,
436
+ budget: { automaticResetEnabled: () => false, hardReserveDue: () => false, consumeTurnEnd: () => [], clear() { } },
437
+ buildReset: () => [],
438
+ });
439
+ const windowId = `pcw:${sessionManager.getSessionId().slice(0, 8)}:root`;
400
440
  lifecycle.command(windowId, false);
401
- const stale = { role: "custom", ...sent[0].message };
402
- assert.deepEqual(await handlers.get("context_with_system")({ messages: [stale] }, ctx), { messages: [] });
441
+ assert.deepEqual(await handlers.get("input")({ source: "rpc", text: "restore after error" }, ctx), { action: "handled" });
442
+ const error = { ...fakeBoundaryEvent(), outcome: "error", message: { role: "assistant", content: [], stopReason: "error", timestamp: Date.now() } };
443
+ await handlers.get("turn_end")(error, ctx);
444
+ assert.deepEqual(sent, [{ message: { type: "custom_message", customType: CARRIED_INPUT_TYPE, content: "restore after error", display: true }, options: { triggerTurn: true } }]);
403
445
  });
404
446
  test("reset construction failure preserves incoming and budget drafts without continuation", async () => {
405
447
  const sessionManager = Manager.inMemory("/private/tmp/notesoup-reset-failure-test");
@@ -4,22 +4,23 @@ Pi reset control lives in `plugins/pi/reset/lifecycle.ts`: the pure `reduceReset
4
4
 
5
5
  ## Lifecycle at a glance
6
6
 
7
- **Human input not yet answered must survive a reset and be answered afterward. Every `/empty` or `/fresh-window` stops after resetting unless separate human input arrives during emptying.**
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.**
8
8
 
9
9
  | Trigger | Behavior |
10
10
  | --- | --- |
11
11
  | `empty_brain` tool | Record the actual call and optional last word. Without command policy, reset after the whole tool batch at `turn_end` and continue. Under command policy, wait for settlement. |
12
12
  | `/empty <text>` or `/fresh-window <text>` | Send a hidden close-out warning (trigger when idle, steer when busy), with the argument verbatim as context for notes, then reset and stop unless separate human input arrives during emptying. |
13
13
  | Bare `/empty` or `/fresh-window` | Close out, reset, and stop, unless more human input arrives while close-out is pending. |
14
- | Human input during command close-out | Intercept public `input` events except source `extension`, return `handled`, and stash text/images in command state. Also hidden-steer the bare `<notesoup:next_window_prompt>` block plus original images to the closing model. The originals are carried even if that steer never arrives; any carried input makes the reset continue. |
15
- | Passive provider overflow / recoverable length | With automatic reset enabled, force a retain-none reset and continue once. Carry the failed logical run's human messages: starting prompt and delivered steering/follow-ups. A run started by our own continuation has no human input to carry. |
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
+ | 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
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. |
17
18
  | Budget warning | Stage reminders when automatic reset is enabled. Warnings alone never authorize reset. |
18
- | Hard reserve | Independently reset at `turn_end` when automatic reset is enabled. A command stop latch cancels empty tool follow-ups, but never real queued or carried human input. |
19
- | Abort / ordinary error | Restore stashed originals as visible user-content custom messages before clearing command state. Explicit abort stays stopped; ordinary close-out errors do not force 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. |
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. |
20
21
  | `/compact` while active | Cancel native compaction; manual attempts receive a `/fresh-window` notice. |
21
22
 
22
- Switching to a smaller model does not proactively reset or select another model. If its request overflows, the same bounded automatic recovery carries the unanswered prompt into a fresh window on the selected model. Disabling automatic reset disables passive overflow recovery.
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
24
 
24
25
  ## Boundary order and handoff
25
26
 
@@ -45,15 +46,15 @@ Raw session history remains available. The retain-none checkpoint excludes old c
45
46
  | Request | Meaning |
46
47
  | --- | --- |
47
48
  | `none` | No command or tool request. |
48
- | `pending` | Current `windowId`, optional `tool: { lastWord? }`, and optional `command: { continueAfterReset, inputs? }`. Command inputs retain originals, not prompt-block wrappers. Duplicate commands retain the first policy/text; tool calls do not overwrite command policy. |
49
+ | `pending` | Current `windowId`, optional `tool: { lastWord? }`, and optional `command: { continueAfterReset, inputs? }`. Command inputs retain their original text/images. Separate human input during close-out is intercepted and carried, never steered. Duplicate commands retain the first policy/text; tool calls do not overwrite command policy. |
49
50
 
50
51
  `stopAfterReset` is separate from the request. It retains the safety boundary's intent after construction, while `request` becomes `none`. Settlement waits for queued work; if the window changed, it stops without a second wipe. If the window did not change, the boundary never committed, so settlement retries the retained intent with its stop policy and tool origin intact. A successful settle retry consumes the latch.
51
52
 
52
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.
53
54
 
54
- The adapter collects actual user `message_end` content until settlement or a successful reset boundary. Low-level `agent_start` events do not clear it: Pi can start additional loops while draining follow-ups/recovering. Custom boot/warning/continuation messages are never mistaken for human input. Successful boundary construction clears this run collection, so an automatic continuation does not replay old input.
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
56
 
56
- Command state remains live during asynchronous notes acquisition. Boundary intent captures the trigger, explicit `continueAfterReset` policy, tool fact and origin, but contains no final state or continuation decision. After construction passes the currentness guard, the pure finalizer selects live command-owned originals, or the current run's inputs only for passive recovery, and resolves `resumeModel` and the next control state together. `resumeModel` is true when the policy requests continuation or carried input needs an answer; the adapter maps it to Pi's `continue` field. Late originals therefore join the same boundary and prevent a stop latch from being installed; delivery contents never replace explicit command policy. Hidden steers carry window/command identity; provider projection excludes them once that command ends, including steers Pi delivers only after the reset. Originals remain available exactly once as carried input. Construction captures session/window generations and rechecks identity, enabled state and abort status before returning drafts. Clearing the run invalidates any unfinished construction before resetting its input collection. Stale work preserves incoming/budget entries but discards reset drafts; construction failures notify only while current and do not claim continuation. If close-out cannot commit, stashed originals are restored with public `sendMessage(..., { triggerTurn: false })`, including cancellation during construction; clearing command state must not erase input already reported as handled.
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
58
 
58
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.
59
60
 
@@ -61,7 +62,7 @@ After a manual safety reset, `context_with_system` checks the committed boundary
61
62
 
62
63
  Budget reminders are staged once per window at reserve plus reminder margin, then reserve plus warning runway. Hard reserve remains independent. Budget and command warnings use different types. The final budget warning notifies at first provider injection, not durability; early guidance stays UI-silent. Budget drafts are instance-local and discarded on abort, failed turn, transition or window mismatch. Active-window usage and the exact public `SettingsManager` authority determine thresholds.
63
64
 
64
- Pi and Claude use the same budget warning: budget timing, the handoff checklist, note maintenance (including updating and trimming CHEATSHEET.md and MAP.md), a warning against large tool outputs, then `empty_brain` and the countdown. Pi's manual warnings replace the budget opening with the `/empty` notice inside `<notesoup:budget_notice>`. Optional command text sits after the closing tag in `<notesoup:next_window_prompt>`. The first-tier reminder reports the remaining room, explains that notes survive the wipe, asks for updated notes and offers an optional `empty_brain`, warning that it also clears what the model says to the human right before emptying. Pi's boot retains its existing pre-reset hints; warnings no longer repeat those or the tool's `last_word` description.
65
+ Pi and Claude use the same budget warning: budget timing, the handoff checklist, note maintenance (including updating and trimming CHEATSHEET.md and MAP.md), a warning against large tool outputs, then `empty_brain` and the countdown. Pi's manual warnings replace the budget opening with the `/empty` notice inside `<notesoup:budget_notice>`. Optional command text sits after the closing tag as plain text for the closing model's notes; separate human input during close-out is intercepted and carried, never steered. The first-tier reminder reports the remaining room, explains that notes survive the wipe, asks for updated notes and offers an optional `empty_brain`, warning that it also clears what the model says to the human right before emptying. Pi's boot retains its existing pre-reset hints; warnings no longer repeat those or the tool's `last_word` description.
65
66
 
66
67
  `context_with_system` selects the boot by durable window identity, using Pi's canonical checkpoint projection or legacy slicing. Missing boot aborts safely instead of exposing raw history. Usage estimates use the same projection decision. `/tree` summaries are suppressed when crossing reset branches because native branch summarization bypasses this projection.
67
68
 
@@ -69,4 +70,4 @@ Pi and Claude use the same budget warning: budget timing, the handoff checklist,
69
70
 
70
71
  ## Validation
71
72
 
72
- 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, stale queued steer exclusion, 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 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.57.0",
3
+ "version": "0.57.1",
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.0",
3
+ "version": "0.57.1",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"
@@ -6,5 +6,4 @@ export const RESET_MARKER_TYPE = "notesoup/reset-marker";
6
6
  export const CONTINUATION_TYPE = "notesoup/continuation";
7
7
  export const RESET_LAST_WORD_TYPE = "notesoup/reset-last-word";
8
8
  export const CARRIED_INPUT_TYPE = "notesoup/carried-input";
9
- export const NEXT_WINDOW_PROMPT_TYPE = "notesoup/next-window-prompt";
10
9
  export const MARKER_TYPE = "notesoup/marker";
@@ -1,4 +1,3 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
3
2
  import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
4
3
  import type { AgentBeforeSettleEvent, ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
@@ -9,8 +8,6 @@ import { resetBoundaryCommitted } from "./committed.js";
9
8
  import type { ResetOrigin } from "../../../src/budget/text.js";
10
9
  import { errorMessage } from "../../../src/error-message.js";
11
10
  import { carriedInputDrafts, isCarriedInputEntry, type CarriedInput } from "./artifacts.js";
12
- import { NEXT_WINDOW_PROMPT_TYPE } from "../entries.js";
13
- import { promptBlock } from "../text.js";
14
11
 
15
12
  type BudgetOwner = {
16
13
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
@@ -87,13 +84,14 @@ export type ResetControlEvent =
87
84
  | { readonly type: "before_settle"; readonly facts: ResetBeforeSettleFacts };
88
85
 
89
86
  /** Construction intent, not final state: handled inputs can still arrive while notes load. Only `turn-end`
90
- * may latch a stop; overflow kinds spend recovery; only `overflow-recovery` carries passive run inputs. */
87
+ * may latch a stop; overflow kinds spend recovery; only hard-reserve and overflow carry passive run inputs. */
91
88
  export interface ResetBoundaryIntent {
92
89
  readonly effect: "build-boundary";
93
90
  readonly boundary: "turn-end" | "settle" | "command-overflow" | "overflow-recovery";
94
91
  readonly windowId: string;
95
92
  readonly continueAfterReset: boolean;
96
93
  readonly origin: ResetOrigin;
94
+ readonly carryRunInputs?: boolean;
97
95
  readonly tool?: { readonly lastWord?: string };
98
96
  }
99
97
 
@@ -106,16 +104,16 @@ function requestForWindow(request: ResetRequest, windowId: string): ResetRequest
106
104
 
107
105
  const spendsOverflow = (boundary: ResetBoundaryIntent["boundary"]) => boundary === "command-overflow" || boundary === "overflow-recovery";
108
106
 
109
- function boundaryIntent(request: ResetRequest, windowId: string, boundary: ResetBoundaryIntent["boundary"]): ResetBoundaryIntent {
107
+ function boundaryIntent(request: ResetRequest, windowId: string, boundary: ResetBoundaryIntent["boundary"], carryRunInputs = false): ResetBoundaryIntent {
110
108
  const tool = request.phase === "none" ? undefined : request.tool;
111
109
  const continueAfterReset = request.phase === "pending" ? request.command?.continueAfterReset ?? true : true;
112
- return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal" };
110
+ return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal", ...(carryRunInputs ? { carryRunInputs: true } : {}) };
113
111
  }
114
112
 
115
113
  /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
116
114
  export function finalizeResetBoundary(intent: ResetBoundaryIntent, request: ResetRequest, passiveInputs: readonly CarriedInput[] = []) {
117
115
  const inputs = request.phase === "pending" && request.command ? request.command.inputs ?? []
118
- : intent.boundary === "overflow-recovery" ? passiveInputs : [];
116
+ : intent.boundary === "overflow-recovery" || intent.carryRunInputs ? passiveInputs : [];
119
117
  const resumeModel = intent.continueAfterReset || inputs.length > 0;
120
118
  const state: ResetControlState = {
121
119
  request: NO_REQUEST,
@@ -170,8 +168,9 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
170
168
  }
171
169
  // A direct tool request commits after the whole tool batch. The budget cutoff is
172
170
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
173
- if ((request.phase === "pending" && request.tool && !manual) || facts.hardReserveDue) {
174
- return boundaryIntent(request, facts.windowId, "turn-end");
171
+ const toolReset = request.phase === "pending" && request.tool !== undefined;
172
+ if ((toolReset && !manual) || facts.hardReserveDue) {
173
+ return boundaryIntent(request, facts.windowId, "turn-end", !manual && !toolReset && facts.hardReserveDue);
175
174
  }
176
175
  return { state: { request, overflow: "idle" }, effect: "none" };
177
176
  }
@@ -220,17 +219,16 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
220
219
  let lifecycleGeneration = 0;
221
220
  let control = initialResetControl();
222
221
  let runInputs: CarriedInput[] = [];
223
- let commandId: string | undefined;
224
222
 
225
223
  // Once input returns handled, Pi no longer owns its original content. If close-out
226
- // fails/cancels, return that content to the transcript without starting another run.
227
- const restoreCommandInputs = () => {
224
+ // fails/cancels, restore it; only an ordinary error starts a turn to answer it.
225
+ const restoreCommandInputs = (triggerTurn = false) => {
228
226
  const request = control.request;
229
227
  if (request.phase !== "pending" || !request.command?.inputs?.length) return;
230
228
  const inputs = request.command.inputs;
231
229
  control = { ...control, request: { ...request, command: { ...request.command, inputs: [] } } };
232
230
  for (const draft of carriedInputDrafts(inputs)) {
233
- pi.sendMessage(draft, { triggerTurn: false });
231
+ pi.sendMessage(draft, { triggerTurn });
234
232
  }
235
233
  runInputs.push(...inputs);
236
234
  };
@@ -239,11 +237,9 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
239
237
  if (preserveInputs) restoreCommandInputs();
240
238
  control = initialResetControl();
241
239
  runInputs = [];
242
- commandId = undefined;
243
240
  };
244
241
  const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, intent: ResetBoundaryIntent) => {
245
- // Keep command state live while notes load: input arriving during this await must
246
- // join this very boundary even if its steer cannot reach the closing model.
242
+ // Keep command state live while notes load so input arriving during this await joins this boundary.
247
243
  const generation = lifecycleGeneration;
248
244
  const outerGeneration = options.getLifecycleGeneration?.();
249
245
  const sessionId = ctx.sessionManager.getSessionId();
@@ -281,10 +277,6 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
281
277
  ? [{ type: "text", text: event.text }, ...event.images]
282
278
  : event.text;
283
279
  control = reduceResetControl(control, { type: "input", windowId: request.windowId, input: content }).state;
284
- const steerContent: CarriedInput = event.images?.length
285
- ? [{ type: "text", text: promptBlock(event.text) }, ...event.images]
286
- : promptBlock(event.text);
287
- pi.sendMessage({ customType: NEXT_WINDOW_PROMPT_TYPE, content: steerContent, display: false, details: { windowId: request.windowId, commandId } }, { deliverAs: "steer" });
288
280
  return { action: "handled" };
289
281
  });
290
282
 
@@ -292,23 +284,13 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
292
284
  // safety reset is actually committed, cancel that empty follow-up before provider
293
285
  // work. Real queued user input is allowed through and answered before settlement.
294
286
  pi.on("context_with_system", (event, ctx) => {
295
- const request = control.request;
296
- // Steering can be queued during buildReset's await and arrive after the boundary.
297
- // It is closing-model context only; originals already live in the carried entries.
298
- const messages = event.messages.filter((message) => {
299
- if (message.role !== "custom" || message.customType !== NEXT_WINDOW_PROMPT_TYPE) return true;
300
- const details = message.details as { windowId?: unknown; commandId?: unknown } | undefined;
301
- return request.phase === "pending" && request.command !== undefined &&
302
- request.windowId === currentWindowId(ctx) && details?.windowId === request.windowId && commandId !== undefined && details?.commandId === commandId;
303
- });
304
- const filtered = messages.length === event.messages.length ? undefined : { messages };
305
287
  const stop = control.stopAfterReset;
306
- if (!sessionActive || !stop || ctx.hasPendingMessages()) return filtered;
288
+ if (!sessionActive || !stop || ctx.hasPendingMessages()) return undefined;
307
289
  const marker = currentReset(ctx);
308
- if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId)) return filtered;
290
+ if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId)) return undefined;
309
291
  const branch = ctx.sessionManager.getBranch();
310
292
  const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
311
- if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry))) return filtered;
293
+ if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry))) return undefined;
312
294
  ctx.abort();
313
295
  const system = getCurrentSystemMessage(event.messages);
314
296
  return { messages: system ? [system] : [] };
@@ -334,8 +316,11 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
334
316
  },
335
317
  });
336
318
  if (decision.effect === "build-boundary") return await resetBoundaryResult(entries, ctx, decision);
337
- if (aborted || (event.outcome === "error" && decision.state.request.phase === "none")) restoreCommandInputs();
319
+ if (aborted) restoreCommandInputs();
320
+ else if (event.outcome === "error" && decision.state.request.phase === "none") restoreCommandInputs(true);
338
321
  control = decision.state;
322
+ if (!aborted && event.outcome === "completed" && event.message.role === "assistant" && event.message.stopReason === "stop" &&
323
+ event.context.pendingMessages.length === 0 && !ctx.hasPendingMessages()) runInputs = [];
339
324
  if (!aborted && event.outcome !== "error" && options.isEnabled()) {
340
325
  const marker = buildMarkerDraft(ctx, entries);
341
326
  if (marker) entries.push(marker);
@@ -390,7 +375,6 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
390
375
  command(windowId: string, continueAfterReset: boolean, input?: CarriedInput) {
391
376
  const decision = reduceResetControl(control, { type: "command", windowId, continueAfterReset, ...(input !== undefined ? { input } : {}) });
392
377
  control = decision.state;
393
- if (decision.effect === "close-out-armed") commandId = randomUUID();
394
378
  return decision.effect;
395
379
  },
396
380
  request(windowId: string, lastWord?: string) {
@@ -3,7 +3,7 @@ import { resetBoundaryCommitted } from "./reset/committed.js";
3
3
  import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
4
4
  import { VERSION, defineTool, type ExtensionAPI, type ExtensionCommandContext, type ExtensionContext, type SettingsManager } from "@earendil-works/pi-coding-agent";
5
5
  import { registerBudget } from "./budget.js";
6
- import { output } from "./tool-result.js";
6
+ import { DREAM_NAMESPACE, HISTORY_NAMESPACE, NOTES_NAMESPACE, output } from "./tool-result.js";
7
7
  import { emptyBrainRenderers } from "./render.js";
8
8
  import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, markerResetOrigin, projectRootWindow, projectWindow, rootWindowId, type WindowMarker } from "./window.js";
9
9
  import { registerResetLifecycle } from "./reset/lifecycle.js";
@@ -24,6 +24,9 @@ function readPackageVersion(): string {
24
24
  }
25
25
 
26
26
  const buildLabel = `v${readPackageVersion()}`;
27
+ const notesoupTools = [NOTES_NAMESPACE, HISTORY_NAMESPACE, DREAM_NAMESPACE]
28
+ .map(({ name, description }) => `${name}: ${description}`)
29
+ .join("\n") + "\nDiscover deferred tools through codemode or tool_search when available.";
27
30
 
28
31
  function branchHasWindowMarker(ctx: ExtensionContext, fromId?: string): boolean {
29
32
  return ctx.sessionManager.getBranch(fromId).some((entry) => isWindowMarker(entry));
@@ -77,7 +80,8 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
77
80
  if (markerResetOrigin(marker) === "forced") ctx.ui.notify("🥣 Brain forcibly emptied: overflow", "warning");
78
81
  }
79
82
  };
80
- pi.on("before_agent_start", (_event, ctx) => {
83
+ pi.on("before_agent_start", (event, ctx) => {
84
+ event.systemPromptOptions.sections.notesoup_tools = notesoupTools;
81
85
  if (enabled) maybeSendMarker(pi, ctx);
82
86
  });
83
87
  pi.on("turn_start", (_event, ctx) => {
@@ -16,11 +16,6 @@ export function markerContent(seq: number): string {
16
16
  return `<notesoup:marker seq="${seq}" />`;
17
17
  }
18
18
 
19
- /** The closing model sees deferred input as a bare next-window prompt block. */
20
- export function promptBlock(commandLine: string): string {
21
- return `<notesoup:next_window_prompt>\n${commandLine}\n</notesoup:next_window_prompt>`;
22
- }
23
-
24
19
  /** Approved manual close-out notices; both variants live here. */
25
20
  export const COMMAND_NOTICE = {
26
21
  prompted: "The human ran /empty. Save your notes now and call `empty_brain` immediately. Anything you say here will be erased afterward — put the handoff in your notes. The command below is context for your notes, not a task for the fresh window. Anything the human sends separately from now on should be handled after the reset.",
@@ -30,5 +25,5 @@ export const COMMAND_NOTICE = {
30
25
  /** Manual orders omit budget timing hints; deferred work sits outside the notice. */
31
26
  export function commandWarningContent(commandLine?: string): string {
32
27
  const notice = commandLine ? COMMAND_NOTICE.prompted : COMMAND_NOTICE.bare;
33
- return `${GUIDANCE_OPEN_TAG}\n${notice}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}${commandLine ? `\n${promptBlock(commandLine)}` : ""}`;
28
+ return `${GUIDANCE_OPEN_TAG}\n${notice}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}${commandLine ? `\n${commandLine}` : ""}`;
34
29
  }