llm-large-files 0.8.0 → 0.8.2

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 (63) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +2 -0
  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/evidence.d.ts.map +1 -1
  8. package/dist/evidence.js +17 -0
  9. package/dist/evidence.js.map +1 -1
  10. package/dist/extract.d.ts +8 -1
  11. package/dist/extract.d.ts.map +1 -1
  12. package/dist/extract.js +40 -2
  13. package/dist/extract.js.map +1 -1
  14. package/dist/library.d.ts +7 -0
  15. package/dist/library.d.ts.map +1 -1
  16. package/dist/library.js +112 -18
  17. package/dist/library.js.map +1 -1
  18. package/dist/limiter.d.ts +2 -2
  19. package/dist/limiter.js +2 -2
  20. package/dist/node/handlers.d.ts +15 -0
  21. package/dist/node/handlers.d.ts.map +1 -1
  22. package/dist/node/handlers.js +155 -36
  23. package/dist/node/handlers.js.map +1 -1
  24. package/dist/plan.d.ts +3 -1
  25. package/dist/plan.d.ts.map +1 -1
  26. package/dist/plan.js +17 -1
  27. package/dist/plan.js.map +1 -1
  28. package/dist/quality.d.ts +16 -0
  29. package/dist/quality.d.ts.map +1 -0
  30. package/dist/quality.js +157 -0
  31. package/dist/quality.js.map +1 -0
  32. package/dist/ranged.d.ts +7 -0
  33. package/dist/ranged.d.ts.map +1 -1
  34. package/dist/ranged.js +8 -1
  35. package/dist/ranged.js.map +1 -1
  36. package/dist/tools.d.ts +9 -0
  37. package/dist/tools.d.ts.map +1 -1
  38. package/dist/tools.js +258 -5
  39. package/dist/tools.js.map +1 -1
  40. package/dist/types.d.ts +20 -0
  41. package/dist/types.d.ts.map +1 -1
  42. package/docs/guides/deployment.md +27 -6
  43. package/docs/guides/storage.md +5 -2
  44. package/docs/guides/web-app.md +14 -3
  45. package/docs/how-it-works.md +7 -0
  46. package/docs/measurements.md +20 -0
  47. package/docs/reference/library.md +22 -8
  48. package/docs/reference/node.md +30 -15
  49. package/docs/reference/tools.md +99 -1
  50. package/docs/security.md +15 -6
  51. package/docs/troubleshooting.md +28 -0
  52. package/package.json +1 -1
  53. package/src/aggregate.ts +674 -0
  54. package/src/evidence.ts +17 -0
  55. package/src/extract.ts +37 -2
  56. package/src/library.ts +116 -16
  57. package/src/limiter.ts +2 -2
  58. package/src/node/handlers.ts +159 -32
  59. package/src/plan.ts +17 -1
  60. package/src/quality.ts +146 -0
  61. package/src/ranged.ts +8 -1
  62. package/src/tools.ts +249 -5
  63. package/src/types.ts +17 -0
