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
@@ -6,6 +6,13 @@ export declare const CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
6
6
  export declare const CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
7
7
  export declare const CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
8
8
  export declare const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
9
+ /**
10
+ * The one sentence that tells the model how to end its window voluntarily. A host with no
11
+ * model-facing reset tool replaces the whole sentence through BootToolNames.wipeSentence.
12
+ */
13
+ export declare const PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `clear_memory` and erase yourself with dignity.";
14
+ /** Claude has no model-facing reset tool: the model ends its turn and the human runs the command. */
15
+ export declare const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/clear-memory`.";
9
16
  /** Logical tool names are supplied by the composing host, not discovered here. */
10
17
  export type BootToolNames = Readonly<{
11
18
  notes: string;
@@ -13,5 +20,10 @@ export type BootToolNames = Readonly<{
13
20
  history: string;
14
21
  remaining: string;
15
22
  wipe: string;
23
+ /**
24
+ * Replaces the whole voluntary-wipe sentence (PROTOCOL_WIPE_SENTENCE) when the host has
25
+ * no model-facing reset tool. Absent means Pi's default sentence, byte for byte.
26
+ */
27
+ wipeSentence?: string;
16
28
  }>;
17
29
  export declare function renderProtocolBlock(tools: BootToolNames): string;
@@ -6,6 +6,13 @@ export const CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
6
6
  export const CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
7
7
  export const CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
8
8
  export const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
9
+ /**
10
+ * The one sentence that tells the model how to end its window voluntarily. A host with no
11
+ * model-facing reset tool replaces the whole sentence through BootToolNames.wipeSentence.
12
+ */
13
+ export const PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `clear_memory` and erase yourself with dignity.";
14
+ /** Claude has no model-facing reset tool: the model ends its turn and the human runs the command. */
15
+ export const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/clear-memory`.";
9
16
  /**
10
17
  * Static protocol teaching adapted from Codex's token_budget.guidance_message to
11
18
  * notesoup's tool names. It lives once per window in the persisted boot block;
@@ -27,7 +34,7 @@ Notes are for what's true NOW. Not a diary of every dumb thing you did on the wa
27
34
  *flips a page* "First I tried this, then that broke, then—" Nobody reads that!
28
35
  Something's not true anymore? Cross it out! Write the right thing!
29
36
 
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.
37
+ \`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}
31
38
 
32
39
  An address decides who the note belongs to — and how long it is meant to last. Ask that first; the rest follows.
33
40
 
@@ -52,5 +59,10 @@ export function renderProtocolBlock(tools) {
52
59
  get_context_remaining: tools.remaining,
53
60
  clear_memory: tools.wipe,
54
61
  };
55
- return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]);
62
+ // The sentence is replaced before name substitution, so a replacement may speak the host's
63
+ // own words (a command line, a tool name) instead of any `notes_*`-style token.
64
+ const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0
65
+ ? PROTOCOL_BLOCK.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence)
66
+ : PROTOCOL_BLOCK;
67
+ return block.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]);
56
68
  }
@@ -1,5 +1,17 @@
1
1
  export declare const GUIDANCE_OPEN_TAG = "<context_window_guidance>";
2
2
  export declare const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
3
+ /**
4
+ * The single reset message: the only reset prose persisted, carried by the continuation entry.
5
+ */
6
+ 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*";
7
+ /**
8
+ * The shared warning body: the one text both hosts show before a reset. Only the closing
9
+ * instruction differs — Pi can reset the model itself, Claude can only end the turn.
10
+ */
11
+ export declare const 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.";
12
+ 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.";
13
+ /** Claude's variant: the mod resets after the turn, so the model only has to stop. */
14
+ export declare const CLAUDE_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, end your turn; the reset runs after it.";
3
15
  /**
4
16
  * Codex-equivalent low-budget reminder. The measured remaining count is frozen into
5
17
  * the text at the crossing that fires it, so each persisted copy is a snapshot true
@@ -1,5 +1,17 @@
1
1
  export const GUIDANCE_OPEN_TAG = "<context_window_guidance>";
2
2
  export const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
3
+ /**
4
+ * The single reset message: the only reset prose persisted, carried by the continuation entry.
5
+ */
6
+ 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*";
7
+ /**
8
+ * The shared warning body: the one text both hosts show before a reset. Only the closing
9
+ * instruction differs — Pi can reset the model itself, Claude can only end the turn.
10
+ */
11
+ export const 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.";
12
+ export const WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, call \`clear_memory\` to reset now instead of being cut off mid-task.`;
13
+ /** Claude's variant: the mod resets after the turn, so the model only has to stop. */
14
+ export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, end your turn; the reset runs after it.`;
3
15
  /**
4
16
  * Codex-equivalent low-budget reminder. The measured remaining count is frozen into
5
17
  * the text at the crossing that fires it, so each persisted copy is a snapshot true
@@ -1,9 +1,12 @@
1
1
  import { realpathSync } from "node:fs";
2
2
  import { pathToFileURL } from "node:url";
3
- import { Check } from "typebox/value";
3
+ import { Check, Errors } from "typebox/value";
4
4
  import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../tools/notes.js";
5
5
  import { loadNotesSnapshot } from "../boot/snapshot.js";
6
6
  import { renderBootBlock } from "../boot/render.js";
7
+ import { CLAUDE_WIPE_SENTENCE } from "../boot/text.js";
8
+ import { CLAUDE_WARNING_PROMPT, CONTINUATION } from "../budget/text.js";
9
+ import { resolveClaudeLimits } from "./thresholds.js";
7
10
  import { projectKey } from "../notes/paths.js";
8
11
  import { snapshotNotesIdentity } from "../notes/identity.js";
9
12
  const MAX_REQUEST_BYTES = 512 * 1024;
@@ -14,6 +17,16 @@ function identity(input) {
14
17
  throw new Error("invalid identity");
15
18
  return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd), agent: input.agent, model: input.model });
16
19
  }
20
+ /** The first schema violation, named by parameter so the model can fix that one field. */
21
+ function paramProblem(schema, params) {
22
+ // A false subschema reports "schema is false"; its parent's additionalProperties error names the field instead.
23
+ const first = Errors(schema, params).find((error) => error.keyword !== "boolean");
24
+ if (!first)
25
+ return "unrecognized shape";
26
+ const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
27
+ const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
28
+ return `${field ? `${field} ` : ""}${first.message}${extra}`;
29
+ }
17
30
  function jsonValue(value) { return JSON.parse(JSON.stringify(value)); }
18
31
  /** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
19
32
  function boundOperation(operation, ...rest) {
@@ -23,7 +36,7 @@ function boundOperation(operation, ...rest) {
23
36
  async call(params, id) {
24
37
  // Refuse before the operation can act: a rejected shape never reaches a write.
25
38
  if (!Check(operation.parameters, params))
26
- throw new Error(`invalid ${operation.name} parameters`);
39
+ throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
27
40
  // The same business outcome and the same renderer as the Pi tool; only the envelope differs.
28
41
  const outcome = await operation.execute(params, id, ...rest);
29
42
  return { text: operation.render(outcome), outcome };
@@ -47,6 +60,14 @@ export async function dispatch(request) {
47
60
  const value = request;
48
61
  if (value.op === "schemas")
49
62
  return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: jsonValue(OPERATIONS[name].parameters) }));
63
+ // The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
64
+ // cannot drift apart. The hooks module caches one copy per session.
65
+ if (value.op === "texts")
66
+ return { warning: CLAUDE_WARNING_PROMPT, continuation: CONTINUATION, wipeSentence: CLAUDE_WIPE_SENTENCE };
67
+ // Threshold derivation crosses the boundary as raw facts: everything the engine could
68
+ // read, unvalidated. resolveClaudeLimits guards every field and never throws.
69
+ if (value.op === "limits")
70
+ return resolveClaudeLimits(value.facts);
50
71
  if (value.op === "tool") {
51
72
  if (typeof value.tool !== "string" || !TOOL_NAMES.includes(value.tool))
52
73
  throw new Error("unknown tool");
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Claude's auto-compact point, derived the way Claude derives it — never a hardcoded percent.
3
+ *
4
+ * Claude compacts at `min(floor((W_eff - out) * pct/100), W_eff - out - 13000)`, where
5
+ * `W_eff` is the resolved auto-compact window, `out` is the output reserve (capped at 20000),
6
+ * and `pct` is CLAUDE_AUTOCOMPACT_PCT_OVERRIDE. This module mirrors those constants so
7
+ * notesoup can resolve the same point from settings and environment alone when the
8
+ * undocumented `usage({breakdown:true})` field is missing.
9
+ */
10
+ /** Claude's summary buffer between the output reserve and the auto-compact point. */
11
+ export declare const CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13000;
12
+ /** Claude's cap on the reserved output tokens; the mod cannot read the model's own value. */
13
+ export declare const CLAUDE_OUTPUT_RESERVE_TOKENS = 20000;
14
+ /** Default slack between Claude's auto-compact point and notesoup's notes-only reset. */
15
+ export declare const DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8192;
16
+ export type ClaudeLimitSource = "auto-compact" | "window" | "percent";
17
+ export type ClaudeLimits = {
18
+ /** Which field produced the point: Claude's own threshold, a computed window, or the percent fallback. */
19
+ readonly source: ClaudeLimitSource;
20
+ /** False when automatic compaction is off, so the point sits at the hard window instead. */
21
+ readonly autoCompact: boolean;
22
+ /** Which measured field the points are expressed in. */
23
+ readonly unit: "tokens" | "percent";
24
+ /** Claude's effective auto-compact point. */
25
+ readonly native: number;
26
+ /** Where notesoup resets: native minus the reset margin. */
27
+ readonly reset: number;
28
+ /** Where the one warning per window fires: reset minus the warning runway. */
29
+ readonly warn: number;
30
+ readonly resetMargin: number;
31
+ readonly warningRunway: number;
32
+ };
33
+ /**
34
+ * Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
35
+ * so a missing or malformed one degrades to the next source and finally to the percent
36
+ * fallback; resolution never throws. `facts` is deliberately unknown: it crosses the mod
37
+ * helper boundary, where nothing is typed.
38
+ */
39
+ export declare function resolveClaudeLimits(facts: unknown): ClaudeLimits;
@@ -0,0 +1,149 @@
1
+ import { WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
2
+ import { mergeNotesoupSettings } from "../settings.js";
3
+ /**
4
+ * Claude's auto-compact point, derived the way Claude derives it — never a hardcoded percent.
5
+ *
6
+ * Claude compacts at `min(floor((W_eff - out) * pct/100), W_eff - out - 13000)`, where
7
+ * `W_eff` is the resolved auto-compact window, `out` is the output reserve (capped at 20000),
8
+ * and `pct` is CLAUDE_AUTOCOMPACT_PCT_OVERRIDE. This module mirrors those constants so
9
+ * notesoup can resolve the same point from settings and environment alone when the
10
+ * undocumented `usage({breakdown:true})` field is missing.
11
+ */
12
+ /** Claude's summary buffer between the output reserve and the auto-compact point. */
13
+ export const CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13_000;
14
+ /** Claude's cap on the reserved output tokens; the mod cannot read the model's own value. */
15
+ export const CLAUDE_OUTPUT_RESERVE_TOKENS = 20_000;
16
+ /** Default slack between Claude's auto-compact point and notesoup's notes-only reset. */
17
+ export const DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8_192;
18
+ /**
19
+ * The percent fallback assumes the classic 200K model window: it is reached only when
20
+ * `usage()` reports no window and no breakdown, and it reproduces the token maths below
21
+ * on that window (about 83.5% / 79.4% / 71.2%).
22
+ */
23
+ const ASSUMED_WINDOW_TOKENS = 200_000;
24
+ function isObject(value) {
25
+ return typeof value === "object" && value !== null && !Array.isArray(value);
26
+ }
27
+ /** Numbers may arrive typed or as environment strings; anything else is unknown. */
28
+ function numberOf(value) {
29
+ if (typeof value === "number")
30
+ return Number.isFinite(value) ? value : undefined;
31
+ if (typeof value === "string" && value.trim() !== "") {
32
+ const parsed = Number(value);
33
+ return Number.isFinite(parsed) ? parsed : undefined;
34
+ }
35
+ return undefined;
36
+ }
37
+ function positiveNumberOf(value) {
38
+ const parsed = numberOf(value);
39
+ return parsed !== undefined && parsed > 0 ? parsed : undefined;
40
+ }
41
+ /** A margin is usable only as a positive integer, matching Pi's budget policy. */
42
+ function positiveIntegerOf(value) {
43
+ const parsed = numberOf(value);
44
+ return parsed !== undefined && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
45
+ }
46
+ /** Claude accepts a percent override only in (0, 100]. */
47
+ function percentOf(value) {
48
+ const parsed = numberOf(value);
49
+ return parsed !== undefined && parsed > 0 && parsed <= 100 ? parsed : undefined;
50
+ }
51
+ /** Presence-style flags (DISABLE_AUTO_COMPACT): any value but an explicit no counts as on. */
52
+ function flagOn(value) {
53
+ if (typeof value !== "string")
54
+ return false;
55
+ const text = value.trim().toLowerCase();
56
+ return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off";
57
+ }
58
+ function settingFlag(settings, key) {
59
+ if (!isObject(settings))
60
+ return undefined;
61
+ const value = settings[key];
62
+ return typeof value === "boolean" ? value : undefined;
63
+ }
64
+ /**
65
+ * The configured auto-compact window, smallest first: CLAUDE_CODE_AUTO_COMPACT_WINDOW,
66
+ * modelSettings.<model>.autoCompactWindow, then the top-level autoCompactWindow. Taking the
67
+ * smallest present value keeps notesoup's reset ahead of whichever one Claude would use.
68
+ */
69
+ function configuredWindow(settings, env, model) {
70
+ const windows = [];
71
+ const fromEnv = positiveNumberOf(env.autoCompactWindow);
72
+ if (fromEnv !== undefined)
73
+ windows.push(fromEnv);
74
+ if (typeof model === "string" && model.length > 0 && isObject(settings)) {
75
+ const modelSettings = isObject(settings.modelSettings) ? settings.modelSettings : {};
76
+ const perModel = modelSettings[model];
77
+ if (isObject(perModel)) {
78
+ const value = positiveNumberOf(perModel.autoCompactWindow);
79
+ if (value !== undefined)
80
+ windows.push(value);
81
+ }
82
+ }
83
+ if (isObject(settings)) {
84
+ const value = positiveNumberOf(settings.autoCompactWindow);
85
+ if (value !== undefined)
86
+ windows.push(value);
87
+ }
88
+ return windows.length === 0 ? undefined : Math.min(...windows);
89
+ }
90
+ function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
91
+ const tokens = Math.max(0, Math.floor(native));
92
+ const reset = Math.max(0, tokens - resetMargin);
93
+ return {
94
+ source, autoCompact, unit: "tokens",
95
+ native: tokens, reset, warn: Math.max(0, reset - warningRunway), resetMargin, warningRunway,
96
+ };
97
+ }
98
+ /** The percent fallback: the same reserves expressed as points of ASSUMED_WINDOW_TOKENS. */
99
+ function percentLimits(autoCompact, pct, resetMargin, warningRunway) {
100
+ const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
101
+ const native = pct === undefined ? base : Math.min(pct, base);
102
+ const reset = Math.max(0, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
103
+ return {
104
+ source: "percent", autoCompact, unit: "percent",
105
+ native, reset, warn: Math.max(0, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
106
+ };
107
+ }
108
+ /**
109
+ * Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
110
+ * so a missing or malformed one degrades to the next source and finally to the percent
111
+ * fallback; resolution never throws. `facts` is deliberately unknown: it crosses the mod
112
+ * helper boundary, where nothing is typed.
113
+ */
114
+ export function resolveClaudeLimits(facts) {
115
+ const root = isObject(facts) ? facts : {};
116
+ const usage = isObject(root.usage) ? root.usage : {};
117
+ const breakdown = isObject(root.breakdown) ? root.breakdown : {};
118
+ const env = isObject(root.env) ? root.env : {};
119
+ const settings = root.settings;
120
+ const margins = mergeNotesoupSettings(settings, undefined);
121
+ const resetMargin = positiveIntegerOf(margins.resetMarginTokens) ?? DEFAULT_CLAUDE_RESET_MARGIN_TOKENS;
122
+ const warningRunway = positiveIntegerOf(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
123
+ const autoCompact = settingFlag(settings, "autoCompactEnabled") !== false
124
+ && !flagOn(env.disableAutoCompact)
125
+ && breakdown.isAutoCompactEnabled !== false;
126
+ const pct = percentOf(env.pctOverride);
127
+ // (a) Claude's own point. It already includes the window, model settings and CLI flag; only
128
+ // the percent override is applied separately, on the window-after-output-reserve it is
129
+ // minted from (threshold + summary buffer).
130
+ const threshold = positiveNumberOf(breakdown.autoCompactThreshold);
131
+ if (autoCompact && threshold !== undefined) {
132
+ const native = pct === undefined ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
133
+ if (native > 0)
134
+ return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
135
+ }
136
+ // (b) The same point computed from the reported window plus settings and environment.
137
+ const window = positiveNumberOf(usage.window);
138
+ if (window !== undefined) {
139
+ const configured = configuredWindow(settings, env, breakdown.model);
140
+ const effective = Math.min(configured ?? window, window);
141
+ const native = autoCompact
142
+ ? effective - CLAUDE_OUTPUT_RESERVE_TOKENS - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS
143
+ : effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
144
+ if (native > 0)
145
+ return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
146
+ }
147
+ // (c) Nothing usable but percentages.
148
+ return percentLimits(autoCompact, pct, resetMargin, warningRunway);
149
+ }
@@ -77,7 +77,7 @@ export function doctor(home) {
77
77
  report(path, `${address}: target missing; update or remove the reference`);
78
78
  }
79
79
  catch {
80
- report(path, `${address}: invalid address; ${ADDRESS_FORMS}`);
80
+ report(path, `${address} isn't a note address. ${ADDRESS_FORMS}`);
81
81
  }
