llm-large-files 0.4.1 → 0.7.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 (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
package/src/tools.ts CHANGED
@@ -1,21 +1,33 @@
1
1
  import { safeErrorMessage } from "./errors.js";
2
- import { analyzeWholeDocument } from "./map-reduce.js";
2
+ import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
3
3
  import { cutPdfPages } from "./pdf-pages.js";
4
- import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource } from "./search.js";
4
+ import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource, type LineMatch } from "./search.js";
5
5
  import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
6
- import type { Budget, GenerateText, ProgressListener, ToolDeclaration, ToolFileLimits, ToolOutput, ToolResult, ToolSet } from "./types.js";
6
+ import type { RetryOptions } from "./retry.js";
7
+ import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
8
+ import type { Budget, GenerateText, ProgressListener, ToolCallHooks, ToolCallLimits, ToolDeclaration, ToolOutput, ToolResult, ToolSet } from "./types.js";
7
9
 
8
10
  const DEFAULT_READ_LINES = 200;
9
11
  const MAX_READ_LINES = 600;
10
12
  /** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
11
13
  export const MAX_VIEW_PAGES = 5;
12
14
  /**
13
- * The time the regex searches of one tool set (one question, in `askGemini`) may take together,
15
+ * The time the regex searches of one tool set (one question, in `askWithFiles`) may take together,
14
16
  * unless `regexBudgetMs` says otherwise. An ordinary search of a 60 MB log takes about 0.15 s.
15
17
  */
16
18
  export const REGEX_BUDGET_MS = 6_000;
17
19
  /** Below this, no page fits: a cut of one page of plain text is larger. */
18
20
  const MIN_FILE_BYTES = 1_024;
21
+ /** The answer of a whole-document read may be this long, when the cap on tool results is lower. */
22
+ const ANALYSIS_RESULT_CHARACTERS = 40_000;
23
+ /** A result is never cut below this, whatever room a caller names: less holds no line of a file. */
24
+ export const LEAST_RESULT_CHARACTERS = 600;
25
+ /**
26
+ * How many times one document is read whole by the tools of one tool set (one question, in
27
+ * `askWithFiles`), unless `maxWholeDocumentReads` says otherwise. One read of a large file is
28
+ * up to `maxMapChunks` model requests.
29
+ */
30
+ export const MAX_WHOLE_DOCUMENT_READS = 1;
19
31
 
