llm-large-files 0.7.0 → 0.8.1

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 (196) hide show
  1. package/CHANGELOG.md +370 -1
  2. package/README.md +12 -8
  3. package/dist/aggregate.d.ts +103 -0
  4. package/dist/aggregate.d.ts.map +1 -0
  5. package/dist/aggregate.js +651 -0
  6. package/dist/aggregate.js.map +1 -0
  7. package/dist/analyze.d.ts +3 -1
  8. package/dist/analyze.d.ts.map +1 -1
  9. package/dist/analyze.js +109 -14
  10. package/dist/analyze.js.map +1 -1
  11. package/dist/anthropic/adapter.d.ts.map +1 -1
  12. package/dist/anthropic/adapter.js +4 -1
  13. package/dist/anthropic/adapter.js.map +1 -1
  14. package/dist/ask.d.ts +3 -3
  15. package/dist/ask.d.ts.map +1 -1
  16. package/dist/ask.js +72 -17
  17. package/dist/ask.js.map +1 -1
  18. package/dist/decode.d.ts +19 -0
  19. package/dist/decode.d.ts.map +1 -0
  20. package/dist/decode.js +97 -0
  21. package/dist/decode.js.map +1 -0
  22. package/dist/errors.d.ts +55 -0
  23. package/dist/errors.d.ts.map +1 -1
  24. package/dist/errors.js +65 -0
  25. package/dist/errors.js.map +1 -1
  26. package/dist/events.d.ts +6 -0
  27. package/dist/events.d.ts.map +1 -1
  28. package/dist/events.js +5 -1
  29. package/dist/events.js.map +1 -1
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +23 -0
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +12 -18
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +82 -746
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts.map +1 -1
  38. package/dist/gemini/adapter.js +9 -5
  39. package/dist/gemini/adapter.js.map +1 -1
  40. package/dist/gemini/endpoints.d.ts +5 -1
  41. package/dist/gemini/endpoints.d.ts.map +1 -1
  42. package/dist/gemini/endpoints.js +11 -2
  43. package/dist/gemini/endpoints.js.map +1 -1
  44. package/dist/gemini/generate.d.ts.map +1 -1
  45. package/dist/gemini/generate.js +20 -3
  46. package/dist/gemini/generate.js.map +1 -1
  47. package/dist/groups.d.ts +54 -0
  48. package/dist/groups.d.ts.map +1 -0
  49. package/dist/groups.js +136 -0
  50. package/dist/groups.js.map +1 -0
  51. package/dist/html.d.ts +11 -0
  52. package/dist/html.d.ts.map +1 -0
  53. package/dist/html.js +1112 -0
  54. package/dist/html.js.map +1 -0
  55. package/dist/index.d.ts +2 -1
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +1 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/library.d.ts.map +1 -1
  60. package/dist/library.js +57 -14
  61. package/dist/library.js.map +1 -1
  62. package/dist/limiter.d.ts +2 -1
  63. package/dist/limiter.d.ts.map +1 -1
  64. package/dist/limiter.js +3 -2
  65. package/dist/limiter.js.map +1 -1
  66. package/dist/model.d.ts.map +1 -1
  67. package/dist/model.js +8 -1
  68. package/dist/model.js.map +1 -1
  69. package/dist/node/handlers.d.ts.map +1 -1
  70. package/dist/node/handlers.js +69 -15
  71. package/dist/node/handlers.js.map +1 -1
  72. package/dist/node/index.d.ts +2 -0
  73. package/dist/node/index.d.ts.map +1 -1
  74. package/dist/node/index.js +1 -0
  75. package/dist/node/index.js.map +1 -1
  76. package/dist/node/ingest-child.d.ts +38 -0
  77. package/dist/node/ingest-child.d.ts.map +1 -0
  78. package/dist/node/ingest-child.js +42 -0
  79. package/dist/node/ingest-child.js.map +1 -0
  80. package/dist/node/isolated.d.ts +88 -0
  81. package/dist/node/isolated.d.ts.map +1 -0
  82. package/dist/node/isolated.js +381 -0
  83. package/dist/node/isolated.js.map +1 -0
  84. package/dist/office.d.ts +105 -0
  85. package/dist/office.d.ts.map +1 -0
  86. package/dist/office.js +1092 -0
  87. package/dist/office.js.map +1 -0
  88. package/dist/openai/adapter.d.ts.map +1 -1
  89. package/dist/openai/adapter.js +15 -1
  90. package/dist/openai/adapter.js.map +1 -1
  91. package/dist/pdf-pages.d.ts.map +1 -1
  92. package/dist/pdf-pages.js +2 -6
  93. package/dist/pdf-pages.js.map +1 -1
  94. package/dist/peers.d.ts +8 -0
  95. package/dist/peers.d.ts.map +1 -0
  96. package/dist/peers.js +32 -0
  97. package/dist/peers.js.map +1 -0
  98. package/dist/plan.d.ts +3 -1
  99. package/dist/plan.d.ts.map +1 -1
  100. package/dist/plan.js +17 -1
  101. package/dist/plan.js.map +1 -1
  102. package/dist/quality.d.ts +16 -0
  103. package/dist/quality.d.ts.map +1 -0
  104. package/dist/quality.js +157 -0
  105. package/dist/quality.js.map +1 -0
  106. package/dist/ranged.d.ts.map +1 -1
  107. package/dist/ranged.js +4 -2
  108. package/dist/ranged.js.map +1 -1
  109. package/dist/search.d.ts +99 -22
  110. package/dist/search.d.ts.map +1 -1
  111. package/dist/search.js +744 -140
  112. package/dist/search.js.map +1 -1
  113. package/dist/text-index.d.ts +3 -1
  114. package/dist/text-index.d.ts.map +1 -1
  115. package/dist/text-index.js +3 -1
  116. package/dist/text-index.js.map +1 -1
  117. package/dist/text.d.ts +27 -3
  118. package/dist/text.d.ts.map +1 -1
  119. package/dist/text.js +225 -23
  120. package/dist/text.js.map +1 -1
  121. package/dist/tools.d.ts +9 -0
  122. package/dist/tools.d.ts.map +1 -1
  123. package/dist/tools.js +457 -16
  124. package/dist/tools.js.map +1 -1
  125. package/dist/types.d.ts +23 -3
  126. package/dist/types.d.ts.map +1 -1
  127. package/dist/word-styles.d.ts +102 -0
  128. package/dist/word-styles.d.ts.map +1 -0
  129. package/dist/word-styles.js +419 -0
  130. package/dist/word-styles.js.map +1 -0
  131. package/dist/xlsx.d.ts +23 -0
  132. package/dist/xlsx.d.ts.map +1 -0
  133. package/dist/xlsx.js +511 -0
  134. package/dist/xlsx.js.map +1 -0
  135. package/dist/xml-stream.d.ts +55 -0
  136. package/dist/xml-stream.d.ts.map +1 -0
  137. package/dist/xml-stream.js +235 -0
  138. package/dist/xml-stream.js.map +1 -0
  139. package/docs/README.md +8 -8
  140. package/docs/getting-started.md +1 -1
  141. package/docs/guides/costs-and-limits.md +7 -5
  142. package/docs/guides/deployment.md +95 -29
  143. package/docs/guides/errors-and-reliability.md +23 -10
  144. package/docs/guides/pdfs.md +127 -74
  145. package/docs/guides/storage.md +1 -1
  146. package/docs/guides/testing.md +5 -1
  147. package/docs/guides/web-app.md +10 -9
  148. package/docs/how-it-works.md +80 -50
  149. package/docs/reference/ask.md +26 -8
  150. package/docs/reference/errors-and-retries.md +5 -3
  151. package/docs/reference/events.md +14 -6
  152. package/docs/reference/gemini.md +6 -2
  153. package/docs/reference/library.md +221 -79
  154. package/docs/reference/node.md +201 -23
  155. package/docs/reference/openai.md +1 -1
  156. package/docs/reference/tools.md +269 -23
  157. package/docs/security.md +114 -69
  158. package/docs/troubleshooting.md +40 -20
  159. package/package.json +6 -2
  160. package/src/aggregate.ts +674 -0
  161. package/src/analyze.ts +117 -13
  162. package/src/anthropic/adapter.ts +4 -1
  163. package/src/ask.ts +73 -17
  164. package/src/decode.ts +89 -0
  165. package/src/errors.ts +108 -0
  166. package/src/events.ts +10 -1
  167. package/src/evidence.ts +23 -0
  168. package/src/extract.ts +79 -701
  169. package/src/gemini/adapter.ts +9 -5
  170. package/src/gemini/endpoints.ts +12 -2
  171. package/src/gemini/generate.ts +19 -3
  172. package/src/groups.ts +162 -0
  173. package/src/html.ts +1071 -0
  174. package/src/index.ts +2 -1
  175. package/src/library.ts +52 -14
  176. package/src/limiter.ts +6 -1
  177. package/src/model.ts +8 -1
  178. package/src/node/handlers.ts +66 -16
  179. package/src/node/index.ts +2 -0
  180. package/src/node/ingest-child.ts +61 -0
  181. package/src/node/isolated.ts +464 -0
  182. package/src/office.ts +1047 -0
  183. package/src/openai/adapter.ts +14 -1
  184. package/src/pdf-pages.ts +2 -5
  185. package/src/peers.ts +29 -0
  186. package/src/plan.ts +19 -1
  187. package/src/quality.ts +146 -0
  188. package/src/ranged.ts +4 -2
  189. package/src/search.ts +738 -146
  190. package/src/text-index.ts +4 -2
  191. package/src/text.ts +214 -23
  192. package/src/tools.ts +440 -16
  193. package/src/types.ts +20 -3
  194. package/src/word-styles.ts +420 -0
  195. package/src/xlsx.ts +478 -0
  196. package/src/xml-stream.ts +224 -0
