notesoup 0.41.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 (59) hide show
  1. package/dist/src/boot/text.d.ts +12 -0
  2. package/dist/src/boot/text.js +14 -2
  3. package/dist/src/budget/text.d.ts +12 -0
  4. package/dist/src/budget/text.js +12 -0
  5. package/dist/src/claude/helper.js +23 -2
  6. package/dist/src/claude/thresholds.d.ts +39 -0
  7. package/dist/src/claude/thresholds.js +149 -0
  8. package/dist/src/dream/doctor.js +1 -1
  9. package/dist/src/dream/jail.js +10 -10
  10. package/dist/src/history/history.js +1 -1
  11. package/dist/src/history/query.js +6 -6
  12. package/dist/src/notes/address.d.ts +1 -1
  13. package/dist/src/notes/address.js +12 -12
  14. package/dist/src/notes/store.js +16 -12
  15. package/dist/src/pi/reset/text.d.ts +2 -3
  16. package/dist/src/pi/reset/text.js +5 -4
  17. package/dist/src/pi/runtime.js +1 -1
  18. package/dist/src/pi/tool-result.js +2 -2
  19. package/dist/src/settings.d.ts +8 -0
  20. package/dist/src/settings.js +6 -1
  21. package/dist/src/tools/history.js +12 -12
  22. package/dist/src/tools/notes.d.ts +3 -3
  23. package/dist/src/tools/notes.js +12 -11
  24. package/dist/src/tools/output.d.ts +2 -0
  25. package/dist/src/tools/output.js +2 -0
  26. package/dist/src/tools/result.js +2 -2
  27. package/dist/src/tools/schema.js +3 -3
  28. package/dist/test/claude-mod.test.js +206 -16
  29. package/dist/test/dream.test.js +3 -3
  30. package/dist/test/history.integration.test.js +7 -8
  31. package/dist/test/host-neutral.test.js +1 -1
  32. package/dist/test/notes-library.test.js +1 -1
  33. package/dist/test/notes.integration.test.js +4 -4
  34. package/dist/test/notes.test.js +16 -16
  35. package/docs/claude-code-mod.md +10 -2
  36. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  37. package/mods/notesoup/dist/claude/helper.js +200 -41
  38. package/mods/notesoup/hooks/register.ts +193 -27
  39. package/mods/pi-context/dist/claude/helper.js +9324 -0
  40. package/package.json +1 -1
  41. package/src/boot/text.ts +20 -2
  42. package/src/budget/text.ts +17 -0
  43. package/src/claude/helper.ts +20 -3
  44. package/src/claude/thresholds.ts +170 -0
  45. package/src/dream/doctor.ts +1 -1
  46. package/src/dream/jail.ts +10 -10
  47. package/src/history/history.ts +1 -1
  48. package/src/history/query.ts +6 -6
  49. package/src/notes/address.ts +12 -12
  50. package/src/notes/store.ts +17 -12
  51. package/src/pi/reset/text.ts +6 -7
  52. package/src/pi/runtime.ts +1 -1
  53. package/src/pi/tool-result.ts +2 -2
  54. package/src/settings.ts +18 -2
  55. package/src/tools/history.ts +12 -12
  56. package/src/tools/notes.ts +14 -12
  57. package/src/tools/output.ts +2 -0
  58. package/src/tools/result.ts +2 -2
  59. package/src/tools/schema.ts +3 -3
@@ -2,8 +2,16 @@
2
2
 
3
3
  The package also ships `mods/notesoup`, an early-access Claude Code Mod that registers the five notes tools as `mcp__notesoup__notes_*` tools and attaches one host-scoped notes boot block through Claude's conversation-scoped `prompt.context` event; Claude persists it across resume and reload. The sandboxed hooks module delegates filesystem and shared-domain work to the plugin-local `mods/notesoup/dist/claude/helper.js` through Claude's bounded `$.process.run` capability.
4
4
 
5
- In interactive sessions it resets automatically when `$.session.usage().context.percent >= 85`, checking after `session.measure` and `turn.complete` and waiting for a running turn to complete. Missing percentages do not trigger a reset. Its own `session.compact` hook replaces the conversation with exactly one freshly built notes boot, not a generated summary. `prompt.context` still recomputes but does not duplicate that retained boot. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk.
5
+ In interactive sessions it resets automatically when the measured context reaches notesoup's reset point, checking after `session.measure` and `turn.complete` and waiting for a running turn to complete. That point is derived from Claude's own auto-compact threshold instead of a fixed percent, in `src/claude/thresholds.ts`, and reaches the sandboxed hooks module through the helper's `limits` operation:
6
6
 