package/src/quality.ts ADDED
@@ -0,0 +1,146 @@
1
+ import type { TimeSlicer } from "./pause.js";
2
+ import type { DocumentFormat, DocumentMeta } from "./types.js";
3
+
4
+ /**
5
+ * Signs of the quality of a document's text, worked out at ingest and shown on its card, so the
6
+ * model knows where the text cannot be trusted before it relies on it:
7
+ * - the pages of a PDF that have no text (a scan, a photo), and those whose text layer looks
8
+ * garbled (fonts without a Unicode map give "ÞÞÞ" or "�����");
9
+ * - the scripts the text is written in, when it is not Latin alone: a Hebrew file is searched in
10
+ * Hebrew.
11
+ */
12
+ export type TextQuality = Pick<DocumentMeta, "pagesWithoutText" | "garbledPages" | "scripts">;
13
+
14
+ /** Page numbers kept in a list, at most. */
15
+ const MAX_LISTED_PAGES = 200;
16
+ /** Characters of the text the script shares are counted over. */
17
+ const SCRIPT_SAMPLE = 2 * 1024 * 1024;
18
+ /** Letters needed before shares are given. */
19
+ const MIN_LETTERS = 200;
20
+ /** A script is named when it has at least this share of the letters, in percent. */
21
+ const MIN_SHARE = 5;
22
+ /** A page is judged garbled only with at least this many characters that are not white space. */
23
+ const MIN_PAGE_CHARACTERS = 40;
24
+
25
+ const PAGE_LINE = /^--- Page (\d+) ---$/;
26
+ const NO_TEXT_LINE = "[No text on this page. It may be a scan, a photo, or a chart.]";
27
+ const PICTURE_LINE = "[Picture on this page. This text cannot show it.]";
28
+
29
+ /**
30
+ * The script of the letter at `at`, or undefined when it is not a letter. The common scripts are
31
+ * known by their code points, with no regular expression; only rarer blocks are tested.
32
+ */
33
+ function letterScript(text: string, at: number): string | undefined {
34
+ const code = text.charCodeAt(at);
35
+ if (code < 0x80) return (code >= 65 && code <= 90) || (code >= 97 && code <= 122) ? "Latin" : undefined;
36
+ if (code >= 0x5d0 && code <= 0x5f2) return code <= 0x5ea || code >= 0x5f0 ? "Hebrew" : undefined;
37
+ if (code >= 0x591 && code <= 0x5cf) return undefined; // Hebrew points and marks
38
+ if (code >= 0xc0 && code <= 0x24f) return code === 0xd7 || code === 0xf7 ? undefined : "Latin";
39
+ if ((code >= 0x620 && code <= 0x64a) || (code >= 0x671 && code <= 0x6d3)) return "Arabic";
40
+ if (code >= 0x410 && code <= 0x44f) return "Cyrillic";
41
+ if (code >= 0x4e00 && code <= 0x9fff) return "CJK";
42
+ if (code >= 0xdc00 && code <= 0xdfff) return undefined;
43
+ const character = code >= 0xd800 && code <= 0xdbff ? text.slice(at, at + 2) : text[at]!;
44
+ return LETTER.test(character) ? scriptOf(character.codePointAt(0)!) : undefined;
45
+ }
46
+
47
+ /** The script of a letter, by its code point. */
48
+ function scriptOf(code: number): string {
49
+ if (code < 0x250) return "Latin";
50
+ if (code >= 0x370 && code < 0x400) return "Greek";
51
+ if (code >= 0x400 && code < 0x530) return "Cyrillic";
52
+ if (code >= 0x590 && code < 0x600) return "Hebrew";
53
+ if ((code >= 0x600 && code < 0x780) || (code >= 0xfb50 && code < 0xfe00) || (code >= 0xfe70 && code < 0xff00)) return "Arabic";
54
+ if (code >= 0xfb1d && code < 0xfb50) return "Hebrew";
55
+ if (code >= 0x900 && code < 0x980) return "Devanagari";
56
+ if (code >= 0xe00 && code < 0xe80) return "Thai";
57
+ if ((code >= 0x3040 && code < 0x3100) || (code >= 0x3400 && code < 0xa000) || (code >= 0xac00 && code < 0xd7b0) || (code >= 0x1100 && code < 0x1200)) return "CJK";
58
+ if (code >= 0x1e00 && code < 0x1f00) return "Latin";
59
+ return "other";
60
+ }
61
+
62
+ const LETTER = /\p{L}/u;
63
+
64
+ /** The text quality of a document, from its lines (see `TextQuality`). */
65
+ export async function measureQuality(lines: string[], format: DocumentFormat, slicer: TimeSlicer): Promise<TextQuality> {
66
+ const empty: number[] = [];
67
+ const garbled: number[] = [];
68
+ let emptyCount = 0;
69
+ let garbledCount = 0;
70
+ // The page being read: its number, its characters that are not white space, its letters and
71
+ // digits, its replacement characters, and whether it said it has no text.
72
+ let page = 0;
73
+ let characters = 0;
74
+ let wordy = 0;
75
+ let replaced = 0;
76
+ let noText = false;
77
+ const endPage = () => {
78
+ if (page === 0) return;
79
+ if (noText && characters === 0) {
80
+ emptyCount++;
81
+ if (empty.length < MAX_LISTED_PAGES) empty.push(page);
82
+ } else if (characters >= MIN_PAGE_CHARACTERS && (wordy / characters < 0.3 || replaced > Math.max(6, characters * 0.03))) {
83
+ garbledCount++;
84
+ if (garbled.length < MAX_LISTED_PAGES) garbled.push(page);
85
+ }
86
+ };
87
+ const letters = new Map<string, number>();
88
+ let sampled = 0;
89
+ let total = 0;
90
+ /** Adds a line of a PDF page to its counts, a character code at a time. */
91
+ const countPage = (line: string) => {
92
+ for (let at = 0; at < line.length; at++) {
93
+ const code = line.charCodeAt(at);
94
+ if (code === 32 || code === 9 || code === 0xa0 || code === 0x202f) continue;
95
+ // The second half of a character outside the basic plane is counted with its first.
96
+ if (code >= 0xdc00 && code <= 0xdfff) continue;
97
+ characters++;
98
+ if (code === 0xfffd) replaced++;
99
+ else if ((code >= 48 && code <= 57) || letterScript(line, at) !== undefined) wordy++;
100
+ }
101
+ };
102
+ for (let index = 0; index < lines.length; index++) {
103
+ if ((index & 4095) === 4095) await slicer.maybePause();
104
+ const line = lines[index]!;
105
+ if (format === "pdf") {
106
+ const header = PAGE_LINE.exec(line);
107
+ if (header && Number(header[1]) === page + 1) {
108
+ endPage();
109
+ page++;
110
+ characters = wordy = replaced = 0;
111
+ noText = false;
112
+ continue;
113
+ }
114
+ if (line === NO_TEXT_LINE) {
115
+ noText = true;
116
+ continue;
117
+ }
118
+ if (line !== PICTURE_LINE) countPage(line);
119
+ }
120
+ if (sampled < SCRIPT_SAMPLE) {
121
+ sampled += line.length + 1;
122
+ for (let at = 0; at < line.length; at++) {
123
+ const script = letterScript(line, at);
124
+ if (script === undefined) continue;
125
+ letters.set(script, (letters.get(script) ?? 0) + 1);
126
+ total++;
127
+ }
128
+ }
129
+ }
130
+ endPage();
131
+ const shares = total >= MIN_LETTERS
132
+ ? [...letters].map(([script, count]) => ({ script, percent: Math.round((count / total) * 100) })).filter((share) => share.percent >= MIN_SHARE && share.script !== "other").sort((left, right) => right.percent - left.percent)
133
+ : [];
134
+ const notLatinOnly = shares.some((share) => share.script !== "Latin");
135
+ return {
136
+ ...(emptyCount > 0 ? { pagesWithoutText: empty } : {}),
137
+ ...(garbledCount > 0 ? { garbledPages: garbled } : {}),
138
+ ...(notLatinOnly ? { scripts: shares } : {}),
139
+ };
140
+ }
141
+
142
+ /** Page numbers as a short list: "3, 7, 12" or "3, 7, 12 and 40 more". */
143
+ export function pageList(pages: number[], shown = 12): string {
144
+ const listed = pages.slice(0, shown).join(", ");
145
+ return pages.length > shown ? `${listed} and ${pages.length - shown} more` : listed;
146
+ }
package/src/ranged.ts CHANGED
@@ -48,7 +48,14 @@ const YIELD_AFTER_MS = 15;
48
48
  // starts at a line, so a line that began with one lost it, and its piece no longer matched the index.
