llm-large-files 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/CHANGELOG.md +446 -0
  2. package/README.md +13 -7
  3. package/dist/access.d.ts +45 -3
  4. package/dist/access.d.ts.map +1 -1
  5. package/dist/access.js +106 -3
  6. package/dist/access.js.map +1 -1
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +115 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +572 -103
  26. package/dist/ask.js.map +1 -1
  27. package/dist/citations.d.ts +36 -0
  28. package/dist/citations.d.ts.map +1 -0
  29. package/dist/citations.js +291 -0
  30. package/dist/citations.js.map +1 -0
  31. package/dist/error-info.d.ts +13 -0
  32. package/dist/error-info.d.ts.map +1 -1
  33. package/dist/error-info.js +37 -1
  34. package/dist/error-info.js.map +1 -1
  35. package/dist/errors.d.ts +3 -1
  36. package/dist/errors.d.ts.map +1 -1
  37. package/dist/errors.js +3 -1
  38. package/dist/errors.js.map +1 -1
  39. package/dist/events.d.ts +25 -7
  40. package/dist/events.d.ts.map +1 -1
  41. package/dist/events.js.map +1 -1
  42. package/dist/evidence.d.ts.map +1 -1
  43. package/dist/evidence.js +21 -2
  44. package/dist/evidence.js.map +1 -1
  45. package/dist/extract.d.ts.map +1 -1
  46. package/dist/extract.js +6 -1
  47. package/dist/extract.js.map +1 -1
  48. package/dist/gemini/adapter.d.ts +35 -4
  49. package/dist/gemini/adapter.d.ts.map +1 -1
  50. package/dist/gemini/adapter.js +68 -29
  51. package/dist/gemini/adapter.js.map +1 -1
  52. package/dist/gemini/chat.d.ts +28 -55
  53. package/dist/gemini/chat.d.ts.map +1 -1
  54. package/dist/gemini/chat.js +20 -27
  55. package/dist/gemini/chat.js.map +1 -1
  56. package/dist/gemini/endpoints.d.ts +59 -11
  57. package/dist/gemini/endpoints.d.ts.map +1 -1
  58. package/dist/gemini/endpoints.js +33 -7
  59. package/dist/gemini/endpoints.js.map +1 -1
  60. package/dist/gemini/errors.d.ts +39 -5
  61. package/dist/gemini/errors.d.ts.map +1 -1
  62. package/dist/gemini/errors.js +70 -9
  63. package/dist/gemini/errors.js.map +1 -1
  64. package/dist/gemini/generate.d.ts +53 -2
  65. package/dist/gemini/generate.d.ts.map +1 -1
  66. package/dist/gemini/generate.js +100 -50
  67. package/dist/gemini/generate.js.map +1 -1
  68. package/dist/gemini/index.d.ts +3 -3
  69. package/dist/gemini/index.d.ts.map +1 -1
  70. package/dist/http.d.ts +41 -3
  71. package/dist/http.d.ts.map +1 -1
  72. package/dist/http.js +40 -2
  73. package/dist/http.js.map +1 -1
  74. package/dist/index.d.ts +6 -4
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +4 -2
  77. package/dist/index.js.map +1 -1
  78. package/dist/ingest.d.ts +9 -1
  79. package/dist/ingest.d.ts.map +1 -1
  80. package/dist/ingest.js +50 -25
  81. package/dist/ingest.js.map +1 -1
  82. package/dist/library.d.ts +129 -2
  83. package/dist/library.d.ts.map +1 -1
  84. package/dist/library.js +224 -149
  85. package/dist/library.js.map +1 -1
  86. package/dist/map-reduce.d.ts +176 -10
  87. package/dist/map-reduce.d.ts.map +1 -1
  88. package/dist/map-reduce.js +804 -58
  89. package/dist/map-reduce.js.map +1 -1
  90. package/dist/model.d.ts +36 -4
  91. package/dist/model.d.ts.map +1 -1
  92. package/dist/model.js +17 -1
  93. package/dist/model.js.map +1 -1
  94. package/dist/node/handlers.d.ts +29 -8
  95. package/dist/node/handlers.d.ts.map +1 -1
  96. package/dist/node/handlers.js +148 -126
  97. package/dist/node/handlers.js.map +1 -1
  98. package/dist/node/index.d.ts +1 -1
  99. package/dist/node/index.d.ts.map +1 -1
  100. package/dist/node/index.js.map +1 -1
  101. package/dist/node/ingest-child.js +2 -2
  102. package/dist/node/ingest-child.js.map +1 -1
  103. package/dist/node/spool.d.ts +9 -5
  104. package/dist/node/spool.d.ts.map +1 -1
  105. package/dist/node/spool.js +28 -15
  106. package/dist/node/spool.js.map +1 -1
  107. package/dist/node/sse.d.ts +6 -5
  108. package/dist/node/sse.d.ts.map +1 -1
  109. package/dist/node/sse.js +8 -7
  110. package/dist/node/sse.js.map +1 -1
  111. package/dist/openai/adapter.d.ts +5 -1
  112. package/dist/openai/adapter.d.ts.map +1 -1
  113. package/dist/openai/adapter.js +53 -12
  114. package/dist/openai/adapter.js.map +1 -1
  115. package/dist/output-limit.d.ts +2 -1
  116. package/dist/output-limit.d.ts.map +1 -1
  117. package/dist/output-limit.js +5 -2
  118. package/dist/output-limit.js.map +1 -1
  119. package/dist/pdf-outline.d.ts +71 -0
  120. package/dist/pdf-outline.d.ts.map +1 -0
  121. package/dist/pdf-outline.js +414 -0
  122. package/dist/pdf-outline.js.map +1 -0
  123. package/dist/plan.d.ts +137 -7
  124. package/dist/plan.d.ts.map +1 -1
  125. package/dist/plan.js +248 -26
  126. package/dist/plan.js.map +1 -1
  127. package/dist/prepare.d.ts +50 -0
  128. package/dist/prepare.d.ts.map +1 -0
  129. package/dist/prepare.js +207 -0
  130. package/dist/prepare.js.map +1 -0
  131. package/dist/ranged.d.ts +2 -1
  132. package/dist/ranged.d.ts.map +1 -1
  133. package/dist/ranged.js +16 -3
  134. package/dist/ranged.js.map +1 -1
  135. package/dist/search.d.ts +7 -0
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +72 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/stores.d.ts +6 -0
  140. package/dist/stores.d.ts.map +1 -1
  141. package/dist/stores.js +82 -11
  142. package/dist/stores.js.map +1 -1
  143. package/dist/tools.d.ts +22 -2
  144. package/dist/tools.d.ts.map +1 -1
  145. package/dist/tools.js +323 -76
  146. package/dist/tools.js.map +1 -1
  147. package/dist/types.d.ts +49 -1
  148. package/dist/types.d.ts.map +1 -1
  149. package/dist/whole-cost.d.ts +37 -0
  150. package/dist/whole-cost.d.ts.map +1 -0
  151. package/dist/whole-cost.js +46 -0
  152. package/dist/whole-cost.js.map +1 -0
  153. package/docs/README.md +4 -0
  154. package/docs/guides/anthropic.md +5 -2
  155. package/docs/guides/conversations.md +1 -1
  156. package/docs/guides/costs-and-limits.md +132 -36
  157. package/docs/guides/deployment.md +106 -13
  158. package/docs/guides/errors-and-reliability.md +157 -45
  159. package/docs/guides/explorer-model.md +4 -1
  160. package/docs/guides/openai-compatible.md +47 -7
  161. package/docs/guides/own-adapter-and-loop.md +33 -6
  162. package/docs/guides/pdfs.md +96 -7
  163. package/docs/guides/storage.md +46 -3
  164. package/docs/guides/testing.md +71 -0
  165. package/docs/guides/vertex-and-gemini.md +159 -50
  166. package/docs/guides/web-app.md +10 -6
  167. package/docs/how-it-works.md +120 -22
  168. package/docs/measurements.md +172 -5
  169. package/docs/publishing.md +76 -4
  170. package/docs/reference/anthropic.md +12 -7
  171. package/docs/reference/ask.md +262 -35
  172. package/docs/reference/errors-and-retries.md +30 -2
  173. package/docs/reference/events.md +27 -10
  174. package/docs/reference/gemini.md +184 -68
  175. package/docs/reference/library.md +190 -23
  176. package/docs/reference/node.md +51 -17
  177. package/docs/reference/openai.md +21 -10
  178. package/docs/reference/tools.md +271 -26
  179. package/docs/security.md +101 -12
  180. package/docs/troubleshooting.md +14 -12
  181. package/docs/upgrading-0.10.md +472 -0
  182. package/package.json +5 -1
  183. package/src/access.ts +127 -4
  184. package/src/aggregate.ts +92 -14
  185. package/src/analyze.ts +2 -2
  186. package/src/answer-info.ts +45 -0
  187. package/src/anthropic/adapter.ts +40 -11
  188. package/src/ask.ts +646 -106
  189. package/src/citations.ts +294 -0
  190. package/src/error-info.ts +36 -1
  191. package/src/errors.ts +3 -1
  192. package/src/events.ts +29 -6
  193. package/src/evidence.ts +21 -2
  194. package/src/extract.ts +6 -1
  195. package/src/gemini/adapter.ts +99 -32
  196. package/src/gemini/chat.ts +53 -82
  197. package/src/gemini/endpoints.ts +89 -16
  198. package/src/gemini/errors.ts +74 -11
  199. package/src/gemini/generate.ts +147 -57
  200. package/src/gemini/index.ts +3 -3
  201. package/src/http.ts +65 -4
  202. package/src/index.ts +6 -4
  203. package/src/ingest.ts +58 -27
  204. package/src/library.ts +336 -142
  205. package/src/map-reduce.ts +855 -67
  206. package/src/model.ts +44 -4
  207. package/src/node/handlers.ts +159 -118
  208. package/src/node/index.ts +1 -0
  209. package/src/node/ingest-child.ts +2 -2
  210. package/src/node/spool.ts +28 -14
  211. package/src/node/sse.ts +8 -7
  212. package/src/openai/adapter.ts +56 -13
  213. package/src/output-limit.ts +5 -2
  214. package/src/pdf-outline.ts +400 -0
  215. package/src/plan.ts +287 -36
  216. package/src/prepare.ts +253 -0
  217. package/src/ranged.ts +16 -3
  218. package/src/search.ts +69 -13
  219. package/src/stores.ts +76 -11
  220. package/src/tools.ts +327 -75
  221. package/src/types.ts +45 -1
  222. package/src/whole-cost.ts +64 -0