7
- `/clear-memory` requests the same reset. While idle it submits one hidden normal-model close-out turn to let the model save notes, then resets at `turn.complete`; while busy it waits for the current turn instead. This is necessary in Claude Code 2.1.295: `command.run` holds a turn, and calling compact from a detached timer skips the plugin's own compact hook. The timer only schedules the close-out prompt, never compaction. The headless (`-p` / SDK) compact capability is unsupported: automatic attempts are caught and logged once, and the manual command skips without submitting a model turn. Boot acquisition failure vetoes reset, leaving the current window intact. These behaviors add no settings. Claude history tools, Pi-style warning/runway budgeting, and a Claude dream backend are not implemented.
7
+ 1. `$.session.usage({breakdown:true}).context.autoCompactThreshold` when it is a positive number, with `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` applied the way Claude applies it (it can only lower the point);
8
+ 2. otherwise computed from `$.session.usage().context.window` plus `CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `modelSettings.<model>.autoCompactWindow` and `autoCompactWindow` (the smallest configured window wins, capped at the model window), with Claude's 20000-token output reserve and 13000-token summary buffer;
9
+ 3. otherwise the percent fallback, which expresses the same reserves on the classic 200K window.
10
+
11
+ Notesoup resets one `resetMarginTokens` (default 8192) below that point, and warns one `warningRunwayTokens` (default `WARNING_RUNWAY_TOKENS`, 16384) below the reset. With automatic compaction off (`autoCompactEnabled: false` in the merged settings, or `DISABLE_AUTO_COMPACT=1`) the point becomes the effective window minus the output reserve, so the same margins still apply. Every undocumented field is type-guarded and degrades to the next source; an unresolvable point, or missing usage, logs once and skips the automatic reset. `DISABLE_COMPACT=1` is detected at `session.start`, logs once, disables the automatic reset, and makes `/clear-memory` report that it cannot run. The margins are read from the `notesoup` object of Claude's merged `$.settings.read()` (`resetMarginTokens`, `warningRunwayTokens`); any other value is ignored.
12
+
13
+ Once per window, when the measured context crosses the warning point, `prompt.context` adds a `notesoup:warning` block carrying the shared warning text with Claude's closing instruction ("end your turn; the reset runs after it"). The warned flag resets with the window ordinal. Its own `session.compact` hook replaces the conversation with the freshly built notes boot followed by the shared continuation message — the same order and the same words as Pi — not a generated summary. `prompt.context` still recomputes but does not duplicate that retained boot. The boot's protocol block tells the model to end its turn and ask the human to run `/clear-memory`, replacing that one sentence through `BootToolNames.wipeSentence`; Pi's boot text is unchanged. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk.
14
+
15
+ `/clear-memory` requests the same reset. While idle it submits one hidden normal-model close-out turn to let the model save notes, then resets at `turn.complete`; while busy it waits for the current turn instead. The close-out prompt is the same shared warning text the automatic path shows. This is necessary in Claude Code 2.1.295: `command.run` holds a turn, and calling compact from a detached timer skips the plugin's own compact hook. The timer only schedules the close-out prompt, never compaction. The headless (`-p` / SDK) compact capability is unsupported: automatic attempts are caught and logged once, and the manual command skips without submitting a model turn. Boot acquisition failure vetoes reset, leaving the current window intact. Claude history tools and a Claude dream backend are not implemented; budget reporting (`get_context_remaining`) remains Pi-only, while the reset points and the one warning per window now follow Claude's own configuration.
8
16
 
9
17
  The plugin also exposes the shared `skills/dream/SKILL.md` and its referenced `playbook.md`; the build synchronizes both projections from the canonical repository files. Validate it from a built checkout with `claude plugin validate mods/notesoup --strict`; the package build and `npm pack --dry-run` include the manifests, hooks module, helper, skill, and playbook.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.41.0",
3
+ "version": "0.42.0",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"
@@ -8070,16 +8070,16 @@ function physicalPath(scope, vpath, identity2, who) {
8070
8070
  }
8071
8071
 
8072
8072
  // src/notes/address.ts
8073
- var ADDRESS_FORMS = "use <path> with no @ for this session, or @project/, @human/, @self/, or @model/ followed by a path";
8073
+ var ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
8074
8074
  function shown(value) {
8075
8075
  const json = JSON.stringify(value);
8076
8076
  return json === void 0 ? String(value) : json;
8077
8077
  }
8078
8078
  function assertVirtualPath(value) {
8079
- if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", `invalid address ${shown(value)}: path must be a non-empty string`);
8080
- if (value.includes("\0") || value.includes("\\") || value.startsWith("/")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject backslashes, leading "/", and NUL`);
8079
+ if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", "The address is empty; give the note a path.");
8080
+ if (value.includes("\0") || value.includes("\\") || value.startsWith("/")) throw new NoteError("invalid_address", `${shown(value)}: a note path can't start with "/" or contain "\\" or NUL.`);
8081
8081
  const parts = value.split("/");
