llm-large-files 0.8.2 → 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 (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  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 +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
@@ -110,11 +110,16 @@ const openai = openAiCompatible({
110
110
  apiKey: process.env.OPENAI_API_KEY!,
111
111
  model: "gpt-5.5",
112
112
  contextTokens: 400_000,
113
- body: { reasoning_effort: "medium" }, // every chat request
114
- analysisBody: () => ({ reasoning_effort: "low" }), // the part reads of a whole-file read
113
+ body: { reasoning_effort: "none" }, // every chat request: tool calls need it (below)
114
+ analysisBody: () => ({ reasoning_effort: "low" }), // the part reads of a whole-file read, which offer no tools
115
115
  });
116
116
  ```
117
117
 
118
+ - **Tool calls on GPT-5.4 and later need `reasoning_effort: "none"`** through Chat Completions,
119
+ which is their default: with another effort and tools in the request, the API refuses the
120
+ request. The chat requests of the loop offer tools, so leave the effort out of `body`, or set
121
+ `"none"`. A part read offers no tools, and may reason. For reasoning with tools, OpenAI points to
122
+ its Responses API, which this adapter does not speak (planned for 1.0.0).
118
123
  - Part reads name their output limit `max_completion_tokens`, which OpenAI's newer models require.
119
124
  - A reasoning model sends nothing while it thinks. `firstByteTimeoutMs` (600 s) is the wait for
120
125
  its first piece. Its `completion_tokens_details.reasoning_tokens` are counted as
@@ -202,7 +207,33 @@ const deepseek = openAiCompatible({
202
207
  question and the request for an answer with no turn between them, and DeepSeek's reasoner
203
208
  refuses two user turns in a row.
204
209
  - **The model's own turn goes back with its `reasoning_content`**, streamed or not
205
- ([the reply](../reference/openai.md#openaicompatibleoptions)).
210
+ ([the reply](../reference/openai.md#openaicompatibleoptions)). Within a question the loop sends
211
+ it back.
212
+ - **Thinking mode and follow-up questions.** In a request with tools, DeepSeek's thinking mode
213
+ asks for the `reasoning_content` of every earlier assistant turn, those of earlier questions
214
+ included, even a turn that made no tool call, and refuses a request without it (HTTP 400). So
215
+ says its [thinking mode guide](https://api-docs.deepseek.com/guides/thinking_mode) (read in
216
+ November 2026). Without tools in the request, earlier reasoning is ignored. The library does not
217
+ keep the reasoning of an answer yet: `AskResult` does not give it, and a stored answer is a
218
+ `ChatTurn` of text. So a follow-up question that offers tools goes out without the reasoning of
219
+ the earlier answers, and DeepSeek refuses it. Thinking is on by default on DeepSeek's current
220
+ models. In a chat of several questions, turn it off for chat requests. The part reads of a
221
+ whole-file read offer no tools and do not use `body`, so they keep thinking:
222
+
223
+ ```ts
224
+ const deepseek = openAiCompatible({
225
+ baseUrl: "https://api.deepseek.com/v1",
226
+ apiKey: process.env.DEEPSEEK_API_KEY!,
227
+ model: "deepseek-v4-pro",
228
+ contextTokens: 128_000,
229
+ body: { thinking: { type: "disabled" } }, // chat requests: a follow-up offers tools
230
+ });
231
+ ```
232
+
233
+ A first question, with no earlier answer in `messages`, works with thinking on. The tool rounds
234
+ of earlier questions go back as their calls and results, without their reasoning, so they do
235
+ not give DeepSeek what it asks for either. Keeping the reasoning of earlier questions is planned
236
+ for a later version.
206
237
  - **`insufficient_system_resource`**: DeepSeek stops a reply when its servers run short. The
207
238
  adapter takes that for the server's failure, HTTP 503, and the loop sends the request again. A
208
239
  reply that is not streamed is checked before any of it is shown, so it can always be sent again;
@@ -380,9 +411,13 @@ the larger limit off when that allowance is no larger than 32,768. Both requests
380
411
  - **When a wait runs out**, the request is aborted with an `OpenAiRequestError` of status 0 and kind
381
412
  `"timeout"` ("The model sent nothing for 600 s."). `askWithFiles` sends it again once, unless
382
413
  text of it was already shown.
383
- - **A part read** has `timeoutMs` for the whole request, reply included. One that runs out is tried
384
- once more at once, and then counts as a part that could not be read, which the tool result says.
385
- Raise `timeoutMs` for a model that thinks long over a large part.
414
+ - **A part read** has `timeoutMs` for the whole request, reply included. One that runs out is an
415
+ `OpenAiRequestError` of status 0 and kind `"timeout"` ("The model took longer than 180 s to
416
+ answer."), since 0.10.0; before, the abort error of the timer, with no status, tried once more at
417
+ once. It is tried once more, after the retry wait (`retry.baseDelayMs`: 250 to 500 ms by default)
418
+ and with a `retry` event, and then counts as a part that could not be read, which the
419
+ tool result says ("The model took too long to answer."). Raise `timeoutMs` for a model that
420
+ thinks long over a large part; 0 sets none (since 0.10.0).
386
421
 
387
422
  How failed requests are sent again, and what to tell your user, is in
388
423
  [Errors and reliability](./errors-and-reliability.md).
@@ -590,7 +625,12 @@ Who does what, what changes for your application, and what it costs:
590
625
 
591
626
  Gemini also has an OpenAI layer, at `https://generativelanguage.googleapis.com/v1beta/openai`, and
592
627
  the adapter reads its errors, which come wrapped in a list. For Gemini, `gemini()` is the adapter to
593
- use: it sends pages to the model, which the layer refuses as a `file` part.
628
+ use: it sends pages to the model, which the layer refuses as a `file` part. The layer also leaves a
629
+ thinking model's thoughts out of its usage: in a live check in 0.10.0 on `gemini-3.8-flash`, its
630
+ `total_tokens` was about 46 more than `prompt_tokens` plus `completion_tokens`, with no
631
+ `reasoning_tokens`. Those tokens are billed, but `usage.outputTokens` does not hold them, and
632
+ `usage.thoughtTokens` is 0. `result.lastUsage` keeps the layer's own object, `total_tokens`
633
+ included.
594
634
 
595
635
  ## What was run live
596
636
 
@@ -701,7 +701,7 @@ refusing a whole-file read that would pass a ceiling of the question before it s
701
701
 
702
702
  ### The steps
703
703
 
704
- 1. **Plan.** `files.prepare(documentIds, base, { owner, viewPages, wholeDocumentAnalysis, budget })`.
704
+ 1. **Plan.** `files.prepare(documentIds, base, { owner, scope, viewPages, wholeDocumentAnalysis, budget })`.
705
705
  `base` is the size of the rest of the request, `{ tokens, bytes }`: the system prompt and the
706
706
  conversation, with a margin for what frames them (`askWithFiles` adds 2,000 tokens and 8,000
707
707
  bytes). The documents are fitted into what the budget leaves. Pass `wholeDocumentAnalysis: false`
@@ -709,7 +709,9 @@ refusing a whole-file read that would pass a ceiling of the question before it s
709
709
  `analyze_whole_document`, and the cards do not offer a whole-file read. The result is a
710
710
  `PreparedContext`:
711
711
  - `missing`: IDs that were never uploaded, were deleted, have expired, or belong to another
712
- owner. Stop and ask for them again. `askWithFiles` throws `DocumentsNotFoundError` here.
712
+ owner or scope. Stop and ask for them again. `askWithFiles` throws `DocumentsNotFoundError`
713
+ here, unless its `onMissingDocuments` says to answer without them (the plan you got is already
714
+ made without them) or brings them back (plan again).
713
715
  - `blocks`: for each document, its whole text or its card. Put them at the start of the first
714
716
  user turn, in the order of your IDs.
715
717
  - `instruction`: the guide to the tools, for the system prompt. Empty when there is nothing to
@@ -718,10 +720,29 @@ refusing a whole-file read that would pass a ceiling of the question before it s
718
720
  bytes of the inline text.
719
721
  - `viewable`: the PDFs whose pages `view_pages` can show, because their uploaded file is kept
720
722
  (`keepOriginals`). Empty unless you pass `viewPages: true` and the store keeps originals.
721
- 2. **No tools needed?** When `plan.searchable` and `viewable` are both empty, every document is in
722
- the prompt: send one request without tools.
723
+ - New in 0.10.0: `toolable`, with `inlineTables: "tools"`. `instruction` and the blocks stay
724
+ those of 0.9 unless you ask for `numberInline` or `inlineTables`.
725
+
726
+ Two options of 0.10.0 change the text, and are off unless you ask for them:
727
+ - `numberInline: true` numbers the lines of each file sent whole as the tools number them
728
+ (`12| `), so that the model can cite its lines as it cites those of a searched file. The file is
729
+ planned by its numbered size, about 8% to 16% more tokens, so a file at the edge of
730
+ `inlineTokens` may become a card. `instruction` asks for citations only when a file is
731
+ searched. When none is (no tools, a table shown in full, a PDF whose pages can be looked at),
732
+ add `Cite line numbers like (report.docx L12).` to the system text after it.
733
+ - `inlineTables: "tools"` lists in `toolable` the files sent whole whose tables the tools can
734
+ count: a CSV or an XLSX workbook, or a DOCX, PPTX, PDF, HTML or Markdown file with a table of at
735
+ least 3 `| cell |` rows. Give them to `tools` with the searched files, so that a count over a
736
+ table shown in full is exact (`aggregate_table`), not done by eye. The block of each gives its
737
+ document_id in its first frame line, since the tools take it and it has no card.
738
+ `instruction` does not say that these tables can be counted. When `toolable` is not empty,
739
+ add after it the line `askWithFiles` adds: `Files shown in full can still be counted exactly:
740
+ use aggregate_table for counts, sums and groups over their tables, and search_document exact
741
+ for matching lines. In a spreadsheet, give the Row number when asked which row.`
742
+ 2. **No tools needed?** When `plan.searchable` and `viewable` are both empty, and `toolable` is
743
+ empty or not set, every document is in the prompt: send one request without tools.
723
744
  3. **Tools.** `files.tools(prepared.plan.searchable, options)` gives a `ToolSet`. The options that
724
- matter here: `generate` (a `GenerateText`, which turns on `analyze_whole_document`; without it,
745
+ matter here: `access` (the owner and scope of step 1), `generate` (a `GenerateText`, which turns on `analyze_whole_document`; without it,
725
746
  plan with `wholeDocumentAnalysis: false` in step 1), `viewPages` (pass `prepared.viewable`, and
726
747
  only when your loop sends files to the model), `signal`, `onProgress` (progress of whole-file
727
748
  reads, for every call; per call, see [`ToolCallHooks`](#progress-of-each-call-toolcallhooks)),
@@ -730,12 +751,14 @@ refusing a whole-file read that would pass a ceiling of the question before it s
730
751
  searches belong to it. The full list is in the
731
752
  [library reference](../reference/library.md#tooloptions).
732
753
 
733
- Pass `tools()` only metadata that came back for this user: `prepared.plan.searchable` and
734
- `prepared.viewable` from `prepare(ids, base, { owner })`, or `getMeta(id, { owner })`. The tool
735
- set takes no owner option: the model can reach every document it is given, and each call
736
- compares the owner stored with the document with the `owner` of the metadata it was handed.
737
- Metadata built from IDs the client sent, without the stored owner, reads nothing of a document
738
- that has one: each call answers `doc_… is no longer available on the server. …`.
754
+ Pass `access: { owner, scope }`, new in 0.9.0: each call then asks the store for the document
755
+ with that owner and scope, and checks the ones the store holds against them, whatever the
756
+ metadata handed in says. A document of another owner or scope reads nothing: each call answers
757
+ `doc_… is no longer available on the server. …`. Under `requireOwner` or `requireScope`, `tools()`
758
+ throws without it. Without `access`, as before 0.9.0, each call compares the owner and scope
759
+ stored with the document with those of the metadata it was handed, so pass `tools()` only
760
+ metadata that came back for this user: `prepared.plan.searchable` and `prepared.viewable` from
761
+ `prepare(ids, base, { owner, scope })`, or `getMeta(id, { owner, scope })`.
739
762
  4. **Offer** `tools.declarations` in your provider's form. Gemini takes them as
740
763
  `functionDeclarations` (`toGeminiTools`), the OpenAI-compatible adapter sends each as
741
764
  `{ type: "function", function: declaration }`, and the Claude adapter as
@@ -782,6 +805,7 @@ import {
782
805
  FINAL_ANSWER_REQUEST,
783
806
  jsonBytes,
784
807
  retryAfterMs,
808
+ TOOL_NAMES,
785
809
  toolResultSummary,
786
810
  UsageMeter,
787
811
  withRetry,
@@ -866,6 +890,8 @@ export async function ask(question: string, documentIds: string[], owner: string
866
890
  const needsTools = prepared.plan.searchable.length > 0 || prepared.viewable.length > 0;
867
891
  const readPart = createGeminiGenerateText({ url: endpoint.url, headers: endpoint.headers });
868
892
  const tools = files.tools(prepared.plan.searchable, {
893
+ // The store's owner of each document is checked against this one on every call.
894
+ access: { owner },
869
895
  // Part reads of analyze_whole_document, counted with the chat's requests.
870
896
  generate: (request) => readPart({ ...request, onUsage: (used) => usage.add(MODEL, used) }),
871
897
  viewPages: prepared.viewable,
@@ -910,7 +936,9 @@ export async function ask(question: string, documentIds: string[], owner: string
910
936
  maxResultCharacters: Math.floor((tokensLeft * 2) / Math.min(calls.length, MAX_CALLS)),
911
937
  maxFileBytes: Math.floor(((budget.maxRequestBytes - sentBytes - 1_000_000) * 3) / 4), // base64: four bytes for three
912
938
  maxPages: pagesLeft,
913
- maxRequests: MAX_REQUESTS - usage.totals.requests - 1, // for a whole-file read; one is kept for the answer
939
+ // For a whole-file read, one is kept for the answer. A read_document call points at a whole
940
+ // read the model can make on its next turn at the earliest: that turn's request is kept too.
941
+ maxRequests: MAX_REQUESTS - usage.totals.requests - (call.name === TOOL_NAMES.read ? 2 : 1),
914
942
  });
915
943
  console.log(`${label}${toolResultSummary(label, output.result)}`);
916
944
  if (output.files.length > 0) {
@@ -959,9 +987,18 @@ into. Fill it from your own request, as the sample above does:
959
987
  - `maxFileBytes`: the room left in your request for the pages of this call, times 3/4 when files go
960
988
  as base64.
961
989
  - `maxPages`: the pages the question may still show. Lower it as the pages add up.
962
- - `maxRequests`: what your ceiling on requests has left, for a whole-file read. It only limits how
963
- many parts refused as too large are read again as two halves: a read that needs more parts than
964
- this still makes all of them, the merges of their notes and an answer.
990
+ - `maxRequests`: what your ceiling on requests has left, for a whole-file read. Since 0.10.0 a read
991
+ with more parts than this is refused before any request, and makes its merges within it; before,
992
+ it only limited how many parts refused as too large were read again as two halves. Give it to
993
+ `read_document` calls too, as the sample does (since 0.10.0): a read cut short of its range
994
+ points at a whole read of its file (`whole_file`) only when the file's parts are within it. The
995
+ model can call that read on its next turn at the earliest: `askWithFiles` keeps that turn's
996
+ request out of what it gives a `read_document` call, and gives 0 when it would not run a whole
997
+ read on that turn. Do the same in your loop.
998
+ - `maxWaitMs` (new in 0.9.0): the most a look at pages waits for its turn, when that is less than
999
+ the library's `pageLookWaitMs`. `askWithFiles` gives 0 to the looks of a turn after one was told
1000
+ the server is busy (`onPagesBusy`, below), so that a wait that ends busy comes once in a turn. Do
1001
+ the same in your loop.
965
1002
 
966
1003
  The defaults, the floors and the errors a call answers with are in the
967
1004
  [tools reference](../reference/tools.md#toolcalllimits).
@@ -981,7 +1018,14 @@ listeners for one call as the fourth argument of `executeWithFiles`
981
1018
  once when it ends. `usage` is what the part reader passed to `onUsage` for that request, so you
982
1019
  can show or count the cost of each read.
983
1020
 
984
- Only `analyze_whole_document` calls them; the other tools ignore them.
1021
+ Only `analyze_whole_document` calls them; the other tools ignore them. Two more, new in 0.9.0,
1022
+ are called by any tool:
1023
+
1024
+ - `onDocumentGone(documentId)`: the document was deleted or expired after you planned the request.
1025
+ The call's result tells the model so. Tell the user, or take it off the chat.
1026
+ - `onPagesBusy(documentId)`: a look at pages waited longer than `pageLookWaitMs` for its turn
1027
+ (`maxConcurrentPageLooks` of the library) and was not run. The result tells the model the server
1028
+ is busy.
985
1029
 
986
1030
  ```ts
987
1031
  import type { ToolCall, ToolCallHooks, ToolCallLimits, ToolOutput, ToolSet } from "llm-large-files";
@@ -12,7 +12,7 @@ on every server that ingests files:
12
12
 
13
13
  ```bash
14
14
  npm install jszip # DOCX, PPTX and XLSX
15
- npm install unpdf # PDF text (on Node 20 and 22, name a version: see below)
15
+ npm install unpdf # PDF text (on Node 22, name a version: see below)
16
16
  npm install @cantoo/pdf-lib # PDF picture marks, page check, and view_pages
17
17
  ```
18
18
 
@@ -20,12 +20,11 @@ They are optional peer dependencies of the package: `jszip` ^3.10.0, `unpdf` ^1.
20
20
  and `@cantoo/pdf-lib` ^2.11.1.
21
21
 
22
22
  Not every `unpdf` runs on every Node. unpdf 2 asks for Node 24, and on Node 24 and later
23
- `npm install unpdf` installs it. On Node 20 and 22, install a version that runs there:
23
+ `npm install unpdf` installs it. On Node 22, install a version that runs there:
24
24
 
25
25
  | Node | `unpdf` to install | Refused at the first PDF ([What is refused](#what-is-refused)) |
26
26
  |---|---|---|
27
- | 20 | 1.4.0, or 1.6.1 to 1.8.1: `npm install unpdf@1.7.0`. 1.7.0 is the last that does not ask for Node 22. | 1.5.0 to 1.6.0, which would stop the whole process; 1.9 and later, 2.x included, which cannot load pdf.js on Node 20 |
28
- | 22 | 1.4.0, or 1.6.1 or a later 1.x: `npm install unpdf@1` | 1.5.0 to 1.6.0 |
27
+ | 22 | 1.4.0, or 1.6.1 or a later 1.x: `npm install unpdf@1` | 1.5.0 to 1.6.0, which would stop the whole process |
29
28
  | 24 and later | Any version from 1.4.0, 2.x included: `npm install unpdf` | None |
30
29
 
31
30
  The 12 test PDFs of the package give the same text, pages, picture marks and page cuts with every
@@ -73,8 +72,10 @@ pieces than 0.5.0 split it, which moves the lines after it. Since 0.8.0 the text
73
72
  (NFC): "e" and a combining accent become "é". Every format but log, JSON and CSV gets an outline
74
73
  from its headings: Markdown `#` lines (`## Slide N` and `## Sheet N: name` among them; not in a
75
74
  fenced code block, nor the comments of a text file that reads as code), chapter and numbered section
76
- lines, and short lines in capitals. `meta.pages` is the number of pages of a PDF, of slides of a
77
- PPTX and of sheets of an XLSX. [How it works](../how-it-works.md) follows ingest from there.
75
+ lines, and short lines in capitals; a PDF whose text gives fewer than 3 of these, from the lines set
76
+ in larger type than its body, when there are 3 or more ([PDF outline](#pdf-outline), new in
77
+ 0.10.0). `meta.pages` is the number of pages of a PDF, of slides of a PPTX and of sheets of an
78
+ XLSX. [How it works](../how-it-works.md) follows ingest from there.
78
79
 
79
80
  ### Text encodings
80
81
 
@@ -257,11 +258,19 @@ all, and an XLSX was refused as a ZIP archive.
257
258
 
258
259
  `files.ingest` throws an [`IngestError`](../reference/library.md#ingesterror) whose message is
259
260
  meant for the user, with a `code` for your application. `createDocumentHandlers` answers it with
260
- HTTP 422 and that message, except a file over `maxUploadBytes`, which the upload route refuses
261
- before reading it all: HTTP 413, `The file is larger than the 100 MB upload limit.`
262
- ([node reference](../reference/node.md)). For a damaged file the message is the reader's own, from
263
- pdf.js or jszip, and not written for a user, with the code `"unreadable"`: an application that
264
- wants friendlier wording maps the codes itself.
261
+ HTTP 422 and that message, with two exceptions:
262
+
263
+ - A file over `maxUploadBytes`, which the upload route refuses before reading it all: HTTP 413,
264
+ `The file is larger than the 100 MB upload limit.` ([node reference](../reference/node.md)).
265
+ - A file of code `"unreadable"`: a damaged file, whose message is the reader's own (from pdf.js or
266
+ jszip, and not written for a user), a DOCX or XLSX without its main part, and an error of an
267
+ extractor of your own that the library does not know. Since 0.9.0 the upload route,
268
+ `uploadAnswerOf` and `errorInfoOf` answer it in fixed words: `This file could not be read. It may
269
+ be damaged, or not of the type its name says.` The message below stays on the error, for your
270
+ log.
271
+
272
+ An application that wants other wording maps the codes itself
273
+ ([`errorInfoOf`](./errors-and-reliability.md#your-users-words-errorinfoof)).
265
274
 
266
275
  | What | Message |
267
276
  |---|---|
@@ -293,16 +302,14 @@ wants friendlier wording maps the codes itself.
293
302
  | A file that takes longer than `ingestTimeoutMs` to read (2 minutes by default) | `report.pdf took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.` |
294
303
  | A PDF without text on any page | See [Scanned PDFs](#scanned-pdfs). |
295
304
  | A PDF that needs a password to open | `This PDF is protected by a password, so it cannot be read. Open it, print it to a new PDF without the password, and attach that.` Until 0.8.0, `No password given`, the message of pdf.js. |
296
- | A damaged PDF | The message of pdf.js, such as `Invalid PDF structure.` |
297
- | A damaged DOCX, PPTX or XLSX, or one that is not a ZIP | The message of jszip, such as `Can't find end of central directory : is this a zip file ? …` |
298
- | A DOCX without `word/document.xml` | `This DOCX does not contain word/document.xml.` |
305
+ | A damaged PDF | The message of pdf.js, such as `Invalid PDF structure.` Code `"unreadable"`: the upload route answers in fixed words (above). |
306
+ | A damaged DOCX, PPTX or XLSX, or one that is not a ZIP | The message of jszip, such as `Can't find end of central directory : is this a zip file ? …` Code `"unreadable"`: the upload route answers in fixed words. |
307
+ | A DOCX without `word/document.xml` | `This DOCX does not contain word/document.xml.` Code `"unreadable"`: the upload route answers in fixed words. |
299
308
  | A PPTX without slides | `This PPTX does not contain any slides.` |
300
- | An XLSX without `xl/workbook.xml`, or without sheets | `This XLSX does not contain xl/workbook.xml.`, `This XLSX does not contain any sheets with cells.` |
309
+ | An XLSX without `xl/workbook.xml`, or without sheets | `This XLSX does not contain xl/workbook.xml.` (code `"unreadable"`: the upload route answers in fixed words), `This XLSX does not contain any sheets with cells.` |
301
310
  | A DOCX, PPTX or XLSX without `jszip` installed | `Reading DOCX, PPTX and XLSX files needs the optional dependency "jszip".` |
302
311
  | A PDF without `unpdf` installed | `Reading PDF files needs the optional dependency "unpdf".` |
303
312
  | A PDF, with `unpdf` 1.5.0 to 1.6.0 on Node 22 or 23, which would stop the whole process at the first PDF (0.5.0 did stop) | `The unpdf installed would stop the whole server at the first PDF file on Node 22, so PDF files are not read. Install unpdf 1.6.1 or later, or run Node 24 or later.` |
304
- | The same on Node 20 | `The unpdf installed would stop the whole server at the first PDF file on Node 20, so PDF files are not read. Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 24 or later.` |
305
- | A PDF, with `unpdf` 1.9 or later (2.x included) on Node 20, which cannot load pdf.js there | `The unpdf installed cannot read PDF files on Node 20 (Serverless PDF.js bundle could not be resolved: ReferenceError: Iterator is not defined). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.` The part in parentheses is unpdf's own message: with unpdf 2 it is `PDF.js could not be resolved: ReferenceError: Iterator is not defined`. |
306
313
 
307
314
  A missing dependency, or an `unpdf` that does not run on your Node, is your server's fault, but it
308
315
  reaches the user as a 422, a file that cannot be read. Install the dependencies wherever the upload
@@ -409,6 +416,7 @@ Figure 3: sales by region.
409
416
  - With `@cantoo/pdf-lib` installed, a page that shows a picture or a drawing gets the second line
410
417
  ([The line that marks a page](#the-line-that-marks-a-page)).
411
418
  - Tables are rebuilt as rows of cells ([PDF tables](#pdf-tables)).
419
+ - The lines set in larger type than the body are the outline ([PDF outline](#pdf-outline)).
412
420
 
413
421
  ### PDF tables
414
422
 
@@ -422,8 +430,9 @@ the rebuilt rows 110 ([measurements](../measurements.md)).
422
430
  What it handles: empty cells, tables inside one column of a two-column page, right-to-left tables
423
431
  (the first column is the rightmost), tables printed sideways, rotated pages, footnote marks,
424
432
  headings that span columns, and cells whose text wraps onto several lines when the rows are visibly
425
- spaced apart. Text that is not a table (paragraphs, lists, columns of prose, justified text) is left
426
- as pdf.js gives it.
433
+ spaced apart. A cell that mixes the two directions (a Latin name in a Hebrew table, a Hebrew phrase
434
+ in an English one) keeps each run of words in its reading order. Text that is not a table
435
+ (paragraphs, lists, columns of prose, justified text) is left as pdf.js gives it.
427
436
 
428
437
  It is cautious: where the evidence for a table is weak, the text stays as it was. So:
429
438
 
@@ -459,6 +468,87 @@ alone, `@cantoo/pdf-lib` still reads each PDF at ingest, for the page check, and
459
468
  process loads it, in one block of about 0.4 s. With `pictures: false` and `checkPages: false`,
460
469
  ingest does not use it at all ([Deployment](./deployment.md#uploads-and-ingest)).
461
470
 
471
+ ### PDF outline
472
+
473
+ The card and `get_document_overview` give the model an outline, headings with their line numbers,
474
+ and a search hit names the heading above it (`section`). The rules that find headings in a text
475
+ seldom find any in a PDF: pdf.js gives no blank line between paragraphs, and Hebrew has no capitals,
476
+ so an unnumbered Hebrew contract had no outline. Since 0.10.0 the PDF extractor finds the lines set
477
+ in larger type than the body, from the size pdf.js gives each piece of text, and `ingest` makes them
478
+ the outline of a PDF whose text gives fewer than 3 headings, when 3 or more of them are found in the
479
+ stored text. One or two are not an outline: a PDF with a title alone keeps the card and search hits
480
+ of 0.9.0. The card of a lease then starts its outline with:
481
+
482
+ ```text
483
+ Outline (8 of 8 headings):
484
+ L3 חוזה שכירות בלתי מוגנת
485
+ L6 הצדדים לחוזה
486
+ L9 פרטי השוכר
487
+ L16 תקופת השכירות
488
+ ```
489
+
490
+ - The body is the size most of the text is set in, table rows aside. A heading is a line at least
491
+ 15% larger, with three quarters of its characters in that size: the title, Word's Heading 1 and
492
+ Heading 2 (16 and 13 points over 11), the `h1` to `h3` of a page printed by Chrome.
493
+ - A table row is a line with a gap of more than 3 times its type size between two of its pieces:
494
+ cells, or a label and its value, whether the table was rebuilt or not (two columns, or
495
+ `tables: false`). It counts for neither the body nor the headings, so a statement whose table is
496
+ set smaller than its notes does not make its notes headings.
497
+ - Its level comes from its size. The sizes of several headings rank from the largest: 1, 2, then 3
498
+ for all smaller ones. A size of one heading only, larger than all of those (a title, the lines of
499
+ a cover page), is level 1, and the ranks then start at 2: a cover does not flatten the sections
500
+ and subsections under it.
501
+ - Each heading is a line of the stored text, and points to it: `read_document` from that line
502
+ starts at the heading. A heading set on several lines in a row is one entry, at its first line.
503
+ A line above it on its page that reads the same (a contents list, a running header in small type)
504
+ is passed over.
505
+ - Not headings: a line of more than 120 characters, or of fewer than 3 letters, or with more digits
506
+ than letters (a bare amount, a date in digits, a page number); a table row; a running header or
507
+ footer, which is a line found on 3 pages or more, or on 2 pages and at least half of them.
508
+ - A line that differs from those of other pages only by its numbers ("עמוד 3 מתוך 10", "Annual
509
+ Report page 7") is a page number, and not a heading, when it is found on at least half of the
510
+ pages, does not count up on one page (the same number in a page's header and its footer is one
511
+ page number), and does not count as section numbers do. Section numbers count
512
+ headings: each is the one before with one number 1 more, with pages without one between some of
513
+ them ("פרק 1" to "פרק 5" on the odd pages). A page number counts pages, and skips those it is
514
+ missing from: a header on the odd pages only reads "page 1", "page 3". Numbered headings several
515
+ to a page ("Article 1" to "Article 18", 3 to a page; "סעיף 1" to "סעיף 20", 2 to a page above
516
+ their titles) are always kept.
517
+ - No outline from sizes when more than 30% of the text is set larger than the body: the sizes then
518
+ mark something else.
519
+
520
+ It adds no line to the text: the text of a PDF, its reads and its pages are those of 0.9.0, and its
521
+ search hits the same but for the `section` they now name. What it does not find: a heading in bold
522
+ type of the body's size (pdf.js does not say which text is bold), a heading less than 15% larger
523
+ than the body (Word's Heading 3, 12 points over 11), a heading repeated on 3 pages or more,
524
+ numbered chapters one to a page on pages in a row that are at least half the document ("Chapter 1"
525
+ to "Chapter 4" on pages 1 to 4 of 6: they count as a page number does), and headings a PDF keeps
526
+ only in its bookmarks or tags. What it can take for a heading: any other short line set large, such
527
+ as a caption, a date written with its month's name, or a total with its label ("Total due
528
+ 12,500.00"); the header cell of a table that is not rebuilt when pdf.js gives it as a line of its
529
+ own; and a header row set large whose cells are closer than 3 times its type size, as in a narrow
530
+ table of two columns ("Field" and "Value"), which does not read as a table row. A PDF whose text
531
+ gives 3 headings or more (lines that start with `#`) keeps the outline of its text.
532
+
533
+ A PDF ingested before 0.10.0 keeps the outline it was given, most often none, until it is uploaded
534
+ again; the metadata does not say where an outline came from. The outline from sizes comes in
535
+ `ExtractedText.headings`: to keep the outline of the text alone, drop them in a wrapper.
536
+
537
+ ```ts
538
+ import { createLargeFiles, defaultExtractors, FileDocumentStore, type Extractor } from "llm-large-files";
539
+
540
+ // The outline of 0.9.0: from the text alone.
541
+ const pdfWithoutSizes: Extractor = async (bytes, input) => {
542
+ const { headings, ...extracted } = await defaultExtractors.pdf(bytes, input);
543
+ return extracted;
544
+ };
545
+
546
+ export const files = createLargeFiles({
547
+ store: new FileDocumentStore("./data/large-files"),
548
+ extractors: { pdf: pdfWithoutSizes },
549
+ });
550
+ ```
551
+
462
552
  ## Pictures in PDFs
463
553
 
464
554
  The text of a PDF does not hold its photos, charts and diagrams. Asked about a bar chart from the
@@ -467,8 +557,9 @@ close that gap:
467
557
 
468
558
  1. **A line in the text that says where the pictures are.** It needs `@cantoo/pdf-lib`.
469
559
  2. **A tool, `view_pages`, that hands the model the real pages** as a small PDF, when it asks. It
470
- needs `@cantoo/pdf-lib` and the uploaded file itself, which the store keeps when you list
471
- `"pdf"` in `keepOriginals`.
560
+ needs `@cantoo/pdf-lib` and the uploaded file itself, which is kept when you list `"pdf"` in
561
+ `keepOriginals`: by the store, or, since 0.9.0, where your application keeps it
562
+ ([below](#view_pages-from-your-own-uploads)).
472
563
 
473
564
  ```ts
474
565
  import { createLargeFiles, FileDocumentStore } from "llm-large-files";
@@ -491,6 +582,7 @@ The options of this page, and where each is explained:
491
582
  | Option | Default | What it does |
492
583
  |---|---|---|
493
584
  | `keepOriginals` (`createLargeFiles`) | `[]`: no file kept | List `"pdf"` to keep the uploaded file, which `view_pages` and scanned PDFs need ([above](#pictures-in-pdfs)). |
585
+ | `originals` (`createLargeFiles`) | none | Reads the uploads your application keeps, so the store keeps no copy ([`view_pages` from your own uploads](#view_pages-from-your-own-uploads)). New in 0.9.0. |
494
586
  | `scannedPdfPages` (`createLargeFiles`) | 30 | The most pages a PDF without text may have to be accepted, when PDFs are kept. 0 refuses every one ([Scanned PDFs](#scanned-pdfs)). |
495
587
  | `maxPdfPages`, `maxTextBytes`, `ingestTimeoutMs` (`createLargeFiles`) | 5,000 pages; 100 MB, or `maxUploadBytes` when that is larger; 120,000 ms | The most pages, text and time one file may take at ingest ([What is refused](#what-is-refused)). |
496
588
  | `tables`, `pictures` (`createPdfExtractor`) | `true` | Rebuild tables; write the line that marks a page with a picture ([PDF tables](#pdf-tables), [The line that marks a page](#the-line-that-marks-a-page)). |
@@ -659,6 +751,81 @@ block:
659
751
  A look runs on the server that answers the question, not where the file was ingested
660
752
  ([Deployment](./deployment.md#pages-of-pdfs)).
661
753
 
754
+ **Looks take their turns** (new in 0.9.0). Looks share the thread of your server, so more of them
755
+ at once do not finish sooner: six at once each took about four times as long, and held 352 MB more
756
+ than one. So one look runs at a time in a library, over all its questions, and the others wait in
757
+ order, before their PDF is loaded:
758
+
759
+ | Option (`createLargeFiles`) | Default | What it does |
760
+ |---|---|---|
761
+ | `maxConcurrentPageLooks` | 1 | How many looks run at once. `Infinity` for no limit, as before 0.9.0. |
762
+ | `pageLookWaitMs` | 30,000 | How long a look waits for its turn. Past it, it is not run. |
763
+
764
+ A look that waited too long tells the model "report.pdf: The pages cannot be looked at right now;
765
+ the server is busy. Answer from the text, or look again later.", and the question gets a
766
+ `page_looks_busy` notice ([events](../reference/events.md#noticecode-and-noticedisplay)). A
767
+ question that is stopped stops waiting at once, and loads nothing. A question stopped while its
768
+ PDF is read gives the turn back at once, and no pages are cut for it.
769
+
770
+ A look holds its turn while it reads the PDF from the store, for at most `ingestTimeoutMs` (2
771
+ minutes by default). Past it, the turn goes back, the next look runs, and the model reads "The
772
+ original file of report.pdf could not be read in time, so its pages cannot be shown. Answer from
773
+ the text." Give your store's `getOriginal` a time limit of its own: the read goes on.
774
+
775
+ How long a question can wait for turns:
776
+
777
+ - A look waits at most `pageLookWaitMs` (30 s) for its turn. A wait that ends with "busy" happens
778
+ at most once in a tool turn: after a look of the turn was told the server is busy, the other
779
+ looks of that turn do not wait. Each runs if a turn is free at that moment, and is told the
780
+ server is busy if not.
781
+ - A look that gets its turn may still have waited for it up to `pageLookWaitMs`. So when other
782
+ questions hold the turn all that time, a tool turn can wait up to `pageLookWaitMs` for each of its
783
+ looks: 8 looks of 30 s, 4 minutes, with the defaults (`callsPerTurn` 8), and a question waits that
784
+ in each tool turn that looks at pages.
785
+ - Lower `pageLookWaitMs`, or raise `maxConcurrentPageLooks`, for a chat that must answer sooner.
786
+
787
+ ### `view_pages` from your own uploads
788
+
789
+ New in 0.9.0. When your application keeps each upload anyway, the store need not keep a second
790
+ copy of the PDF. Give the ingest where the file is (`original: { ref }`), and the library a reader
791
+ of your uploads (`originals`): `fileOriginals(root)` of `llm-large-files/node` reads them from a
792
+ folder.
793
+
794
+ ```ts
795
+ import path from "node:path";
796
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
797
+ import { fileOriginals } from "llm-large-files/node";
798
+
799
+ const VOLUME = process.env.DOCUMENTS_DIR!;
800
+
801
+ export const files = createLargeFiles({
802
+ store: new FileDocumentStore(VOLUME, { scopes: { depth: 2 } }),
803
+ keepOriginals: ["pdf"],
804
+ originals: fileOriginals(VOLUME),
805
+ });
806
+
807
+ /** Ingests a PDF your upload route saved under <VOLUME>/<user>/<chat>/uploads/. */
808
+ export function ingestSaved(userId: string, chatId: string, uploadId: string, name: string) {
809
+ const ref = `${userId}/${chatId}/uploads/${uploadId}`;
810
+ return files.ingest({ name, source: { path: path.join(VOLUME, ref) }, original: { ref }, owner: userId, scope: [userId, chatId], id: uploadId });
811
+ }
812
+ ```
813
+
814
+ - The model sees nothing of this: the ref is never in the prompt, the cards or the results.
815
+ - A look reads the file through the reader, within its turn and its time, as it reads a copy from
816
+ the store. The metadata records the size and SHA-256 the file had at ingest, and the look
817
+ compares them. A file that has changed since (saved again under the same name, cut short, edited)
818
+ is not cut, and the model reads "report.pdf changed on the server since it was read. Attach it
819
+ again to look at its pages.": its pages would not match the text the model has. A file that is
820
+ gone reads as "The original file of report.pdf is no longer on the server, so its pages cannot
821
+ be shown. Answer from the text."
822
+ - `files.delete` and the sweep never touch your upload. Remove it with its chat.
823
+ - A scanned PDF is accepted with a ref as with a copy in the store ([Scanned PDFs](#scanned-pdfs)),
824
+ even over a store without `putOriginal`.
825
+ - [Storage](./storage.md#keeping-the-uploaded-files) has the rules for the ref and a reader of your
826
+ own, and [Security](../security.md#originals-your-application-keeps) what `fileOriginals`
827
+ refuses.
828
+
662
829
  ### Limits and cost
663
830
 
664
831
  | Limit | Value | When it is reached |
@@ -785,7 +952,8 @@ refuses text before a tool result.
785
952
 
786
953
  The model gets `view_pages` for a PDF only when all of these hold:
787
954
 
788
- - `keepOriginals` lists `"pdf"`, and the store has `putOriginal` and `getOriginal`.
955
+ - `keepOriginals` lists `"pdf"`, and the store has `putOriginal` and `getOriginal`, or (0.9.0)
956
+ the document was ingested with `original` and the library has `originals`.
789
957
  `FileDocumentStore` and `MemoryDocumentStore` have both. Documents ingested before you turned it
790
958
  on have no file kept: upload them again. `meta.originalKept` says whether a document has one.
791
959
  - Every model of the question can be sent a file: not `openAiCompatible()` without `pdfInput`, not
@@ -827,7 +995,8 @@ export const files = createLargeFiles({
827
995
  });
828
996
  ```
829
997
 
830
- `scannedPdfPages` has an effect only when PDFs are kept, by a store that can keep them. A PDF with
998
+ `scannedPdfPages` has an effect only when PDFs are kept: by a store that can keep them, or (0.9.0)
999
+ by their ref, for an ingest with `original` in a library with `originals`. A PDF with
831
1000
  text on any page is always accepted, however many of its pages are scans: those pages say that they
832
1001
  have no text, and with the file kept the model can look at them.
833
1002
 
@@ -877,15 +1046,27 @@ What the library does with what you return:
877
1046
  your extractor stored as U+FFFD. Both reach the card, the frame of a file sent whole, and
878
1047
  `toDocumentSummary` ([Text encodings](#text-encodings)).
879
1048
  - A `text` file whose lines look like a log becomes `log`.
1049
+ - `headings`, for a PDF, become its outline when its text gives fewer than 3 headings and 3 or more
1050
+ of them are found ([PDF outline](#pdf-outline)): each is looked for among the lines of its page,
1051
+ after the line `--- Page N ---`, by its text without spaces, past the `skip` lines of its page
1052
+ that read the same. New in 0.10.0.
880
1053
 
881
1054
  An error you throw is the answer to the upload. `ingest` throws it as an `IngestError` with the
882
- same message (and your error as `cause`), and `createDocumentHandlers` answers 422 with its
883
- message, unless the error has a `status` (or `statusCode`) from 400 to 599: then it answers that
884
- status, with your message. A status of 413 is answered with the upload-limit message instead of
885
- yours. An error with a Node system `code` and `syscall` (from `fs` or a socket) is answered 500,
886
- `Upload failed (ENOENT).`, without its message. A value that is not an `Error`, such as a thrown
887
- string, is answered 500 too: `Upload failed.` Write messages a user can read, and give a status
888
- when the fault is on your side, such as an OCR service that is down.
1055
+ same message (and your error as `cause`), with the code its message gives
1056
+ ([`ingestErrorCodeOf`](../reference/library.md#ingesterrorcodeofmessage)). `createDocumentHandlers`
1057
+ answers 422 with your message only when the message gives a code the library knows ("is protected
1058
+ by a password", say). Any other message gives code `"unreadable"`, and since 0.9.0 the answer is
1059
+ then 422 in fixed words: `This file could not be read. It may be damaged, or not of the type its
1060
+ name says.` Your message stays on the error, for your log ([what is refused](#what-is-refused)). To
1061
+ have your own words shown, throw `new IngestError(code, message)` with the code that fits
1062
+ ([`Extractor`](../reference/library.md#extractor)).
1063
+
1064
+ An error with a `status` (or `statusCode`) from 400 to 599 is answered with that status and your
1065
+ message. A status of 413 is answered with the upload-limit message instead of yours. An error with
1066
+ a Node system `code` and `syscall` (from `fs` or a socket) is answered 500, `Upload failed
1067
+ (ENOENT).`, without its message. A value that is not an `Error`, such as a thrown string, is
1068
+ answered 500 too: `Upload failed.` Write messages a user can read, and give a status when the fault
1069
+ is on your side, such as an OCR service that is down.
889
1070
 
890
1071
  ### Rules for a PDF extractor
891
1072
 
@@ -900,7 +1081,8 @@ built-in one does:
900
1081
  `@cantoo/pdf-lib` counts another number, since a page number could then point at the wrong page.
901
1082
  Without `pages`, that check is not made, and the card and the instruction give no page count.
902
1083
  3. **Honour `input.scannedPages`.** The library sets it on every PDF it ingests when PDFs are kept
903
- (`keepOriginals` lists `"pdf"` and the store has `putOriginal`) and `scannedPdfPages` is above 0.
1084
+ (`keepOriginals` lists `"pdf"`, and the store has `putOriginal` or the ingest gives `original`
1085
+ to a library with `originals`) and `scannedPdfPages` is above 0.
904
1086
  It does not say that the file has no text: its value is `scannedPdfPages`, the most pages a PDF
905
1087
  without any text may have. Unset, refuse a PDF in which you found no text. The library does not check
906
1088
  this for you: page lines alone are text, so a scan your extractor lets through is stored even
@@ -963,7 +1145,8 @@ const pdfWithOcr: Extractor = async (bytes, input) => {
963
1145
  // Nothing recognized in a PDF without any text: the built-in rules decide. It is refused, or
964
1146
  // accepted when its pages can be shown.
965
1147
  if (filled === 0 && blank === extracted.pages) return builtIn(bytes, input);
966
- return { text, pages: extracted.pages };
1148
+ // The rest as the built-in extractor returned it: `pages`, and the headings of the outline.
1149
+ return { ...extracted, text };
967
1150
  };
968
1151
 
969
1152
  export const files = createLargeFiles({
@@ -974,10 +1157,10 @@ export const files = createLargeFiles({
974
1157
  ```
975
1158
 
976
1159
  What this keeps: the page lines, so search results still give page numbers; `pages`; the rebuilt
977
- tables and the picture marks of the pages that had text; and the picture line over a scanned page,
978
- since the model can still look at it to check a stamp or a signature. Only PDFs with a page without
979
- text go to the OCR service, and only those pages change. A scan of any length is accepted once OCR
980
- found text in it.
1160
+ tables, the picture marks and the outline from type sizes of the pages that had text; and the
1161
+ picture line over a scanned page, since the model can still look at it to check a stamp or a
1162
+ signature. Only PDFs with a page without text go to the OCR service, and only those pages change. A
1163
+ scan of any length is accepted once OCR found text in it.
981
1164
 
982
1165
  OCR runs inside `files.ingest`, so the upload waits for it, and it counts toward `ingestTimeoutMs`
983
1166
  (2 minutes by default). For long scans, raise `ingestTimeoutMs` (0 sets no limit), run ingest in a