82
82
  }
83
83
  };
@@ -11,12 +11,12 @@ export async function jailWritePath(notesHome, path, options = {}) {
11
11
  realNotesHome = await realpath(notesHome);
12
12
  }
13
13
  catch {
14
- throw new Error(`write jail: cannot resolve notes home ${notesHome}`);
14
+ throw new Error(`Can't open the notes home ${notesHome}.`);
15
15
  }
16
16
  const target = resolve(realNotesHome, path);
17
17
  const targetParent = dirname(target);
18
18
  if (isOutside(realNotesHome, targetParent))
19
- throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
19
+ throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
20
20
  // write creates parent directories itself. Create only after the lexical check, then
21
21
  // canonicalize the parent so a symlink cannot lead the underlying tool out of home.
22
22
  // delete passes createParent:false: the parent must already exist for there to be anything to remove.
@@ -27,17 +27,17 @@ export async function jailWritePath(notesHome, path, options = {}) {
27
27
  realTargetParent = await realpath(targetParent);
28
28
  }
29
29
  catch {
30
- throw new Error(`write jail: cannot resolve target parent in notes home ${notesHome}`);
30
+ throw new Error(`Can't open the folder of ${path} in the notes home.`);
31
31
  }
32
32
  if (isOutside(realNotesHome, realTargetParent))
