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/src/tools.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { safeErrorMessage } from "./errors.js";
2
+ import { aggregateTable, FILTER_OPS, MAX_SHOWN_GROUPS, type AggregateRequest, type FilterOp } from "./aggregate.js";
3
+ import { GROUP_BY_VALUES, MAX_GROUP_KEYS, type GroupBy, type GroupResult } 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, type DocumentSource, type LineMatch } from "./search.js";
@@ -8,6 +10,12 @@ import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
8
10
  import type { Budget, GenerateText, ProgressListener, ToolCallHooks, ToolCallLimits, ToolDeclaration, ToolOutput, ToolResult, ToolSet } from "./types.js";
9
11
 
10
12
  const DEFAULT_READ_LINES = 200;
13
+ /** Matching lines an exact or regex search shows: the default, and the most a call may ask for. */
14
+ const DEFAULT_GREP_RESULTS = 20;
15
+ const MAX_GREP_RESULTS = 50;
16
+ /** Groups a search with `group_by` shows: the default, and the most a call may ask for. */
17
+ const DEFAULT_GROUPS = 50;
18
+ const MAX_GROUPS = 200;
11
19
  const MAX_READ_LINES = 600;
12
20
  /** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
13
21
  export const MAX_VIEW_PAGES = 5;
@@ -35,6 +43,7 @@ export const TOOL_NAMES = {
35
43
  overview: "get_document_overview",
36
44
  analyze: "analyze_whole_document",
37
45
  view: "view_pages",
46
+ aggregate: "aggregate_table",
38
47
  } as const;
39
48
 
40
49
  const documentId = { type: "string" as const, description: "The document_id from the file's card." };
@@ -42,16 +51,21 @@ const documentId = { type: "string" as const, description: "The document_id from
42
51
  const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
43
52
  search: {
44
53
  name: TOOL_NAMES.search,
45
- description: "Search a large attached file. mode \"keywords\" returns the most relevant passages for a question; \"exact\" finds the lines that contain the text; \"regex\" finds the lines that match a JavaScript regular expression. For exact and regex, total_matching_lines counts every matching line, and the result shows the first max_results of them and the last one. Results include line numbers to read further with read_document.",
54
+ 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.",
46
55
  parameters: {
47
56
  type: "object",
48
57
  properties: {
49
58
  document_id: documentId,
50
59
  query: { type: "string", description: "Keywords, exact text, or a regex, depending on mode." },
51
60
  mode: { type: "string", enum: ["keywords", "exact", "regex"], description: "Defaults to keywords." },
52
- max_results: { type: "integer", description: "Up to 50 for exact/regex (default 20), up to 10 passages for keywords (default 5)." },
61
+ 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).` },
53
62
  context_lines: { type: "integer", description: "exact/regex only: lines to show before and after each match, 0-5." },
54
63
  case_sensitive: { type: "boolean", description: "exact/regex only. Defaults to false." },
64
+ 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." },
65
+ to_line: { type: "integer", description: "Search only up to this line." },
66
+ 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\"." },
67
+ 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." },
68
+ whole_word: { type: "boolean", description: "exact only: match the text only as a whole word, not inside a longer one. Defaults to false." },
55
69
  },
56
70
  required: ["document_id", "query"],
57
71
  },
@@ -86,6 +100,36 @@ const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
86
100
  required: ["document_id", "task"],
87
101
  },
88
102
  },
103
+ aggregate: {
104
+ name: TOOL_NAMES.aggregate,
105
+ 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.",
106
+ parameters: {
107
+ type: "object",
108
+ properties: {
109
+ document_id: documentId,
110
+ 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." },
111
+ 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\"]." },
112
+ 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\"." },
113
+ filters: {
114
+ type: "array",
115
+ 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.",
116
+ items: {
117
+ type: "object",
118
+ properties: {
119
+ column: { type: "string" },
120
+ op: { type: "string", enum: [...FILTER_OPS] },
121
+ value: { type: "string", description: "Not needed for empty and not_empty." },
122
+ },
123
+ required: ["column", "op"],
124
+ },
125
+ },
126
+ 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)." },
127
+ limit: { type: "integer", description: `Groups to show, up to ${MAX_SHOWN_GROUPS} (default 50).` },
128
+ 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." },
129
+ },
130
+ required: ["document_id"],
131
+ },
132
+ },
89
133
  view: {
90
134
  name: TOOL_NAMES.view,
91
135
  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.`,
@@ -110,6 +154,16 @@ function integer(value: unknown, fallback: number, min: number, max: number): nu
110
154
  return Math.min(max, Math.max(min, Math.trunc(Number.isFinite(number) ? number : fallback)));
111
155
  }
112
156
 
157
+ /**
158
+ * A boolean given by the model: on for `true`, and for "true" (in any case) or 1, as a number or as
159
+ * text. A model sometimes sends a boolean as text, as it does numbers; read as off, "true" gave
160
+ * another search than true without a word about it. Anything else is off.
161
+ */
162
+ function flag(value: unknown): boolean {
163
+ if (value === true || value === 1) return true;
164
+ return typeof value === "string" && /^\s*(?:true|1)\s*$/i.test(value);
165
+ }
166
+
113
167
  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.";
