llm-large-files 0.5.0 → 0.8.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 (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
package/src/tools.ts CHANGED
@@ -1,17 +1,25 @@
1
1
  import { safeErrorMessage } from "./errors.js";
2
- import { analyzeWholeDocument, TooManyPartsError } from "./map-reduce.js";
2
+ import { GROUP_BY_VALUES, MAX_GROUP_KEYS, type GroupBy, type GroupResult } from "./groups.js";
3
+ import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
3
4
  import { cutPdfPages } from "./pdf-pages.js";
4
- import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource } from "./search.js";
5
+ import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource, type LineMatch } from "./search.js";
5
6
  import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
6
7
  import type { RetryOptions } from "./retry.js";
7
- import type { Budget, GenerateText, ProgressListener, ToolCallLimits, ToolDeclaration, ToolOutput, ToolResult, ToolSet } from "./types.js";
8
+ import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
9
+ import type { Budget, GenerateText, ProgressListener, ToolCallHooks, ToolCallLimits, ToolDeclaration, ToolOutput, ToolResult, ToolSet } from "./types.js";
8
10
 
9
11
  const DEFAULT_READ_LINES = 200;
12
+ /** Matching lines an exact or regex search shows: the default, and the most a call may ask for. */
13
+ const DEFAULT_GREP_RESULTS = 20;
14
+ const MAX_GREP_RESULTS = 50;
15
+ /** Groups a search with `group_by` shows: the default, and the most a call may ask for. */
16
+ const DEFAULT_GROUPS = 50;
17
+ const MAX_GROUPS = 200;
10
18
  const MAX_READ_LINES = 600;
11
19
  /** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
12
20
  export const MAX_VIEW_PAGES = 5;
13
21
  /**
14
- * The time the regex searches of one tool set (one question, in `askGemini`) may take together,
22
+ * The time the regex searches of one tool set (one question, in `askWithFiles`) may take together,
15
23
  * unless `regexBudgetMs` says otherwise. An ordinary search of a 60 MB log takes about 0.15 s.
16
24
  */
17
25
  export const REGEX_BUDGET_MS = 6_000;
@@ -20,7 +28,7 @@ const MIN_FILE_BYTES = 1_024;
20
28
  /** The answer of a whole-document read may be this long, when the cap on tool results is lower. */
21
29
  const ANALYSIS_RESULT_CHARACTERS = 40_000;
22
30
  /** A result is never cut below this, whatever room a caller names: less holds no line of a file. */
23
- const LEAST_RESULT_CHARACTERS = 600;
31
+ export const LEAST_RESULT_CHARACTERS = 600;
24
32
  /**
25
33
  * How many times one document is read whole by the tools of one tool set (one question, in
26
34
  * `askWithFiles`), unless `maxWholeDocumentReads` says otherwise. One read of a large file is
@@ -41,16 +49,21 @@ const documentId = { type: "string" as const, description: "The document_id from
41
49
  const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
42
50
  search: {
43
51
  name: TOOL_NAMES.search,
44
- 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.",
52
+ 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 (\\w and \\b know the letters of every language). 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; search again from next_from_line for the ones after those shown, or with order \"last\" for the last ones. To count by group (per hour or day, per error code, per message shape), pass group_by: the result then counts each group, and shows no lines. from_line and to_line search part of the file. Results include line numbers to read further with read_document.",
45
53
  parameters: {
46
54
  type: "object",
47
55
  properties: {
48
56
  document_id: documentId,
49
57
  query: { type: "string", description: "Keywords, exact text, or a regex, depending on mode." },
50
58
  mode: { type: "string", enum: ["keywords", "exact", "regex"], description: "Defaults to keywords." },
51
- max_results: { type: "integer", description: "Up to 50 for exact/regex (default 20), up to 10 passages for keywords (default 5)." },
59
+ max_results: { type: "integer", description: `Up to ${MAX_GREP_RESULTS} for exact/regex (default ${DEFAULT_GREP_RESULTS}), up to ${MAX_GROUPS} groups with group_by (default ${DEFAULT_GROUPS}), up to 10 passages for keywords (default 5).` },
52
60
  context_lines: { type: "integer", description: "exact/regex only: lines to show before and after each match, 0-5." },
53
61
  case_sensitive: { type: "boolean", description: "exact/regex only. Defaults to false." },
62
+ from_line: { type: "integer", description: "Search only from this line on (1-based). Pass a result's next_from_line to see the matches after those it shows." },
63
+ to_line: { type: "integer", description: "Search only up to this line." },
64
+ order: { type: "string", enum: ["first", "last"], description: "exact/regex only: \"last\" shows the last max_results matching lines (in file order) instead of the first. Defaults to \"first\"." },
65
+ group_by: { type: "string", enum: [...GROUP_BY_VALUES], description: "exact/regex only: count the matching lines by group instead of showing them. \"capture\": by the text of the regex's first (group); \"minute\", \"hour\", \"day\": by the timestamp on the line; \"shape\": by the line with its numbers, IDs and quoted values taken out." },
66
+ whole_word: { type: "boolean", description: "exact only: match the text only as a whole word, not inside a longer one. Defaults to false." },
54
67
  },
55
68
  required: ["document_id", "query"],
56
69
  },
@@ -75,7 +88,7 @@ const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
75
88
  },
76
89
  analyze: {
77
90
  name: TOOL_NAMES.analyze,
78
- 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.",
91
+ 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.",
79
92
  parameters: {
80
93
  type: "object",
81
94
  properties: {
@@ -109,6 +122,16 @@ function integer(value: unknown, fallback: number, min: number, max: number): nu
109
122
  return Math.min(max, Math.max(min, Math.trunc(Number.isFinite(number) ? number : fallback)));
110
123
  }
111
124
 
125
+ /**
126
+ * A boolean given by the model: on for `true`, and for "true" (in any case) or 1, as a number or as
127
+ * text. A model sometimes sends a boolean as text, as it does numbers; read as off, "true" gave
128
+ * another search than true without a word about it. Anything else is off.
129
+ */
130
+ function flag(value: unknown): boolean {
131
+ if (value === true || value === 1) return true;
132
+ return typeof value === "string" && /^\s*(?:true|1)\s*$/i.test(value);
133
+ }
134
+
112
135
  const INCOMPLETE_ANALYSIS = "Incomplete: the model's output limit was reached, so some relevant items are missing from this answer. Tell the user it is incomplete. For a complete list or an exact count, use search_document in exact or regex mode (it returns total_matching_lines), or ask about a narrower part of the file.";