package/src/tools.ts CHANGED
@@ -2,7 +2,7 @@ import { safeErrorMessage } from "./errors.js";
2
2
  import { until } from "./http.js";
3
3
  import { aggregateTable, FILTER_OPS, MAX_SHOWN_GROUPS, type AggregateRequest, type FilterOp } from "./aggregate.js";
4
4
  import { GROUP_BY_VALUES, MAX_GROUP_KEYS, type GroupBy, type GroupResult } from "./groups.js";
5
- import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
5
+ import { analyzeWholeDocument, listWholeDocumentItems, MAX_ITEM_LABELS, MAX_LABEL_CHARACTERS, NothingReadError, storeGaveUp, type WholeItemsResult } from "./map-reduce.js";
6
6
  import { cutPdfPages, type PageCut } from "./pdf-pages.js";
7
7
  import type { Limiter } from "./limiter.js";
8
8
  import { DocumentGoneError } from "./ranged.js";
@@ -10,7 +10,7 @@ import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type Document
10
10
  import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
11
11
  import type { RetryOptions } from "./retry.js";
12
12
  import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
13
- import type { Budget, GenerateText, ProgressListener, ToolCallHooks, ToolCallLimits, ToolDeclaration, ToolOutput, ToolResult, ToolSet } from "./types.js";
13
+ import type { Budget, GenerateText, ProgressListener, ToolCallHooks, ToolCallLimits, ToolDeclaration, ToolName, ToolOutput, ToolResult, ToolSet } from "./types.js";
14
14
 
15
15
  const DEFAULT_READ_LINES = 200;
16
16
  /** Matching lines an exact or regex search shows: the default, and the most a call may ask for. */
@@ -47,7 +47,7 @@ export const TOOL_NAMES = {
47
47
  analyze: "analyze_whole_document",
48
48
  view: "view_pages",
49
49
  aggregate: "aggregate_table",
50
- } as const;
50
+ } as const satisfies Record<string, ToolName>;
51
51
 
52
52
  const documentId = { type: "string" as const, description: "The document_id from the file's card." };
53
53
 
@@ -93,12 +93,18 @@ const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
93
93
  },
94
94
  analyze: {
95
95
  name: TOOL_NAMES.analyze,
96
+ // 0.9.0's words, kept: with a sentence on items here, Gemini Flash-Lite stopped choosing the
97
+ // read for a full summary. What items do is said in the description of `output` alone.
96
98
  description: "Read an entire large file in parts and answer a task that needs all of it, such as a full summary, a timeline, or items that must be judged by meaning. To count or list lines that contain a word, an ID or a pattern, use search_document in exact or regex mode instead: its count is exact, and this can miss items. Slow and costly: prefer search_document and read_document for specific questions.",
97
99
  parameters: {
98
100
  type: "object",
99
101
  properties: {
100
102
  document_id: documentId,
101
103
  task: { type: "string", description: "What to find or produce from the whole file, stated completely." },
104
+ // "answer" is named for a summary and a timeline: told that items list things, Flash-Lite
105
+ // chose them for a timeline of events, whose items explain nothing, and lost events.
106
+ output: { type: "string", enum: ["answer", "items"], description: "\"answer\" (the default): one answer written from the notes of every part, for a summary, a timeline, or a description of events. \"items\": to count the items of a kind that must be judged by meaning, such as the clauses that set a fine: each part lists them, each with its line and a quote checked against the file, and the result counts them, by label." },
107
+ labels: { type: "array", items: { type: "string" }, description: `output "items" only: the kinds of item to label each one with, such as ["penalty", "deadline"]. Up to ${MAX_ITEM_LABELS}, each up to ${MAX_LABEL_CHARACTERS} characters.` },
102
108
  },
103
109
  required: ["document_id", "task"],
104
110
  },
@@ -148,6 +154,20 @@ const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
148
154
  },
149
155
  };
150
156
 
