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
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
3
  import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
3
4
  import type { AgentBeforeSettleEvent, ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
@@ -6,6 +7,9 @@ import { nextHistorySeq } from "../history.js";
6
7
  import { resetBoundaryCommitted } from "./committed.js";
7
8
  import type { ResetOrigin } from "../../../src/budget/text.js";
8
9
  import { errorMessage } from "../../../src/error-message.js";
10
+ import { carriedInputDrafts, isCarriedInputEntry, type CarriedInput } from "./artifacts.js";
11
+ import { NEXT_WINDOW_PROMPT_TYPE } from "../entries.js";
12
+ import { promptBlock } from "../text.js";
9
13
 
10
14
  type BudgetOwner = {
11
15
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
@@ -34,15 +38,15 @@ function isOverflowLike(message: AgentMessage, ctx: ExtensionContext): boolean {
34
38
 
35
39
  export type ResetRequest =
36
40
  | { readonly phase: "none" }
37
- // A hard-reserve reset may precede the end of Pi's tool-batch continuation.
38
- | { readonly phase: "stop-pending"; readonly windowId: string; readonly tool?: { readonly lastWord?: string } }
39
41
  | { readonly phase: "pending"; readonly windowId: string;
40
- readonly command?: { readonly continueAfterReset: boolean };
42
+ readonly command?: { readonly continueAfterReset: boolean; readonly inputs?: readonly CarriedInput[] };
41
43
  readonly tool?: { readonly lastWord?: string } };
42
44
  export type ResetOverflowPhase = "idle" | "pending" | "pending-spent" | "spent";
43
45
 
44
46
  export interface ResetControlState {
45
47
  readonly request: ResetRequest;
48
+ /** Await settlement after a safety reset; retain its intent to retry if it never committed. */
49
+ readonly stopAfterReset?: ResetBoundaryIntent;
46
50
  readonly overflow: ResetOverflowPhase;
47
51
  }
48
52
 
@@ -75,60 +79,69 @@ export interface ResetBeforeSettleFacts {
75
79
  }
76
80
 
77
81
  export type ResetControlEvent =
78
- | { readonly type: "command"; readonly windowId: string; readonly continueAfterReset: boolean }
82
+ | { readonly type: "command"; readonly windowId: string; readonly continueAfterReset: boolean; readonly input?: CarriedInput }
83
+ | { readonly type: "input"; readonly windowId: string; readonly input: CarriedInput }
79
84
  | { readonly type: "tool_request"; readonly windowId: string; readonly lastWord?: string }
80
85
  | { readonly type: "turn_end"; readonly facts: ResetTurnEndFacts }
81
- | { readonly type: "before_settle"; readonly facts: ResetBeforeSettleFacts }
82
- | { readonly type: "settled" }
83
- | { readonly type: "abort" }
84
- | { readonly type: "clear" };
86
+ | { readonly type: "before_settle"; readonly facts: ResetBeforeSettleFacts };
85
87
 
86
- export type ResetControlEffect =
87
- | "none"
88
- | "close-out-armed"
89
- | "already-pending"
90
- | "commit-boundary"
91
- | "commit-boundary-stop"
92
- | "stop"
93
- | "recover-overflow";
94
-
95
- export interface ResetControlResult {
96
- readonly state: ResetControlState;
97
- readonly effect: ResetControlEffect;
98
- readonly lastWord?: string;
99
- /** The origin of the boundary this decision commits. Absent means no `empty_brain` call was recorded, so forced. */
100
- readonly origin?: ResetOrigin;
88
+ /** Construction intent, not final state: handled inputs can still arrive while notes load. Only `turn-end`
89
+ * may latch a stop; overflow kinds spend recovery; only `overflow-recovery` carries passive run inputs. */
90
+ export interface ResetBoundaryIntent {
91
+ readonly effect: "build-boundary";
92
+ readonly boundary: "turn-end" | "settle" | "command-overflow" | "overflow-recovery";
93
+ readonly windowId: string;
94
+ readonly continueAfterReset: boolean;
95
+ readonly origin: ResetOrigin;
96
+ readonly tool?: { readonly lastWord?: string };
101
97
  }
102
98
 
99
+ export type ResetControlResult = ResetBoundaryIntent |
100
+ { readonly state: ResetControlState; readonly effect: "none" | "close-out-armed" | "already-pending" | "stop" };
101
+
103
102
  function requestForWindow(request: ResetRequest, windowId: string): ResetRequest {
104
- return request.phase === "stop-pending" || (request.phase !== "none" && request.windowId === windowId) ? request : NO_REQUEST;
103
+ return request.phase === "pending" && request.windowId === windowId ? request : NO_REQUEST;
105
104
  }
106
105
 
107
- function commandCommit(request: Extract<ResetRequest, { phase: "pending" }>): ResetControlResult {
108
- return {
109
- state: initialResetControl(),
110
- effect: request.command?.continueAfterReset ? "commit-boundary" : "commit-boundary-stop",
111
- ...requestDetails(request),
112
- };
113
- }
106
+ const spendsOverflow = (boundary: ResetBoundaryIntent["boundary"]) => boundary === "command-overflow" || boundary === "overflow-recovery";
114
107
 
115
- /** The tool request itself is the origin fact; the stop latch retains it for construction retry. */
116
- function requestDetails(request: ResetRequest): { origin: ResetOrigin; lastWord?: string } {
108
+ function boundaryIntent(request: ResetRequest, windowId: string, boundary: ResetBoundaryIntent["boundary"]): ResetBoundaryIntent {
117
109
  const tool = request.phase === "none" ? undefined : request.tool;
118
- return { origin: tool ? "normal" : "forced", ...tool };
110
+ const continueAfterReset = request.phase === "pending" ? request.command?.continueAfterReset ?? true : true;
111
+ return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal" };
112
+ }
113
+
114
+ /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
115
+ export function finalizeResetBoundary(intent: ResetBoundaryIntent, request: ResetRequest, passiveInputs: readonly CarriedInput[] = []) {
116
+ const inputs = request.phase === "pending" && request.command ? request.command.inputs ?? []
117
+ : intent.boundary === "overflow-recovery" ? passiveInputs : [];
118
+ const resumeModel = intent.continueAfterReset || inputs.length > 0;
119
+ const state: ResetControlState = {
120
+ request: NO_REQUEST,
121
+ ...(intent.boundary === "turn-end" && !resumeModel ? { stopAfterReset: intent } : {}),
122
+ overflow: spendsOverflow(intent.boundary) ? "spent" : "idle",
123
+ };
124
+ return { state, inputs, resumeModel };
119
125
  }
120
126
 
121
127
  /** Pure transitions: command policy schedules a reset without disguising actual tool calls. */
128
+ export function reduceResetControl(state: ResetControlState, event: Extract<ResetControlEvent, { type: "input" | "command" | "tool_request" }>): Extract<ResetControlResult, { state: ResetControlState }>;
129
+ export function reduceResetControl(state: ResetControlState, event: ResetControlEvent): ResetControlResult;
122
130
  export function reduceResetControl(state: ResetControlState, event: ResetControlEvent): ResetControlResult {
123
131
  switch (event.type) {
132
+ case "input": {
133
+ const request = requestForWindow(state.request, event.windowId);
134
+ if (request.phase !== "pending" || !request.command) return { state, effect: "none" };
135
+ return { state: { ...state, request: { ...request, command: { ...request.command, inputs: [...(request.command.inputs ?? []), event.input] } } }, effect: "none" };
136
+ }
124
137
  case "command":
125
138
  case "tool_request": {
139
+ if (state.stopAfterReset) return { state, effect: "already-pending" };
126
140
  const current = requestForWindow(state.request, event.windowId);
127
- if (current.phase === "stop-pending") return { state, effect: "already-pending" };
128
141
  const request = current.phase === "pending" ? current : { phase: "pending" as const, windowId: event.windowId };
129
142
  if (event.type === "command") {
130
143
  if (request.command) return { state, effect: "already-pending" };
131
- return { state: { ...state, request: { ...request, command: { continueAfterReset: event.continueAfterReset } } }, effect: "close-out-armed" };
144
+ return { state: { ...state, request: { ...request, command: { continueAfterReset: event.continueAfterReset, ...(event.input !== undefined ? { inputs: [event.input] } : {}) } } }, effect: "close-out-armed" };
132
145
  }
133
146
  // The call remains a real request even when command policy delays its commit.
134
147
  const duplicate = request.tool !== undefined;
@@ -140,7 +153,7 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
140
153
  const facts = event.facts;
141
154
  const request = requestForWindow(state.request, facts.windowId);
142
155
  if (facts.aborted) return { state: initialResetControl(), effect: "none" };
143
- if (request.phase === "stop-pending") return { state: { request, overflow: "idle" }, effect: "none" };
156
+ if (state.stopAfterReset) return { state: { ...state, overflow: "idle" }, effect: "none" };
144
157
  const manual = request.phase === "pending" && request.command !== undefined;
145
158
  if (facts.overflow) {
146
159
  const pending = manual ? facts.enabled : !facts.queued && facts.enabled && facts.automaticResetEnabled;
@@ -157,9 +170,7 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
157
170
  // A direct tool request commits after the whole tool batch. The budget cutoff is
158
171
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
159
172
  if ((request.phase === "pending" && request.tool && !manual) || facts.hardReserveDue) {
160
- if (manual && request.command?.continueAfterReset) return commandCommit(request);
161
- if (manual) return { state: { request: { phase: "stop-pending", windowId: facts.windowId, ...(request.tool ? { tool: request.tool } : {}) }, overflow: "idle" }, effect: "commit-boundary-stop", ...requestDetails(request) };
162
- return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary", ...requestDetails(request) };
173
+ return boundaryIntent(request, facts.windowId, "turn-end");
163
174
  }
164
175
  return { state: { request, overflow: "idle" }, effect: "none" };
165
176
  }
@@ -167,12 +178,12 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
167
178
  const facts = event.facts;
168
179
  if (facts.aborted) return { state: initialResetControl(), effect: "none" };
169
180
  const request = requestForWindow(state.request, facts.windowId);
170
- if (request.phase === "stop-pending") {
181
+ if (state.stopAfterReset) {
171
182
  if (facts.queued) return { state, effect: "none" };
172
- // Only retry construction if the safety boundary never committed. Otherwise
173
- // stop without a second wipe, even if a queued turn subsequently failed.
174
- if (request.windowId !== facts.windowId) return { state: initialResetControl(), effect: "stop" };
175
- return { state: initialResetControl(), effect: facts.failed || !facts.enabled ? "none" : "commit-boundary-stop", ...requestDetails(request) };
183
+ // A changed window confirms commit: stop without wiping twice. Otherwise retry.
184
+ if (state.stopAfterReset.windowId !== facts.windowId) return { state: initialResetControl(), effect: "stop" };
185
+ if (facts.failed || !facts.enabled) return { state: initialResetControl(), effect: "none" };
186
+ return { ...state.stopAfterReset, boundary: "settle" };
176
187
  }
177
188
  const manual = request.phase === "pending" && request.command !== undefined;
178
189
  if (state.overflow === "pending" || state.overflow === "pending-spent") {
@@ -181,24 +192,20 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
181
192
  }
182
193
  // An explicit manual wipe is not an automatic recovery/retry. It must still
183
194
  // clear on overflow, including when automatic reset is disabled.
184
- if (manual && facts.enabled) return commandCommit(request);
195
+ if (manual && facts.enabled) return boundaryIntent(request, facts.windowId, "command-overflow");
185
196
  const spent = state.overflow === "pending-spent";
186
197
  if (!facts.enabled || !facts.automaticResetEnabled) {
187
198
  return { state: { request: facts.failed ? NO_REQUEST : request, overflow: spent ? "spent" : "idle" }, effect: "none" };
188
199
  }
189
- return { state: { request: NO_REQUEST, overflow: "spent" }, effect: spent ? "none" : "recover-overflow", ...requestDetails(request) };
200
+ if (spent) return { state: { request: NO_REQUEST, overflow: "spent" }, effect: "none" };
201
+ return boundaryIntent(request, facts.windowId, "overflow-recovery");
190
202
  }
191
203
  if (facts.failed || !facts.enabled || !manual) {
192
204
  return { state: { ...state, request: NO_REQUEST }, effect: "none" };
193
205
  }
194
206
  if (facts.queued) return { state: { ...state, request }, effect: "none" };
195
- return commandCommit(request);
207
+ return boundaryIntent(request, facts.windowId, "settle");
196
208
  }
197
- case "settled":
198
- return { state: initialResetControl(), effect: "none" };
199
- case "abort":
200
- case "clear":
201
- return { state: initialResetControl(), effect: "none" };
202
209
  }
203
210
  }
204
211
 
@@ -211,9 +218,31 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
211
218
  let sessionActive = true;
212
219
  let lifecycleGeneration = 0;
213
220
  let control = initialResetControl();
221
+ let runInputs: CarriedInput[] = [];
222
+ let commandId: string | undefined;
214
223
 
215
- const clear = () => { control = reduceResetControl(control, { type: "clear" }).state; };
216
- const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, continueAfterReset: boolean, lastWord: string | undefined, origin: ResetOrigin) => {
224
+ // Once input returns handled, Pi no longer owns its original content. If close-out
225
+ // fails/cancels, return that content to the transcript without starting another run.
226
+ const restoreCommandInputs = () => {
227
+ const request = control.request;
228
+ if (request.phase !== "pending" || !request.command?.inputs?.length) return;
229
+ const inputs = request.command.inputs;
230
+ control = { ...control, request: { ...request, command: { ...request.command, inputs: [] } } };
231
+ for (const draft of carriedInputDrafts(inputs)) {
232
+ pi.sendMessage(draft, { triggerTurn: false });
233
+ }
234
+ runInputs.push(...inputs);
235
+ };
236
+ const clear = (preserveInputs = true) => {
237
+ lifecycleGeneration++;
238
+ if (preserveInputs) restoreCommandInputs();
239
+ control = initialResetControl();
240
+ runInputs = [];
241
+ commandId = undefined;
242
+ };
243
+ const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, intent: ResetBoundaryIntent) => {
244
+ // Keep command state live while notes load: input arriving during this await must
245
+ // join this very boundary even if its steer cannot reach the closing model.
217
246
  const generation = lifecycleGeneration;
218
247
  const outerGeneration = options.getLifecycleGeneration?.();
219
248
  const sessionId = ctx.sessionManager.getSessionId();
@@ -225,27 +254,60 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
225
254
  const firstSeq = nextHistorySeq(ctx, entries) + 1;
226
255
  let resetDrafts: SessionBoundaryDraft[];
227
256
  try {
228
- resetDrafts = await options.buildReset(ctx, isCurrent, lastWord, firstSeq, origin);
257
+ resetDrafts = await options.buildReset(ctx, isCurrent, intent.tool?.lastWord, firstSeq, intent.origin);
229
258
  } catch (error) {
230
259
  if (isCurrent()) ctx.ui.notify(`๐Ÿฅฃ Brain still full: ${errorMessage(error)}`, "warning");
231
260
  return entries.length > 0 ? { entries } : undefined;
232
261
  }
233
262
  if (!isCurrent()) return entries.length > 0 ? { entries } : undefined;
263
+ const finalized = finalizeResetBoundary(intent, control.request, runInputs);
264
+ control = finalized.state;
265
+ runInputs = [];
234
266
  options.onResetReady?.(ctx, resetDrafts);
235
- return { entries: [...entries, ...resetDrafts], continue: continueAfterReset };
267
+ return { entries: [...entries, ...resetDrafts, ...carriedInputDrafts(finalized.inputs)], continue: finalized.resumeModel };
236
268
  };
237
269
 
270
+ // Pi may start multiple low-level loops while draining follow-ups/recovering.
271
+ // Keep the logical run's inputs until settlement or a successful boundary.
272
+ pi.on("message_end", (event) => {
273
+ if (event.message.role === "user") runInputs.push(event.message.content);
274
+ });
275
+ pi.on("input", (event, ctx) => {
276
+ if (event.source === "extension" || !sessionActive || !options.isEnabled()) return undefined;
277
+ const request = control.request;
278
+ if (request.phase !== "pending" || !request.command || request.windowId !== currentWindowId(ctx)) return undefined;
279
+ const content: CarriedInput = event.images?.length
280
+ ? [{ type: "text", text: event.text }, ...event.images]
281
+ : event.text;
282
+ control = reduceResetControl(control, { type: "input", windowId: request.windowId, input: content }).state;
283
+ const steerContent: CarriedInput = event.images?.length
284
+ ? [{ type: "text", text: promptBlock(event.text) }, ...event.images]
285
+ : promptBlock(event.text);
286
+ pi.sendMessage({ customType: NEXT_WINDOW_PROMPT_TYPE, content: steerContent, display: false, details: { windowId: request.windowId, commandId } }, { deliverAs: "steer" });
287
+ return { action: "handled" };
288
+ });
289
+
238
290
  // Boundary continue:false is not a veto of Pi's tool-batch follow-up. Once the
239
291
  // safety reset is actually committed, cancel that empty follow-up before provider
240
292
  // work. Real queued user input is allowed through and answered before settlement.
241
293
  pi.on("context_with_system", (event, ctx) => {
242
294
  const request = control.request;
243
- if (!sessionActive || request.phase !== "stop-pending" || ctx.hasPendingMessages()) return undefined;
295
+ // Steering can be queued during buildReset's await and arrive after the boundary.
296
+ // It is closing-model context only; originals already live in the carried entries.
297
+ const messages = event.messages.filter((message) => {
298
+ if (message.role !== "custom" || message.customType !== NEXT_WINDOW_PROMPT_TYPE) return true;
299
+ const details = message.details as { windowId?: unknown; commandId?: unknown } | undefined;
300
+ return request.phase === "pending" && request.command !== undefined &&
301
+ request.windowId === currentWindowId(ctx) && details?.windowId === request.windowId && commandId !== undefined && details?.commandId === commandId;
302
+ });
303
+ const filtered = messages.length === event.messages.length ? undefined : { messages };
304
+ const stop = control.stopAfterReset;
305
+ if (!sessionActive || !stop || ctx.hasPendingMessages()) return filtered;
244
306
  const marker = currentReset(ctx);
245
- if (!marker || marker.data.windowId === request.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId)) return undefined;
307
+ if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId)) return filtered;
246
308
  const branch = ctx.sessionManager.getBranch();
247
309
  const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
248
- if (branch.slice(markerIndex + 1).some((entry) => entry.type === "message" && entry.message.role === "user")) return undefined;
310
+ if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry))) return filtered;
249
311
  ctx.abort();