113
136
 
114
137
  function text(value: unknown, name: string): string {
@@ -125,13 +148,17 @@ function pageNumber(value: unknown, name: string): number {
125
148
 
126
149
  const pageRange = (from: number, to: number): string => (to > from ? `${from}-${to}` : String(from));
127
150
 
128
- /** Trims a result to the character budget by dropping trailing list entries, then cutting text. */
151
+ /**
152
+ * Trims a result to the character budget by dropping trailing list entries, then cutting text. A
153
+ * note the result already has (a search that stopped early) is kept, before the one that says so.
154
+ */
129
155
  function fit(result: ToolResult, listKey: string | null, limit: number): ToolResult {
130
156
  if (JSON.stringify(result).length <= limit) return result;
131
157
  const list = listKey ? result[listKey] : undefined;
132
158
  if (Array.isArray(list)) {
133
159
  const kept = [...list];
134
- const note = () => `Showing ${kept.length} of ${list.length} results to stay within the size limit. Narrow the query or read specific lines.`;
160
+ const before = typeof result.note === "string" ? `${result.note} ` : "";
161
+ const note = () => `${before}Showing ${kept.length} of ${list.length} results to stay within the size limit. Narrow the query or read specific lines.`;
135
162
  const trimmed = () => ({ ...result, [listKey!]: kept, note: note() });
136
163
  while (kept.length > 1 && JSON.stringify(trimmed()).length > limit) kept.pop();
137
164
  if (JSON.stringify(trimmed()).length <= limit) return trimmed();
@@ -142,22 +169,300 @@ function fit(result: ToolResult, listKey: string | null, limit: number): ToolRes
142
169
  let cut: ToolResult;
143
170
  do {
144
171
  size = Math.floor(size * 0.85);
145
- cut = { truncated: true, partial: serialized.slice(0, size), note: "Result cut to the size limit. Ask for a smaller range." };
172
+ cut = { truncated: true, partial: sliceWhole(serialized, size), note: "Result cut to the size limit. Ask for a smaller range." };
146
173
  } while (JSON.stringify(cut).length > limit && size > 100);
147
174
  return cut;
148
175
  }
149
176
 
177
+ /**
178
+ * The result of a whole-document read within `limit` characters: its answer is cut at the end,
179
+ * and says so, rather than the result being cut as JSON, which loses what the other fields say.
180
+ */
181
+ export function fitAnswer(result: ToolResult, limit: number): ToolResult {
182
+ if (JSON.stringify(result).length <= limit || typeof result.answer !== "string") return fit(result, null, limit);
183
+ const answer = result.answer;
184
+ const cutAt = (keep: number): ToolResult => ({
185
+ ...result,
186
+ answer: `${sliceWhole(answer, keep)}…`,
187
+ answer_shortened: "The rest of this answer did not fit in the room left in this conversation.",
188
+ });
189
+ // The longest start of the answer that fits. Escapes (quotes, line breaks) make the JSON longer
190
+ // than the text by as much as the text holds of them, so it is found by halving, not worked out.
191
+ let low = 0;
192
+ let high = answer.length;
193
+ while (low < high) {
194
+ const middle = Math.ceil((low + high) / 2);
195
+ if (JSON.stringify(cutAt(middle)).length <= limit) low = middle;
196
+ else high = middle - 1;
197
+ }
198
+ return fit(cutAt(low), null, limit);
199
+ }
200
+
201
+ /**
202
+ * The result of an exact or regex search that read the whole file: the first matches, then the
203
+ * last one of the file, and a note that says how many of how many are shown when that is not all.
204
+ * Without the last one, a model asked when something last happened named the last line it was
205
+ * shown. To fit `limit`, matches are dropped from the end of the first ones: the last one stays.
206
+ */
207
+ function firstAndLastMatches(base: ToolResult, first: LineMatch[], last: LineMatch, total: number, limit: number): ToolResult {
208
+ const which = (kept: number) => (kept === 0 ? `the last (line ${last.line})` : `the first${kept > 1 ? ` ${kept}` : ""} and the last (line ${last.line})`);
209
+ const shown = (kept: number) => `${kept + 1} of the ${total} matching lines`;
210
+ // Where a search for the ones in between goes on: after the last of the first ones shown.
211
+ const next = (kept: number) => (kept > 0 ? first[kept - 1]!.line + 1 : undefined);
212
+ const between = (kept: number) => (next(kept) !== undefined ? `To see the ones in between, search again with from_line ${next(kept)}, or count them with group_by.` : "Narrow the query or read specific lines.");
213
+ const withFirst = (kept: number, cut: boolean): ToolResult => ({
214
+ ...base,
215
+ ...(cut
216
+ ? { note: `Showing ${shown(kept)} to stay within the size limit: ${which(kept)}. ${between(kept)}` }
217
+ // When every match is shown, there is nothing to say.
218
+ : kept + 1 < total ? { note: `${shown(kept)} are shown: ${which(kept)}. ${between(kept)}` } : {}),
219
+ ...(kept + 1 < total && next(kept) !== undefined ? { next_from_line: next(kept) } : {}),
220
+ matches: [...first.slice(0, kept), last],
221
+ });
222
+ const whole = withFirst(first.length, false);
223
+ if (JSON.stringify(whole).length <= limit) return whole;
224
+ let kept = first.length;
225
+ while (kept > 0 && JSON.stringify(withFirst(kept, true)).length > limit) kept--;
226
+ const cut = withFirst(kept, true);
227
+ if (JSON.stringify(cut).length <= limit) return cut;
228
+ // Only the last match is left, and its note is too long for the room: a shorter one. It still
229
+ // starts with "Showing ", so the result is taken as cut. `fit` must not put its own note in its
230
+ // place, which would say "1 of 1 results" and drop the line of the last match. When even this
231
+ // does not fit, `fit` cuts the result as text: the note, with that line, comes before the match.
232
+ const lastOnly = { ...base, note: `Showing 1 of the ${total} matching lines: ${which(0)}. Narrow the search.`, matches: [last] };
233
+ return fit(lastOnly, null, limit);
234
+ }
235
+
236
+ /**
237
+ * The result of a search with `order: "last"`: the last matching lines, in the order of the file,
238
+ * with a note that says so, and on which line the first match is. To fit `limit`, the earliest of
239
+ * them are dropped first: the very last stays. `stopped` is given when the scan stopped early: the
240
+ * last line of the lines searched, and the `to_line` of the call, which a search for the lines after
241
+ * those it found keeps.
242
+ */
243
+ function lastMatches(base: ToolResult, first: LineMatch | undefined, last: LineMatch[], total: number, limit: number, stopped?: { end: number; toLine?: number }): ToolResult {
244
+ const build = (kept: number, cut: boolean): ToolResult => {
245
+ const shown = last.slice(last.length - kept);
246
+ const end = shown.at(-1)?.line;
247
+ // A scan that stopped early found these last: the lines after them were not all looked at. Its
248
+ // note starts as those of the other searches that stopped early do, which `alreadyShown` looks
249
+ // for: a later question has time of its own, and the call made then is run, not pointed back to.
250
+ if (stopped) {
251
+ // Nothing found means out of time (an exact search stops only past its limit on matches). It
252
+ // is not known where the scan stopped, so no line is named to search from.
253
+ if (end === undefined) {
254
+ return { ...base, note: "The scan stopped early, out of time, before it found a matching line: the lines it did not reach may have some. Try a simpler pattern, mode \"exact\", or fewer lines with from_line and to_line.", matches: shown };
255
+ }
256
+ const lines = `${shown.length} ${plural(shown.length, "matching line")}`;
257
+ const which = cut ? `Showing the last ${lines} it found to stay within the size limit` : `These are the last ${lines} it found`;
258
+ // The search goes on after the last line found, in the same range. When that line is the last
259
+ // of the range, the scan stopped there and missed none of it: there is nothing to search on.
260
+ const later = end < stopped.end
261
+ ? ` There may be later ones, after line ${end}: search again with from_line ${end + 1}${stopped.toLine !== undefined ? ` and to_line ${stopped.toLine}` : ""}.`
262
+ : "";
263
+ return { ...base, note: `The scan stopped early; the total is a lower bound. ${which}, in the order of the file.${later}`, matches: shown };
264
+ }
265
+ const note = shown.length < total
266
+ // A cut result's note starts with "Showing ", as `alreadyShown` looks for: a call made later may have more room.
267
+ ? cut
268
+ ? `Showing the last ${shown.length} of the ${total} matching lines to stay within the size limit, in the order of the file: the last match is on line ${end}${first ? `, and the first on line ${first.line}` : ""}. Narrow the query or read specific lines.`
269
+ : `These are the last ${shown.length} of the ${total} matching lines, in the order of the file: the last match is on line ${end}${first ? `, and the first on line ${first.line}` : ""}.`
270
+ : undefined;
271
+ return { ...base, ...(note ? { note: typeof base.note === "string" ? `${base.note} ${note}` : note } : {}), matches: shown };
272
+ };
273
+ const whole = build(last.length, false);
274
+ if (JSON.stringify(whole).length <= limit) return whole;
275
+ let kept = last.length;
276
+ while (kept > 1 && JSON.stringify(build(kept, true)).length > limit) kept--;
277
+ return fit(build(kept, true), null, limit);
278
+ }
279
+
280
+ /** The result of a search with `group_by`: the total, then up to `shown` groups, cut further to fit `limit`. */
281
+ function groupedResult(base: ToolResult, counted: GroupResult, shown: number, limit: number): ToolResult {
282
+ const byTime = base.group_by === "minute" || base.group_by === "hour" || base.group_by === "day";
283
+ const all = counted.groups.map(({ key, count, firstLine, lastLine }) => ({ key, count, first_line: firstLine, last_line: lastLine }));
284
+ // By time, the groups shown are the largest, put back in time order; so are those kept when the
285
+ // result is cut to its room. Cutting the end of the list there kept the earliest groups, while the
286
+ // note said the largest, and a model named the wrong hour as the busiest. The sort is stable: of
287
+ // groups of the same size, the earlier comes first.
288
+ const largest = byTime ? [...all].sort((left, right) => right.count - left.count) : all;
289
+ const pick = (kept: number) => (byTime ? largest.slice(0, kept).sort((left, right) => left.first_line - right.first_line) : all.slice(0, kept));
290
+ const most = Math.min(shown, all.length);
291
+ const extra = {
292
+ total_groups: counted.totalGroups,
293
+ ...(counted.otherCount > 0 ? { other_count: counted.otherCount, other_note: `Lines of groups past the first ${MAX_GROUP_KEYS.toLocaleString("en-US")} found.` } : {}),
294
+ ...(counted.ungrouped > 0 ? { lines_without_group: counted.ungrouped } : {}),
295
+ };
296
+ const build = (kept: number, cut: boolean): ToolResult => {
297
+ const groups = pick(kept);
298
+ const order = byTime ? (groups.length < all.length ? "the largest, in time order" : "in time order") : "the largest first";
299
+ const note = groups.length < counted.totalGroups ? `${cut ? "Showing " : ""}${groups.length} of the ${counted.totalGroups} groups${cut ? " to stay within the size limit" : " are shown"}, ${order}. Narrow the search, or use from_line and to_line, for the others.` : undefined;
300
+ return { ...base, ...extra, ...(note ? { note: typeof base.note === "string" ? `${base.note} ${note}` : note } : {}), groups };
301
+ };
302
+ const whole = build(most, false);
303
+ if (JSON.stringify(whole).length <= limit) return whole;
304
+ let kept = most;
305
+ while (kept > 1 && JSON.stringify(build(kept, true)).length > limit) kept--;
306
+ return fit(build(kept, true), null, limit);
307
+ }
308
+
309
+ const searchMode = (mode: unknown): "keywords" | "exact" | "regex" => (mode === "exact" || mode === "regex" ? mode : "keywords");
310
+
311
+ /** `group_by` as the search reads it: undefined when not given. A value it does not know is an error. */
312
+ function groupByOf(value: unknown): GroupBy | undefined {
313
+ if (value === undefined || value === null || value === "" || value === "none") return undefined;
314
+ if (typeof value === "string" && (GROUP_BY_VALUES as readonly string[]).includes(value)) return value as GroupBy;
315
+ throw new Error(`group_by must be one of ${GROUP_BY_VALUES.map((name) => `"${name}"`).join(", ")}.`);
316
+ }
317
+
318
+ /** A line number of a search's range, as the search reads it: undefined when not given. */
319
+ const rangeLine = (value: unknown): number | undefined => (value === undefined || value === null || value === "" ? undefined : integer(value, 1, 1, Number.MAX_SAFE_INTEGER));
320
+
321
+ /**
322
+ * The arguments of a search that choose which lines it looks at and how it shows them, as the
323
+ * search reads them. The search, its key and its label all read them here, so that they agree.
324
+ */
325
+ function searchScope(args: Record<string, unknown>): { fromLine?: number; toLine?: number; order: "first" | "last"; groupBy?: GroupBy; wholeWord: boolean; caseSensitive: boolean } {
326
+ const fromLine = rangeLine(args.from_line);
327
+ const toLine = rangeLine(args.to_line);
328
+ let groupBy: GroupBy | undefined;
329
+ try {
330
+ groupBy = groupByOf(args.group_by);
331
+ } catch {
332
+ groupBy = undefined;
333
+ }
334
+ return {
335
+ ...(fromLine !== undefined ? { fromLine } : {}),
336
+ ...(toLine !== undefined ? { toLine } : {}),
337
+ order: args.order === "last" ? "last" : "first",
338
+ ...(groupBy ? { groupBy } : {}),
339
+ wholeWord: flag(args.whole_word),
340
+ caseSensitive: flag(args.case_sensitive),
341
+ };
342
+ }
343
+
344
+ /** The lines a `read_document` call asks for, as its handler reads them, before the end of the file is known. */
345
+ function requestedLines(args: Record<string, unknown>): [number, number] {
346
+ const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
347
+ return [start, integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, start + MAX_READ_LINES - 1)];
348
+ }
349
+
350
+ /**
351
+ * A call's arguments as its tool reads them, with the defaults filled in: two calls with the same
352
+ * key get the same result from a file that has not changed. Undefined for a tool whose calls are
353
+ * not compared (a whole-file read has a count of its own; a look at pages returns a file).
354
+ */
355
+ export function toolCallKey(name: string, args: Record<string, unknown>): string | undefined {
356
+ const id = typeof args.document_id === "string" && args.document_id ? args.document_id : undefined;
357
+ if (!id) return undefined;
358
+ if (name === TOOL_NAMES.search) {
359
+ if (typeof args.query !== "string" || !args.query.trim()) return undefined;
360
+ const mode = searchMode(args.mode);
361
+ // A group_by the search refuses: the call answers with an error, and is not compared.
362
+ try {
363
+ groupByOf(args.group_by);
364
+ } catch {
365
+ return undefined;
366
+ }
367
+ const { fromLine, toLine, order, groupBy, wholeWord, caseSensitive } = searchScope(args);
368
+ // The arguments of 0.8.0 are added only when given: a call without them has the key it had.
369
+ const scope = [
370
+ ...(fromLine !== undefined || toLine !== undefined ? [fromLine ?? 1, toLine ?? null] : []),
371
+ ...(mode !== "keywords" && (order === "last" || groupBy || wholeWord) ? [order, groupBy ?? null, mode === "exact" && wholeWord] : []),
372
+ ];
373
+ return JSON.stringify(mode === "keywords"
374
+ ? [name, id, args.query, mode, integer(args.max_results, 5, 1, 10), ...scope]
375
+ : [name, id, args.query, mode, groupBy ? integer(args.max_results, DEFAULT_GROUPS, 1, MAX_GROUPS) : integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS), groupBy ? 0 : integer(args.context_lines, 0, 0, 5), caseSensitive, ...scope]);
376
+ }
377
+ if (name === TOOL_NAMES.read) return JSON.stringify([name, id, ...requestedLines(args)]);
378
+ if (name === TOOL_NAMES.overview) return JSON.stringify([name, id]);
379
+ return undefined;
380
+ }
381
+
382
+ /**
383
+ * When an earlier call's result already holds all that `call` would return, and is still in the
384
+ * conversation in full: a short result that says so, in place of running the call again. A result
385
+ * that was cut to the room it had, or replaced by a stand-in, or failed, is not pointed to: the call
386
+ * is run, and may get more. A read of lines inside a read that is shown in full is pointed to.
387
+ * `stored` is true for a result in the tool rounds of an earlier question, which an older version
388
+ * may have written: 0.5.0 cut the text of a read of one long line without saying so (no
389
+ * `text_cut`), so a read of one line from there is not taken as shown in full.
390
+ */
391
+ export function alreadyShown(call: { name: string; args: Record<string, unknown> }, earlier: { call: { name: string; args: Record<string, unknown> }; result: ToolResult }, stored = false): ToolResult | undefined {
392
+ const { result } = earlier;
393
+ if (earlier.call.name !== call.name || earlier.call.args.document_id !== call.args.document_id) return undefined;
394
+ if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true) return undefined;
395
+ // A search stored by 0.7.0 with case_sensitive or whole_word as text or 1 ("true", 1): 0.7.0 read
396
+ // those as off, 0.8.0 as on, so the call made now would not return what was stored.
397
+ if (stored && call.name === TOOL_NAMES.search && [earlier.call.args.case_sensitive, earlier.call.args.whole_word].some((value) => value !== undefined && value !== true && value !== false && flag(value))) return undefined;
398
+ // A list that `fit` cut to the room it had, a read whose text was cut, or a search that ran out of
399
+ // time ("the total is a lower bound"; a later question has time of its own): a call made now may get more.
400
+ if (typeof result.note === "string" && (result.note.startsWith("Showing ") || result.note.startsWith("The scan stopped early"))) return undefined;
401
+ if (result.text_cut === true) return undefined;
402
+ // An exact or regex search that an earlier version stored: the first matches, without the last one
403
+ // and without a note. Run now, the call returns more (the last match), not the same.
404
+ if (call.name === TOOL_NAMES.search && typeof result.total_matching_lines === "number" && Array.isArray(result.matches)
405
+ && result.matches.length < result.total_matching_lines && typeof result.note !== "string") return undefined;
406
+ const document = typeof result.document === "string" ? { document: result.document } : {};
407
+ if (call.name === TOOL_NAMES.read) {
408
+ const shown = typeof result.lines === "string" ? /^(\d+)-(\d+)$/.exec(result.lines) : null;
409
+ const total = result.total_lines;
410
+ if (!shown || typeof total !== "number") return undefined;
411
+ const [first, last] = [Number(shown[1]), Number(shown[2])];
412
+ if (stored && first === last) return undefined;
413
+ const [start, end] = requestedLines(call.args);
414
+ const from = Math.min(start, total);
415
+ const to = Math.min(end, total);
416
+ if (from < first || to > last) return undefined;
417
+ return {
418
+ ...document,
419
+ lines: `${from}-${to}`,
420
+ already_shown: true,
421
+ 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.`,
422
+ };
423
+ }
424
+ const key = toolCallKey(call.name, call.args);
425
+ if (key === undefined || key !== toolCallKey(earlier.call.name, earlier.call.args)) return undefined;
426
+ return {
427
+ ...document,
428
+ already_shown: true,
429
+ 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.",
430
+ };
431
+ }
432
+
433
+ /**
434
+ * A hint added to the error of a search that failed twice in a row in the same mode, so that the
435
+ * model tries another way instead of sending the same kind of call a third time.
436
+ */
437
+ export function repeatedFailureHint(call: { name: string; args: Record<string, unknown> }): string {
438
+ return searchMode(call.args.mode) === "regex"
439
+ ? "Two regex searches in a row failed. Try mode \"exact\" with a plain word or ID from the file, or mode \"keywords\"."
440
+ : "This search failed twice in a row. Check the arguments against the tool's description, or answer from what you have.";
441
+ }
442
+
443
+ /**
444
+ * The tool and mode of a search, to tell whether two failures in a row were of the same kind.
445
+ * Undefined for the other tools: their errors say what to do (a whole-file read that is not made
446
+ * again, a page that does not exist), and a hint would only blur that.
447
+ */
448
+ export function failureKind(call: { name: string; args: Record<string, unknown> }): string | undefined {
449
+ return call.name === TOOL_NAMES.search ? `${call.name}|${searchMode(call.args.mode)}` : undefined;
450
+ }
451
+
150
452
  /**
151
453
  * What a finished tool call found, as a suffix for its `describe()` label, for a steps list:
152
454
  * "Search app.log (exact) for “timeout”" + " — 12 matching lines".
153
455
  */
154
456
  export function toolResultSummary(label: string, result: ToolResult): string {
155
457
  if (typeof result.error === "string") return ` — failed: ${result.error}`;
156
- if (typeof result.total_matching_lines === "number") return ` — ${result.total_matching_lines.toLocaleString("en-US")} matching lines`;
157
- if (Array.isArray(result.passages)) return ` — ${result.passages.length} passages`;
458
+ if (typeof result.total_matching_lines === "number") {
459
+ const groups = typeof result.total_groups === "number" ? ` in ${result.total_groups.toLocaleString("en-US")} ${plural(result.total_groups, "group")}` : "";
460
+ return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}${groups}`;
461
+ }
462
+ if (Array.isArray(result.passages)) return ` — ${result.passages.length} ${plural(result.passages.length, "passage")}`;
158
463
  if (typeof result.parts_read === "number") {
159
- const incomplete = result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
160
- return ` — ${result.parts_read} parts, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
464
+ const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
465
+ return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
161
466
  }
162
467
  // A read reports its range only when it was cut short of what was asked.
163
468
  if (typeof result.lines === "string" && typeof result.total_lines === "number") return label.endsWith(result.lines) ? "" : ` — got ${result.lines}`;
@@ -168,6 +473,31 @@ export function toolResultSummary(label: string, result: ToolResult): string {
168
473
  return "";
169
474
  }
170
475
 
476
+ /**
477
+ * A step, or a label of one, as one line of plain text. Steps quote what the model sent (a query, a
478
+ * task, the name of a tool, arguments that were not JSON), and they reach users' screens: the
479
+ * invisible characters that file text and names lose are dropped (`removeInvisible`: text-direction
480
+ * overrides and isolates, zero-width spaces, tag characters), a line break, a tab or another control
481
+ * character becomes one space with the blanks around it, and "](" gets a space, so that a markdown
482
+ * link or picture in a query stays text. A line without them is unchanged.
483
+ */
484
+ export function stepLine(text: string): string {
485
+ // Each control character, tab and line break is a "\n" first, which `removeInvisible` keeps (it
486
+ // would drop the others): an invisible character between two of them then leaves one space, not
487
+ // two. A soft hyphen it keeps before one goes too. Then a run of blanks with a "\n" in it is one space.
488
+ const marked = removeInvisible(text.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, "\n")).replace(/\xAD+(?=\n)/g, "");
489
+ return marked.replace(/\s+/g, (blank) => (blank.includes("\n") ? " " : blank)).replaceAll("](", "] (");
490
+ }
491
+
492
+ /** An unknown tool's name as a step or an error quotes it: the model chose it, at any length. */
493
+ export const unknownToolName = (name: string): string => `“${sliceWhole(name, 64)}”`;
494
+
495
+ /**
496
+ * A document_id the model sent, as an error quotes it: whole when it is as long as a real one can
497
+ * be, cut otherwise. The model chose it, at any length, and the error goes into steps too.
498
+ */
499
+ const shownId = (id: string): string => (id.length > 64 ? `${sliceWhole(id, 64)}…` : id);
500
+
171
501
  export function createDocumentTools(options: {
172
502
  /** Loads a document the tools may access. Return undefined for anything out of scope. */
173
503
  load(documentId: string): Promise<DocumentSource | undefined>;
@@ -228,23 +558,37 @@ export function createDocumentTools(options: {
228
558
  regexQueue = next.catch(() => undefined);
229
559
  return next;
230
560
  };
561
+ const givenReads: unknown = options.maxWholeDocumentReads;
562
+ // NaN failed every comparison, so it let a document be read whole any number of times.
563
+ if (givenReads !== undefined && (typeof givenReads !== "number" || Number.isNaN(givenReads))) {
564
+ const shown = typeof givenReads === "number" ? String(givenReads) : typeof givenReads === "string" ? JSON.stringify(givenReads) : typeof givenReads;
565
+ throw new (typeof givenReads === "number" ? RangeError : TypeError)(`maxWholeDocumentReads must be a number, and is ${shown}.`);
566
+ }
231
567
  const maxWholeReads = Math.max(0, Math.trunc(options.maxWholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS));
232
568
  /** Whole-document reads started, by document. */
233
569
  const wholeReads = new Map<string, number>();
570
+ /** Why the last whole-document read of a document failed, when no part of it could be read. */
571
+ const failedWholeReads = new Map<string, string>();
234
572
  // When no limit is given with a call: three eighths of a request, so that two looks still fit.
235
573
  const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
236
574
 
237
575
  async function documentFor(args: Record<string, unknown>): Promise<DocumentSource> {
238
576
  const id = text(args.document_id, "document_id");
239
577
  // Scope check: a model can only reach files attached to this conversation.
240
- if (!allowed.has(id)) throw new Error(`Unknown document_id ${id}. Use an ID from a file card.`);
578
+ if (!allowed.has(id)) {
579
+ // The IDs it may use, with their file names, so that the next call is right.
580
+ const usable = [...allowed].slice(0, 20).map((known) => `${known}${names.has(known) ? ` (${JSON.stringify(names.get(known))})` : ""}`);
581
+ throw new Error(usable.length === 0
582
+ ? `Unknown document_id ${shownId(id)}. No attached file is read with this tool in this conversation.`
583
+ : `Unknown document_id ${shownId(id)}. Use one of: ${usable.join(", ")}${allowed.size > 20 ? ", …" : ""}.`);
584
+ }
241
585
  const document = await options.load(id);
242
586
  if (!document) throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
243
587
  names.set(id, document.meta.name);
244
588
  return document;
245
589
  }
246
590
 
247
- const handlers: Record<string, (args: Record<string, unknown>, limits: ToolCallLimits) => Promise<ToolResult>> = {
591
+ const handlers: Record<string, (args: Record<string, unknown>, limits: ToolCallLimits, hooks: ToolCallHooks) => Promise<ToolResult>> = {
248
592
  async [TOOL_NAMES.search](args, limits) {
249
593
  const limit = limitOf(limits);
250
594
  const document = await documentFor(args);
@@ -253,13 +597,24 @@ export function createDocumentTools(options: {
253
597
  // Page numbers are added only for a PDF whose pages can be looked at: they are what
254
598
  // view_pages takes. Everything else gets the results of 0.2.0 unchanged.
255
599
  const paged = viewable.has(document.meta.id);
600
+ const groupBy = groupByOf(args.group_by);
601
+ const { fromLine, toLine, order, wholeWord, caseSensitive } = searchScope(args);
602
+ const total = document.lineCount;
603
+ if (fromLine !== undefined && fromLine > total) throw new Error(`from_line ${fromLine} is past the end of the file, which has ${total} ${plural(total, "line")}.`);
604
+ if (toLine !== undefined && toLine < (fromLine ?? 1)) throw new Error(`to_line ${toLine} is before from_line ${fromLine ?? 1}.`);
605
+ const ranged = fromLine !== undefined || toLine !== undefined;
606
+ const range = { from: fromLine ?? 1, to: Math.min(total, toLine ?? total) };
607
+ // Said in the result when part of the file was searched: the counts are of those lines.
608
+ const searched = ranged ? { searched_lines: `${range.from}-${range.to}` } : {};
256
609
  if (mode === "keywords") {
610
+ if (groupBy) throw new Error("group_by counts the lines of an exact or regex search: use mode \"exact\" or \"regex\".");
257
611
  const topK = integer(args.max_results, 5, 1, 10);
258
- const ranked = await rankSource(document, query, topK, options.signal);
612
+ const ranked = await rankSource(document, query, topK, options.signal, ranged ? range : undefined);
259
613
  const texts = await Promise.all(ranked.map((passage) => document.readLines(passage.from, passage.to)));
260
614
  return fit({
261
615
  document: document.meta.name,
262
616
  mode,
617
+ ...searched,
263
618
  passages: ranked.map((passage, index) => {
264
619
  const pages = paged ? document.pagesOfLines(passage.from, passage.to) : undefined;
265
620
  return {
@@ -273,6 +628,7 @@ export function createDocumentTools(options: {
273
628
  }, "passages", limit);
274
629
  }
275
630
  const regex = mode === "regex";
631
+ const shownGroups = integer(args.max_results, DEFAULT_GROUPS, 1, MAX_GROUPS);
276
632
  const grep = async () => {
277
633
  const regexLeft = regexBudget - regexClock.usedMs;
278
634
  if (regex && regexLeft <= 0) {
@@ -280,23 +636,44 @@ export function createDocumentTools(options: {
280
636
  }
281
637
  return grepSource(document, query, {
282
638
  regex,
283
- caseSensitive: args.case_sensitive === true,
284
- maxResults: integer(args.max_results, 20, 1, 50),
639
+ caseSensitive,
640
+ maxResults: integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS),
285
641
  contextLines: integer(args.context_lines, 0, 0, 5),
286
642
  ...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
287
643
  ...(options.signal ? { signal: options.signal } : {}),
644
+ ...(ranged ? { fromLine: range.from, toLine: range.to } : {}),
645
+ ...(order === "last" ? { order } : {}),
646
+ ...(groupBy ? { groupBy } : {}),
647
+ ...(wholeWord && !regex ? { wholeWord } : {}),
288
648
  });
289
649
  };
290
650
  const result = await (regex ? inRegexTurn(grep) : grep());
651
+ const placed = (match: LineMatch): LineMatch => {
652
+ if (!paged) return match;
653
+ const { line, ...rest } = match;
654
+ const page = document.pageOfLine(line);
655
+ return { line, ...(page ? { page } : {}), ...rest };
656
+ };
657
+ const base = { document: document.meta.name, mode, ...searched, total_matching_lines: result.totalMatchingLines };
658
+ const stopped = result.stoppedEarly ? { note: "The scan stopped early; the counts are lower bounds." } : {};
659
+ if (result.groups) return groupedResult({ ...base, group_by: groupBy!, ...stopped }, result.groups, shownGroups, limit);
660
+ const matches = result.matches.map(placed);
661
+ if (order === "last") {
662
+ // The range a search for the lines after those found goes on in, when the scan stopped early.
663
+ const rest = result.stoppedEarly ? { end: range.to, ...(toLine !== undefined ? { toLine: range.to } : {}) } : undefined;
664
+ return lastMatches({ ...base, order }, result.first ? placed(result.first) : undefined, matches, result.totalMatchingLines, limit, rest);
665
+ }
666
+ if (!result.stoppedEarly && result.totalMatchingLines >= 2) {
667
+ // The last match is `last`, or, when every match is among the first ones, the last of them.
668
+ return result.last
669
+ ? firstAndLastMatches(base, matches, placed(result.last), result.totalMatchingLines, limit)
670
+ : firstAndLastMatches(base, matches.slice(0, -1), matches.at(-1)!, result.totalMatchingLines, limit);
671
+ }
291
672
  return fit({
292
- document: document.meta.name,
293
- mode,
294
- total_matching_lines: result.totalMatchingLines,
295
- ...(result.stoppedEarly ? { note: "The scan stopped early; the total is a lower bound." } : {}),
296
- matches: paged ? result.matches.map(({ line, ...rest }) => {
297
- const page = document.pageOfLine(line);
298
- return { line, ...(page ? { page } : {}), ...rest };
299
- }) : result.matches,
673
+ ...base,
674
+ // The description says the last match is shown: here it is not known.
675
+ ...(result.stoppedEarly ? { note: "The scan stopped early; the total is a lower bound, and the last match in the file is not known." } : {}),
676
+ matches,
300
677
  }, "matches", limit);
301
678
  },
302
679
 
@@ -322,7 +699,9 @@ export function createDocumentTools(options: {
322
699
  lines: `${start}-${to}`,
323
700
  ...(pages ? { pages } : {}),
324
701
  total_lines: total,
325
- text: fits(body) ? body : body.slice(0, Math.floor((limit - 500) / 2)),
702
+ text: fits(body) ? body : sliceWhole(body, Math.floor((limit - 500) / 2)),
703
+ // One line longer than the room: its text was cut, so the lines are not all shown.
704
+ ...(fits(body) ? {} : { text_cut: true }),
326
705
  ...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
327
706
  };
328
707
  },
@@ -346,14 +725,15 @@ export function createDocumentTools(options: {
346
725
  ...(meta.pages ? { pages: meta.pages } : {}),
347
726
  parts_for_whole_document_analysis: parts,
348
727
  ...(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.` } : {}),
349
- ...(meta.logProfile ? { log_profile: meta.logProfile } : {}),
728
+ // 0.5.0 stored some log templates cut inside an emoji: half of a character is not sent.
729
+ ...(meta.logProfile ? { log_profile: wellFormedJson(meta.logProfile) } : {}),
350
730
  first_lines: numberLines(await document.readLines(1, first), 1),
351
731
  last_lines: lineCount > 30 ? numberLines(await document.readLines(tail, lineCount), tail) : "",
352
732
  outline: meta.outline.length ? outlineLines(meta.outline) : [],
353
733
  }, "outline", limit);