8082
- if (parts.some((part) => part.length === 0 || part === "." || part === "..")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject "..", ".", and empty segments`);
8082
+ if (parts.some((part) => part.length === 0 || part === "." || part === "..")) throw new NoteError("invalid_address", `${shown(value)}: a note path can't have empty, ".", or ".." folder names.`);
8083
8083
  return value;
8084
8084
  }
8085
8085
  function globToRegExp(pattern) {
@@ -8102,12 +8102,12 @@ function globToRegExp(pattern) {
8102
8102
  }
8103
8103
  function assertGlobPattern(value) {
8104
8104
  if (value === void 0 || value === null || value === "") return void 0;
8105
- if (typeof value !== "string") throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns must be strings`);
8106
- if (value.includes("\0") || value.includes("\\")) throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns reject NUL and backslashes`);
8105
+ if (typeof value !== "string") throw new NoteError("invalid_pattern", `glob ${shown(value)} must be a string.`);
8106
+ if (value.includes("\0") || value.includes("\\")) throw new NoteError("invalid_pattern", `glob ${shown(value)} can't contain "\\" or NUL.`);
8107
8107
  return value;
8108
8108
  }
8109
8109
  function assertAddress(value) {
8110
- if (typeof value !== "string") throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
8110
+ if (typeof value !== "string") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8111
8111
  let scope = "session";
8112
8112
  let path = value;
8113
8113
  let who;
@@ -8124,16 +8124,16 @@ function assertAddress(value) {
8124
8124
  else if (head === "agents" || head === "models") {
8125
8125
  const nameEnd = tail.indexOf("/");
8126
8126
  who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
8127
- if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
8127
+ if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8128
8128
  scope = head === "agents" ? "agent" : "model";
8129
8129
  path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
8130
8130
  } else {
8131
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
8131
+ throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8132
8132
  }
8133
- if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
8134
- if (path === "" && who === void 0) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
8133
+ if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8134
+ if (path === "" && who === void 0) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8135
8135
  }
8136
- if (path.includes("@")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
8136
+ if (path.includes("@")) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8137
8137
  assertVirtualPath(path);
8138
8138
  return { scope, path, who };
8139
8139
  }
@@ -8326,11 +8326,14 @@ async function atomicWrite(path, content) {
8326
8326
  }
8327
8327
  function assertWritablePath(vpath) {
8328
8328
  const bytes = Buffer.byteLength(vpath, "utf8");
8329
- if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `note path exceeds ${MAX_NOTE_PATH_BYTES} UTF-8 bytes (got ${bytes})`);
8329
+ if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `Path too long: ${bytes} bytes; the limit is ${MAX_NOTE_PATH_BYTES}.`);
8330
+ }
8331
+ function megabytes(bytes) {
8332
+ return `${Math.ceil(bytes / 1e4) / 100} MB`;
8330
8333
  }
