notesoup 0.42.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 (120) 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.js +1 -1
  4. package/dist/src/budget/parse.d.ts +14 -0
  5. package/dist/src/budget/parse.js +36 -0
  6. package/dist/src/budget/policy.js +2 -7
  7. package/dist/src/budget/text.d.ts +2 -0
  8. package/dist/src/budget/text.js +2 -0
  9. package/dist/src/claude/helper.js +1 -2
  10. package/dist/src/claude/thresholds.js +45 -66
  11. package/dist/src/dream/lock.js +6 -13
  12. package/dist/src/dream/report.js +5 -15
  13. package/dist/src/history/history.js +4 -2
  14. package/dist/src/history/query.js +10 -22
  15. package/dist/src/notes/address.d.ts +0 -1
  16. package/dist/src/notes/address.js +5 -17
  17. package/dist/src/notes/errors.d.ts +2 -0
  18. package/dist/src/notes/errors.js +5 -0
  19. package/dist/src/notes/frontmatter.js +16 -2
  20. package/dist/src/notes/identity.js +0 -3
  21. package/dist/src/notes/paths.d.ts +11 -1
  22. package/dist/src/notes/paths.js +28 -7
  23. package/dist/src/notes/store.d.ts +1 -0
  24. package/dist/src/notes/store.js +38 -37
  25. package/dist/src/pi/boot.js +1 -5
  26. package/dist/src/pi/budget.d.ts +3 -3
  27. package/dist/src/pi/budget.js +11 -11
  28. package/dist/src/pi/dream/cli.js +43 -11
  29. package/dist/src/pi/estimate.d.ts +1 -5
  30. package/dist/src/pi/estimate.js +4 -4
  31. package/dist/src/pi/history.js +1 -4
  32. package/dist/src/pi/notes/adapter.d.ts +1 -1
  33. package/dist/src/pi/notes/adapter.js +2 -2
  34. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  35. package/dist/src/pi/reset/artifacts.js +4 -4
  36. package/dist/src/pi/reset/committed.js +2 -2
  37. package/dist/src/pi/runtime.js +8 -5
  38. package/dist/src/pi/thresholds.js +5 -9
  39. package/dist/src/pi/tool-result.d.ts +1 -4
  40. package/dist/src/pi/tool-result.js +1 -1
  41. package/dist/src/pi/window.d.ts +5 -0
  42. package/dist/src/pi/window.js +7 -0
  43. package/dist/src/settings.d.ts +2 -0
  44. package/dist/src/settings.js +4 -3
  45. package/dist/src/tools/history.js +4 -7
  46. package/dist/src/tools/notes.d.ts +0 -4
  47. package/dist/src/tools/notes.js +6 -16
  48. package/dist/src/tools/output.d.ts +0 -3
  49. package/dist/src/tools/output.js +1 -9
  50. package/dist/src/tools/result.d.ts +1 -0
  51. package/dist/src/tools/result.js +14 -20
  52. package/dist/src/tools/schema.d.ts +0 -1
  53. package/dist/src/tools/schema.js +0 -1
  54. package/dist/test/agent-loop.test.js +1 -2
  55. package/dist/test/boot.integration.test.js +1 -1
  56. package/dist/test/claude-mod.test.js +221 -9
  57. package/dist/test/claude-validation.test.d.ts +1 -0
  58. package/dist/test/claude-validation.test.js +73 -0
  59. package/dist/test/dream-skill.test.js +2 -4
  60. package/dist/test/dream.test.js +14 -0
  61. package/dist/test/helpers/extension.js +1 -1
  62. package/dist/test/history.integration.test.js +2 -1
  63. package/dist/test/host-neutral.test.js +15 -0
  64. package/dist/test/notes-library.test.js +30 -1
  65. package/dist/test/notes.integration.test.js +7 -7
  66. package/dist/test/notes.test.js +24 -5
  67. package/dist/test/reset-lifecycle.test.js +1 -1
  68. package/docs/claude-code-mod.md +5 -3
  69. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  70. package/mods/notesoup/dist/claude/helper.js +147 -173
  71. package/mods/notesoup/hooks/register.ts +158 -67
  72. package/mods/notesoup/playbook.md +1 -1
  73. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  74. package/mods/notesoup/skills/memory/SKILL.md +61 -0
  75. package/package.json +5 -3
  76. package/playbook.md +1 -1
  77. package/skills/dream/SKILL.md +1 -1
  78. package/skills/memory/SKILL.md +1 -1
  79. package/src/boot/render.ts +11 -21
  80. package/src/boot/snapshot.ts +2 -7
  81. package/src/boot/text.ts +1 -1
  82. package/src/budget/parse.ts +39 -0
  83. package/src/budget/policy.ts +2 -6
  84. package/src/budget/text.ts +3 -0
  85. package/src/claude/helper.ts +2 -2
  86. package/src/claude/thresholds.ts +45 -62
  87. package/src/dream/lock.ts +3 -9
  88. package/src/dream/report.ts +5 -10
  89. package/src/history/history.ts +4 -2
  90. package/src/history/query.ts +10 -23
  91. package/src/notes/address.ts +4 -16
  92. package/src/notes/errors.ts +6 -0
  93. package/src/notes/frontmatter.ts +12 -2
  94. package/src/notes/identity.ts +0 -2
  95. package/src/notes/paths.ts +23 -5
  96. package/src/notes/store.ts +33 -36
  97. package/src/pi/boot.ts +1 -13
  98. package/src/pi/budget.ts +10 -11
  99. package/src/pi/dream/cli.ts +35 -10
  100. package/src/pi/estimate.ts +4 -4
  101. package/src/pi/history.ts +1 -5
  102. package/src/pi/notes/adapter.ts +2 -2
  103. package/src/pi/reset/artifacts.ts +4 -4
  104. package/src/pi/reset/committed.ts +2 -2
  105. package/src/pi/runtime.ts +7 -6
  106. package/src/pi/thresholds.ts +5 -11
  107. package/src/pi/tool-result.ts +1 -1
  108. package/src/pi/window.ts +8 -0
  109. package/src/settings.ts +4 -3
  110. package/src/tools/history.ts +4 -8
  111. package/src/tools/notes.ts +7 -20
  112. package/src/tools/output.ts +1 -12
  113. package/src/tools/result.ts +14 -19
  114. package/src/tools/schema.ts +0 -1
  115. package/dist/src/dream/playbook.d.ts +0 -1
  116. package/dist/src/dream/playbook.js +0 -2
  117. package/dist/src/pi/reset/text.d.ts +0 -4
  118. package/dist/src/pi/reset/text.js +0 -7
  119. package/src/dream/playbook.ts +0 -3
  120. package/src/pi/reset/text.ts +0 -9