package/dist/tools.js CHANGED
@@ -1,10 +1,18 @@
1
1
  import { safeErrorMessage } from "./errors.js";
2
+ import { aggregateTable, FILTER_OPS, MAX_SHOWN_GROUPS } from "./aggregate.js";
3
+ import { GROUP_BY_VALUES, MAX_GROUP_KEYS } from "./groups.js";
2
4
  import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
3
5
  import { cutPdfPages } from "./pdf-pages.js";
4
6
  import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS } from "./search.js";
5
7
  import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
6
8
  import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
7
9
  const DEFAULT_READ_LINES = 200;
10
+ /** Matching lines an exact or regex search shows: the default, and the most a call may ask for. */
11
+ const DEFAULT_GREP_RESULTS = 20;
12
+ const MAX_GREP_RESULTS = 50;
13
+ /** Groups a search with `group_by` shows: the default, and the most a call may ask for. */
14
+ const DEFAULT_GROUPS = 50;
15
+ const MAX_GROUPS = 200;
8
16
  const MAX_READ_LINES = 600;
9
17
  /** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
10
18
  export const MAX_VIEW_PAGES = 5;
@@ -31,21 +39,27 @@ export const TOOL_NAMES = {
31
39
  overview: "get_document_overview",
32
40
  analyze: "analyze_whole_document",
33
41
  view: "view_pages",
42
+ aggregate: "aggregate_table",
34
43
  };
35
44
  const documentId = { type: "string", description: "The document_id from the file's card." };
36
45
  const DECLARATIONS = {
37
46
  search: {
38
47
  name: TOOL_NAMES.search,
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.",
48
+ 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.",
40
49
  parameters: {
41
50
  type: "object",
42
51
  properties: {
43
52
  document_id: documentId,
44
53
  query: { type: "string", description: "Keywords, exact text, or a regex, depending on mode." },
45
54
  mode: { type: "string", enum: ["keywords", "exact", "regex"], description: "Defaults to keywords." },
46
- max_results: { type: "integer", description: "Up to 50 for exact/regex (default 20), up to 10 passages for keywords (default 5)." },
55
+ 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).` },
47
56
  context_lines: { type: "integer", description: "exact/regex only: lines to show before and after each match, 0-5." },
48
57
  case_sensitive: { type: "boolean", description: "exact/regex only. Defaults to false." },
58
+ 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." },
59
+ to_line: { type: "integer", description: "Search only up to this line." },
60
+ 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\"." },
61
+ 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." },
62
+ whole_word: { type: "boolean", description: "exact only: match the text only as a whole word, not inside a longer one. Defaults to false." },
49
63
  },
50
64
  required: ["document_id", "query"],
51
65
  },
@@ -80,6 +94,36 @@ const DECLARATIONS = {
80
94
  required: ["document_id", "task"],
81
95
  },
82
96
  },
97
+ aggregate: {
98
+ name: TOOL_NAMES.aggregate,
99
+ description: "Count, sum, average, or find the minimum or maximum over the rows of a table in an attached file: a CSV or TSV file, a sheet of an Excel workbook, or a table written as | cell | rows (in Word, PowerPoint, PDF or HTML files). It can keep only the rows that match filters, and group them by up to 3 columns (a date column by year, month or day). Its numbers are exact, as it reads every row: use it instead of reading rows to add them up or count them. Columns are named as in the table's header row; a letter (C) or a number (3) works too. Each group lists the lines of its first rows, to cite.",
100
+ parameters: {
101
+ type: "object",
102
+ properties: {
103
+ document_id: documentId,
104
+ table: { type: "string", description: "Which table: a sheet's name or number in a workbook, or a table's number in other files (1 is the first). Defaults to the first." },
105
+ metrics: { type: "array", items: { type: "string" }, description: "What to compute: \"count\", or an operation and a column: \"sum:Revenue\", \"avg:Price\", \"min:Date\", \"max:Amount\", \"count_distinct:Customer\". Defaults to [\"count\"]." },
106
+ group_by: { type: "array", items: { type: "string" }, description: "Up to 3 columns to group the rows by. A date column may end in \":year\", \":month\" or \":day\": \"Date:month\"." },
107
+ filters: {
108
+ type: "array",
109
+ description: "Keep only the rows that match all of these. Numbers compare as numbers, ISO dates (2026-03-01) as text, other text ignoring case.",
110
+ items: {
111
+ type: "object",
112
+ properties: {
113
+ column: { type: "string" },
114
+ op: { type: "string", enum: [...FILTER_OPS] },
115
+ value: { type: "string", description: "Not needed for empty and not_empty." },
116
+ },
117
+ required: ["column", "op"],
118
+ },
119
+ },
120
+ order_by: { type: "string", enum: ["metric", "key"], description: "\"metric\" (the default): the largest value of the first metric first; \"key\": by the values grouped by, in order (dates and months in time order)." },
121
+ limit: { type: "integer", description: `Groups to show, up to ${MAX_SHOWN_GROUPS} (default 50).` },
122
+ header_rows: { type: "integer", description: "Leave it out: the header is found by itself (a title row above it is skipped, and a header of two or three rows is joined, as \"Q1 / January\"). Only when a result's columns show the header was read wrong: how many rows it has, 0 to 5, below a title row." },
123
+ },
124
+ required: ["document_id"],
125
+ },
126
+ },
83
127
  view: {
84
128
  name: TOOL_NAMES.view,
85
129
  description: `Look at pages of an attached PDF as they are printed. Use it when the answer depends on something the text of the file cannot show: a picture, photo, chart, diagram, map, handwriting, a stamp or signature, or how a page is laid out. It is not for reading text. Up to ${MAX_VIEW_PAGES} pages per call.`,
@@ -101,6 +145,16 @@ function integer(value, fallback, min, max) {
101
145
  // The fallback is clamped too: a default end line must not point past the end of the file.
102
146
  return Math.min(max, Math.max(min, Math.trunc(Number.isFinite(number) ? number : fallback)));
103
147
  }
148
+ /**
149
+ * A boolean given by the model: on for `true`, and for "true" (in any case) or 1, as a number or as
150
+ * text. A model sometimes sends a boolean as text, as it does numbers; read as off, "true" gave
151
+ * another search than true without a word about it. Anything else is off.
152
+ */
153
+ function flag(value) {
154
+ if (value === true || value === 1)
155
+ return true;
156
+ return typeof value === "string" && /^\s*(?:true|1)\s*$/i.test(value);
157
+ }
104
158
  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.";
