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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.41.0",
3
+ "version": "0.42.0",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
package/src/boot/text.ts CHANGED
@@ -6,6 +6,14 @@ 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`.";
16
+
9
17
  /**
10
18
  * Static protocol teaching adapted from Codex's token_budget.guidance_message to
11
19
  * notesoup's tool names. It lives once per window in the persisted boot block;
@@ -27,7 +35,7 @@ Notes are for what's true NOW. Not a diary of every dumb thing you did on the wa
27
35
  *flips a page* "First I tried this, then that broke, then—" Nobody reads that!
28
36
  Something's not true anymore? Cross it out! Write the right thing!
29
37
 
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.
38
+ \`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
39
 
32
40
  An address decides who the note belongs to — and how long it is meant to last. Ask that first; the rest follows.
33
41
 
@@ -53,6 +61,11 @@ export type BootToolNames = Readonly<{
53
61
  history: string;
54
62
  remaining: string;
55
63
  wipe: string;
64
+ /**
65
+ * Replaces the whole voluntary-wipe sentence (PROTOCOL_WIPE_SENTENCE) when the host has
66
+ * no model-facing reset tool. Absent means Pi's default sentence, byte for byte.
67
+ */
68
+ wipeSentence?: string;
56
69
  }>;
57
70
 
58
71
  export function renderProtocolBlock(tools: BootToolNames): string {
@@ -62,5 +75,10 @@ export function renderProtocolBlock(tools: BootToolNames): string {
62
75
  get_context_remaining: tools.remaining,
63
76
  clear_memory: tools.wipe,
64
77
  };
65
- return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]!);
78
+ // The sentence is replaced before name substitution, so a replacement may speak the host's
79
+ // own words (a command line, a tool name) instead of any `notes_*`-style token.
80
+ const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0
81
+ ? PROTOCOL_BLOCK.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence!)
82
+ : PROTOCOL_BLOCK;
83
+ return block.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]!);
66
84
  }
@@ -1,6 +1,23 @@
1
1
  export const GUIDANCE_OPEN_TAG = "<context_window_guidance>";
2
2
  export const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
3
3
 
4
+ /**
5
+ * The single reset message: the only reset prose persisted, carried by the continuation entry.
6
+ */
7
+ 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*";
8
+
9
+ /**
10
+ * The shared warning body: the one text both hosts show before a reset. Only the closing
11
+ * instruction differs — Pi can reset the model itself, Claude can only end the turn.
12
+ */
13
+ export const WARNING_BODY =
14
+ "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.";
15
+
16
+ export const WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, call \`clear_memory\` to reset now instead of being cut off mid-task.`;
17
+
18
+ /** Claude's variant: the mod resets after the turn, so the model only has to stop. */
19
+ export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, end your turn; the reset runs after it.`;
20
+
4
21
  /**
5
22
  * Codex-equivalent low-budget reminder. The measured remaining count is frozen into
6
23
  * the text at the crossing that fires it, so each persisted copy is a snapshot true
@@ -1,15 +1,17 @@
1
1
  import { realpathSync } from "node:fs";
2
2
  import { pathToFileURL } from "node:url";
3
3
  import type { Static, TSchema } from "typebox";
4
- import { Check } from "typebox/value";
4
+ import { Check, Errors } from "typebox/value";
5
5
  import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../tools/notes.js";
6
6
  import { loadNotesSnapshot } from "../boot/snapshot.js";
7
7
  import { renderBootBlock } from "../boot/render.js";
8
+ import { CLAUDE_WIPE_SENTENCE, type BootToolNames } from "../boot/text.js";
9
+ import { CLAUDE_WARNING_PROMPT, CONTINUATION } from "../budget/text.js";
10
+ import { resolveClaudeLimits } from "./thresholds.js";
8
11
  import { projectKey } from "../notes/paths.js";
9
12
  import { snapshotNotesIdentity, type NotesIdentity } from "../notes/identity.js";
10
13
  import type { NoteChange } from "../notes/store.js";
11
14
  import type { Operation, Outcome } from "../tools/result.js";
12
- import type { BootToolNames } from "../boot/text.js";
13
15
 
14
16
  const MAX_REQUEST_BYTES = 512 * 1024;
15
17
  const MAX_RESPONSE_BYTES = 1024 * 1024;
@@ -28,6 +30,15 @@ function identity(input: ClaudeIdentityInput): NotesIdentity {
28
30
  if (!input || typeof input !== "object" || typeof input.cwd !== "string") throw new Error("invalid identity");
29
31
  return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd), agent: input.agent, model: input.model });
30
32
  }
33
+ /** The first schema violation, named by parameter so the model can fix that one field. */
34
+ function paramProblem(schema: TSchema, params: unknown): string {
35
+ // A false subschema reports "schema is false"; its parent's additionalProperties error names the field instead.
36
+ const first = Errors(schema, params).find((error) => error.keyword !== "boolean");
37
+ if (!first) return "unrecognized shape";
38
+ const extra = first.keyword === "additionalProperties" ? `: ${(first.params as { additionalProperties: string[] }).additionalProperties.join(", ")}` : "";
39
+ const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
40
+ return `${field ? `${field} ` : ""}${first.message}${extra}`;
41
+ }
31
42
  function jsonValue(value: unknown): unknown { return JSON.parse(JSON.stringify(value)); }
32
43
 
33
44
  /** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
@@ -40,7 +51,7 @@ function boundOperation<TParams extends TSchema, TData, TRest extends readonly u
40
51
  parameters: operation.parameters,
41
52
  async call(params, id) {
42
53
  // Refuse before the operation can act: a rejected shape never reaches a write.
43
- if (!Check(operation.parameters, params)) throw new Error(`invalid ${operation.name} parameters`);
54
+ if (!Check(operation.parameters, params)) throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
44
55
  // The same business outcome and the same renderer as the Pi tool; only the envelope differs.
45
56
  const outcome = await operation.execute(params as Static<TParams>, id, ...rest);
46
57
  return { text: operation.render(outcome), outcome };
@@ -65,6 +76,12 @@ export async function dispatch(request: unknown): Promise<unknown> {
65
76
  if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
66
77
  const value = request as Record<string, unknown>;
67
78
  if (value.op === "schemas") return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: jsonValue(OPERATIONS[name].parameters) }));
79
+ // The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
80
+ // cannot drift apart. The hooks module caches one copy per session.
81
+ if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, continuation: CONTINUATION, wipeSentence: CLAUDE_WIPE_SENTENCE };
82
+ // Threshold derivation crosses the boundary as raw facts: everything the engine could
83
+ // read, unvalidated. resolveClaudeLimits guards every field and never throws.
84
+ if (value.op === "limits") return resolveClaudeLimits(value.facts);
68
85
  if (value.op === "tool") {
69
86
  if (typeof value.tool !== "string" || !(TOOL_NAMES as readonly string[]).includes(value.tool)) throw new Error("unknown tool");
70
87
  const id = identity(value.identity as ClaudeIdentityInput);
@@ -0,0 +1,170 @@
1
+ import { WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
2
+ import { mergeNotesoupSettings } from "../settings.js";
3
+
4
+ /**
5
+ * Claude's auto-compact point, derived the way Claude derives it — never a hardcoded percent.
6
+ *
7
+ * Claude compacts at `min(floor((W_eff - out) * pct/100), W_eff - out - 13000)`, where
8
+ * `W_eff` is the resolved auto-compact window, `out` is the output reserve (capped at 20000),
9
+ * and `pct` is CLAUDE_AUTOCOMPACT_PCT_OVERRIDE. This module mirrors those constants so
10
+ * notesoup can resolve the same point from settings and environment alone when the
11
+ * undocumented `usage({breakdown:true})` field is missing.
12
+ */
13
+ /** Claude's summary buffer between the output reserve and the auto-compact point. */
14
+ export const CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13_000;
15
+ /** Claude's cap on the reserved output tokens; the mod cannot read the model's own value. */
16
+ export const CLAUDE_OUTPUT_RESERVE_TOKENS = 20_000;
17
+ /** Default slack between Claude's auto-compact point and notesoup's notes-only reset. */
18
+ export const DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8_192;
19
+ /**
20
+ * The percent fallback assumes the classic 200K model window: it is reached only when
21
+ * `usage()` reports no window and no breakdown, and it reproduces the token maths below
22
+ * on that window (about 83.5% / 79.4% / 71.2%).
23
+ */
24
+ const ASSUMED_WINDOW_TOKENS = 200_000;
25
+
26
+ export type ClaudeLimitSource = "auto-compact" | "window" | "percent";
27
+ export type ClaudeLimits = {
28
+ /** Which field produced the point: Claude's own threshold, a computed window, or the percent fallback. */
29
+ readonly source: ClaudeLimitSource;
30
+ /** False when automatic compaction is off, so the point sits at the hard window instead. */
31
+ readonly autoCompact: boolean;
32
+ /** Which measured field the points are expressed in. */
33
+ readonly unit: "tokens" | "percent";
34
+ /** Claude's effective auto-compact point. */
35
+ readonly native: number;
36
+ /** Where notesoup resets: native minus the reset margin. */
37
+ readonly reset: number;
38
+ /** Where the one warning per window fires: reset minus the warning runway. */
39
+ readonly warn: number;
40
+ readonly resetMargin: number;
41
+ readonly warningRunway: number;
42
+ };
43
+
44
+ function isObject(value: unknown): value is Record<string, unknown> {
45
+ return typeof value === "object" && value !== null && !Array.isArray(value);
46
+ }
47
+ /** Numbers may arrive typed or as environment strings; anything else is unknown. */
48
+ function numberOf(value: unknown): number | undefined {
49
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
50
+ if (typeof value === "string" && value.trim() !== "") {
51
+ const parsed = Number(value);
52
+ return Number.isFinite(parsed) ? parsed : undefined;
53
+ }
54
+ return undefined;
55
+ }
56
+ function positiveNumberOf(value: unknown): number | undefined {
57
+ const parsed = numberOf(value);
58
+ return parsed !== undefined && parsed > 0 ? parsed : undefined;
59
+ }
60
+ /** A margin is usable only as a positive integer, matching Pi's budget policy. */
61
+ function positiveIntegerOf(value: unknown): number | undefined {
62
+ const parsed = numberOf(value);
63
+ return parsed !== undefined && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
64
+ }
65
+ /** Claude accepts a percent override only in (0, 100]. */
66
+ function percentOf(value: unknown): number | undefined {
67
+ const parsed = numberOf(value);
68
+ return parsed !== undefined && parsed > 0 && parsed <= 100 ? parsed : undefined;
69
+ }
70
+ /** Presence-style flags (DISABLE_AUTO_COMPACT): any value but an explicit no counts as on. */
71
+ function flagOn(value: unknown): boolean {
72
+ if (typeof value !== "string") return false;
73
+ const text = value.trim().toLowerCase();
74
+ return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off";
75
+ }
76
+ function settingFlag(settings: unknown, key: string): boolean | undefined {
77
+ if (!isObject(settings)) return undefined;
78
+ const value = settings[key];
79
+ return typeof value === "boolean" ? value : undefined;
80
+ }
81
+
82
+ /**
83
+ * The configured auto-compact window, smallest first: CLAUDE_CODE_AUTO_COMPACT_WINDOW,
84
+ * modelSettings.<model>.autoCompactWindow, then the top-level autoCompactWindow. Taking the
85
+ * smallest present value keeps notesoup's reset ahead of whichever one Claude would use.
86
+ */
87
+ function configuredWindow(settings: unknown, env: Record<string, unknown>, model: unknown): number | undefined {
88
+ const windows: number[] = [];
89
+ const fromEnv = positiveNumberOf(env.autoCompactWindow);
90
+ if (fromEnv !== undefined) windows.push(fromEnv);
91
+ if (typeof model === "string" && model.length > 0 && isObject(settings)) {
92
+ const modelSettings = isObject(settings.modelSettings) ? settings.modelSettings : {};
93
+ const perModel = modelSettings[model];
94
+ if (isObject(perModel)) {
95
+ const value = positiveNumberOf(perModel.autoCompactWindow);
96
+ if (value !== undefined) windows.push(value);
97
+ }
98
+ }
99
+ if (isObject(settings)) {
100
+ const value = positiveNumberOf(settings.autoCompactWindow);
101
+ if (value !== undefined) windows.push(value);
102
+ }
103
+ return windows.length === 0 ? undefined : Math.min(...windows);
104
+ }
105
+
106
+ function tokenLimits(source: ClaudeLimitSource, autoCompact: boolean, native: number, resetMargin: number, warningRunway: number): ClaudeLimits {
107
+ const tokens = Math.max(0, Math.floor(native));
108
+ const reset = Math.max(0, tokens - resetMargin);
109
+ return {
110
+ source, autoCompact, unit: "tokens",
111
+ native: tokens, reset, warn: Math.max(0, reset - warningRunway), resetMargin, warningRunway,
112
+ };
113
+ }
114
+
115
+ /** The percent fallback: the same reserves expressed as points of ASSUMED_WINDOW_TOKENS. */
116
+ function percentLimits(autoCompact: boolean, pct: number | undefined, resetMargin: number, warningRunway: number): ClaudeLimits {
117
+ const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
118
+ const native = pct === undefined ? base : Math.min(pct, base);
119
+ const reset = Math.max(0, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
120
+ return {
121
+ source: "percent", autoCompact, unit: "percent",
122
+ native, reset, warn: Math.max(0, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
128
+ * so a missing or malformed one degrades to the next source and finally to the percent
129
+ * fallback; resolution never throws. `facts` is deliberately unknown: it crosses the mod
130
+ * helper boundary, where nothing is typed.
131
+ */
132
+ export function resolveClaudeLimits(facts: unknown): ClaudeLimits {
133
+ const root = isObject(facts) ? facts : {};
134
+ const usage = isObject(root.usage) ? root.usage : {};
135
+ const breakdown = isObject(root.breakdown) ? root.breakdown : {};
136
+ const env = isObject(root.env) ? root.env : {};
137
+ const settings = root.settings;
138
+
139
+ const margins = mergeNotesoupSettings(settings, undefined);
140
+ const resetMargin = positiveIntegerOf(margins.resetMarginTokens) ?? DEFAULT_CLAUDE_RESET_MARGIN_TOKENS;
141
+ const warningRunway = positiveIntegerOf(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
142
+
143
+ const autoCompact = settingFlag(settings, "autoCompactEnabled") !== false
144
+ && !flagOn(env.disableAutoCompact)
145
+ && breakdown.isAutoCompactEnabled !== false;
146
+ const pct = percentOf(env.pctOverride);
147
+
148
+ // (a) Claude's own point. It already includes the window, model settings and CLI flag; only
149
+ // the percent override is applied separately, on the window-after-output-reserve it is
150
+ // minted from (threshold + summary buffer).
151
+ const threshold = positiveNumberOf(breakdown.autoCompactThreshold);
152
+ if (autoCompact && threshold !== undefined) {
153
+ const native = pct === undefined ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
154
+ if (native > 0) return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
155
+ }
156
+
157
+ // (b) The same point computed from the reported window plus settings and environment.
158
+ const window = positiveNumberOf(usage.window);
159
+ if (window !== undefined) {
160
+ const configured = configuredWindow(settings, env, breakdown.model);
161
+ const effective = Math.min(configured ?? window, window);
162
+ const native = autoCompact
163
+ ? effective - CLAUDE_OUTPUT_RESERVE_TOKENS - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS
164
+ : effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
165
+ if (native > 0) return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
166
+ }
167
+
168
+ // (c) Nothing usable but percentages.
169
+ return percentLimits(autoCompact, pct, resetMargin, warningRunway);
170
+ }
@@ -54,7 +54,7 @@ export function doctor(home: string): string[] {
54
54
  : root;
55
55
  if (!targetHome) { report(path, `${address}: project context unavailable; use a resolvable reference`); continue; }
56
56
  if (!existsSync(join(targetHome, parsed.path))) report(path, `${address}: target missing; update or remove the reference`);
57
- } catch { report(path, `${address}: invalid address; ${ADDRESS_FORMS}`); }
57
+ } catch { report(path, `${address} isn't a note address. ${ADDRESS_FORMS}`); }
58
58
  }
