notesoup 0.41.0 → 0.43.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 (127) hide show
  1. package/dist/src/boot/render.js +11 -20
  2. package/dist/src/boot/snapshot.js +1 -6
  3. package/dist/src/boot/text.d.ts +12 -0
  4. package/dist/src/boot/text.js +15 -3
  5. package/dist/src/budget/parse.d.ts +14 -0
  6. package/dist/src/budget/parse.js +36 -0
  7. package/dist/src/budget/policy.js +2 -7
  8. package/dist/src/budget/text.d.ts +14 -0
  9. package/dist/src/budget/text.js +14 -0
  10. package/dist/src/claude/helper.js +24 -4
  11. package/dist/src/claude/thresholds.d.ts +39 -0
  12. package/dist/src/claude/thresholds.js +128 -0
  13. package/dist/src/dream/doctor.js +1 -1
  14. package/dist/src/dream/jail.js +10 -10
  15. package/dist/src/dream/lock.js +6 -13
  16. package/dist/src/dream/report.js +5 -15
  17. package/dist/src/history/history.js +5 -3
  18. package/dist/src/history/query.js +14 -26
  19. package/dist/src/notes/address.d.ts +1 -2
  20. package/dist/src/notes/address.js +14 -26
  21. package/dist/src/notes/errors.d.ts +2 -0
  22. package/dist/src/notes/errors.js +5 -0
  23. package/dist/src/notes/frontmatter.js +16 -2
  24. package/dist/src/notes/identity.js +0 -3
  25. package/dist/src/notes/paths.d.ts +11 -1
  26. package/dist/src/notes/paths.js +28 -7
  27. package/dist/src/notes/store.d.ts +1 -0
  28. package/dist/src/notes/store.js +54 -49
  29. package/dist/src/pi/boot.js +1 -5
  30. package/dist/src/pi/budget.d.ts +3 -3
  31. package/dist/src/pi/budget.js +11 -11
  32. package/dist/src/pi/dream/cli.js +43 -11
  33. package/dist/src/pi/estimate.d.ts +1 -5
  34. package/dist/src/pi/estimate.js +4 -4
  35. package/dist/src/pi/history.js +1 -4
  36. package/dist/src/pi/notes/adapter.d.ts +1 -1
  37. package/dist/src/pi/notes/adapter.js +2 -2
  38. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  39. package/dist/src/pi/reset/artifacts.js +4 -4
  40. package/dist/src/pi/reset/committed.js +2 -2
  41. package/dist/src/pi/runtime.js +9 -6
  42. package/dist/src/pi/thresholds.js +5 -9
  43. package/dist/src/pi/tool-result.d.ts +1 -4
  44. package/dist/src/pi/tool-result.js +3 -3
  45. package/dist/src/pi/window.d.ts +5 -0
  46. package/dist/src/pi/window.js +7 -0
  47. package/dist/src/settings.d.ts +10 -0
  48. package/dist/src/settings.js +10 -4
  49. package/dist/src/tools/history.js +15 -18
  50. package/dist/src/tools/notes.d.ts +3 -7
  51. package/dist/src/tools/notes.js +18 -27
  52. package/dist/src/tools/output.d.ts +2 -3
  53. package/dist/src/tools/output.js +3 -9
  54. package/dist/src/tools/result.d.ts +1 -0
  55. package/dist/src/tools/result.js +15 -21
  56. package/dist/src/tools/schema.d.ts +0 -1
  57. package/dist/src/tools/schema.js +3 -4
  58. package/dist/test/agent-loop.test.js +1 -2
  59. package/dist/test/boot.integration.test.js +1 -1
  60. package/dist/test/claude-mod.test.js +425 -23
  61. package/dist/test/claude-validation.test.d.ts +1 -0
  62. package/dist/test/claude-validation.test.js +73 -0
  63. package/dist/test/dream-skill.test.js +2 -4
  64. package/dist/test/dream.test.js +17 -3
  65. package/dist/test/helpers/extension.js +1 -1
  66. package/dist/test/history.integration.test.js +9 -9
  67. package/dist/test/host-neutral.test.js +16 -1
  68. package/dist/test/notes-library.test.js +31 -2
  69. package/dist/test/notes.integration.test.js +11 -11
  70. package/dist/test/notes.test.js +40 -21
  71. package/dist/test/reset-lifecycle.test.js +1 -1
  72. package/docs/claude-code-mod.md +13 -3
  73. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  74. package/mods/notesoup/dist/claude/helper.js +285 -152
  75. package/mods/notesoup/hooks/register.ts +308 -51
  76. package/mods/notesoup/playbook.md +1 -1
  77. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  78. package/mods/notesoup/skills/memory/SKILL.md +61 -0
  79. package/mods/pi-context/dist/claude/helper.js +9324 -0
  80. package/package.json +5 -3
  81. package/playbook.md +1 -1
  82. package/skills/dream/SKILL.md +1 -1
  83. package/skills/memory/SKILL.md +1 -1
  84. package/src/boot/render.ts +11 -21
  85. package/src/boot/snapshot.ts +2 -7
  86. package/src/boot/text.ts +21 -3
  87. package/src/budget/parse.ts +39 -0
  88. package/src/budget/policy.ts +2 -6
  89. package/src/budget/text.ts +20 -0
  90. package/src/claude/helper.ts +22 -5
  91. package/src/claude/thresholds.ts +153 -0
  92. package/src/dream/doctor.ts +1 -1
  93. package/src/dream/jail.ts +10 -10
  94. package/src/dream/lock.ts +3 -9
  95. package/src/dream/report.ts +5 -10
  96. package/src/history/history.ts +5 -3
  97. package/src/history/query.ts +14 -27
  98. package/src/notes/address.ts +13 -25
  99. package/src/notes/errors.ts +6 -0
  100. package/src/notes/frontmatter.ts +12 -2
  101. package/src/notes/identity.ts +0 -2
  102. package/src/notes/paths.ts +23 -5
  103. package/src/notes/store.ts +50 -48
  104. package/src/pi/boot.ts +1 -13
  105. package/src/pi/budget.ts +10 -11
  106. package/src/pi/dream/cli.ts +35 -10
  107. package/src/pi/estimate.ts +4 -4
  108. package/src/pi/history.ts +1 -5
  109. package/src/pi/notes/adapter.ts +2 -2
  110. package/src/pi/reset/artifacts.ts +4 -4
  111. package/src/pi/reset/committed.ts +2 -2
  112. package/src/pi/runtime.ts +8 -7
  113. package/src/pi/thresholds.ts +5 -11
  114. package/src/pi/tool-result.ts +3 -3
  115. package/src/pi/window.ts +8 -0
  116. package/src/settings.ts +22 -5
  117. package/src/tools/history.ts +15 -19
  118. package/src/tools/notes.ts +21 -32
  119. package/src/tools/output.ts +3 -12
  120. package/src/tools/result.ts +14 -19
  121. package/src/tools/schema.ts +3 -4
  122. package/dist/src/dream/playbook.d.ts +0 -1
  123. package/dist/src/dream/playbook.js +0 -2
  124. package/dist/src/pi/reset/text.d.ts +0 -5
  125. package/dist/src/pi/reset/text.js +0 -6
  126. package/src/dream/playbook.ts +0 -3
  127. package/src/pi/reset/text.ts +0 -10
