notesoup 0.40.0 → 0.42.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 (93) hide show
  1. package/dist/src/boot/render.js +1 -1
  2. package/dist/src/boot/text.d.ts +12 -0
  3. package/dist/src/boot/text.js +25 -5
  4. package/dist/src/budget/policy.js +1 -1
  5. package/dist/src/budget/text.d.ts +12 -0
  6. package/dist/src/budget/text.js +13 -1
  7. package/dist/src/claude/helper.js +23 -2
  8. package/dist/src/claude/thresholds.d.ts +39 -0
  9. package/dist/src/claude/thresholds.js +149 -0
  10. package/dist/src/dream/doctor.js +3 -2
  11. package/dist/src/dream/git.js +2 -1
  12. package/dist/src/dream/jail.js +10 -10
  13. package/dist/src/dream/report.js +3 -2
  14. package/dist/src/error-message.d.ts +2 -0
  15. package/dist/src/error-message.js +4 -0
  16. package/dist/src/history/history.js +1 -1
  17. package/dist/src/history/query.js +6 -6
  18. package/dist/src/notes/address.d.ts +1 -1
  19. package/dist/src/notes/address.js +12 -12
  20. package/dist/src/notes/store.js +16 -12
  21. package/dist/src/pi/anchored.d.ts +16 -0
  22. package/dist/src/pi/anchored.js +55 -0
  23. package/dist/src/pi/budget.d.ts +1 -1
  24. package/dist/src/pi/budget.js +33 -28
  25. package/dist/src/pi/dream/cli.js +3 -2
  26. package/dist/src/pi/dream/runner.js +2 -1
  27. package/dist/src/pi/reset/lifecycle.d.ts +1 -1
  28. package/dist/src/pi/reset/lifecycle.js +4 -3
  29. package/dist/src/pi/reset/text.d.ts +3 -4
  30. package/dist/src/pi/reset/text.js +5 -4
  31. package/dist/src/pi/runtime.js +13 -16
  32. package/dist/src/pi/thresholds.js +2 -1
  33. package/dist/src/pi/tool-result.js +2 -2
  34. package/dist/src/settings.d.ts +8 -0
  35. package/dist/src/settings.js +6 -1
  36. package/dist/src/tools/history.js +12 -12
  37. package/dist/src/tools/notes.d.ts +3 -3
  38. package/dist/src/tools/notes.js +12 -11
  39. package/dist/src/tools/output.d.ts +2 -0
  40. package/dist/src/tools/output.js +2 -0
  41. package/dist/src/tools/result.js +2 -2
  42. package/dist/src/tools/schema.js +3 -3
  43. package/dist/test/agent-loop.test.js +78 -28
  44. package/dist/test/boot.integration.test.js +5 -5
  45. package/dist/test/budget-settings.integration.test.js +9 -8
  46. package/dist/test/claude-mod.test.js +213 -23
  47. package/dist/test/dream.test.js +3 -3
  48. package/dist/test/history.integration.test.js +7 -8
  49. package/dist/test/host-neutral.test.js +2 -2
  50. package/dist/test/notes-library.test.js +1 -1
  51. package/dist/test/notes.integration.test.js +5 -5
  52. package/dist/test/notes.test.js +16 -16
  53. package/dist/test/reset-lifecycle.test.js +2 -2
  54. package/docs/claude-code-mod.md +10 -2
  55. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  56. package/mods/notesoup/dist/claude/helper.js +212 -45
  57. package/mods/notesoup/hooks/register.ts +209 -48
  58. package/mods/notesoup/playbook.md +10 -10
  59. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  60. package/package.json +1 -1
  61. package/playbook.md +10 -10
  62. package/skills/dream/SKILL.md +1 -1
  63. package/skills/memory/SKILL.md +5 -3
  64. package/src/boot/render.ts +1 -1
  65. package/src/boot/text.ts +31 -5
  66. package/src/budget/policy.ts +1 -1
  67. package/src/budget/text.ts +18 -1
  68. package/src/claude/helper.ts +20 -3
  69. package/src/claude/thresholds.ts +170 -0
  70. package/src/dream/doctor.ts +3 -2
  71. package/src/dream/git.ts +2 -1
  72. package/src/dream/jail.ts +10 -10
  73. package/src/dream/report.ts +3 -2
  74. package/src/error-message.ts +4 -0
  75. package/src/history/history.ts +1 -1
  76. package/src/history/query.ts +6 -6
  77. package/src/notes/address.ts +12 -12
  78. package/src/notes/store.ts +17 -12
  79. package/src/pi/anchored.ts +62 -0
  80. package/src/pi/budget.ts +27 -26
  81. package/src/pi/dream/cli.ts +3 -2
  82. package/src/pi/dream/runner.ts +2 -1
  83. package/src/pi/reset/lifecycle.ts +5 -4
  84. package/src/pi/reset/text.ts +6 -7
  85. package/src/pi/runtime.ts +13 -16
  86. package/src/pi/thresholds.ts +2 -1
  87. package/src/pi/tool-result.ts +2 -2
  88. package/src/settings.ts +18 -2
  89. package/src/tools/history.ts +12 -12
  90. package/src/tools/notes.ts +14 -12
  91. package/src/tools/output.ts +2 -0
  92. package/src/tools/result.ts +2 -2
  93. package/src/tools/schema.ts +3 -3