20
32
  export const TOOL_NAMES = {
21
33
  search: "search_document",
@@ -30,7 +42,7 @@ const documentId = { type: "string" as const, description: "The document_id from
30
42
  const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
31
43
  search: {
32
44
  name: TOOL_NAMES.search,
33
- description: "Search a large attached file. mode \"keywords\" returns the most relevant passages for a question; \"exact\" returns every line containing the text; \"regex\" returns lines matching a JavaScript regular expression. Results include line numbers to read further with read_document.",
45
+ description: "Search a large attached file. mode \"keywords\" returns the most relevant passages for a question; \"exact\" finds the lines that contain the text; \"regex\" finds the lines that match a JavaScript regular expression. For exact and regex, total_matching_lines counts every matching line, and the result shows the first max_results of them and the last one. Results include line numbers to read further with read_document.",
34
46
  parameters: {
35
47
  type: "object",
36
48
  properties: {
@@ -64,7 +76,7 @@ const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
64
76
  },
65
77
  analyze: {
66
78
  name: TOOL_NAMES.analyze,
67
- description: "Read an entire large file in parts and answer a task that needs all of it, such as a full summary, a timeline, or every occurrence of something. Slow and costly: prefer search_document and read_document for specific questions.",
79
+ description: "Read an entire large file in parts and answer a task that needs all of it, such as a full summary, a timeline, or items that must be judged by meaning. To count or list lines that contain a word, an ID or a pattern, use search_document in exact or regex mode instead: its count is exact, and this can miss items. Slow and costly: prefer search_document and read_document for specific questions.",
68
80
  parameters: {
69
81
  type: "object",
70
82
  properties: {
@@ -114,13 +126,17 @@ function pageNumber(value: unknown, name: string): number {
114
126
 
115
127
  const pageRange = (from: number, to: number): string => (to > from ? `${from}-${to}` : String(from));
116
128
 
117
- /** Trims a result to the character budget by dropping trailing list entries, then cutting text. */
129
+ /**
130
+ * Trims a result to the character budget by dropping trailing list entries, then cutting text. A
131
+ * note the result already has (a search that stopped early) is kept, before the one that says so.
132
+ */
118
133
  function fit(result: ToolResult, listKey: string | null, limit: number): ToolResult {
119
134
  if (JSON.stringify(result).length <= limit) return result;
120
135
  const list = listKey ? result[listKey] : undefined;
121
136
  if (Array.isArray(list)) {
122
137
  const kept = [...list];
123
- const note = () => `Showing ${kept.length} of ${list.length} results to stay within the size limit. Narrow the query or read specific lines.`;
138
+ const before = typeof result.note === "string" ? `${result.note} ` : "";
139
+ const note = () => `${before}Showing ${kept.length} of ${list.length} results to stay within the size limit. Narrow the query or read specific lines.`;
124
140
  const trimmed = () => ({ ...result, [listKey!]: kept, note: note() });
125
141
  while (kept.length > 1 && JSON.stringify(trimmed()).length > limit) kept.pop();
126
142
  if (JSON.stringify(trimmed()).length <= limit) return trimmed();
@@ -131,22 +147,174 @@ function fit(result: ToolResult, listKey: string | null, limit: number): ToolRes
131
147
  let cut: ToolResult;
132
148
  do {
133
149
  size = Math.floor(size * 0.85);
134
- cut = { truncated: true, partial: serialized.slice(0, size), note: "Result cut to the size limit. Ask for a smaller range." };
150
+ cut = { truncated: true, partial: sliceWhole(serialized, size), note: "Result cut to the size limit. Ask for a smaller range." };
135
151
  } while (JSON.stringify(cut).length > limit && size > 100);
136
152
  return cut;
137
153
  }
138
154
 
155
+ /**
156
+ * The result of a whole-document read within `limit` characters: its answer is cut at the end,
157
+ * and says so, rather than the result being cut as JSON, which loses what the other fields say.
158
+ */
159
+ export function fitAnswer(result: ToolResult, limit: number): ToolResult {
160
+ if (JSON.stringify(result).length <= limit || typeof result.answer !== "string") return fit(result, null, limit);
161
+ const answer = result.answer;
162
+ const cutAt = (keep: number): ToolResult => ({
163
+ ...result,
164
+ answer: `${sliceWhole(answer, keep)}…`,
165
+ answer_shortened: "The rest of this answer did not fit in the room left in this conversation.",
166
+ });
167
+ // The longest start of the answer that fits. Escapes (quotes, line breaks) make the JSON longer
168
+ // than the text by as much as the text holds of them, so it is found by halving, not worked out.
169
+ let low = 0;
170
+ let high = answer.length;
171
+ while (low < high) {
172
+ const middle = Math.ceil((low + high) / 2);
173
+ if (JSON.stringify(cutAt(middle)).length <= limit) low = middle;
174
+ else high = middle - 1;
175
+ }
176
+ return fit(cutAt(low), null, limit);
177
+ }
178
+
179
+ /**
180
+ * The result of an exact or regex search that read the whole file: the first matches, then the
181
+ * last one of the file, and a note that says how many of how many are shown when that is not all.
182
+ * Without the last one, a model asked when something last happened named the last line it was
183
+ * shown. To fit `limit`, matches are dropped from the end of the first ones: the last one stays.
184
+ */
185
+ function firstAndLastMatches(base: ToolResult, first: LineMatch[], last: LineMatch, total: number, limit: number): ToolResult {
186
+ const which = (kept: number) => (kept === 0 ? `the last (line ${last.line})` : `the first${kept > 1 ? ` ${kept}` : ""} and the last (line ${last.line})`);
187
+ const shown = (kept: number) => `${kept + 1} of the ${total} matching lines`;
188
+ const withFirst = (kept: number, cut: boolean): ToolResult => ({
189
+ ...base,
190
+ ...(cut
191
+ ? { note: `Showing ${shown(kept)} to stay within the size limit: ${which(kept)}. Narrow the query or read specific lines.` }
192
+ // When every match is shown, there is nothing to say.
193
+ : kept + 1 < total ? { note: `${shown(kept)} are shown: ${which(kept)}. To see the ones in between, narrow the search.` } : {}),
194
+ matches: [...first.slice(0, kept), last],
195
+ });
196
+ const whole = withFirst(first.length, false);
197
+ if (JSON.stringify(whole).length <= limit) return whole;
198
+ let kept = first.length;
199
+ while (kept > 0 && JSON.stringify(withFirst(kept, true)).length > limit) kept--;
200
+ const cut = withFirst(kept, true);
201
+ if (JSON.stringify(cut).length <= limit) return cut;
202
+ // Only the last match is left, and its note is too long for the room: a shorter one. It still
203
+ // starts with "Showing ", so the result is taken as cut. `fit` must not put its own note in its
204
+ // place, which would say "1 of 1 results" and drop the line of the last match. When even this
205
+ // does not fit, `fit` cuts the result as text: the note, with that line, comes before the match.
206
+ const lastOnly = { ...base, note: `Showing 1 of the ${total} matching lines: ${which(0)}. Narrow the search.`, matches: [last] };
207
+ return fit(lastOnly, null, limit);
208
+ }
209
+
210
+ const searchMode = (mode: unknown): "keywords" | "exact" | "regex" => (mode === "exact" || mode === "regex" ? mode : "keywords");
211
+
212
+ /** The lines a `read_document` call asks for, as its handler reads them, before the end of the file is known. */
213
+ function requestedLines(args: Record<string, unknown>): [number, number] {
214
+ const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
215
+ return [start, integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, start + MAX_READ_LINES - 1)];
216
+ }
217
+
218
+ /**
219
+ * A call's arguments as its tool reads them, with the defaults filled in: two calls with the same
220
+ * key get the same result from a file that has not changed. Undefined for a tool whose calls are
221
+ * not compared (a whole-file read has a count of its own; a look at pages returns a file).
222
+ */
223
+ export function toolCallKey(name: string, args: Record<string, unknown>): string | undefined {
224
+ const id = typeof args.document_id === "string" && args.document_id ? args.document_id : undefined;
225
+ if (!id) return undefined;
226
+ if (name === TOOL_NAMES.search) {
227
+ if (typeof args.query !== "string" || !args.query.trim()) return undefined;
228
+ const mode = searchMode(args.mode);
229
+ return JSON.stringify(mode === "keywords"
230
+ ? [name, id, args.query, mode, integer(args.max_results, 5, 1, 10)]
231
+ : [name, id, args.query, mode, integer(args.max_results, 20, 1, 50), integer(args.context_lines, 0, 0, 5), args.case_sensitive === true]);
232
+ }
233
+ if (name === TOOL_NAMES.read) return JSON.stringify([name, id, ...requestedLines(args)]);
234
+ if (name === TOOL_NAMES.overview) return JSON.stringify([name, id]);
235
+ return undefined;
236
+ }
237
+
238
+ /**
239
+ * When an earlier call's result already holds all that `call` would return, and is still in the
240
+ * conversation in full: a short result that says so, in place of running the call again. A result
241
+ * that was cut to the room it had, or replaced by a stand-in, or failed, is not pointed to: the call
242
+ * is run, and may get more. A read of lines inside a read that is shown in full is pointed to.
243
+ * `stored` is true for a result in the tool rounds of an earlier question, which an older version
244
+ * may have written: 0.5.0 cut the text of a read of one long line without saying so (no
245
+ * `text_cut`), so a read of one line from there is not taken as shown in full.
246
+ */
247
+ export function alreadyShown(call: { name: string; args: Record<string, unknown> }, earlier: { call: { name: string; args: Record<string, unknown> }; result: ToolResult }, stored = false): ToolResult | undefined {
248
+ const { result } = earlier;
249
+ if (earlier.call.name !== call.name || earlier.call.args.document_id !== call.args.document_id) return undefined;
250
+ if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true) return undefined;
251
+ // A list that `fit` cut to the room it had, a read whose text was cut, or a search that ran out of
252
+ // time ("the total is a lower bound"; a later question has time of its own): a call made now may get more.
253
+ if (typeof result.note === "string" && (result.note.startsWith("Showing ") || result.note.startsWith("The scan stopped early"))) return undefined;
254
+ if (result.text_cut === true) return undefined;
255
+ // An exact or regex search that an earlier version stored: the first matches, without the last one
256
+ // and without a note. Run now, the call returns more (the last match), not the same.
257
+ if (call.name === TOOL_NAMES.search && typeof result.total_matching_lines === "number" && Array.isArray(result.matches)
258
+ && result.matches.length < result.total_matching_lines && typeof result.note !== "string") return undefined;
259
+ const document = typeof result.document === "string" ? { document: result.document } : {};
260
+ if (call.name === TOOL_NAMES.read) {
261
+ const shown = typeof result.lines === "string" ? /^(\d+)-(\d+)$/.exec(result.lines) : null;
262
+ const total = result.total_lines;
263
+ if (!shown || typeof total !== "number") return undefined;
264
+ const [first, last] = [Number(shown[1]), Number(shown[2])];
265
+ if (stored && first === last) return undefined;
266
+ const [start, end] = requestedLines(call.args);
267
+ const from = Math.min(start, total);
268
+ const to = Math.min(end, total);
269
+ if (from < first || to > last) return undefined;
270
+ return {
271
+ ...document,
272
+ lines: `${from}-${to}`,
273
+ already_shown: true,
274
+ note: `Not run: lines ${from}-${to} are already shown above in full, in the result that has lines ${first}-${last} of this file, and the file has not changed. Use them. To see more, read other lines.`,
275
+ };
276
+ }
277
+ const key = toolCallKey(call.name, call.args);
278
+ if (key === undefined || key !== toolCallKey(earlier.call.name, earlier.call.args)) return undefined;
279
+ return {
280
+ ...document,
281
+ already_shown: true,
282
+ note: "Not run: this exact call was answered earlier in this conversation, and its result is still shown above in full. The file has not changed, so it would return the same. Use that result. For more, read other lines, or search with other words or another mode.",
283
+ };
284
+ }
285
+
286
+ /**
287
+ * A hint added to the error of a search that failed twice in a row in the same mode, so that the
288
+ * model tries another way instead of sending the same kind of call a third time.
289
+ */
290
+ export function repeatedFailureHint(call: { name: string; args: Record<string, unknown> }): string {
291
+ return searchMode(call.args.mode) === "regex"
292
+ ? "Two regex searches in a row failed. Try mode \"exact\" with a plain word or ID from the file, or mode \"keywords\"."
293
+ : "This search failed twice in a row. Check the arguments against the tool's description, or answer from what you have.";
294
+ }
295
+
296
+ /**
297
+ * The tool and mode of a search, to tell whether two failures in a row were of the same kind.
298
+ * Undefined for the other tools: their errors say what to do (a whole-file read that is not made
299
+ * again, a page that does not exist), and a hint would only blur that.
300
+ */
301
+ export function failureKind(call: { name: string; args: Record<string, unknown> }): string | undefined {
302
+ return call.name === TOOL_NAMES.search ? `${call.name}|${searchMode(call.args.mode)}` : undefined;
303
+ }
304
+
139
305
  /**
140
306
  * What a finished tool call found, as a suffix for its `describe()` label, for a steps list:
141
307
  * "Search app.log (exact) for “timeout”" + " — 12 matching lines".
142
308
  */
143
309
  export function toolResultSummary(label: string, result: ToolResult): string {
144
310
  if (typeof result.error === "string") return ` — failed: ${result.error}`;
145
- if (typeof result.total_matching_lines === "number") return ` — ${result.total_matching_lines.toLocaleString("en-US")} matching lines`;
146
- if (Array.isArray(result.passages)) return ` — ${result.passages.length} passages`;
311
+ if (typeof result.total_matching_lines === "number") {
312
+ return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}`;
313
+ }
314
+ if (Array.isArray(result.passages)) return ` — ${result.passages.length} ${plural(result.passages.length, "passage")}`;
147
315
  if (typeof result.parts_read === "number") {
148
- const incomplete = result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
149
- return ` — ${result.parts_read} parts, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
316
+ const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
317
+ return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
150
318
  }
151
319
  // A read reports its range only when it was cut short of what was asked.
152
320
  if (typeof result.lines === "string" && typeof result.total_lines === "number") return label.endsWith(result.lines) ? "" : ` — got ${result.lines}`;
@@ -157,6 +325,31 @@ export function toolResultSummary(label: string, result: ToolResult): string {
157
325
  return "";
158
326
  }
159
327
 
328
+ /**
329
+ * A step, or a label of one, as one line of plain text. Steps quote what the model sent (a query, a
330
+ * task, the name of a tool, arguments that were not JSON), and they reach users' screens: the
331
+ * invisible characters that file text and names lose are dropped (`removeInvisible`: text-direction
332
+ * overrides and isolates, zero-width spaces, tag characters), a line break, a tab or another control
333
+ * character becomes one space with the blanks around it, and "](" gets a space, so that a markdown
334
+ * link or picture in a query stays text. A line without them is unchanged.
335
+ */
336
+ export function stepLine(text: string): string {
337
+ // Each control character, tab and line break is a "\n" first, which `removeInvisible` keeps (it
338
+ // would drop the others): an invisible character between two of them then leaves one space, not
339
+ // two. A soft hyphen it keeps before one goes too. Then a run of blanks with a "\n" in it is one space.
340
+ const marked = removeInvisible(text.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, "\n")).replace(/\xAD+(?=\n)/g, "");
341
+ return marked.replace(/\s+/g, (blank) => (blank.includes("\n") ? " " : blank)).replaceAll("](", "] (");
342
+ }
343
+
344
+ /** An unknown tool's name as a step or an error quotes it: the model chose it, at any length. */
345
+ export const unknownToolName = (name: string): string => `“${sliceWhole(name, 64)}”`;
346
+
347
+ /**
348
+ * A document_id the model sent, as an error quotes it: whole when it is as long as a real one can
349
+ * be, cut otherwise. The model chose it, at any length, and the error goes into steps too.
350
+ */
351
+ const shownId = (id: string): string => (id.length > 64 ? `${sliceWhole(id, 64)}…` : id);
352
+
160
353
  export function createDocumentTools(options: {
161
354
  /** Loads a document the tools may access. Return undefined for anything out of scope. */
162
355
  load(documentId: string): Promise<DocumentSource | undefined>;
@@ -169,6 +362,10 @@ export function createDocumentTools(options: {
169
362
  signal?: AbortSignal;
170
363
  /** The most time, in milliseconds, that the regex searches of this tool set may take together. Defaults to `REGEX_BUDGET_MS`. */
171
364
  regexBudgetMs?: number;
365
+ /** How many times each document may be read whole by this tool set. Defaults to `MAX_WHOLE_DOCUMENT_READS`. */
366
+ maxWholeDocumentReads?: number;
367
+ /** How a model request of a whole-document read that failed is sent again. */
368
+ retry?: RetryOptions;
172
369
  /**
173
370
  * False when every document is too large for a whole-document read: `analyze_whole_document` is
174
371
  * then not declared. A call of it still answers with the reason. Defaults to true.
@@ -195,26 +392,51 @@ export function createDocumentTools(options: {
195
392
  const known = new Set(declarations.map((declaration) => declaration.name));
196
393
  // Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
197
394
  if (textTools && options.generate) known.add(TOOL_NAMES.analyze);
198
- const limit = options.budget.toolResultCharacters;
395
+ const cap = options.budget.toolResultCharacters;
396
+ /** The cap on the result of one call: the tool set's own, or the room its caller has left when that is less. */
397
+ const limitOf = (limits: ToolCallLimits, own = cap): number => {
398
+ const room = limits.maxResultCharacters;
399
+ return typeof room === "number" && Number.isFinite(room) ? Math.max(LEAST_RESULT_CHARACTERS, Math.min(own, Math.trunc(room))) : own;
400
+ };
199
401
  // The model writes the regex, and a file it reads can ask for a slow one: the time is counted
200
402
  // over every search of this tool set, not only within one.
201
403
  const regexBudget = Math.max(0, options.regexBudgetMs ?? REGEX_BUDGET_MS);
202
404
  const regexClock = { usedMs: 0 };
405
+ // Calls of one turn may run together. Regex searches still take their turns, one after another:
406
+ // each must know how much of the time the ones before it used.
407
+ let regexQueue: Promise<unknown> = Promise.resolve();
408
+ const inRegexTurn = <T>(run: () => Promise<T>): Promise<T> => {
409
+ const next = regexQueue.then(run, run);
410
+ regexQueue = next.catch(() => undefined);
411
+ return next;
412
+ };
413
+ const maxWholeReads = Math.max(0, Math.trunc(options.maxWholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS));
414
+ /** Whole-document reads started, by document. */
415
+ const wholeReads = new Map<string, number>();
416
+ /** Why the last whole-document read of a document failed, when no part of it could be read. */
417
+ const failedWholeReads = new Map<string, string>();
203
418
  // When no limit is given with a call: three eighths of a request, so that two looks still fit.
204
419
  const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
205
420
 
206
421
  async function documentFor(args: Record<string, unknown>): Promise<DocumentSource> {
207
422
  const id = text(args.document_id, "document_id");
208
423
  // Scope check: a model can only reach files attached to this conversation.
209
- if (!allowed.has(id)) throw new Error(`Unknown document_id ${id}. Use an ID from a file card.`);
424
+ if (!allowed.has(id)) {
425
+ // The IDs it may use, with their file names, so that the next call is right.
426
+ const usable = [...allowed].slice(0, 20).map((known) => `${known}${names.has(known) ? ` (${JSON.stringify(names.get(known))})` : ""}`);
427
+ throw new Error(usable.length === 0
428
+ ? `Unknown document_id ${shownId(id)}. No attached file is read with this tool in this conversation.`
429
+ : `Unknown document_id ${shownId(id)}. Use one of: ${usable.join(", ")}${allowed.size > 20 ? ", …" : ""}.`);
430
+ }
210
431
  const document = await options.load(id);
211
432
  if (!document) throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
212
433
  names.set(id, document.meta.name);
213
434
  return document;
214
435
  }
215
436
 
216
- const handlers: Record<string, (args: Record<string, unknown>) => Promise<ToolResult>> = {
217
- async [TOOL_NAMES.search](args) {
437
+ const handlers: Record<string, (args: Record<string, unknown>, limits: ToolCallLimits, hooks: ToolCallHooks) => Promise<ToolResult>> = {
438
+ async [TOOL_NAMES.search](args, limits) {
439
+ const limit = limitOf(limits);
218
440
  const document = await documentFor(args);
219
441
  const query = text(args.query, "query");
220
442
  const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
@@ -241,31 +463,45 @@ export function createDocumentTools(options: {
241
463
  }, "passages", limit);
242
464
  }
243
465
  const regex = mode === "regex";
244
- const regexLeft = regexBudget - regexClock.usedMs;
245
- if (regex && regexLeft <= 0) {
246
- throw new Error("The time for regex searches is used up for this answer. Search with mode \"exact\" or \"keywords\" instead.");
466
+ const grep = async () => {
467
+ const regexLeft = regexBudget - regexClock.usedMs;
468
+ if (regex && regexLeft <= 0) {
469
+ throw new Error("The time for regex searches is used up for this answer. Search with mode \"exact\" or \"keywords\" instead.");
470
+ }
471
+ return grepSource(document, query, {
472
+ regex,
473
+ caseSensitive: args.case_sensitive === true,
474
+ maxResults: integer(args.max_results, 20, 1, 50),
475
+ contextLines: integer(args.context_lines, 0, 0, 5),
476
+ ...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
477
+ ...(options.signal ? { signal: options.signal } : {}),
478
+ });
479
+ };
480
+ const result = await (regex ? inRegexTurn(grep) : grep());
481
+ const placed = (match: LineMatch): LineMatch => {
482
+ if (!paged) return match;
483
+ const { line, ...rest } = match;
484
+ const page = document.pageOfLine(line);
485
+ return { line, ...(page ? { page } : {}), ...rest };
486
+ };
487
+ const base = { document: document.meta.name, mode, total_matching_lines: result.totalMatchingLines };
488
+ const matches = result.matches.map(placed);
489
+ if (!result.stoppedEarly && result.totalMatchingLines >= 2) {
490
+ // The last match is `last`, or, when every match is among the first ones, the last of them.
491
+ return result.last
492
+ ? firstAndLastMatches(base, matches, placed(result.last), result.totalMatchingLines, limit)
493
+ : firstAndLastMatches(base, matches.slice(0, -1), matches.at(-1)!, result.totalMatchingLines, limit);
247
494
  }
248
- const result = await grepSource(document, query, {
249
- regex,
250
- caseSensitive: args.case_sensitive === true,
251
- maxResults: integer(args.max_results, 20, 1, 50),
252
- contextLines: integer(args.context_lines, 0, 0, 5),
253
- ...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
254
- ...(options.signal ? { signal: options.signal } : {}),
255
- });
256
495
  return fit({
257
- document: document.meta.name,
258
- mode,
259
- total_matching_lines: result.totalMatchingLines,
260
- ...(result.stoppedEarly ? { note: "The scan stopped early; the total is a lower bound." } : {}),
261
- matches: paged ? result.matches.map(({ line, ...rest }) => {
262
- const page = document.pageOfLine(line);
263
- return { line, ...(page ? { page } : {}), ...rest };
264
- }) : result.matches,
496
+ ...base,
497
+ // The description says the last match is shown: here it is not known.
498
+ ...(result.stoppedEarly ? { note: "The scan stopped early; the total is a lower bound, and the last match in the file is not known." } : {}),
499
+ matches,
265
500
  }, "matches", limit);
266
501
  },
267
502
 
268
- async [TOOL_NAMES.read](args) {
503
+ async [TOOL_NAMES.read](args, limits) {
504
+ const limit = limitOf(limits);
269
505
  const document = await documentFor(args);
270
506
  const total = document.lineCount;
271
507
  const start = integer(args.start_line, 1, 1, total);
@@ -286,12 +522,15 @@ export function createDocumentTools(options: {
286
522
  lines: `${start}-${to}`,
287
523
  ...(pages ? { pages } : {}),
288
524
  total_lines: total,
289
- text: fits(body) ? body : body.slice(0, Math.floor((limit - 500) / 2)),
525
+ text: fits(body) ? body : sliceWhole(body, Math.floor((limit - 500) / 2)),
526
+ // One line longer than the room: its text was cut, so the lines are not all shown.
527
+ ...(fits(body) ? {} : { text_cut: true }),
290
528
  ...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
291
529
  };
292
530
  },
293
531
 
294
- async [TOOL_NAMES.overview](args) {
532
+ async [TOOL_NAMES.overview](args, limits) {
533
+ const limit = limitOf(limits);
295
534
  const document = await documentFor(args);
296
535
  const { meta, lineCount } = document;
297
536
  const tail = Math.max(1, lineCount - 19);
@@ -309,48 +548,84 @@ export function createDocumentTools(options: {
309
548
  ...(meta.pages ? { pages: meta.pages } : {}),
310
549
  parts_for_whole_document_analysis: parts,
311
550
  ...(parts > options.budget.maxMapChunks ? { whole_document_analysis: `Not available for this file: it would take about ${parts} parts, and the limit is ${options.budget.maxMapChunks}. Use search_document and read_document.` } : {}),
312
- ...(meta.logProfile ? { log_profile: meta.logProfile } : {}),
551
+ // 0.5.0 stored some log templates cut inside an emoji: half of a character is not sent.
552
+ ...(meta.logProfile ? { log_profile: wellFormedJson(meta.logProfile) } : {}),
313
553
  first_lines: numberLines(await document.readLines(1, first), 1),
314
554
  last_lines: lineCount > 30 ? numberLines(await document.readLines(tail, lineCount), tail) : "",
315
555
  outline: meta.outline.length ? outlineLines(meta.outline) : [],
316
556
  }, "outline", limit);
317
557
  },
318
558
 
319
- async [TOOL_NAMES.analyze](args) {
559
+ async [TOOL_NAMES.analyze](args, limits, hooks) {
320
560
  if (!options.generate) throw new Error("Whole-document analysis is not enabled.");
321
561
  const document = await documentFor(args);
322
562
  const task = text(args.task, "task");
323
- const result = await analyzeWholeDocument({
324
- document,
325
- task,
326
- generate: options.generate,
327
- budget: options.budget,
328
- onProgress: options.onProgress,
329
- signal: options.signal,
330
- });
563
+ // A read of the whole file is many model requests. A model that asks for it again, with the
564
+ // task put another way, is told to use what it has. The count is taken before the read
565
+ // starts, so that two calls in one turn do not both pass.
566
+ const id = document.meta.id;
567
+ const reads = wholeReads.get(id) ?? 0;
568
+ if (reads >= maxWholeReads) {
569
+ const failure = failedWholeReads.get(id);
570
+ throw new Error(maxWholeReads === 0
571
+ ? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
572
+ : failure !== undefined
573
+ // There is no answer to use: saying "use the answer of that read" would invite one made up.
574
+ ? `The whole-file read of ${document.meta.name} failed earlier in this question (${failure}), and is not tried again. Use search_document and read_document.`
575
+ : `${document.meta.name} was already read whole for this question${maxWholeReads > 1 ? ` ${maxWholeReads} times` : ""}, and is not read whole again. Use the answer of that read, or search_document and read_document for the details.`);
576
+ }
577
+ wholeReads.set(id, reads + 1);
578
+ let result;
579
+ try {
580
+ result = await analyzeWholeDocument({
581
+ document,
582
+ task,
583
+ generate: options.generate,
584
+ budget: options.budget,
585
+ // The call's own listener, when it has one, in place of the tool set's.
586
+ onProgress: hooks.onProgress ?? options.onProgress,
587
+ ...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
588
+ signal: options.signal,
589
+ ...(options.retry ? { retry: options.retry } : {}),
590
+ ...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
591
+ });
592
+ } catch (error) {
593
+ // Parts were sent and none could be read: that read is counted, since another would most
594
+ // likely fail the same way. Anything else (too many parts, a store that could not be read)
595
+ // failed before any model request: that was no read. Its count is given back, not set to
596
+ // what it was when the read started, which would take back the count of another read of
597
+ // the same document running in this turn.
598
+ if (error instanceof NothingReadError) failedWholeReads.set(id, error.reason);
599
+ else wholeReads.set(id, Math.max(0, (wholeReads.get(id) ?? 1) - 1));
600
+ throw error;
601
+ }
602
+ failedWholeReads.delete(id);
331
603
  const notesCutShort = result.truncatedParts + result.truncatedMerges;
332
- return fit({
604
+ return fitAnswer({
333
605
  document: document.meta.name,
334
606
  parts_read: result.parts,
335
607
  parts_with_relevant_content: result.relevantParts,
336
608
  ...(result.failedParts ? { parts_that_failed: result.failedParts } : {}),
337
609
  ...(notesCutShort ? { notes_cut_short: notesCutShort } : {}),
338
610
  ...(result.answerTruncated ? { answer_cut_short: true } : {}),
339
- ...(notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
611
+ ...(result.answerFailed !== undefined ? { notes_only: true } : {}),
612
+ ...(result.answerFailed !== undefined
613
+ ? { note: `The last step of this read, which writes one answer from the notes of the parts, failed (${result.answerFailed}). The answer is those notes: answer from them.${notesCutShort ? " Some of them were cut off at the output limit, so they are incomplete: tell the user." : ""}` }
614
+ : notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
340
615
  answer: result.answer,
341
- }, null, Math.max(limit, 40_000));
616
+ }, limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS)));
342
617
  },
343
618
  };
344
619
 
345
620
  /** `view_pages`: the pages as one small PDF, next to a short JSON result. */
346
- async function viewPages(args: Record<string, unknown>, limits: ToolFileLimits): Promise<ToolOutput> {
621
+ async function viewPages(args: Record<string, unknown>, limits: ToolCallLimits): Promise<ToolOutput> {
347
622
  const id = text(args.document_id, "document_id");
348
623
  // The same scope check as the text tools, on its own list: a PDF can be looked at without
349
624
  // being searchable, and the other way round.
350
625
  if (!viewable.has(id)) {
351
626
  throw new Error(allowed.has(id)
352
627
  ? `The pages of ${names.get(id) ?? id} cannot be shown: only its text was kept. Answer from the text.`
353
- : `Unknown document_id ${id}. Use the document_id of an attached PDF.`);
628
+ : `Unknown document_id ${shownId(id)}. Use the document_id of an attached PDF.`);
354
629
  }
355
630
  const document = await options.load(id);
356
631
  if (!document) throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
@@ -394,13 +669,13 @@ export function createDocumentTools(options: {
394
669
  // What a tool could not do goes to the model, and from there to a user's screen: never a server path.
395
670
  const failure = (error: unknown): ToolResult => ({ error: safeErrorMessage(error) });
396
671
 
397
- async function execute(name: string, args: Record<string, unknown>): Promise<ToolResult> {
398
- if (!known.has(name)) return { error: `Unknown tool ${name}.` };
672
+ async function execute(name: string, args: Record<string, unknown>, limits: ToolCallLimits = {}, hooks: ToolCallHooks = {}): Promise<ToolResult> {
673
+ if (!known.has(name)) return { error: `Unknown tool ${unknownToolName(name)}.` };
399
674
  // The pages are a file, and this method returns only JSON. Saying that pages are attached
400
675
  // with nothing attached would be worse than saying that they could not be shown.
401
676
  if (name === TOOL_NAMES.view) return { error: FILES_NOT_DELIVERED };
402
677
  try {
403
- return await handlers[name]!(args);
678
+ return await handlers[name]!(args, limits, hooks);
404
679
  } catch (error) {
405
680
  if (options.signal?.aborted) throw error;
406
681
  return failure(error);
@@ -410,9 +685,10 @@ export function createDocumentTools(options: {
410
685
  return {
411
686
  declarations,
412
687
  has: (name) => known.has(name),
413
- execute,
414
- async executeWithFiles(name, args, limits = {}) {
415
- if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args), files: [] };
688
+ execute: (name, args) => execute(name, args),
689
+ resultCharacters: (name) => (name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
690
+ async executeWithFiles(name, args, limits = {}, hooks = {}) {
691
+ if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args, limits, hooks), files: [] };
416
692
  try {
417
693
  return await viewPages(args, limits);
418
694
  } catch (error) {
@@ -431,7 +707,7 @@ export function createDocumentTools(options: {
431
707
  }
432
708
  if (name === TOOL_NAMES.search) {
433
709
  const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
434
- return `Search ${file} (${mode}) for “${String(args.query ?? "").slice(0, 80)}”`;
710
+ return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”`;
435
711
  }
436
712
  if (name === TOOL_NAMES.read) {
437
713
  const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
@@ -439,7 +715,7 @@ export function createDocumentTools(options: {
439
715
  return `Read ${file} lines ${start}${end}`;
440
716
  }
441
717
  if (name === TOOL_NAMES.overview) return `Overview of ${file}`;
442
- if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${String(args.task ?? "").slice(0, 100)}”`;
718
+ if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”`;
443
719
  return name;
444
720
  },
445
721
  };