105
159
  function text(value, name) {
106
160
  if (typeof value !== "string" || !value.trim())
@@ -178,12 +232,16 @@ export function fitAnswer(result, limit) {
178
232
  function firstAndLastMatches(base, first, last, total, limit) {
179
233
  const which = (kept) => (kept === 0 ? `the last (line ${last.line})` : `the first${kept > 1 ? ` ${kept}` : ""} and the last (line ${last.line})`);
180
234
  const shown = (kept) => `${kept + 1} of the ${total} matching lines`;
235
+ // Where a search for the ones in between goes on: after the last of the first ones shown.
236
+ const next = (kept) => (kept > 0 ? first[kept - 1].line + 1 : undefined);
237
+ const between = (kept) => (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.");
181
238
  const withFirst = (kept, cut) => ({
182
239
  ...base,
183
240
  ...(cut
184
- ? { note: `Showing ${shown(kept)} to stay within the size limit: ${which(kept)}. Narrow the query or read specific lines.` }
241
+ ? { note: `Showing ${shown(kept)} to stay within the size limit: ${which(kept)}. ${between(kept)}` }
185
242
  // 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.` } : {}),
243
+ : kept + 1 < total ? { note: `${shown(kept)} are shown: ${which(kept)}. ${between(kept)}` } : {}),
244
+ ...(kept + 1 < total && next(kept) !== undefined ? { next_from_line: next(kept) } : {}),
187
245
  matches: [...first.slice(0, kept), last],
188
246
  });
189
247
  const whole = withFirst(first.length, false);
@@ -202,7 +260,263 @@ function firstAndLastMatches(base, first, last, total, limit) {
202
260
  const lastOnly = { ...base, note: `Showing 1 of the ${total} matching lines: ${which(0)}. Narrow the search.`, matches: [last] };
203
261
  return fit(lastOnly, null, limit);
204
262
  }
263
+ /**
264
+ * The result of a search with `order: "last"`: the last matching lines, in the order of the file,
265
+ * with a note that says so, and on which line the first match is. To fit `limit`, the earliest of
266
+ * them are dropped first: the very last stays. `stopped` is given when the scan stopped early: the
267
+ * last line of the lines searched, and the `to_line` of the call, which a search for the lines after
268
+ * those it found keeps.
269
+ */
270
+ function lastMatches(base, first, last, total, limit, stopped) {
271
+ const build = (kept, cut) => {
272
+ const shown = last.slice(last.length - kept);
273
+ const end = shown.at(-1)?.line;
274
+ // A scan that stopped early found these last: the lines after them were not all looked at. Its
275
+ // note starts as those of the other searches that stopped early do, which `alreadyShown` looks
276
+ // for: a later question has time of its own, and the call made then is run, not pointed back to.
277
+ if (stopped) {
278
+ // Nothing found means out of time (an exact search stops only past its limit on matches). It
279
+ // is not known where the scan stopped, so no line is named to search from.
280
+ if (end === undefined) {
281
+ 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 };
282
+ }
283
+ const lines = `${shown.length} ${plural(shown.length, "matching line")}`;
284
+ const which = cut ? `Showing the last ${lines} it found to stay within the size limit` : `These are the last ${lines} it found`;
285
+ // The search goes on after the last line found, in the same range. When that line is the last
286
+ // of the range, the scan stopped there and missed none of it: there is nothing to search on.
287
+ const later = end < stopped.end
288
+ ? ` There may be later ones, after line ${end}: search again with from_line ${end + 1}${stopped.toLine !== undefined ? ` and to_line ${stopped.toLine}` : ""}.`
289
+ : "";
290
+ return { ...base, note: `The scan stopped early; the total is a lower bound. ${which}, in the order of the file.${later}`, matches: shown };
291
+ }
292
+ const note = shown.length < total
293
+ // A cut result's note starts with "Showing ", as `alreadyShown` looks for: a call made later may have more room.
294
+ ? cut
295
+ ? `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.`
296
+ : `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}` : ""}.`
297
+ : undefined;
298
+ return { ...base, ...(note ? { note: typeof base.note === "string" ? `${base.note} ${note}` : note } : {}), matches: shown };
299
+ };
300
+ const whole = build(last.length, false);
301
+ if (JSON.stringify(whole).length <= limit)
302
+ return whole;
303
+ let kept = last.length;
304
+ while (kept > 1 && JSON.stringify(build(kept, true)).length > limit)
305
+ kept--;
306
+ return fit(build(kept, true), null, limit);
307
+ }
308
+ /** The result of a search with `group_by`: the total, then up to `shown` groups, cut further to fit `limit`. */
309
+ function groupedResult(base, counted, shown, limit) {
310
+ const byTime = base.group_by === "minute" || base.group_by === "hour" || base.group_by === "day";
311
+ const all = counted.groups.map(({ key, count, firstLine, lastLine }) => ({ key, count, first_line: firstLine, last_line: lastLine }));
312
+ // By time, the groups shown are the largest, put back in time order; so are those kept when the
313
+ // result is cut to its room. Cutting the end of the list there kept the earliest groups, while the
314
+ // note said the largest, and a model named the wrong hour as the busiest. The sort is stable: of
315
+ // groups of the same size, the earlier comes first.
316
+ const largest = byTime ? [...all].sort((left, right) => right.count - left.count) : all;
317
+ const pick = (kept) => (byTime ? largest.slice(0, kept).sort((left, right) => left.first_line - right.first_line) : all.slice(0, kept));
318
+ const most = Math.min(shown, all.length);
319
+ const extra = {
320
+ total_groups: counted.totalGroups,
321
+ ...(counted.otherCount > 0 ? { other_count: counted.otherCount, other_note: `Lines of groups past the first ${MAX_GROUP_KEYS.toLocaleString("en-US")} found.` } : {}),
322
+ ...(counted.ungrouped > 0 ? { lines_without_group: counted.ungrouped } : {}),
323
+ };
324
+ const build = (kept, cut) => {
325
+ const groups = pick(kept);
326
+ const order = byTime ? (groups.length < all.length ? "the largest, in time order" : "in time order") : "the largest first";
327
+ 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;
328
+ return { ...base, ...extra, ...(note ? { note: typeof base.note === "string" ? `${base.note} ${note}` : note } : {}), groups };
329
+ };
330
+ const whole = build(most, false);
331
+ if (JSON.stringify(whole).length <= limit)
332
+ return whole;
333
+ let kept = most;
334
+ while (kept > 1 && JSON.stringify(build(kept, true)).length > limit)
335
+ kept--;
336
+ return fit(build(kept, true), null, limit);
337
+ }
338
+ /** The most tables whose header rows one search result gives. */
339
+ const MAX_TABLE_HEADERS = 5;
340
+ /** Lines read at a time above a row of a `| cell |` table, to find the table's first row; and the most read in all. */
341
+ const HEADER_SEARCH_LINES = 500;
342
+ const MAX_HEADER_LOOKBACK = 20_000;
343
+ /** A section's title is given up to this many characters. */
344
+ const MAX_SECTION = 80;
345
+ const isPipeRow = (text) => {
346
+ const trimmed = text.trim();
347
+ return trimmed.length > 1 && trimmed.startsWith("|") && trimmed.endsWith("|");
348
+ };
349
+ /**
350
+ * Where the matches of a search sit, so a hit can be understood without another read:
351
+ * - `section(line)`: the heading of the outline above a line ("2.1 Rent", "Sheet 2: Sales");
352
+ * - `headers`: the first row of each table a match is a row of: line 1 of a CSV file, the first
353
+ * row of a sheet of a workbook, the first row of a `| cell |` table elsewhere. A row of 0.8.0's
354
+ * `Row 812: | 4,200 |` means little without its header.
355
+ */
356
+ async function locationsOf(document, matches) {
357
+ const { meta } = document;
358
+ // A store of your own may give metadata without an outline.
359
+ const outline = meta.format === "log" || meta.format === "json" || meta.format === "csv" || !Array.isArray(meta.outline) ? [] : meta.outline;
360
+ const section = (line) => {
361
+ let low = 0;
362
+ let high = outline.length - 1;
363
+ let found = -1;
364
+ while (low <= high) {
365
+ const middle = (low + high) >> 1;
366
+ if (outline[middle].line <= line) {
367
+ found = middle;
368
+ low = middle + 1;
369
+ }
370
+ else {
371
+ high = middle - 1;
372
+ }
373
+ }
374
+ return found === -1 ? undefined : sliceWhole(outline[found].title, MAX_SECTION);
375
+ };
376
+ const headers = new Map();
377
+ const add = async (line) => {
378
+ if (headers.has(line) || headers.size >= MAX_TABLE_HEADERS)
379
+ return;
380
+ const [text] = await document.readLines(line, line);
381
+ if (text !== undefined && text.trim())
382
+ headers.set(line, text.length > 400 ? `${sliceWhole(text, 400)}…` : text);
383
+ };
384
+ if (matches.length > 0) {
385
+ if (meta.format === "csv") {
386
+ if (matches.some((match) => match.line > 1))
387
+ await add(1);
388
+ }
389
+ else if (meta.format === "xlsx") {
390
+ // A sheet's first row is two lines below its "## Sheet" heading, after its "Columns:" line.
391
+ const checked = new Set();
392
+ for (const match of matches) {
393
+ const sheet = outline.filter((entry) => entry.title.startsWith("Sheet ") && entry.line <= match.line).at(-1);
394
+ if (!sheet || match.line <= sheet.line + 2 || checked.has(sheet.line))
395
+ continue;
396
+ checked.add(sheet.line);
397
+ const [first] = await document.readLines(sheet.line + 2, sheet.line + 2);
398
+ if (first?.startsWith("Row "))
399
+ await add(sheet.line + 2);
400
+ }
401
+ }
402
+ else {
403
+ const seen = new Set();
404
+ // The table found last: its first row, and its last line known to be a row. A later match in
405
+ // the same table is known by the rows between, read once, not by another look up the table.
406
+ let known;
407
+ for (const match of matches) {
408
+ if (!isPipeRow(match.text) || seen.size >= MAX_TABLE_HEADERS)
409
+ continue;
410
+ if (known && match.line >= known.first && match.line <= known.end)
411
+ continue;
412
+ if (known && match.line > known.end && match.line - known.end <= HEADER_SEARCH_LINES) {
413
+ const between = await document.readLines(known.end + 1, match.line);
414
+ if (between.every(isPipeRow)) {
415
+ known.end = match.line;
416
+ continue;
417
+ }
418
+ }
419
+ // Up the table a block at a time, to the first line that is not a row, or the file's start.
420
+ let line = match.line;
421
+ for (let looked = 0;;) {
422
+ const from = Math.max(1, line - HEADER_SEARCH_LINES);
423
+ const above = await document.readLines(from, line - 1);
424
+ let first = above.length;
425
+ while (first > 0 && isPipeRow(above[first - 1]))
426
+ first--;
427
+ if (first > 0 || from === 1) {
428
+ line = from + first;
429
+ break;
430
+ }
431
+ line = from;
432
+ looked += above.length;
433
+ // A table longer than this: its first row is not looked for.
434
+ if (looked >= MAX_HEADER_LOOKBACK) {
435
+ line = undefined;
436
+ break;
437
+ }
438
+ }
439
+ if (line === undefined)
440
+ continue;
441
+ known = { first: line, end: match.line };
442
+ if (line === match.line || seen.has(line))
443
+ continue;
444
+ seen.add(line);
445
+ await add(line);
446
+ }
447
+ }
448
+ }
449
+ return { section: outline.length > 0 ? section : () => undefined, headers: [...headers].map(([line, text]) => ({ line, text })) };
450
+ }
451
+ /** A list of strings the model sent: an array, or one string (which a model sometimes sends for a list of one). */
452
+ function stringList(value, name) {
453
+ if (value === undefined || value === null || value === "")
454
+ return undefined;
455
+ const list = Array.isArray(value) ? value : [value];
456
+ return list.map((item) => {
457
+ if (typeof item !== "string" && typeof item !== "number")
458
+ throw new Error(`${name} must be a list of strings.`);
459
+ return String(item);
460
+ });
461
+ }
462
+ /** The arguments of an `aggregate_table` call as the tool reads them. */
463
+ export function aggregateRequest(args) {
464
+ const rawFilters = args.filters === undefined || args.filters === null ? [] : Array.isArray(args.filters) ? args.filters : [args.filters];
465
+ const filters = rawFilters.map((filter) => {
466
+ const { column, op, value } = (filter ?? {});
467
+ if (typeof column !== "string" && typeof column !== "number")
468
+ throw new Error("Each filter needs a column.");
469
+ if (typeof op !== "string" || !FILTER_OPS.includes(op))
470
+ throw new Error(`A filter's op must be one of ${FILTER_OPS.map((name) => `"${name}"`).join(", ")}.`);
471
+ return { column: String(column), op: op, ...(value !== undefined && value !== null ? { value: typeof value === "number" ? value : String(value) } : {}) };
472
+ });
473
+ const table = typeof args.table === "number" || (typeof args.table === "string" && args.table.trim()) ? args.table : undefined;
474
+ const groupBy = stringList(args.group_by, "group_by");
475
+ const metrics = stringList(args.metrics, "metrics");
476
+ return {
477
+ ...(table !== undefined ? { table } : {}),
478
+ ...(filters.length > 0 ? { filters } : {}),
479
+ ...(groupBy ? { groupBy } : {}),
480
+ ...(metrics ? { metrics } : {}),
481
+ orderBy: args.order_by === "key" ? "key" : "metric",
482
+ limit: integer(args.limit, 50, 1, MAX_SHOWN_GROUPS),
483
+ ...(args.header_rows !== undefined && args.header_rows !== null && args.header_rows !== "" ? { headerRows: integer(args.header_rows, 1, 0, 5) } : {}),
484
+ };
485
+ }
205
486
  const searchMode = (mode) => (mode === "exact" || mode === "regex" ? mode : "keywords");
487
+ /** `group_by` as the search reads it: undefined when not given. A value it does not know is an error. */
488
+ function groupByOf(value) {
489
+ if (value === undefined || value === null || value === "" || value === "none")
490
+ return undefined;
491
+ if (typeof value === "string" && GROUP_BY_VALUES.includes(value))
492
+ return value;
493
+ throw new Error(`group_by must be one of ${GROUP_BY_VALUES.map((name) => `"${name}"`).join(", ")}.`);
494
+ }
495
+ /** A line number of a search's range, as the search reads it: undefined when not given. */
496
+ const rangeLine = (value) => (value === undefined || value === null || value === "" ? undefined : integer(value, 1, 1, Number.MAX_SAFE_INTEGER));
497
+ /**
498
+ * The arguments of a search that choose which lines it looks at and how it shows them, as the
499
+ * search reads them. The search, its key and its label all read them here, so that they agree.
500
+ */
501
+ function searchScope(args) {
502
+ const fromLine = rangeLine(args.from_line);
503
+ const toLine = rangeLine(args.to_line);
504
+ let groupBy;
505
+ try {
506
+ groupBy = groupByOf(args.group_by);
507
+ }
508
+ catch {
509
+ groupBy = undefined;
510
+ }
511
+ return {
512
+ ...(fromLine !== undefined ? { fromLine } : {}),
513
+ ...(toLine !== undefined ? { toLine } : {}),
514
+ order: args.order === "last" ? "last" : "first",
515
+ ...(groupBy ? { groupBy } : {}),
516
+ wholeWord: flag(args.whole_word),
517
+ caseSensitive: flag(args.case_sensitive),
518
+ };
519
+ }
206
520
  /** The lines a `read_document` call asks for, as its handler reads them, before the end of the file is known. */
207
521
  function requestedLines(args) {
208
522
  const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
@@ -221,12 +535,33 @@ export function toolCallKey(name, args) {
221
535
  if (typeof args.query !== "string" || !args.query.trim())
222
536
  return undefined;
223
537
  const mode = searchMode(args.mode);
538
+ // A group_by the search refuses: the call answers with an error, and is not compared.
539
+ try {
540
+ groupByOf(args.group_by);
541
+ }
542
+ catch {
543
+ return undefined;
544
+ }
545
+ const { fromLine, toLine, order, groupBy, wholeWord, caseSensitive } = searchScope(args);
546
+ // The arguments of 0.8.0 are added only when given: a call without them has the key it had.
547
+ const scope = [
548
+ ...(fromLine !== undefined || toLine !== undefined ? [fromLine ?? 1, toLine ?? null] : []),
549
+ ...(mode !== "keywords" && (order === "last" || groupBy || wholeWord) ? [order, groupBy ?? null, mode === "exact" && wholeWord] : []),
550
+ ];
224
551
  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]);
552
+ ? [name, id, args.query, mode, integer(args.max_results, 5, 1, 10), ...scope]
553
+ : [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]);
227
554
  }