49
49
  const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
50
50
 
51
- const gone = (id: string) => new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
51
+ /**
52
+ * The text of a document is gone from the store while its metadata is still there (removed by hand,
53
+ * or by a cleanup outside the library). Told apart from other read errors, so that a question can
54
+ * report the document as missing.
55
+ */
56
+ export class DocumentGoneError extends Error {}
57
+
58
+ const gone = (id: string) => new DocumentGoneError(`${id} is no longer available on the server. Ask the user to attach the file again.`);
52
59
 
53
60
  /** A scan of a document: fed the pieces in order until it says it is done. */
54
61
  type Consumer = { feed: ScanFeed; done: boolean; settle: (error?: unknown) => void };
package/src/tools.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { safeErrorMessage } from "./errors.js";
2
+ import { aggregateTable, FILTER_OPS, MAX_SHOWN_GROUPS, type AggregateRequest, type FilterOp } from "./aggregate.js";
2
3
  import { GROUP_BY_VALUES, MAX_GROUP_KEYS, type GroupBy, type GroupResult } from "./groups.js";
3
4
  import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
4
5
  import { cutPdfPages } from "./pdf-pages.js";
@@ -42,6 +43,7 @@ export const TOOL_NAMES = {
42
43
  overview: "get_document_overview",
43
44
  analyze: "analyze_whole_document",
44
45
  view: "view_pages",
46
+ aggregate: "aggregate_table",
45
47
  } as const;
46
48
 
47
49
  const documentId = { type: "string" as const, description: "The document_id from the file's card." };
@@ -98,6 +100,36 @@ const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
98
100
  required: ["document_id", "task"],
99
101
  },