114
168
 
115
169
  function text(value: unknown, name: string): string {
@@ -185,12 +239,16 @@ export function fitAnswer(result: ToolResult, limit: number): ToolResult {
185
239
  function firstAndLastMatches(base: ToolResult, first: LineMatch[], last: LineMatch, total: number, limit: number): ToolResult {
186
240
  const which = (kept: number) => (kept === 0 ? `the last (line ${last.line})` : `the first${kept > 1 ? ` ${kept}` : ""} and the last (line ${last.line})`);
187
241
  const shown = (kept: number) => `${kept + 1} of the ${total} matching lines`;
242
+ // Where a search for the ones in between goes on: after the last of the first ones shown.
243
+ const next = (kept: number) => (kept > 0 ? first[kept - 1]!.line + 1 : undefined);
244
+ 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.");
188
245
  const withFirst = (kept: number, cut: boolean): ToolResult => ({
189
246
  ...base,
190
247
  ...(cut
191
- ? { note: `Showing ${shown(kept)} to stay within the size limit: ${which(kept)}. Narrow the query or read specific lines.` }
248
+ ? { note: `Showing ${shown(kept)} to stay within the size limit: ${which(kept)}. ${between(kept)}` }
192
249
  // When every match is shown, there is nothing to say.
193
- : kept + 1 < total ? { note: `${shown(kept)} are shown: ${which(kept)}. To see the ones in between, narrow the search.` } : {}),
250
+ : kept + 1 < total ? { note: `${shown(kept)} are shown: ${which(kept)}. ${between(kept)}` } : {}),
251
+ ...(kept + 1 < total && next(kept) !== undefined ? { next_from_line: next(kept) } : {}),
194
252
  matches: [...first.slice(0, kept), last],
195
253
  });
196
254
  const whole = withFirst(first.length, false);
@@ -207,8 +265,250 @@ function firstAndLastMatches(base: ToolResult, first: LineMatch[], last: LineMat
207
265
  return fit(lastOnly, null, limit);
208
266
  }
209
267
 
268
+ /**
269
+ * The result of a search with `order: "last"`: the last matching lines, in the order of the file,
270
+ * with a note that says so, and on which line the first match is. To fit `limit`, the earliest of
271
+ * them are dropped first: the very last stays. `stopped` is given when the scan stopped early: the
272
+ * last line of the lines searched, and the `to_line` of the call, which a search for the lines after
273
+ * those it found keeps.
274
+ */
275
+ function lastMatches(base: ToolResult, first: LineMatch | undefined, last: LineMatch[], total: number, limit: number, stopped?: { end: number; toLine?: number }): ToolResult {
276
+ const build = (kept: number, cut: boolean): ToolResult => {
277
+ const shown = last.slice(last.length - kept);
278
+ const end = shown.at(-1)?.line;
279
+ // A scan that stopped early found these last: the lines after them were not all looked at. Its
280
+ // note starts as those of the other searches that stopped early do, which `alreadyShown` looks
281
+ // for: a later question has time of its own, and the call made then is run, not pointed back to.
282
+ if (stopped) {
283
+ // Nothing found means out of time (an exact search stops only past its limit on matches). It
284
+ // is not known where the scan stopped, so no line is named to search from.
285
+ if (end === undefined) {
286
+ 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 };
287
+ }
288
+ const lines = `${shown.length} ${plural(shown.length, "matching line")}`;
289
+ const which = cut ? `Showing the last ${lines} it found to stay within the size limit` : `These are the last ${lines} it found`;
290
+ // The search goes on after the last line found, in the same range. When that line is the last
291
+ // of the range, the scan stopped there and missed none of it: there is nothing to search on.
292
+ const later = end < stopped.end
293
+ ? ` There may be later ones, after line ${end}: search again with from_line ${end + 1}${stopped.toLine !== undefined ? ` and to_line ${stopped.toLine}` : ""}.`
294
+ : "";
295
+ return { ...base, note: `The scan stopped early; the total is a lower bound. ${which}, in the order of the file.${later}`, matches: shown };
296
+ }
297
+ const note = shown.length < total
298
+ // A cut result's note starts with "Showing ", as `alreadyShown` looks for: a call made later may have more room.
299
+ ? cut
300
+ ? `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.`
301
+ : `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}` : ""}.`
302
+ : undefined;
303
+ return { ...base, ...(note ? { note: typeof base.note === "string" ? `${base.note} ${note}` : note } : {}), matches: shown };
304
+ };
305
+ const whole = build(last.length, false);
306
+ if (JSON.stringify(whole).length <= limit) return whole;
307
+ let kept = last.length;
308
+ while (kept > 1 && JSON.stringify(build(kept, true)).length > limit) kept--;
309
+ return fit(build(kept, true), null, limit);
310
+ }
311
+
312
+ /** The result of a search with `group_by`: the total, then up to `shown` groups, cut further to fit `limit`. */
313
+ function groupedResult(base: ToolResult, counted: GroupResult, shown: number, limit: number): ToolResult {
314
+ const byTime = base.group_by === "minute" || base.group_by === "hour" || base.group_by === "day";
315
+ const all = counted.groups.map(({ key, count, firstLine, lastLine }) => ({ key, count, first_line: firstLine, last_line: lastLine }));
316
+ // By time, the groups shown are the largest, put back in time order; so are those kept when the
317
+ // result is cut to its room. Cutting the end of the list there kept the earliest groups, while the
318
+ // note said the largest, and a model named the wrong hour as the busiest. The sort is stable: of
319
+ // groups of the same size, the earlier comes first.
320
+ const largest = byTime ? [...all].sort((left, right) => right.count - left.count) : all;
321
+ const pick = (kept: number) => (byTime ? largest.slice(0, kept).sort((left, right) => left.first_line - right.first_line) : all.slice(0, kept));
322
+ const most = Math.min(shown, all.length);
323
+ const extra = {
324
+ total_groups: counted.totalGroups,
325
+ ...(counted.otherCount > 0 ? { other_count: counted.otherCount, other_note: `Lines of groups past the first ${MAX_GROUP_KEYS.toLocaleString("en-US")} found.` } : {}),
326
+ ...(counted.ungrouped > 0 ? { lines_without_group: counted.ungrouped } : {}),
327
+ };
328
+ const build = (kept: number, cut: boolean): ToolResult => {
329
+ const groups = pick(kept);
330
+ const order = byTime ? (groups.length < all.length ? "the largest, in time order" : "in time order") : "the largest first";
331
+ 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;
332
+ return { ...base, ...extra, ...(note ? { note: typeof base.note === "string" ? `${base.note} ${note}` : note } : {}), groups };
333
+ };
334
+ const whole = build(most, false);
335
+ if (JSON.stringify(whole).length <= limit) return whole;
336
+ let kept = most;
337
+ while (kept > 1 && JSON.stringify(build(kept, true)).length > limit) kept--;
338
+ return fit(build(kept, true), null, limit);
339
+ }
340
+
341
+ /** The most tables whose header rows one search result gives. */
342
+ const MAX_TABLE_HEADERS = 5;
343
+ /** 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. */
344
+ const HEADER_SEARCH_LINES = 500;
345
+ const MAX_HEADER_LOOKBACK = 20_000;
346
+ /** A section's title is given up to this many characters. */
347
+ const MAX_SECTION = 80;
348
+
349
+ const isPipeRow = (text: string) => {
350
+ const trimmed = text.trim();
351
+ return trimmed.length > 1 && trimmed.startsWith("|") && trimmed.endsWith("|");
352
+ };
353
+
354
+ /**
355
+ * Where the matches of a search sit, so a hit can be understood without another read:
356
+ * - `section(line)`: the heading of the outline above a line ("2.1 Rent", "Sheet 2: Sales");
357
+ * - `headers`: the first row of each table a match is a row of: line 1 of a CSV file, the first
358
+ * row of a sheet of a workbook, the first row of a `| cell |` table elsewhere. A row of 0.8.0's
359
+ * `Row 812: | 4,200 |` means little without its header.
360
+ */
361
+ async function locationsOf(document: DocumentSource, matches: LineMatch[]): Promise<{ section(line: number): string | undefined; headers: Array<{ line: number; text: string }> }> {
362
+ const { meta } = document;
363
+ // A store of your own may give metadata without an outline.
364
+ const outline = meta.format === "log" || meta.format === "json" || meta.format === "csv" || !Array.isArray(meta.outline) ? [] : meta.outline;
365
+ const section = (line: number): string | undefined => {
366
+ let low = 0;
367
+ let high = outline.length - 1;
368
+ let found = -1;
369
+ while (low <= high) {
370
+ const middle = (low + high) >> 1;
371
+ if (outline[middle]!.line <= line) {
372
+ found = middle;
373
+ low = middle + 1;
374
+ } else {
375
+ high = middle - 1;
376
+ }
377
+ }
378
+ return found === -1 ? undefined : sliceWhole(outline[found]!.title, MAX_SECTION);
379
+ };
380
+ const headers = new Map<number, string>();
381
+ const add = async (line: number) => {
382
+ if (headers.has(line) || headers.size >= MAX_TABLE_HEADERS) return;
383
+ const [text] = await document.readLines(line, line);
384
+ if (text !== undefined && text.trim()) headers.set(line, text.length > 400 ? `${sliceWhole(text, 400)}…` : text);
385
+ };
386
+ if (matches.length > 0) {
387
+ if (meta.format === "csv") {
388
+ if (matches.some((match) => match.line > 1)) await add(1);
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<number>();
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)) continue;
395
+ checked.add(sheet.line);
396
+ const [first] = await document.readLines(sheet.line + 2, sheet.line + 2);
397
+ if (first?.startsWith("Row ")) await add(sheet.line + 2);
398
+ }
399
+ } else {
400
+ const seen = new Set<number>();
401
+ // The table found last: its first row, and its last line known to be a row. A later match in
402
+ // the same table is known by the rows between, read once, not by another look up the table.
403
+ let known: { first: number; end: number } | undefined;
404
+ for (const match of matches) {
405
+ if (!isPipeRow(match.text) || seen.size >= MAX_TABLE_HEADERS) continue;
406
+ if (known && match.line >= known.first && match.line <= known.end) continue;
407
+ if (known && match.line > known.end && match.line - known.end <= HEADER_SEARCH_LINES) {
408
+ const between = await document.readLines(known.end + 1, match.line);
409
+ if (between.every(isPipeRow)) {
410
+ known.end = match.line;
411
+ continue;
412
+ }
413
+ }
414
+ // Up the table a block at a time, to the first line that is not a row, or the file's start.
415
+ let line: number | undefined = match.line;
416
+ for (let looked = 0; ; ) {
417
+ const from: number = Math.max(1, line - HEADER_SEARCH_LINES);
418
+ const above = await document.readLines(from, line - 1);
419
+ let first = above.length;
420
+ while (first > 0 && isPipeRow(above[first - 1]!)) first--;
421
+ if (first > 0 || from === 1) {
422
+ line = from + first;
423
+ break;
424
+ }
425
+ line = from;
426
+ looked += above.length;
427
+ // A table longer than this: its first row is not looked for.
428
+ if (looked >= MAX_HEADER_LOOKBACK) {
429
+ line = undefined;
430
+ break;
431
+ }
432
+ }
433
+ if (line === undefined) continue;
434
+ known = { first: line, end: match.line };
435
+ if (line === match.line || seen.has(line)) continue;
436
+ seen.add(line);
437
+ await add(line);
438
+ }
439
+ }
440
+ }
441
+ return { section: outline.length > 0 ? section : () => undefined, headers: [...headers].map(([line, text]) => ({ line, text })) };
442
+ }
443
+
444
+ /** A list of strings the model sent: an array, or one string (which a model sometimes sends for a list of one). */
445
+ function stringList(value: unknown, name: string): string[] | undefined {
446
+ if (value === undefined || value === null || value === "") return undefined;
447
+ const list = Array.isArray(value) ? value : [value];
448
+ return list.map((item) => {
449
+ if (typeof item !== "string" && typeof item !== "number") throw new Error(`${name} must be a list of strings.`);
450
+ return String(item);
451
+ });
452
+ }
453
+
454
+ /** The arguments of an `aggregate_table` call as the tool reads them. */
455
+ export function aggregateRequest(args: Record<string, unknown>): AggregateRequest {
456
+ const rawFilters = args.filters === undefined || args.filters === null ? [] : Array.isArray(args.filters) ? args.filters : [args.filters];
457
+ const filters = rawFilters.map((filter) => {
458
+ const { column, op, value } = (filter ?? {}) as { column?: unknown; op?: unknown; value?: unknown };
459
+ if (typeof column !== "string" && typeof column !== "number") throw new Error("Each filter needs a column.");
460
+ if (typeof op !== "string" || !(FILTER_OPS as readonly string[]).includes(op)) throw new Error(`A filter's op must be one of ${FILTER_OPS.map((name) => `"${name}"`).join(", ")}.`);
461
+ return { column: String(column), op: op as FilterOp, ...(value !== undefined && value !== null ? { value: typeof value === "number" ? value : String(value) } : {}) };
462
+ });
463
+ const table = typeof args.table === "number" || (typeof args.table === "string" && args.table.trim()) ? args.table as string | number : undefined;
464
+ const groupBy = stringList(args.group_by, "group_by");
465
+ const metrics = stringList(args.metrics, "metrics");
466
+ return {
467
+ ...(table !== undefined ? { table } : {}),
468
+ ...(filters.length > 0 ? { filters } : {}),
469
+ ...(groupBy ? { groupBy } : {}),
470
+ ...(metrics ? { metrics } : {}),
471
+ orderBy: args.order_by === "key" ? "key" : "metric",
472
+ limit: integer(args.limit, 50, 1, MAX_SHOWN_GROUPS),
473
+ ...(args.header_rows !== undefined && args.header_rows !== null && args.header_rows !== "" ? { headerRows: integer(args.header_rows, 1, 0, 5) } : {}),
474
+ };
475
+ }
476
+
210
477
  const searchMode = (mode: unknown): "keywords" | "exact" | "regex" => (mode === "exact" || mode === "regex" ? mode : "keywords");