228
555
  if (name === TOOL_NAMES.read)
229
556
  return JSON.stringify([name, id, ...requestedLines(args)]);
557
+ if (name === TOOL_NAMES.aggregate) {
558
+ try {
559
+ return JSON.stringify([name, id, aggregateRequest(args)]);
560
+ }
561
+ catch {
562
+ return undefined;
563
+ }
564
+ }
230
565
  if (name === TOOL_NAMES.overview)
231
566
  return JSON.stringify([name, id]);
232
567
  return undefined;
@@ -246,6 +581,10 @@ export function alreadyShown(call, earlier, stored = false) {
246
581
  return undefined;
247
582
  if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true)
248
583
  return undefined;
584
+ // A search stored by 0.7.0 with case_sensitive or whole_word as text or 1 ("true", 1): 0.7.0 read
585
+ // those as off, 0.8.0 as on, so the call made now would not return what was stored.
586
+ 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)))
587
+ return undefined;
249
588
  // A list that `fit` cut to the room it had, a read whose text was cut, or a search that ran out of
250
589
  // time ("the total is a lower bound"; a later question has time of its own): a call made now may get more.
251
590
  if (typeof result.note === "string" && (result.note.startsWith("Showing ") || result.note.startsWith("The scan stopped early")))
@@ -312,10 +651,15 @@ export function toolResultSummary(label, result) {
312
651
  if (typeof result.error === "string")
313
652
  return ` — failed: ${result.error}`;
314
653
  if (typeof result.total_matching_lines === "number") {
315
- return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}`;
654
+ const groups = typeof result.total_groups === "number" ? ` in ${result.total_groups.toLocaleString("en-US")} ${plural(result.total_groups, "group")}` : "";
655
+ return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}${groups}`;
316
656
  }
