notesoup 0.51.1 → 0.51.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/plugins/pi/entries.d.ts +2 -0
  2. package/dist/plugins/pi/entries.js +2 -0
  3. package/dist/plugins/pi/reset/artifacts.d.ts +10 -2
  4. package/dist/plugins/pi/reset/artifacts.js +24 -5
  5. package/dist/plugins/pi/reset/lifecycle.d.ts +37 -21
  6. package/dist/plugins/pi/reset/lifecycle.js +132 -57
  7. package/dist/plugins/pi/runtime.js +9 -10
  8. package/dist/plugins/pi/text.d.ts +11 -14
  9. package/dist/plugins/pi/text.js +15 -16
  10. package/dist/test/agent-loop.test.js +316 -163
  11. package/dist/test/boot.integration.test.js +3 -3
  12. package/dist/test/claude-validation.test.js +4 -2
  13. package/dist/test/dsh-cli.test.js +7 -6
  14. package/dist/test/helpers/dsh-messages.js +3 -0
  15. package/dist/test/model-facing-text.test.js +10 -4
  16. package/dist/test/reset-lifecycle.test.js +272 -88
  17. package/docs/architecture.md +1 -1
  18. package/docs/reset-lifecycle.md +42 -57
  19. package/package.json +2 -2
  20. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  21. package/plugins/paseo/OVERVIEW.md +7 -0
  22. package/plugins/paseo/README.md +12 -0
  23. package/plugins/paseo/client/source-row.ts +14 -0
  24. package/plugins/paseo/client/sticky-card.tsx +21 -0
  25. package/plugins/paseo/index.client.tsx +10 -0
  26. package/plugins/paseo/package.json +19 -0
  27. package/plugins/paseo/paseo-plugin.json +4 -0
  28. package/plugins/paseo/shared/last-word.ts +6 -0
  29. package/plugins/paseo/test/source-row.test.ts +19 -0
  30. package/plugins/paseo/tsconfig.json +16 -0
  31. package/plugins/pi/entries.ts +2 -0
  32. package/plugins/pi/reset/artifacts.ts +26 -5
  33. package/plugins/pi/reset/lifecycle.ts +135 -70
  34. package/plugins/pi/runtime.ts +9 -10
  35. package/plugins/pi/text.ts +17 -17
@@ -5,3 +5,5 @@ export declare const MANUAL_WIPE_TYPE = "notesoup/manual-wipe";
5
5
  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
+ export declare const CARRIED_INPUT_TYPE = "notesoup/carried-input";
9
+ export declare const NEXT_WINDOW_PROMPT_TYPE = "notesoup/next-window-prompt";
@@ -5,3 +5,5 @@ export const MANUAL_WIPE_TYPE = "notesoup/manual-wipe";
5
5
  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
+ export const CARRIED_INPUT_TYPE = "notesoup/carried-input";
9
+ export const NEXT_WINDOW_PROMPT_TYPE = "notesoup/next-window-prompt";
@@ -6,6 +6,14 @@ export type ResetTailState = {
6
6
  readonly boot: boolean;
7
7
  readonly continuation: boolean;
8
8
  };
9
+ /** Original user content, including images; custom boundary messages become LLM user messages. */
10
+ export type CarriedInput = Extract<SessionBoundaryDraft, {
11
+ type: "custom_message";
12
+ }>["content"];
13
+ export declare function carriedInputDrafts(inputs: readonly CarriedInput[]): Extract<SessionBoundaryDraft, {
14
+ type: "custom_message";
15
+ }>[];
16
+ export declare function isCarriedInputEntry(entry: SessionEntry): boolean;
9
17
  /** A sticky note, not a letter: over this, empty_brain refuses instead of truncating. */
10
18
  export declare const MAX_LAST_WORD_CHARS = 250;
11
19
  /** How the next window finds the note. */
@@ -16,8 +24,8 @@ export declare function sanitizeLastWord(raw: string | undefined): string | unde
16
24
  export declare function isWindowContinuationEntry(entry: SessionEntry): boolean;