211
478
 
479
+ /** `group_by` as the search reads it: undefined when not given. A value it does not know is an error. */
480
+ function groupByOf(value: unknown): GroupBy | undefined {
481
+ if (value === undefined || value === null || value === "" || value === "none") return undefined;
482
+ if (typeof value === "string" && (GROUP_BY_VALUES as readonly string[]).includes(value)) return value as GroupBy;
483
+ throw new Error(`group_by must be one of ${GROUP_BY_VALUES.map((name) => `"${name}"`).join(", ")}.`);
484
+ }
485
+
486
+ /** A line number of a search's range, as the search reads it: undefined when not given. */
487
+ const rangeLine = (value: unknown): number | undefined => (value === undefined || value === null || value === "" ? undefined : integer(value, 1, 1, Number.MAX_SAFE_INTEGER));
488
+
489
+ /**
490
+ * The arguments of a search that choose which lines it looks at and how it shows them, as the
491
+ * search reads them. The search, its key and its label all read them here, so that they agree.
492
+ */
493
+ function searchScope(args: Record<string, unknown>): { fromLine?: number; toLine?: number; order: "first" | "last"; groupBy?: GroupBy; wholeWord: boolean; caseSensitive: boolean } {
494
+ const fromLine = rangeLine(args.from_line);
495
+ const toLine = rangeLine(args.to_line);
496
+ let groupBy: GroupBy | undefined;
497
+ try {
498
+ groupBy = groupByOf(args.group_by);
499
+ } catch {
500
+ groupBy = undefined;
501
+ }
502
+ return {
503
+ ...(fromLine !== undefined ? { fromLine } : {}),
504
+ ...(toLine !== undefined ? { toLine } : {}),
505
+ order: args.order === "last" ? "last" : "first",
506
+ ...(groupBy ? { groupBy } : {}),
507
+ wholeWord: flag(args.whole_word),
508
+ caseSensitive: flag(args.case_sensitive),
509
+ };
510
+ }
511
+
212
512
  /** The lines a `read_document` call asks for, as its handler reads them, before the end of the file is known. */
