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/dist/tools.js CHANGED
@@ -1,19 +1,30 @@
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
4
  import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS } from "./search.js";
5
5
  import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
6
+ import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
6
7
  const DEFAULT_READ_LINES = 200;
7
8
  const MAX_READ_LINES = 600;
8
9
  /** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
9
10
  export const MAX_VIEW_PAGES = 5;
10
11
  /**
11
- * The time the regex searches of one tool set (one question, in `askGemini`) may take together,
12
+ * The time the regex searches of one tool set (one question, in `askWithFiles`) may take together,
12
13
  * unless `regexBudgetMs` says otherwise. An ordinary search of a 60 MB log takes about 0.15 s.
13
14
  */
14
15
  export const REGEX_BUDGET_MS = 6_000;
15
16
  /** Below this, no page fits: a cut of one page of plain text is larger. */
16
17
  const MIN_FILE_BYTES = 1_024;
18
+ /** The answer of a whole-document read may be this long, when the cap on tool results is lower. */
19
+ const ANALYSIS_RESULT_CHARACTERS = 40_000;
20
+ /** A result is never cut below this, whatever room a caller names: less holds no line of a file. */
21
+ export const LEAST_RESULT_CHARACTERS = 600;
22
+ /**
23
+ * How many times one document is read whole by the tools of one tool set (one question, in
24
+ * `askWithFiles`), unless `maxWholeDocumentReads` says otherwise. One read of a large file is
25
+ * up to `maxMapChunks` model requests.
26
+ */
27
+ export const MAX_WHOLE_DOCUMENT_READS = 1;
17
28
  export const TOOL_NAMES = {
18
29
  search: "search_document",
19
30
  read: "read_document",
@@ -25,7 +36,7 @@ const documentId = { type: "string", description: "The document_id from the file
25
36
  const DECLARATIONS = {
26
37
  search: {
27
38
  name: TOOL_NAMES.search,
28
- 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.",
39
+ 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.",
29
40
  parameters: {
30
41
  type: "object",
31
42
  properties: {
@@ -59,7 +70,7 @@ const DECLARATIONS = {
59
70
  },
60
71
  analyze: {
61
72
  name: TOOL_NAMES.analyze,
62
- 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.",
73
+ 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.",
63
74
  parameters: {
64
75
  type: "object",
65
76
  properties: {
@@ -104,14 +115,18 @@ function pageNumber(value, name) {
104
115
  return Math.trunc(number);
105
116
  }
106
117
  const pageRange = (from, to) => (to > from ? `${from}-${to}` : String(from));
107
- /** Trims a result to the character budget by dropping trailing list entries, then cutting text. */
118
+ /**
119
+ * Trims a result to the character budget by dropping trailing list entries, then cutting text. A
120
+ * note the result already has (a search that stopped early) is kept, before the one that says so.
121
+ */
108
122
  function fit(result, listKey, limit) {
109
123
  if (JSON.stringify(result).length <= limit)
110
124
  return result;
111
125
  const list = listKey ? result[listKey] : undefined;
112
126
  if (Array.isArray(list)) {
113
127
  const kept = [...list];
114
- const note = () => `Showing ${kept.length} of ${list.length} results to stay within the size limit. Narrow the query or read specific lines.`;
128
+ const before = typeof result.note === "string" ? `${result.note} ` : "";
129
+ const note = () => `${before}Showing ${kept.length} of ${list.length} results to stay within the size limit. Narrow the query or read specific lines.`;
115
130
  const trimmed = () => ({ ...result, [listKey]: kept, note: note() });
116
131
  while (kept.length > 1 && JSON.stringify(trimmed()).length > limit)
117
132
  kept.pop();
@@ -124,10 +139,171 @@ function fit(result, listKey, limit) {
124
139
  let cut;
125
140
  do {
126
141
  size = Math.floor(size * 0.85);
127
- cut = { truncated: true, partial: serialized.slice(0, size), note: "Result cut to the size limit. Ask for a smaller range." };
142
+ cut = { truncated: true, partial: sliceWhole(serialized, size), note: "Result cut to the size limit. Ask for a smaller range." };
128
143
  } while (JSON.stringify(cut).length > limit && size > 100);
129
144
  return cut;
130
145
  }
146
+ /**
147
+ * The result of a whole-document read within `limit` characters: its answer is cut at the end,
148
+ * and says so, rather than the result being cut as JSON, which loses what the other fields say.
149
+ */
150
+ export function fitAnswer(result, limit) {
151
+ if (JSON.stringify(result).length <= limit || typeof result.answer !== "string")
152
+ return fit(result, null, limit);
153
+ const answer = result.answer;
154
+ const cutAt = (keep) => ({
155
+ ...result,
156
+ answer: `${sliceWhole(answer, keep)}…`,
157
+ answer_shortened: "The rest of this answer did not fit in the room left in this conversation.",
158
+ });
159
+ // The longest start of the answer that fits. Escapes (quotes, line breaks) make the JSON longer
160
+ // than the text by as much as the text holds of them, so it is found by halving, not worked out.
161
+ let low = 0;
162
+ let high = answer.length;
163
+ while (low < high) {
164
+ const middle = Math.ceil((low + high) / 2);
165
+ if (JSON.stringify(cutAt(middle)).length <= limit)
166
+ low = middle;
167
+ else
168
+ high = middle - 1;
169
+ }
170
+ return fit(cutAt(low), null, limit);
171
+ }
172
+ /**
173
+ * The result of an exact or regex search that read the whole file: the first matches, then the
174
+ * last one of the file, and a note that says how many of how many are shown when that is not all.
175
+ * Without the last one, a model asked when something last happened named the last line it was
176
+ * shown. To fit `limit`, matches are dropped from the end of the first ones: the last one stays.
177
+ */
178
+ function firstAndLastMatches(base, first, last, total, limit) {
179
+ const which = (kept) => (kept === 0 ? `the last (line ${last.line})` : `the first${kept > 1 ? ` ${kept}` : ""} and the last (line ${last.line})`);
180
+ const shown = (kept) => `${kept + 1} of the ${total} matching lines`;
181
+ const withFirst = (kept, cut) => ({
182
+ ...base,
183
+ ...(cut
184
+ ? { note: `Showing ${shown(kept)} to stay within the size limit: ${which(kept)}. Narrow the query or read specific lines.` }
185
+ // When every match is shown, there is nothing to say.
186
+ : kept + 1 < total ? { note: `${shown(kept)} are shown: ${which(kept)}. To see the ones in between, narrow the search.` } : {}),
187
+ matches: [...first.slice(0, kept), last],
188
+ });
189
+ const whole = withFirst(first.length, false);
190
+ if (JSON.stringify(whole).length <= limit)
191
+ return whole;
192
+ let kept = first.length;
193
+ while (kept > 0 && JSON.stringify(withFirst(kept, true)).length > limit)
194
+ kept--;
195
+ const cut = withFirst(kept, true);
196
+ if (JSON.stringify(cut).length <= limit)
197
+ return cut;
198
+ // Only the last match is left, and its note is too long for the room: a shorter one. It still
199
+ // starts with "Showing ", so the result is taken as cut. `fit` must not put its own note in its
200
+ // place, which would say "1 of 1 results" and drop the line of the last match. When even this
201
+ // does not fit, `fit` cuts the result as text: the note, with that line, comes before the match.
202
+ const lastOnly = { ...base, note: `Showing 1 of the ${total} matching lines: ${which(0)}. Narrow the search.`, matches: [last] };
203
+ return fit(lastOnly, null, limit);
204
+ }
205
+ const searchMode = (mode) => (mode === "exact" || mode === "regex" ? mode : "keywords");
206
+ /** The lines a `read_document` call asks for, as its handler reads them, before the end of the file is known. */
207
+ function requestedLines(args) {
208
+ const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
209
+ return [start, integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, start + MAX_READ_LINES - 1)];
210
+ }
211
+ /**
212
+ * A call's arguments as its tool reads them, with the defaults filled in: two calls with the same
213
+ * key get the same result from a file that has not changed. Undefined for a tool whose calls are
214
+ * not compared (a whole-file read has a count of its own; a look at pages returns a file).
215
+ */
216
+ export function toolCallKey(name, args) {
217
+ const id = typeof args.document_id === "string" && args.document_id ? args.document_id : undefined;
218
+ if (!id)
219
+ return undefined;
220
+ if (name === TOOL_NAMES.search) {
221
+ if (typeof args.query !== "string" || !args.query.trim())
222
+ return undefined;
223
+ const mode = searchMode(args.mode);
224
+ return JSON.stringify(mode === "keywords"
225
+ ? [name, id, args.query, mode, integer(args.max_results, 5, 1, 10)]
226
+ : [name, id, args.query, mode, integer(args.max_results, 20, 1, 50), integer(args.context_lines, 0, 0, 5), args.case_sensitive === true]);
227
+ }
228
+ if (name === TOOL_NAMES.read)
229
+ return JSON.stringify([name, id, ...requestedLines(args)]);
230
+ if (name === TOOL_NAMES.overview)
231
+ return JSON.stringify([name, id]);
232
+ return undefined;
233
+ }
234
+ /**
235
+ * When an earlier call's result already holds all that `call` would return, and is still in the
236
+ * conversation in full: a short result that says so, in place of running the call again. A result
237
+ * that was cut to the room it had, or replaced by a stand-in, or failed, is not pointed to: the call
238
+ * is run, and may get more. A read of lines inside a read that is shown in full is pointed to.
239
+ * `stored` is true for a result in the tool rounds of an earlier question, which an older version
240
+ * may have written: 0.5.0 cut the text of a read of one long line without saying so (no
241
+ * `text_cut`), so a read of one line from there is not taken as shown in full.
242
+ */
243
+ export function alreadyShown(call, earlier, stored = false) {
244
+ const { result } = earlier;
245
+ if (earlier.call.name !== call.name || earlier.call.args.document_id !== call.args.document_id)
246
+ return undefined;
247
+ if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true)
248
+ return undefined;
249
+ // A list that `fit` cut to the room it had, a read whose text was cut, or a search that ran out of
250
+ // time ("the total is a lower bound"; a later question has time of its own): a call made now may get more.
251
+ if (typeof result.note === "string" && (result.note.startsWith("Showing ") || result.note.startsWith("The scan stopped early")))
252
+ return undefined;
253
+ if (result.text_cut === true)
254
+ 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")
259
+ return undefined;
260
+ const document = typeof result.document === "string" ? { document: result.document } : {};
261
+ if (call.name === TOOL_NAMES.read) {
262
+ const shown = typeof result.lines === "string" ? /^(\d+)-(\d+)$/.exec(result.lines) : null;
263
+ const total = result.total_lines;
264
+ if (!shown || typeof total !== "number")
265
+ return undefined;
266
+ const [first, last] = [Number(shown[1]), Number(shown[2])];
267
+ if (stored && first === last)
268
+ return undefined;
269
+ const [start, end] = requestedLines(call.args);
270
+ const from = Math.min(start, total);
271
+ const to = Math.min(end, total);
272
+ if (from < first || to > last)
273
+ return undefined;
274
+ return {
275
+ ...document,
276
+ lines: `${from}-${to}`,
277
+ already_shown: true,
278
+ 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.`,
279
+ };
280
+ }
281
+ const key = toolCallKey(call.name, call.args);
282
+ if (key === undefined || key !== toolCallKey(earlier.call.name, earlier.call.args))
283
+ return undefined;
284
+ return {
285
+ ...document,
286
+ already_shown: true,
287
+ 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.",
288
+ };
289
+ }
290
+ /**
291
+ * A hint added to the error of a search that failed twice in a row in the same mode, so that the
292
+ * model tries another way instead of sending the same kind of call a third time.
293
+ */
294
+ export function repeatedFailureHint(call) {
295
+ return searchMode(call.args.mode) === "regex"
296
+ ? "Two regex searches in a row failed. Try mode \"exact\" with a plain word or ID from the file, or mode \"keywords\"."
297
+ : "This search failed twice in a row. Check the arguments against the tool's description, or answer from what you have.";
298
+ }
299
+ /**
300
+ * The tool and mode of a search, to tell whether two failures in a row were of the same kind.
301
+ * Undefined for the other tools: their errors say what to do (a whole-file read that is not made
302
+ * again, a page that does not exist), and a hint would only blur that.
303
+ */
304
+ export function failureKind(call) {
305
+ return call.name === TOOL_NAMES.search ? `${call.name}|${searchMode(call.args.mode)}` : undefined;
306
+ }
131
307
  /**
132
308
  * What a finished tool call found, as a suffix for its `describe()` label, for a steps list:
133
309
  * "Search app.log (exact) for “timeout”" + " — 12 matching lines".
@@ -135,13 +311,14 @@ function fit(result, listKey, limit) {
135
311
  export function toolResultSummary(label, result) {
136
312
  if (typeof result.error === "string")
137
313
  return ` — failed: ${result.error}`;
138
- if (typeof result.total_matching_lines === "number")
139
- return ` — ${result.total_matching_lines.toLocaleString("en-US")} matching lines`;
314
+ if (typeof result.total_matching_lines === "number") {
315
+ return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}`;
316
+ }
140
317
  if (Array.isArray(result.passages))
141
- return ` — ${result.passages.length} passages`;
318
+ return ` — ${result.passages.length} ${plural(result.passages.length, "passage")}`;
142
319
  if (typeof result.parts_read === "number") {
143
- const incomplete = result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
144
- return ` — ${result.parts_read} parts, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
320
+ const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
321
+ return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
145
322
  }
146
323
  // A read reports its range only when it was cut short of what was asked.
147
324
  if (typeof result.lines === "string" && typeof result.total_lines === "number")
@@ -152,6 +329,28 @@ export function toolResultSummary(label, result) {
152
329
  }
153
330
  return "";
154
331
  }
332
+ /**
333
+ * A step, or a label of one, as one line of plain text. Steps quote what the model sent (a query, a
334
+ * task, the name of a tool, arguments that were not JSON), and they reach users' screens: the
335
+ * invisible characters that file text and names lose are dropped (`removeInvisible`: text-direction
336
+ * overrides and isolates, zero-width spaces, tag characters), a line break, a tab or another control
337
+ * character becomes one space with the blanks around it, and "](" gets a space, so that a markdown
338
+ * link or picture in a query stays text. A line without them is unchanged.
339
+ */
340
+ export function stepLine(text) {
341
+ // Each control character, tab and line break is a "\n" first, which `removeInvisible` keeps (it
342
+ // would drop the others): an invisible character between two of them then leaves one space, not
343
+ // two. A soft hyphen it keeps before one goes too. Then a run of blanks with a "\n" in it is one space.
344
+ const marked = removeInvisible(text.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, "\n")).replace(/\xAD+(?=\n)/g, "");
345
+ return marked.replace(/\s+/g, (blank) => (blank.includes("\n") ? " " : blank)).replaceAll("](", "] (");
346
+ }
347
+ /** An unknown tool's name as a step or an error quotes it: the model chose it, at any length. */
348
+ export const unknownToolName = (name) => `“${sliceWhole(name, 64)}”`;
349
+ /**
350
+ * A document_id the model sent, as an error quotes it: whole when it is as long as a real one can
351
+ * be, cut otherwise. The model chose it, at any length, and the error goes into steps too.
352
+ */
353
+ const shownId = (id) => (id.length > 64 ? `${sliceWhole(id, 64)}…` : id);
155
354
  export function createDocumentTools(options) {
156
355
  const allowed = new Set(options.documentIds);
157
356
  const viewable = new Set(options.loadOriginal ? options.viewableIds ?? [] : []);
@@ -166,18 +365,41 @@ export function createDocumentTools(options) {
166
365
  // Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
167
366
  if (textTools && options.generate)
168
367
  known.add(TOOL_NAMES.analyze);
169
- const limit = options.budget.toolResultCharacters;
368
+ const cap = options.budget.toolResultCharacters;
369
+ /** The cap on the result of one call: the tool set's own, or the room its caller has left when that is less. */
370
+ const limitOf = (limits, own = cap) => {
371
+ const room = limits.maxResultCharacters;
372
+ return typeof room === "number" && Number.isFinite(room) ? Math.max(LEAST_RESULT_CHARACTERS, Math.min(own, Math.trunc(room))) : own;
373
+ };
170
374
  // The model writes the regex, and a file it reads can ask for a slow one: the time is counted
171
375
  // over every search of this tool set, not only within one.
172
376
  const regexBudget = Math.max(0, options.regexBudgetMs ?? REGEX_BUDGET_MS);
173
377
  const regexClock = { usedMs: 0 };
378
+ // Calls of one turn may run together. Regex searches still take their turns, one after another:
379
+ // each must know how much of the time the ones before it used.
380
+ let regexQueue = Promise.resolve();
381
+ const inRegexTurn = (run) => {
382
+ const next = regexQueue.then(run, run);
383
+ regexQueue = next.catch(() => undefined);
384
+ return next;
385
+ };
386
+ const maxWholeReads = Math.max(0, Math.trunc(options.maxWholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS));
387
+ /** Whole-document reads started, by document. */
388
+ const wholeReads = new Map();
389
+ /** Why the last whole-document read of a document failed, when no part of it could be read. */
390
+ const failedWholeReads = new Map();
174
391
  // When no limit is given with a call: three eighths of a request, so that two looks still fit.
175
392
  const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
176
393
  async function documentFor(args) {
177
394
  const id = text(args.document_id, "document_id");
178
395
  // Scope check: a model can only reach files attached to this conversation.
179
- if (!allowed.has(id))
180
- throw new Error(`Unknown document_id ${id}. Use an ID from a file card.`);
396
+ if (!allowed.has(id)) {
397
+ // The IDs it may use, with their file names, so that the next call is right.
398
+ const usable = [...allowed].slice(0, 20).map((known) => `${known}${names.has(known) ? ` (${JSON.stringify(names.get(known))})` : ""}`);
399
+ throw new Error(usable.length === 0
400
+ ? `Unknown document_id ${shownId(id)}. No attached file is read with this tool in this conversation.`
401
+ : `Unknown document_id ${shownId(id)}. Use one of: ${usable.join(", ")}${allowed.size > 20 ? ", …" : ""}.`);
402
+ }
181
403
  const document = await options.load(id);
182
404
  if (!document)
183
405
  throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
@@ -185,7 +407,8 @@ export function createDocumentTools(options) {
185
407
  return document;
186
408
  }
187
409
  const handlers = {
188
- async [TOOL_NAMES.search](args) {
410
+ async [TOOL_NAMES.search](args, limits) {
411
+ const limit = limitOf(limits);
189
412
  const document = await documentFor(args);
190
413
  const query = text(args.query, "query");
191
414
  const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
@@ -212,30 +435,45 @@ export function createDocumentTools(options) {
212
435
  }, "passages", limit);
213
436
  }
214
437
  const regex = mode === "regex";
215
- const regexLeft = regexBudget - regexClock.usedMs;
216
- if (regex && regexLeft <= 0) {
217
- throw new Error("The time for regex searches is used up for this answer. Search with mode \"exact\" or \"keywords\" instead.");
438
+ const grep = async () => {
439
+ const regexLeft = regexBudget - regexClock.usedMs;
440
+ if (regex && regexLeft <= 0) {
441
+ throw new Error("The time for regex searches is used up for this answer. Search with mode \"exact\" or \"keywords\" instead.");
442
+ }
443
+ return grepSource(document, query, {
444
+ regex,
445
+ caseSensitive: args.case_sensitive === true,
446
+ maxResults: integer(args.max_results, 20, 1, 50),
447
+ contextLines: integer(args.context_lines, 0, 0, 5),
448
+ ...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
449
+ ...(options.signal ? { signal: options.signal } : {}),
450
+ });
451
+ };
452
+ const result = await (regex ? inRegexTurn(grep) : grep());
453
+ const placed = (match) => {
454
+ if (!paged)
455
+ return match;
456
+ const { line, ...rest } = match;
457
+ const page = document.pageOfLine(line);
458
+ return { line, ...(page ? { page } : {}), ...rest };
459
+ };
460
+ const base = { document: document.meta.name, mode, total_matching_lines: result.totalMatchingLines };
461
+ const matches = result.matches.map(placed);
462
+ if (!result.stoppedEarly && result.totalMatchingLines >= 2) {
463
+ // The last match is `last`, or, when every match is among the first ones, the last of them.
464
+ return result.last
465
+ ? firstAndLastMatches(base, matches, placed(result.last), result.totalMatchingLines, limit)
466
+ : firstAndLastMatches(base, matches.slice(0, -1), matches.at(-1), result.totalMatchingLines, limit);
218
467
  }
219
- const result = await grepSource(document, query, {
220
- regex,
221
- caseSensitive: args.case_sensitive === true,
222
- maxResults: integer(args.max_results, 20, 1, 50),
223
- contextLines: integer(args.context_lines, 0, 0, 5),
224
- ...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
225
- ...(options.signal ? { signal: options.signal } : {}),
226
- });
227
468
  return fit({
228
- document: document.meta.name,
229
- mode,
230
- total_matching_lines: result.totalMatchingLines,
231
- ...(result.stoppedEarly ? { note: "The scan stopped early; the total is a lower bound." } : {}),
232
- matches: paged ? result.matches.map(({ line, ...rest }) => {
233
- const page = document.pageOfLine(line);
234
- return { line, ...(page ? { page } : {}), ...rest };
235
- }) : result.matches,
469
+ ...base,
470
+ // The description says the last match is shown: here it is not known.
471
+ ...(result.stoppedEarly ? { note: "The scan stopped early; the total is a lower bound, and the last match in the file is not known." } : {}),
472
+ matches,
236
473
  }, "matches", limit);
237
474
  },
238
- async [TOOL_NAMES.read](args) {
475
+ async [TOOL_NAMES.read](args, limits) {
476
+ const limit = limitOf(limits);
239
477
  const document = await documentFor(args);
240
478
  const total = document.lineCount;
241
479
  const start = integer(args.start_line, 1, 1, total);
@@ -256,11 +494,14 @@ export function createDocumentTools(options) {
256
494
  lines: `${start}-${to}`,
257
495
  ...(pages ? { pages } : {}),
258
496
  total_lines: total,
259
- text: fits(body) ? body : body.slice(0, Math.floor((limit - 500) / 2)),
497
+ text: fits(body) ? body : sliceWhole(body, Math.floor((limit - 500) / 2)),
498
+ // One line longer than the room: its text was cut, so the lines are not all shown.
499
+ ...(fits(body) ? {} : { text_cut: true }),
260
500
  ...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
261
501
  };
262
502
  },
263
- async [TOOL_NAMES.overview](args) {
503
+ async [TOOL_NAMES.overview](args, limits) {
504
+ const limit = limitOf(limits);
264
505
  const document = await documentFor(args);
265
506
  const { meta, lineCount } = document;
266
507
  const tail = Math.max(1, lineCount - 19);
@@ -278,36 +519,75 @@ export function createDocumentTools(options) {
278
519
  ...(meta.pages ? { pages: meta.pages } : {}),
279
520
  parts_for_whole_document_analysis: parts,
280
521
  ...(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.` } : {}),
281
- ...(meta.logProfile ? { log_profile: meta.logProfile } : {}),
522
+ // 0.5.0 stored some log templates cut inside an emoji: half of a character is not sent.
523
+ ...(meta.logProfile ? { log_profile: wellFormedJson(meta.logProfile) } : {}),
282
524
  first_lines: numberLines(await document.readLines(1, first), 1),
283
525
  last_lines: lineCount > 30 ? numberLines(await document.readLines(tail, lineCount), tail) : "",
284
526
  outline: meta.outline.length ? outlineLines(meta.outline) : [],
285
527
  }, "outline", limit);
286
528
  },
287
- async [TOOL_NAMES.analyze](args) {
529
+ async [TOOL_NAMES.analyze](args, limits, hooks) {
288
530
  if (!options.generate)
289
531
  throw new Error("Whole-document analysis is not enabled.");
290
532
  const document = await documentFor(args);
291
533
  const task = text(args.task, "task");
292
- const result = await analyzeWholeDocument({
293
- document,
294
- task,
295
- generate: options.generate,
296
- budget: options.budget,
297
- onProgress: options.onProgress,
298
- signal: options.signal,
299
- });
534
+ // A read of the whole file is many model requests. A model that asks for it again, with the
535
+ // task put another way, is told to use what it has. The count is taken before the read
536
+ // starts, so that two calls in one turn do not both pass.
537
+ const id = document.meta.id;
538
+ const reads = wholeReads.get(id) ?? 0;
539
+ if (reads >= maxWholeReads) {
540
+ const failure = failedWholeReads.get(id);
541
+ throw new Error(maxWholeReads === 0
542
+ ? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
543
+ : failure !== undefined
544
+ // There is no answer to use: saying "use the answer of that read" would invite one made up.
545
+ ? `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.`
546
+ : `${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.`);
547
+ }
548
+ wholeReads.set(id, reads + 1);
549
+ let result;
550
+ try {
551
+ result = await analyzeWholeDocument({
552
+ document,
553
+ task,
554
+ generate: options.generate,
555
+ budget: options.budget,
556
+ // The call's own listener, when it has one, in place of the tool set's.
557
+ onProgress: hooks.onProgress ?? options.onProgress,
558
+ ...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
559
+ signal: options.signal,
560
+ ...(options.retry ? { retry: options.retry } : {}),
561
+ ...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
562
+ });
563
+ }
564
+ catch (error) {
565
+ // Parts were sent and none could be read: that read is counted, since another would most
566
+ // likely fail the same way. Anything else (too many parts, a store that could not be read)
567
+ // failed before any model request: that was no read. Its count is given back, not set to
568
+ // what it was when the read started, which would take back the count of another read of
569
+ // the same document running in this turn.
570
+ if (error instanceof NothingReadError)
571
+ failedWholeReads.set(id, error.reason);
572
+ else
573
+ wholeReads.set(id, Math.max(0, (wholeReads.get(id) ?? 1) - 1));
574
+ throw error;
575
+ }
576
+ failedWholeReads.delete(id);
300
577
  const notesCutShort = result.truncatedParts + result.truncatedMerges;
301
- return fit({
578
+ return fitAnswer({
302
579
  document: document.meta.name,
303
580
  parts_read: result.parts,
304
581
  parts_with_relevant_content: result.relevantParts,
305
582
  ...(result.failedParts ? { parts_that_failed: result.failedParts } : {}),
306
583
  ...(notesCutShort ? { notes_cut_short: notesCutShort } : {}),
307
584
  ...(result.answerTruncated ? { answer_cut_short: true } : {}),
308
- ...(notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
585
+ ...(result.answerFailed !== undefined ? { notes_only: true } : {}),
586
+ ...(result.answerFailed !== undefined
587
+ ? { 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." : ""}` }
588
+ : notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
309
589
  answer: result.answer,
310
- }, null, Math.max(limit, 40_000));
590
+ }, limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS)));
311
591
  },
312
592
  };
313
593
  /** `view_pages`: the pages as one small PDF, next to a short JSON result. */
@@ -318,7 +598,7 @@ export function createDocumentTools(options) {
318
598
  if (!viewable.has(id)) {
319
599
  throw new Error(allowed.has(id)
320
600
  ? `The pages of ${names.get(id) ?? id} cannot be shown: only its text was kept. Answer from the text.`
321
- : `Unknown document_id ${id}. Use the document_id of an attached PDF.`);
601
+ : `Unknown document_id ${shownId(id)}. Use the document_id of an attached PDF.`);
322
602
  }
323
603
  const document = await options.load(id);
324
604
  if (!document)
@@ -367,15 +647,15 @@ export function createDocumentTools(options) {
367
647
  }
368
648
  // What a tool could not do goes to the model, and from there to a user's screen: never a server path.
369
649
  const failure = (error) => ({ error: safeErrorMessage(error) });
370
- async function execute(name, args) {
650
+ async function execute(name, args, limits = {}, hooks = {}) {
371
651
  if (!known.has(name))
372
- return { error: `Unknown tool ${name}.` };
652
+ return { error: `Unknown tool ${unknownToolName(name)}.` };
373
653
  // The pages are a file, and this method returns only JSON. Saying that pages are attached
374
654
  // with nothing attached would be worse than saying that they could not be shown.
375
655
  if (name === TOOL_NAMES.view)
376
656
  return { error: FILES_NOT_DELIVERED };
377
657
  try {
378
- return await handlers[name](args);
658
+ return await handlers[name](args, limits, hooks);
379
659
  }
380
660
  catch (error) {
381
661
  if (options.signal?.aborted)
@@ -386,10 +666,11 @@ export function createDocumentTools(options) {
386
666
  return {
387
667
  declarations,
388
668
  has: (name) => known.has(name),
389
- execute,
390
- async executeWithFiles(name, args, limits = {}) {
669
+ execute: (name, args) => execute(name, args),
670
+ resultCharacters: (name) => (name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
671
+ async executeWithFiles(name, args, limits = {}, hooks = {}) {
391
672
  if (name !== TOOL_NAMES.view || !known.has(name))
392
- return { result: await execute(name, args), files: [] };
673
+ return { result: await execute(name, args, limits, hooks), files: [] };
393
674
  try {
394
675
  return await viewPages(args, limits);
395
676
  }
@@ -410,7 +691,7 @@ export function createDocumentTools(options) {
410
691
  }
411
692
  if (name === TOOL_NAMES.search) {
412
693
  const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
413
- return `Search ${file} (${mode}) for “${String(args.query ?? "").slice(0, 80)}”`;
694
+ return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”`;
414
695
  }
415
696
  if (name === TOOL_NAMES.read) {
416
697
  const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
@@ -420,7 +701,7 @@ export function createDocumentTools(options) {
420
701
  if (name === TOOL_NAMES.overview)
421
702
  return `Overview of ${file}`;
422
703
  if (name === TOOL_NAMES.analyze)
423
- return `Read all of ${file} for “${String(args.task ?? "").slice(0, 100)}”`;
704
+ return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”`;
424
705
  return name;
425
706
  },
426
707
  };