100
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
+ },
101
133
  view: {
102
134
  name: TOOL_NAMES.view,
103
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.`,
@@ -306,6 +338,142 @@ function groupedResult(base: ToolResult, counted: GroupResult, shown: number, li
306
338
  return fit(build(kept, true), null, limit);
307
339
  }
308
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
+
309
477
  const searchMode = (mode: unknown): "keywords" | "exact" | "regex" => (mode === "exact" || mode === "regex" ? mode : "keywords");
310
478
 
311
479
  /** `group_by` as the search reads it: undefined when not given. A value it does not know is an error. */
@@ -375,6 +543,13 @@ export function toolCallKey(name: string, args: Record<string, unknown>): string
375
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]);
376
544
  }
377
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
+ }
378
553
  if (name === TOOL_NAMES.overview) return JSON.stringify([name, id]);
379
554
  return undefined;
380
555
  }
@@ -460,6 +635,10 @@ export function toolResultSummary(label: string, result: ToolResult): string {
460
635
  return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}${groups}`;
461
636
  }
462
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
+ }
463
642
  if (typeof result.parts_read === "number") {
464
643
  const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
465
644
  return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
@@ -527,6 +706,11 @@ export function createDocumentTools(options: {
527
706
  viewableIds?: string[];
528
707
  /** Loads the uploaded file of a document, for `view_pages`. */
529
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;
530
714
  }): ToolSet {
531
715
  const allowed = new Set(options.documentIds);
532
716
  const viewable = new Set(options.loadOriginal ? options.viewableIds ?? [] : []);
@@ -534,10 +718,12 @@ export function createDocumentTools(options: {
534
718
  // The text tools are left out only when there are pages to look at and no document to search.
535
719
  const textTools = allowed.size > 0 || viewable.size === 0;
536
720
  const declarations = [
537
- ...(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] : [])] : []),
538
722
  ...(viewable.size > 0 ? [DECLARATIONS.view] : []),
539
723
  ];
540
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);
541
727
  // Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
542
728
  if (textTools && options.generate) known.add(TOOL_NAMES.analyze);
543
729
  const cap = options.budget.toolResultCharacters;
@@ -648,13 +834,22 @@ export function createDocumentTools(options: {
648
834
  });
649
835
  };
650
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);
651
839
  const placed = (match: LineMatch): LineMatch => {
652
- 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;
653
843
  const { line, ...rest } = match;
654
- const page = document.pageOfLine(line);
655
- return { line, ...(page ? { page } : {}), ...rest };
844
+ return { line, ...(page ? { page } : {}), ...(section ? { section } : {}), ...rest };
845
+ };
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 } : {}),
656
852
  };
657
- const base = { document: document.meta.name, mode, ...searched, total_matching_lines: result.totalMatchingLines };
658
853
  const stopped = result.stoppedEarly ? { note: "The scan stopped early; the counts are lower bounds." } : {};
659
854
  if (result.groups) return groupedResult({ ...base, group_by: groupBy!, ...stopped }, result.groups, shownGroups, limit);
660
855
  const matches = result.matches.map(placed);
@@ -733,6 +928,41 @@ export function createDocumentTools(options: {
733
928
  }, "outline", limit);
734
929
  },
735
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
+
736
966
  async [TOOL_NAMES.analyze](args, limits, hooks) {
737
967
  if (!options.generate) throw new Error("Whole-document analysis is not enabled.");
738
968
  const document = await documentFor(args);
@@ -895,6 +1125,20 @@ export function createDocumentTools(options: {
895
1125
  return `Read ${file} lines ${start}${end}`;
896
1126
  }
897
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
+ }
898
1142
  if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”`;
899
1143
  return name;
900
1144
  },
package/src/types.ts CHANGED
@@ -69,6 +69,23 @@ export type DocumentMeta = {
69
69
  originalKept?: boolean;
70
70
  outline: OutlineEntry[];
71
71
  logProfile?: LogProfile;
72
+ /**
73
+ * The pages of a PDF that have no text at all: scans, photos, charts. Up to 200 are listed.
74
+ * Absent when there are none, and on documents from before 0.8.1.
75
+ */
76
+ pagesWithoutText?: number[];
77
+ /**
78
+ * The pages of a PDF whose text looks garbled: few letters and digits among their characters, or
79
+ * many replacement characters (a font without a Unicode map). Up to 200 are listed. Absent when
80
+ * there are none, and on documents from before 0.8.1.
81
+ */
82
+ garbledPages?: number[];
83
+ /**
84
+ * The scripts the text is written in, by their share of its letters in percent ("Hebrew" 81,
85
+ * "Latin" 19), from its first 2 MB, those of 5% or more. Absent for a text in Latin letters alone,
86
+ * one with few letters, and documents from before 0.8.1.
87
+ */
88
+ scripts?: Array<{ script: string; percent: number }>;
72
89
  createdAt: string;
73
90
  expiresAt: string;
74
91
  };