59
59
  };
60
60
  const walk = (dir: string, root: string, project?: string) => {
package/src/dream/jail.ts CHANGED
@@ -12,11 +12,11 @@ export async function jailWritePath(notesHome: string, path: string, options: {
12
12
  try {
13
13
  realNotesHome = await realpath(notesHome);
14
14
  } catch {
15
- throw new Error(`write jail: cannot resolve notes home ${notesHome}`);
15
+ throw new Error(`Can't open the notes home ${notesHome}.`);
16
16
  }
17
17
  const target = resolve(realNotesHome, path);
18
18
  const targetParent = dirname(target);
19
- if (isOutside(realNotesHome, targetParent)) throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
19
+ if (isOutside(realNotesHome, targetParent)) 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.
@@ -25,25 +25,25 @@ export async function jailWritePath(notesHome: string, path: string, options: {
25
25
  try {
26
26
  realTargetParent = await realpath(targetParent);
27
27
  } catch {
28
- throw new Error(`write jail: cannot resolve target parent in notes home ${notesHome}`);
28
+ throw new Error(`Can't open the folder of ${path} in the notes home.`);
29
29
  }
30
- if (isOutside(realNotesHome, realTargetParent)) throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
30
+ if (isOutside(realNotesHome, realTargetParent)) throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
31
31
  let targetStats;
32
32
  try {
33
33
  targetStats = await lstat(target);
34
34
  } catch (error: any) {
35
- if (error.code !== "ENOENT") throw new Error(`write jail: cannot inspect target in notes home ${notesHome}`);
35
+ if (error.code !== "ENOENT") throw new Error(`Can't check ${path} in the notes home.`);
36
36
  }
37
37
  if (targetStats?.isSymbolicLink()) {
38
38
  let realTarget: string;
39
39
  try {
40
40
  realTarget = await realpath(target);
41
41
  } catch {
42
- throw new Error(`write jail: cannot resolve target in notes home ${notesHome}`);
42
+ throw new Error(`Can't follow the link at ${path} in the notes home.`);
43
43
  }
44
- if (isOutside(realNotesHome, realTarget)) throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
44
+ if (isOutside(realNotesHome, realTarget)) throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
45
45
  }
46
- if (targetStats && targetStats.nlink > 1) throw new Error(`write jail: ${path} has hard links and is not allowed in notes home ${notesHome}`);
46
+ if (targetStats && targetStats.nlink > 1) throw new Error(`${path} has other hard links, which may reach outside the notes home; leave it alone.`);
47
47
  return target;
48
48
  }
49
49
 
@@ -54,9 +54,9 @@ export async function deleteCrumpledNote(notesHome: string, path: string) {
54
54
  try {
55
55
  raw = await readFile(target, "utf8");
56
56
  } catch (error: any) {
57
- throw new Error(`delete: cannot read ${path} in notes home: ${error.message}`);
57
+ throw new Error(`Can't read ${path} in the notes home: ${error.message}`);
58
58
  }
59
- if (parseNote(raw).meta.crumpledAt === undefined) throw new Error(`delete: ${path} is not a crumpled note; only the wastebasket rule permits deletion`);
59
+ if (parseNote(raw).meta.crumpledAt === undefined) throw new Error(`${path} isn't crumpled; only crumpled notes can be deleted.`);
60
60
  await unlink(target);
61
61
  return { content: [{ type: "text" as const, text: `deleted ${path}` }], details: undefined };
62
62
  }
@@ -259,7 +259,7 @@ export function allItems(projection: HistoryProjection): HistoryEvent[] {
259
259
  export function unknownWindowId(projection: HistoryProjection, params: HistoryFilter): { message: string; known: string[] } | undefined {
260
260
  if (typeof params.window_id !== "string") return undefined;
261
261
  const known = projection.windows.map((current) => current.windowId);
262
- return known.includes(params.window_id) ? undefined : { message: `unknown window_id "${params.window_id}"`, known };
262
+ return known.includes(params.window_id) ? undefined : { message: `No window "${params.window_id}" in this session`, known };
263
263
  }
264
264
 
265
265
  /**
@@ -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, type Static } from "typebox";
3
3
  import { failure, success, type Outcome } 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, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
7
7
 
@@ -40,7 +40,7 @@ function isoUtcMs(value: string): number | undefined {
40
40
  function timeBound(name: "since" | "until", value: string | undefined): Outcome<number | undefined> {
41
41
  if (value === undefined) return success(undefined);
42
42
  const at = isoUtcMs(value);
43
- return at === undefined ? failure("invalid_time", `${name} is not an ISO 8601 timestamp: "${value}"`) : success(at);
43
+ return at === undefined ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
44
44
  }
45
45
 
46
46
  /** Parse `since`/`until`; a malformed or inverted pair refuses here. */
@@ -50,7 +50,7 @@ function resolveTimeBounds(params: HistorySelection): Outcome<{ sinceMs?: number
50
50
  const until = timeBound("until", params.until);
51
51
  if (!until.ok) return until;
52
52
  if (since.data !== undefined && until.data !== undefined && since.data >= until.data) {
53
- return failure("invalid_time", "since must be earlier than until");
53
+ return failure("invalid_time", "`since` must be earlier than `until`.");
54
54
  }
55
55
  return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
56
56
  }
@@ -67,8 +67,8 @@ export const HistoryNewerSchema = Type.Object({
67
67
 
68
68
  export const HistoryPageSchema = Type.Object({
69
69
  items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
70
- page_older: Type.Union([HistoryOlderSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
71
- page_newer: Type.Union([HistoryNewerSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
70
+ page_older: Type.Union([HistoryOlderSchema, Type.Null()]),
71
+ page_newer: Type.Union([HistoryNewerSchema, Type.Null()]),
72
72
  }, { additionalProperties: false });
73
73
 
74
74
  /** One whole page payload, before it becomes an outcome. */
@@ -216,7 +216,7 @@ export function selectPage(projection: HistoryProjection, params: HistorySelecti
216
216
  }
217
217
  const page = pageData(projection, scoped, allVisible, kept, maxChars, folds);
218
218
  if (!fits(page)) {
219
- 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`);
219
+ 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.`);
220
220
  }
221
221
  return success(page);
222
222
  }
@@ -4,7 +4,7 @@ import { SLUG_PATTERN, type Scope } from "./paths.js";
4
4
 
5
5
  export type NoteAddress = { scope: Scope; path: string; who?: string };
6
6
 
7
- export const ADDRESS_FORMS = "use <path> with no @ for this session, or @project/, @human/, @self/, or @model/ followed by a path";
7
+ export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
8
8
 
9
9
  /** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
10
10
  function shown(value: unknown): string {
@@ -13,10 +13,10 @@ function shown(value: unknown): string {
13
13
  }
14
14
 
15
15
  export function assertVirtualPath(value: unknown): string {
16
- if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", `invalid address ${shown(value)}: path must be a non-empty string`);
17
- if (value.includes("\0") || value.includes("\\") || value.startsWith("/")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject backslashes, leading "/", and NUL`);
16
+ if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", "The address is empty; give the note a path.");
17
+ 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.`);
18
18
  const parts = value.split("/");
19
- if (parts.some((part) => part.length === 0 || part === "." || part === "..")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject "..", ".", and empty segments`);
19
+ 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.`);
20
20
  return value;
21
21
  }
22
22
 
@@ -49,8 +49,8 @@ export function globToRegExp(pattern: string): RegExp {
49
49
  /** Glob patterns are not virtual paths (`*` is legal), so they get their own guard. */
50
50
  export function assertGlobPattern(value: unknown): string | undefined {
51
51
  if (value === undefined || value === null || value === "") return undefined;
52
- if (typeof value !== "string") throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns must be strings`);
53
- if (value.includes("\0") || value.includes("\\")) throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns reject NUL and backslashes`);
52
+ if (typeof value !== "string") throw new NoteError("invalid_pattern", `glob ${shown(value)} must be a string.`);
53
+ if (value.includes("\0") || value.includes("\\")) 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: unknown): string | undefined {
59
59
  * are relative; explicit agents/models addresses always name a canonical slug.
60
60
  */
61
61
  export function assertAddress(value: unknown): NoteAddress {
62
- if (typeof value !== "string") throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
62
+ if (typeof value !== "string") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
63
63
  let scope: Scope = "session";
64
64
  let path = value;
65
65
  let who: string | undefined;
@@ -76,16 +76,16 @@ export function assertAddress(value: unknown): NoteAddress {
76
76
  else if (head === "agents" || head === "models") {
77
77
  const nameEnd = tail.indexOf("/");
78
78
  who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
79
- if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
79
+ if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
80
80
  scope = head === "agents" ? "agent" : "model";
81
81
  path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
82
82
  } else {
83
- throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
83
+ throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
84
84
  }
85
- if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
86
- if (path === "" && who === undefined) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
85
+ if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
86
+ if (path === "" && who === undefined) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
87
87
  }
88
- if (path.includes("@")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
88
+ if (path.includes("@")) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
89
89
  assertVirtualPath(path);
90
90
  return { scope, path, who };
91
91
  }
@@ -228,12 +228,17 @@ async function atomicWrite(path: string, content: string): Promise<void> {
228
228
  /** The byte cap is a write-time boundary rule, never a path-jail rule. */
229
229
  function assertWritablePath(vpath: string): void {
230
230
  const bytes = Buffer.byteLength(vpath, "utf8");
231
- if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `note path exceeds ${MAX_NOTE_PATH_BYTES} UTF-8 bytes (got ${bytes})`);
231
+ if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `Path too long: ${bytes} bytes; the limit is ${MAX_NOTE_PATH_BYTES}.`);
232
+ }
233
+
234
+ /** Rounded up, so a note just over the limit never reads as exactly at it. */
235
+ function megabytes(bytes: number): string {
236
+ return `${Math.ceil(bytes / 10_000) / 100} MB`;
232
237
  }
233
238
 
234
239
  function assertSerializedSize(content: string): void {
235
240
  const bytes = Buffer.byteLength(content, "utf8");
236
- if (bytes > MAX_NOTE_BYTES) throw new NoteError("too_large", `note exceeds ${MAX_NOTE_BYTES} UTF-8 bytes (serialized ${bytes})`);
241
+ 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.`);
237
242
  }
238
243
 
239
244
  /** Frontmatter block only (the body separator stripped), for metadata-only change inputs. */
@@ -247,7 +252,7 @@ function assertWritableHome(scope: Scope, who: string | undefined, identity: Not
247
252
  const current = scope === "agent" ? identity.agent : identity.model;
248
253
  if (who === current) return;
249
254
  const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
250
- throw new NoteError("invalid_scope", `${home} is not your home: writable homes are this session, @project/, @human/, @self/, and the current @model/ home`);
255
+ throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
251
256
  }
252
257
 
253
258
  /** Normalize parsed metadata exactly as a read does, including its access mutation. */
@@ -319,12 +324,12 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
319
324
  const scope = destination.scope;
320
325
  assertWritableHome(scope, destination.who, identity);
321
326
  if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined) {
322
- throw new NoteError("nothing_to_do", "nothing to do: provide edits or at least one of origin, crumpled");
327
+ throw new NoteError("nothing_to_do", "Nothing to change: pass edits, origin, crumpled, or rename_to.");
323
328
  }
324
329
  const path = physicalPath(scope, destination.path, identity, destination.who);
325
330
  return withPathQueue(path, async () => {
326
331
  const raw = await readFileIfExists(path);
327
- if (raw === undefined) throw new NoteError("not_found", "note not found");
332
+ if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
328
333
  const { meta, body } = parseNote(raw);
329
334
  meta.scope = scope;
330
335
  const beforeMeta: NoteMeta = { ...meta };
@@ -333,12 +338,12 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
333
338
  operations.forEach((operation, index) => {
334
339
  const oldText = operation?.oldText;
335
340
  const newText = operation?.newText;
336
- if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("no_match", `edit ${index}: oldText must be a non-empty string`, { editIndex: index });
337
- if (typeof newText !== "string") throw new NoteError("no_match", `edit ${index}: newText must be a string`, { editIndex: index });
341
+ if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("no_match", `edits[${index}].oldText is empty.`, { editIndex: index });
342
+ if (typeof newText !== "string") throw new NoteError("no_match", `edits[${index}].newText must be a string.`, { editIndex: index });
338
343
  const lines = matchLineNumbers(next, oldText);
339
- if (lines.length === 0) throw new NoteError("no_match", `edit ${index}: oldText does not occur in the note body`, { editIndex: index });
344
+ 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 });
340
345
  if (lines.length > 1 && !stableOptions.replaceAll) {
341
- 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 });
346
+ 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 });
342
347
  }
343
348
  if (oldText !== newText) applied++;
344
349
  // Positional splicing preserves user replacement text byte-for-byte.
@@ -384,14 +389,14 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
384
389
  assertWritableHome(toScope, to.who, identity);
385
390
  const fromPath = physicalPath(fromScope, from.path, identity, from.who);
386
391
  const toPath = physicalPath(toScope, to.path, identity, to.who);
387
- if (resolve(fromPath) === resolve(toPath)) throw new NoteError("nothing_to_do", "rename_to resolves to the same note");
392
+ if (resolve(fromPath) === resolve(toPath)) throw new NoteError("nothing_to_do", "rename_to points at the note itself.");
388
393
  const [first, second] = [fromPath, toPath].sort();
389
394
  return withPathQueue(first!, () => withPathQueue(second!, async () => {
390
395
  const raw = await readFileIfExists(fromPath);
391
- if (raw === undefined) throw new NoteError("not_found", "note not found");
396
+ if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, fromAddress).address}.`);
392
397
  const targetRaw = await readFileIfExists(toPath);
393
398
  if (targetRaw !== undefined && parseNote(targetRaw).meta.crumpledAt === undefined) {
394
- throw new NoteError("already_exists", "rename_to target is a live note; crumple it first or pick another address");
399
+ throw new NoteError("already_exists", `${noteIdentity(identity, toAddress).address} already holds a note; crumple it first or pick another address.`);
395
400
  }
396
401
  const { meta, body } = parseNote(raw);
397
402
  meta.scope = toScope;
@@ -1,10 +1,9 @@
1
- import { GUIDANCE_OPEN_TAG, GUIDANCE_CLOSE_TAG } from "../../budget/text.js";
2
-
3
- /** The single reset message: the only reset prose persisted, carried by the continuation entry. */
4
- 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*";
5
-
6
- export const WARNING_PROMPT =
7
- "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.";
1
+ import { CLAUDE_WARNING_PROMPT, CONTINUATION, GUIDANCE_CLOSE_TAG, GUIDANCE_OPEN_TAG, WARNING_BODY, WARNING_PROMPT } from "../../budget/text.js";
8
2
 
9
3
  /** Shared hidden checkpoint text for manual and budget-triggered requests. */
10
4
  export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${GUIDANCE_CLOSE_TAG}`;
5
+
6
+ // The reset prose lives beside the guidance text in the host-neutral budget domain, so the
7
+ // Claude mod can show the same words without depending on any Pi module. Re-exported here
8
+ // for the Pi-side importers that already reach for this module.
9
+ export { CLAUDE_WARNING_PROMPT, CONTINUATION, WARNING_BODY, WARNING_PROMPT };
package/src/pi/runtime.ts CHANGED
@@ -176,7 +176,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
176
176
  description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive.",
177
177
  parameters: Type.Object({}, { additionalProperties: false }),
178
178
  async execute(_id, _params, _signal, _update, ctx) {
179
- if (!enabled) return output({ error: "notesoup is off (/notesoup on to enable)" });
179
+ if (!enabled) return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
180
180
  return output({ status: resets.request(currentWindowId(ctx)) }, undefined, true);
181
181
  },
182
182
  }));
@@ -16,8 +16,8 @@ export function piOperationResult<TData>(render: Renderer<TData>, outcome: Outco
16
16
  }
17
17
 
18
18
  export type ToolNamespace = { name: string; description: string };
19
- export const NOTES_NAMESPACE: ToolNamespace = { name: "notes", description: "Notes you choose to keep across context windows. See /skill:memory." };
20
- export const HISTORY_NAMESPACE: ToolNamespace = { name: "history", description: "What happened in this session, read-only. See /skill:memory." };
19
+ export const NOTES_NAMESPACE: ToolNamespace = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
20
+ export const HISTORY_NAMESPACE: ToolNamespace = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
21
21
 
22
22
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
23
23
  export function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(