317
657
  if (Array.isArray(result.passages))
318
658
  return ` — ${result.passages.length} ${plural(result.passages.length, "passage")}`;
659
+ if (typeof result.rows_matched === "number") {
660
+ const groups = typeof result.total_groups === "number" ? `, ${result.total_groups.toLocaleString("en-US")} ${plural(result.total_groups, "group")}` : "";
661
+ return ` — ${result.rows_matched.toLocaleString("en-US")} ${plural(result.rows_matched, "row")}${groups}`;
662
+ }
319
663
  if (typeof result.parts_read === "number") {
320
664
  const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
321
665
  return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
@@ -358,10 +702,13 @@ export function createDocumentTools(options) {
358
702
  // The text tools are left out only when there are pages to look at and no document to search.
359
703
  const textTools = allowed.size > 0 || viewable.size === 0;
360
704
  const declarations = [
361
- ...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
705
+ ...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.tables ? [DECLARATIONS.aggregate] : []), ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
362
706
  ...(viewable.size > 0 ? [DECLARATIONS.view] : []),
363
707
  ];
364
708
  const known = new Set(declarations.map((declaration) => declaration.name));
709
+ // Answered for any document, declared or not: a model may know the tool from earlier in the conversation.
710
+ if (textTools)
711
+ known.add(TOOL_NAMES.aggregate);
365
712
  // Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
366
713
  if (textTools && options.generate)
367
714
  known.add(TOOL_NAMES.analyze);
@@ -383,6 +730,12 @@ export function createDocumentTools(options) {
383
730
  regexQueue = next.catch(() => undefined);
384
731
  return next;
385
732
  };
733
+ const givenReads = options.maxWholeDocumentReads;
734
+ // NaN failed every comparison, so it let a document be read whole any number of times.
735
+ if (givenReads !== undefined && (typeof givenReads !== "number" || Number.isNaN(givenReads))) {
736
+ const shown = typeof givenReads === "number" ? String(givenReads) : typeof givenReads === "string" ? JSON.stringify(givenReads) : typeof givenReads;
737
+ throw new (typeof givenReads === "number" ? RangeError : TypeError)(`maxWholeDocumentReads must be a number, and is ${shown}.`);
738
+ }
386
739
  const maxWholeReads = Math.max(0, Math.trunc(options.maxWholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS));
387
740
  /** Whole-document reads started, by document. */
388
741
  const wholeReads = new Map();
@@ -415,13 +768,27 @@ export function createDocumentTools(options) {
415
768
  // Page numbers are added only for a PDF whose pages can be looked at: they are what
416
769
  // view_pages takes. Everything else gets the results of 0.2.0 unchanged.
417
770
  const paged = viewable.has(document.meta.id);
771
+ const groupBy = groupByOf(args.group_by);
772
+ const { fromLine, toLine, order, wholeWord, caseSensitive } = searchScope(args);
773
+ const total = document.lineCount;
774
+ if (fromLine !== undefined && fromLine > total)
775
+ throw new Error(`from_line ${fromLine} is past the end of the file, which has ${total} ${plural(total, "line")}.`);
776
+ if (toLine !== undefined && toLine < (fromLine ?? 1))
777
+ throw new Error(`to_line ${toLine} is before from_line ${fromLine ?? 1}.`);
778
+ const ranged = fromLine !== undefined || toLine !== undefined;
779
+ const range = { from: fromLine ?? 1, to: Math.min(total, toLine ?? total) };
780
+ // Said in the result when part of the file was searched: the counts are of those lines.
781
+ const searched = ranged ? { searched_lines: `${range.from}-${range.to}` } : {};
418
782
  if (mode === "keywords") {
783
+ if (groupBy)
784
+ throw new Error("group_by counts the lines of an exact or regex search: use mode \"exact\" or \"regex\".");
419
785
  const topK = integer(args.max_results, 5, 1, 10);
420
- const ranked = await rankSource(document, query, topK, options.signal);
786
+ const ranked = await rankSource(document, query, topK, options.signal, ranged ? range : undefined);
421
787
  const texts = await Promise.all(ranked.map((passage) => document.readLines(passage.from, passage.to)));
422
788
  return fit({
423
789
  document: document.meta.name,
424
790
  mode,
791
+ ...searched,
425
792
  passages: ranked.map((passage, index) => {
426
793
  const pages = paged ? document.pagesOfLines(passage.from, passage.to) : undefined;
427
794
  return {
@@ -435,6 +802,7 @@ export function createDocumentTools(options) {
435
802
  }, "passages", limit);
436
803
  }
437
804
  const regex = mode === "regex";
805
+ const shownGroups = integer(args.max_results, DEFAULT_GROUPS, 1, MAX_GROUPS);
438
806
  const grep = async () => {
439
807
  const regexLeft = regexBudget - regexClock.usedMs;
440
808
  if (regex && regexLeft <= 0) {
@@ -442,23 +810,44 @@ export function createDocumentTools(options) {
442
810
  }
443
811
  return grepSource(document, query, {
444
812
  regex,
445
- caseSensitive: args.case_sensitive === true,
446
- maxResults: integer(args.max_results, 20, 1, 50),
813
+ caseSensitive,
814
+ maxResults: integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS),
447
815
  contextLines: integer(args.context_lines, 0, 0, 5),
448
816
  ...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
449
817
  ...(options.signal ? { signal: options.signal } : {}),
818
+ ...(ranged ? { fromLine: range.from, toLine: range.to } : {}),
819
+ ...(order === "last" ? { order } : {}),
820
+ ...(groupBy ? { groupBy } : {}),
821
+ ...(wholeWord && !regex ? { wholeWord } : {}),
450
822
  });
451
823
  };
452
824
  const result = await (regex ? inRegexTurn(grep) : grep());
825
+ const shownMatches = [...(result.first ? [result.first] : []), ...result.matches, ...(result.last ? [result.last] : [])];
826
+ const where = await locationsOf(document, shownMatches);
453
827
  const placed = (match) => {
454
- if (!paged)
828
+ const page = paged ? document.pageOfLine(match.line) : undefined;
829
+ const section = where.section(match.line);
830
+ if (!page && !section)
455
831
  return match;
456
832
  const { line, ...rest } = match;
457
- const page = document.pageOfLine(line);
458
- return { line, ...(page ? { page } : {}), ...rest };
833
+ return { line, ...(page ? { page } : {}), ...(section ? { section } : {}), ...rest };
834
+ };
835
+ const base = {
836
+ document: document.meta.name,
837
+ mode,
838
+ ...searched,
839
+ total_matching_lines: result.totalMatchingLines,
840
+ ...(where.headers.length > 0 ? { table_headers: where.headers } : {}),
459
841
  };
460
- const base = { document: document.meta.name, mode, total_matching_lines: result.totalMatchingLines };
842
+ const stopped = result.stoppedEarly ? { note: "The scan stopped early; the counts are lower bounds." } : {};
843
+ if (result.groups)
844
+ return groupedResult({ ...base, group_by: groupBy, ...stopped }, result.groups, shownGroups, limit);
461
845
  const matches = result.matches.map(placed);
846
+ if (order === "last") {
847
+ // The range a search for the lines after those found goes on in, when the scan stopped early.
848
+ const rest = result.stoppedEarly ? { end: range.to, ...(toLine !== undefined ? { toLine: range.to } : {}) } : undefined;
849
+ return lastMatches({ ...base, order }, result.first ? placed(result.first) : undefined, matches, result.totalMatchingLines, limit, rest);
850
+ }
462
851
  if (!result.stoppedEarly && result.totalMatchingLines >= 2) {
463
852
  // The last match is `last`, or, when every match is among the first ones, the last of them.
464
853
  return result.last
@@ -526,6 +915,40 @@ export function createDocumentTools(options) {
526
915
  outline: meta.outline.length ? outlineLines(meta.outline) : [],
527
916
  }, "outline", limit);
528
917
  },
918
+ async [TOOL_NAMES.aggregate](args, limits) {
919
+ const limit = limitOf(limits);
920
+ const document = await documentFor(args);
921
+ const request = aggregateRequest(args);
922
+ const result = await aggregateTable(document, request, options.signal);
923
+ const groups = result.groups.map((group) => ({
924
+ ...(Object.keys(group.key).length > 0 ? { group: group.key } : {}),
925
+ ...group.values,
926
+ ...(group.values.count === undefined ? { rows: group.count } : {}),
927
+ lines: group.lines,
928
+ }));
929
+ const shownColumns = result.columns.slice(0, 60);
930
+ const base = {
931
+ document: document.meta.name,
932
+ table: result.table,
933
+ ...(result.tables > 1 ? { tables_in_file: result.tables } : {}),
934
+ header_line: result.headerLine,
935
+ ...(result.headerRows !== 1 ? { header_rows: result.headerRows } : {}),
936
+ ...(result.title !== undefined ? { title: result.title } : {}),
937
+ columns: result.columns.length > shownColumns.length ? [...shownColumns, `… ${result.columns.length - shownColumns.length} more`] : shownColumns,
938
+ rows_read: result.rowsRead,
939
+ rows_matched: result.rowsMatched,
940
+ ...(result.totalGroups > 1 || (request.groupBy?.length ?? 0) > 0 ? { total_groups: result.totalGroups } : {}),
941
+ ...(result.otherRows > 0 ? { other_rows: result.otherRows, other_note: `Rows of groups past the first ${MAX_GROUP_KEYS.toLocaleString("en-US")} found.` } : {}),
942
+ ...(Object.keys(result.notNumbers).length > 0 ? { values_not_numbers: result.notNumbers, values_note: "Cells of these columns that are not numbers were left out of the metric." } : {}),
943
+ ...(result.repeatedHeaders > 0 ? { repeated_header_rows: result.repeatedHeaders } : {}),
944
+ ...(result.distinctCapped ? { distinct_note: "count_distinct stopped telling values apart after 1,000,000 in all: its counts are lower bounds. Filter, or group by fewer values." } : {}),
945
+ ...(result.irregularRows > 0 ? { irregular_rows: result.irregularRows, irregular_note: "Rows with values past the header's columns: check columns and header_rows." } : {}),
946
+ };
947
+ const note = groups.length < result.totalGroups
948
+ ? { note: `${groups.length} of the ${result.totalGroups} groups are shown, ${request.orderBy === "key" ? "in the order of their values" : "the largest first"}. Raise limit, or filter, for the others.` }
949
+ : {};
950
+ return fit({ ...base, ...note, groups }, "groups", limit);
951
+ },
529
952
  async [TOOL_NAMES.analyze](args, limits, hooks) {
530
953
  if (!options.generate)
531
954
  throw new Error("Whole-document analysis is not enabled.");
@@ -691,7 +1114,10 @@ export function createDocumentTools(options) {
691
1114
  }
692
1115
  if (name === TOOL_NAMES.search) {
693
1116
  const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
694
- return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”`;
1117
+ const { fromLine, toLine, order, groupBy } = searchScope(args);
1118
+ const where = fromLine !== undefined || toLine !== undefined ? ` in lines ${fromLine ?? 1}-${toLine ?? "end"}` : "";
1119
+ const how = mode === "keywords" ? "" : groupBy ? `, counted by ${groupBy}` : order === "last" ? ", the last ones" : "";
1120
+ return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”${where}${how}`;
695
1121
  }
696
1122
  if (name === TOOL_NAMES.read) {
697
1123
  const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
@@ -700,6 +1126,21 @@ export function createDocumentTools(options) {
700
1126
  }
701
1127
  if (name === TOOL_NAMES.overview)
702
1128
  return `Overview of ${file}`;
1129
+ if (name === TOOL_NAMES.aggregate) {
1130
+ const request = (() => {
1131
+ try {
1132
+ return aggregateRequest(args);
1133
+ }
1134
+ catch {
1135
+ return {};
1136
+ }
1137
+ })();
1138
+ const metrics = (request.metrics?.length ? request.metrics : ["count"]).join(", ");
1139
+ const by = request.groupBy?.length ? ` by ${request.groupBy.join(", ")}` : "";
1140
+ const where = request.filters?.length ? ` where ${request.filters.map((filter) => `${filter.column} ${filter.op}${filter.value !== undefined && filter.value !== "" ? ` ${filter.value}` : ""}`).join(" and ")}` : "";
1141
+ const table = request.table !== undefined && request.table !== "" ? ` (${typeof request.table === "number" ? `table ${request.table}` : request.table})` : "";
1142
+ return sliceWhole(`Aggregate ${file}${table}: ${metrics}${by}${where}`, 200);
1143
+ }
703
1144
  if (name === TOOL_NAMES.analyze)
704
1145
  return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”`;
705
1146
  return name;