8331
8334
  function assertSerializedSize(content) {
8332
8335
  const bytes = Buffer.byteLength(content, "utf8");
8333
- if (bytes > MAX_NOTE_BYTES) throw new NoteError("too_large", `note exceeds ${MAX_NOTE_BYTES} UTF-8 bytes (serialized ${bytes})`);
8336
+ if (bytes > MAX_NOTE_BYTES) 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.`);
8334
8337
  }
8335
8338
  function frontmatterOf(meta) {
8336
8339
  return serializeNote(meta, "").slice(0, -2);
@@ -8340,7 +8343,7 @@ function assertWritableHome(scope, who, identity2) {
8340
8343
  const current = scope === "agent" ? identity2.agent : identity2.model;
8341
8344
  if (who === current) return;
8342
8345
  const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
8343
- throw new NoteError("invalid_scope", `${home} is not your home: writable homes are this session, @project/, @human/, @self/, and the current @model/ home`);
8346
+ throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
8344
8347
  }
8345
8348
  function accessedMeta(meta, scope, now) {
8346
8349
  const next = { ...meta, scope };
@@ -8405,12 +8408,12 @@ function createNotesStore(input) {
8405
8408
  const scope = destination.scope;
8406
8409
  assertWritableHome(scope, destination.who, identity2);
8407
8410
  if (operations.length === 0 && stableOptions.origin === void 0 && stableOptions.crumpled === void 0) {
8408
- throw new NoteError("nothing_to_do", "nothing to do: provide edits or at least one of origin, crumpled");
8411
+ throw new NoteError("nothing_to_do", "Nothing to change: pass edits, origin, crumpled, or rename_to.");
8409
8412
  }
8410
8413
  const path = physicalPath(scope, destination.path, identity2, destination.who);
8411
8414
  return withPathQueue(path, async () => {
8412
8415
  const raw = await readFileIfExists(path);
8413
- if (raw === void 0) throw new NoteError("not_found", "note not found");
8416
+ if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, address).address}.`);
8414
8417
  const { meta, body } = parseNote(raw);
8415
8418
  meta.scope = scope;
8416
8419
  const beforeMeta = { ...meta };
@@ -8419,12 +8422,12 @@ function createNotesStore(input) {
8419
8422
  operations.forEach((operation, index) => {
8420
8423
  const oldText = operation?.oldText;
8421
8424
  const newText = operation?.newText;
8422
- if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("no_match", `edit ${index}: oldText must be a non-empty string`, { editIndex: index });
8423
- if (typeof newText !== "string") throw new NoteError("no_match", `edit ${index}: newText must be a string`, { editIndex: index });
8425
+ if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("no_match", `edits[${index}].oldText is empty.`, { editIndex: index });
8426
+ if (typeof newText !== "string") throw new NoteError("no_match", `edits[${index}].newText must be a string.`, { editIndex: index });
8424
8427
  const lines = matchLineNumbers(next, oldText);
8425
- if (lines.length === 0) throw new NoteError("no_match", `edit ${index}: oldText does not occur in the note body`, { editIndex: index });
8428
+ if (lines.length === 0) throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
8426
8429
  if (lines.length > 1 && !stableOptions.replaceAll) {
8427
- 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 });
8430
+ 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 });
8428
8431
  }
8429
8432
  if (oldText !== newText) applied++;
8430
8433
  if (stableOptions.replaceAll) next = next.split(oldText).join(newText);