250
312
  const system = getCurrentSystemMessage(event.messages);
251
313
  return { messages: system ? [system] : [] };
@@ -270,8 +332,9 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
270
332
  get hardReserveDue() { return options.budget.hardReserveDue(ctx); },
271
333
  },
272
334
  });
335
+ if (decision.effect === "build-boundary") return await resetBoundaryResult(entries, ctx, decision);
336
+ if (aborted || (event.outcome === "error" && decision.state.request.phase === "none")) restoreCommandInputs();
273
337
  control = decision.state;
274
- if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop") return await resetBoundaryResult(entries, ctx, decision.effect === "commit-boundary", decision.lastWord, decision.origin ?? "forced");
275
338
  return entries.length > 0 ? { entries } : undefined;
276
339
  });
277
340
 
@@ -288,10 +351,11 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
288
351
  failed: event.outcome === "error",
289
352
  },
290
353
  });
354
+ if (decision.effect === "build-boundary") return await resetBoundaryResult(event.entries, ctx, decision);
355
+ if (decision.state.request.phase === "none") restoreCommandInputs();
291
356
  control = decision.state;
292
357
  if (decision.effect === "stop") return { entries: event.entries, continue: false };
293
- if (decision.effect !== "commit-boundary" && decision.effect !== "commit-boundary-stop" && decision.effect !== "recover-overflow") return undefined;
294
- return await resetBoundaryResult(event.entries, ctx, decision.effect !== "commit-boundary-stop", decision.lastWord, decision.origin ?? "forced");
358
+ return undefined;
295
359
  });