354
734
  },
355
735
 
356
- async [TOOL_NAMES.analyze](args, limits) {
736
+ async [TOOL_NAMES.analyze](args, limits, hooks) {
357
737
  if (!options.generate) throw new Error("Whole-document analysis is not enabled.");
358
738
  const document = await documentFor(args);
359
739
  const task = text(args.task, "task");
@@ -363,9 +743,13 @@ export function createDocumentTools(options: {
363
743
  const id = document.meta.id;
364
744
  const reads = wholeReads.get(id) ?? 0;
365
745
  if (reads >= maxWholeReads) {
746
+ const failure = failedWholeReads.get(id);
366
747
  throw new Error(maxWholeReads === 0
367
748
  ? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
368
- : `${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.`);
749
+ : failure !== undefined
750
+ // There is no answer to use: saying "use the answer of that read" would invite one made up.
751
+ ? `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.`
752
+ : `${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.`);
369
753
  }
370
754
  wholeReads.set(id, reads + 1);
371
755
  let result;
@@ -375,26 +759,38 @@ export function createDocumentTools(options: {
375
759
  task,
376
760
  generate: options.generate,
377
761
  budget: options.budget,
378
- onProgress: options.onProgress,
762
+ // The call's own listener, when it has one, in place of the tool set's.
763
+ onProgress: hooks.onProgress ?? options.onProgress,
764
+ ...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
379
765
  signal: options.signal,
380
766
  ...(options.retry ? { retry: options.retry } : {}),
767
+ ...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
381
768
  });
382
769
  } catch (error) {
383
- // Refused before any model call: that was no read.
384
- if (error instanceof TooManyPartsError) wholeReads.set(id, reads);
770
+ // Parts were sent and none could be read: that read is counted, since another would most
771
+ // likely fail the same way. Anything else (too many parts, a store that could not be read)
772
+ // failed before any model request: that was no read. Its count is given back, not set to
773
+ // what it was when the read started, which would take back the count of another read of
774
+ // the same document running in this turn.
775
+ if (error instanceof NothingReadError) failedWholeReads.set(id, error.reason);
776
+ else wholeReads.set(id, Math.max(0, (wholeReads.get(id) ?? 1) - 1));
385
777
  throw error;
386
778
  }
779
+ failedWholeReads.delete(id);
387
780
  const notesCutShort = result.truncatedParts + result.truncatedMerges;
388
- return fit({
781
+ return fitAnswer({
389
782
  document: document.meta.name,
390
783
  parts_read: result.parts,
391
784
  parts_with_relevant_content: result.relevantParts,
392
785
  ...(result.failedParts ? { parts_that_failed: result.failedParts } : {}),
393
786
  ...(notesCutShort ? { notes_cut_short: notesCutShort } : {}),
394
787
  ...(result.answerTruncated ? { answer_cut_short: true } : {}),
395
- ...(notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
788
+ ...(result.answerFailed !== undefined ? { notes_only: true } : {}),
789
+ ...(result.answerFailed !== undefined
790
+ ? { 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." : ""}` }
791
+ : notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
396
792
  answer: result.answer,
397
- }, null, limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS)));
793
+ }, limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS)));
398
794
  },
