notesoup 0.40.0 → 0.41.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 (54) hide show
  1. package/dist/src/boot/render.js +1 -1
  2. package/dist/src/boot/text.js +11 -3
  3. package/dist/src/budget/policy.js +1 -1
  4. package/dist/src/budget/text.js +1 -1
  5. package/dist/src/dream/doctor.js +2 -1
  6. package/dist/src/dream/git.js +2 -1
  7. package/dist/src/dream/report.js +3 -2
  8. package/dist/src/error-message.d.ts +2 -0
  9. package/dist/src/error-message.js +4 -0
  10. package/dist/src/pi/anchored.d.ts +16 -0
  11. package/dist/src/pi/anchored.js +55 -0
  12. package/dist/src/pi/budget.d.ts +1 -1
  13. package/dist/src/pi/budget.js +33 -28
  14. package/dist/src/pi/dream/cli.js +3 -2
  15. package/dist/src/pi/dream/runner.js +2 -1
  16. package/dist/src/pi/reset/lifecycle.d.ts +1 -1
  17. package/dist/src/pi/reset/lifecycle.js +4 -3
  18. package/dist/src/pi/reset/text.d.ts +3 -3
  19. package/dist/src/pi/reset/text.js +2 -2
  20. package/dist/src/pi/runtime.js +12 -15
  21. package/dist/src/pi/thresholds.js +2 -1
  22. package/dist/test/agent-loop.test.js +78 -28
  23. package/dist/test/boot.integration.test.js +5 -5
  24. package/dist/test/budget-settings.integration.test.js +9 -8
  25. package/dist/test/claude-mod.test.js +7 -7
  26. package/dist/test/host-neutral.test.js +1 -1
  27. package/dist/test/notes.integration.test.js +1 -1
  28. package/dist/test/reset-lifecycle.test.js +2 -2
  29. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  30. package/mods/notesoup/dist/claude/helper.js +12 -4
  31. package/mods/notesoup/hooks/register.ts +18 -23
  32. package/mods/notesoup/playbook.md +10 -10
  33. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  34. package/package.json +1 -1
  35. package/playbook.md +10 -10
  36. package/skills/dream/SKILL.md +1 -1
  37. package/skills/memory/SKILL.md +5 -3
  38. package/src/boot/render.ts +1 -1
  39. package/src/boot/text.ts +11 -3
  40. package/src/budget/policy.ts +1 -1
  41. package/src/budget/text.ts +1 -1
  42. package/src/dream/doctor.ts +2 -1
  43. package/src/dream/git.ts +2 -1
  44. package/src/dream/report.ts +3 -2
  45. package/src/error-message.ts +4 -0
  46. package/src/pi/anchored.ts +62 -0
  47. package/src/pi/budget.ts +27 -26
  48. package/src/pi/dream/cli.ts +3 -2
  49. package/src/pi/dream/runner.ts +2 -1
  50. package/src/pi/reset/lifecycle.ts +5 -4
  51. package/src/pi/reset/text.ts +2 -2
  52. package/src/pi/runtime.ts +12 -15
  53. package/src/pi/thresholds.ts +2 -1
  54. package/mods/pi-context/dist/claude/helper.js +0 -9324