33
- throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
33
+ throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
34
34
  let targetStats;
35
35
  try {
36
36
  targetStats = await lstat(target);
37
37
  }
38
38
  catch (error) {
39
39
  if (error.code !== "ENOENT")
40
- throw new Error(`write jail: cannot inspect target in notes home ${notesHome}`);
40
+ throw new Error(`Can't check ${path} in the notes home.`);
41
41
  }
42
42
  if (targetStats?.isSymbolicLink()) {
43
43
  let realTarget;
@@ -45,13 +45,13 @@ export async function jailWritePath(notesHome, path, options = {}) {
45
45
  realTarget = await realpath(target);
46
46
  }
47
47
  catch {
48
- throw new Error(`write jail: cannot resolve target in notes home ${notesHome}`);
48
+ throw new Error(`Can't follow the link at ${path} in the notes home.`);
49
49
  }
50
50
  if (isOutside(realNotesHome, realTarget))
51
- throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
51
+ throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
52
52
  }
53
53
  if (targetStats && targetStats.nlink > 1)
54
- throw new Error(`write jail: ${path} has hard links and is not allowed in notes home ${notesHome}`);
54
+ throw new Error(`${path} has other hard links, which may reach outside the notes home; leave it alone.`);
55
55
  return target;
56
56
  }