399
795
  };
400
796
 
@@ -406,7 +802,7 @@ export function createDocumentTools(options: {
406
802
  if (!viewable.has(id)) {
407
803
  throw new Error(allowed.has(id)
408
804
  ? `The pages of ${names.get(id) ?? id} cannot be shown: only its text was kept. Answer from the text.`
409
- : `Unknown document_id ${id}. Use the document_id of an attached PDF.`);
805
+ : `Unknown document_id ${shownId(id)}. Use the document_id of an attached PDF.`);
410
806
  }
411
807
  const document = await options.load(id);
412
808
  if (!document) throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
@@ -450,13 +846,13 @@ export function createDocumentTools(options: {
450
846
  // What a tool could not do goes to the model, and from there to a user's screen: never a server path.
451
847
  const failure = (error: unknown): ToolResult => ({ error: safeErrorMessage(error) });
452
848
 
453
- async function execute(name: string, args: Record<string, unknown>, limits: ToolCallLimits = {}): Promise<ToolResult> {
454
- if (!known.has(name)) return { error: `Unknown tool ${name}.` };
849
+ async function execute(name: string, args: Record<string, unknown>, limits: ToolCallLimits = {}, hooks: ToolCallHooks = {}): Promise<ToolResult> {
850
+ if (!known.has(name)) return { error: `Unknown tool ${unknownToolName(name)}.` };
455
851
  // The pages are a file, and this method returns only JSON. Saying that pages are attached
456
852
  // with nothing attached would be worse than saying that they could not be shown.
457
853
  if (name === TOOL_NAMES.view) return { error: FILES_NOT_DELIVERED };
458
854
  try {
459
- return await handlers[name]!(args, limits);
855
+ return await handlers[name]!(args, limits, hooks);
460
856
  } catch (error) {
461
857
  if (options.signal?.aborted) throw error;
462
858
  return failure(error);
@@ -468,8 +864,8 @@ export function createDocumentTools(options: {
468
864
  has: (name) => known.has(name),
469
865
  execute: (name, args) => execute(name, args),
470
866
  resultCharacters: (name) => (name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
471
- async executeWithFiles(name, args, limits = {}) {
472
- if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args, limits), files: [] };
867
+ async executeWithFiles(name, args, limits = {}, hooks = {}) {
868
+ if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args, limits, hooks), files: [] };
473
869
  try {
474
870
  return await viewPages(args, limits);
475
871
  } catch (error) {
@@ -488,7 +884,10 @@ export function createDocumentTools(options: {
488
884
  }
489
885
  if (name === TOOL_NAMES.search) {
490
886
  const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
491
- return `Search ${file} (${mode}) for “${String(args.query ?? "").slice(0, 80)}”`;
887
+ const { fromLine, toLine, order, groupBy } = searchScope(args);
888
+ const where = fromLine !== undefined || toLine !== undefined ? ` in lines ${fromLine ?? 1}-${toLine ?? "end"}` : "";
889
+ const how = mode === "keywords" ? "" : groupBy ? `, counted by ${groupBy}` : order === "last" ? ", the last ones" : "";
890
+ return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”${where}${how}`;
492
891
  }
493
892
  if (name === TOOL_NAMES.read) {
494
893
  const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
@@ -496,7 +895,7 @@ export function createDocumentTools(options: {
496
895
  return `Read ${file} lines ${start}${end}`;
497
896
  }
498
897
  if (name === TOOL_NAMES.overview) return `Overview of ${file}`;
499
- if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${String(args.task ?? "").slice(0, 100)}”`;
898
+ if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”`;
500
899
  return name;
501
900
  },
502
901
  };