notesoup 0.0.0-stage → 0.39.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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +91 -2
  3. package/dist/src/boot/render.d.ts +16 -0
  4. package/dist/src/boot/render.js +95 -0
  5. package/dist/src/boot/snapshot.d.ts +32 -0
  6. package/dist/src/boot/snapshot.js +36 -0
  7. package/dist/src/boot/text.d.ts +21 -0
  8. package/dist/src/boot/text.js +52 -0
  9. package/dist/src/budget/constants.d.ts +9 -0
  10. package/dist/src/budget/constants.js +9 -0
  11. package/dist/src/budget/policy.d.ts +19 -0
  12. package/dist/src/budget/policy.js +36 -0
  13. package/dist/src/budget/text.d.ts +8 -0
  14. package/dist/src/budget/text.js +10 -0
  15. package/dist/src/claude/helper.d.ts +15 -0
  16. package/dist/src/claude/helper.js +87 -0
  17. package/dist/src/dream/doctor.d.ts +2 -0
  18. package/dist/src/dream/doctor.js +160 -0
  19. package/dist/src/dream/gates.d.ts +10 -0
  20. package/dist/src/dream/gates.js +26 -0
  21. package/dist/src/dream/git.d.ts +21 -0
  22. package/dist/src/dream/git.js +71 -0
  23. package/dist/src/dream/jail.d.ts +11 -0
  24. package/dist/src/dream/jail.js +71 -0
  25. package/dist/src/dream/lock.d.ts +31 -0
  26. package/dist/src/dream/lock.js +99 -0
  27. package/dist/src/dream/playbook.d.ts +1 -0
  28. package/dist/src/dream/playbook.js +2 -0
  29. package/dist/src/dream/report.d.ts +7 -0
  30. package/dist/src/dream/report.js +43 -0
  31. package/dist/src/dream/result.d.ts +9 -0
  32. package/dist/src/dream/result.js +1 -0
  33. package/dist/src/dream/settings.d.ts +10 -0
  34. package/dist/src/dream/settings.js +14 -0
  35. package/dist/src/history/history.d.ts +151 -0
  36. package/dist/src/history/history.js +195 -0
  37. package/dist/src/history/query.d.ts +75 -0
  38. package/dist/src/history/query.js +143 -0
  39. package/dist/src/index.d.ts +1 -0
  40. package/dist/src/index.js +1 -0
  41. package/dist/src/notes/address.d.ts +31 -0
  42. package/dist/src/notes/address.js +123 -0
  43. package/dist/src/notes/constants.d.ts +3 -0
  44. package/dist/src/notes/constants.js +3 -0
  45. package/dist/src/notes/errors.d.ts +11 -0
  46. package/dist/src/notes/errors.js +13 -0
  47. package/dist/src/notes/frontmatter.d.ts +44 -0
  48. package/dist/src/notes/frontmatter.js +145 -0
  49. package/dist/src/notes/fs-error.d.ts +2 -0
  50. package/dist/src/notes/fs-error.js +5 -0
  51. package/dist/src/notes/identity.d.ts +10 -0
  52. package/dist/src/notes/identity.js +33 -0
  53. package/dist/src/notes/index.d.ts +5 -0
  54. package/dist/src/notes/index.js +3 -0
  55. package/dist/src/notes/paths.d.ts +21 -0
  56. package/dist/src/notes/paths.js +113 -0
  57. package/dist/src/notes/store.d.ts +104 -0
  58. package/dist/src/notes/store.js +478 -0
  59. package/dist/src/pi/boot.d.ts +24 -0
  60. package/dist/src/pi/boot.js +56 -0
  61. package/dist/src/pi/budget.d.ts +13 -0
  62. package/dist/src/pi/budget.js +178 -0
  63. package/dist/src/pi/dream/cli.d.ts +10 -0
  64. package/dist/src/pi/dream/cli.js +140 -0
  65. package/dist/src/pi/dream/runner.d.ts +27 -0
  66. package/dist/src/pi/dream/runner.js +90 -0
  67. package/dist/src/pi/dream/settings.d.ts +7 -0
  68. package/dist/src/pi/dream/settings.js +17 -0
  69. package/dist/src/pi/entries.d.ts +7 -0
  70. package/dist/src/pi/entries.js +7 -0
  71. package/dist/src/pi/estimate.d.ts +16 -0
  72. package/dist/src/pi/estimate.js +99 -0
  73. package/dist/src/pi/extension.d.ts +10 -0
  74. package/dist/src/pi/extension.js +24 -0
  75. package/dist/src/pi/history-tools.d.ts +3 -0
  76. package/dist/src/pi/history-tools.js +10 -0
  77. package/dist/src/pi/history.d.ts +4 -0
  78. package/dist/src/pi/history.js +150 -0
  79. package/dist/src/pi/notes/adapter.d.ts +10 -0
  80. package/dist/src/pi/notes/adapter.js +27 -0
  81. package/dist/src/pi/notes/tools.d.ts +3 -0
  82. package/dist/src/pi/notes/tools.js +15 -0
  83. package/dist/src/pi/reset/artifacts.d.ts +24 -0
  84. package/dist/src/pi/reset/artifacts.js +84 -0
  85. package/dist/src/pi/reset/committed.d.ts +7 -0
  86. package/dist/src/pi/reset/committed.js +28 -0
  87. package/dist/src/pi/reset/lifecycle.d.ts +101 -0
  88. package/dist/src/pi/reset/lifecycle.js +277 -0
  89. package/dist/src/pi/reset/text.d.ts +5 -0
  90. package/dist/src/pi/reset/text.js +6 -0
  91. package/dist/src/pi/runtime.d.ts +3 -0
  92. package/dist/src/pi/runtime.js +206 -0
  93. package/dist/src/pi/session-reader.d.ts +5 -0
  94. package/dist/src/pi/session-reader.js +1 -0
  95. package/dist/src/pi/thresholds.d.ts +17 -0
  96. package/dist/src/pi/thresholds.js +33 -0
  97. package/dist/src/pi/tool-names.d.ts +11 -0
  98. package/dist/src/pi/tool-names.js +11 -0
  99. package/dist/src/pi/tool-result.d.ts +15 -0
  100. package/dist/src/pi/tool-result.js +29 -0
  101. package/dist/src/pi/window.d.ts +41 -0
  102. package/dist/src/pi/window.js +127 -0
  103. package/dist/src/settings.d.ts +9 -0
  104. package/dist/src/settings.js +18 -0
  105. package/dist/src/text-match.d.ts +5 -0
  106. package/dist/src/text-match.js +16 -0
  107. package/dist/src/tools/history.d.ts +67 -0
  108. package/dist/src/tools/history.js +251 -0
  109. package/dist/src/tools/notes.d.ts +282 -0
  110. package/dist/src/tools/notes.js +378 -0
  111. package/dist/src/tools/output.d.ts +23 -0
  112. package/dist/src/tools/output.js +39 -0
  113. package/dist/src/tools/result.d.ts +79 -0
  114. package/dist/src/tools/result.js +130 -0
  115. package/dist/src/tools/schema.d.ts +18 -0
  116. package/dist/src/tools/schema.js +31 -0
  117. package/dist/test/agent-loop.test.d.ts +1 -0
  118. package/dist/test/agent-loop.test.js +1497 -0
  119. package/dist/test/boot.integration.test.d.ts +1 -0
  120. package/dist/test/boot.integration.test.js +294 -0
  121. package/dist/test/budget-settings.integration.test.d.ts +1 -0
  122. package/dist/test/budget-settings.integration.test.js +144 -0
  123. package/dist/test/claude-mod.test.d.ts +1 -0
  124. package/dist/test/claude-mod.test.js +404 -0
  125. package/dist/test/dependencies.test.d.ts +1 -0
  126. package/dist/test/dependencies.test.js +101 -0
  127. package/dist/test/doctor.test.d.ts +1 -0
  128. package/dist/test/doctor.test.js +37 -0
  129. package/dist/test/dream-skill.test.d.ts +1 -0
  130. package/dist/test/dream-skill.test.js +72 -0
  131. package/dist/test/dream.test.d.ts +1 -0
  132. package/dist/test/dream.test.js +136 -0
  133. package/dist/test/helpers/dependency-graph.d.ts +5 -0
  134. package/dist/test/helpers/dependency-graph.js +73 -0
  135. package/dist/test/helpers/extension-test-environment.d.ts +1 -0
  136. package/dist/test/helpers/extension-test-environment.js +9 -0
  137. package/dist/test/helpers/extension.d.ts +119 -0
  138. package/dist/test/helpers/extension.js +368 -0
  139. package/dist/test/helpers/notes.d.ts +6 -0
  140. package/dist/test/helpers/notes.js +13 -0
  141. package/dist/test/history.integration.test.d.ts +1 -0
  142. package/dist/test/history.integration.test.js +556 -0
  143. package/dist/test/host-neutral.test.d.ts +1 -0
  144. package/dist/test/host-neutral.test.js +300 -0
  145. package/dist/test/notes-library.test.d.ts +1 -0
  146. package/dist/test/notes-library.test.js +214 -0
  147. package/dist/test/notes.integration.test.d.ts +1 -0
  148. package/dist/test/notes.integration.test.js +497 -0
  149. package/dist/test/notes.test.d.ts +1 -0
  150. package/dist/test/notes.test.js +528 -0
  151. package/dist/test/reset-lifecycle.test.d.ts +1 -0
  152. package/dist/test/reset-lifecycle.test.js +605 -0
  153. package/docs/architecture.md +63 -0
  154. package/docs/claude-code-mod.md +9 -0
  155. package/docs/notes-library.md +74 -0
  156. package/docs/reset-lifecycle.md +75 -0
  157. package/docs/sdk-integration.md +39 -0
  158. package/docs/skills.md +30 -0
  159. package/docs/tool-results.md +88 -0
  160. package/mods/notesoup/.claude-plugin/plugin.json +8 -0
  161. package/mods/notesoup/dist/claude/helper.js +9324 -0
  162. package/mods/notesoup/hooks/hooks.json +4 -0
  163. package/mods/notesoup/hooks/register.ts +241 -0
  164. package/mods/notesoup/playbook.md +34 -0
  165. package/mods/notesoup/skills/dream/SKILL.md +12 -0
  166. package/mods/pi-context/dist/claude/helper.js +9324 -0
  167. package/package.json +89 -5
  168. package/playbook.md +34 -0
  169. package/skills/dream/SKILL.md +12 -0
  170. package/skills/memory/SKILL.md +59 -0
  171. package/src/boot/render.ts +115 -0
  172. package/src/boot/snapshot.ts +46 -0
  173. package/src/boot/text.ts +66 -0
  174. package/src/budget/constants.ts +9 -0
  175. package/src/budget/policy.ts +36 -0
  176. package/src/budget/text.ts +11 -0
  177. package/src/claude/helper.ts +94 -0
  178. package/src/dream/doctor.ts +117 -0
  179. package/src/dream/gates.ts +26 -0
  180. package/src/dream/git.ts +73 -0
  181. package/src/dream/jail.ts +62 -0
  182. package/src/dream/lock.ts +82 -0
  183. package/src/dream/playbook.ts +3 -0
  184. package/src/dream/report.ts +36 -0
  185. package/src/dream/result.ts +2 -0
  186. package/src/dream/settings.ts +16 -0
  187. package/src/history/history.ts +270 -0
  188. package/src/history/query.ts +147 -0
  189. package/src/index.ts +1 -0
  190. package/src/notes/address.ts +110 -0
  191. package/src/notes/constants.ts +3 -0
  192. package/src/notes/errors.ts +15 -0
  193. package/src/notes/frontmatter.ts +166 -0
  194. package/src/notes/fs-error.ts +5 -0
  195. package/src/notes/identity.ts +40 -0
  196. package/src/notes/index.ts +24 -0
  197. package/src/notes/paths.ts +109 -0
  198. package/src/notes/store.ts +497 -0
  199. package/src/pi/boot.ts +88 -0
  200. package/src/pi/budget.ts +178 -0
  201. package/src/pi/dream/cli.ts +92 -0
  202. package/src/pi/dream/runner.ts +91 -0
  203. package/src/pi/dream/settings.ts +17 -0
  204. package/src/pi/entries.ts +7 -0
  205. package/src/pi/estimate.ts +116 -0
  206. package/src/pi/extension.ts +27 -0
  207. package/src/pi/history-tools.ts +12 -0
  208. package/src/pi/history.ts +162 -0
  209. package/src/pi/notes/adapter.ts +33 -0
  210. package/src/pi/notes/tools.ts +18 -0
  211. package/src/pi/reset/artifacts.ts +100 -0
  212. package/src/pi/reset/committed.ts +26 -0
  213. package/src/pi/reset/lifecycle.ts +342 -0
  214. package/src/pi/reset/text.ts +10 -0
  215. package/src/pi/runtime.ts +200 -0
  216. package/src/pi/session-reader.ts +6 -0
  217. package/src/pi/thresholds.ts +50 -0
  218. package/src/pi/tool-names.ts +13 -0
  219. package/src/pi/tool-result.ts +41 -0
  220. package/src/pi/window.ts +133 -0
  221. package/src/settings.ts +22 -0
  222. package/src/text-match.ts +14 -0
  223. package/src/tools/history.ts +273 -0
  224. package/src/tools/notes.ts +394 -0
  225. package/src/tools/output.ts +41 -0
  226. package/src/tools/result.ts +169 -0
  227. package/src/tools/schema.ts +31 -0