57
57
  /** Physical deletion refuses live notes even before playbook policy is consulted. */
@@ -62,10 +62,10 @@ export async function deleteCrumpledNote(notesHome, path) {
62
62
  raw = await readFile(target, "utf8");
63
63
  }
64
64
  catch (error) {
65
- throw new Error(`delete: cannot read ${path} in notes home: ${error.message}`);
65
+ throw new Error(`Can't read ${path} in the notes home: ${error.message}`);
66
66
  }
67
67
  if (parseNote(raw).meta.crumpledAt === undefined)
68
- throw new Error(`delete: ${path} is not a crumpled note; only the wastebasket rule permits deletion`);
68
+ throw new Error(`${path} isn't crumpled; only crumpled notes can be deleted.`);
69
69
  await unlink(target);
70
70
  return { content: [{ type: "text", text: `deleted ${path}` }], details: undefined };
71
71
  }
@@ -180,7 +180,7 @@ export function unknownWindowId(projection, params) {
180
180
  if (typeof params.window_id !== "string")
181
181
  return undefined;
182
182
  const known = projection.windows.map((current) => current.windowId);
183
- return known.includes(params.window_id) ? undefined : { message: `unknown window_id "${params.window_id}"`, known };
183
+ return known.includes(params.window_id) ? undefined : { message: `No window "${params.window_id}" in this session`, known };
184
184
  }