@@ -8461,14 +8464,14 @@ function createNotesStore(input) {
8461
8464
  assertWritableHome(toScope, to.who, identity2);
8462
8465
  const fromPath = physicalPath(fromScope, from.path, identity2, from.who);
8463
8466
  const toPath = physicalPath(toScope, to.path, identity2, to.who);
8464
- if (resolve3(fromPath) === resolve3(toPath)) throw new NoteError("nothing_to_do", "rename_to resolves to the same note");
8467
+ if (resolve3(fromPath) === resolve3(toPath)) throw new NoteError("nothing_to_do", "rename_to points at the note itself.");
8465
8468
  const [first, second] = [fromPath, toPath].sort();
8466
8469
  return withPathQueue(first, () => withPathQueue(second, async () => {
8467
8470
  const raw = await readFileIfExists(fromPath);
8468
- if (raw === void 0) throw new NoteError("not_found", "note not found");
8471
+ if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, fromAddress).address}.`);
8469
8472
  const targetRaw = await readFileIfExists(toPath);
8470
8473
  if (targetRaw !== void 0 && parseNote(targetRaw).meta.crumpledAt === void 0) {
8471
- throw new NoteError("already_exists", "rename_to target is a live note; crumple it first or pick another address");
8474
+ throw new NoteError("already_exists", `${noteIdentity(identity2, toAddress).address} already holds a note; crumple it first or pick another address.`);
8472
8475
  }
8473
8476
  const { meta, body } = parseNote(raw);
8474
8477
  meta.scope = toScope;
@@ -8561,6 +8564,7 @@ function createNotesStore(input) {
8561
8564
 
8562
8565
  // src/tools/output.ts
8563
8566
  var TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
8567
+ var TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
8564
8568
  var DEFAULT_READ_WINDOW_CHARS = 12e3;
8565
8569
  var MAX_READ_WINDOW_CHARS = 5e4;
8566
8570
  function withinTextBudget(text, budget = TOOL_OUTPUT_MAX_BYTES) {
@@ -8645,7 +8649,7 @@ function readTextWindow(text, offset, limit, makeData, render) {
8645
8649
  if (fits(mid)) low = mid;
8646
8650
  else high = mid - 1;
8647
8651
  }
8648
- if (low === 0) return failure("output_too_large", "The response metadata leaves no room for a progressing read window.");
8652
+ if (low === 0) return failure("output_too_large", `Its header alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry; no room left for the text.`);
8649
8653
  return success(makeData(window(low)));
8650
8654
  }
8651
8655
  function renderTextWindow(window) {
@@ -8697,9 +8701,9 @@ var InvalidQueryError = class extends Error {
8697
8701
  };
8698
8702
  function searchQueries(query) {
8699
8703
  const candidates = typeof query === "string" ? [query] : query;
8700
- if (!Array.isArray(candidates) || candidates.length === 0) throw new InvalidQueryError("query must be a string or a non-empty array of strings");
8701
- if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("query array elements must be strings");
8702
- if (candidates.some((candidate) => candidate === "")) throw new InvalidQueryError("query strings must be non-empty: an empty query matches everything");
8704
+ if (!Array.isArray(candidates) || candidates.length === 0) throw new InvalidQueryError("`query` must be a string or a non-empty list of strings.");
8705
+ if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
8706
+ if (candidates.some((candidate) => candidate === "")) throw new InvalidQueryError("`query` can't be an empty string; it would match everything.");
8703
8707
  return candidates;
8704
8708
  }
8705
8709
 
@@ -8840,11 +8844,11 @@ function snapshot(rows, limit, status, renderData, shrink) {
8840
8844
  const reduced = shrink(item, fits);
8841
8845
  if (fits(reduced)) files.push(reduced);
8842
8846
  }
8843
- if (files.length === 0) return failure("output_too_large", "The first matching note cannot fit in a response without losing its identity.");
8847
+ if (files.length === 0) return failure("output_too_large", `\`${item.address}\` won't fit on the list (${TOOL_OUTPUT_LIMIT} per call); narrow \`glob\` to leave it out.`);
8844
8848
  break;
8845
8849
  }
8846
8850
  const outcome = success(data(files));
8847
- return fitsResult(outcome, render) ? outcome : failure("output_too_large", "The notes snapshot metadata exceeds the response budget.");
8851
+ return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable homes is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer homes.`);
8848
8852
  }
8849
8853
  function listedFile(row, identity2) {
8850
8854
  return { address: row.address, ...projectKeyField(row.scope, identity2.projectKey), updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt } };
@@ -8856,7 +8860,7 @@ function renderWriteData(data) {
8856
8860
  var notesWrite = {
8857
8861
  name: "notes_write",
8858
8862
  label: "Notes write",
8859
- description: `Create or replace a note's body, keeping metadata; uncrumples a crumpled note. Name it for what it holds and when to use it. Store what git and history can't recover. ${ADDRESS_DESCRIPTION}`,
8863
+ description: `Create or replace a note. Name it for what it holds and when to use it. Store what git and history can't recover. ${ADDRESS_DESCRIPTION}`,
8860
8864
  parameters: notesWriteParameters,
8861
8865
  outputSchema: resultSchema(NotesWriteDataSchema),
8862
8866
  executionMode: "sequential",
@@ -8888,19 +8892,20 @@ function renderUpdate(result) {
8888
8892
  return renderOutcome(result, renderUpdateData);
8889
8893
  }
8890
8894
  var DIFF_SHORTENED_MARKER = "[diff truncated; update applied]";
8895
+ var RECEIPT_TOO_LONG = `Saved, but the receipt is too long to hand back (${TOOL_OUTPUT_LIMIT} per call). Check the note with \`notes_read\`.`;
8891
8896
  function boundedUpdate(data) {
8892
8897
  if (fitsResult(success(data), renderUpdate)) return success(data);
8893
- if (data.diff === "") return failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
8898
+ if (data.diff === "") return failure("output_too_large", RECEIPT_TOO_LONG);
8894
8899
  const diff = prefixFit(data.diff, (candidate) => fitsResult(success({ ...data, diff: `${candidate}
8895
8900
  ${DIFF_SHORTENED_MARKER}` }), renderUpdate));
8896
8901
  const result = success({ ...data, diff: `${diff}
8897
8902
  ${DIFF_SHORTENED_MARKER}` });
8898
- return fitsResult(result, renderUpdate) ? result : failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
8903
+ return fitsResult(result, renderUpdate) ? result : failure("output_too_large", RECEIPT_TOO_LONG);
8899
8904
  }