@@ -1,6 +1,6 @@
1
1
  import { NoteError } from "./errors.js";
2
2
  import { SLUG_PATTERN } from "./paths.js";
3
- export const ADDRESS_FORMS = "use <path> with no @ for this session, or @project/, @human/, @self/, or @model/ followed by a path";
3
+ export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
4
4
  /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
5
5
  function shown(value) {
6
6
  const json = JSON.stringify(value);
@@ -8,12 +8,12 @@ function shown(value) {
8
8
  }
9
9
  export function assertVirtualPath(value) {
10
10
  if (typeof value !== "string" || value.length === 0)
11
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: path must be a non-empty string`);
11
+ throw new NoteError("invalid_address", "The address is empty; give the note a path.");
12
12
  if (value.includes("\0") || value.includes("\\") || value.startsWith("/"))
13
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject backslashes, leading "/", and NUL`);
13
+ throw new NoteError("invalid_address", `${shown(value)}: a note path can't start with "/" or contain "\\" or NUL.`);
14
14
  const parts = value.split("/");
15
15
  if (parts.some((part) => part.length === 0 || part === "." || part === ".."))
16
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject "..", ".", and empty segments`);
16
+ throw new NoteError("invalid_address", `${shown(value)}: a note path can't have empty, ".", or ".." folder names.`);
17
17
  return value;
18
18
  }
19
19
  /**
@@ -48,9 +48,9 @@ export function assertGlobPattern(value) {
48
48
  if (value === undefined || value === null || value === "")
49
49
  return undefined;
50
50
  if (typeof value !== "string")
51
- throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns must be strings`);
51
+ throw new NoteError("invalid_pattern", `glob ${shown(value)} must be a string.`);
52
52
  if (value.includes("\0") || value.includes("\\"))
53
- throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns reject NUL and backslashes`);
53
+ throw new NoteError("invalid_pattern", `glob ${shown(value)} can't contain "\\" or NUL.`);
54
54
  return value;
55
55
  }
56
56
  /**
@@ -59,7 +59,7 @@ export function assertGlobPattern(value) {
59
59
  */
60
60
  export function assertAddress(value) {
61
61
  if (typeof value !== "string")
62
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
62
+ throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
63
63
  let scope = "session";
64
64
  let path = value;
65
65
  let who;
@@ -81,20 +81,20 @@ export function assertAddress(value) {
81
81
  const nameEnd = tail.indexOf("/");
82
82
  who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
83
83
  if (!SLUG_PATTERN.test(who))
84
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
84
+ throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
85
85
  scope = head === "agents" ? "agent" : "model";
86
86
  path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
87
87
  }
88
88
  else {
89
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
89
+ throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
90
90
  }
91
91
  if (path === "" && scope !== "agent" && scope !== "model")
92
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
92
+ throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
93
93
  if (path === "" && who === undefined)
94
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
94
+ throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
95
95
  }
96
96
  if (path.includes("@"))
97
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
97
+ throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
98
98
  assertVirtualPath(path);
99
99
  return { scope, path, who };