17
25
  /**
18
26
  * The closed, ordered reset shape: retain-none native checkpoint, marker, matching boot,
19
- * continuation, then an optional parting line. The prompt is not persisted here — it reached the
20
- * closing window inside the warning. The boot snapshot is acquired asynchronously after capturing
27
+ * continuation, then an optional parting line. The lifecycle appends carried inputs in the same
28
+ * boundary after these artifacts. The boot snapshot is acquired asynchronously after capturing
21
29
  * this identity. The continuation is drawn from the pool its origin names, here, once: the caller
22
30
  * persists the returned text and no read, render, or repair draws it again. The origin defaults to
23
31
  * `normal`, the same reading a legacy marker with no origin gets.
@@ -1,8 +1,14 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { BOOT_TYPE, CONTINUATION_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE } from "../entries.js";
2
+ import { BOOT_TYPE, CARRIED_INPUT_TYPE, CONTINUATION_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE } from "../entries.js";
3
3
  import { selectContinuation } from "../../../src/budget/text.js";
4
4
  import { isForeignResetTailEntry, isWindowBootEntry, isWindowMarker, markerResetOrigin } from "../window.js";
5
5
  import { buildBootMessage, sendBoot } from "../boot.js";
6
+ export function carriedInputDrafts(inputs) {
7
+ return inputs.map((content) => ({ type: "custom_message", customType: CARRIED_INPUT_TYPE, content, display: true }));
8
+ }
9
+ export function isCarriedInputEntry(entry) {
10
+ return entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE && entry.display === true;
11
+ }
6
12
  /** A sticky note, not a letter: over this, empty_brain refuses instead of truncating. */
7
13
  export const MAX_LAST_WORD_CHARS = 250;
8
14
  /** How the next window finds the note. */
@@ -21,8 +27,8 @@ function sendContinuation(pi, content) {
21
27
  }
22
28
  /**
23
29
  * The closed, ordered reset shape: retain-none native checkpoint, marker, matching boot,
24
- * continuation, then an optional parting line. The prompt is not persisted here — it reached the
25
- * closing window inside the warning. The boot snapshot is acquired asynchronously after capturing
30
+ * continuation, then an optional parting line. The lifecycle appends carried inputs in the same
31
+ * boundary after these artifacts. The boot snapshot is acquired asynchronously after capturing
26
32
  * this identity. The continuation is drawn from the pool its origin names, here, once: the caller
27
33
  * persists the returned text and no read, render, or repair draws it again. The origin defaults to
28
34
  * `normal`, the same reading a legacy marker with no origin gets.
@@ -56,6 +62,8 @@ export function inspectResetTail(ctx, markerId, windowId) {
56
62
  return undefined;
57
63
  let boot = false;
58
64
  let continuation = false;
65
+ let lastWord = false;
66
+ let carried = false;
59
67
  for (const entry of branch.slice(markerIndex + 1)) {
60
68
  if (isWindowBootEntry(entry, windowId)) {
61
69
  // The boot is unique and must precede the continuation; a repeat or a late
@@ -71,9 +79,20 @@ export function inspectResetTail(ctx, markerId, windowId) {
71
79
  continuation = true;
72
80
  continue;
73
81
  }
74
- if (isForeignResetTailEntry(entry)) {
75
- return undefined;
82
+ if (entry.type === "custom_message" && entry.customType === RESET_LAST_WORD_TYPE) {
83
+ if (!continuation || lastWord || carried || entry.display !== true)
84
+ return undefined;
85
+ lastWord = true;
86
+ continue;
76
87
  }
88
+ if (isCarriedInputEntry(entry)) {
89
+ if (!continuation)
90
+ return undefined;
91
+ carried = true;
92
+ continue;
93
+ }
94
+ if (isForeignResetTailEntry(entry))
95
+ return undefined;
77
96
  }
78
97
  return { boot, continuation };
79
98
  }
@@ -1,5 +1,6 @@
1
1
  import type { ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
2
2
  import type { ResetOrigin } from "../../../src/budget/text.js";
3
+ import { type CarriedInput } from "./artifacts.js";
3
4
  type BudgetOwner = {
4
5
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
5
6
  hardReserveDue: (ctx: ExtensionContext) => boolean;
@@ -15,17 +16,12 @@ type ResetOptions = {
15
16
  };
16
17
  export type ResetRequest = {
17
18
  readonly phase: "none";
18
- } | {
19
- readonly phase: "stop-pending";
20
- readonly windowId: string;
21
- readonly tool?: {
22
- readonly lastWord?: string;
23
- };
24
19
  } | {
25
20
  readonly phase: "pending";
26
21
  readonly windowId: string;
27
22
  readonly command?: {
28
23
  readonly continueAfterReset: boolean;
24
+ readonly inputs?: readonly CarriedInput[];
29
25
  };
30
26
  readonly tool?: {
31
27
  readonly lastWord?: string;
@@ -34,6 +30,8 @@ export type ResetRequest = {
34
30
  export type ResetOverflowPhase = "idle" | "pending" | "pending-spent" | "spent";
35
31
  export interface ResetControlState {
36
32
  readonly request: ResetRequest;
33
+ /** Await settlement after a safety reset; retain its intent to retry if it never committed. */
34
+ readonly stopAfterReset?: ResetBoundaryIntent;
37
35
  readonly overflow: ResetOverflowPhase;
38
36
  }
39
37
  export declare function initialResetControl(): ResetControlState;