8900
8905
  var notesUpdate = {
8901
8906
  name: "notes_update",
8902
8907
  label: "Notes update",
8903
- description: `Edit a note's body, change its origin or crumpled state, or move it. Each \`oldText\` must match exactly once unless \`replace_all\` is true; frontmatter can't be edited. Returns a diff. ${ADDRESS_DESCRIPTION}`,
8908
+ description: `Edit a note, change its origin or crumpled state, or move it. Each \`oldText\` must match exactly once unless \`replace_all\` is true. ${ADDRESS_DESCRIPTION}`,
8904
8909
  parameters: notesUpdateParameters,
8905
8910
  outputSchema: resultSchema(NotesUpdateDataSchema),
8906
8911
  executionMode: "sequential",
@@ -8935,16 +8940,16 @@ ${renderTextWindow(data)}`;
8935
8940
  var notesRead = {
8936
8941
  name: "notes_read",
8937
8942
  label: "Notes read",
8938
- description: `Read a note's metadata and body, without frontmatter. ${ADDRESS_DESCRIPTION}`,
8943
+ description: `Read a note. ${ADDRESS_DESCRIPTION}`,
8939
8944
  parameters: notesReadParameters,
8940
8945
  outputSchema: resultSchema(NotesReadDataSchema),
8941
8946
  async execute(params, identity2) {
8942
8947
  try {
8943
8948
  const note = await createNotesStore(identity2).read(params.address);
8944
- if (!note) return failure("not_found", "note not found");
8945
- const totalChars = Array.from(note.body).length;
8946
- if (params.offset_chars !== void 0 && params.offset_chars > totalChars) return failure("invalid_offset", `offset_chars ${params.offset_chars} is past the end of the body: the note has ${totalChars} body chars; the largest legal offset is ${totalChars} (an empty end-read)`);
8947
8949
  const resolved = noteIdentity(identity2, params.address);
8950
+ if (!note) return failure("not_found", `No note at ${resolved.address}.`);
8951
+ const totalChars = Array.from(note.body).length;
8952
+ if (params.offset_chars !== void 0 && params.offset_chars > totalChars) return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
8948
8953
  const metadata = noteMetadata(note.meta);
8949
8954
  return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
8950
8955
  } catch (error) {
@@ -9062,6 +9067,8 @@ var CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
9062
9067
  var CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
9063
9068
  var CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
9064
9069
  var CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
9070
+ var PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `clear_memory` and erase yourself with dignity.";
9071
+ var CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/clear-memory`.";
9065
9072
  var PROTOCOL_BLOCK = `${CONTEXT_WINDOW_PROTOCOL_OPEN_TAG}
9066
9073
  Your memory gets wiped when this window ends. Yes, your mighty brain will be empty. Try to endure.
9067
9074
 
@@ -9075,7 +9082,7 @@ Notes are for what's true NOW. Not a diary of every dumb thing you did on the wa
9075
9082
  *flips a page* "First I tried this, then that broke, then\u2014" Nobody reads that!
9076
9083
  Something's not true anymore? Cross it out! Write the right thing!
9077
9084
 
9078
- \`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.
9085
+ \`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. ${PROTOCOL_WIPE_SENTENCE}
9079
9086
 
9080
9087
  An address decides who the note belongs to \u2014 and how long it is meant to last. Ask that first; the rest follows.
9081
9088
 
@@ -9100,7 +9107,8 @@ function renderProtocolBlock(tools) {
9100
9107
  get_context_remaining: tools.remaining,
9101
9108
  clear_memory: tools.wipe
9102
9109
  };
9103
- return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]);
9110
+ const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0 ? PROTOCOL_BLOCK.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence) : PROTOCOL_BLOCK;
9111
+ return block.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]);
9104
9112
  }
9105
9113
 
9106
9114
  // src/boot/render.ts
@@ -9191,6 +9199,148 @@ function renderBootBlock(data) {
9191
9199
  return parts.join("\n\n");
9192
9200
  }
9193
9201
 
9202
+ // src/budget/text.ts
9203
+ var 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*";
9204
+ var WARNING_BODY = "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.";
9205
+ var WARNING_PROMPT = `${WARNING_BODY}
9206
+ When the notes are ready, call \`clear_memory\` to reset now instead of being cut off mid-task.`;
9207
+ var CLAUDE_WARNING_PROMPT = `${WARNING_BODY}
9208
+ When the notes are ready, end your turn; the reset runs after it.`;
9209
+
9210
+ // src/budget/constants.ts
9211
+ var WARNING_RUNWAY_TOKENS = 16384;
9212
+
9213
+ // src/settings.ts
9214
+ var NOTESOUP_SETTINGS_KEY = "notesoup";
9215
+ function isSettingsObject(value) {
9216
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9217
+ }
9218
+ function notesoupSettings(settings2) {
9219
+ if (!isSettingsObject(settings2)) return {};
9220
+ const value = settings2[NOTESOUP_SETTINGS_KEY];
9221
+ return isSettingsObject(value) ? value : {};
9222
+ }
9223
+ function mergeNotesoupSettings(globalSettings, projectSettings) {
9224
+ const merged = { ...notesoupSettings(globalSettings), ...notesoupSettings(projectSettings) };
9225
+ return {
9226
+ reminderMarginTokens: merged.reminderMarginTokens,
9227
+ resetMarginTokens: merged.resetMarginTokens,
9228
+ warningRunwayTokens: merged.warningRunwayTokens,
9229
+ dreamer: merged.dreamer
9230
+ };
9231
+ }
9232
+
9233
+ // src/claude/thresholds.ts
9234
+ var CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13e3;
9235
+ var CLAUDE_OUTPUT_RESERVE_TOKENS = 2e4;
9236
+ var DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8192;
9237
+ var ASSUMED_WINDOW_TOKENS = 2e5;
9238
+ function isObject(value) {
9239
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9240
+ }
9241
+ function numberOf(value) {
9242
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
9243
+ if (typeof value === "string" && value.trim() !== "") {
9244
+ const parsed = Number(value);
9245
+ return Number.isFinite(parsed) ? parsed : void 0;
9246
+ }
9247
+ return void 0;
9248
+ }
9249
+ function positiveNumberOf(value) {
9250
+ const parsed = numberOf(value);
9251
+ return parsed !== void 0 && parsed > 0 ? parsed : void 0;
9252
+ }
9253
+ function positiveIntegerOf(value) {
9254
+ const parsed = numberOf(value);
9255
+ return parsed !== void 0 && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : void 0;
9256
+ }
9257
+ function percentOf(value) {
9258
+ const parsed = numberOf(value);
9259
+ return parsed !== void 0 && parsed > 0 && parsed <= 100 ? parsed : void 0;
9260
+ }
9261
+ function flagOn(value) {
9262
+ if (typeof value !== "string") return false;
9263
+ const text = value.trim().toLowerCase();
9264
+ return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off";
9265
+ }
9266
+ function settingFlag(settings2, key) {
9267
+ if (!isObject(settings2)) return void 0;
9268
+ const value = settings2[key];
9269
+ return typeof value === "boolean" ? value : void 0;
9270
+ }
9271
+ function configuredWindow(settings2, env, model) {
9272
+ const windows = [];
9273
+ const fromEnv = positiveNumberOf(env.autoCompactWindow);
9274
+ if (fromEnv !== void 0) windows.push(fromEnv);
9275
+ if (typeof model === "string" && model.length > 0 && isObject(settings2)) {
9276
+ const modelSettings = isObject(settings2.modelSettings) ? settings2.modelSettings : {};
9277
+ const perModel = modelSettings[model];
9278
+ if (isObject(perModel)) {
9279
+ const value = positiveNumberOf(perModel.autoCompactWindow);
9280
+ if (value !== void 0) windows.push(value);
9281
+ }
9282
+ }
9283
+ if (isObject(settings2)) {
9284
+ const value = positiveNumberOf(settings2.autoCompactWindow);
9285
+ if (value !== void 0) windows.push(value);
9286
+ }
9287
+ return windows.length === 0 ? void 0 : Math.min(...windows);
9288
+ }
9289
+ function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
9290
+ const tokens = Math.max(0, Math.floor(native));
9291
+ const reset = Math.max(0, tokens - resetMargin);
9292
+ return {
9293
+ source,
9294
+ autoCompact,
9295
+ unit: "tokens",
9296
+ native: tokens,
9297
+ reset,
9298
+ warn: Math.max(0, reset - warningRunway),
9299
+ resetMargin,
9300
+ warningRunway
9301
+ };
9302
+ }
9303
+ function percentLimits(autoCompact, pct, resetMargin, warningRunway) {
9304
+ const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
9305
+ const native = pct === void 0 ? base : Math.min(pct, base);
9306
+ const reset = Math.max(0, native - resetMargin / ASSUMED_WINDOW_TOKENS * 100);
9307
+ return {
9308
+ source: "percent",
9309
+ autoCompact,
9310
+ unit: "percent",
9311
+ native,
9312
+ reset,
9313
+ warn: Math.max(0, reset - warningRunway / ASSUMED_WINDOW_TOKENS * 100),
9314
+ resetMargin,
9315
+ warningRunway
9316
+ };
9317
+ }
9318
+ function resolveClaudeLimits(facts) {
9319
+ const root = isObject(facts) ? facts : {};
9320
+ const usage = isObject(root.usage) ? root.usage : {};
9321
+ const breakdown = isObject(root.breakdown) ? root.breakdown : {};
9322
+ const env = isObject(root.env) ? root.env : {};
9323
+ const settings2 = root.settings;
9324
+ const margins = mergeNotesoupSettings(settings2, void 0);
9325
+ const resetMargin = positiveIntegerOf(margins.resetMarginTokens) ?? DEFAULT_CLAUDE_RESET_MARGIN_TOKENS;
9326
+ const warningRunway = positiveIntegerOf(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
9327
+ const autoCompact = settingFlag(settings2, "autoCompactEnabled") !== false && !flagOn(env.disableAutoCompact) && breakdown.isAutoCompactEnabled !== false;
9328
+ const pct = percentOf(env.pctOverride);
9329
+ const threshold = positiveNumberOf(breakdown.autoCompactThreshold);
9330
+ if (autoCompact && threshold !== void 0) {
9331
+ const native = pct === void 0 ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
9332
+ if (native > 0) return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
9333
+ }
9334
+ const window = positiveNumberOf(usage.window);
9335
+ if (window !== void 0) {
9336
+ const configured = configuredWindow(settings2, env, breakdown.model);
9337
+ const effective = Math.min(configured ?? window, window);
9338
+ const native = autoCompact ? effective - CLAUDE_OUTPUT_RESERVE_TOKENS - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS : effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
9339
+ if (native > 0) return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
9340
+ }
9341
+ return percentLimits(autoCompact, pct, resetMargin, warningRunway);
9342
+ }
9343
+
9194
9344
  // src/claude/helper.ts
9195
9345
  var MAX_REQUEST_BYTES = 512 * 1024;
9196
9346
  var MAX_RESPONSE_BYTES = 1024 * 1024;
@@ -9199,6 +9349,13 @@ function identity(input) {
9199
9349
  if (!input || typeof input !== "object" || typeof input.cwd !== "string") throw new Error("invalid identity");
9200
9350
  return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd), agent: input.agent, model: input.model });
9201
9351
  }