213
513
  function requestedLines(args: Record<string, unknown>): [number, number] {
214
514
  const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
@@ -226,11 +526,30 @@ export function toolCallKey(name: string, args: Record<string, unknown>): string
226
526
  if (name === TOOL_NAMES.search) {
227
527
  if (typeof args.query !== "string" || !args.query.trim()) return undefined;
228
528
  const mode = searchMode(args.mode);
529
+ // A group_by the search refuses: the call answers with an error, and is not compared.
530
+ try {
531
+ groupByOf(args.group_by);
532
+ } catch {
533
+ return undefined;
534
+ }
535
+ const { fromLine, toLine, order, groupBy, wholeWord, caseSensitive } = searchScope(args);
536
+ // The arguments of 0.8.0 are added only when given: a call without them has the key it had.
537
+ const scope = [
538
+ ...(fromLine !== undefined || toLine !== undefined ? [fromLine ?? 1, toLine ?? null] : []),
539
+ ...(mode !== "keywords" && (order === "last" || groupBy || wholeWord) ? [order, groupBy ?? null, mode === "exact" && wholeWord] : []),
540
+ ];
229
541
  return JSON.stringify(mode === "keywords"
230
- ? [name, id, args.query, mode, integer(args.max_results, 5, 1, 10)]
231
- : [name, id, args.query, mode, integer(args.max_results, 20, 1, 50), integer(args.context_lines, 0, 0, 5), args.case_sensitive === true]);
542
+ ? [name, id, args.query, mode, integer(args.max_results, 5, 1, 10), ...scope]
543
+ : [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]);
232
544
  }