@@ -0,0 +1,394 @@
1
+ import type { NotesIdentity } from "../notes/identity.js";
2
+ import { Type, type Static } from "typebox";
3
+ import { localIso } from "../notes/frontmatter.js";
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 { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, prefixFit } from "./output.js";
7
+ import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, structuredBytes, success, TextWindowSchema, type Outcome } from "./result.js";
8
+ import { nullableString, InvalidQueryError, searchQueries, searchQuery } from "./schema.js";
9
+
10
+ const ORIGIN_VALUES = [Type.Literal("user"), Type.Literal("self"), Type.Literal("external")] as const;
11
+ const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
12
+ description: "Content source: user, self (default), or external.",
13
+ }));
14
+ const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "true crumples (archives) the note: hidden from list/search, still readable by address; false restores it." }));
15
+ const WASTEBASKET_PARAMETER = Type.Optional(Type.Boolean({ description: "true lists only crumpled notes instead of live ones." }));
16
+ const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "Max files (default: as many as fit the output budget)." }));
17
+ const ADDRESS_DESCRIPTION = "Addresses: <path> with no @ for this session; @project/, @human/, @self/, @model/ for durable homes (see /skill:memory). Never pass them to filesystem tools.";
18
+
19
+ /** The one receipt field a caller cannot derive from the address itself. */
20
+ function projectKeyField(scope: Scope, projectKey: string): { project_key?: string } {
21
+ return scope === "project" ? { project_key: projectKey } : {};
22
+ }
23
+
24
+ const MAX_ERROR_LINE_FACTS = 20;
25
+
26
+ /**
27
+ * Typed refusal. Edit locations keep their precise line/edit facts in `details`.
28
+ * Convert expected refusals; unexpected errors propagate unchanged.
29
+ */
30
+ function failureOf(error: unknown): Outcome<never> {
31
+ if (error instanceof NoteError) {
32
+ const details: Record<string, unknown> = {};
33
+ let message = error.message;
34
+ if (error.lineNumbers) {
35
+ if (error.lineNumbers.length > MAX_ERROR_LINE_FACTS) {
36
+ details.line_numbers = error.lineNumbers.slice(0, MAX_ERROR_LINE_FACTS);
37
+ details.line_numbers_total = error.lineNumbers.length;
38
+ message = `${message} (this refusal names ${MAX_ERROR_LINE_FACTS} of ${error.lineNumbers.length} match lines; the note is unchanged)`;
39
+ } else {
40
+ details.line_numbers = error.lineNumbers;
41
+ }
42
+ }
43
+ if (error.editIndex !== undefined) details.edit_index = error.editIndex;
44
+ return failure(error.code, message, Object.keys(details).length > 0 ? details : undefined);
45
+ }
46
+ // Address, pattern, and query guards raise declared types; nothing else is converted.
47
+ if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
48
+ if (isFilesystemError(error)) return failure("io_error", "notes operation failed");
49
+ throw error;
50
+ }
51
+
52
+ function byRecent<T extends { address: string; meta: { updatedAt: number } }>(a: T, b: T): number {
53
+ return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
54
+ }
55
+
56
+ /** Metadata keys this layer normalizes; everything else is exposed verbatim under `extra`. */
57
+ const NORMALIZED_META_KEYS = new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
58
+ /** One unrecognized entry, and all of them together, are bounded; omissions are counted, never listed. */
59
+ export const MAX_METADATA_ENTRY_BYTES = 1024;
60
+ const MAX_METADATA_EXTRA_BYTES = 2048;
61
+
62
+ /** Include the key: hand-written frontmatter can have arbitrarily long keys. */
63
+ function extraEntryBytes(key: string, value: unknown): number {
64
+ return structuredBytes(key) + 1 + structuredBytes(value);
65
+ }
66
+
67
+ export const NoteMetadataSchema = Type.Object({
68
+ origin: Type.Union([...ORIGIN_VALUES]),
69
+ created_at: Type.String(),
70
+ updated_at: Type.String(),
71
+ crumpled_at: Type.Optional(Type.String()),
72
+ project: Type.Optional(Type.String()),
73
+ extra: Type.Record(Type.String(), Type.Unknown()),
74
+ /** Values left in the file but too large to show, summarized so the summary cannot grow. */
75
+ omitted_extra: Type.Optional(Type.Object({ keys: Type.Integer(), bytes: Type.Integer() })),
76
+ });
77
+ export type NoteMetadata = Static<typeof NoteMetadataSchema>;
78
+
79
+ /** Normalize known metadata and bound extras without partially serializing their values. */
80
+ function noteMetadata(meta: NoteMeta): NoteMetadata {
81
+ const extra: Record<string, unknown> = {};
82
+ let extraBytes = 0;
83
+ let omittedKeys = 0;
84
+ let omittedBytes = 0;
85
+ for (const [key, value] of Object.entries(meta)) {
86
+ if (NORMALIZED_META_KEYS.has(key) || value === undefined) continue;
87
+ const bytes = extraEntryBytes(key, value);
88
+ if (bytes > MAX_METADATA_ENTRY_BYTES || extraBytes + bytes > MAX_METADATA_EXTRA_BYTES) {
89
+ omittedKeys++;
90
+ omittedBytes += bytes;
91
+ continue;
92
+ }
93
+ extraBytes += bytes;
94
+ // defineProperty keeps a hand-written `__proto__` key as ordinary data.
95
+ Object.defineProperty(extra, key, { value, enumerable: true, writable: true, configurable: true });
96
+ }
97
+ return {
98
+ origin: meta.origin,
99
+ created_at: localIso(meta.createdAt),
100
+ updated_at: localIso(meta.updatedAt),
101
+ ...(typeof meta.crumpledAt === "string" ? { crumpled_at: meta.crumpledAt } : {}),
102
+ ...(typeof meta.project === "string" ? { project: meta.project } : {}),
103
+ extra,
104
+ ...(omittedKeys > 0 ? { omitted_extra: { keys: omittedKeys, bytes: omittedBytes } } : {}),
105
+ };
106
+ }
107
+
108
+ function renderMetadata(metadata: NoteMetadata): string {
109
+ const fields = [
110
+ `origin ${metadata.origin}`,
111
+ `created ${metadata.created_at}`,
112
+ `updated ${metadata.updated_at}`,
113
+ ...(metadata.crumpled_at === undefined ? [] : [`crumpled ${metadata.crumpled_at}`]),
114
+ ...(metadata.project === undefined ? [] : [`project ${metadata.project}`]),
115
+ ];
116
+ const extra = Object.keys(metadata.extra);
117
+ if (extra.length > 0) fields.push(`extra ${JSON.stringify(metadata.extra)}`);
118
+ if (metadata.omitted_extra !== undefined) fields.push(`${metadata.omitted_extra.keys} more metadata values (${metadata.omitted_extra.bytes} bytes) are in the note file but too large to show`);
119
+ return fields.join(" | ");
120
+ }
121
+
122
+ /** Address plus project key in one line; the project key never replaces the address. */
123
+ function renderIdentity(identity: { address: string; project_key?: string }): string {
124
+ return identity.project_key === undefined ? identity.address : `${identity.address} (project ${identity.project_key})`;
125
+ }
126
+
127
+ const ListedFileSchema = Type.Object({
128
+ address: Type.String(),
129
+ project_key: Type.Optional(Type.String()),
130
+ updated_at: Type.String(),
131
+ crumpled_at: Type.Optional(Type.String()),
132
+ });
133
+
134
+ const MatchSchema = Type.Object({
135
+ line: Type.Integer(),
136
+ text: Type.String(),
137
+ truncated: Type.Boolean(),
138
+ offset_chars: Type.Integer(),
139
+ });
140
+
141
+ const SearchedFileSchema = Type.Object({
142
+ ...ListedFileSchema.properties,
143
+ matches_total: Type.Integer(),
144
+ matches: Type.Array(MatchSchema),
145
+ });
146
+
147
+ const SnapshotSchema = {
148
+ more: Type.Integer(),
149
+ crumpled_excluded: Type.Integer(),
150
+ homes_unavailable: Type.Array(Type.String()),
151
+ };
152
+
153
+ export const NotesWriteDataSchema = Type.Object({
154
+ address: Type.String(),
155
+ project_key: Type.Optional(Type.String()),
156
+ outcome: Type.Union([Type.Literal("created"), Type.Literal("overwrote"), Type.Literal("uncrumpled")]),
157
+ });
158
+ export type NotesWriteData = Static<typeof NotesWriteDataSchema>;
159
+
160
+ export const NotesUpdateDataSchema = Type.Object({
161
+ address: Type.String(),
162
+ project_key: Type.Optional(Type.String()),
163
+ applied: Type.Integer(),
164
+ change_kind: Type.Union([Type.Literal("none"), Type.Literal("body"), Type.Literal("metadata"), Type.Literal("file")]),
165
+ diff: Type.String(),
166
+ diff_truncated: Type.Optional(Type.Literal(true)),
167
+ rename_from: Type.Optional(Type.String()),
168
+ replaced_crumpled_target: Type.Optional(Type.Boolean()),
169
+ });
170
+ export type NotesUpdateData = Static<typeof NotesUpdateDataSchema>;
171
+
172
+ export const NotesReadDataSchema = Type.Object({
173
+ address: Type.String(),
174
+ project_key: Type.Optional(Type.String()),
175
+ metadata: NoteMetadataSchema,
176
+ ...TextWindowSchema.properties,
177
+ });
178
+ export type NotesReadData = Static<typeof NotesReadDataSchema>;
179
+
180
+ export const NotesListDataSchema = Type.Object({
181
+ files: Type.Array(ListedFileSchema),
182
+ ...SnapshotSchema,
183
+ });
184
+ export type NotesListData = Static<typeof NotesListDataSchema>;
185
+
186
+ export const NotesSearchDataSchema = Type.Object({
187
+ files: Type.Array(SearchedFileSchema),
188
+ ...SnapshotSchema,
189
+ });
190
+ export type NotesSearchData = Static<typeof NotesSearchDataSchema>;
191
+
192
+ type Snapshot<T> = Omit<NotesListData, "files"> & { files: T[] };
193
+
194
+ /** Keep identities intact. Only search previews may shrink to make the first row fit. */
195
+ function snapshot<T>(
196
+ rows: T[],
197
+ limit: number | undefined,
198
+ status: NoteQueryStatus,
199
+ renderData: (data: Snapshot<T>) => string,
200
+ shrink?: (item: T, fits: (candidate: T) => boolean) => T,
201
+ ): Outcome<Snapshot<T>> {
202
+ const files: T[] = [];
203
+ const data = (selected: T[]): Snapshot<T> => ({ files: selected, more: rows.length - selected.length, crumpled_excluded: status.crumpledExcluded, homes_unavailable: status.homesUnavailable });
204
+ const render = (outcome: Outcome<Snapshot<T>>) => renderOutcome(outcome, renderData);
205
+ const fits = (item: T) => fitsResult(success(data([...files, item])), render);
206
+ for (const item of rows.slice(0, limit)) {
207
+ if (fits(item)) {
208
+ files.push(item);
209
+ continue;
210
+ }
211
+ if (files.length === 0 && shrink) {
212
+ const reduced = shrink(item, fits);
213
+ if (fits(reduced)) files.push(reduced);
214
+ }
215
+ if (files.length === 0) return failure("output_too_large", "The first matching note cannot fit in a response without losing its identity.");
216
+ break;
217
+ }
218
+ const outcome = success(data(files));
219
+ return fitsResult(outcome, render) ? outcome : failure("output_too_large", "The notes snapshot metadata exceeds the response budget.");
220
+ }
221
+
222
+ function listedFile(row: Pick<NoteRow, "address" | "scope" | "meta">, identity: NotesIdentity): NotesListData["files"][number] {
223
+ return { address: row.address, ...projectKeyField(row.scope, identity.projectKey), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
224
+ }
225
+
226
+ export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN }, { additionalProperties: false });
227
+
228
+ function renderWriteData(data: NotesWriteData): string {
229
+ return `${data.outcome} ${renderIdentity(data)}`;
230
+ }
231
+
232
+ export const notesWrite = {
233
+ name: "notes_write", label: "Notes write",
234
+ description: `Create or replace a note body, preserving metadata; uncrumples a crumpled note. Name it for its contents and when to use it. Store what git/history cannot recover. ${ADDRESS_DESCRIPTION}`,
235
+ parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
236
+ async execute(params: Static<typeof notesWriteParameters>, identity: NotesIdentity): Promise<Outcome<NotesWriteData>> {
237
+ try {
238
+ const { outcome } = await createNotesStore(identity).write(params.address, params.content, { origin: params.origin ?? "self" });
239
+ return success({ ...noteIdentity(identity, params.address), outcome });
240
+ } catch (error) { return failureOf(error); }
241
+ },
242
+ render: (result: Outcome<NotesWriteData>): string => renderOutcome(result, renderWriteData),
243
+ } as const;
244
+
245
+ export const notesUpdateParameters = Type.Object({ address: Type.String(), edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String(), newText: Type.String() }, { additionalProperties: false }))), origin: ORIGIN, crumpled: CRUMPLED_PARAMETER, replace_all: Type.Optional(Type.Boolean()), rename_to: Type.Optional(Type.String({ description: "Move, preserving metadata. Use alone. Refuses live targets; may replace crumpled targets. References are not updated. Empty string is ignored." })) }, { additionalProperties: false });
246
+
247
+ function renderUpdateData(data: NotesUpdateData): string {
248
+ const head = data.rename_from === undefined
249
+ ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}: ${data.applied} ${data.applied === 1 ? "edit" : "edits"}`
250
+ : `moved ${data.rename_from} -> ${data.address}${data.replaced_crumpled_target === true ? " (replaced a crumpled note)" : ""}`;
251
+ const lines = [head];
252
+ if (data.diff_truncated === true) lines.push("diff (this receipt's diff was shortened to fit the output budget; the update itself was applied):");
253
+ else if (data.diff.length > 0) lines.push("diff:");
254
+ if (data.diff.length > 0) lines.push(data.diff);
255
+ return lines.join("\n");
256
+ }
257
+
258
+ function renderUpdate(result: Outcome<NotesUpdateData>): string {
259
+ return renderOutcome(result, renderUpdateData);
260
+ }
261
+
262
+ /** Bound a mutation receipt on both surfaces; a huge diff is cut to the longest fitting prefix. */
263
+ function boundedUpdate(data: NotesUpdateData): Outcome<NotesUpdateData> {
264
+ if (fitsResult(success(data), renderUpdate)) return success(data);
265
+ const shortened: NotesUpdateData = { ...data, diff_truncated: true };
266
+ const diff = prefixFit(data.diff, (candidate) => fitsResult(success({ ...shortened, diff: candidate }), renderUpdate));
267
+ const result = success({ ...shortened, diff });
268
+ return fitsResult(result, renderUpdate) ? result : failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
269
+ }
270
+
271
+ export const notesUpdate = {
272
+ name: "notes_update", label: "Notes update",
273
+ description: `Edit body text, change origin or crumpled state, or move a note. Each oldText must match once unless replace_all is true; edits cannot change frontmatter. Metadata-only updates need origin or crumpled. Returns applied changes and a bounded diff. ${ADDRESS_DESCRIPTION}`,
274
+ parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
275
+ async execute(params: Static<typeof notesUpdateParameters>, identity: NotesIdentity, renderDiff: (change: NoteChange) => string): Promise<Outcome<NotesUpdateData>> {
276
+ try {
277
+ const store = createNotesStore(identity);
278
+ // Empty filler is not a request: models that pass every parameter get the edit path.
279
+ const renameTo = params.rename_to === "" ? undefined : params.rename_to;
280
+ if (renameTo !== undefined) {
281
+ if ((params.edits?.length ?? 0) > 0 || params.origin !== undefined || params.crumpled !== undefined || params.replace_all === true) {
282
+ return failureOf(new NoteError("invalid_scope", "rename_to is used alone: do not combine it with edits, origin, crumpled, or replace_all"));
283
+ }
284
+ const { replacedCrumpledTarget } = await store.rename(params.address, renameTo);
285
+ const from = noteIdentity(identity, params.address).address;
286
+ const to = noteIdentity(identity, renameTo);
287
+ return boundedUpdate({ ...to, rename_from: from, applied: 0, change_kind: "file", diff: `rename ${from} -> ${to.address}`, replaced_crumpled_target: replacedCrumpledTarget });
288
+ }
289
+ const { applied, change } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all });
290
+ return boundedUpdate({ ...noteIdentity(identity, params.address), applied, change_kind: change.kind, diff: renderDiff(change) });
291
+ } catch (error) { return failureOf(error); }
292
+ },
293
+ render: renderUpdate,
294
+ } as const;
295
+
296
+ export const notesReadParameters = Type.Object({ address: Type.String(), offset_chars: Type.Optional(Type.Integer({ description: "Body code-point offset (default 0); negative counts from EOF." })), limit_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `Max code points (default ${DEFAULT_READ_WINDOW_CHARS}); also bounded by output bytes.` })) }, { additionalProperties: false });
297
+
298
+ function renderReadData(data: NotesReadData): string {
299
+ return `${renderIdentity(data)}\n${renderMetadata(data.metadata)}\n\n${renderTextWindow(data)}`;
300
+ }
301
+
302
+ export const notesRead = {
303
+ name: "notes_read", label: "Notes read",
304
+ description: `Read note metadata and a verbatim body slice, excluding frontmatter. Pass next_offset_chars as offset_chars until null. ${ADDRESS_DESCRIPTION}`,
305
+ parameters: notesReadParameters, outputSchema: resultSchema(NotesReadDataSchema),
306
+ async execute(params: Static<typeof notesReadParameters>, identity: NotesIdentity): Promise<Outcome<NotesReadData>> {
307
+ try {
308
+ const note = await createNotesStore(identity).read(params.address);
309
+ if (!note) return failure("not_found", "note not found");
310
+ const totalChars = Array.from(note.body).length;
311
+ 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)`);
312
+ const resolved = noteIdentity(identity, params.address);
313
+ const metadata = noteMetadata(note.meta);
314
+ return readTextWindow(note.body, params.offset_chars, params.limit_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
315
+ } catch (error) { return failureOf(error); }
316
+ },
317
+ render: (result: Outcome<NotesReadData>): string => renderOutcome(result, renderReadData),
318
+ } as const;
319
+
320
+ export const notesListParameters = Type.Object({ pattern: nullableString(), limit: FILE_LIMIT_PARAMETER, wastebasket: WASTEBASKET_PARAMETER }, { additionalProperties: false });
321
+
322
+ function renderListData(data: NotesListData): string {
323
+ const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
324
+ for (const file of data.files) {
325
+ lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
326
+ }
327
+ if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with pattern`);
328
+ if (data.crumpled_excluded > 0) lines.push(`${data.crumpled_excluded} crumpled notes hidden; pass wastebasket to list them`);
329
+ for (const home of data.homes_unavailable) lines.push(`${home} could not be read`);
330
+ return lines.join("\n");
331
+ }
332
+
333
+ export const notesList = {
334
+ name: "notes_list", label: "Notes list",
335
+ description: `List notes in the session and the four @ homes, newest first. Snapshot, not pageable: more counts omitted files; pattern globs full addresses. Reports unavailable homes and how many crumpled notes were excluded. ${ADDRESS_DESCRIPTION}`,
336
+ parameters: notesListParameters, outputSchema: resultSchema(NotesListDataSchema),
337
+ async execute(params: Static<typeof notesListParameters>, identity: NotesIdentity): Promise<Outcome<NotesListData>> {
338
+ try {
339
+ const { rows, status } = await createNotesStore(identity).listWithStatus({ pattern: params.pattern ?? undefined, wastebasket: params.wastebasket });
340
+ return snapshot(rows.map(row => listedFile(row, identity)), params.limit, status, renderListData);
341
+ } catch (error) { return failureOf(error); }
342
+ },
343
+ render: (result: Outcome<NotesListData>): string => renderOutcome(result, renderListData),
344
+ } as const;
345
+
346
+ export const notesSearchParameters = Type.Object({ query: searchQuery(), pattern: nullableString(), limit: FILE_LIMIT_PARAMETER, max_matches_per_file: Type.Optional(Type.Integer({ minimum: 1, description: "Max matches shown per file (default: no cap); matches_total still counts all." })), wastebasket: WASTEBASKET_PARAMETER }, { additionalProperties: false });
347
+
348
+ function renderSearchData(data: NotesSearchData): string {
349
+ const lines = [`${data.files.length} ${data.files.length === 1 ? "file" : "files"}`];
350
+ for (const file of data.files) {
351
+ lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | ${file.matches_total} ${file.matches_total === 1 ? "match" : "matches"}${file.matches.length < file.matches_total ? ` (${file.matches.length} shown)` : ""}`);
352
+ for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}${match.truncated ? " [line shortened]" : ""}`);
353
+ }
354
+ if (data.more > 0) lines.push(`${data.more} more matching files omitted; narrow with pattern`);
355
+ if (data.crumpled_excluded > 0) lines.push(`${data.crumpled_excluded} crumpled notes hidden; pass wastebasket to search them`);
356
+ for (const home of data.homes_unavailable) lines.push(`${home} could not be read`);
357
+ return lines.join("\n");
358
+ }
359
+
360
+ type SearchFile = NotesSearchData["files"][number];
361
+
362
+ /** Prefer whole match lines; shorten the first line only if no whole line fits. */
363
+ function fitSearchFile(file: SearchFile, fits: (candidate: SearchFile) => boolean): SearchFile {
364
+ let low = 0;
365
+ let high = file.matches.length;
366
+ while (low < high) {
367
+ const mid = Math.ceil((low + high) / 2);
368
+ if (fits({ ...file, matches: file.matches.slice(0, mid) })) low = mid;
369
+ else high = mid - 1;
370
+ }
371
+ if (low > 0) return { ...file, matches: file.matches.slice(0, low) };
372
+ const first = file.matches[0];
373
+ if (!first) return file;
374
+ const withText = (text: string): SearchFile => ({ ...file, matches: [{ ...first, text, truncated: true }] });
375
+ return withText(prefixFit(first.text, text => fits(withText(text))));
376
+ }
377
+
378
+ export const notesSearch = {
379
+ name: "notes_search", label: "Notes search",
380
+ description: `Search note bodies for case-insensitive literal queries (OR). Returns matching lines and body code-point offsets for notes_read. Snapshot, not pageable: more counts omitted files; matches_total is before per-file capping. pattern globs full addresses across the session and the four @ homes. ${ADDRESS_DESCRIPTION}`,
381
+ parameters: notesSearchParameters, outputSchema: resultSchema(NotesSearchDataSchema),
382
+ async execute(params: Static<typeof notesSearchParameters>, identity: NotesIdentity): Promise<Outcome<NotesSearchData>> {
383
+ try {
384
+ const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { pattern: params.pattern ?? undefined, wastebasket: params.wastebasket });
385
+ const files: NotesSearchData["files"] = rows.sort(byRecent).map(row => ({
386
+ ...listedFile(row, identity),
387
+ matches_total: row.matches.length,
388
+ matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, truncated: false, offset_chars: match.offsetChars })),
389
+ }));
390
+ return snapshot(files, params.limit, status, renderSearchData, fitSearchFile);
391
+ } catch (error) { return failureOf(error); }
392
+ },
393
+ render: (result: Outcome<NotesSearchData>): string => renderOutcome(result, renderSearchData),
394
+ } as const;
@@ -0,0 +1,41 @@
1
+ /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
2
+ export { earliestMatchOffsetChars } from "../text-match.js";
3
+
4
+ export const TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
5
+ export const DEFAULT_READ_WINDOW_CHARS = 12000;
6
+ export const MAX_READ_WINDOW_CHARS = 50000;
7
+ export const HISTORY_PREVIEW_CHARS = 1200;
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
+ /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
19
+ export function prefixFit(text: string, fits: (content: string) => boolean): string {
20
+ if (fits(text)) return text;
21
+ const chars = Array.from(text);
22
+ // Serialized size is non-decreasing in the kept count, so the largest fitting prefix is
23
+ // found by a monotone binary search instead of a quadratic shrink loop.
24
+ let low = 0;
25
+ let high = chars.length;
26
+ while (low < high) {
27
+ const mid = Math.ceil((low + high) / 2);
28
+ if (fits(chars.slice(0, mid).join(""))) low = mid;
29
+ else high = mid - 1;
30
+ }
31
+ return chars.slice(0, low).join("");
32
+ }
33
+
34
+ /**
35
+ * Encode a structured result through the common tool result boundary. `details` is slim
36
+ * metadata for logs/UI (pi convention: never a second copy of the payload) and stays
37
+ * undefined unless the tool has metadata worth persisting.
38
+ */
39
+ export function output(value: unknown, details?: unknown, terminate = false) {
40
+ return { content: [{ type: "text" as const, text: json(value) }], details, terminate };
41
+ }
@@ -0,0 +1,169 @@
1
+ /** Internal outcomes, compact wire results, and bounded read windows. */
2
+ import { Type, type Static, type TSchema } from "typebox";
3
+ import { DEFAULT_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES, withinTextBudget } from "./output.js";
4
+
5
+ /** `details` is sanitized context for a caller, never a payload or a file body. */
6
+ export const OperationErrorSchema = Type.Object({
7
+ code: Type.String(),
8
+ message: Type.String(),
9
+ details: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
10
+ }, { additionalProperties: false });
11
+ export type OperationError = Static<typeof OperationErrorSchema>;
12
+
13
+ /** `data` exists without `error`, never both, never neither. */
14
+ export type Outcome<T> = { ok: true; data: T } | { ok: false; error: OperationError };
15
+
16
+ export function success<T>(data: T): Outcome<T> {
17
+ return { ok: true, data };
18
+ }
19
+
20
+ /** A code is an internal stable identifier and is never clipped; the dynamic message and details are the bounded surface. */
21
+ export const ERROR_MESSAGE_MAX_CHARS = 2000;
22
+ export const ERROR_DETAILS_MAX_BYTES = 4096;
23
+
24
+ function boundedMessage(message: string): string {
25
+ const chars = Array.from(message);
26
+ return chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}…[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
27
+ }
28
+
29
+ /** Oversized context becomes an explicit marker, and context JSON cannot serialize propagates instead of being swallowed. */
30
+ function boundedDetails(details: Record<string, unknown>): Record<string, unknown> {
31
+ const json = JSON.stringify(details);
32
+ const bytes = Buffer.byteLength(json, "utf8");
33
+ return bytes <= ERROR_DETAILS_MAX_BYTES ? JSON.parse(json) as Record<string, unknown> : { truncated: true, details_bytes: bytes };
34
+ }
35
+
36
+ export function failure(code: string, message: string, details?: Record<string, unknown>): Outcome<never> {
37
+ return {
38
+ ok: false,
39
+ error: {
40
+ code,
41
+ message: boundedMessage(message),
42
+ ...(details === undefined ? {} : { details: boundedDetails(details) }),
43
+ },
44
+ };
45
+ }
46
+
47
+ /** Public results have no success envelope. `error` is reserved for a refusal message. */
48
+ export type WireError = { error: string; code: string; details?: Record<string, unknown> };
49
+ export type WireResult<T> = T | WireError;
50
+
51
+ export function wireResult<T>(result: Outcome<T>): WireResult<T> {
52
+ if (result.ok) return result.data;
53
+ const { code, message, details } = result.error;
54
+ return { error: message, code, ...(details === undefined ? {} : { details }) };
55
+ }
56
+
57
+ export function resultSchema<S extends TSchema>(dataSchema: S) {
58
+ return Type.Union([
59
+ dataSchema,
60
+ Type.Object({
61
+ error: Type.String(),
62
+ code: Type.String(),
63
+ details: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
64
+ }, { additionalProperties: false }),
65
+ ]);
66
+ }
67
+
68
+ /** A refusal reads as one short line; a success is the operation's own reading of its data. */
69
+ export function renderOutcome<T>(result: Outcome<T>, renderData: (data: T) => string): string {
70
+ if (result.ok) return renderData(result.data);
71
+ const { code, message, details } = result.error;
72
+ return `error: ${code}: ${message}${details === undefined ? "" : ` ${JSON.stringify(details)}`}`;
73
+ }
74
+
75
+ /** Bytes of the structured payload as delivered: compact JSON, not the model-facing text. A value with no JSON representation has no size to measure. */
76
+ export function structuredBytes(value: unknown): number {
77
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
78
+ }
79
+
80
+ /**
81
+ * The one bound: the rendered text and the structured payload must both fit, and the rendered
82
+ * measure covers everything the renderer puts around the payload, headers and footers included.
83
+ */
84
+ export function fitsResult<T>(result: Outcome<T>, render: (result: Outcome<T>) => string): boolean {
85
+ return withinTextBudget(render(result)) && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
86
+ }
87
+
88
+ /** `text` is verbatim, with no marker inserted, so windows concatenate back into the source. */
89
+ export const TextWindowSchema = Type.Object({
90
+ text: Type.String(),
91
+ offset_chars: Type.Integer({ minimum: 0 }),
92
+ total_chars: Type.Integer({ minimum: 0 }),
93
+ next_offset_chars: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()], { description: "Continue at this code-point offset; null at EOF." }),
94
+ limited_by: Type.Union([Type.Literal("limit"), Type.Literal("bytes"), Type.Null()]),
95
+ }, { additionalProperties: false });
96
+ export type TextWindow = Static<typeof TextWindowSchema>;
97
+
98
+ /**
99
+ * Read one code-point window of `text` and build the operation's data around it. `offset` and
100
+ * `limit` are the integers the parameter schema already admitted; a negative `offset` resolves to
101
+ * `max(0, total + offset)`, and the caller refuses an offset past the end.
102
+ *
103
+ * An envelope that cannot fit even empty is refused instead of returned: a zero-length window
104
+ * would resume at the offset it started from, so paging could never make progress.
105
+ */
106
+ export function readTextWindow<T>(
107
+ text: string,
108
+ offset: number | undefined,
109
+ limit: number | undefined,
110
+ makeData: (window: TextWindow) => T,
111
+ render: (result: Outcome<T>) => string,
112
+ ): Outcome<T> {
113
+ const chars = Array.from(text);
114
+ const requested = offset ?? 0;
115
+ const start = requested < 0 ? Math.max(0, chars.length + requested) : requested;
116
+ const requestedChars = limit ?? DEFAULT_READ_WINDOW_CHARS;
117
+ const range = Math.min(requestedChars, chars.length - start);
118
+ const window = (delivered: number): TextWindow => {
119
+ const end = start + delivered;
120
+ const withheld = end < chars.length;
121
+ return {
122
+ text: chars.slice(start, end).join(""),
123
+ offset_chars: start,
124
+ total_chars: chars.length,
125
+ next_offset_chars: withheld ? end : null,
126
+ limited_by: !withheld ? null : delivered === range ? "limit" : "bytes",
127
+ };
128
+ };
129
+ const fits = (delivered: number): boolean => fitsResult(success(makeData(window(delivered))), render);
130
+ // Test the full range first: its footer can disappear at the end of the document.
131
+ if (fits(range)) return success(makeData(window(range)));
132
+ let low = 0;
133
+ let high = range;
134
+ while (low < high) {
135
+ const mid = Math.ceil((low + high) / 2);
136
+ if (fits(mid)) low = mid;
137
+ else high = mid - 1;
138
+ }
139
+ if (low === 0) {
140
+ return failure("output_too_large", "The response metadata leaves no room for a progressing read window.", { total_chars: chars.length, offset_chars: start, budget_bytes: TOOL_OUTPUT_MAX_BYTES });
141
+ }
142
+ return success(makeData(window(low)));
143
+ }
144
+
145
+ /** The continuation line never becomes part of `window.text`, and a complete window has none. */
146
+ export function renderTextWindow(window: TextWindow): string {
147
+ const next = window.next_offset_chars;
148
+ if (next === null) return window.text;
149
+ const resume = `Use offset_chars=${next} to continue.`;
150
+ if (window.limited_by === "limit") return `${window.text}\n\n[${window.total_chars - next} more characters. ${resume}]`;
151
+ return `${window.text}\n\n[Showing chars [${window.offset_chars}, ${next}) of ${window.total_chars} (${TOOL_OUTPUT_MAX_BYTES / 1024}KB limit). ${resume}]`;
152
+ }
153
+
154
+ /** One outcome in, model-facing text out. */
155
+ export type Renderer<TData> = (result: Outcome<TData>) => string;
156
+
157
+ /** What both host adapters register: parameters in, canonical outcome out, and its text. */
158
+ export type Operation<TParams extends TSchema, TData, TRest extends readonly unknown[]> = {
159
+ readonly name: string;
160
+ readonly label: string;
161
+ readonly description: string;
162
+ readonly parameters: TParams;
163
+ /** Absent leaves concurrency to the host default. */
164
+ readonly executionMode?: "sequential" | "parallel";
165
+ /** Schema of wireResult(outcome), not the internal outcome envelope. */
166
+ readonly outputSchema: TSchema;
167
+ readonly execute: (params: Static<TParams>, ...rest: TRest) => Promise<Outcome<TData>>;
168
+ readonly render: Renderer<TData>;
169
+ };
@@ -0,0 +1,31 @@
1
+ import { Type } from "typebox";
2
+ import { HistoryRoleSchema } from "../history/history.js";
3
+ export const nullableString = () => Type.Optional(Type.Union([Type.String(), Type.Null()]));
4
+ export const positiveInteger = () => Type.Optional(Type.Integer({ minimum: 1 }));
5
+ export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "Any of user, assistant, tool, context." }));
6
+
7
+ /** Search query parameter: one literal, or several literals combined with OR. */
8
+ export const searchQuery = () => Type.Union([Type.String(), Type.Array(Type.String(), { minItems: 1 })]);
9
+
10
+ /** Expected search-query refusal, distinct from any other Error an operation may raise. */
11
+ export class InvalidQueryError extends Error {
12
+ constructor(message: string) {
13
+ super(message);
14
+ this.name = "InvalidQueryError";
15
+ }
16
+ }
17
+
18
+ /**
19
+ * Normalize a search `query` parameter into the literal needles to match.
20
+ * A bare string is a one-element list, so single-query behavior is unchanged.
21
+ * An empty list, a non-string element, or an empty string is refused rather than silently
22
+ * searching for nothing: those are argument errors, not empty result sets. An empty string
23
+ * matches every line and every item, so it can never be what the caller meant.
24
+ */
25
+ export function searchQueries(query: unknown): string[] {
26
+ 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");
30
+ return candidates as string[];
31
+ }