@@ -61,6 +59,11 @@ export type ResetControlEvent = {
61
59
  readonly type: "command";
62
60
  readonly windowId: string;
63
61
  readonly continueAfterReset: boolean;
62
+ readonly input?: CarriedInput;
63
+ } | {
64
+ readonly type: "input";
65
+ readonly windowId: string;
66
+ readonly input: CarriedInput;
64
67
  } | {
65
68
  readonly type: "tool_request";
66
69
  readonly windowId: string;
@@ -71,22 +74,35 @@ export type ResetControlEvent = {
71
74
  } | {
72
75
  readonly type: "before_settle";
73
76
  readonly facts: ResetBeforeSettleFacts;
74
- } | {
75
- readonly type: "settled";
76
- } | {
77
- readonly type: "abort";
78
- } | {
79
- readonly type: "clear";
80
77
  };
81
- export type ResetControlEffect = "none" | "close-out-armed" | "already-pending" | "commit-boundary" | "commit-boundary-stop" | "stop" | "recover-overflow";
82
- export interface ResetControlResult {
83
- readonly state: ResetControlState;
84
- readonly effect: ResetControlEffect;
85
- readonly lastWord?: string;
86
- /** The origin of the boundary this decision commits. Absent means no `empty_brain` call was recorded, so forced. */
87
- readonly origin?: ResetOrigin;
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. */
80
+ export interface ResetBoundaryIntent {
81
+ readonly effect: "build-boundary";
82
+ readonly boundary: "turn-end" | "settle" | "command-overflow" | "overflow-recovery";
83
+ readonly windowId: string;
84
+ readonly continueAfterReset: boolean;
85
+ readonly origin: ResetOrigin;
86
+ readonly tool?: {
87
+ readonly lastWord?: string;
88
+ };
88
89
  }
90
+ export type ResetControlResult = ResetBoundaryIntent | {
91
+ readonly state: ResetControlState;
92
+ readonly effect: "none" | "close-out-armed" | "already-pending" | "stop";
93
+ };
94
+ /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
95
+ export declare function finalizeResetBoundary(intent: ResetBoundaryIntent, request: ResetRequest, passiveInputs?: readonly CarriedInput[]): {
96
+ state: ResetControlState;
97
+ inputs: readonly (string | (import("@earendil-works/pi-ai").TextContent | import("@earendil-works/pi-ai").ImageContent)[])[];
98
+ resumeModel: boolean;
99
+ };
89
100
  /** Pure transitions: command policy schedules a reset without disguising actual tool calls. */
101
+ export declare function reduceResetControl(state: ResetControlState, event: Extract<ResetControlEvent, {
102
+ type: "input" | "command" | "tool_request";
103
+ }>): Extract<ResetControlResult, {
104
+ state: ResetControlState;
105
+ }>;
90
106
  export declare function reduceResetControl(state: ResetControlState, event: ResetControlEvent): ResetControlResult;
91
107
  /**
92
108
  * Tool-only requests commit at turn_end; command policy waits for settlement.
@@ -94,8 +110,8 @@ export declare function reduceResetControl(state: ResetControlState, event: Rese
94
110
  * Budget warnings carry no lifecycle state. Overflow recovery remains bounded.
95
111
  */
96
112
  export declare function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions): {
97
- command(windowId: string, continueAfterReset: boolean): ResetControlEffect;
113
+ command(windowId: string, continueAfterReset: boolean, input?: CarriedInput): "none" | "stop" | "close-out-armed" | "already-pending";
98
114
  request(windowId: string, lastWord?: string): "rollover_already_pending" | "rollover_requested";
99
- clear: () => void;
115
+ clear: (preserveInputs?: boolean) => void;
100
116
  };
101
117
  export {};
@@ -1,8 +1,12 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
2
3
  import { currentReset, currentWindowId } from "../window.js";
3
4
  import { nextHistorySeq } from "../history.js";
4
5
  import { resetBoundaryCommitted } from "./committed.js";
5
6
  import { errorMessage } from "../../../src/error-message.js";
7
+ import { carriedInputDrafts, isCarriedInputEntry } from "./artifacts.js";
8
+ import { NEXT_WINDOW_PROMPT_TYPE } from "../entries.js";
9
+ import { promptBlock } from "../text.js";
6
10
  function isAbort(message, outcome, ctx) {
7
11
  return outcome === "aborted" || (message.role === "assistant" && message.stopReason === "aborted") || ctx.signal?.aborted === true;
8
12
  }
@@ -17,33 +21,44 @@ export function initialResetControl() {
17
21
  return { request: NO_REQUEST, overflow: "idle" };
18
22
  }
19
23
  function requestForWindow(request, windowId) {
20
- return request.phase === "stop-pending" || (request.phase !== "none" && request.windowId === windowId) ? request : NO_REQUEST;
24
+ return request.phase === "pending" && request.windowId === windowId ? request : NO_REQUEST;
21
25
  }
22
- function commandCommit(request) {
23
- return {
24
- state: initialResetControl(),
25
- effect: request.command?.continueAfterReset ? "commit-boundary" : "commit-boundary-stop",
26
- ...requestDetails(request),
27
- };
28
- }
29
- /** The tool request itself is the origin fact; the stop latch retains it for construction retry. */
30
- function requestDetails(request) {
26
+ const spendsOverflow = (boundary) => boundary === "command-overflow" || boundary === "overflow-recovery";
27
+ function boundaryIntent(request, windowId, boundary) {
31
28
  const tool = request.phase === "none" ? undefined : request.tool;
32
- return { origin: tool ? "normal" : "forced", ...tool };
29
+ const continueAfterReset = request.phase === "pending" ? request.command?.continueAfterReset ?? true : true;
30
+ return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal" };
31
+ }
32
+ /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
33
+ export function finalizeResetBoundary(intent, request, passiveInputs = []) {
34
+ const inputs = request.phase === "pending" && request.command ? request.command.inputs ?? []
35
+ : intent.boundary === "overflow-recovery" ? passiveInputs : [];
36
+ const resumeModel = intent.continueAfterReset || inputs.length > 0;
37
+ const state = {
38
+ request: NO_REQUEST,
39
+ ...(intent.boundary === "turn-end" && !resumeModel ? { stopAfterReset: intent } : {}),
40
+ overflow: spendsOverflow(intent.boundary) ? "spent" : "idle",
41
+ };
42
+ return { state, inputs, resumeModel };
33
43
  }
34
- /** Pure transitions: command policy schedules a reset without disguising actual tool calls. */
35
44
  export function reduceResetControl(state, event) {
36
45
  switch (event.type) {
46
+ case "input": {
47
+ const request = requestForWindow(state.request, event.windowId);
48
+ if (request.phase !== "pending" || !request.command)
49
+ return { state, effect: "none" };
50
+ return { state: { ...state, request: { ...request, command: { ...request.command, inputs: [...(request.command.inputs ?? []), event.input] } } }, effect: "none" };
51
+ }
37
52
  case "command":
38
53
  case "tool_request": {
39
- const current = requestForWindow(state.request, event.windowId);
40
- if (current.phase === "stop-pending")
54
+ if (state.stopAfterReset)
41
55
  return { state, effect: "already-pending" };
56
+ const current = requestForWindow(state.request, event.windowId);
42
57
  const request = current.phase === "pending" ? current : { phase: "pending", windowId: event.windowId };
43
58
  if (event.type === "command") {
44
59
  if (request.command)
45
60
  return { state, effect: "already-pending" };
46
- return { state: { ...state, request: { ...request, command: { continueAfterReset: event.continueAfterReset } } }, effect: "close-out-armed" };
61
+ return { state: { ...state, request: { ...request, command: { continueAfterReset: event.continueAfterReset, ...(event.input !== undefined ? { inputs: [event.input] } : {}) } } }, effect: "close-out-armed" };
47
62
  }
48
63
  // The call remains a real request even when command policy delays its commit.
49
64
  const duplicate = request.tool !== undefined;
@@ -56,8 +71,8 @@ export function reduceResetControl(state, event) {
56
71
  const request = requestForWindow(state.request, facts.windowId);
57
72
  if (facts.aborted)
58
73
  return { state: initialResetControl(), effect: "none" };
59
- if (request.phase === "stop-pending")
60
- return { state: { request, overflow: "idle" }, effect: "none" };
74
+ if (state.stopAfterReset)
75
+ return { state: { ...state, overflow: "idle" }, effect: "none" };
61
76
  const manual = request.phase === "pending" && request.command !== undefined;
62
77
  if (facts.overflow) {
63
78
  const pending = manual ? facts.enabled : !facts.queued && facts.enabled && facts.automaticResetEnabled;
@@ -75,11 +90,7 @@ export function reduceResetControl(state, event) {
75
90
  // A direct tool request commits after the whole tool batch. The budget cutoff is
76
91
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
77
92
  if ((request.phase === "pending" && request.tool && !manual) || facts.hardReserveDue) {
78
- if (manual && request.command?.continueAfterReset)
79
- return commandCommit(request);
80
- if (manual)
81
- return { state: { request: { phase: "stop-pending", windowId: facts.windowId, ...(request.tool ? { tool: request.tool } : {}) }, overflow: "idle" }, effect: "commit-boundary-stop", ...requestDetails(request) };
82
- return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary", ...requestDetails(request) };
93
+ return boundaryIntent(request, facts.windowId, "turn-end");
83
94
  }
84
95
  return { state: { request, overflow: "idle" }, effect: "none" };
85
96
  }
@@ -88,14 +99,15 @@ export function reduceResetControl(state, event) {
88
99
  if (facts.aborted)
89
100
  return { state: initialResetControl(), effect: "none" };
90
101
  const request = requestForWindow(state.request, facts.windowId);
91
- if (request.phase === "stop-pending") {
102
+ if (state.stopAfterReset) {
92
103
  if (facts.queued)
93
104
  return { state, effect: "none" };
94
- // Only retry construction if the safety boundary never committed. Otherwise
95
- // stop without a second wipe, even if a queued turn subsequently failed.
96
- if (request.windowId !== facts.windowId)
105
+ // A changed window confirms commit: stop without wiping twice. Otherwise retry.
106
+ if (state.stopAfterReset.windowId !== facts.windowId)
97
107
  return { state: initialResetControl(), effect: "stop" };
98
- return { state: initialResetControl(), effect: facts.failed || !facts.enabled ? "none" : "commit-boundary-stop", ...requestDetails(request) };
108
+ if (facts.failed || !facts.enabled)
109
+ return { state: initialResetControl(), effect: "none" };
110
+ return { ...state.stopAfterReset, boundary: "settle" };
99
111
  }
100
112
  const manual = request.phase === "pending" && request.command !== undefined;
101
113
  if (state.overflow === "pending" || state.overflow === "pending-spent") {
@@ -105,25 +117,22 @@ export function reduceResetControl(state, event) {
105
117
  // An explicit manual wipe is not an automatic recovery/retry. It must still
106
118
  // clear on overflow, including when automatic reset is disabled.
107
119
  if (manual && facts.enabled)
108
- return commandCommit(request);
120
+ return boundaryIntent(request, facts.windowId, "command-overflow");
109
121
  const spent = state.overflow === "pending-spent";
110
122
  if (!facts.enabled || !facts.automaticResetEnabled) {
111
123
  return { state: { request: facts.failed ? NO_REQUEST : request, overflow: spent ? "spent" : "idle" }, effect: "none" };
112
124
  }
113
- return { state: { request: NO_REQUEST, overflow: "spent" }, effect: spent ? "none" : "recover-overflow", ...requestDetails(request) };
125
+ if (spent)
126
+ return { state: { request: NO_REQUEST, overflow: "spent" }, effect: "none" };
127
+ return boundaryIntent(request, facts.windowId, "overflow-recovery");
114
128
  }
115
129
  if (facts.failed || !facts.enabled || !manual) {
116
130
  return { state: { ...state, request: NO_REQUEST }, effect: "none" };
117
131
  }
118
132
  if (facts.queued)
119
133
  return { state: { ...state, request }, effect: "none" };
120
- return commandCommit(request);
134
+ return boundaryIntent(request, facts.windowId, "settle");
121
135
  }
122
- case "settled":
123
- return { state: initialResetControl(), effect: "none" };
124
- case "abort":
125
- case "clear":
126
- return { state: initialResetControl(), effect: "none" };
127
136
  }
128
137
  }
129
138
  /**
@@ -135,8 +144,32 @@ export function registerResetLifecycle(pi, options) {
135
144
  let sessionActive = true;
136
145
  let lifecycleGeneration = 0;
137
146
  let control = initialResetControl();
138
- const clear = () => { control = reduceResetControl(control, { type: "clear" }).state; };
139
- const resetBoundaryResult = async (entries, ctx, continueAfterReset, lastWord, origin) => {
147
+ let runInputs = [];
148
+ let commandId;
149
+ // Once input returns handled, Pi no longer owns its original content. If close-out
150
+ // fails/cancels, return that content to the transcript without starting another run.
151
+ const restoreCommandInputs = () => {
152
+ const request = control.request;
153
+ if (request.phase !== "pending" || !request.command?.inputs?.length)
154
+ return;
155
+ const inputs = request.command.inputs;
156
+ control = { ...control, request: { ...request, command: { ...request.command, inputs: [] } } };
157
+ for (const draft of carriedInputDrafts(inputs)) {
158
+ pi.sendMessage(draft, { triggerTurn: false });
159
+ }
160
+ runInputs.push(...inputs);
161
+ };
162
+ const clear = (preserveInputs = true) => {
163
+ lifecycleGeneration++;
164
+ if (preserveInputs)
165
+ restoreCommandInputs();
166
+ control = initialResetControl();
167
+ runInputs = [];
168
+ commandId = undefined;
169
+ };
170
+ const resetBoundaryResult = async (entries, ctx, intent) => {
171
+ // Keep command state live while notes load: input arriving during this await must
172
+ // join this very boundary even if its steer cannot reach the closing model.
140
173
  const generation = lifecycleGeneration;
141
174
  const outerGeneration = options.getLifecycleGeneration?.();
142
175
  const sessionId = ctx.sessionManager.getSessionId();
@@ -148,7 +181,7 @@ export function registerResetLifecycle(pi, options) {
148
181
  const firstSeq = nextHistorySeq(ctx, entries) + 1;
149
182
  let resetDrafts;
150
183
  try {
151
- resetDrafts = await options.buildReset(ctx, isCurrent, lastWord, firstSeq, origin);
184
+ resetDrafts = await options.buildReset(ctx, isCurrent, intent.tool?.lastWord, firstSeq, intent.origin);
152
185
  }
153
186
  catch (error) {
154
187
  if (isCurrent())
@@ -157,23 +190,59 @@ export function registerResetLifecycle(pi, options) {
157
190
  }
158
191
  if (!isCurrent())
159
192
  return entries.length > 0 ? { entries } : undefined;
193
+ const finalized = finalizeResetBoundary(intent, control.request, runInputs);
194
+ control = finalized.state;
195
+ runInputs = [];
160
196
  options.onResetReady?.(ctx, resetDrafts);
161
- return { entries: [...entries, ...resetDrafts], continue: continueAfterReset };
197
+ return { entries: [...entries, ...resetDrafts, ...carriedInputDrafts(finalized.inputs)], continue: finalized.resumeModel };
162
198
  };
199
+ // Pi may start multiple low-level loops while draining follow-ups/recovering.
200
+ // Keep the logical run's inputs until settlement or a successful boundary.
201
+ pi.on("message_end", (event) => {
202
+ if (event.message.role === "user")
203
+ runInputs.push(event.message.content);
204
+ });
205
+ pi.on("input", (event, ctx) => {
206
+ if (event.source === "extension" || !sessionActive || !options.isEnabled())
207
+ return undefined;
208
+ const request = control.request;
209
+ if (request.phase !== "pending" || !request.command || request.windowId !== currentWindowId(ctx))
210
+ return undefined;
211
+ const content = event.images?.length
212
+ ? [{ type: "text", text: event.text }, ...event.images]
213
+ : event.text;
214
+ control = reduceResetControl(control, { type: "input", windowId: request.windowId, input: content }).state;
215
+ const steerContent = event.images?.length
216
+ ? [{ type: "text", text: promptBlock(event.text) }, ...event.images]
217
+ : promptBlock(event.text);
218
+ pi.sendMessage({ customType: NEXT_WINDOW_PROMPT_TYPE, content: steerContent, display: false, details: { windowId: request.windowId, commandId } }, { deliverAs: "steer" });
219
+ return { action: "handled" };
220
+ });
163
221
  // Boundary continue:false is not a veto of Pi's tool-batch follow-up. Once the
164
222
  // safety reset is actually committed, cancel that empty follow-up before provider
165
223
  // work. Real queued user input is allowed through and answered before settlement.
166
224
  pi.on("context_with_system", (event, ctx) => {
167
225
  const request = control.request;
168
- if (!sessionActive || request.phase !== "stop-pending" || ctx.hasPendingMessages())
169
- return undefined;
226
+ // Steering can be queued during buildReset's await and arrive after the boundary.
227
+ // It is closing-model context only; originals already live in the carried entries.
228
+ const messages = event.messages.filter((message) => {
229
+ if (message.role !== "custom" || message.customType !== NEXT_WINDOW_PROMPT_TYPE)
230
+ return true;
231
+ const details = message.details;
232
+ return request.phase === "pending" && request.command !== undefined &&
233
+ request.windowId === currentWindowId(ctx) && details?.windowId === request.windowId && commandId !== undefined && details?.commandId === commandId;
234
+ });
235
+ const filtered = messages.length === event.messages.length ? undefined : { messages };
236
+ const stop = control.stopAfterReset;
237
+ if (!sessionActive || !stop || ctx.hasPendingMessages())
238
+ return filtered;
170
239
  const marker = currentReset(ctx);
171
- if (!marker || marker.data.windowId === request.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId))
172
- return undefined;
240
+ if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId))
241
+ return filtered;
173
242
  const branch = ctx.sessionManager.getBranch();
174
243
  const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
175
- if (branch.slice(markerIndex + 1).some((entry) => entry.type === "message" && entry.message.role === "user"))
176
- return undefined;
244
+ if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry)))
245
+ return filtered;
177
246
  ctx.abort();
178
247
  const system = getCurrentSystemMessage(event.messages);
179
248
  return { messages: system ? [system] : [] };
@@ -198,9 +267,11 @@ export function registerResetLifecycle(pi, options) {
198
267
  get hardReserveDue() { return options.budget.hardReserveDue(ctx); },
199
268
  },
200
269
  });
270
+ if (decision.effect === "build-boundary")
271
+ return await resetBoundaryResult(entries, ctx, decision);
272
+ if (aborted || (event.outcome === "error" && decision.state.request.phase === "none"))
273
+ restoreCommandInputs();
201
274
  control = decision.state;
202
- if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop")
203
- return await resetBoundaryResult(entries, ctx, decision.effect === "commit-boundary", decision.lastWord, decision.origin ?? "forced");
204
275
  return entries.length > 0 ? { entries } : undefined;
205
276
  });
206
277
  pi.on("agent_before_settle", async (event, ctx) => {
@@ -217,12 +288,14 @@ export function registerResetLifecycle(pi, options) {
217
288
  failed: event.outcome === "error",
218
289
  },
219
290
  });
291
+ if (decision.effect === "build-boundary")
292
+ return await resetBoundaryResult(event.entries, ctx, decision);
293
+ if (decision.state.request.phase === "none")
294
+ restoreCommandInputs();
220
295
  control = decision.state;
221
296
  if (decision.effect === "stop")
222
297
  return { entries: event.entries, continue: false };
223
- if (decision.effect !== "commit-boundary" && decision.effect !== "commit-boundary-stop" && decision.effect !== "recover-overflow")
224
- return undefined;
225
- return await resetBoundaryResult(event.entries, ctx, decision.effect !== "commit-boundary-stop", decision.lastWord, decision.origin ?? "forced");
298
+ return undefined;
226
299
  });
227
300
  pi.on("session_before_compact", (event, ctx) => {
228
301
  if (!sessionActive)
@@ -240,18 +313,20 @@ export function registerResetLifecycle(pi, options) {
240
313
  });
241
314
  pi.on("agent_end", (_event, ctx) => {
242
315
  if (ctx.signal?.aborted)
243
- control = reduceResetControl(control, { type: "abort" }).state;
316
+ clear();
244
317
  });
245
318
  pi.on("agent_settled", () => {
246
- control = reduceResetControl(control, { type: "settled" }).state;
319
+ clear();
247
320
  });
248
- pi.on("session_start", () => { lifecycleGeneration++; clear(); sessionActive = true; });
249
- pi.on("session_tree", () => { lifecycleGeneration++; clear(); });
250
- pi.on("session_shutdown", () => { lifecycleGeneration++; clear(); options.budget.clear(); sessionActive = false; });
321
+ pi.on("session_start", () => { clear(false); sessionActive = true; });
322
+ pi.on("session_tree", () => { clear(false); });
323
+ pi.on("session_shutdown", () => { clear(false); options.budget.clear(); sessionActive = false; });
251
324
  return {
252
- command(windowId, continueAfterReset) {
253
- const decision = reduceResetControl(control, { type: "command", windowId, continueAfterReset });
325
+ command(windowId, continueAfterReset, input) {
326
+ const decision = reduceResetControl(control, { type: "command", windowId, continueAfterReset, ...(input !== undefined ? { input } : {}) });
254
327
  control = decision.state;
328
+ if (decision.effect === "close-out-armed")
329
+ commandId = randomUUID();
255
330
  return decision.effect;
256
331
  },
257
332
  request(windowId, lastWord) {
@@ -6,9 +6,9 @@ import { registerBudget } from "./budget.js";
6
6
  import { output } from "./tool-result.js";
7
7
  import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, markerResetOrigin, projectRootWindow, projectWindow, rootWindowId } from "./window.js";
8
8
  import { registerResetLifecycle } from "./reset/lifecycle.js";
9
- import { buildResetDrafts, LAST_WORD_PREFIX, MAX_LAST_WORD_CHARS, repairResetTail, sanitizeLastWord } from "./reset/artifacts.js";
10
- import { BOOT_TYPE, MANUAL_WIPE_TYPE, RESET_LAST_WORD_TYPE } from "./entries.js";
11
- import { warningContent } from "./text.js";
9
+ import { buildResetDrafts, MAX_LAST_WORD_CHARS, repairResetTail, sanitizeLastWord } from "./reset/artifacts.js";
10
+ import { BOOT_TYPE, MANUAL_WIPE_TYPE } from "./entries.js";
11
+ import { commandWarningContent } from "./text.js";
12
12
  import { buildBootMessage, sendBoot } from "./boot.js";
13
13
  import { nextHistorySeq } from "./history.js";
14
14
  import { errorMessage } from "../../src/error-message.js";
@@ -72,11 +72,10 @@ export function registerContext(pi, settingsManager) {
72
72
  if (!marker || !isCheckpointBackedReset(ctx, marker) || !resetBoundaryCommitted(ctx, marker.id, windowId))
73
73
  continue;
74
74
  pendingResetNotices.delete(windowId);
75
- const tail = branch.slice(branch.indexOf(marker) + 1);
76
- const lastWordEntry = tail.find((entry) => entry.customType === RESET_LAST_WORD_TYPE);
77
- const lastWord = lastWordEntry?.content?.startsWith(LAST_WORD_PREFIX) ? lastWordEntry.content.slice(LAST_WORD_PREFIX.length) : undefined;
75
+ // The last word already lands as its own visible sticky-note entry; the
76
+ // committed notice stays a one-line marker instead of repeating it.
78
77
  const forced = markerResetOrigin(marker) === "forced";
79
- ctx.ui.notify(`🥣 Brain emptied${forced ? " forcibly: overflow" : ""}${lastWord ? ` · last word: “${lastWord}”` : ""}`, forced ? "warning" : "info");
78
+ ctx.ui.notify(forced ? "🥣 Brain forcibly emptied: overflow" : "🥣 Fresh brain", forced ? "warning" : "info");
80
79
  }
81
80
  };
82
81
  pi.on("turn_start", (_event, ctx) => notifyCommittedResets(ctx));
@@ -187,15 +186,15 @@ export function registerContext(pi, settingsManager) {
187
186
  // Manual wipes close out at settlement, then stop or continue with the prompt. The hidden warning goes out in both cases — triggered when idle,
188
187
  // steered into the running turn when busy — so the agent closes out promptly
189
188
  // instead of the reset waiting for the whole run.
190
- const prompt = args.trim() || undefined;
191
- const armed = resets.command(requestedWindowId, prompt !== undefined);
189
+ const prompt = args.trim() ? args : undefined;
190
+ const armed = resets.command(requestedWindowId, prompt !== undefined, prompt);
192
191
  if (armed === "already-pending") {
193
192
  cmdCtx.ui.notify("🥣 Brain already being emptied", "info");
194
193
  return;
195
194
  }
196
195
  cmdCtx.ui.notify("🥣 Brain being emptied", "info");
197
196
  try {
198
- pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: warningContent(prompt ? `/empty ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
197
+ pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: commandWarningContent(prompt !== undefined ? `/empty ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
199
198
  }
200
199
  catch (error) {
201
200
  resets.clear();
@@ -4,20 +4,17 @@
4
4
  * view intact must not carry these — the claim would be false there. The bare `empty_brain` token
5
5
  * is interpolated by renderProtocolBlock; the prose itself stays plain English.
6
6
  */
7
- export declare const PI_PRE_RESET_HINTS = "Resetting clears the human's chat view too. Don't put a long explanation right before a reset and assume they'll still be able to read it. Save the handoff in notes; give the explanation after the reset.\nUnless the human explicitly directs otherwise, decide for yourself when to call empty_brain. Don't keep asking them whether to reset.";
7
+ export declare const PI_PRE_RESET_HINTS = "Anything you say here is erased with the reset \u2014 the human can't read it afterward either. Put the handoff in your notes; explanations belong after the reset.\nUnless the human explicitly directs otherwise, decide for yourself when to call empty_brain. Don't keep asking them whether to reset.";
8
8
  /** Pi-only nudge: pi's empty_brain persists a parting line; the dsh tool has no such parameter. */
9
9
  export declare const LAST_WORD_HINT = "If you want, pass `empty_brain` a `last_word`: a tiny sticky note (at most 250 characters) slapped on your forehead after the wipe.";
10
- /**
11
- * With a prompt attached the close-out is an order rather than a nudge: the human already
12
- * said when to reset, and a task line for the next window just preceded it. Only Pi has a
13
- * reset command that takes a prompt, so this lives with the Pi text.
14
- */
15
- export declare const WARNING_CALL_PROMPTED = "Organize the notes first, then call `empty_brain` right away \u2014 do not wait to be cut off.";
16
- /**
17
- * The human typed `/empty <prompt>`: the raw command line leads the close-out so the
18
- * closing model sees what the next window was asked to do, verbatim. The tag names it as the
19
- * next window's prompt, so no prose has to explain that.
20
- */
10
+ /** The closing model sees deferred input as a bare next-window prompt block. */
21
11
  export declare function promptBlock(commandLine: string): string;
22
- /** The hidden checkpoint text for Pi's manual/budget-triggered requests (dsh reads warningPrompt() directly). */
23
- export declare function warningContent(commandLine?: string): string;
12
+ /** Pi's hidden budget warning (dsh reads warningPrompt() directly). */
13
+ export declare function warningContent(): string;
14
+ /** Approved manual close-out notices; both variants live here. */
15
+ export declare const COMMAND_NOTICE: {
16
+ prompted: string;
17
+ bare: string;
18
+ };
19
+ /** Manual orders omit budget timing hints; deferred work sits outside the notice. */
20
+ export declare function commandWarningContent(commandLine?: string): string;