notesoup 0.62.0 → 0.63.0

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 (50) hide show
  1. package/README.md +1 -1
  2. package/dist/plugins/claude/src/helper.js +22 -4
  3. package/dist/plugins/claude/src/text.d.ts +7 -0
  4. package/dist/plugins/claude/src/text.js +12 -1
  5. package/dist/plugins/pi/budget.d.ts +3 -0
  6. package/dist/plugins/pi/budget.js +32 -6
  7. package/dist/plugins/pi/entries.d.ts +1 -0
  8. package/dist/plugins/pi/entries.js +1 -0
  9. package/dist/plugins/pi/reset/artifacts.d.ts +1 -1
  10. package/dist/plugins/pi/reset/artifacts.js +4 -4
  11. package/dist/plugins/pi/reset/lifecycle.d.ts +8 -1
  12. package/dist/plugins/pi/reset/lifecycle.js +101 -22
  13. package/dist/plugins/pi/runtime.js +4 -4
  14. package/dist/plugins/pi/tool-result.js +1 -1
  15. package/dist/plugins/pi/window.d.ts +2 -10
  16. package/dist/plugins/pi/window.js +32 -22
  17. package/dist/src/budget/text.d.ts +5 -1
  18. package/dist/src/budget/text.js +11 -2
  19. package/dist/src/index.d.ts +1 -1
  20. package/dist/test/agent-loop.test.js +197 -41
  21. package/dist/test/boot.integration.test.js +23 -1
  22. package/dist/test/budget-settings.integration.test.js +4 -4
  23. package/dist/test/claude-mod.test.js +192 -12
  24. package/dist/test/claude-validation.test.js +69 -2
  25. package/dist/test/dream-skill.test.js +3 -3
  26. package/dist/test/helpers/extension.d.ts +3 -1
  27. package/dist/test/helpers/extension.js +2 -2
  28. package/dist/test/model-facing-text.test.js +13 -3
  29. package/dist/test/reset-lifecycle.test.js +10 -0
  30. package/docs/claude-code-mod.md +6 -6
  31. package/docs/reset-lifecycle.md +1 -1
  32. package/docs/skills.md +2 -2
  33. package/package.json +1 -1
  34. package/plugins/antigravity/plugin.json +1 -1
  35. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  36. package/plugins/claude/dist/claude/helper.js +49 -5
  37. package/plugins/claude/hooks/register.ts +201 -61
  38. package/plugins/claude/skills/{notesoup → notesoup-guide}/SKILL.md +2 -2
  39. package/plugins/claude/src/helper.ts +22 -4
  40. package/plugins/claude/src/text.ts +14 -1
  41. package/plugins/pi/budget.ts +28 -5
  42. package/plugins/pi/entries.ts +1 -0
  43. package/plugins/pi/reset/artifacts.ts +4 -3
  44. package/plugins/pi/reset/lifecycle.ts +116 -22
  45. package/plugins/pi/runtime.ts +4 -4
  46. package/plugins/pi/tool-result.ts +1 -1
  47. package/plugins/pi/window.ts +30 -19
  48. package/skills/{notesoup → notesoup-guide}/SKILL.md +2 -2
  49. package/src/budget/text.ts +14 -2
  50. package/src/index.ts +1 -1
package/README.md CHANGED
@@ -96,7 +96,7 @@ Environment variables:
96
96
  - [Claude Code Mod](docs/claude-code-mod.md) — early-access notes and persisted-session history tools for Claude Code
97
97
  - [Codex plugin](docs/codex.md) — native notes boot and persisted history; compatibility is determined from host data, not a CLI version number
98
98
  - [Antigravity plugin](docs/antigravity.md) — automatic startup notes and the four notes tools over stdio MCP
99
- - [Skills and dream](docs/skills.md) — `/skill:notesoup`, `/skill:dream`, the `dream_*` tools and the dream lock
99
+ - [Skills and dream](docs/skills.md) — `/skill:notesoup-guide`, `/skill:dream`, the `dream_*` tools and the dream lock
100
100
 
101
101
  ## Development
102
102
 
@@ -1,4 +1,4 @@
1
- import { realpathSync } from "node:fs";
1
+ import { readFileSync, realpathSync } from "node:fs";
2
2
  import { pathToFileURL } from "node:url";
3
3
  import { Check } from "typebox/value";
4
4
  import { paramProblem } from "../../../src/tools/schema.js";
@@ -9,7 +9,7 @@ import { readClaudeHistory } from "./history.js";
9
9
  import { loadNotesSnapshot } from "../../../src/boot/snapshot.js";
10
10
  import { renderBootBlock } from "../../../src/boot/render.js";
11
11
  import { selectContinuation } from "../../../src/budget/text.js";