157
+ /** The keys of `DECLARATIONS` in the order a tool set declares them. */
158
+ const DECLARATION_ORDER = ["search", "read", "overview", "aggregate", "analyze", "view"] as const satisfies ReadonlyArray<keyof typeof TOOL_NAMES>;
159
+
160
+ /**
161
+ * The declarations of the tools `names`, in the order a tool set declares them (search, read,
162
+ * overview, aggregate, analyze, view), whatever the order of `names`: those `files.tools(…,
163
+ * { declare: names })` gives. For planning the size of a request before the tools are made. A name
164
+ * that is not a tool's is left out. New in 0.10.0.
165
+ */
166
+ export function declarationsFor(names: readonly ToolName[]): ToolDeclaration[] {
167
+ const wanted = new Set<string>(names);
168
+ return DECLARATION_ORDER.filter((key) => wanted.has(TOOL_NAMES[key])).map((key) => DECLARATIONS[key]);
169
+ }
170
+
151
171
  /** Says so when a tool that returns files is run through `execute`, which has nowhere to put them. */
152
172
  const FILES_NOT_DELIVERED = "The pages could not be shown: this application does not pass files from tools to the model. Answer from the text.";
153
173
 
@@ -169,6 +189,64 @@ function flag(value: unknown): boolean {
169
189
 
170
190
  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.";
171
191
 
192
+ /** The note of a read that stopped merging at the question's limit on model requests (N12, new in 0.10.0). */
193
+ const notesLeftOutNote = (leftOut: number, relevant: number): string =>
194
+ `Incomplete: this read reached the question's limit on model requests before it could combine the notes of every part, so the notes of ${leftOut} of the ${relevant} relevant parts are not in 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.`;
195
+
196
+ /** The items a read that lists them shows in its result; `total_items` counts them all. */
197
+ const MAX_SHOWN_ITEMS = 50;
198
+
199
+ /** The `labels` of a read that lists items, as the model sent them: up to `MAX_ITEM_LABELS`, each up to `MAX_LABEL_CHARACTERS`. */
200
+ function itemLabels(value: unknown): string[] | undefined {
201
+ const list = stringList(value, "labels")?.map((label) => label.trim()).filter(Boolean);
202
+ if (!list || list.length === 0) return undefined;
203
+ const distinct = [...new Set(list)];
204
+ if (distinct.length > MAX_ITEM_LABELS || distinct.some((label) => [...label].length > MAX_LABEL_CHARACTERS)) {
205
+ throw new Error(`labels takes up to ${MAX_ITEM_LABELS} labels, each up to ${MAX_LABEL_CHARACTERS} characters.`);
206
+ }
207
+ return distinct;
208
+ }
209
+
210
+ /** A task as a note quotes it: ending in a stop, so that the sentence after it starts as one. */
211
+ const quotedTask = (task: string): string => {
212
+ const trimmed = task.trim();
213
+ return /[.!?…:;]$/u.test(trimmed) ? trimmed : `${trimmed}.`;
214
+ };
215
+
216
+ /** The sentence of a note on the items a result shows, when not all of them: as `itemsResult` and `fitItems` write it. */
217
+ const itemsShown = (shown: number, cut: boolean): string =>
218
+ `The first ${shown} ${plural(shown, "item")} ${shown === 1 ? "is" : "are"} shown${cut ? ", to stay within the size limit" : ""}; total_items counts them all.`;
219
+ const ITEMS_SHOWN = /The first \d+ items? (?:is|are) shown(?:, to stay within the size limit)?; total_items counts them all\.\s*/;
220
+
221
+ /**
222
+ * The result of a read that lists items (`output: "items"`): the totals, counted by code from the
223
+ * items each part listed and checked against its lines, and the first items in the order of the file.
224
+ */
225
+ function itemsResult(file: string, task: string, read: WholeItemsResult): ToolResult {
226
+ const shown = read.items.slice(0, MAX_SHOWN_ITEMS);
227
+ const more = read.items.length - shown.length;
228
+ const notes = [
229
+ // With items listed and none found on its line, the note on those that are not counted follows.
230
+ ...(read.items.length === 0 ? [read.unverified > 0 ? `No item was found on its line for: ${quotedTask(task)}` : `No part of ${file} listed an item for: ${quotedTask(task)}`] : []),
231
+ ...(more > 0 ? [itemsShown(shown.length, false)] : []),
232
+ ...(read.unverified > 0 ? [`${read.unverified} listed ${plural(read.unverified, "item")} ${read.unverified === 1 ? "is" : "are"} not counted: ${read.unverified === 1 ? "its" : "their"} quote is not on the line ${read.unverified === 1 ? "it names" : "they name"}, nor on just one other line of the part.`] : []),
233
+ ...(read.failedParts > 0 ? [`${read.failedParts} ${plural(read.failedParts, "part")} could not be read (${read.firstFailure ?? "see the notes"}), so items may be missing: tell the user the count may be incomplete.`] : []),
234
+ ...(read.truncatedParts > 0 ? [`${read.truncatedParts} ${plural(read.truncatedParts, "part")} listed more items than fit the model's output limit, even read in smaller pieces, so items may be missing: tell the user the count may be incomplete.`] : []),
235
+ ];
236
+ return {
237
+ document: file,
238
+ total_items: read.items.length,
239
+ ...(Object.keys(read.countsByLabel).length > 0 ? { counts_by_label: read.countsByLabel } : {}),
240
+ items: shown.map(({ line, label, value, quote }) => ({ line, ...(label !== undefined ? { label } : {}), ...(value !== undefined ? { value } : {}), quote })),
241
+ ...(more > 0 ? { more_items: more } : {}),
242
+ unverified_items: read.unverified,
243
+ parts_read: read.parts,
244
+ ...(read.failedParts > 0 ? { parts_failed: read.failedParts } : {}),
245
+ ...(read.truncatedParts > 0 ? { parts_cut_short: read.truncatedParts } : {}),
246
+ ...(notes.length > 0 ? { note: notes.join(" ") } : {}),
247
+ };
248
+ }
249
+
172
250
  function text(value: unknown, name: string): string {
173
251
  if (typeof value !== "string" || !value.trim()) throw new Error(`${name} is required.`);
174
252
  return value;
@@ -211,9 +289,12 @@ function fit(result: ToolResult, listKey: string | null, limit: number): ToolRes
211
289
 
212
290
  /**
213
291
  * The result of a whole-document read within `limit` characters: its answer is cut at the end,
214
- * and says so, rather than the result being cut as JSON, which loses what the other fields say.
292
+ * and says so, rather than the result being cut as JSON, which loses what the other fields say. A
293
+ * read that lists items (`output: "items"`, new in 0.10.0) loses items from the end of its list,
294
+ * and keeps its counts.
215
295
  */
216
296
  export function fitAnswer(result: ToolResult, limit: number): ToolResult {
297
+ if (JSON.stringify(result).length > limit && typeof result.answer !== "string" && Array.isArray(result.items) && result.items.length > 0) return fitItems(result, limit);
217
298
  if (JSON.stringify(result).length <= limit || typeof result.answer !== "string") return fit(result, null, limit);
218
299
  const answer = result.answer;
219
300
  const cutAt = (keep: number): ToolResult => ({
@@ -233,6 +314,33 @@ export function fitAnswer(result: ToolResult, limit: number): ToolResult {
233
314
  return fit(cutAt(low), null, limit);
234
315
  }
235
316
 
317
+ /**
318
+ * The result of a read that lists items within `limit` characters: items are dropped from the end of
319
+ * its list, at least one kept, `more_items` counts every item not shown, and the note says how many
320
+ * are shown. Its counts stay whole. A result cut before (`askWithFiles` fits a result again to the
321
+ * room left) is cut the same way, from what it still shows.
322
+ */
323
+ function fitItems(result: ToolResult, limit: number): ToolResult {
324
+ const items = result.items as unknown[];
325
+ const total = typeof result.total_items === "number" ? result.total_items : items.length;
326
+ const others = typeof result.note === "string" ? result.note.replace(ITEMS_SHOWN, "").trim() : "";
327
+ const build = (kept: number): ToolResult => {
328
+ const more = total - kept;
329
+ const out: ToolResult = {};
330
+ // The fields in their order, with more_items after the items.
331
+ for (const [key, value] of Object.entries(result)) {
332
+ if (key === "more_items" || key === "note") continue;
333
+ out[key] = key === "items" ? items.slice(0, kept) : value;
334
+ if (key === "items" && more > 0) out.more_items = more;
335
+ }
336
+ out.note = [itemsShown(kept, true), others].filter(Boolean).join(" ");
337
+ return out;
338
+ };
339
+ let kept = items.length;
340
+ while (kept > 1 && JSON.stringify(build(kept)).length > limit) kept--;
341
+ return fit(build(kept), null, limit);
342
+ }
343
+
236
344
  /**
237
345
  * The result of an exact or regex search that read the whole file: the first matches, then the
238
346
  * last one of the file, and a note that says how many of how many are shown when that is not all.
@@ -570,6 +678,8 @@ export function alreadyShown(call: { name: string; args: Record<string, unknown>
570
678
  const { result } = earlier;
571
679
  if (earlier.call.name !== call.name || earlier.call.args.document_id !== call.args.document_id) return undefined;
572
680
  if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true) return undefined;
681
+ // A result the application replaced (`onToolResult`, since 0.10.0) does not hold what the call returns.
682
+ if (result.redacted === true) return undefined;
573
683
  // A search stored by 0.7.0 with case_sensitive or whole_word as text or 1 ("true", 1): 0.7.0 read
574
684
  // those as off, 0.8.0 as on, so the call made now would not return what was stored.
575
685
  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;
@@ -642,8 +752,13 @@ export function toolResultSummary(label: string, result: ToolResult): string {
642
752
  const groups = typeof result.total_groups === "number" ? `, ${result.total_groups.toLocaleString("en-US")} ${plural(result.total_groups, "group")}` : "";
643
753
  return ` — ${result.rows_matched.toLocaleString("en-US")} ${plural(result.rows_matched, "row")}${groups}`;
644
754
  }
755
+ if (typeof result.total_items === "number" && typeof result.parts_read === "number") {
756
+ const unverified = typeof result.unverified_items === "number" && result.unverified_items > 0 ? `, ${result.unverified_items.toLocaleString("en-US")} not counted` : "";
757
+ const incomplete = result.parts_failed || result.parts_cut_short ? ", incomplete" : "";
758
+ return ` — ${result.total_items.toLocaleString("en-US")} ${plural(result.total_items, "item")} in ${result.parts_read} ${plural(result.parts_read, "part")}${unverified}${incomplete}`;
759
+ }
645
760
  if (typeof result.parts_read === "number") {
646
- const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
761
+ const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.notes_left_out || result.answer_cut_short ? ", incomplete" : "";
647
762
  return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
648
763
  }
649
764
  // A read reports its range only when it was cut short of what was asked.
@@ -752,21 +867,48 @@ export function createDocumentTools(options: {
752
867
  * `aggregate_table` is then declared. A call of it is answered either way. Defaults to false.
753
868
  */
754
869
  tables?: boolean;
870
+ /**
871
+ * Declare exactly these tools, in the order of `declarationsFor`, in place of those the documents
872
+ * call for. A declared tool that cannot run answers each call with its reason. New in 0.10.0.
873
+ */
874
+ declare?: readonly ToolName[];
875
+ /**
876
+ * The IDs of documents sent whole in the prompt: `analyze_whole_document` refuses them, as the
877
+ * model has every line of them already, and `aggregate_table` says how to cite their lines. New in
878
+ * 0.10.0.
879
+ */
880
+ inline?: readonly string[];
755
881
  }): ToolSet {
756
882
  const allowed = new Set(options.documentIds);
757
883
  const viewable = new Set(options.loadOriginal ? options.viewableIds ?? [] : []);
758
884
  const names = new Map<string, string>(Object.entries(options.names ?? {}));
885
+ const inline = new Set(options.inline ?? []);
886
+ const declared = options.declare ? new Set<string>(options.declare) : undefined;
759
887
  // The text tools are left out only when there are pages to look at and no document to search.
760
888
  const textTools = allowed.size > 0 || viewable.size === 0;
761
- const declarations = [
889
+ const declarations = options.declare ? declarationsFor(options.declare) : [
762
890
  ...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.tables ? [DECLARATIONS.aggregate] : []), ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
763
891
  ...(viewable.size > 0 ? [DECLARATIONS.view] : []),
764
892
  ];
765
893
  const known = new Set(declarations.map((declaration) => declaration.name));
766
- // Answered for any document, declared or not: a model may know the tool from earlier in the conversation.
767
- if (textTools) known.add(TOOL_NAMES.aggregate);
768
- // Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
769
- if (textTools && options.generate) known.add(TOOL_NAMES.analyze);
894
+ // With `declare`, the tool set answers the tools it declares and no other: a call of one it does
895
+ // not declare (a whole-file read, many requests) is not run.
896
+ if (!declared) {
897
+ // Answered for any document, declared or not: a model may know the tool from earlier in the conversation.
898
+ if (textTools) known.add(TOOL_NAMES.aggregate);
899
+ // Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
900
+ if (textTools && options.generate) known.add(TOOL_NAMES.analyze);
901
+ }
902
+ /**
903
+ * Why a declared tool cannot run in this tool set, when it cannot: each call of it answers with
904
+ * this. A caller may declare a tool (`ToolOptions.declare`) that has nothing to work on here.
905
+ */
906
+ const cannotRun = (name: string): string | undefined => {
907
+ if (!declared?.has(name)) return undefined;
908
+ if (name === TOOL_NAMES.aggregate && !options.tables) return "No attached file has a table: aggregate_table needs one.";
909
+ if (name === TOOL_NAMES.view && viewable.size === 0) return "No attached file has pages to look at: view_pages needs a PDF whose original file is kept. Answer from the text.";
910
+ return undefined;
911
+ };
770
912
  const cap = options.budget.toolResultCharacters;
771
913
  /** The cap on the result of one call: the tool set's own, or the room its caller has left when that is less. */
772
914
  const limitOf = (limits: ToolCallLimits, own = cap): number => {
@@ -796,13 +938,54 @@ export function createDocumentTools(options: {
796
938
  const wholeReads = new Map<string, number>();
797
939
  /** Why the last whole-document read of a document failed, when no part of it could be read. */
798
940
  const failedWholeReads = new Map<string, string>();
941
+ const wholeReadsDeclared = declarations.some((declaration) => declaration.name === TOOL_NAMES.analyze);
942
+ /**
943
+ * What a `read_document` result cut short of its range by the size limit adds (`whole_file`), as
944
+ * the lines it shows of the file from `start` (`shown`, or none whole when `cut`: the text of the
945
+ * first line was cut): that `analyze_whole_document` reads all of it. Gemini Flash-Lite and Flash
946
+ * read a contract to summarize in ranges of about 16 lines, and answered from those
947
+ * (`evals/results/0100-t-live-3.md`). Only when this tool set declares the read and would run it on
948
+ * the file, by the estimate of its parts: a part reader, a file not sent whole, a read of it left,
949
+ * and its parts within `maxMapChunks` and within the requests the call says a whole read may make
950
+ * (`limits.maxRequests`), the checks the read makes before it sends a part (`partsToRead`). The
951
+ * parts are `estimateParts`'s, without the margin `canBeReadWhole` gives the estimate. The read
952
+ * counts its own, and at a border may count one more than the estimate: then it is refused, before
953
+ * it sends a request. `askWithFiles` gives a read 0 requests when the question would not start a
954
+ * whole read of its file on the next turn, the first the model can call it on (its ceilings on
955
+ * input tokens and requests, with that turn's request counted, its whole reads made). New in 0.10.0.
956
+ */
957
+ const wholeFileHint = (document: DocumentSource, start: number, shown: number, cut: boolean, limits: ToolCallLimits): string | undefined => {
958
+ const id = document.meta.id;
959
+ if (!wholeReadsDeclared || !options.generate || inline.has(id) || failedWholeReads.has(id) || (wholeReads.get(id) ?? 0) >= maxWholeReads) return undefined;
960
+ const requests = typeof limits.maxRequests === "number" && !Number.isNaN(limits.maxRequests) ? limits.maxRequests : Number.POSITIVE_INFINITY;
961
+ // Every part is one request.
962
+ if (requests < 1) return undefined;
963
+ const parts = estimateParts(document.meta, options.budget);
964
+ // Metadata that does not give its size (a record an application kept in part): as `canBeReadWhole`, not held back.
965
+ if (Number.isFinite(parts) && (parts > options.budget.maxMapChunks || parts > requests)) return undefined;
966
+ const total = document.lineCount.toLocaleString("en-US");
967
+ const fitting = cut
968
+ ? `Not even one line fits here: the text of line ${start.toLocaleString("en-US")} is cut.`
969
+ : `Only ${shown.toLocaleString("en-US")} ${shown === 1 ? "line fits" : "lines fit"} here.`;
970
+ return `${fitting} To read all ${total} lines for a task that needs all of them, such as a full summary or a timeline, use analyze_whole_document.`;
971
+ };
799
972
  // When no limit is given with a call: three eighths of a request, so that two looks still fit.
800
973
  const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
801
974
 
802
975
  /** The documents the calls under way loaded, by the arguments of the call: checked once it ends (`checkRead`). */
803
976
  const loaded = new WeakMap<object, Set<DocumentSource[]>>();
804
977
 
805
- async function documentFor(args: Record<string, unknown>): Promise<DocumentSource> {
978
+ /**
979
+ * The signal of one call: the tool set's, joined with the call's own (`ToolCallHooks.signal`, new
980
+ * in 0.10.0) when it has one. The call's own ends that call alone.
981
+ */
982
+ const signalOf = (hooks: ToolCallHooks): AbortSignal | undefined => {
983
+ const own = hooks.signal;
984
+ if (!own) return options.signal;
985
+ return options.signal ? AbortSignal.any([options.signal, own]) : own;
986
+ };
987
+
988
+ async function documentFor(args: Record<string, unknown>, signal: AbortSignal | undefined): Promise<DocumentSource> {
806
989
  const id = text(args.document_id, "document_id");
807
990
  // Scope check: a model can only reach files attached to this conversation.
808
991
  if (!allowed.has(id)) {
@@ -812,7 +995,8 @@ export function createDocumentTools(options: {
812
995
  ? `Unknown document_id ${shownId(id)}. No attached file is read with this tool in this conversation.`
813
996
  : `Unknown document_id ${shownId(id)}. Use one of: ${usable.join(", ")}${allowed.size > 20 ? ", …" : ""}.`);
814
997
  }
815
- const document = await options.load(id);
998
+ // A load that hangs does not hold a call that was stopped.
999
+ const document = await until(options.load(id), signal);
816
1000
  if (!document) throw gone(id);
817
1001
  for (const reads of loaded.get(args) ?? []) reads.push(document);
818
1002
  names.set(id, document.meta.name);
@@ -822,10 +1006,10 @@ export function createDocumentTools(options: {
822
1006
  /**
823
1007
  * Waits for the turn of a look at pages of `file`, for at most `pageLookWaitMs`, or the call's
824
1008
  * `maxWaitMs` when that is less. Returns the function that gives the turn back. Past the wait, a
825
- * `PagesBusyError`. The wait ends at once when the tool set is stopped, with the reason it was
826
- * stopped for.
1009
+ * `PagesBusyError`. The wait ends at once when the call is stopped (`signal`), with the reason it
1010
+ * was stopped for.
827
1011
  */
828
- async function pageLookTurn(id: string, file: string, limits: ToolCallLimits): Promise<() => void> {
1012
+ async function pageLookTurn(id: string, file: string, limits: ToolCallLimits, signal: AbortSignal | undefined): Promise<() => void> {
829
1013
  const turns = options.pageLooks;
830
1014
  if (!turns) return () => undefined;
831
1015
  const waited = new AbortController();
@@ -834,9 +1018,9 @@ export function createDocumentTools(options: {
834
1018
  const timer = waitMs <= LONGEST_WAIT_MS ? setTimeout(() => waited.abort(), waitMs) : undefined;
835
1019
  timer?.unref?.();
836
1020
  try {
837
- return await turns.limiter.acquire(options.signal ? AbortSignal.any([options.signal, waited.signal]) : waited.signal);
1021
+ return await turns.limiter.acquire(signal ? AbortSignal.any([signal, waited.signal]) : waited.signal);
838
1022
  } catch (error) {
839
- if (options.signal?.aborted || !waited.signal.aborted) throw error;
1023
+ if (signal?.aborted || !waited.signal.aborted) throw error;
840
1024
  throw new PagesBusyError(id, file);
841
1025
  } finally {
842
1026
  clearTimeout(timer);
@@ -845,10 +1029,10 @@ export function createDocumentTools(options: {
845
1029
 
846
1030
  /**
847
1031
  * The original file of a look, read while the look holds its turn: for at most `holdMs`, and
848
- * only while the tool set runs. A read given up on goes on, but holds no turn.
1032
+ * only while the call runs. A read given up on goes on, but holds no turn.
849
1033
  */
850
- async function originalOf(id: string, file: string): Promise<Uint8Array | undefined> {
851
- const reading = until(options.loadOriginal!(id), options.signal);
1034
+ async function originalOf(id: string, file: string, signal: AbortSignal | undefined): Promise<Uint8Array | undefined> {
1035
+ const reading = until(options.loadOriginal!(id), signal);
852
1036
  const holdMs = options.pageLooks?.holdMs;
853
1037
  if (holdMs === undefined || !(holdMs <= LONGEST_WAIT_MS)) return reading;
854
1038
  let timer: ReturnType<typeof setTimeout> | undefined;
@@ -864,10 +1048,11 @@ export function createDocumentTools(options: {
864
1048
  }
865
1049
  }
866
1050
 
867
- const handlers: Record<string, (args: Record<string, unknown>, limits: ToolCallLimits, hooks: ToolCallHooks) => Promise<ToolResult>> = {
868
- async [TOOL_NAMES.search](args, limits) {
1051
+ /** The tools that return JSON. `signal` is the call's (`signalOf`). */
1052
+ const handlers: Record<string, (args: Record<string, unknown>, limits: ToolCallLimits, hooks: ToolCallHooks, signal: AbortSignal | undefined) => Promise<ToolResult>> = {
1053
+ async [TOOL_NAMES.search](args, limits, _hooks, signal) {
869
1054
  const limit = limitOf(limits);
870
- const document = await documentFor(args);
1055
+ const document = await documentFor(args, signal);
871
1056
  const query = text(args.query, "query");
872
1057
  const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
873
1058
  // Page numbers are added only for a PDF whose pages can be looked at: they are what
@@ -885,7 +1070,7 @@ export function createDocumentTools(options: {
885
1070
  if (mode === "keywords") {
886
1071
  if (groupBy) throw new Error("group_by counts the lines of an exact or regex search: use mode \"exact\" or \"regex\".");
887
1072
  const topK = integer(args.max_results, 5, 1, 10);
888
- const ranked = await rankSource(document, query, topK, options.signal, ranged ? range : undefined);
1073
+ const ranked = await rankSource(document, query, topK, signal, ranged ? range : undefined);
889
1074
  const texts = await Promise.all(ranked.map((passage) => document.readLines(passage.from, passage.to)));
890
1075
  return fit({
891
1076
  document: document.meta.name,
@@ -916,7 +1101,7 @@ export function createDocumentTools(options: {
916
1101
  maxResults: integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS),
917
1102
  contextLines: integer(args.context_lines, 0, 0, 5),
918
1103
  ...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
919
- ...(options.signal ? { signal: options.signal } : {}),
1104
+ ...(signal ? { signal } : {}),
920
1105
  ...(ranged ? { fromLine: range.from, toLine: range.to } : {}),
921
1106
  ...(order === "last" ? { order } : {}),
922
1107
  ...(groupBy ? { groupBy } : {}),
@@ -962,9 +1147,9 @@ export function createDocumentTools(options: {
962
1147
  }, "matches", limit);
963
1148
  },
964
1149
 
965
- async [TOOL_NAMES.read](args, limits) {
1150
+ async [TOOL_NAMES.read](args, limits, _hooks, signal) {
966
1151
  const limit = limitOf(limits);
967
- const document = await documentFor(args);
1152
+ const document = await documentFor(args, signal);
968
1153
  const total = document.lineCount;
969
1154
  const start = integer(args.start_line, 1, 1, total);
970
1155
  const end = integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, Math.min(total, start + MAX_READ_LINES - 1));
@@ -979,21 +1164,28 @@ export function createDocumentTools(options: {
979
1164
  body = numberLines(read.slice(0, to - start + 1), start);
980
1165
  }
981
1166
  const pages = viewable.has(document.meta.id) ? document.pagesOfLines(start, to) : undefined;
982
- return {
1167
+ const cut = !fits(body);
1168
+ const result: ToolResult = {
983
1169
  document: document.meta.name,
984
1170
  lines: `${start}-${to}`,
985
1171
  ...(pages ? { pages } : {}),
986
1172
  total_lines: total,
987
- text: fits(body) ? body : sliceWhole(body, Math.floor((limit - 500) / 2)),
1173
+ text: cut ? sliceWhole(body, Math.floor((limit - 500) / 2)) : body,
988
1174
  // One line longer than the room: its text was cut, so the lines are not all shown.
989
- ...(fits(body) ? {} : { text_cut: true }),
1175
+ ...(cut ? { text_cut: true } : {}),
990
1176
  ...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
991
1177
  };
1178
+ // Cut short of the range asked by the size limit: the way to all of the file, when there is
1179
+ // one. Left out when it would take the result past its cap.
1180
+ const hint = to < end ? wholeFileHint(document, start, to - start + 1, cut, limits) : undefined;
1181
+ if (!hint) return result;
1182
+ const hinted = { ...result, whole_file: hint };
1183
+ return JSON.stringify(hinted).length <= limit ? hinted : result;
992
1184
  },
993
1185
 
994
- async [TOOL_NAMES.overview](args, limits) {
1186
+ async [TOOL_NAMES.overview](args, limits, _hooks, signal) {
995
1187
  const limit = limitOf(limits);
996
- const document = await documentFor(args);
1188
+ const document = await documentFor(args, signal);
997
1189
  const { meta, lineCount } = document;
998
1190
  const tail = Math.max(1, lineCount - 19);
999
1191
  // Counting the parts means reading the whole text, for a number that only says how costly a
@@ -1018,11 +1210,11 @@ export function createDocumentTools(options: {
1018
1210
  }, "outline", limit);
1019
1211
  },
1020
1212
 
1021
- async [TOOL_NAMES.aggregate](args, limits) {
1213
+ async [TOOL_NAMES.aggregate](args, limits, _hooks, signal) {
1022
1214
  const limit = limitOf(limits);
1023
- const document = await documentFor(args);
1215
+ const document = await documentFor(args, signal);
1024
1216
  const request = aggregateRequest(args);
1025
- const result = await aggregateTable(document, request, options.signal);
1217
+ const result = await aggregateTable(document, request, signal);
1026
1218
  const groups = result.groups.map((group) => ({
1027
1219
  ...(Object.keys(group.key).length > 0 ? { group: group.key } : {}),
1028
1220
  ...group.values,
@@ -1046,24 +1238,40 @@ export function createDocumentTools(options: {
1046
1238
  ...(result.repeatedHeaders > 0 ? { repeated_header_rows: result.repeatedHeaders } : {}),
1047
1239
  ...(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." } : {}),
1048
1240
  ...(result.irregularRows > 0 ? { irregular_rows: result.irregularRows, irregular_note: "Rows with values past the header's columns: check columns and header_rows." } : {}),
1241
+ // A filter whose value named a column compared two cells of each row (since 0.10.0): said, so that no one takes it for a value.
1242
+ ...(result.compared ? { filter_note: result.compared.map((one) => `Each row's ${JSON.stringify(one.column)} was compared with its own ${JSON.stringify(one.with)} (${one.op}), as the filter's value names that column.`).join(" ") } : {}),
1049
1243
  };
1050
1244
  const note = groups.length < result.totalGroups
1051
1245
  ? { 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.` }
1052
1246
  : {};
1053
- return fit({ ...base, ...note, groups }, "groups", limit);
1247
+ // Over a table shown in full, Flash-Lite answered with the count alone, citing no line: the
1248
+ // result says how to cite the lines it lists, with the file's name (since 0.10.0).
1249
+ const firstLines = groups[0]?.lines ?? [];
1250
+ const cite = inline.has(document.meta.id) && firstLines.length > 0
1251
+ ? { cite: `Cite the lines listed in your answer, like (${document.meta.name} ${firstLines.map((line) => `L${line}`).join(", ")}).` }
1252
+ : {};
1253
+ return fit({ ...base, ...note, groups, ...cite }, "groups", limit);
1054
1254
  },
1055
1255
 
1056
- async [TOOL_NAMES.analyze](args, limits, hooks) {
1256
+ async [TOOL_NAMES.analyze](args, limits, hooks, signal) {
1057
1257
  if (!options.generate) throw new Error("Whole-document analysis is not enabled.");
1058
- const document = await documentFor(args);
1258
+ // A document sent whole is not read again in parts: the model has every line of it.
1259
+ const asked = text(args.document_id, "document_id");
1260
+ if (inline.has(asked)) throw new Error(`${names.get(asked) ?? shownId(asked)} is shown in full above: answer from it, and use search_document or aggregate_table for exact counts.`);
1261
+ const document = await documentFor(args, signal);
1059
1262
  const task = text(args.task, "task");
1263
+ const items = args.output === "items";
1264
+ // Read before the count is taken: a call with labels it cannot use is no read.
1265
+ const labels = items ? itemLabels(args.labels) : undefined;
1060
1266
  // A read of the whole file is many model requests. A model that asks for it again, with the
1061
1267
  // task put another way, is told to use what it has. The count is taken before the read
1062
1268
  // starts, so that two calls in one turn do not both pass.
1063
1269
  const id = document.meta.id;
1064
1270
  const reads = wholeReads.get(id) ?? 0;
1065
- if (reads >= maxWholeReads) {
1066
- const failure = failedWholeReads.get(id);
1271
+ const failure = failedWholeReads.get(id);
1272
+ // A read that could read no part is not tried again, whatever the cap: another would most
1273
+ // likely fail the same way, and `wholeReadsLeft` says 0 for it.
1274
+ if (reads >= maxWholeReads || failure !== undefined) {
1067
1275
  throw new Error(maxWholeReads === 0
1068
1276
  ? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
1069
1277
  : failure !== undefined
@@ -1072,20 +1280,21 @@ export function createDocumentTools(options: {
1072
1280
  : `${document.meta.name} was already read whole for this question${maxWholeReads > 1 ? ` ${maxWholeReads} times` : ""}, and is not read whole again. Use the answer of that read, or search_document and read_document for the details.`);
1073
1281
  }
1074
1282
  wholeReads.set(id, reads + 1);
1283
+ const read = {
1284
+ document,
1285
+ task,
1286
+ generate: options.generate,
1287
+ budget: options.budget,
1288
+ // The call's own listener, when it has one, in place of the tool set's.
1289
+ onProgress: hooks.onProgress ?? options.onProgress,
1290
+ ...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
1291
+ signal,
1292
+ ...(options.retry ? { retry: options.retry } : {}),
1293
+ ...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
1294
+ };
1075
1295
  let result;
1076
1296
  try {
1077
- result = await analyzeWholeDocument({
1078
- document,
1079
- task,
1080
- generate: options.generate,
1081
- budget: options.budget,
1082
- // The call's own listener, when it has one, in place of the tool set's.
1083
- onProgress: hooks.onProgress ?? options.onProgress,
1084
- ...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
1085
- signal: options.signal,
1086
- ...(options.retry ? { retry: options.retry } : {}),
1087
- ...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
1088
- });
1297
+ result = items ? await listWholeDocumentItems({ ...read, ...(labels ? { labels } : {}) }) : await analyzeWholeDocument(read);
1089
1298
  } catch (error) {
1090
1299
  // Parts were sent and none could be read: that read is counted, since another would most
1091
1300
  // likely fail the same way. Anything else (too many parts, a store that could not be read)
@@ -1097,25 +1306,35 @@ export function createDocumentTools(options: {
1097
1306
  throw error;
1098
1307
  }
1099
1308
  failedWholeReads.delete(id);
1309
+ const room = limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS));
1310
+ if ("items" in result) return fitAnswer(itemsResult(document.meta.name, task, result), room);
1100
1311
  const notesCutShort = result.truncatedParts + result.truncatedMerges;
1312
+ const cutNote = notesCutShort ? " Some of them were cut off at the output limit, so they are incomplete: tell the user." : "";
1101
1313
  return fitAnswer({
1102
1314
  document: document.meta.name,
1103
1315
  parts_read: result.parts,
1104
1316
  parts_with_relevant_content: result.relevantParts,
1105
1317
  ...(result.failedParts ? { parts_that_failed: result.failedParts } : {}),
1106
1318
  ...(notesCutShort ? { notes_cut_short: notesCutShort } : {}),
1319
+ ...(result.notesLeftOut ? { notes_left_out: result.notesLeftOut } : {}),
1107
1320
  ...(result.answerTruncated ? { answer_cut_short: true } : {}),
1108
- ...(result.answerFailed !== undefined ? { notes_only: true } : {}),
1321
+ ...(result.answerFailed !== undefined || result.answerSkipped ? { notes_only: true } : {}),
1109
1322
  ...(result.answerFailed !== undefined
1110
- ? { note: `The last step of this read, which writes one answer from the notes of the parts, failed (${result.answerFailed}). The answer is those notes: answer from them.${notesCutShort ? " Some of them were cut off at the output limit, so they are incomplete: tell the user." : ""}` }
1111
- : notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
1323
+ ? { note: `The last step of this read, which writes one answer from the notes of the parts, failed (${result.answerFailed}). The answer is those notes: answer from them.${cutNote}` }
1324
+ : result.answerSkipped
1325
+ ? { note: `This read reached the question's limit on model requests before its last step, which writes one answer from the notes of the parts. The answer is those notes: answer from them.${cutNote}` }
1326
+ : result.notesLeftOut
1327
+ ? { note: notesLeftOutNote(result.notesLeftOut, result.relevantParts) }
1328
+ : notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
1112
1329
  answer: result.answer,
1113
- }, limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS)));
1330
+ }, room);
1114
1331
  },
1115
1332
  };
1116
1333
 
1117
1334
  /** `view_pages`: the pages as one small PDF, next to a short JSON result. */
1118
- async function viewPages(args: Record<string, unknown>, limits: ToolCallLimits): Promise<ToolOutput> {
1335
+ async function viewPages(args: Record<string, unknown>, limits: ToolCallLimits, signal: AbortSignal | undefined): Promise<ToolOutput> {
1336
+ const reason = cannotRun(TOOL_NAMES.view);
1337
+ if (reason) throw new Error(reason);
1119
1338
  const id = text(args.document_id, "document_id");
1120
1339
  // The same scope check as the text tools, on its own list: a PDF can be looked at without
1121
1340
  // being searchable, and the other way round.
@@ -1124,7 +1343,7 @@ export function createDocumentTools(options: {
1124
1343
  ? `The pages of ${names.get(id) ?? id} cannot be shown: only its text was kept. Answer from the text.`
1125
1344
  : `Unknown document_id ${shownId(id)}. Use the document_id of an attached PDF.`);
1126
1345
  }
1127
- const document = await options.load(id);
1346
+ const document = await until(options.load(id), signal);
1128
1347
  if (!document) throw gone(id);
1129
1348
  const file = document.meta.name;
1130
1349
  names.set(id, file);
@@ -1143,13 +1362,13 @@ export function createDocumentTools(options: {
1143
1362
  // look that waits holds none of its bytes, and the memory left is looked at then (`cutPdfPages`).
1144
1363
  // A question stopped while its original is read gives the turn back at once, and so does a
1145
1364
  // read that takes longer than the library allows its store calls (`holdMs`).
1146
- const release = await pageLookTurn(id, file, limits);
1365
+ const release = await pageLookTurn(id, file, limits, signal);
1147
1366
  let cut: PageCut | undefined;
1148
1367
  try {
1149
- options.signal?.throwIfAborted();
1150
- const original = await originalOf(id, file);
1368
+ signal?.throwIfAborted();
1369
+ const original = await originalOf(id, file, signal);
1151
1370
  // Stopped while the original was read: no pages are cut for a question that has left.
1152
- options.signal?.throwIfAborted();
1371
+ signal?.throwIfAborted();
1153
1372
  if (original) {
1154
1373
  try {
1155
1374
  cut = await cutPdfPages(original, from, Math.min(asked, from + mostPages - 1), maxBytes, total);
@@ -1162,7 +1381,7 @@ export function createDocumentTools(options: {
1162
1381
  }
1163
1382
  if (!cut) {
1164
1383
  // The document may have gone while the look waited for its turn: that is told as such.
1165
- if (!await options.load(id)) throw gone(id);
1384
+ if (!await until(options.load(id), signal)) throw gone(id);
1166
1385
  throw new Error(`The original file of ${file} is no longer on the server, so its pages cannot be shown. Answer from the text.`);
1167
1386
  }
1168
1387
  const pages = pageRange(cut.from, cut.to);
@@ -1193,32 +1412,51 @@ export function createDocumentTools(options: {
1193
1412
  return { error: safeErrorMessage(error) };
1194
1413
  };
1195
1414
 
1415
+ /**
1416
+ * True for an error the call throws rather than tells the model: the call, or the tool set, was
1417
+ * stopped; or the store did not answer in time, or was not asked because too many store calls are
1418
+ * stuck (since 0.10.0), which ends the question with an error and shows the model nothing.
1419
+ */
1420
+ const thrown = (error: unknown, signal: AbortSignal | undefined): boolean => signal?.aborted === true || storeGaveUp(error);
1421
+
1196
1422
  async function execute(name: string, args: Record<string, unknown>, limits: ToolCallLimits = {}, hooks: ToolCallHooks = {}): Promise<ToolResult> {
1197
1423
  if (!known.has(name)) return { error: `Unknown tool ${unknownToolName(name)}.` };
1198
1424
  // The pages are a file, and this method returns only JSON. Saying that pages are attached
1199
1425
  // with nothing attached would be worse than saying that they could not be shown.
1200
- if (name === TOOL_NAMES.view) return { error: FILES_NOT_DELIVERED };
1426
+ if (name === TOOL_NAMES.view) return { error: cannotRun(name) ?? FILES_NOT_DELIVERED };
1427
+ const reason = cannotRun(name);
1428
+ if (reason) return { error: reason };
1429
+ const signal = signalOf(hooks);
1201
1430
  // The documents this call loads (`documentFor`), by its arguments: calls given the same object
1202
1431
  // at once each note them all.
1203
1432
  const reads: DocumentSource[] = [];
1204
1433
  const calls = typeof args === "object" && args !== null ? loaded.get(args) ?? new Set<DocumentSource[]>() : undefined;
1205
1434
  if (calls) loaded.set(args, calls.add(reads));
1435
+ /**
1436
+ * Asks the store, once the call has ended, whether each document it read is still the one it
1437
+ * loaded. A call with a signal of its own ends when it aborts, even while this store call hangs.
1438
+ */
1206
1439
  const checkReads = async () => {
1207
- for (const document of reads) if (options.checkRead && !await options.checkRead(document)) throw gone(document.meta.id);
1440
+ const checking = (async () => {
1441
+ for (const document of reads) if (options.checkRead && !await options.checkRead(document)) throw gone(document.meta.id);
1442
+ })();
1443
+ await (hooks.signal ? until(checking, signal) : checking);
1208
1444
  };
1209
1445
  try {
1210
1446
  let result: ToolResult;
1211
1447
  try {
1212
- result = await handlers[name]!(args, limits, hooks);
1448
+ // A call with a signal of its own ends when it aborts, even in a store call that hangs.
1449
+ const running = handlers[name]!(args, limits, hooks, signal);
1450
+ result = await (hooks.signal ? until(running, signal) : running);
1213
1451
  } catch (error) {
1214
- if (options.signal?.aborted) throw error;
1452
+ if (thrown(error, signal)) throw error;
1215
1453
  await checkReads();
1216
1454
  throw error;
1217
1455
  }
1218
1456
  await checkReads();
1219
1457
  return result;
1220
1458
  } catch (error) {
1221
- if (options.signal?.aborted) throw error;
1459
+ if (thrown(error, signal)) throw error;
1222
1460
  return failure(error, args, hooks);
1223
1461
  } finally {
1224
1462
  calls?.delete(reads);
@@ -1229,16 +1467,27 @@ export function createDocumentTools(options: {
1229
1467
  declarations,
1230
1468
  has: (name) => known.has(name),
1231
1469
  execute: (name, args) => execute(name, args),
1232
- resultCharacters: (name) => (name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
1470
+ // A name the tool set does not answer, a declared tool that cannot run, and a whole-file read
1471
+ // with no part reader each get an error of a few words: no more room is kept for them.
1472
+ resultCharacters: (name) => (!known.has(name) || cannotRun(name) !== undefined || (name === TOOL_NAMES.analyze && !options.generate) ? LEAST_RESULT_CHARACTERS
1473
+ : name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
1233
1474
  async executeWithFiles(name, args, limits = {}, hooks = {}) {
1234
1475
  if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args, limits, hooks), files: [] };
1476
+ const signal = signalOf(hooks);
1235
1477
  try {
1236
- return await viewPages(args, limits);
1478
+ const running = viewPages(args, limits, signal);
1479
+ return await (hooks.signal ? until(running, signal) : running);
1237
1480
  } catch (error) {
1238
- if (options.signal?.aborted) throw error;
1481
+ if (thrown(error, signal)) throw error;
1239
1482
  return { result: failure(error, args, hooks), files: [] };
1240
1483
  }
1241
1484
  },
1485
+ wholeReadsLeft(documentId) {
1486
+ // None for a document this tool set cannot read whole: no part reader, not one of its
1487
+ // documents, or one sent whole; none once a read of it could read no part.
1488
+ if (!options.generate || !allowed.has(documentId) || inline.has(documentId) || failedWholeReads.has(documentId)) return 0;
1489
+ return Math.max(0, maxWholeReads - (wholeReads.get(documentId) ?? 0));
1490
+ },
1242
1491
  describe(name, args) {
1243
1492
  const id = typeof args.document_id === "string" ? args.document_id : "";
1244
1493
  const file = names.get(id) ?? "the file";
@@ -1256,9 +1505,12 @@ export function createDocumentTools(options: {
1256
1505
  return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”${where}${how}`;
1257
1506
  }
1258
1507
  if (name === TOOL_NAMES.read) {
1259
- const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
1260
- const end = typeof args.end_line === "number" && args.end_line >= start ? `-${Math.trunc(args.end_line)}` : "";
1261
- return `Read ${file} lines ${start}${end}`;
1508
+ // The lines as the tool reads them (`requestedLines`): an end sent as text ("250") too, and
1509
+ // never past the most lines one read shows. The end is shown when the call gave one, not
1510
+ // before the start.
1511
+ const [start, end] = requestedLines(args);
1512
+ const given = args.end_line !== undefined && args.end_line !== null && args.end_line !== "" && Number(args.end_line) >= start;
1513
+ return `Read ${file} lines ${start}${given ? `-${end}` : ""}`;
1262
1514
  }
1263
1515
  if (name === TOOL_NAMES.overview) return `Overview of ${file}`;
1264
1516
  if (name === TOOL_NAMES.aggregate) {
@@ -1275,7 +1527,7 @@ export function createDocumentTools(options: {
1275
1527
  const table = request.table !== undefined && request.table !== "" ? ` (${typeof request.table === "number" ? `table ${request.table}` : request.table})` : "";
1276
1528
  return sliceWhole(`Aggregate ${file}${table}: ${metrics}${by}${where}`, 200);
1277
1529
  }
1278
- if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”`;
1530
+ if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”${args.output === "items" ? ", as a list of items" : ""}`;
1279
1531
  return name;
1280
1532
  },
1281
1533
  };