@@ -2,8 +2,8 @@ import type { NotesIdentity } from "../notes/identity.js";
2
2
  import { Type, type Static } from "typebox";
3
3
  import { localIso } from "../notes/frontmatter.js";
4
4
  import { isFilesystemError } from "../notes/fs-error.js";
5
- import { createNotesStore, NoteError, noteIdentity, type NoteChange, type NoteMeta, type NoteQueryStatus, type NoteRow, type Scope } from "../notes/index.js";
6
- import { prefixFit } from "./output.js";
5
+ import { createNotesStore, NoteError, noteIdentity, type NoteChange, type NoteMeta, type NoteQueryStatus, type NoteRow } from "../notes/index.js";
6
+ import { prefixFit, TOOL_OUTPUT_LIMIT } from "./output.js";
7
7
  import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, structuredBytes, success, TextWindowRequestSchema, TextWindowSchema, type Outcome } from "./result.js";
8
8
  import { nullableString, InvalidQueryError, searchQueries, searchQuery } from "./schema.js";
9
9
 
@@ -17,11 +17,6 @@ const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, descriptio
17
17
  const GLOB_PARAMETER = nullableString("(optional) Glob over full addresses.");
18
18
  const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes. Not file paths: never pass them to file tools.";
19
19
 
20
- /** The one receipt field a caller cannot derive from the address itself. */
21
- function projectKeyField(scope: Scope, projectKey: string): { project_key?: string } {
22
- return scope === "project" ? { project_key: projectKey } : {};
23
- }
24
-
25
20
  /**
26
21
  * Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
27
22
  * Convert expected refusals; unexpected errors propagate unchanged.
@@ -34,22 +29,13 @@ function failureOf(error: unknown): Outcome<never> {
34
29
  throw error;
35
30
  }
36
31
 
37
- function byRecent<T extends { address: string; meta: { updatedAt: number } }>(a: T, b: T): number {
38
- return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
39
- }
40
-
41
32
  /** Metadata keys this layer normalizes; everything else is exposed verbatim under `extra`. */