12
- import { claudeHistoryGapNotice, claudeHistoryUnconfirmedSeq, CLAUDE_HISTORY_UNKNOWN_WINDOW, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
12
+ import { claudeCommandWarningContent, claudeHistoryGapNotice, claudeHistoryUnconfirmedSeq, CLAUDE_COMMAND_PROMPTED_HEAD, CLAUDE_HISTORY_UNKNOWN_WINDOW, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
13
13
  import { resolveClaudeLimits } from "./thresholds.js";
14
14
  import { parseContextCap } from "../../../src/budget/cap.js";
15
15
  import { projectKey, snapshotNotesIdentity } from "../../../src/notes/index.js";
@@ -52,6 +52,18 @@ function historySource(value, sessionId) {
52
52
  throw new Error("Claude history binding belongs to a different session");
53
53
  return source;
54
54
  }
55
+ function readPluginVersion() {
56
+ for (const candidate of ["../../.claude-plugin/plugin.json", "../../../../package.json", "../../../package.json"]) {
57
+ try {
58
+ const parsed = JSON.parse(readFileSync(new URL(candidate, import.meta.url), "utf8"));
59
+ if (typeof parsed.version === "string" && parsed.version.length > 0)
60
+ return parsed.version;
61
+ }
62
+ catch { /* try the next layout */ }
63
+ }
64
+ return "dev";
65
+ }
66
+ const PLUGIN_VERSION = readPluginVersion();
55
67
  export async function dispatch(request, historyOptions = {}) {
56
68
  if (!request || typeof request !== "object" || Array.isArray(request))
57
69
  throw new Error("malformed request");
@@ -73,12 +85,18 @@ export async function dispatch(request, historyOptions = {}) {
73
85
  // The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
74
86
  // cannot drift apart. The hooks module caches one copy per session.
75
87
  if (value.op === "texts")
76
- return { warning: CLAUDE_WARNING_PROMPT, historyUnavailableSentence: CLAUDE_HISTORY_UNAVAILABLE_SENTENCE };
88
+ return {
89
+ version: PLUGIN_VERSION,
90
+ warning: CLAUDE_WARNING_PROMPT,
91
+ commandBare: claudeCommandWarningContent(),
92
+ commandPrompted: CLAUDE_COMMAND_PROMPTED_HEAD,
93
+ historyUnavailableSentence: CLAUDE_HISTORY_UNAVAILABLE_SENTENCE,
94
+ };
77
95
  // The caller draws once per artifact and caches the answer; text reads never draw.
78
96
  if (value.op === "continuation") {
79
97
  if (value.origin !== "normal" && value.origin !== "forced")
80
98
  throw new Error("invalid reset origin");
81
- return { text: selectContinuation(value.origin) };
99
+ return { text: selectContinuation(value.origin, { betweenTurns: value.betweenTurns === true }) };
82
100
  }
83
101
  // Threshold derivation crosses the boundary as raw facts: everything the engine could
84
102
  // read, unvalidated. resolveClaudeLimits guards every field and never throws.
@@ -2,6 +2,13 @@
2
2
  export declare const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in this Claude session: no main transcript_path was supplied. Keep essential state in notes; don't pretend those notes are the missing transcript.";
3
3
  /** The same notice as Pi; empty_brain's result explains Claude's deferred reset. */
4
4
  export declare const CLAUDE_WARNING_PROMPT: string;
5
+ /** Manual close-out notices omit budget timing and never claim Claude's chat view is erased. */
6
+ export declare const CLAUDE_COMMAND_NOTICE: {
7
+ prompted: string;
8
+ bare: string;
9
+ };
10
+ export declare const CLAUDE_COMMAND_PROMPTED_HEAD: string;
11
+ export declare function claudeCommandWarningContent(commandLine?: string): string;
5
12
  export declare const CLAUDE_HISTORY_UNKNOWN_WINDOW = "Claude history cannot determine the current window ordinal across a missing ancestor; restore the ancestry or use a retained notesoup boot to re-anchor it.";
6
13
  export declare function claudeHistoryUnconfirmedSeq(seq: number): string;
7
14
  /** Bounded host-only evidence, outside event documents/search offsets and shared schemas. */
@@ -1,8 +1,19 @@
1
- import { warningNotice } from "../../../src/budget/text.js";
1
+ import { COUNTDOWN_LINE, GUIDANCE_CLOSE_TAG, GUIDANCE_OPEN_TAG, WARNING_BODY, WARNING_CALL, warningNotice } from "../../../src/budget/text.js";
2
2
  /** Claude's boot says history is missing rather than naming tools it cannot serve. */
3
3
  export const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in this Claude session: no main transcript_path was supplied. Keep essential state in notes; don't pretend those notes are the missing transcript.";
4
4
  /** The same notice as Pi; empty_brain's result explains Claude's deferred reset. */
5
5
  export const CLAUDE_WARNING_PROMPT = warningNotice();
6
+ /** Manual close-out notices omit budget timing and never claim Claude's chat view is erased. */
7
+ export const CLAUDE_COMMAND_NOTICE = {
8
+ prompted: "The human ran /empty. Save your notes now and call `empty_brain` immediately. The command below is context for your notes, not a task for the fresh window.",
9
+ bare: "The human ran /empty. Save your notes now and call `empty_brain` immediately.",
10
+ };
11
+ export const CLAUDE_COMMAND_PROMPTED_HEAD = `${GUIDANCE_OPEN_TAG}\n${CLAUDE_COMMAND_NOTICE.prompted}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}`;
12
+ export function claudeCommandWarningContent(commandLine) {
13
+ if (commandLine)
14
+ return `${CLAUDE_COMMAND_PROMPTED_HEAD}\n${commandLine}`;
15
+ return `${GUIDANCE_OPEN_TAG}\n${CLAUDE_COMMAND_NOTICE.bare}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}`;
16
+ }
6
17
  export const CLAUDE_HISTORY_UNKNOWN_WINDOW = "Claude history cannot determine the current window ordinal across a missing ancestor; restore the ancestry or use a retained notesoup boot to re-anchor it.";
7
18
  export function claudeHistoryUnconfirmedSeq(seq) {
8
19
  return `Seq ${seq} is outside the confirmed selected history; it may be on another branch or beyond an unresolved ancestry gap.`;
@@ -1,4 +1,5 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
2
3
  import { Type } from "typebox";
3
4
  import { type ExtensionAPI, type ExtensionContext, type SessionBoundaryDraft, type SettingsManager } from "@earendil-works/pi-coding-agent";
4
5
  export declare const ContextRemainingOutputSchema: Type.TObject<{
@@ -7,6 +8,8 @@ export declare const ContextRemainingOutputSchema: Type.TObject<{
7
8
  export declare function registerBudget(pi: ExtensionAPI, isEnabled: (ctx: ExtensionContext) => boolean, settingsManager?: SettingsManager): {
8
9
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
9
10
  hardReserveDue: (ctx: ExtensionContext, preSendMessages?: AgentMessage[]) => boolean;
11
+ hardReserveDueForInput: (ctx: ExtensionContext, content: string | Array<TextContent | ImageContent>) => boolean;
12
+ fitsInFreshWindow: (ctx: ExtensionContext, content: string | Array<TextContent | ImageContent>) => boolean;
10
13
  consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
11
14
  /** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
12
15
  statusFor: (ctx: ExtensionContext) => {
@@ -2,7 +2,7 @@ import { DEFAULT_BOOT_TOOL_NAMES } from "../../src/boot/text.js";
2
2
  import { remainingBudget } from "../../src/budget/policy.js";
3
3
  import { Type } from "typebox";
4
4
  import { convertToLlm, defineTool } from "@earendil-works/pi-coding-agent";
5
- import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
5
+ import { GUIDANCE_TYPE, TURNOVER_TRIGGER_TYPE, WARNING_TYPE } from "./entries.js";
6
6
  import { estimateContextTokens } from "./estimate.js";
7
7
  import { warningContent } from "./text.js";
8
8
  import { readThresholdSettings } from "./thresholds.js";
@@ -41,19 +41,40 @@ export function registerBudget(pi, isEnabled, settingsManager) {
41
41
  const hardReserveDue = (ctx, preSendMessages) => {
42
42
  if (!automaticResetEnabled(ctx))
43
43
  return false;
44
+ const { reserve } = thresholdsFor(ctx);
45
+ const remaining = ctx.sessionManager ? remainingTokens(ctx, cap) : null;
44
46
  if (preSendMessages) {
47
+ if (remaining !== null && remaining <= reserve)
48
+ return true;
45
49
  const nativeWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow;
46
50
  if (!nativeWindow || nativeWindow <= 0)
47
51
  return false;
48
52
  const contextWindow = Math.min(nativeWindow, cap ?? Infinity);
49
- const { reserve } = thresholdsFor(ctx);
50
53
  const estimate = estimateContextTokens(convertToLlm(preSendMessages));
51
- if (estimate.lastUsageIndex !== null && contextWindow - estimate.usageTokens <= reserve)
52
- return false;
54
+ if (remaining !== null)
55
+ return remaining - estimate.trailingTokens <= reserve;
53
56
  return contextWindow - estimate.tokens <= reserve;
54
57
  }
55
- const remaining = remainingTokens(ctx, cap);
56
- return remaining !== null && remaining <= thresholdsFor(ctx).reserve;
58
+ return remaining !== null && remaining <= reserve;
59
+ };
60
+ const inputTokensFor = (content) => estimateContextTokens([{ role: "user", content, timestamp: 0 }]).tokens;
61
+ const hardReserveDueForInput = (ctx, content) => {
62
+ if (!automaticResetEnabled(ctx))
63
+ return false;
64
+ const { reserve } = thresholdsFor(ctx);
65
+ const remaining = ctx.sessionManager ? remainingTokens(ctx, cap) : null;
66
+ if (remaining === null)
67
+ return false;
68
+ return remaining <= reserve || remaining - inputTokensFor(content) <= reserve;
69
+ };
70
+ const fitsInFreshWindow = (ctx, content) => {
71
+ const nativeWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow;
72
+ if (!nativeWindow || nativeWindow <= 0)
73
+ return true;
74
+ const contextWindow = Math.min(nativeWindow, cap ?? Infinity);
75
+ const { reserve } = thresholdsFor(ctx);
76
+ const freshBudget = Math.max(0, contextWindow - reserve);
77
+ return inputTokensFor(content) <= Math.floor(freshBudget / 2);
57
78
  };
58
79
  let pendingGuidance;
59
80
  let pendingWarning;
@@ -105,6 +126,9 @@ export function registerBudget(pi, isEnabled, settingsManager) {
105
126
  // Without automatic reset nothing gets cleared, so there is nothing to remind about.
106
127
  if (!automaticResetEnabled(ctx))
107
128
  return result();
129
+ const last = event.messages.at(-1);
130
+ if (last?.role === "custom" && last.customType === TURNOVER_TRIGGER_TYPE)
131
+ return result();
108
132
  const remaining = remainingTokens(ctx, cap);
109
133
  if (remaining === null)
110
134
  return result();
@@ -153,6 +177,8 @@ export function registerBudget(pi, isEnabled, settingsManager) {
153
177
  return {
154
178
  automaticResetEnabled,
155
179
  hardReserveDue,
180
+ hardReserveDueForInput,
181
+ fitsInFreshWindow,
156
182
  consumeTurnEnd,
157
183
  /** The same room before the hard-reserve wipe the model sees; null when usage is unknown. */
158
184
  statusFor: (ctx) => ({ remaining: remainingBudget(remainingTokens(ctx, cap), thresholdsFor(ctx).reserve), cap }),
@@ -2,6 +2,7 @@ export declare const BOOT_TYPE = "notesoup/boot";
2
2
  export declare const GUIDANCE_TYPE = "notesoup/guidance";
3
3
  export declare const WARNING_TYPE = "notesoup/warning";
4
4
  export declare const MANUAL_WIPE_TYPE = "notesoup/manual-wipe";
5
+ export declare const TURNOVER_TRIGGER_TYPE = "notesoup/turnover";
5
6
  export declare const RESET_MARKER_TYPE = "notesoup/reset-marker";
6
7
  export declare const CONTINUATION_TYPE = "notesoup/continuation";
7
8
  export declare const RESET_LAST_WORD_TYPE = "notesoup/reset-last-word";
@@ -2,6 +2,7 @@ export const BOOT_TYPE = "notesoup/boot";
2
2
  export const GUIDANCE_TYPE = "notesoup/guidance";
3
3
  export const WARNING_TYPE = "notesoup/warning";
4
4
  export const MANUAL_WIPE_TYPE = "notesoup/manual-wipe";
5
+ export const TURNOVER_TRIGGER_TYPE = "notesoup/turnover";
5
6
  export const RESET_MARKER_TYPE = "notesoup/reset-marker";
6
7
  export const CONTINUATION_TYPE = "notesoup/continuation";
7
8
  export const RESET_LAST_WORD_TYPE = "notesoup/reset-last-word";
@@ -32,7 +32,7 @@ export declare function isWindowContinuationEntry(entry: SessionEntry): boolean;
32
32
  * persists the returned text and no read, render, or repair draws it again. The origin defaults to
33
33
  * `normal`, the same reading a legacy marker with no origin gets.
34
34
  */
35
- export declare function buildResetDrafts(ctx: ExtensionContext, notifyIncompleteNotes?: IncompleteNotesNotifier, isCurrent?: () => boolean, lastWord?: string, firstSeq?: number, origin?: ResetOrigin): Promise<SessionBoundaryDraft[]>;
35
+ export declare function buildResetDrafts(ctx: ExtensionContext, notifyIncompleteNotes?: IncompleteNotesNotifier, isCurrent?: () => boolean, lastWord?: string, firstSeq?: number, origin?: ResetOrigin, betweenTurns?: boolean): Promise<SessionBoundaryDraft[]>;
36
36
  /**
37
37
  * Inspect the persisted tail of a reset marker. It reports which reset messages are present
38
38
  * only while the tail stays repairable: metadata may follow the marker, but real conversation,
@@ -35,7 +35,7 @@ function sendContinuation(pi, content) {
35
35
  * persists the returned text and no read, render, or repair draws it again. The origin defaults to
36
36
  * `normal`, the same reading a legacy marker with no origin gets.
37
37
  */
38
- export async function buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent = () => true, lastWord, firstSeq, origin = "normal") {
38
+ export async function buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent = () => true, lastWord, firstSeq, origin = "normal", betweenTurns = false) {
39
39
  const sessionId = ctx.sessionManager.getSessionId();
40
40
  const sessionPrefix = sessionId.slice(0, 8);
41
41
  const usedWindowIds = new Set(ctx.sessionManager.getBranch().filter(isWindowMarker).map((entry) => entry.data.windowId));
@@ -46,9 +46,9 @@ export async function buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent = (
46
46
  const boot = await buildBootMessage(ctx, windowId, firstSeq, notifyIncompleteNotes, isCurrent);
47
47
  return [
48
48
  { type: "compaction", summary: "", firstKeptEntryId: null },
49
- { type: "custom", customType: RESET_MARKER_TYPE, data: { windowId, origin } },
49
+ { type: "custom", customType: RESET_MARKER_TYPE, data: { windowId, origin, ...(betweenTurns ? { betweenTurns: true } : {}) } },
50
50
  { type: "custom_message", customType: BOOT_TYPE, content: boot.content, display: false, details: { windowId } },
51
- { type: "custom_message", customType: CONTINUATION_TYPE, content: selectContinuation(origin), display: false },
51
+ { type: "custom_message", customType: CONTINUATION_TYPE, content: selectContinuation(origin, { betweenTurns }), display: false },
52
52
  ...(lastWord ? [{ type: "custom_message", customType: RESET_LAST_WORD_TYPE, content: `${LAST_WORD_PREFIX}${lastWord}`, display: true }] : []),
53
53
  ];
54
54
  }
@@ -112,5 +112,5 @@ export async function repairResetTail(pi, ctx, marker, notifyIncompleteNotes, is
112
112
  if (!latest.boot && boot)
113
113
  sendBoot(pi, boot);
114
114
  if (!latest.continuation && (latest.boot || boot))
115
- sendContinuation(pi, selectContinuation(markerResetOrigin(marker)));
115
+ sendContinuation(pi, selectContinuation(markerResetOrigin(marker), { betweenTurns: marker.data.betweenTurns === true }));
116
116
  }
@@ -5,13 +5,15 @@ import { type CarriedInput } from "./artifacts.js";
5
5
  type BudgetOwner = {
6
6
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
7
7
  hardReserveDue: (ctx: ExtensionContext, preSendMessages?: AgentMessage[]) => boolean;
8
+ hardReserveDueForInput?: (ctx: ExtensionContext, content: CarriedInput) => boolean;
9
+ fitsInFreshWindow?: (ctx: ExtensionContext, content: CarriedInput) => boolean;
8
10
  consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
9
11
  clear: () => void;
10
12
  };
11
13
  type ResetOptions = {
12
14
  isEnabled: (ctx: ExtensionContext) => boolean;
13
15
  budget: BudgetOwner;
14
- buildReset: (ctx: ExtensionContext, isCurrent: () => boolean, lastWord: string | undefined, firstSeq: number, origin: ResetOrigin) => SessionBoundaryDraft[] | Promise<SessionBoundaryDraft[]>;
16
+ buildReset: (ctx: ExtensionContext, isCurrent: () => boolean, lastWord: string | undefined, firstSeq: number, origin: ResetOrigin, betweenTurns?: boolean) => SessionBoundaryDraft[] | Promise<SessionBoundaryDraft[]>;
15
17
  getLifecycleGeneration?: () => number;
16
18
  onResetReady?: (ctx: ExtensionContext, drafts: readonly SessionBoundaryDraft[]) => void;
17
19
  };
@@ -47,6 +49,10 @@ export interface ResetTurnEndFacts {
47
49
  readonly queued: boolean;
48
50
  readonly automaticResetEnabled: boolean;
49
51
  readonly hardReserveDue: boolean;
52
+ /** True when this turn still has follow-up work (tool batch, pre-send cutoff, or queued input). */
53
+ readonly hasPendingWork: boolean;
54
+ /** True when the host view erases scrollback on reset (Pi TUI), so clean answers defer rollover until next input. */
55
+ readonly deferBetweenTurns?: boolean;
50
56
  }
51
57
  /** Facts for the pre-settlement boundary; policy guards stay lazy for the same reason. */
52
58
  export interface ResetBeforeSettleFacts {
@@ -86,6 +92,7 @@ export interface ResetBoundaryIntent {
86
92
  readonly windowId: string;
87
93
  readonly continueAfterReset: boolean;
88
94
  readonly origin: ResetOrigin;
95
+ readonly betweenTurns?: boolean;
89
96
  readonly tool?: {
90
97
  readonly lastWord?: string;
91
98
  readonly terminate?: boolean;
@@ -1,4 +1,5 @@
1
1
  import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
2
+ import { TURNOVER_TRIGGER_TYPE } from "../entries.js";
2
3
  import { currentReset, currentWindowId } from "../window.js";
3
4
  import { nextHistorySeq } from "../history.js";
4
5
  import { buildMarkerDraft } from "../marker.js";
@@ -33,7 +34,7 @@ export function finalizeResetBoundary(intent, request) {
33
34
  const resumeModel = intent.continueAfterReset || inputs.length > 0;
34
35
  const state = {
35
36
  request: NO_REQUEST,
36
- ...(intent.boundary === "turn-end" && !resumeModel ? { stopAfterReset: intent } : {}),
37
+ ...(intent.boundary === "turn-end" && !resumeModel && !intent.betweenTurns ? { stopAfterReset: intent } : {}),
37
38
  overflow: spendsOverflow(intent.boundary) ? "spent" : "idle",
38
39
  };
39
40
  return { state, inputs, resumeModel };
@@ -87,12 +88,30 @@ export function reduceResetControl(state, event) {
87
88
  if (!facts.enabled) {
88
89
  return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "none" };
89
90
  }
90
- // A direct tool request commits after the whole tool batch. The budget cutoff is
91
- // a separate hard-reserve safety path; ordinary close-out waits for settlement.
91
+ // A direct tool request commits after the whole tool batch. An automatic hard-reserve
92
+ // cutoff fires at turn_end with continuation while work is still in flight (tool batch,
93
+ // pre-send, queued input, or manual close-out). For a clean final answer:
94
+ // - non-erasing views (RPC/print/JSON) rotate quietly at turn_end with continue:false;
95
+ // - scrollback-erasing views (Pi TUI) defer rollover until the human's next input.
92
96
  const toolReset = request.phase === "pending" && request.tool !== undefined;
93
- if ((toolReset && !manual) || facts.hardReserveDue) {
97
+ if (toolReset && !manual) {
94
98
  return boundaryIntent(request, facts.windowId, "turn-end");
95
99
  }
100
+ if (facts.hardReserveDue) {
101
+ if (manual || toolReset || facts.hasPendingWork) {
102
+ return boundaryIntent(request, facts.windowId, "turn-end");
103
+ }
104
+ if (!facts.deferBetweenTurns) {
105
+ return {
106
+ effect: "build-boundary",
107
+ boundary: "turn-end",
108
+ windowId: facts.windowId,
109
+ continueAfterReset: false,
110
+ origin: "forced",
111
+ betweenTurns: true,
112
+ };
113
+ }
114
+ }
96
115
  return { state: { request, overflow: "idle" }, effect: "none" };
97
116
  }
98
117
  case "before_settle": {
@@ -147,6 +166,9 @@ export function registerResetLifecycle(pi, options) {
147
166
  let control = initialResetControl();
148
167
  let preSendHardReserveWindowId;
149
168
  let pendingPreSendTrigger;
169
+ let pendingTurnover;
170
+ let pendingUserReplays = [];
171
+ let failedTurnoverWindowId;
150
172
  // Once input returns handled, Pi no longer owns its original content. If close-out
151
173
  // fails/cancels, restore it; only an ordinary error starts a turn to answer it.
152
174
  const restoreCommandInputs = (triggerTurn = false) => {
@@ -163,12 +185,19 @@ export function registerResetLifecycle(pi, options) {
163
185
  lifecycleGeneration++;
164
186
  preSendHardReserveWindowId = undefined;
165
187
  pendingPreSendTrigger = undefined;
166
- if (preserveInputs)
188
+ const turnoverInputs = pendingTurnover?.inputs ?? [];
189
+ pendingTurnover = undefined;
190
+ pendingUserReplays = [];
191
+ if (preserveInputs) {
167
192
  restoreCommandInputs();
193
+ for (const draft of carriedInputDrafts(turnoverInputs)) {
194
+ pi.sendMessage(draft, { triggerTurn: false });
195
+ }
196
+ }
168
197
  control = initialResetControl();
169
198
  };
170
- const resetBoundaryResult = async (entries, ctx, intent, preSendHardReserve = false) => {
171
- // Keep command state live while notes load so input arriving during this await joins this boundary.
199
+ const resetBoundaryResult = async (entries, ctx, intent, preSendHardReserve = false, turnover) => {
200
+ // Keep command/turnover state live while notes load so input arriving during this await joins this boundary.
172
201
  const generation = lifecycleGeneration;
173
202
  const outerGeneration = options.getLifecycleGeneration?.();
174
203
  const sessionId = ctx.sessionManager.getSessionId();
@@ -180,9 +209,14 @@ export function registerResetLifecycle(pi, options) {
180
209
  const firstSeq = nextHistorySeq(ctx, entries) + 1;
181
210
  let resetDrafts;
182
211
  try {
183
- resetDrafts = await options.buildReset(ctx, isCurrent, intent.tool?.lastWord, firstSeq, intent.origin);
212
+ resetDrafts = await options.buildReset(ctx, isCurrent, intent.tool?.lastWord, firstSeq, intent.origin, turnover !== undefined || intent.betweenTurns === true);
184
213
  }
185
214
  catch (error) {
215
+ if (turnover && pendingTurnover === turnover) {
216
+ pendingUserReplays = [...turnover.inputs];
217
+ pendingTurnover = undefined;
218
+ failedTurnoverWindowId = windowId;
219
+ }
186
220
  if (isCurrent())
187
221
  ctx.ui.notify(`🥣 Brain still full: ${errorMessage(error)}`, "warning");
188
222
  return entries.length > 0 ? { entries } : undefined;
@@ -192,6 +226,13 @@ export function registerResetLifecycle(pi, options) {
192
226
  const finalized = finalizeResetBoundary(intent, control.request);
193
227
  control = finalized.state;
194
228
  options.onResetReady?.(ctx, resetDrafts);
229
+ if (turnover && pendingTurnover === turnover) {
230
+ // Commit the entire fresh window atomically; agent_settled delivers the withheld user prompt directly.
231
+ pendingUserReplays = [...turnover.inputs];
232
+ pendingTurnover = undefined;
233
+ failedTurnoverWindowId = undefined;
234
+ return { entries: [...entries, ...resetDrafts], continue: false };
235
+ }
195
236
  const allDrafts = [...resetDrafts, ...carriedInputDrafts(finalized.inputs)];
196
237
  if (preSendHardReserve && finalized.resumeModel) {
197
238
  const last = allDrafts.at(-1);
@@ -205,14 +246,37 @@ export function registerResetLifecycle(pi, options) {
205
246
  pi.on("input", (event, ctx) => {
206
247
  if (event.source === "extension" || !sessionActive || !options.isEnabled(ctx))
207
248
  return undefined;
208
- const request = control.request;
209
- if (request.phase !== "pending" || !request.command || request.windowId !== currentWindowId(ctx))
210
- return undefined;
211
249
  const content = event.images?.length
212
250
  ? [{ type: "text", text: event.text }, ...event.images]
213
251
  : event.text;
214
- control = reduceResetControl(control, { type: "input", windowId: request.windowId, input: content }).state;
215
- return { action: "handled" };
252
+ const windowId = currentWindowId(ctx);
253
+ const request = control.request;
254
+ if (request.phase === "pending" && request.command && request.windowId === windowId) {
255
+ control = reduceResetControl(control, { type: "input", windowId, input: content }).state;
256
+ return { action: "handled" };
257
+ }
258
+ if (pendingTurnover && pendingTurnover.windowId === windowId) {
259
+ pendingTurnover.inputs.push(content);
260
+ return { action: "handled" };
261
+ }
262
+ if (ctx.mode === "tui" &&
263
+ event.source === "interactive" &&
264
+ !event.streamingBehavior &&
265
+ ctx.isIdle() &&
266
+ request.phase === "none" &&
267
+ !control.stopAfterReset &&
268
+ failedTurnoverWindowId !== windowId &&
269
+ (options.budget.hardReserveDueForInput
270
+ ? options.budget.hardReserveDueForInput(ctx, content)
271
+ : options.budget.hardReserveDue(ctx))) {
272
+ const fits = options.budget.fitsInFreshWindow ? options.budget.fitsInFreshWindow(ctx, content) : true;
273
+ if (!fits)
274
+ return undefined;
275
+ pendingTurnover = { windowId, inputs: [content] };
276
+ pi.sendMessage({ customType: TURNOVER_TRIGGER_TYPE, content: "", display: false }, { triggerTurn: true });
277
+ return { action: "handled" };
278
+ }
279
+ return undefined;
216
280
  });
217
281
  // Boundary continue:false is not a veto of Pi's tool-batch follow-up. Once the
218
282
  // safety reset is actually committed, cancel that empty follow-up before provider
@@ -239,9 +303,11 @@ export function registerResetLifecycle(pi, options) {
239
303
  return undefined;
240
304
  if (control.request.phase === "pending" && control.request.command !== undefined)
241
305
  return undefined;
242
- if (!options.budget.hardReserveDue(ctx, event.messages))
306
+ const windowId = currentWindowId(ctx);
307
+ const turnoverDue = pendingTurnover !== undefined && pendingTurnover.windowId === windowId;
308
+ if (!turnoverDue && (failedTurnoverWindowId === windowId || !options.budget.hardReserveDue(ctx, event.messages)))
243
309
  return undefined;
244
- preSendHardReserveWindowId = currentWindowId(ctx);
310
+ preSendHardReserveWindowId = windowId;
245
311
  ctx.abort();
246
312
  const system = getCurrentSystemMessage(event.messages);
247
313
  return { messages: system ? [system] : [] };
@@ -252,10 +318,12 @@ export function registerResetLifecycle(pi, options) {
252
318
  const windowId = currentWindowId(ctx);
253
319
  const preSendHardReserve = preSendHardReserveWindowId !== undefined && preSendHardReserveWindowId === windowId;
254
320
  preSendHardReserveWindowId = undefined;
321
+ const turnover = preSendHardReserve && pendingTurnover?.windowId === windowId ? pendingTurnover : undefined;
255
322
  const aborted = preSendHardReserve ? false : isAbort(event.message, event.outcome, ctx);
256
323
  const stagedBudgetEntries = options.budget.consumeTurnEnd(ctx, event.messageEntryId);
257
324
  const budgetEntries = options.isEnabled(ctx) && !aborted && event.outcome !== "error" ? stagedBudgetEntries : [];
258
325
  const entries = [...(event.entries ?? []), ...budgetEntries];
326
+ const hasToolTurn = event.toolResults.length > 0 || (event.message.role === "assistant" && event.message.stopReason === "toolUse");
259
327
  const decision = reduceResetControl(control, {
260
328
  type: "turn_end",
261
329
  facts: {
@@ -267,10 +335,12 @@ export function registerResetLifecycle(pi, options) {
267
335
  get queued() { return event.context.pendingMessages.length > 0 || ctx.hasPendingMessages(); },
268
336
  get automaticResetEnabled() { return options.budget.automaticResetEnabled(ctx); },
269
337
  get hardReserveDue() { return preSendHardReserve || options.budget.hardReserveDue(ctx); },
338
+ get hasPendingWork() { return preSendHardReserve || hasToolTurn || event.context.pendingMessages.length > 0 || ctx.hasPendingMessages(); },
339
+ deferBetweenTurns: ctx.mode === "tui",
270
340
  },
271
341
  });
272
342
  if (decision.effect === "build-boundary")
273
- return await resetBoundaryResult(entries, ctx, decision, preSendHardReserve);
343
+ return await resetBoundaryResult(entries, ctx, decision, preSendHardReserve, turnover);
274
344
  if (aborted)
275
345
  restoreCommandInputs();
276
346
  else if (event.outcome === "error" && decision.state.request.phase === "none")
@@ -320,19 +390,28 @@ export function registerResetLifecycle(pi, options) {
320
390
  return undefined;
321
391
  });
322
392
  pi.on("agent_end", (_event, ctx) => {
323
- if (ctx.signal?.aborted && !pendingPreSendTrigger)
393
+ if (ctx.signal?.aborted && !pendingPreSendTrigger && pendingUserReplays.length === 0)
324
394
  clear();
325
395
  });
326
396
  pi.on("agent_settled", () => {
327
397
  const trigger = pendingPreSendTrigger;
398
+ const replays = pendingUserReplays;
328
399
  clear();
329
- if (trigger) {
400
+ if (replays.length > 0) {
401
+ for (let i = 0; i < replays.length; i++) {
402
+ pi.sendUserMessage(replays[i], {
403
+ ...(i > 0 ? { deliverAs: "followUp" } : {}),
404
+ expandPromptTemplates: true,
405
+ });
406
+ }
407
+ }
408
+ else if (trigger) {
330
409
  pi.sendMessage(trigger, { triggerTurn: true });
331
410
  }
332
411
  });
333
- pi.on("session_start", () => { clear(false); sessionActive = true; });
334
- pi.on("session_tree", () => { clear(false); });
335
- pi.on("session_shutdown", () => { clear(false); options.budget.clear(); sessionActive = false; });
412
+ pi.on("session_start", () => { failedTurnoverWindowId = undefined; clear(false); sessionActive = true; });
413
+ pi.on("session_tree", () => { failedTurnoverWindowId = undefined; clear(false); });
414
+ pi.on("session_shutdown", () => { failedTurnoverWindowId = undefined; clear(false); options.budget.clear(); sessionActive = false; });
336
415
  return {
337
416
  command(windowId, continueAfterReset, input) {
338
417
  const decision = reduceResetControl(control, { type: "command", windowId, continueAfterReset, ...(input !== undefined ? { input } : {}) });
@@ -344,7 +423,7 @@ export function registerResetLifecycle(pi, options) {
344
423
  control = decision.state;
345
424
  return decision.effect === "already-pending" ? "rollover_already_pending" : "rollover_requested";
346
425
  },
347
- hasPendingTrigger: () => pendingPreSendTrigger !== undefined,
426
+ hasPendingTrigger: () => pendingPreSendTrigger !== undefined || pendingUserReplays.length > 0,
348
427
  clear,
349
428
  };
350
429
  }
@@ -10,7 +10,7 @@ import { emptyBrainRenderers } from "./render.js";
10
10
  import { activeBranchTail, currentReset, currentWindowId, isCheckpointBackedReset, isNotesoupEnabled, isNotesoupSkillPath, isWindowBoot, isWindowBootEntry, isWindowMarker, markerResetOrigin, projectRootWindow, projectWindow, stripNotesoupProjection } from "./window.js";
11
11
  import { registerResetLifecycle } from "./reset/lifecycle.js";
12
12
  import { buildResetDrafts, LAST_WORD_ADVERTISED_CHARS, MAX_LAST_WORD_CHARS, repairResetTail, sanitizeLastWord } from "./reset/artifacts.js";
13
- import { BOOT_TYPE, ENABLED_TYPE, MANUAL_WIPE_TYPE } from "./entries.js";
13
+ import { BOOT_TYPE, ENABLED_TYPE, MANUAL_WIPE_TYPE, TURNOVER_TRIGGER_TYPE } from "./entries.js";
14
14
  import { commandWarningContent, PI_PRE_RESET_HINTS } from "./text.js";
15
15
  import { DEFAULT_BOOT_TOOL_NAMES, MAPS_BLOCK, renderProtocolBlock } from "../../src/boot/text.js";
16
16
  import { agentSlug } from "./notes/adapter.js";
@@ -75,7 +75,7 @@ export function registerContext(pi, settingsManager) {
75
75
  if (!marker || !isCheckpointBackedReset(ctx, marker) || !resetBoundaryCommitted(ctx, marker.id, windowId))
76
76
  continue;
77
77
  pendingResetNotices.delete(windowId);
78
- if (markerResetOrigin(marker) === "forced")
78
+ if (markerResetOrigin(marker) === "forced" && !marker.data.betweenTurns)
79
79
  ctx.ui.notify("🥣 Brain forcibly emptied: overflow", "warning");
80
80
  }
81
81
  };
@@ -115,7 +115,7 @@ export function registerContext(pi, settingsManager) {
115
115
  event.systemPromptOptions.sections.notesoup_tools = notesoupTools;
116
116
  event.systemPromptOptions.sections.notesoup_protocol = `${renderProtocolBlock({ ...DEFAULT_BOOT_TOOL_NAMES, preResetHints: PI_PRE_RESET_HINTS }, agentSlug())}\n\n${MAPS_BLOCK}`;
117
117
  maybeSendMarker(pi, ctx);
118
- if (!currentReset(ctx) && !(event.messageType === "custom" && event.message.customType === MANUAL_WIPE_TYPE)) {
118
+ if (!currentReset(ctx) && !(event.messageType === "custom" && (event.message.customType === MANUAL_WIPE_TYPE || event.message.customType === TURNOVER_TRIGGER_TYPE))) {
119
119
  const generation = lifecycleGeneration;
120
120
  const boot = await buildLazyBoot(ctx, () => generation === lifecycleGeneration && isEnabled(ctx));
121
121
  if (boot)
@@ -285,7 +285,7 @@ export function registerContext(pi, settingsManager) {
285
285
  }));
286
286
  const resets = registerResetLifecycle(pi, {
287
287
  isEnabled: (ctx) => isEnabled(ctx),
288
- buildReset: (ctx, isCurrent, lastWord, firstSeq, origin) => buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent, lastWord, firstSeq, origin),
288
+ buildReset: (ctx, isCurrent, lastWord, firstSeq, origin, betweenTurns) => buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent, lastWord, firstSeq, origin, betweenTurns),
289
289
  getLifecycleGeneration: () => lifecycleGeneration,
290
290
  onResetReady: (_ctx, drafts) => {
291
291
  const boot = drafts.find((draft) => draft.type === "custom_message" && draft.customType === BOOT_TYPE);
@@ -16,7 +16,7 @@ function piOperationResult(operation, outcome, details) {
16
16
  details: details,
17
17
  };
18
18
  }
19
- export const NOTES_NAMESPACE = { name: "notes", description: "Notes you choose to keep across context windows. See the notesoup skill." };
19
+ export const NOTES_NAMESPACE = { name: "notes", description: "Notes you choose to keep across context windows. See the notesoup-guide skill." };
20
20
  export const DREAM_NAMESPACE = { name: "dream", description: "Consolidate one project's notes: begin, edit with notes_*, forget crumpled notes, end." };
21
21
  export const HISTORY_NAMESPACE = { name: "history", description: "Session history (this or other local sessions): history_list to browse a timeline or list sessions, history_search to find passages, history_read to read one event." };
22
22
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
@@ -5,6 +5,7 @@ import type { SessionReader } from "./session-reader.js";
5
5
  export type WindowMarkerData = {
6
6
  readonly windowId: string;
7
7
  readonly origin?: ResetOrigin;
8
+ readonly betweenTurns?: boolean;
8
9
  };
9
10
  export type WindowMarker = CustomEntry<WindowMarkerData> & {
10
11
  data: WindowMarkerData;
@@ -21,16 +22,7 @@ export declare function activeBranchTail(branch: readonly SessionEntry[]): reado
21
22
  export declare function currentReset(ctx: SessionReader): WindowMarker | undefined;
22
23
  /** The explicit `/notesoup on|off|reset` choice for this branch, or undefined when never chosen. */
23
24
  export declare function sessionEnabled(branch: readonly SessionEntry[]): boolean | undefined;
24
- /**
25
- * Whether pi-souls reports a naked run. Ask the loaded pi-souls extension synchronously first;
26
- * when it is absent, read the same durable entry it would have consulted.
27
- */
28
- export declare function isNakedSession(pi: {
29
- events?: {
30
- emit(channel: string, data: unknown): void;
31
- };
32
- }, branch: readonly SessionEntry[]): boolean;
33
- /** Explicit branch choice wins; otherwise the CLI flag and a naked pi-souls run both disable. */
25
+ /** Explicit branch choice wins; otherwise the CLI flag and naked/restricted-tools pi-souls runs disable. */
34
26
  export declare function isNotesoupEnabled(pi: {
35
27
  getFlag?(name: string): unknown;
36
28
  events?: {