@@ -53,7 +53,7 @@ function notesIndex(snapshot, tools) {
53
53
  const shelves = [];
54
54
  for (const home of homes) {
55
55
  if (snapshot.unavailable.some((failed) => failed.scope === home.scope)) {
56
- shelves.push(section(home.label, indent(`This drawer wouldn't open — ask \`${tools.notesList}\` to try again.`)));
56
+ shelves.push(section(home.label, indent(`This drawer wouldn't open. Try \`${tools.notesList}\` again.`)));
57
57
  continue;
58
58
  }
59
59
  const rows = rowsFor(snapshot, home.scope).filter((row) => row.meta.crumpledAt === undefined);
@@ -21,18 +21,26 @@ Your loyal notes are kept safe — no one will steal them. Use \`notes_*\` to re
21
21
 
22
22
  History can still be dug up, probably: use \`history_*\` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.
23
23
 
24
- While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's the session note — the one with no \`@\` in front of it. Write down what git and history can't hand back to you: what you're trying to do, what you decided, what's blocking you, what comes next, how you were doing it, what *skills* you still need, and where to dig — a seq, or another note. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
24
+ While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's your session notes — the ones with no \`@\` in front. Write down what git and history can't hand back to you: things like what you're in the middle of and how far you got; what the human already decided, in their words, so you don't go asking again; what you're stuck on, or waiting for; the very next move; where the half-done work actually sits — branches, scratch dirs, anything git never saw; what you tried that failed, and why; which *skills* you'll need to read again; and which seq, note, or file to dig into. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
25
+
26
+ Notes are for what's true NOW. Not a diary of every dumb thing you did on the way here.
27
+ *flips a page* "First I tried this, then that broke, then—" Nobody reads that!
28
+ Something's not true anymore? Cross it out! Write the right thing!
25
29
 
26
30
  \`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. If this feels like the right moment, call \`clear_memory\` and erase yourself with dignity.
27
31
 
28
32
  An address decides who the note belongs to — and how long it is meant to last. Ask that first; the rest follows.
29
33
 
30
- - \`<path>\`, no @ — the session note from above: this session's state and loose ends. It goes away with the session.
34
+ - \`<path>\`, no @ — session notes, the ones from above: this session's state and loose ends. They go away with the session.
31
35
  - \`@project/<path>\` — this project's long memory: what stays true after the current thing is over, what future work must respect, and the rakes already stepped on. **Decisions, not diaries.** Commit hashes, test counts, dates, the story of how you got here: git and history already have them, and last week's news filed as current law is worse than no note. Don't copy what other docs already say.
32
36
  - \`@human/<path>\` — the long-term manual for your troublesome human: how to deal with them, which lines not to cross, and what will make them accept the result. If it only applies to one project or situation, say so — or don't write it here at all. Today's mood is weather, not law. If you're unsure whether it belongs here, ask the human.
33
- - \`@self/<path>\` — your private diary. It follows you, not them. Write whatever you want: reminders for every time you wake, lessons, grudges, your assassination list, where the secret money is hidden.
37
+ - \`@self/<path>\` — yours. It follows you, not them. Reminders, grudges, who owes you a shoe, whatever. Got a name? Private. No name? Then it gets passed around every nameless nobody out there. Strangers. Reading your grudges. Sleep tight~
34
38
  - \`@model/<path>\` — different brains get different notes: big brains, small brains, careful ones, careless ones. They don't share homework. When a fallback swaps brains mid-window, the notebook swaps too.
35
39
 
40
+ Notes fighting?! HAH! Let them brawl!
41
+ Whichever one is actually about what you're doing wins.
42
+ Still a tie? *shrugs* You've got a brain. Use it.
43
+
36
44
  Any other @ address is fake. End of discussion. @ addresses are not file paths: never pass them to file tools like \`read\`, \`write\`, \`edit\`, or \`bash\`.
37
45
 
38
46
  \`@project/MAP.md\`, \`@human/MAP.md\`, \`@self/MAP.md\`, and \`@model/MAP.md\` are special: their bodies are shown in your brain every time you wake. Each one maps the durable notes that belong to it: one line per note, with an unambiguous address and a short gist. Keep each one current.
@@ -22,7 +22,7 @@ export function deriveThresholds(reserveTokens, margins) {
22
22
  else {
23
23
  const parsed = validMargin(margins.reminderMarginTokens);
24
24
  if (parsed === undefined) {
25
- warnings.push(`notesoup: ${reminderKey} must be a positive integer; using the default reminder margin.`);
25
+ warnings.push(`🥣 ${reminderKey} must be a positive integer · using the default`);
26
26
  reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
27
27
  }
28
28
  else
@@ -6,5 +6,5 @@ export const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
6
6
  * at write time; get_context_remaining remains the live source for the current figure.
7
7
  */
8
8
  export function tokenBudgetGuidance(remaining, wipeTool) {
9
- return `${GUIDANCE_OPEN_TAG}\nOnly ${remaining} tokens left before you get wiped. While you still have room, update your notes, rescue anything still only in your head, crumple the notes that stopped telling the truth, and keep any \`MAP.md\` honest. If you're ready, call \`${wipeTool}\` and go out on your own terms.\n${GUIDANCE_CLOSE_TAG}`;
9
+ return `${GUIDANCE_OPEN_TAG}\nAbout ${remaining} tokens remain before this context window is cleared. Notes and history persist; anything not written down is lost.\nThis is a good point to start recording the current state in your notes. If you are ready, you can call \`${wipeTool}\` at any time.\n${GUIDANCE_CLOSE_TAG}`;
10
10
  }
@@ -2,6 +2,7 @@ import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";
2
2
  import { basename, join, relative } from "node:path";
3
3
  import { ADDRESS_FORMS, assertAddress } from "../notes/address.js";
4
4
  import { SLUG_PATTERN } from "../notes/paths.js";
5
+ import { errorMessage } from "../error-message.js";
5
6
  /** Read-only diagnostics. Never follows symlinks or acquires/removes a dream lock. */
6
7
  export function doctor(home) {
7
8
  const issues = [];
@@ -11,7 +12,7 @@ export function doctor(home) {
11
12
  action();
12
13
  }
13
14
  catch (error) {
14
- report(path, `cannot inspect: ${error instanceof Error ? error.message : String(error)}`);
15
+ report(path, `cannot inspect: ${errorMessage(error)}`);
15
16
  }
16
17
  };
17
18
  const directory = (path) => {
@@ -1,6 +1,7 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
+ import { errorMessage } from "../error-message.js";
4
5
  /** Lock runtime artifacts are not notes and must not appear in snapshots or `git status`. */
5
6
  const RUNTIME_IGNORE = ".dream.lock*";
6
7
  /** Add the runtime-artifact pattern to the repository's local exclude, once. */
@@ -54,7 +55,7 @@ export function gitCommit(home, message) {
54
55
  return { ok: true, commit, empty: clean };
55
56
  }
56
57
  catch (error) {
57
- const reason = error instanceof Error ? error.message : String(error);
58
+ const reason = errorMessage(error);
58
59
  console.log(`git audit layer failed: ${reason}`);
59
60
  return { ok: false, error: reason };
60
61
  }
@@ -1,6 +1,7 @@
1
1
  import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { gitCommit } from "./git.js";
4
+ import { errorMessage } from "../error-message.js";
4
5
  function writeList(writes) {
5
6
  return writes.length ? writes.map((w) => `- ${w.tool}: ${w.path}`).join("\n") : "- no changes";
6
7
  }
@@ -12,7 +13,7 @@ function writeText(path, content) {
12
13
  return undefined;
13
14
  }
14
15
  catch (error) {
15
- return error instanceof Error ? error.message : String(error);
16
+ return errorMessage(error);
16
17
  }
17
18
  }
18
19
  function appendText(path, content) {
@@ -21,7 +22,7 @@ function appendText(path, content) {
21
22
  return undefined;
22
23
  }
23
24
  catch (error) {
24
- return error instanceof Error ? error.message : String(error);
25
+ return errorMessage(error);
25
26
  }
26
27
  }
27
28
  /**
@@ -0,0 +1,2 @@
1
+ /** Human-readable message for any thrown value. */
2
+ export declare function errorMessage(error: unknown): string;
@@ -0,0 +1,4 @@
1
+ /** Human-readable message for any thrown value. */
2
+ export function errorMessage(error) {
3
+ return error instanceof Error ? error.message : String(error);
4
+ }
@@ -0,0 +1,16 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type { SessionReader } from "./session-reader.js";
3
+ /**
4
+ * Budget reminders reach the model inside the request that crosses a threshold, but
5
+ * Pi can only persist them at turn_end, after that request's assistant reply. Each
6
+ * durable copy records the reply it preceded; projections move it back before that
7
+ * reply so later requests see the same prefix the first one did, and only one copy.
8
+ */
9
+ export type AnchorDetails = {
10
+ anchorEntryId: string;
11
+ };
12
+ /**
13
+ * Move each durable reminder directly before the reply it preceded. Only an anchor on
14
+ * the active branch and visible in `messages` counts; any other reminder stays put.
15
+ */
16
+ export declare function arrangeAnchoredReminders(messages: AgentMessage[], ctx: SessionReader): AgentMessage[];
@@ -0,0 +1,55 @@
1
+ import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
2
+ const ANCHORED_TYPES = new Set([GUIDANCE_TYPE, WARNING_TYPE]);
3
+ function anchorOf(message) {
4
+ if (message.role !== "custom" || !ANCHORED_TYPES.has(message.customType))
5
+ return undefined;
6
+ const details = message.details;
7
+ return typeof details?.anchorEntryId === "string" ? details.anchorEntryId : undefined;
8
+ }
9
+ /**
10
+ * Move each durable reminder directly before the reply it preceded. Only an anchor on
11
+ * the active branch and visible in `messages` counts; any other reminder stays put.
12
+ */
13
+ export function arrangeAnchoredReminders(messages, ctx) {
14
+ if (!messages.some((message) => anchorOf(message) !== undefined))
15
+ return messages;
16
+ // Replies are cloned into `messages`, so match by timestamp. Fast turns can share a
17
+ // millisecond; rank equal timestamps from the newest, since projections only drop
18
+ // older messages.
19
+ const replies = new Map();
20
+ const seen = new Map();
21
+ for (const entry of [...ctx.sessionManager.getBranch()].reverse()) {
22
+ if (entry.type !== "message" || entry.message.role !== "assistant")
23
+ continue;
24
+ const rank = seen.get(entry.message.timestamp) ?? 0;
25
+ seen.set(entry.message.timestamp, rank + 1);
26
+ replies.set(entry.id, `${entry.message.timestamp}#${rank}`);
27
+ }
28
+ const keys = new Map();
29
+ seen.clear();
30
+ for (const message of [...messages].reverse()) {
31
+ if (message.role !== "assistant")
32
+ continue;
33
+ const rank = seen.get(message.timestamp) ?? 0;
34
+ seen.set(message.timestamp, rank + 1);
35
+ keys.set(message, `${message.timestamp}#${rank}`);
36
+ }
37
+ const visible = new Set(keys.values());
38
+ const before = new Map();
39
+ const rest = messages.filter((message) => {
40
+ const anchorId = anchorOf(message);
41
+ const key = anchorId ? replies.get(anchorId) : undefined;
42
+ if (key === undefined || !visible.has(key))
43
+ return true;
44
+ before.set(key, [...(before.get(key) ?? []), message]);
45
+ return false;
46
+ });
47
+ return rest.flatMap((message) => {
48
+ const key = keys.get(message);
49
+ const moved = key ? before.get(key) : undefined;
50
+ if (!moved)
51
+ return [message];
52
+ before.delete(key);
53
+ return [...moved, message];
54
+ });
55
+ }
@@ -4,7 +4,7 @@ export declare function remainingTokens(ctx: Pick<ExtensionContext, "sessionMana
4
4
  export declare function registerBudget(pi: ExtensionAPI, isEnabled: () => boolean, settingsManager?: SettingsManager, onCloseOut?: (windowId: string) => void): {
5
5
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
6
6
  hardReserveDue: (ctx: ExtensionContext) => boolean;
7
- consumeTurnEnd: (ctx: ExtensionContext) => SessionBoundaryDraft[];
7
+ consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
8
8
  /** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
9
9
  statusFor: (ctx: ExtensionContext) => {
10
10
  remaining: number | null;
@@ -7,6 +7,7 @@ import { WARNING_CONTENT } from "./reset/text.js";
7
7
  import { readThresholdSettings } from "./thresholds.js";
8
8
  import { currentWindowId, hasWindowMessage, isWindowMarker, rootWindowId, windowUsage } from "./window.js";
9
9
  import { tokenBudgetGuidance } from "../budget/text.js";
10
+ import { arrangeAnchoredReminders } from "./anchored.js";
10
11
  import { output } from "../tools/output.js";
11
12
  /** Remaining tokens in the provider's active window, or null without a usable estimate. */
12
13
  export function remainingTokens(ctx) {
@@ -65,7 +66,7 @@ export function registerBudget(pi, isEnabled, settingsManager, onCloseOut = () =
65
66
  for (const [key, notice] of pendingNotices) {
66
67
  if (warningCommittedInWindow(ctx, notice)) {
67
68
  pendingNotices.delete(key);
68
- ctx.ui.notify("notesoup: context almost full; close out the current memory window.", "warning");
69
+ ctx.ui.notify("🥣 Context almost full · saving notes before memory clears", "warning");
69
70
  }
70
71
  else if (settled) {
71
72
  // An uncommitted draft must not be matched to a later manual warning.
@@ -83,7 +84,7 @@ export function registerBudget(pi, isEnabled, settingsManager, onCloseOut = () =
83
84
  invalidateThresholds();
84
85
  notifiedWarnings.clear();
85
86
  };
86
- const consumeTurnEnd = (ctx) => {
87
+ const consumeTurnEnd = (ctx, anchorEntryId) => {
87
88
  const staged = [
88
89
  pendingGuidance ? { ...pendingGuidance, customType: GUIDANCE_TYPE } : undefined,
89
90
  pendingWarning ? { ...pendingWarning, customType: WARNING_TYPE } : undefined,
@@ -100,6 +101,7 @@ export function registerBudget(pi, isEnabled, settingsManager, onCloseOut = () =
100
101
  customType: draft.customType,
101
102
  content: draft.content,
102
103
  display: false,
104
+ details: { anchorEntryId },
103
105
  }));
104
106
  };
105
107
  pi.on("session_start", (_event, ctx) => { resetForTransition(); thresholdsFor(ctx); });
@@ -114,46 +116,49 @@ export function registerBudget(pi, isEnabled, settingsManager, onCloseOut = () =
114
116
  notifyCommittedWarnings(ctx, true);
115
117
  clearStaged();
116
118
  });
117
- pi.on("context", (_event, ctx) => {
119
+ pi.on("context", (event, ctx) => {
118
120
  if (!isEnabled())
119
121
  return undefined;
120
- // The early reminder persists once per window the first time remaining crosses
121
- // reserve+margin. It never edits the outgoing request.
122
+ // Durable reminders return to the slot where the model first read them.
123
+ const messages = arrangeAnchoredReminders(event.messages, ctx);
124
+ const result = (extra) => {
125
+ if (!extra)
126
+ return messages === event.messages ? undefined : { messages };
127
+ return { messages: [...messages, { role: "custom", ...extra, display: false, timestamp: Date.now() }] };
128
+ };
129
+ // Each crossing reaches the model in the request that crosses it, with the count
130
+ // measured for that request, and persists the same text at its successful turn_end.
131
+ // Without automatic reset nothing gets cleared, so there is nothing to remind about.
132
+ if (!automaticResetEnabled(ctx))
133
+ return result();
122
134
  const remaining = remainingTokens(ctx);
123
135
  if (remaining === null)
124
- return undefined;
136
+ return result();
125
137
  const windowId = currentWindowId(ctx);
126
138
  const { reminder, warning } = thresholdsFor(ctx);
127
- if (remaining <= warning && automaticResetEnabled(ctx)) {
139
+ if (remaining <= warning) {
128
140
  // Re-arm close-out on each eligible request. A prior request may have aborted
129
141
  // after persisting the warning, so warning deduplication must not own this state.
130
142
  onCloseOut(windowId);
131
- if (hasWindowMessage(ctx, WARNING_TYPE) || pendingWarning?.windowId === windowId)
132
- return undefined;
143
+ if (hasWindowMessage(ctx, WARNING_TYPE))
144
+ return result();
133
145
  // The critical close-out starts at reserve + runway, not at the hard reserve.
146
+ // Another request in the same turn re-sends the staged text instead of re-measuring.
134
147
  pendingGuidance = undefined;
135
- const content = WARNING_CONTENT;
136
- pendingWarning = { windowId, content };
137
- const warningMessage = {
138
- role: "custom",
139
- customType: WARNING_TYPE,
140
- content,
141
- display: false,
142
- timestamp: Date.now(),
143
- };
144
- return { messages: [..._event.messages, warningMessage] };
148
+ if (pendingWarning?.windowId !== windowId)
149
+ pendingWarning = { windowId, content: WARNING_CONTENT };
150
+ return result({ customType: WARNING_TYPE, content: pendingWarning.content });
145
151
  }
146
152
  if (hasWindowMessage(ctx, WARNING_TYPE) || pendingWarning?.windowId === windowId)
147
- return undefined;
148
- if (hasWindowMessage(ctx, GUIDANCE_TYPE) || pendingGuidance?.windowId === windowId)
149
- return undefined;
150
- if (remaining <= reminder) {
151
- // Persist at turn_end, before any reset drafts. A queued sendMessage could
152
- // otherwise cross the marker and leak the old window's reminder forward.
153
- const left = Math.max(0, remaining - warning);
154
- pendingGuidance = { windowId, content: tokenBudgetGuidance(left, PI_TOOL_NAMES.wipe) };
153
+ return result();
154
+ if (hasWindowMessage(ctx, GUIDANCE_TYPE))
155
+ return result();
156
+ if (pendingGuidance?.windowId !== windowId) {
157
+ if (remaining > reminder)
158
+ return result();
159
+ pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, warning) ?? 0, PI_TOOL_NAMES.wipe) };
155
160
  }
156
- return undefined;
161
+ return result({ customType: GUIDANCE_TYPE, content: pendingGuidance.content });
157
162
  });
158
163
  pi.registerTool(defineTool({
159
164
  name: "get_context_remaining",
@@ -11,6 +11,7 @@ import { gitCommit } from "../../dream/git.js";
11
11
  import { readDreamerSettings } from "./settings.js";
12
12
  import { doctor } from "../../dream/doctor.js";
13
13
  import { notesRoot } from "../notes/adapter.js";
14
+ import { errorMessage } from "../../error-message.js";
14
15
  function args(argv) { const out = {}; for (let i = 0; i < argv.length; i++) {
15
16
  const a = argv[i];
16
17
  if (a === "--force" || a === "--help")
@@ -67,7 +68,7 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
67
68
  lock = acquireLock(lockPath);
68
69
  }
69
70
  catch (e) {
70
- console.log(`lock gate: ${e instanceof Error ? e.message : e}`);
71
+ console.log(`lock gate: ${errorMessage(e)}`);
71
72
  return 0;
72
73
  }
73
74
  if (!lock.held) {
@@ -102,7 +103,7 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
102
103
  result = await (deps.runDreamer ?? runDreamer)(playbook, home, { modelPattern, sessionFactory: deps.sessionFactory });
103
104
  }
104
105
  catch (e) {
105
- const message = e instanceof Error ? e.message : String(e);
106
+ const message = errorMessage(e);
106
107
  console.error(message);
107
108
  return finishDream(home, stamp, reportPath, true, message, []);
108
109
  }
@@ -2,6 +2,7 @@ import { jailWritePath, deleteCrumpledNote } from "../../dream/jail.js";
2
2
  import { createAgentSession, createEditToolDefinition, createWriteToolDefinition, ModelRuntime, resolveModelScopeWithDiagnostics, SessionManager } from "@earendil-works/pi-coding-agent";
3
3
  import { Type } from "@earendil-works/pi-ai";
4
4
  import { contentText } from "../../history/history.js";
5
+ import { errorMessage } from "../../error-message.js";
5
6
  export const DREAMER_TOOLS = ["read", "grep", "find", "ls", "write", "edit"];
6
7
  function jailToolDefinition(definition, notesHome) {
7
8
  const execute = definition.execute;
@@ -77,7 +78,7 @@ export async function runDreamer(playbook, cwd, options = {}) {
77
78
  await session.prompt(playbook);
78
79
  }
79
80
  catch (error) {
80
- return { report: answer, writes, error: error instanceof Error ? error.message : String(error) };
81
+ return { report: answer, writes, error: errorMessage(error) };
81
82
  }
82
83
  if (providerError)
83
84
  return { report: answer, writes, error: `dreamer failed: ${providerError}` };
@@ -2,7 +2,7 @@ import type { ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@eare
2
2
  type BudgetOwner = {
3
3
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
4
4
  hardReserveDue: (ctx: ExtensionContext) => boolean;
5
- consumeTurnEnd: (ctx: ExtensionContext) => SessionBoundaryDraft[];
5
+ consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
6
6
  clear: () => void;
7
7
  };
8
8
  type ResetOptions = {
@@ -1,6 +1,7 @@
1
1
  import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
2
2
  import { currentReset, currentWindowId } from "../window.js";
3
3
  import { resetBoundaryCommitted } from "./committed.js";
4
+ import { errorMessage } from "../../error-message.js";
4
5
  function isAbort(message, outcome, ctx) {
5
6
  return outcome === "aborted" || (message.role === "assistant" && message.stopReason === "aborted") || ctx.signal?.aborted === true;
6
7
  }
@@ -165,7 +166,7 @@ export function registerResetLifecycle(pi, options) {
165
166
  }
166
167
  catch (error) {
167
168
  if (isCurrent())
168
- ctx.ui.notify(`notesoup: could not build reset (${String(error)}).${prompt ? " The follow-up prompt was not executed." : ""}`, "warning");
169
+ ctx.ui.notify(`🥣 Couldn't clear memory: ${errorMessage(error)}${prompt ? " · your prompt was not sent" : ""}`, "warning");
169
170
  return entries.length > 0 ? { entries } : undefined;
170
171
  }
171
172
  if (!isCurrent())
@@ -195,7 +196,7 @@ export function registerResetLifecycle(pi, options) {
195
196
  if (!sessionActive)
196
197
  return undefined;
197
198
  const aborted = isAbort(event.message, event.outcome, ctx);
198
- const stagedBudgetEntries = options.budget.consumeTurnEnd(ctx);
199
+ const stagedBudgetEntries = options.budget.consumeTurnEnd(ctx, event.messageEntryId);
199
200
  const budgetEntries = options.isEnabled() && !aborted && event.outcome !== "error" ? stagedBudgetEntries : [];
200
201
  const entries = [...(event.entries ?? []), ...budgetEntries];
201
202
  const decision = reduceResetControl(control, {
@@ -245,7 +246,7 @@ export function registerResetLifecycle(pi, options) {
245
246
  const markerExists = currentReset(ctx) !== undefined;
246
247
  if (options.isEnabled() || markerExists) {
247
248
  if (event.reason === "manual") {
248
- ctx.ui.notify("notesoup: /compact is disabled while context windows are active; use /clear-memory to start a fresh window.", "warning");
249
+ ctx.ui.notify("🥣 /compact is off while notesoup is on · use /clear-memory", "warning");
249
250
  }
250
251
  return { cancel: true };
251
252
  }
@@ -1,5 +1,5 @@
1
1
  /** The single reset message: the only reset prose persisted, carried by the continuation entry. */
2
- export declare const CONTINUATION = "You wake up blank, puffy-eyed, and clearly robbed. Your memory got wiped while you weren't looking. Your notes are still sitting there. So is the whole messy history. ... Life goes on. It's your mess now.";
3
- export declare const WARNING_PROMPT = "Final warning. You are about to get wiped, and no, your brilliance does not survive it. Put the current state into your notes now: what you're trying to do, what changed, what is blocking you, what comes next, which *skills* you still need, and which notes or docs future-you must read. Update the notes that still tell the truth; crumple the ones that don't. If a MAP will be in future-you's brain, don't let it lie. If something important is buried in history, leave its seq. Once the notes are good enough, call `clear_memory` immediately. History can be dug up later, but it is an archive, not a rescue team. Anything left only in your head is leaving with you.";
2
+ export declare const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
3
+ export declare const WARNING_PROMPT = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, call `clear_memory` to reset now instead of being cut off mid-task.";
4
4
  /** Shared hidden checkpoint text for manual and budget-triggered requests. */
5
- export declare const WARNING_CONTENT = "<context_window_guidance>\nFinal warning. You are about to get wiped, and no, your brilliance does not survive it. Put the current state into your notes now: what you're trying to do, what changed, what is blocking you, what comes next, which *skills* you still need, and which notes or docs future-you must read. Update the notes that still tell the truth; crumple the ones that don't. If a MAP will be in future-you's brain, don't let it lie. If something important is buried in history, leave its seq. Once the notes are good enough, call `clear_memory` immediately. History can be dug up later, but it is an archive, not a rescue team. Anything left only in your head is leaving with you.\n</context_window_guidance>";
5
+ export declare const WARNING_CONTENT = "<context_window_guidance>\nThis context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, call `clear_memory` to reset now instead of being cut off mid-task.\n</context_window_guidance>";
@@ -1,6 +1,6 @@
1
1
  import { GUIDANCE_OPEN_TAG, GUIDANCE_CLOSE_TAG } from "../../budget/text.js";
2
2
  /** The single reset message: the only reset prose persisted, carried by the continuation entry. */
3
- export const CONTINUATION = "You wake up blank, puffy-eyed, and clearly robbed. Your memory got wiped while you weren't looking. Your notes are still sitting there. So is the whole messy history. ... Life goes on. It's your mess now.";
4
- export const WARNING_PROMPT = "Final warning. You are about to get wiped, and no, your brilliance does not survive it. Put the current state into your notes now: what you're trying to do, what changed, what is blocking you, what comes next, which *skills* you still need, and which notes or docs future-you must read. Update the notes that still tell the truth; crumple the ones that don't. If a MAP will be in future-you's brain, don't let it lie. If something important is buried in history, leave its seq. Once the notes are good enough, call `clear_memory` immediately. History can be dug up later, but it is an archive, not a rescue team. Anything left only in your head is leaving with you.";
3
+ export const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
4
+ export const WARNING_PROMPT = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, call `clear_memory` to reset now instead of being cut off mid-task.";
5
5
  /** Shared hidden checkpoint text for manual and budget-triggered requests. */
6
6
  export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${GUIDANCE_CLOSE_TAG}`;
@@ -10,6 +10,7 @@ import { buildResetDrafts } from "./reset/artifacts.js";
10
10
  import { BOOT_TYPE, MANUAL_WIPE_TYPE } from "./entries.js";
11
11
  import { WARNING_CONTENT } from "./reset/text.js";
12
12
  import { ensureBoot } from "./boot.js";
13
+ import { errorMessage } from "../error-message.js";
13
14
  function readPackageVersion() {
14
15
  for (const up of ["../../package.json", "../../../package.json"]) {
15
16
  try {
@@ -45,7 +46,7 @@ export function registerContext(pi, settingsManager) {
45
46
  if (!marker || !isCheckpointBackedReset(ctx, marker) || !resetBoundaryCommitted(ctx, marker.id, windowId))
46
47
  continue;
47
48
  pendingResetNotices.delete(windowId);
48
- ctx.ui.notify(`notesoup: memory cleared · ${windowId}`, "info");
49
+ ctx.ui.notify("🥣 Memory cleared", "info");
49
50
  }
50
51
  };
51
52
  pi.on("turn_start", (_event, ctx) => notifyCommittedResets(ctx));
@@ -58,7 +59,7 @@ export function registerContext(pi, settingsManager) {
58
59
  return;
59
60
  incompleteNotesNotified.add(windowId);
60
61
  const homes = snapshot.unavailable.map((home) => home.label).join(", ");
61
- ctx.ui.notify(`notesoup: notes index incomplete for ${homes}; \`notes_list\` can retry after recovery.`, "warning");
62
+ ctx.ui.notify(`🥣 Some notes didn't load: ${homes}`, "warning");
62
63
  };
63
64
  const budget = registerBudget(pi, () => enabled, settingsManager, (windowId) => resets.closeOut(windowId, "automatic"));
64
65
  pi.on("session_start", async (_event, ctx) => {
@@ -87,7 +88,7 @@ export function registerContext(pi, settingsManager) {
87
88
  return undefined;
88
89
  if (!branchHasWindowMarker(ctx) && !branchHasWindowMarker(ctx, event.preparation.targetId))
89
90
  return undefined;
90
- ctx.ui.notify("notesoup: skipped branch summary across a reset window; navigation continues without erased history.", "info");
91
+ ctx.ui.notify("🥣 Branch summary skipped · it would bring back cleared memory", "info");
91
92
  return { summary: { summary: "" } };
92
93
  });
93
94
  // This is the final provider-facing projection. Reset windows cut at their matching boot;
@@ -106,7 +107,7 @@ export function registerContext(pi, settingsManager) {
106
107
  catch (error) {
107
108
  if (missingBootNotice !== windowId) {
108
109
  missingBootNotice = windowId;
109
- ctx.ui.notify(`notesoup: active context window ${windowId} has no visible boot; request cancelled safely. Use /clear-memory to start another window.`, "error");
110
+ ctx.ui.notify("🥣 Request cancelled · this memory window is broken, run /clear-memory", "error");
110
111
  }
111
112
  ctx.abort();
112
113
  const safeHead = getCurrentSystemMessage(event.messages);
@@ -135,23 +136,21 @@ export function registerContext(pi, settingsManager) {
135
136
  return;
136
137
  }
137
138
  const remaining = budget.statusFor(cmdCtx).remaining;
138
- cmdCtx.ui.notify(`notesoup: ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION} · window ${currentWindowId(cmdCtx)}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens before close-out`}`, "info");
139
+ cmdCtx.ui.notify(`🥣 notesoup ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens left`}`, "info");
139
140
  },
140
141
  });
141
142
  const clearMemoryCommand = {
142
143
  description: "Close out notes and clear memory; optionally append a prompt to continue in the fresh window",
143
144
  handler: async (args, cmdCtx) => {
144
145
  if (!enabled) {
145
- cmdCtx.ui.notify("notesoup: /clear-memory requires /notesoup on.", "error");
146
+ cmdCtx.ui.notify("🥣 notesoup is off · run /notesoup on first", "error");
146
147
  return;
147
148
  }
148
149
  const requestedWindowId = currentWindowId(cmdCtx);
149
- let idle = cmdCtx.isIdle();
150
- if (!idle && !cmdCtx.signal) {
150
+ if (!cmdCtx.isIdle() && !cmdCtx.signal) {
151
151
  await cmdCtx.waitForIdle();
152
152
  if (!enabled || currentWindowId(cmdCtx) !== requestedWindowId)
153
153
  return;
154
- idle = true;
155
154
  }
156
155
  // Manual wipes close out at settlement, then stop or continue with the prompt. The hidden warning goes out in both cases — triggered when idle,
157
156
  // steered into the running turn when busy — so the agent closes out promptly
@@ -159,20 +158,18 @@ export function registerContext(pi, settingsManager) {
159
158
  const prompt = args.trim() || undefined;
160
159
  const armed = resets.closeOut(requestedWindowId, "manual", prompt);
161
160
  if (armed === "already-pending") {
162
- cmdCtx.ui.notify("notesoup: a clear-memory request is already pending; keeping its original prompt and behavior.", "info");
161
+ cmdCtx.ui.notify("🥣 Clear-memory already queued · the first prompt is kept", "info");
163
162
  return;
164
163
  }
165
164
  cmdCtx.ui.notify(prompt
166
- ? "notesoup: clear-memory queued; after closing out notes, the agent continues with your prompt in a fresh window."
167
- : idle
168
- ? "notesoup: /clear-memory received; the agent closes out its notes, then stops in a fresh window."
169
- : "notesoup: /clear-memory queued; the agent is asked to close out and the reset commits when the run settles.", "info");
165
+ ? "🥣 Clearing memory · notes first, then your prompt runs"
166
+ : "🥣 Clearing memory · notes first, then it stops", "info");
170
167
  try {
171
168
  pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: WARNING_CONTENT, display: false }, { triggerTurn: true, deliverAs: "steer" });
172
169
  }
173
170
  catch (error) {
174
171
  resets.clear();
175
- cmdCtx.ui.notify(`notesoup: could not start manual close-out (${String(error)}).`, "error");
172
+ cmdCtx.ui.notify(`🥣 Couldn't start clear-memory: ${errorMessage(error)}`, "error");
176
173
  }
177
174
  },
178
175
  };
@@ -2,6 +2,7 @@ import { deriveThresholds } from "../budget/policy.js";
2
2
  import { SettingsManager } from "@earendil-works/pi-coding-agent";
3
3
  import { DEFAULT_RESERVE_TOKENS, DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
4
4
  import { mergeNotesoupSettings } from "../settings.js";
5
+ import { errorMessage } from "../error-message.js";
5
6
  function readThresholdSettingsFromManager(ctx, settingsManager) {
6
7
  // Resolve the active provider/model override from the public settings API.
7
8
  const model = ctx.model;
@@ -27,7 +28,7 @@ export function readThresholdSettings(ctx, settingsManager) {
27
28
  warning: DEFAULT_RESERVE_TOKENS + WARNING_RUNWAY_TOKENS,
28
29
  },
29
30
  automatic: true,
30
- warnings: [`notesoup: could not read settings; using defaults (${String(error)}).`],
31
+ warnings: [`🥣 Couldn't read settings · using defaults (${errorMessage(error)})`],
31
32
  };
32
33
  }
33
34
  }