296
360
 
297
361
  pi.on("session_before_compact", (event, ctx) => {
@@ -308,19 +372,20 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
308
372
  });
309
373
 
310
374
  pi.on("agent_end", (_event, ctx) => {
311
- if (ctx.signal?.aborted) control = reduceResetControl(control, { type: "abort" }).state;
375
+ if (ctx.signal?.aborted) clear();
312
376
  });
313
377
  pi.on("agent_settled", () => {
314
- control = reduceResetControl(control, { type: "settled" }).state;
378
+ clear();
315
379
  });
316
- pi.on("session_start", () => { lifecycleGeneration++; clear(); sessionActive = true; });
317
- pi.on("session_tree", () => { lifecycleGeneration++; clear(); });
318
- pi.on("session_shutdown", () => { lifecycleGeneration++; clear(); options.budget.clear(); sessionActive = false; });
380
+ pi.on("session_start", () => { clear(false); sessionActive = true; });
381
+ pi.on("session_tree", () => { clear(false); });
382
+ pi.on("session_shutdown", () => { clear(false); options.budget.clear(); sessionActive = false; });
319
383
 
320
384
  return {
321
- command(windowId: string, continueAfterReset: boolean) {
322
- const decision = reduceResetControl(control, { type: "command", windowId, continueAfterReset });
385
+ command(windowId: string, continueAfterReset: boolean, input?: CarriedInput) {
386
+ const decision = reduceResetControl(control, { type: "command", windowId, continueAfterReset, ...(input !== undefined ? { input } : {}) });
323
387
  control = decision.state;
388
+ if (decision.effect === "close-out-armed") commandId = randomUUID();
324
389
  return decision.effect;
325
390
  },
326
391
  request(windowId: string, lastWord?: string) {
@@ -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, type WindowMarker } 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, type IncompleteNotesNotifier } 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: ExtensionAPI, settingsManager?: SettingsMana
72
72
  const marker = branch.find((entry): entry is WindowMarker => isWindowMarker(entry) && entry.data.windowId === windowId);
73
73
  if (!marker || !isCheckpointBackedReset(ctx, marker) || !resetBoundaryCommitted(ctx, marker.id, windowId)) continue;
74
74
  pendingResetNotices.delete(windowId);
75
- const tail = branch.slice(branch.indexOf(marker) + 1);
76
- const lastWordEntry = tail.find((entry) => (entry as { customType?: string }).customType === RESET_LAST_WORD_TYPE) as { content?: string } | undefined;
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));
@@ -183,15 +182,15 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
183
182
  // Manual wipes close out at settlement, then stop or continue with the prompt. The hidden warning goes out in both cases โ€” triggered when idle,