233
545
  if (name === TOOL_NAMES.read) return JSON.stringify([name, id, ...requestedLines(args)]);
546
+ if (name === TOOL_NAMES.aggregate) {
547
+ try {
548
+ return JSON.stringify([name, id, aggregateRequest(args)]);
549
+ } catch {
550
+ return undefined;
551
+ }
552
+ }
234
553
  if (name === TOOL_NAMES.overview) return JSON.stringify([name, id]);
235
554
  return undefined;
236
555
  }
@@ -248,6 +567,9 @@ export function alreadyShown(call: { name: string; args: Record<string, unknown>
248
567
  const { result } = earlier;
249
568
  if (earlier.call.name !== call.name || earlier.call.args.document_id !== call.args.document_id) return undefined;
250
569
  if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true) return undefined;
570
+ // A search stored by 0.7.0 with case_sensitive or whole_word as text or 1 ("true", 1): 0.7.0 read
571
+ // those as off, 0.8.0 as on, so the call made now would not return what was stored.
572
+ 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;
251
573
  // A list that `fit` cut to the room it had, a read whose text was cut, or a search that ran out of
252
574
  // time ("the total is a lower bound"; a later question has time of its own): a call made now may get more.
253
575
  if (typeof result.note === "string" && (result.note.startsWith("Showing ") || result.note.startsWith("The scan stopped early"))) return undefined;
@@ -309,9 +631,14 @@ export function failureKind(call: { name: string; args: Record<string, unknown>
309
631
  export function toolResultSummary(label: string, result: ToolResult): string {
310
632
  if (typeof result.error === "string") return ` — failed: ${result.error}`;
311
633
  if (typeof result.total_matching_lines === "number") {
312
- return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}`;
634
+ const groups = typeof result.total_groups === "number" ? ` in ${result.total_groups.toLocaleString("en-US")} ${plural(result.total_groups, "group")}` : "";
635
+ return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}${groups}`;
313
636
  }
314
637
  if (Array.isArray(result.passages)) return ` — ${result.passages.length} ${plural(result.passages.length, "passage")}`;
638
+ if (typeof result.rows_matched === "number") {
639
+ const groups = typeof result.total_groups === "number" ? `, ${result.total_groups.toLocaleString("en-US")} ${plural(result.total_groups, "group")}` : "";
640
+ return ` — ${result.rows_matched.toLocaleString("en-US")} ${plural(result.rows_matched, "row")}${groups}`;
641
+ }
315
642
  if (typeof result.parts_read === "number") {
316
643
  const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
317
644
  return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
@@ -379,6 +706,11 @@ export function createDocumentTools(options: {
379
706
  viewableIds?: string[];
380
707
  /** Loads the uploaded file of a document, for `view_pages`. */
381
708
  loadOriginal?(documentId: string): Promise<Uint8Array | undefined>;
709
+ /**
710
+ * True when a document may hold a table (a CSV, a workbook, a document with `| cell |` rows):
711
+ * `aggregate_table` is then declared. A call of it is answered either way. Defaults to false.
712
+ */
713
+ tables?: boolean;
382
714
  }): ToolSet {
383
715
  const allowed = new Set(options.documentIds);
384
716
  const viewable = new Set(options.loadOriginal ? options.viewableIds ?? [] : []);
@@ -386,10 +718,12 @@ export function createDocumentTools(options: {
386
718
  // The text tools are left out only when there are pages to look at and no document to search.
387
719
  const textTools = allowed.size > 0 || viewable.size === 0;
388
720
  const declarations = [
389
- ...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
721
+ ...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.tables ? [DECLARATIONS.aggregate] : []), ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
390
722
  ...(viewable.size > 0 ? [DECLARATIONS.view] : []),
391
723
  ];
392
724
  const known = new Set(declarations.map((declaration) => declaration.name));
725
+ // Answered for any document, declared or not: a model may know the tool from earlier in the conversation.
726
+ if (textTools) known.add(TOOL_NAMES.aggregate);
393
727
  // Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
394
728
  if (textTools && options.generate) known.add(TOOL_NAMES.analyze);
395
729
  const cap = options.budget.toolResultCharacters;
@@ -410,6 +744,12 @@ export function createDocumentTools(options: {
410
744
  regexQueue = next.catch(() => undefined);
411
745
  return next;
412
746
  };
747
+ const givenReads: unknown = options.maxWholeDocumentReads;
748
+ // NaN failed every comparison, so it let a document be read whole any number of times.
749
+ if (givenReads !== undefined && (typeof givenReads !== "number" || Number.isNaN(givenReads))) {
750
+ const shown = typeof givenReads === "number" ? String(givenReads) : typeof givenReads === "string" ? JSON.stringify(givenReads) : typeof givenReads;
751
+ throw new (typeof givenReads === "number" ? RangeError : TypeError)(`maxWholeDocumentReads must be a number, and is ${shown}.`);
752
+ }
413
753
  const maxWholeReads = Math.max(0, Math.trunc(options.maxWholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS));
414
754
  /** Whole-document reads started, by document. */
415
755
  const wholeReads = new Map<string, number>();
@@ -443,13 +783,24 @@ export function createDocumentTools(options: {
443
783
  // Page numbers are added only for a PDF whose pages can be looked at: they are what
444
784
  // view_pages takes. Everything else gets the results of 0.2.0 unchanged.
445
785
  const paged = viewable.has(document.meta.id);
786
+ const groupBy = groupByOf(args.group_by);
787
+ const { fromLine, toLine, order, wholeWord, caseSensitive } = searchScope(args);
788
+ const total = document.lineCount;
789
+ if (fromLine !== undefined && fromLine > total) throw new Error(`from_line ${fromLine} is past the end of the file, which has ${total} ${plural(total, "line")}.`);
790
+ if (toLine !== undefined && toLine < (fromLine ?? 1)) throw new Error(`to_line ${toLine} is before from_line ${fromLine ?? 1}.`);
791
+ const ranged = fromLine !== undefined || toLine !== undefined;
792
+ const range = { from: fromLine ?? 1, to: Math.min(total, toLine ?? total) };
793
+ // Said in the result when part of the file was searched: the counts are of those lines.
794
+ const searched = ranged ? { searched_lines: `${range.from}-${range.to}` } : {};
446
795
  if (mode === "keywords") {
796
+ if (groupBy) throw new Error("group_by counts the lines of an exact or regex search: use mode \"exact\" or \"regex\".");
447
797
  const topK = integer(args.max_results, 5, 1, 10);
448
- const ranked = await rankSource(document, query, topK, options.signal);
798
+ const ranked = await rankSource(document, query, topK, options.signal, ranged ? range : undefined);
449
799
  const texts = await Promise.all(ranked.map((passage) => document.readLines(passage.from, passage.to)));
450
800
  return fit({
451
801
  document: document.meta.name,
452
802
  mode,
803
+ ...searched,
453
804
  passages: ranked.map((passage, index) => {
454
805
  const pages = paged ? document.pagesOfLines(passage.from, passage.to) : undefined;
455
806
  return {
@@ -463,6 +814,7 @@ export function createDocumentTools(options: {
463
814
  }, "passages", limit);
464
815
  }
465
816
  const regex = mode === "regex";
817
+ const shownGroups = integer(args.max_results, DEFAULT_GROUPS, 1, MAX_GROUPS);
466
818
  const grep = async () => {
467
819
  const regexLeft = regexBudget - regexClock.usedMs;
468
820
  if (regex && regexLeft <= 0) {
@@ -470,22 +822,42 @@ export function createDocumentTools(options: {
470
822
  }
471
823
  return grepSource(document, query, {
472
824
  regex,
473
- caseSensitive: args.case_sensitive === true,
474
- maxResults: integer(args.max_results, 20, 1, 50),
825
+ caseSensitive,
826
+ maxResults: integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS),
475
827
  contextLines: integer(args.context_lines, 0, 0, 5),
476
828
  ...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
477
829
  ...(options.signal ? { signal: options.signal } : {}),
830
+ ...(ranged ? { fromLine: range.from, toLine: range.to } : {}),
831
+ ...(order === "last" ? { order } : {}),
832
+ ...(groupBy ? { groupBy } : {}),
833
+ ...(wholeWord && !regex ? { wholeWord } : {}),
478
834
  });
479
835
  };
480
836
  const result = await (regex ? inRegexTurn(grep) : grep());
837
+ const shownMatches = [...(result.first ? [result.first] : []), ...result.matches, ...(result.last ? [result.last] : [])];
838
+ const where = await locationsOf(document, shownMatches);
481
839
  const placed = (match: LineMatch): LineMatch => {
482
- if (!paged) return match;
840
+ const page = paged ? document.pageOfLine(match.line) : undefined;
841
+ const section = where.section(match.line);
842
+ if (!page && !section) return match;
483
843
  const { line, ...rest } = match;
484
- const page = document.pageOfLine(line);
485
- return { line, ...(page ? { page } : {}), ...rest };
844
+ return { line, ...(page ? { page } : {}), ...(section ? { section } : {}), ...rest };
486
845
  };
487
- const base = { document: document.meta.name, mode, total_matching_lines: result.totalMatchingLines };
846
+ const base = {
847
+ document: document.meta.name,
848
+ mode,
849
+ ...searched,
850
+ total_matching_lines: result.totalMatchingLines,
851
+ ...(where.headers.length > 0 ? { table_headers: where.headers } : {}),
852
+ };
853
+ const stopped = result.stoppedEarly ? { note: "The scan stopped early; the counts are lower bounds." } : {};
854
+ if (result.groups) return groupedResult({ ...base, group_by: groupBy!, ...stopped }, result.groups, shownGroups, limit);
488
855
  const matches = result.matches.map(placed);
856
+ if (order === "last") {
857
+ // The range a search for the lines after those found goes on in, when the scan stopped early.
858
+ const rest = result.stoppedEarly ? { end: range.to, ...(toLine !== undefined ? { toLine: range.to } : {}) } : undefined;
859
+ return lastMatches({ ...base, order }, result.first ? placed(result.first) : undefined, matches, result.totalMatchingLines, limit, rest);
860
+ }
489
861
  if (!result.stoppedEarly && result.totalMatchingLines >= 2) {
490
862
  // The last match is `last`, or, when every match is among the first ones, the last of them.
491
863
  return result.last
@@ -556,6 +928,41 @@ export function createDocumentTools(options: {
556
928
  }, "outline", limit);
557
929
  },
558
930
 
931
+ async [TOOL_NAMES.aggregate](args, limits) {
932
+ const limit = limitOf(limits);
933
+ const document = await documentFor(args);
934
+ const request = aggregateRequest(args);
935
+ const result = await aggregateTable(document, request, options.signal);
936
+ const groups = result.groups.map((group) => ({
937
+ ...(Object.keys(group.key).length > 0 ? { group: group.key } : {}),
938
+ ...group.values,
939
+ ...(group.values.count === undefined ? { rows: group.count } : {}),
940
+ lines: group.lines,
941
+ }));
942
+ const shownColumns = result.columns.slice(0, 60);
943
+ const base = {
944
+ document: document.meta.name,
945
+ table: result.table,
946
+ ...(result.tables > 1 ? { tables_in_file: result.tables } : {}),
947
+ header_line: result.headerLine,
948
+ ...(result.headerRows !== 1 ? { header_rows: result.headerRows } : {}),
949
+ ...(result.title !== undefined ? { title: result.title } : {}),
950
+ columns: result.columns.length > shownColumns.length ? [...shownColumns, `… ${result.columns.length - shownColumns.length} more`] : shownColumns,
951
+ rows_read: result.rowsRead,
952
+ rows_matched: result.rowsMatched,
953
+ ...(result.totalGroups > 1 || (request.groupBy?.length ?? 0) > 0 ? { total_groups: result.totalGroups } : {}),
954
+ ...(result.otherRows > 0 ? { other_rows: result.otherRows, other_note: `Rows of groups past the first ${MAX_GROUP_KEYS.toLocaleString("en-US")} found.` } : {}),
955
+ ...(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." } : {}),
956
+ ...(result.repeatedHeaders > 0 ? { repeated_header_rows: result.repeatedHeaders } : {}),
957
+ ...(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." } : {}),
958
+ ...(result.irregularRows > 0 ? { irregular_rows: result.irregularRows, irregular_note: "Rows with values past the header's columns: check columns and header_rows." } : {}),
959
+ };
960
+ const note = groups.length < result.totalGroups
961
+ ? { 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.` }
962
+ : {};
963
+ return fit({ ...base, ...note, groups }, "groups", limit);
964
+ },
965
+
559
966
  async [TOOL_NAMES.analyze](args, limits, hooks) {
560
967
  if (!options.generate) throw new Error("Whole-document analysis is not enabled.");
561
968
  const document = await documentFor(args);
@@ -707,7 +1114,10 @@ export function createDocumentTools(options: {
707
1114
  }
708
1115
  if (name === TOOL_NAMES.search) {
709
1116
  const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
710
- 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}`;
711
1121
  }
712
1122
  if (name === TOOL_NAMES.read) {
713
1123
  const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
@@ -715,6 +1125,20 @@ export function createDocumentTools(options: {
715
1125
  return `Read ${file} lines ${start}${end}`;
716
1126
  }
717
1127
  if (name === TOOL_NAMES.overview) return `Overview of ${file}`;
1128
+ if (name === TOOL_NAMES.aggregate) {
1129
+ const request = (() => {
1130
+ try {
1131
+ return aggregateRequest(args);
1132
+ } catch {
1133
+ return {} as AggregateRequest;
1134
+ }
1135
+ })();
1136
+ const metrics = (request.metrics?.length ? request.metrics : ["count"]).join(", ");
1137
+ const by = request.groupBy?.length ? ` by ${request.groupBy.join(", ")}` : "";
1138
+ const where = request.filters?.length ? ` where ${request.filters.map((filter) => `${filter.column} ${filter.op}${filter.value !== undefined && filter.value !== "" ? ` ${filter.value}` : ""}`).join(" and ")}` : "";
1139
+ const table = request.table !== undefined && request.table !== "" ? ` (${typeof request.table === "number" ? `table ${request.table}` : request.table})` : "";
1140
+ return sliceWhole(`Aggregate ${file}${table}: ${metrics}${by}${where}`, 200);
1141
+ }
718
1142
  if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”`;
719
1143
  return name;
720
1144
  },