@@ -1,6 +1,6 @@
1
1
  import { deriveThresholds } from "../budget/policy.js";
2
2
  import { SettingsManager } from "@earendil-works/pi-coding-agent";
3
- import { DEFAULT_RESERVE_TOKENS, DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
3
+ import { DEFAULT_RESERVE_TOKENS } from "../budget/constants.js";
4
4
  import { mergeNotesoupSettings } from "../settings.js";
5
5
  import { errorMessage } from "../error-message.js";
6
6
  function readThresholdSettingsFromManager(ctx, settingsManager) {
@@ -16,17 +16,13 @@ function readThresholdSettingsFromManager(ctx, settingsManager) {
16
16
  */
17
17
  export function readThresholdSettings(ctx, settingsManager) {
18
18
  try {
19
- if (settingsManager)
20
- return readThresholdSettingsFromManager(ctx, settingsManager);
21
- return readThresholdSettingsFromManager(ctx, SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() }));
19
+ const manager = settingsManager ?? SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() });
20
+ return readThresholdSettingsFromManager(ctx, manager);
22
21
  }
23
22
  catch (error) {
24
23
  return {
25
- thresholds: {
26
- reminder: DEFAULT_RESERVE_TOKENS + DEFAULT_REMINDER_MARGIN_TOKENS,
27
- reserve: DEFAULT_RESERVE_TOKENS,
28
- warning: DEFAULT_RESERVE_TOKENS + WARNING_RUNWAY_TOKENS,
29
- },
24
+ // The same derivation over Pi's default reserve, so the fallback cannot drift from it.
25
+ thresholds: deriveThresholds(DEFAULT_RESERVE_TOKENS, {}).thresholds,
30
26
  automatic: true,
31
27
  warnings: [`🥣 Couldn't read settings · using defaults (${errorMessage(error)})`],
32
28
  };
@@ -1,10 +1,7 @@
1
1
  /** Pi transport for host-neutral operations. */
2
2
  import { type ExtensionAPI, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
3
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
3
  import type { Static, TSchema } from "typebox";
5
- import { type Operation, type Outcome, type Renderer } from "../tools/result.js";
6
- /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
7
- export declare function piOperationResult<TData>(render: Renderer<TData>, outcome: Outcome<TData>): AgentToolResult<undefined>;
4
+ import { type Operation, type Outcome } from "../tools/result.js";
8
5
  export type ToolNamespace = {
9
6
  name: string;
10
7
  description: string;
@@ -2,7 +2,7 @@
2
2
  import { defineTool } from "@earendil-works/pi-coding-agent";
3
3
  import { wireResult } from "../tools/result.js";
4
4
  /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
5
- export function piOperationResult(render, outcome) {
5
+ function piOperationResult(render, outcome) {
6
6
  return {
7
7
  content: [{ type: "text", text: render(outcome) }],
8
8
  structuredContent: wireResult(outcome),
@@ -21,6 +21,11 @@ export declare function hasWindowMessage(ctx: SessionReader, customType: string)
21
21
  export declare function currentWindowId(ctx: SessionReader): string;
22
22
  /** The durable window active just before the marker: the last earlier marker, else the root window. */
23
23
  export declare function previousWindowId(ctx: SessionReader, markerId: string): string;
24
+ /**
25
+ * An entry that cannot appear between a reset marker and its boot/continuation without
26
+ * breaking the closed reset shape. Shared so confirmation and repair cannot drift apart.
27
+ */
28
+ export declare function isForeignResetTailEntry(entry: SessionEntry): boolean;
24
29
  /** Match a provider-facing boot message, optionally by window identity. */
25
30
  export declare function isWindowBoot(message: AgentMessage, windowId?: string): boolean;
26
31
  /** Match a persisted boot entry by raw identity, even when a later edit hides it from projection. */
@@ -64,6 +64,13 @@ function hasWindowId(details, windowId) {
64
64
  typeof details.windowId === "string" &&
65
65
  details.windowId === windowId;
66
66
  }
67
+ /**
68
+ * An entry that cannot appear between a reset marker and its boot/continuation without
69
+ * breaking the closed reset shape. Shared so confirmation and repair cannot drift apart.
70
+ */
71
+ export function isForeignResetTailEntry(entry) {
72
+ return isWindowMarker(entry) || entry.type === "message" || entry.type === "custom_message" || entry.type === "compaction" || entry.type === "branch_summary";
73
+ }
67
74
  /** Match a provider-facing boot message, optionally by window identity. */
68
75
  export function isWindowBoot(message, windowId) {
69
76
  return message.role === "custom" && message.customType === BOOT_TYPE && (windowId === undefined || hasWindowId(message.details, windowId));
@@ -13,5 +13,7 @@ export type NotesoupSettings = {
13
13
  warningRunwayTokens?: unknown;
14
14
  dreamer?: unknown;
15
15
  };
16
+ /** A plain settings object; arrays and null are not one. */
17
+ export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
16
18
  /** Merge the global and project "notesoup" objects per key; project wins, mirroring Pi's deep merge. */
17
19
  export declare function mergeNotesoupSettings(globalSettings: unknown, projectSettings: unknown): NotesoupSettings;
@@ -1,15 +1,16 @@
1
1
  export const NOTESOUP_SETTINGS_KEY = "notesoup";
2
2
  /** Nested under "notesoup": the default dreamer model pattern, overridden by CLI --dreamer. */
3
3
  export const NOTESOUP_DREAMER_KEY = "dreamer";
4
- function isSettingsObject(value) {
4
+ /** A plain settings object; arrays and null are not one. */
5
+ export function isPlainObject(value) {
5
6
  return typeof value === "object" && value !== null && !Array.isArray(value);
6
7
  }
7
8
  /** Read the raw "notesoup" object from one parsed settings scope. */
8
9
  function notesoupSettings(settings) {
9
- if (!isSettingsObject(settings))
10
+ if (!isPlainObject(settings))
10
11
  return {};
11
12
  const value = settings[NOTESOUP_SETTINGS_KEY];
12
- return isSettingsObject(value) ? value : {};
13
+ return isPlainObject(value) ? value : {};
13
14
  }
14
15
  /** Merge the global and project "notesoup" objects per key; project wins, mirroring Pi's deep merge. */
15
16
  export function mergeNotesoupSettings(globalSettings, projectSettings) {
@@ -1,6 +1,6 @@
1
1
  /** Host-neutral history operations: one bounded payload for text and structured results. */
2
2
  import { Type } from "typebox";
3
- import { HISTORY_PREVIEW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
3
+ import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
4
4
  import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema } from "./result.js";
5
5
  import { historyRoles, searchQuery } from "./schema.js";
6
6
  import { HistoryPageSchema, selectPage } from "../history/query.js";
@@ -48,9 +48,6 @@ function renderPageItem(item) {
48
48
  lines.push(item.content);
49
49
  return lines.join("\n");
50
50
  }
51
- function isFoldedRow(item) {
52
- return "folded" in item;
53
- }
54
51
  function renderFoldedRow(row) {
55
52
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
56
53
  const expand = `\n\t→ expand: {"after_seq":${row.first_seq - 1},"before_seq":${row.last_seq + 1},"from":"oldest","roles":["tool","context"]}`;
@@ -60,7 +57,7 @@ function renderPage(page) {
60
57
  // An empty selection has no anchors either, so it would otherwise render as nothing at all.
61
58
  if (page.items.length === 0)
62
59
  return "No events match these filters.";
63
- const body = page.items.map((item) => (isFoldedRow(item) ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
60
+ const body = page.items.map((item) => ("folded" in item ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
64
61
  const cursors = [
65
62
  page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
66
63
  page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
@@ -145,8 +142,8 @@ export const historyListParameters = Type.Object({
145
142
  until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
146
143
  from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
147
144
  window_id: Type.Optional(Type.String({ minLength: 1, description: `(optional) Only this context window. From \`history_windows\` or any event; \`${PREVIOUS_WINDOW}\` is the one before this.` })),
148
- limit: Type.Optional(Type.Integer({ description: "(optional, default 20) Max events per page; folded rows don't count." })),
149
- max_chars_per_item: Type.Optional(Type.Integer({ description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
145
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
146
+ max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
150
147
  }, { additionalProperties: false });
151
148
  export const historyList = {
152
149
  name: "history_list",
@@ -2,10 +2,6 @@ import type { NotesIdentity } from "../notes/identity.js";
2
2
  import { Type, type Static } from "typebox";
3
3
  import { type NoteChange } from "../notes/index.js";
4
4
  import { type Outcome } from "./result.js";
5
- /** One unrecognized entry, and the verbatim extras together, are bounded so `extra` cannot outgrow the read. */
6
- export declare const MAX_METADATA_ENTRY_BYTES = 1024;
7
- /** An extra value that cannot be carried is named in place, never silently dropped. */
8
- export declare const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
9
5
  export declare const NoteMetadataSchema: Type.TObject<{
10
6
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
11
7
  created_at: Type.TString;
@@ -14,10 +14,6 @@ const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "(opti
14
14
  const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
15
15
  const GLOB_PARAMETER = nullableString("(optional) Glob over full addresses.");
16
16
  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.";
17
- /** The one receipt field a caller cannot derive from the address itself. */
18
- function projectKeyField(scope, projectKey) {
19
- return scope === "project" ? { project_key: projectKey } : {};
20
- }
21
17
  /**
22
18
  * Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
23
19
  * Convert expected refusals; unexpected errors propagate unchanged.
@@ -32,20 +28,13 @@ function failureOf(error) {
32
28
  return failure("io_error", "notes operation failed");
33
29
  throw error;
34
30
  }
35
- function byRecent(a, b) {
36
- return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
37
- }
38
31
  /** Metadata keys this layer normalizes; everything else is exposed verbatim under `extra`. */
39
32
  const NORMALIZED_META_KEYS = new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
40
33
  /** One unrecognized entry, and the verbatim extras together, are bounded so `extra` cannot outgrow the read. */
41
- export const MAX_METADATA_ENTRY_BYTES = 1024;
34
+ const MAX_METADATA_ENTRY_BYTES = 1024;
42
35
  const MAX_METADATA_VERBATIM_BYTES = 2048;
43
36
  /** An extra value that cannot be carried is named in place, never silently dropped. */
44
- export const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
45
- /** Include the key: hand-written frontmatter can have arbitrarily long keys. */
46
- function extraEntryBytes(key, value) {
47
- return structuredBytes(key) + 1 + structuredBytes(value);
48
- }
37
+ const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
49
38
  export const NoteMetadataSchema = Type.Object({
50
39
  origin: Type.Union([...ORIGIN_VALUES]),
51
40
  created_at: Type.String(),
@@ -68,7 +57,8 @@ function noteMetadata(meta) {
68
57
  // A key too large to carry cannot be named at all; an oversized value is named in place.
69
58
  if (structuredBytes(key) > MAX_METADATA_ENTRY_BYTES)
70
59
  continue;
71
- const entryBytes = extraEntryBytes(key, value);
60
+ // The key counts too: hand-written frontmatter can have arbitrarily long keys.
61
+ const entryBytes = structuredBytes(key) + 1 + structuredBytes(value);
72
62
  if (entryBytes > MAX_METADATA_ENTRY_BYTES || verbatimBytes + entryBytes > MAX_METADATA_VERBATIM_BYTES) {
73
63
  put(key, TOO_LARGE_EXTRA_VALUE);
74
64
  continue;
@@ -171,7 +161,7 @@ function snapshot(rows, limit, status, renderData, shrink) {
171
161
  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.`);
172
162
  }
173
163
  function listedFile(row, identity) {
174
- return { address: row.address, ...projectKeyField(row.scope, identity.projectKey), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
164
+ 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 }) };
175
165
  }
176
166
  export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN }, { additionalProperties: false });
177
167
  function renderWriteData(data) {
@@ -347,7 +337,7 @@ export const notesSearch = {
347
337
  async execute(params, identity) {
348
338
  try {
349
339
  const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? undefined, crumpled: params.crumpled });
350
- const files = rows.sort(byRecent).map(row => ({
340
+ const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map(row => ({
351
341
  ...listedFile(row, identity),
352
342
  matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
353
343
  }));
@@ -1,13 +1,10 @@
1
1
  /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
2
- export { earliestMatchOffsetChars } from "../text-match.js";
3
2
  export declare const TOOL_OUTPUT_MAX_BYTES: number;
4
3
  /** The per-call limit as the model reads it in refusals. */
5
4
  export declare const TOOL_OUTPUT_LIMIT = "32 KB";
6
5
  export declare const DEFAULT_READ_WINDOW_CHARS = 12000;
7
6
  export declare const MAX_READ_WINDOW_CHARS = 50000;
8
7
  export declare const HISTORY_PREVIEW_CHARS = 1200;
9
- /** True when `text` fits the wire budget verbatim, for raw payloads with no JSON encoding. */
10
- export declare function withinTextBudget(text: string, budget?: number): boolean;
11
8
  /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
12
9
  export declare function prefixFit(text: string, fits: (content: string) => boolean): string;
13
10
  /**
@@ -1,18 +1,10 @@
1
1
  /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
2
- export { earliestMatchOffsetChars } from "../text-match.js";
3
2
  export const TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
4
3
  /** The per-call limit as the model reads it in refusals. */
5
4
  export const TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
6
5
  export const DEFAULT_READ_WINDOW_CHARS = 12000;
7
6
  export const MAX_READ_WINDOW_CHARS = 50000;
8
7
  export const HISTORY_PREVIEW_CHARS = 1200;
9
- function json(value) {
10
- return JSON.stringify(value);
11
- }
12
- /** True when `text` fits the wire budget verbatim, for raw payloads with no JSON encoding. */
13
- export function withinTextBudget(text, budget = TOOL_OUTPUT_MAX_BYTES) {
14
- return Buffer.byteLength(text, "utf8") <= budget;
15
- }
16
8
  /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
17
9
  export function prefixFit(text, fits) {
18
10
  if (fits(text))
@@ -37,5 +29,5 @@ export function prefixFit(text, fits) {
37
29
  * undefined unless the tool has metadata worth persisting.
38
30
  */
39
31
  export function output(value, details, terminate = false) {
40
- return { content: [{ type: "text", text: json(value) }], details, terminate };
32
+ return { content: [{ type: "text", text: JSON.stringify(value) }], details, terminate };
41
33
  }
@@ -17,6 +17,7 @@ export type Outcome<T> = {
17
17
  export declare function success<T>(data: T): Outcome<T>;
18
18
  /** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
19
19
  export declare const ERROR_MESSAGE_MAX_CHARS = 2000;
20
+ /** Bounded refusal: a runaway message is clipped with a marker instead of filling the wire. */
20
21
  export declare function failure(code: string, message: string): Outcome<never>;
21
22
  /** Public results have no success envelope. `error` is reserved for a refusal message. */
22
23
  export declare const WireErrorSchema: Type.TObject<{
@@ -1,6 +1,6 @@
1
1
  /** Internal outcomes, compact wire results, and bounded read windows. */
2
2
  import { Type } from "typebox";
3
- import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT, 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
  /** The one refusal shape: `code` is a stable internal identifier, `message` the bounded reading. */
5
5
  export const OperationErrorSchema = Type.Object({
6
6
  code: Type.String(),
@@ -11,12 +11,11 @@ export function success(data) {
11
11
  }
12
12
  /** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
13
13
  export const ERROR_MESSAGE_MAX_CHARS = 2000;
14
- function boundedMessage(message) {
15
- const chars = Array.from(message);
16
- return chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}…[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
17
- }
14
+ /** Bounded refusal: a runaway message is clipped with a marker instead of filling the wire. */
18
15
  export function failure(code, message) {
19
- return { ok: false, error: { code, message: boundedMessage(message) } };
16
+ const chars = Array.from(message);
17
+ 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]`;
18
+ return { ok: false, error: { code, message: bounded } };
20
19
  }
21
20
  /** Public results have no success envelope. `error` is reserved for a refusal message. */
22
21
  export const WireErrorSchema = Type.Object({ error: Type.String(), code: Type.String() }, { additionalProperties: false });
@@ -42,7 +41,7 @@ export function structuredBytes(value) {
42
41
  * measure covers everything the renderer puts around the payload, headers and footers included.
43
42
  */
44
43
  export function fitsResult(result, render) {
45
- return withinTextBudget(render(result)) && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
44
+ return Buffer.byteLength(render(result), "utf8") <= TOOL_OUTPUT_MAX_BYTES && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
46
45
  }
47
46
  /** `text` is verbatim, with no marker inserted, so windows concatenate back into the source. */
48
47
  export const TextWindowSchema = Type.Object({
@@ -71,7 +70,8 @@ export function readTextWindow(text, offset, limit, makeData, render) {
71
70
  const requested = offset ?? 0;
72
71
  const start = requested < 0 ? Math.max(0, chars.length + requested) : requested;
73
72
  const requestedChars = limit ?? DEFAULT_READ_WINDOW_CHARS;
74
- const range = Math.min(requestedChars, chars.length - start);
73
+ // A start past the end (a caller that skipped its own offset check) has nothing to deliver.
74
+ const range = Math.max(0, Math.min(requestedChars, chars.length - start));
75
75
  const window = (delivered) => {
76
76
  const end = start + delivered;
77
77
  return {
@@ -81,21 +81,15 @@ export function readTextWindow(text, offset, limit, makeData, render) {
81
81
  };
82
82
  };
83
83
  const fits = (delivered) => fitsResult(success(makeData(window(delivered))), render);
84
- // Test the full range first: its footer can disappear at the end of the document.
84
+ // Test the full range first: its footer can disappear at the end of the document, and an
85
+ // empty source is a complete window rather than a refusal.
85
86
  if (fits(range))
86
87
  return success(makeData(window(range)));
87
- let low = 0;
88
- let high = range;
89
- while (low < high) {
90
- const mid = Math.ceil((low + high) / 2);
91
- if (fits(mid))
92
- low = mid;
93
- else
94
- high = mid - 1;
95
- }
96
- if (low === 0)
88
+ // The kept count is monotone in the serialized size, so the shared prefix search owns the shrink.
89
+ const delivered = Array.from(prefixFit(window(range).text, (candidate) => fits(Array.from(candidate).length))).length;
90
+ if (delivered === 0)
97
91
  return failure("output_too_large", `Its header alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry; no room left for the text.`);
98
- return success(makeData(window(low)));
92
+ return success(makeData(window(delivered)));
99
93
  }
100
94
  /** The continuation line never becomes part of `window.text`, and a complete window has none. */
101
95
  export function renderTextWindow(window) {
@@ -1,6 +1,5 @@
1
1
  import { Type } from "typebox";
2
2
  export declare const nullableString: (description?: string) => Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
3
- export declare const positiveInteger: () => Type.TOptional<Type.TInteger>;
4
3
  export declare const historyRoles: () => Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>>>;
5
4
  /** Search query parameter: one literal, or several literals combined with OR. */
6
5
  export declare const searchQuery: (description?: string) => Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>;
@@ -1,7 +1,6 @@
1
1
  import { Type } from "typebox";
2
2
  import { HistoryRoleSchema } from "../history/history.js";
3
3
  export const nullableString = (description) => 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
  /** Search query parameter: one literal, or several literals combined with OR. */
7
6
  export const searchQuery = (description) => Type.Union([Type.String(), Type.Array(Type.String(), { minItems: 1 })], description === undefined ? {} : { description });
@@ -8,8 +8,7 @@ import { createAgentSession, createCodemodeExtension, DefaultResourceLoader, Mod
8
8
  import notesoup, { createNotesoup } from "../src/pi/extension.js";
9
9
  import { BOOT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../src/pi/entries.js";
10
10
  import { CONTEXT_WINDOW_OPEN_TAG } from "../src/boot/text.js";
11
- import { CONTINUATION, WARNING_CONTENT, WARNING_PROMPT } from "../src/pi/reset/text.js";
12
- import { GUIDANCE_OPEN_TAG } from "../src/budget/text.js";
11
+ import { CONTINUATION, GUIDANCE_OPEN_TAG, WARNING_CONTENT, WARNING_PROMPT } from "../src/budget/text.js";
13
12
  async function openFixture(options) {
14
13
  const dir = options.cwd ?? mkdtempSync(join(tmpdir(), "notesoup-agent-loop-"));
15
14
  const ownsDir = options.cwd === undefined;
@@ -6,7 +6,7 @@ import test from "node:test";
6
6
  import { historyFromSession } from "../src/pi/history.js";
7
7
  import { BOOT_TYPE, GUIDANCE_TYPE, RESET_MARKER_TYPE } from "../src/pi/entries.js";
8
8
  import { CONTEXT_WINDOW_OPEN_TAG, CONTEXT_WINDOW_PROTOCOL_OPEN_TAG } from "../src/boot/text.js";
9
- import { CONTINUATION } from "../src/pi/reset/text.js";
9
+ import { CONTINUATION } from "../src/budget/text.js";
10
10
  import { listNotes } from "./helpers/notes.js";
11
11
  import { CONTINUATION_TYPE, MANUAL_WIPE_TYPE } from "../src/pi/entries.js";
12
12
  import { appendText, call, commitTurnEndBoundary, context, makeExtension, manager, noticesOf, resultData, resultJson, resultRead, runContextHook, runContextWithSystemHook, runHandlers, runManualCompact, runCommand, sentOf, } from "./helpers/extension.js";