185
185
  /**
186
186
  * Whether one event is inside the selection: its window, its seq bounds, and a half-open
@@ -1,7 +1,7 @@
1
1
  /** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
2
2
  import { Type } from "typebox";
3
3
  import { failure, success } from "../tools/result.js";
4
- import { earliestMatchOffsetChars, prefixFit } from "../tools/output.js";
4
+ import { earliestMatchOffsetChars, prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
5
5
  import { InvalidQueryError, searchQueries } from "../tools/schema.js";
6
6
  import { allItems, eventDocument, filteredItems, inSelection, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
7
7
  /** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
@@ -19,7 +19,7 @@ function timeBound(name, value) {
19
19
  if (value === undefined)
20
20
  return success(undefined);
21
21
  const at = isoUtcMs(value);
22
- return at === undefined ? failure("invalid_time", `${name} is not an ISO 8601 timestamp: "${value}"`) : success(at);
22
+ return at === undefined ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
23
23
  }
24
24
  /** Parse `since`/`until`; a malformed or inverted pair refuses here. */
25
25
  function resolveTimeBounds(params) {
@@ -30,7 +30,7 @@ function resolveTimeBounds(params) {
30
30
  if (!until.ok)
31
31
  return until;
32
32
  if (since.data !== undefined && until.data !== undefined && since.data >= until.data) {
33
- return failure("invalid_time", "since must be earlier than until");
33
+ return failure("invalid_time", "`since` must be earlier than `until`.");
34
34
  }
35
35
  return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
36
36
  }
@@ -45,8 +45,8 @@ export const HistoryNewerSchema = Type.Object({
45
45
  }, { additionalProperties: false });
46
46
  export const HistoryPageSchema = Type.Object({
47
47
  items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
48
- page_older: Type.Union([HistoryOlderSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
49
- page_newer: Type.Union([HistoryNewerSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
48
+ page_older: Type.Union([HistoryOlderSchema, Type.Null()]),
49
+ page_newer: Type.Union([HistoryNewerSchema, Type.Null()]),
50
50
  }, { additionalProperties: false });
51
51
  /** Shorten preview text first; omit an oversized tool name rather than invent a partial name. */
52
52
  function truncateHistoryItem(item, fits) {
@@ -195,7 +195,7 @@ export function selectPage(projection, params, fits, maxChars) {
195
195
  }
196
196
  const page = pageData(projection, scoped, allVisible, kept, maxChars, folds);
197
197
  if (!fits(page)) {
198
- return failure("page_too_large", `${page.items.length} history rows and their fold summary do not fit one response even at their smallest; narrow with before_seq/after_seq or since/until, or read one seq`);
198
+ return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows and their folded runs fill the ${TOOL_OUTPUT_LIMIT} a call can carry; narrow with \`before_seq\`/\`after_seq\` or \`since\`/\`until\`, pass \`roles\` to skip folding, or \`history_read\` one seq.`);
199
199
  }
200
200
  return success(page);
201
201
  }
@@ -5,7 +5,7 @@ export type NoteAddress = {
5
5
  path: string;
6
6
  who?: string;
7
7
  };
8
- export declare const ADDRESS_FORMS = "use <path> with no @ for this session, or @project/, @human/, @self/, or @model/ followed by a path";
8
+ export declare const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
9
9
  export declare function assertVirtualPath(value: unknown): string;
10
10
  /**
11
11
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never
@@ -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
  }