184
183
  // steered into the running turn when busy โ€” so the agent closes out promptly
185
184
  // instead of the reset waiting for the whole run.
186
- const prompt = args.trim() || undefined;
187
- const armed = resets.command(requestedWindowId, prompt !== undefined);
185
+ const prompt = args.trim() ? args : undefined;
186
+ const armed = resets.command(requestedWindowId, prompt !== undefined, prompt);
188
187
  if (armed === "already-pending") {
189
188
  cmdCtx.ui.notify("๐Ÿฅฃ Brain already being emptied", "info");
190
189
  return;
191
190
  }
192
191
  cmdCtx.ui.notify("๐Ÿฅฃ Brain being emptied", "info");
193
192
  try {
194
- pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: warningContent(prompt ? `/empty ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
193
+ pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: commandWarningContent(prompt !== undefined ? `/empty ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
195
194
  } catch (error) {
196
195
  resets.clear();
197
196
  cmdCtx.ui.notify(`๐Ÿฅฃ Brain refused to empty: ${errorMessage(error)}`, "error");
@@ -6,30 +6,30 @@ import { COUNTDOWN_LINE, GUIDANCE_CLOSE_TAG, GUIDANCE_OPEN_TAG, WARNING_BODY, WA
6
6
  * view intact must not carry these โ€” the claim would be false there. The bare `empty_brain` token
7
7
  * is interpolated by renderProtocolBlock; the prose itself stays plain English.
8
8
  */
9
- export 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.
9
+ export const PI_PRE_RESET_HINTS = `Anything you say here is erased with the reset โ€” the human can't read it afterward either. Put the handoff in your notes; explanations belong after the reset.
10
10
  Unless the human explicitly directs otherwise, decide for yourself when to call empty_brain. Don't keep asking them whether to reset.`;
11
11
 
12
12
  /** Pi-only nudge: pi's empty_brain persists a parting line; the dsh tool has no such parameter. */
13
13
  export 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.";
14
14
 
15
- /**
16
- * With a prompt attached the close-out is an order rather than a nudge: the human already
17
- * said when to reset, and a task line for the next window just preceded it. Only Pi has a
18
- * reset command that takes a prompt, so this lives with the Pi text.
19
- */
20
- export const WARNING_CALL_PROMPTED = "Organize the notes first, then call `empty_brain` right away โ€” do not wait to be cut off.";
21
-
22
- /**
23
- * The human typed `/empty <prompt>`: the raw command line leads the close-out so the
24
- * closing model sees what the next window was asked to do, verbatim. The tag names it as the
25
- * next window's prompt, so no prose has to explain that.
26
- */
15
+ /** The closing model sees deferred input as a bare next-window prompt block. */
27
16
  export function promptBlock(commandLine: string): string {
28
17
  return `<notesoup:next_window_prompt>\n${commandLine}\n</notesoup:next_window_prompt>`;
29
18
  }
30
19
 
31
- /** The hidden checkpoint text for Pi's manual/budget-triggered requests (dsh reads warningPrompt() directly). */
32
- export function warningContent(commandLine?: string): string {
33
- const closeOut = commandLine ? `${promptBlock(commandLine)}\n${WARNING_CALL_PROMPTED}` : WARNING_CALL;
34
- return `${GUIDANCE_OPEN_TAG}\n${WARNING_BODY}\n${closeOut}\n${PI_PRE_RESET_HINTS}\n${LAST_WORD_HINT}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}`;
20
+ /** Pi's hidden budget warning (dsh reads warningPrompt() directly). */
21
+ export function warningContent(): string {
22
+ return `${GUIDANCE_OPEN_TAG}\n${WARNING_BODY}\n${WARNING_CALL}\n${PI_PRE_RESET_HINTS}\n${LAST_WORD_HINT}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}`;
23
+ }
24
+
25
+ /** Approved manual close-out notices; both variants live here. */
26
+ export const COMMAND_NOTICE = {
27
+ 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 prompt below, and anything the human sends from now on, should be handled after the reset.",
28
+ bare: "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. Anything the human sends from now on should be handled after the reset.",
29
+ };
30
+
31
+ /** Manual orders omit budget timing hints; deferred work sits outside the notice. */
32
+ export function commandWarningContent(commandLine?: string): string {
33
+ const notice = commandLine ? COMMAND_NOTICE.prompted : COMMAND_NOTICE.bare;
34
+ return `${GUIDANCE_OPEN_TAG}\n${notice}\n${WARNING_BODY}\n${LAST_WORD_HINT}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}${commandLine ? `\n${promptBlock(commandLine)}` : ""}`;
35
35
  }