42
33
  const NORMALIZED_META_KEYS = new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
43
34
  /** One unrecognized entry, and the verbatim extras together, are bounded so `extra` cannot outgrow the read. */
44
- export const MAX_METADATA_ENTRY_BYTES = 1024;
35
+ const MAX_METADATA_ENTRY_BYTES = 1024;
45
36
  const MAX_METADATA_VERBATIM_BYTES = 2048;
46
37
  /** An extra value that cannot be carried is named in place, never silently dropped. */
47
- export const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
48
-
49
- /** Include the key: hand-written frontmatter can have arbitrarily long keys. */
50
- function extraEntryBytes(key: string, value: unknown): number {
51
- return structuredBytes(key) + 1 + structuredBytes(value);
52
- }
38
+ const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
53
39
 
54
40
  export const NoteMetadataSchema = Type.Object({
55
41
  origin: Type.Union([...ORIGIN_VALUES]),
@@ -73,7 +59,8 @@ function noteMetadata(meta: NoteMeta): NoteMetadata {
73
59
  if (NORMALIZED_META_KEYS.has(key) || value === undefined) continue;
74
60
  // A key too large to carry cannot be named at all; an oversized value is named in place.
75
61
  if (structuredBytes(key) > MAX_METADATA_ENTRY_BYTES) continue;
76
- const entryBytes = extraEntryBytes(key, value);
62
+ // The key counts too: hand-written frontmatter can have arbitrarily long keys.
63
+ const entryBytes = structuredBytes(key) + 1 + structuredBytes(value);
77
64
  if (entryBytes > MAX_METADATA_ENTRY_BYTES || verbatimBytes + entryBytes > MAX_METADATA_VERBATIM_BYTES) {
78
65
  put(key, TOO_LARGE_EXTRA_VALUE);
79
66
  continue;
@@ -171,7 +158,7 @@ export type NotesSearchData = Static<typeof NotesSearchDataSchema>;
171
158
  type Snapshot<T> = Omit<NotesListData, "files"> & { files: T[] };
172
159
 
173
160
  /** Keep identities intact. Only search previews may shrink to make the first row fit. */
174
- function snapshot<T>(
161
+ function snapshot<T extends { address: string }>(
175
162
  rows: T[],
176
163
  limit: number | undefined,
177
164
  status: NoteQueryStatus,
@@ -191,15 +178,15 @@ function snapshot<T>(
191
178
  const reduced = shrink(item, fits);
192
179
  if (fits(reduced)) files.push(reduced);
193
180
  }
194
- if (files.length === 0) return failure("output_too_large", "The first matching note cannot fit in a response without losing its identity.");
181
+ 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.`);
195
182
  break;
196
183
  }
197
184
  const outcome = success(data(files));
198
- return fitsResult(outcome, render) ? outcome : failure("output_too_large", "The notes snapshot metadata exceeds the response budget.");
185
+ 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.`);
199
186
  }
200
187
 
201
188
  function listedFile(row: Pick<NoteRow, "address" | "scope" | "meta">, identity: NotesIdentity): NotesListData["files"][number] {
202
- return { address: row.address, ...projectKeyField(row.scope, identity.projectKey), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
189
+ return { address: row.address, ...(row.scope === "project" ? { project_key: identity.projectKey } : {}), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
203
190
  }
204
191
 
205
192
  export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN }, { additionalProperties: false });
@@ -210,7 +197,7 @@ function renderWriteData(data: NotesWriteData): string {
210
197
 
211
198
  export const notesWrite = {
212
199
  name: "notes_write", label: "Notes write",
213
- 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}`,
200
+ 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}`,
214
201
  parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
215
202
  async execute(params: Static<typeof notesWriteParameters>, identity: NotesIdentity): Promise<Outcome<NotesWriteData>> {
216
203
  try {
@@ -246,18 +233,20 @@ function renderUpdate(result: Outcome<NotesUpdateData>): string {
246
233
  /** A shortened diff still says so in the receipt's own text, on both surfaces. */
247
234
  export const DIFF_SHORTENED_MARKER = "[diff truncated; update applied]";
248
235
 
236
+ const RECEIPT_TOO_LONG = `Saved, but the receipt is too long to hand back (${TOOL_OUTPUT_LIMIT} per call). Check the note with \`notes_read\`.`;
237
+
249
238
  /** Bound a mutation receipt on both surfaces; a huge diff is cut to the longest fitting prefix and marked. */
250
239
  function boundedUpdate(data: NotesUpdateData): Outcome<NotesUpdateData> {
251
240
  if (fitsResult(success(data), renderUpdate)) return success(data);
252
- if (data.diff === "") return failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
241
+ if (data.diff === "") return failure("output_too_large", RECEIPT_TOO_LONG);
253
242
  const diff = prefixFit(data.diff, (candidate) => fitsResult(success({ ...data, diff: `${candidate}\n${DIFF_SHORTENED_MARKER}` }), renderUpdate));
254
243
  const result = success({ ...data, diff: `${diff}\n${DIFF_SHORTENED_MARKER}` });
255
- return fitsResult(result, renderUpdate) ? result : failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
244
+ return fitsResult(result, renderUpdate) ? result : failure("output_too_large", RECEIPT_TOO_LONG);
256
245
  }
257
246
 
258
247
  export const notesUpdate = {
259
248
  name: "notes_update", label: "Notes update",
260
- 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}`,
249
+ 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}`,
261
250
  parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
262
251
  async execute(params: Static<typeof notesUpdateParameters>, identity: NotesIdentity, renderDiff: (change: NoteChange) => string): Promise<Outcome<NotesUpdateData>> {
263
252
  try {
@@ -288,15 +277,15 @@ function renderReadData(data: NotesReadData): string {
288
277
 
289
278
  export const notesRead = {
290
279
  name: "notes_read", label: "Notes read",
291
- description: `Read a note's metadata and body, without frontmatter. ${ADDRESS_DESCRIPTION}`,
280
+ description: `Read a note. ${ADDRESS_DESCRIPTION}`,
292
281
  parameters: notesReadParameters, outputSchema: resultSchema(NotesReadDataSchema),
293
282
  async execute(params: Static<typeof notesReadParameters>, identity: NotesIdentity): Promise<Outcome<NotesReadData>> {
294
283
  try {
295
284
  const note = await createNotesStore(identity).read(params.address);
296
- if (!note) return failure("not_found", "note not found");
297
- const totalChars = Array.from(note.body).length;
298
- if (params.offset_chars !== undefined && 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)`);
299
285
  const resolved = noteIdentity(identity, params.address);
286
+ if (!note) return failure("not_found", `No note at ${resolved.address}.`);
287
+ const totalChars = Array.from(note.body).length;
288
+ if (params.offset_chars !== undefined && params.offset_chars > totalChars) return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
300
289
  const metadata = noteMetadata(note.meta);
301
290
  return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
302
291
  } catch (error) { return failureOf(error); }
@@ -370,7 +359,7 @@ export const notesSearch = {
370
359
  async execute(params: Static<typeof notesSearchParameters>, identity: NotesIdentity): Promise<Outcome<NotesSearchData>> {
371
360
  try {
372
361
  const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? undefined, crumpled: params.crumpled });
373
- const files: NotesSearchData["files"] = rows.sort(byRecent).map(row => ({
362
+ const files: NotesSearchData["files"] = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map(row => ({
374
363
  ...listedFile(row, identity),
375
364
  matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
376
365
  }));
@@ -1,20 +1,11 @@
1
1
  /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
2
- export { earliestMatchOffsetChars } from "../text-match.js";
3
-
4
2
  export const TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
3
+ /** The per-call limit as the model reads it in refusals. */
4
+ export const TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
5
5
  export const DEFAULT_READ_WINDOW_CHARS = 12000;
6
6
  export const MAX_READ_WINDOW_CHARS = 50000;
7
7
  export const HISTORY_PREVIEW_CHARS = 1200;
8
8
 
9
- function json(value: unknown): string {
10
- return JSON.stringify(value);
11
- }
12
-
13
- /** True when `text` fits the wire budget verbatim, for raw payloads with no JSON encoding. */
14
- export function withinTextBudget(text: string, budget = TOOL_OUTPUT_MAX_BYTES): boolean {
15
- return Buffer.byteLength(text, "utf8") <= budget;
16
- }
17
-
18
9
  /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
19
10
  export function prefixFit(text: string, fits: (content: string) => boolean): string {
20
11
  if (fits(text)) return text;
@@ -37,5 +28,5 @@ export function prefixFit(text: string, fits: (content: string) => boolean): str
37
28
  * undefined unless the tool has metadata worth persisting.
38
29
  */
39
30
  export function output(value: unknown, details?: unknown, terminate = false) {
40
- return { content: [{ type: "text" as const, text: json(value) }], details, terminate };
31
+ return { content: [{ type: "text" as const, text: JSON.stringify(value) }], details, terminate };
41
32
  }
@@ -1,6 +1,6 @@
1
1
  /** Internal outcomes, compact wire results, and bounded read windows. */
2
2
  import { Type, type Static, type TSchema } from "typebox";
3
- import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES, withinTextBudget } from "./output.js";
3
+ import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, prefixFit, TOOL_OUTPUT_LIMIT, TOOL_OUTPUT_MAX_BYTES } from "./output.js";
4
4
 
5
5
  /** The one refusal shape: `code` is a stable internal identifier, `message` the bounded reading. */
6
6
  export const OperationErrorSchema = Type.Object({
@@ -19,13 +19,11 @@ export function success<T>(data: T): Outcome<T> {
19
19
  /** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
20
20
  export const ERROR_MESSAGE_MAX_CHARS = 2000;
21
21
 
22
- function boundedMessage(message: string): string {
23
- const chars = Array.from(message);
24
- return chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}…[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
25
- }
26
-
22
+ /** Bounded refusal: a runaway message is clipped with a marker instead of filling the wire. */
27
23
  export function failure(code: string, message: string): Outcome<never> {
28
- return { ok: false, error: { code, message: boundedMessage(message) } };
24
+ const chars = Array.from(message);
25
+ const bounded = chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}…[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
26
+ return { ok: false, error: { code, message: bounded } };
29
27
  }
30
28
 
31
29
  /** Public results have no success envelope. `error` is reserved for a refusal message. */
@@ -58,7 +56,7 @@ export function structuredBytes(value: unknown): number {
58
56
  * measure covers everything the renderer puts around the payload, headers and footers included.
59
57
  */
60
58
  export function fitsResult<T>(result: Outcome<T>, render: (result: Outcome<T>) => string): boolean {
61
- return withinTextBudget(render(result)) && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
59
+ return Buffer.byteLength(render(result), "utf8") <= TOOL_OUTPUT_MAX_BYTES && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
62
60
  }
63
61
 
64
62
  /** `text` is verbatim, with no marker inserted, so windows concatenate back into the source. */
@@ -97,7 +95,8 @@ export function readTextWindow<T>(
97
95
  const requested = offset ?? 0;
98
96
  const start = requested < 0 ? Math.max(0, chars.length + requested) : requested;
99
97
  const requestedChars = limit ?? DEFAULT_READ_WINDOW_CHARS;
100
- const range = Math.min(requestedChars, chars.length - start);
98
+ // A start past the end (a caller that skipped its own offset check) has nothing to deliver.
99
+ const range = Math.max(0, Math.min(requestedChars, chars.length - start));
101
100
  const window = (delivered: number): TextWindow => {
102
101
  const end = start + delivered;
103
102
  return {
@@ -107,17 +106,13 @@ export function readTextWindow<T>(
107
106
  };
108
107
  };
109
108
  const fits = (delivered: number): boolean => fitsResult(success(makeData(window(delivered))), render);
110
- // Test the full range first: its footer can disappear at the end of the document.
109
+ // Test the full range first: its footer can disappear at the end of the document, and an
110
+ // empty source is a complete window rather than a refusal.
111
111
  if (fits(range)) return success(makeData(window(range)));
112
- let low = 0;
113
- let high = range;
114
- while (low < high) {
115
- const mid = Math.ceil((low + high) / 2);
116
- if (fits(mid)) low = mid;
117
- else high = mid - 1;
118
- }
119
- if (low === 0) return failure("output_too_large", "The response metadata leaves no room for a progressing read window.");
120
- return success(makeData(window(low)));
112
+ // The kept count is monotone in the serialized size, so the shared prefix search owns the shrink.
113
+ const delivered = Array.from(prefixFit(window(range).text, (candidate) => fits(Array.from(candidate).length))).length;
114
+ if (delivered === 0) return failure("output_too_large", `Its header alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry; no room left for the text.`);
115
+ return success(makeData(window(delivered)));
121
116
  }
122
117
 
123
118
  /** The continuation line never becomes part of `window.text`, and a complete window has none. */
@@ -1,7 +1,6 @@
1
1
  import { Type } from "typebox";
2
2
  import { HistoryRoleSchema } from "../history/history.js";
3
3
  export const nullableString = (description?: string) => Type.Optional(Type.Union([Type.String(), Type.Null()], description === undefined ? {} : { description }));
4
- export const positiveInteger = () => Type.Optional(Type.Integer({ minimum: 1 }));
5
4
  export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "(optional) Only these roles: user, assistant, tool, context. Omit to see the conversation with tool and context runs folded." }));
6
5
 
7
6
  /** Search query parameter: one literal, or several literals combined with OR. */
@@ -24,8 +23,8 @@ export class InvalidQueryError extends Error {
24
23
  */
25
24
  export function searchQueries(query: unknown): string[] {
26
25
  const candidates = typeof query === "string" ? [query] : query;
27
- if (!Array.isArray(candidates) || candidates.length === 0) throw new InvalidQueryError("query must be a string or a non-empty array of strings");
28
- if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("query array elements must be strings");
29
- if (candidates.some((candidate) => candidate === "")) throw new InvalidQueryError("query strings must be non-empty: an empty query matches everything");
26
+ if (!Array.isArray(candidates) || candidates.length === 0) throw new InvalidQueryError("`query` must be a string or a non-empty list of strings.");
27
+ if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
28
+ if (candidates.some((candidate) => candidate === "")) throw new InvalidQueryError("`query` can't be an empty string; it would match everything.");
30
29
  return candidates as string[];
31
30
  }
@@ -1 +0,0 @@
1
- export declare function loadPlaybook(path: string): string;
@@ -1,2 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
- export function loadPlaybook(path) { return readFileSync(path, "utf8"); }
@@ -1,5 +0,0 @@
1
- /** The single reset message: the only reset prose persisted, carried by the continuation entry. */
2
- export declare const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
3
- export declare const WARNING_PROMPT = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, call `clear_memory` to reset now instead of being cut off mid-task.";
4
- /** Shared hidden checkpoint text for manual and budget-triggered requests. */
5
- export declare const WARNING_CONTENT = "<context_window_guidance>\nThis context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, call `clear_memory` to reset now instead of being cut off mid-task.\n</context_window_guidance>";
@@ -1,6 +0,0 @@
1
- import { GUIDANCE_OPEN_TAG, GUIDANCE_CLOSE_TAG } from "../../budget/text.js";
2
- /** The single reset message: the only reset prose persisted, carried by the continuation entry. */
3
- export const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
4
- export const WARNING_PROMPT = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, call `clear_memory` to reset now instead of being cut off mid-task.";
5
- /** Shared hidden checkpoint text for manual and budget-triggered requests. */
6
- export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${GUIDANCE_CLOSE_TAG}`;
@@ -1,3 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
-
3
- export function loadPlaybook(path: string): string { return readFileSync(path, "utf8"); }
@@ -1,10 +0,0 @@
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.";
8
-
9
- /** Shared hidden checkpoint text for manual and budget-triggered requests. */
10
- export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${GUIDANCE_CLOSE_TAG}`;