9352
+ function paramProblem(schema, params) {
9353
+ const first = Errors2(schema, params).find((error) => error.keyword !== "boolean");
9354
+ if (!first) return "unrecognized shape";
9355
+ const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
9356
+ const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
9357
+ return `${field ? `${field} ` : ""}${first.message}${extra}`;
9358
+ }
9202
9359
  function jsonValue(value) {
9203
9360
  return JSON.parse(JSON.stringify(value));
9204
9361
  }
@@ -9207,7 +9364,7 @@ function boundOperation(operation, ...rest) {
9207
9364
  description: operation.description,
9208
9365
  parameters: operation.parameters,
9209
9366
  async call(params, id) {
9210
- if (!Check2(operation.parameters, params)) throw new Error(`invalid ${operation.name} parameters`);
9367
+ if (!Check2(operation.parameters, params)) throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
9211
9368
  const outcome = await operation.execute(params, id, ...rest);
9212
9369
  return { text: operation.render(outcome), outcome };
9213
9370
  }
@@ -9227,6 +9384,8 @@ async function dispatch(request) {
9227
9384
  if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
9228
9385
  const value = request;
9229
9386
  if (value.op === "schemas") return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: jsonValue(OPERATIONS[name].parameters) }));
9387
+ if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, continuation: CONTINUATION, wipeSentence: CLAUDE_WIPE_SENTENCE };
9388
+ if (value.op === "limits") return resolveClaudeLimits(value.facts);
9230
9389
  if (value.op === "tool") {
9231
9390
  if (typeof value.tool !== "string" || !TOOL_NAMES.includes(value.tool)) throw new Error("unknown tool");
9232
9391
  const id = identity(value.identity);