100
100
  }
@@ -195,12 +195,16 @@ async function atomicWrite(path, content) {
195
195
  function assertWritablePath(vpath) {
196
196
  const bytes = Buffer.byteLength(vpath, "utf8");
197
197
  if (bytes > MAX_NOTE_PATH_BYTES)
198
- throw new NoteError("too_large", `note path exceeds ${MAX_NOTE_PATH_BYTES} UTF-8 bytes (got ${bytes})`);
198
+ throw new NoteError("too_large", `Path too long: ${bytes} bytes; the limit is ${MAX_NOTE_PATH_BYTES}.`);
199
+ }
200
+ /** Rounded up, so a note just over the limit never reads as exactly at it. */
201
+ function megabytes(bytes) {
202
+ return `${Math.ceil(bytes / 10_000) / 100} MB`;
199
203
  }
200
204
  function assertSerializedSize(content) {
201
205
  const bytes = Buffer.byteLength(content, "utf8");
202
206
  if (bytes > MAX_NOTE_BYTES)
203
- throw new NoteError("too_large", `note exceeds ${MAX_NOTE_BYTES} UTF-8 bytes (serialized ${bytes})`);
207
+ throw new NoteError("too_large", `This note would be ${megabytes(bytes)}, over the ${megabytes(MAX_NOTE_BYTES)} limit per note; split it into several notes.`);
204
208
  }
205
209
  /** Frontmatter block only (the body separator stripped), for metadata-only change inputs. */
206
210
  function frontmatterOf(meta) {
@@ -214,7 +218,7 @@ function assertWritableHome(scope, who, identity) {
214
218
  if (who === current)
215
219
  return;
216
220
  const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
217
- throw new NoteError("invalid_scope", `${home} is not your home: writable homes are this session, @project/, @human/, @self/, and the current @model/ home`);
221
+ throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
218
222
  }
219
223
  /** Normalize parsed metadata exactly as a read does, including its access mutation. */
220
224
  function accessedMeta(meta, scope, now) {
@@ -282,13 +286,13 @@ export function createNotesStore(input) {
282
286
  const scope = destination.scope;
283
287
  assertWritableHome(scope, destination.who, identity);
284
288
  if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined) {
285
- throw new NoteError("nothing_to_do", "nothing to do: provide edits or at least one of origin, crumpled");
289
+ throw new NoteError("nothing_to_do", "Nothing to change: pass edits, origin, crumpled, or rename_to.");
286
290
  }
287
291
  const path = physicalPath(scope, destination.path, identity, destination.who);
288
292
  return withPathQueue(path, async () => {
289
293
  const raw = await readFileIfExists(path);
290
294
  if (raw === undefined)
291
- throw new NoteError("not_found", "note not found");
295
+ throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
292
296
  const { meta, body } = parseNote(raw);
293
297
  meta.scope = scope;
294
298
  const beforeMeta = { ...meta };
@@ -298,14 +302,14 @@ export function createNotesStore(input) {
298
302
  const oldText = operation?.oldText;
299
303
  const newText = operation?.newText;
300
304
  if (typeof oldText !== "string" || oldText.length === 0)
301
- throw new NoteError("no_match", `edit ${index}: oldText must be a non-empty string`, { editIndex: index });
305
+ throw new NoteError("no_match", `edits[${index}].oldText is empty.`, { editIndex: index });
302
306
  if (typeof newText !== "string")
303
- throw new NoteError("no_match", `edit ${index}: newText must be a string`, { editIndex: index });
307
+ throw new NoteError("no_match", `edits[${index}].newText must be a string.`, { editIndex: index });
304
308
  const lines = matchLineNumbers(next, oldText);
305
309
  if (lines.length === 0)
306
- throw new NoteError("no_match", `edit ${index}: oldText does not occur in the note body`, { editIndex: index });
310
+ throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
307
311
  if (lines.length > 1 && !stableOptions.replaceAll) {
308
- throw new NoteError("ambiguous_edit", `edit ${index}: oldText occurs ${lines.length} times (${anchorLines(lines)}); pass replace_all to replace every occurrence`, { lineNumbers: lines, editIndex: index });
312
+ throw new NoteError("ambiguous_edit", `edits[${index}].oldText appears ${lines.length} times (${anchorLines(lines)}); add surrounding text to pick one, or set replace_all. Nothing was saved.`, { lineNumbers: lines, editIndex: index });
309
313
  }
310
314
  if (oldText !== newText)
311
315
  applied++;
@@ -361,15 +365,15 @@ export function createNotesStore(input) {
361
365
  const fromPath = physicalPath(fromScope, from.path, identity, from.who);
362
366
  const toPath = physicalPath(toScope, to.path, identity, to.who);
363
367
  if (resolve(fromPath) === resolve(toPath))
364
- throw new NoteError("nothing_to_do", "rename_to resolves to the same note");
368
+ throw new NoteError("nothing_to_do", "rename_to points at the note itself.");
365
369
  const [first, second] = [fromPath, toPath].sort();
366
370
  return withPathQueue(first, () => withPathQueue(second, async () => {
367
371
  const raw = await readFileIfExists(fromPath);
368
372
  if (raw === undefined)
369
- throw new NoteError("not_found", "note not found");
373
+ throw new NoteError("not_found", `No note at ${noteIdentity(identity, fromAddress).address}.`);
370
374
  const targetRaw = await readFileIfExists(toPath);
371
375
  if (targetRaw !== undefined && parseNote(targetRaw).meta.crumpledAt === undefined) {
372
- throw new NoteError("already_exists", "rename_to target is a live note; crumple it first or pick another address");
376
+ throw new NoteError("already_exists", `${noteIdentity(identity, toAddress).address} already holds a note; crumple it first or pick another address.`);
373
377
  }
374
378
  const { meta, body } = parseNote(raw);
375
379
  meta.scope = toScope;
@@ -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,4 @@
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.";
1
+ import { CLAUDE_WARNING_PROMPT, CONTINUATION, WARNING_BODY, WARNING_PROMPT } from "../../budget/text.js";
4
2
  /** 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>";
3
+ 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>";
4
+ export { CLAUDE_WARNING_PROMPT, CONTINUATION, WARNING_BODY, WARNING_PROMPT };
@@ -1,6 +1,7 @@
1
- import { GUIDANCE_OPEN_TAG, GUIDANCE_CLOSE_TAG } from "../../budget/text.js";
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.";
1
+ import { CLAUDE_WARNING_PROMPT, CONTINUATION, GUIDANCE_CLOSE_TAG, GUIDANCE_OPEN_TAG, WARNING_BODY, WARNING_PROMPT } from "../../budget/text.js";
5
2
  /** Shared hidden checkpoint text for manual and budget-triggered requests. */
6
3
  export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${GUIDANCE_CLOSE_TAG}`;
4
+ // The reset prose lives beside the guidance text in the host-neutral budget domain, so the
5
+ // Claude mod can show the same words without depending on any Pi module. Re-exported here
6
+ // for the Pi-side importers that already reach for this module.
7
+ export { CLAUDE_WARNING_PROMPT, CONTINUATION, WARNING_BODY, WARNING_PROMPT };
@@ -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
  };
@@ -185,7 +182,7 @@ export function registerContext(pi, settingsManager) {
185
182
  parameters: Type.Object({}, { additionalProperties: false }),
186
183
  async execute(_id, _params, _signal, _update, ctx) {
187
184
  if (!enabled)
188
- return output({ error: "notesoup is off (/notesoup on to enable)" });
185
+ return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
189
186
  return output({ status: resets.request(currentWindowId(ctx)) }, undefined, true);
190
187
  },
191
188
  }));
@@ -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
  }
@@ -10,8 +10,8 @@ export function piOperationResult(render, outcome) {
10
10
  details: undefined,
11
11
  };
12
12
  }
13
- export const NOTES_NAMESPACE = { name: "notes", description: "Notes you choose to keep across context windows. See /skill:memory." };
14
- export const HISTORY_NAMESPACE = { name: "history", description: "What happened in this session, read-only. See /skill:memory." };
13
+ export const NOTES_NAMESPACE = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
14
+ export const HISTORY_NAMESPACE = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
15
15
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
16
16
  export function registerOperation(pi, operation, run, namespace) {
17
17
  pi.registerTool(defineTool({