llm-large-files 0.5.0 → 0.8.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 (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
package/CHANGELOG.md CHANGED
@@ -1,480 +1,1733 @@
1
1
  # Changelog
2
2
 
3
- All notable changes to this package are recorded here. The format follows
4
- [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
- [semantic versioning](https://semver.org).
6
-
7
- ## [0.5.0] - 2026-11-13
8
-
9
- One tool loop for every model. What `askGemini` did (plan the documents, offer the tools, run the
10
- calls, end with an answer) is now `askWithFiles` in the core, and a model provider is an adapter.
11
- Three come with the package: Gemini and Vertex AI, any OpenAI-compatible endpoint, and Claude. The
12
- loop also learned to send a failed request again, to count what a question costs, and to keep a
13
- growing request inside the model's window.
14
-
15
- `askGemini` is still there and takes the options it took. Read **Changed** before you upgrade:
16
- six of its points can need a change in your code.
17
-
18
- ### Added
19
-
20
- - **`askWithFiles({ files, model, explorer?, documentIds, messages, … })`** in `llm-large-files`.
21
- `model` and `explorer` are adapters, and need not be of the same provider: a cheap model behind
22
- an OpenAI-compatible endpoint can explore while Gemini or Claude writes the answer.
23
- - **Adapters.** `gemini(endpoint, options)` in `llm-large-files/gemini`,
24
- `openAiCompatible({ baseUrl, apiKey, model })` in `llm-large-files/openai` (OpenAI, Azure OpenAI,
25
- DeepSeek, LiteLLM, vLLM, Ollama, OpenRouter, Gemini's OpenAI layer), and
26
- `anthropic({ apiKey, model })` in `llm-large-files/anthropic`. None needs an SDK. An adapter of
27
- your own is an object with `id`, `capabilities`, `send` and, for whole-file reads,
28
- `generateText`: see `ModelAdapter` in the API reference.
29
- - **A request that failed is sent again.** HTTP 408, 409, 429, any 5xx, and a connection that
30
- failed are retried up to three times, after a wait that doubles (at most 0.5, 1 and 2 seconds,
31
- with jitter), or after the wait the provider asks for (`Retry-After`, `retry-after-ms`, and the
32
- `retryDelay` of Gemini's `RetryInfo`). A request the model refused (400, 401, 403, 404) is not retried, and nothing is
33
- retried once text of the reply was shown, or after the caller stopped the question. A wait the
34
- provider asks for that is longer than `retry.maxDelayMs` (one minute) is not waited for. The
35
- part reads of a whole-file read follow the same rule: a 429 was retried 0.2 ms later before.
36
- Set it with `retry: { retries, baseDelayMs, maxDelayMs }`.
37
- - **`usage` is the whole question.** `{ requests, inputTokens, cachedInputTokens, outputTokens,
38
- thoughtTokens, byModel }`, summed over every request that was answered, the part reads of a
39
- whole-file read included. In a live run of 0.4.0, 13,687 prompt tokens were billed and 6,398
40
- reported.
41
- - **Ceilings for one question**, in `limits`: `wholeDocumentReads` (1 for each document: the
42
- model asked for the same file to be read whole six times in one probe), `inputTokens` and
43
- `requests` (no more tools once they are reached, and a whole-file read that would pass them is
44
- refused with the numbers), next to `toolTurns` and `callsPerTurn`.
45
- - **The request is kept inside the window.** The loop counts the request as it grows. Before it
46
- runs the calls of a turn it gives each one the room that is left: a result is cut to it and says
47
- where to go on, and a call that finds no room is answered "no room left, answer now", after
48
- which the next request is the answer. When the room runs short, the results of all but the last
49
- three tool rounds are replaced by short stand-ins that keep the document and the lines or pages
50
- they showed. A turn of sixty reads built a request of 491,000 tokens against a window of 128,000
51
- before; the same run now peaks at about 100,000.
52
- - **The tool calls of one turn run together**, four at a time, and are answered in the order they
53
- were made. Looks at pages still run one after another, because each is given the room the one
54
- before it left, and so do regex searches, which share their time. Six whole-file reads, two in
55
- each of three turns, took 841 ms one after another against a fake model, and take about 540 ms.
56
- - **Headers are asked for with every request**, the part reads included, so a token that
57
- `vertexAi({ accessToken })` renews is used. They were asked for once a question.
58
- - **The budget follows the model.** `reservedTokens`, `inlineTokens`, `mapChunkTokens` and
59
- `toolResultCharacters` are worked out from `contextTokens` when they are left out
60
- (`resolveBudget`): setting only `contextTokens: 64_000` made a nine-token note a card with tools
61
- before. An adapter can say what its model takes (`contextTokens`, `maxRequestBytes`,
62
- `outputTokens`, `pageTokens`, and `tokenScale` for a tokenizer that counts more than the
63
- library's estimate), and the budget of a question is made to fit it. `budget` in `askWithFiles`,
64
- `prepare` and `tools` changes fields for one question, and `files.budgetFor()` shows the result.
65
- - **`evidence`** in the result: for each tool call, the document and the lines or pages the model
66
- was shown.
67
- - **`toolTurns`** in the result: the tool rounds of the question as plain JSON. Kept with the
68
- conversation and passed back in `messages` between the question and its answer, they let a
69
- follow-up question be answered from what was already read. In a live check the follow-up took
70
- one request and no search. `geminiToolTurns`, `openAiToolTurns` and `anthropicToolTurns` give
71
- them in a provider's own form, and `fromGeminiContents`, `fromOpenAiMessages` and
72
- `fromAnthropicMessages` turn a history kept in that form into `messages`.
73
- - **A tool call that did not arrive whole is not run.** Arguments that are not JSON, or a call cut
74
- off at the output limit, are answered with what was wrong, and the model can send the call again.
75
- - **The output limit of a part read is raised for any model that thinks**, not only Gemini: the
76
- rule of 0.4.1 is shared by the three adapters.
77
- - For Claude: the model's turn goes back exactly as it came, thinking blocks included; the tools
78
- stay listed in the request that must be answered in text (`tool_choice: none`); the conversation
79
- is never rewritten, so old results are not shortened for it; pages go into the tool result as a
80
- document block; prompt caching is on; a refusal is reported as `blockReason`; and `fallbacks`
81
- turns on the API's own fallback to another model.
82
-
83
- ### Changed
84
-
85
- What can need a change in your code:
86
-
87
- - **`result.usage` is no longer Gemini's `usageMetadata` of the last response.** That object is
88
- now `result.lastUsage`. If you forward `usage` to a browser or a log, read `lastUsage` for the
89
- old shape, or use the totals.
90
- - **A failure can take longer to reach you**, because the request is tried again first: up to
91
- three and a half seconds of waiting by default for a model that stays down, and up to a minute
92
- when the provider names a wait. `retry: { retries: 0 }` gives the old behaviour.
93
- - **A connection that failed throws `GeminiRequestError` with `status` 0**, not the `TypeError` of
94
- `fetch`. The original error is its `cause`.
95
- - **A second whole-file read of the same document in one question is refused.** Set
96
- `limits.wholeDocumentReads` (or `maxWholeDocumentReads` in `files.tools()`) to allow more. Make
97
- one tool set for each question: the count is the tool set's.
98
- - **Budget values that cannot work together throw at `createLargeFiles`**: `reservedTokens` or
99
- `mapChunkTokens` at or above `contextTokens`. And with `contextTokens` below 400,000, fields you
100
- left out are now smaller than the fixed defaults they had.
101
- - **`onActivity` and `onStep` can interleave differently.** Calls of one turn start together, so
102
- the "Searching…" lines of several calls can come before the first finished step. Steps still
103
- arrive in call order.
104
-
105
- What needs none, unless you built on it:
106
-
107
- - Old tool results can be replaced by stand-ins (`{ dropped: true, lines, note }`) late in a long
108
- question. `steps` then holds "Older tool results were shortened to make room in the request".
109
- - `ToolSet` has a new member, `resultCharacters(name)`, and `LargeFiles` has `budgetFor()`: a mock
110
- of either needs them to type-check.
111
- - `createGeminiGenerateText` throws `GeminiRequestError` (it threw an `Error` with a `status`),
112
- and takes `headers` as a function too.
113
- - `GeminiFunctionCall` and `GeminiToolAnswer` are now the core's `ToolCall` and `ToolAnswer`, and
114
- `ToolFileLimits` is `ToolCallLimits` (the old name is kept).
115
- - `maxToolTurns` and `maxToolCallsPerTurn` of `askGemini` still work. Their new home is
116
- `limits.toolTurns` and `limits.callsPerTurn`.
117
- - Tool results are those of 0.4.1, compared call by call with 0.3.6 over 40 documents, except
118
- that a repeated whole-file read is refused.
119
-
120
- ### Checked
121
-
122
- - 331 tests, 65 of them new. The requests `askGemini` sends are the ones 0.4.1 sent: its 44 tests
123
- pass unchanged but for one that now turns the retry off.
124
- - Live, on the Gemini API: `askWithFiles` with `gemini()` and with `openAiCompatible()` on Gemini's
125
- OpenAI layer (streamed, a 5.2 MB log), an explorer behind the OpenAI layer with a thinking Gemini
126
- model answering, `askGemini` on a thinking model alone and with an explorer, a follow-up
127
- question from stored tool rounds, and a part read through the OpenAI adapter. In each, the usage
128
- the library returned was what the provider reported, request by request.
129
- - **Not run against a real server:** the Claude adapter (there was no key: it is tested against
130
- the request and response shapes of the Messages API documentation), and `pdfInput` of the OpenAI
131
- adapter, which sends the pages of a PDF as a `file` part. Gemini's OpenAI layer refuses that part
132
- (HTTP 400), so it is off by default and follows OpenAI's documented shape untested.
133
-
134
- ## [0.4.1] - 2026-11-13
135
-
136
- Fixes from a review of 0.4.0. Nothing to change in your code. Tool results are those of 0.4.0
137
- except for the three points under Changed (compared call by call with 0.3.6 over 40 documents).
3
+ What changed in each version of `llm-large-files`, for the developers who use it. Each version
4
+ says what you need to change when you upgrade, what you can add, what works differently, and what
5
+ was fixed. Versions follow [semantic versioning](https://semver.org). While the version is 0.x, a
6
+ minor version (0.5 to 0.6) may need changes in your code or settings, and a patch (0.6.0 to 0.6.1)
7
+ does not. The **Upgrading** part of each version says what to change, and it is there even when
8
+ the answer is "nothing".
9
+
10
+ <!--
11
+ Template of an entry, for maintainers. Put the newest version first.
12
+
13
+ ## X.Y.Z — not released yet
14
+ (At release, the date replaces "not released yet": ## X.Y.Z — YYYY-MM-DD.)
15
+
16
+ Two to four sentences: what this version is about.
17
+
18
+ ### Upgrading: what you need to change
19
+
20
+ Always present. First, whether code written for the previous version compiles as it is (check
21
+ the diff of the public .d.ts files). Then each behavior difference an app may need to act on:
22
+ what changed, who it affects, and what to do. Write "Nothing." when there is none.
23
+
24
+ ### New: what you can add
25
+
26
+ Each addition in one or two lines, with a link to the page that explains it. A short sample for
27
+ the ones most apps will use.
28
+
29
+ ### Changed: what works differently
30
+
31
+ One or two lines each.
138
32
 
139
33
  ### Fixed
140
34
 
141
- - **A whole-file read returned almost nothing on a model that thinks.** Such a model counts its
142
- thoughts in `maxOutputTokens`. Asked for 4,096 tokens of notes on a part of a log, Gemini 3.8
143
- Flash spent 3,931 of them thinking and wrote 317 characters, and Gemini 4 Hydrogen wrote none.
144
- `createGeminiGenerateText` now sends such a request once more with 32,768
145
- (`THINKING_OUTPUT_TOKENS`), and starts there for every later request to that model: one request
146
- is wasted per model and process, not one per part. A model or a gateway that refuses the larger
147
- limit is not asked for it again. An `analysisConfig` of your own still decides what it sets.
148
- Checked live: both models then returned whole notes, and an answer that cited all 70 matching
149
- lines of a log read in three parts.
150
- - **`sweep` deleted a healthy document when one read of its metadata failed.** Every error counted
151
- as "cannot be read", and a file older than an hour was then removed, with its text and its
152
- original. Now only metadata that is not valid is that. A read that failed (a busy volume, too
153
- many open files) leaves the document alone, and a document that cannot be removed no longer
154
- stops the sweep.
155
- - **A store that could not be read looked like a deleted document.** `FileDocumentStore` answered
156
- every failed read with "not there", and `askGemini` then told the user to upload the file
157
- again. A failed read is now a `DocumentStoreError`: retry the call. Its message names no path
158
- and no host, and the error that was caught is its `cause`.
159
- - **Storage errors reached the model, and a user's screen, with the server's path.** A tool call
160
- that met `EACCES: permission denied, open '/data/large-files/doc_….txt'` passed that on in its
161
- result and in `steps`. It now answers `The document store could not be read (EACCES). Try again.`
162
- - **One model turn could hold the server.** A regex that the quick check lets through, such as
163
- `(a|a)+$`, ran for its full 3 seconds on the main thread, and a turn can hold any number of
164
- calls: five such searches in one turn answered no other request for 15 seconds. A file can ask
165
- a model for exactly that. Now:
166
- - a regex scan runs in slices of 250 ms with other work in between, and stops at a line that
167
- takes two whole slices: 0.8 s for such a search, not 3;
168
- - the regex searches of one tool set (one question, in `askGemini`) share 6 seconds
169
- (`regexBudgetMs`). Past that, a regex search answers with an error that tells the model to
170
- search another way;
171
- - `askGemini` runs at most 8 tool calls of one turn (`maxToolCallsPerTurn`). The others are
172
- answered "not run, send it again if you still need it". Sixty reads in one turn built a
173
- request of 339,000 tokens before.
174
- - **`ttlMs: Infinity` made every ingest throw** (`RangeError: Invalid time value`). It now keeps
175
- documents until they are deleted: their `expiresAt` is `NEVER_EXPIRES`.
176
- - **A long line of emoji lost characters when it was wrapped.** The cut at 2,000 could fall
177
- between the two halves of a character outside the basic plane, and each half was stored as a
178
- replacement character.
179
- - **`jsonBytes` and the planner under-counted** text with quotes, backslashes, tabs or many line
180
- breaks: by 23% for a JSON-lines export and 31% for TSV. They now count what JSON adds exactly,
181
- `DocumentMeta.jsonBytes` keeps it for planning, and `read_document` trims its result to the
182
- limit as it is sent: a read of quoted text came out at 42,514 characters against 24,000.
183
- - **`**NOTHING RELEVANT**` counted as a relevant part** of a whole-file read. The reply of a part
184
- that found nothing is recognised whatever Markdown is around it.
185
- - **A merge of notes that failed twice lost the notes of every part.** They now go on unmerged,
186
- and the answer is written from them.
187
- - **`cacheSize` counted the pieces kept of a document that is read by range**, so with a small
188
- value a document pushed itself out of memory on every search. It counts documents again.
189
- - **`delete` could leave a document listed without its text.** The metadata is removed first, and
190
- if that fails nothing else is removed.
191
- - **`\p{L}` matched nothing in a regex search.** Patterns are compiled with the Unicode flag when
192
- they allow it, and without it otherwise.
193
-
194
- ### Changed
195
-
196
- - **A file too large for `analyze_whole_document` is no longer offered it.** Its card says "It is
197
- too large to be analyzed whole", the tool guide and the declared tools leave the tool out when
198
- no file can use it, and `get_document_overview` says so in `whole_document_analysis`. A call of
199
- the tool still answers with the reason.
200
- - **`get_document_overview` works out the number of parts from the metadata**, not by reading
201
- the whole file: that took 60 MB of reads and 0.7 s for a 60 MB log. The number is the count, or
202
- within a few percent of it.
203
- - In a regex, `.` and a quantifier take a character outside the basic plane (an emoji) as one
204
- character.
205
-
206
- ### Added
207
-
208
- - `DocumentStoreError`, `NEVER_EXPIRES`, `REGEX_BUDGET_MS` and `THINKING_OUTPUT_TOKENS`.
209
- - Options `maxToolCallsPerTurn` (`askGemini`) and `regexBudgetMs` (`tools`).
210
- - `DocumentMeta.jsonBytes`. Documents ingested before keep the planner's 8% rule.
211
-
212
- ## [0.4.0] - 2026-11-12
213
-
214
- Nothing to change in your code: the API, the tools and their results are those of 0.3.6 (compared
215
- call by call). Servers of 0.3.x and 0.4.0 can share a `FileDocumentStore` during a rolling update;
216
- 0.3.x servers ignore the new index files. The delete fix below holds once every server runs 0.4.0.
35
+ Grouped by area. One or two lines each, written for an app developer, with the numbers that
36
+ matter.
37
+ -->
38
+
39
+ ## 0.8.0 — 2026-11-23
40
+
41
+ Files from an enterprise, read with their structure, and counted exactly. Word files keep their
42
+ headings, clause numbers and tables; PowerPoint decks their order, tables and speaker notes; Excel
43
+ workbooks and HTML pages are read for the first time. Search works in every script (Hebrew with
44
+ its prefix letters, Hindi, Thai, Chinese, text composed or decomposed), can search part of a file,
45
+ show the last matches, and count matching lines per hour, per code or per message shape in one
46
+ call. Untrusted PDF and Office files can be read in child processes with a memory limit and a kill
47
+ timer, and every refusal says why with a code. 0.7.1 was never published: its fifteen fixes ship
48
+ here, and its points are part of this entry. Checked live with the Gemini API on
49
+ `gemini-3.5-flash-lite` and `gemini-3.8-flash`: hourly counts and the last line of a log in one
50
+ search, a clause of a Hebrew lease answered in Hebrew, a row of a workbook, a table of an HTML page.
51
+
52
+ ### Upgrading: what you need to change
53
+
54
+ Code written for 0.7.0 compiles with 0.8.0, with one exception: `DocumentFormat` has two new
55
+ members, `"xlsx"` and `"html"`. An exhaustive `switch` on a document's format, or a
56
+ `Record<DocumentFormat, …>` of your own, needs the two cases. Every other change to the public
57
+ types is an addition: `IngestError`, `ingestErrorCodeOf` and the type `IngestErrorCode` in
58
+ `llm-large-files`; `createIsolatedExtractors` and the types `IsolatedExtractorOptions` and
59
+ `IsolatedExtractors` in `llm-large-files/node`; an optional `code` in `EventError`.
60
+
61
+ Some behavior is different. Check each point against your app:
62
+
63
+ - **Excel and HTML files are read.** An `.xlsx` (and `.xlsm`) upload was refused with "This file is
64
+ a ZIP archive"; it is now a document of format `"xlsx"`. An `.html` or `.htm` file was read as
65
+ text, tags and all, with format `"text"`; it is now format `"html"`, with the text a browser
66
+ shows. Both need nothing new: XLSX uses the optional `jszip`, as DOCX does.
67
+ **What to do:** if your app lists the formats it accepts, add them. See
68
+ [formats](docs/reference/library.md#documentformat).
69
+ - **Word and PowerPoint files are read with their structure.** A DOCX heading is written as a
70
+ Markdown heading, a numbered paragraph with its number (`## 2.1 Rent`, `(a) the flat`), a table
71
+ as rows of `| cell | cell | |` with its empty cells, and the footnotes, endnotes, comments,
72
+ headers and footers each under a heading of its own (a repeated header once). A PPTX is numbered
73
+ in the order of its slide show, with its tables and its speaker notes. Documents ingested by
74
+ 0.7.0 keep the text they have until they are uploaded again.
75
+ **What to do:** nothing, unless your tests compare the text of a DOCX or PPTX: update them.
76
+ - **`ingest` throws `IngestError` for a file it cannot read.** It is an `Error` with the same
77
+ message as before, a `code` (`"too_large"`, `"no_text"`, `"hostile"`…), the HTTP `status` the
78
+ upload handler answers with, and the extractor's error as `cause`. A store that failed, a caller
79
+ that gave up, a listener that threw and a system error from an extractor of your own are thrown
80
+ as before. `ingest.error` events carry the `code`, and name `"IngestError"` where they named
81
+ `"Error"`.
82
+ **What to do:** nothing; to tell users in your own words (another language), map `error.code`.
83
+ A test that expects `name: "Error"` in an `ingest.error` event needs `"IngestError"`.
84
+ - **The answer is asked for in the language of the question.** The three closing requests
85
+ (`FINAL_ANSWER_REQUEST`, `FINAL_ANSWER_AFTER_PAGES`, `FINAL_ANSWER_WITHOUT_TOOLS`) end with
86
+ "Answer in the language of my question." A model asked in Hebrew answered in English after an
87
+ English closing request.
88
+ **What to do:** nothing; to have answers in one language whatever the question, say so in
89
+ `system`.
90
+ - **The text the model is sent changed:** the description of `search_document` (its new
91
+ arguments), the tool guide (two lines: counts by group and paging; searching the bare form of a
92
+ word), and the closing requests. The provider's prompt cache misses once after the upgrade.
93
+ **What to do:** nothing. See **Changed** for what models now do.
94
+ - **Text is composed (NFC) at ingest.** "e" followed by a combining accent becomes "é". Line counts
95
+ do not change; `characters` and the sizes of such a text can be a little smaller. A run of more
96
+ than 30 marks on one letter, which no script writes, gets an invisible combining grapheme joiner
97
+ (U+034F) after each 30, as Unicode's stream-safe form does: composing such a run took time by its
98
+ square, and 600 KB of them held the server 80 seconds.
99
+ **What to do:** nothing.
100
+ - **More files are taken for logs.** A `.txt` of nginx or Apache access lines, JSON log lines,
101
+ klog or logfmt is now format `"log"`, with a log profile; levels in lower case, in brackets,
102
+ after `level=`, in a JSON field or as pino numbers are counted.
103
+ **What to do:** nothing, unless your app switches on `format === "text"` for such files.
104
+ - **From 0.7.1** (never published), some values that were taken in silence and did not work are
105
+ refused:
106
+
107
+ - **NaN in a number option of `createLargeFiles` throws.** `ttlMs`, `maxUploadBytes`,
108
+ `scannedPdfPages`, `cacheBytes`, `cacheSize`, `wholeDocumentBytes`, `scanChunkBytes` and
109
+ `maxConcurrentScans` throw a `RangeError` for NaN (what `Number(process.env.X)` gives for a
110
+ variable that is not set), and a `TypeError` for a value that is not a number, such as a string
111
+ read from the environment. `scanChunkBytes: Infinity` throws too. With NaN, `maxConcurrentScans`
112
+ made every search of a document read by range wait forever, `ttlMs` failed every upload with
113
+ "Invalid time value", and `maxUploadBytes` took off the upload limit.
114
+ **What to do:** nothing, unless you pass such values. Leave an option out for its default, or
115
+ read a variable with a fallback: `Number(process.env.SCANS ?? 4)`.
116
+ - **NaN in `AskOptions.limits` throws, before any request.** A field of `limits` that is NaN throws
117
+ a `RangeError` ("limits.toolTurns must be a number, and is NaN. Leave it out for the default."),
118
+ and one that is not a number a `TypeError`. NaN used to give a question with no tool, refuse
119
+ every call, or take off the cap on whole-file reads and the ceilings on tokens and requests.
120
+ `ToolOptions.maxWholeDocumentReads` is checked the same way. `Infinity` still means no ceiling.
121
+ **What to do:** as above.
122
+ - **`partialResultOf(error)` gives `undefined` for an error that several questions threw.** Questions
123
+ stopped by one shared signal all throw its one reason (`AbortSignal.any` passes it on as it is).
124
+ `partialResultOf` gave each the result of whichever failed last: another user's tool rounds and
125
+ usage. Now it gives none, and each question's `run.error` event still carries its own `partial`.
126
+ **What to do:** if you stop many questions with one signal and keep their partial results, give
127
+ each question an `AbortController` of its own that the shared signal aborts with a new reason.
128
+ See [`partialResultOf`](docs/reference/ask.md#partialresultoferror).
129
+ - **`vertexAi()` and `vertexHost()` check `location`.** One that is not lowercase letters and digits
130
+ joined by single hyphens (`"global"`, `"us"`, `"europe-west4"`) throws a `TypeError`. With `/`,
131
+ `?`, `#` or `@`, it named another host, which got the access token.
132
+ **What to do:** nothing, unless a location comes from a user; then expect the `TypeError`.
133
+ - **An upload answered before its body was read drains the rest, up to 8 MB.** The `413` of an
134
+ upload over `maxUploadBytes` (and every answer sent before the body was read to its end) is
135
+ written at once, and ends once the rest of the body has been read and dropped. A body that goes
136
+ on more than 8 MB past the limit is cut off by closing the connection.
137
+ **What to do:** nothing. See [`node`](docs/reference/node.md).
138
+ - **An adapter of your own whose `capabilities` lack `pageTokens` or `toolFiles`.** A `pageTokens`
139
+ that is missing, NaN or negative counts as 1,000, and a `toolFiles` that is none of `"inside"`,
140
+ `"beside"` and `"none"` counts as `"none"`, so `view_pages` is not offered to that model. Both
141
+ fields are required by the type, so this concerns only an adapter written in JavaScript or cast.
142
+ **What to do:** declare both.
143
+
144
+ ### New: what you can add
145
+
146
+ - **`createIsolatedExtractors(options?)`** in `llm-large-files/node`: PDF, DOCX, PPTX and XLSX files
147
+ read in child processes, each with a heap flag (`maxHeapMb`, 512), a kill timer (120 s), at most
148
+ `concurrency` (2) at once and `maxQueue` (8) waiting. A file that exhausts its child's memory is
149
+ refused (`"out_of_memory"`) and the server goes on; a full queue refuses at once (`"busy"`), and
150
+ the upload handler answers that with 503 and `Retry-After`. Children are replaced after 50 files
151
+ and stopped when idle. A reader that cannot start (a missing `childScript`, an `execArgv` Node
152
+ does not know) is the server's trouble: an `Error` with `status` 500, not an `IngestError`; one
153
+ that cannot be started for want of process slots is `"busy"`. For a server that bundles its code,
154
+ `llm-large-files/node/ingest-child.js` is exported, and `childScript` takes a path or a file
155
+ URL. See [isolated ingest](docs/reference/node.md#createisolatedextractorsoptions).
156
+
157
+ ```ts
158
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
159
+ import { createIsolatedExtractors } from "llm-large-files/node";
160
+
161
+ const isolated = createIsolatedExtractors({ maxHeapMb: 512, concurrency: 2 });
162
+ const files = createLargeFiles({ store: new FileDocumentStore("./data"), extractors: isolated.extractors });
163
+ // A SIGTERM listener replaces Node's own exit: stop your HTTP server there too, or it goes on serving.
164
+ process.once("SIGTERM", () => {
165
+ server.close();
166
+ void isolated.close();
167
+ });
168
+ ```
169
+
170
+ - **`IngestError`**, with `code`, `status` and, for `"busy"`, `retryAfterMs`; and
171
+ `ingestErrorCodeOf(message)`. The codes: `empty`, `too_large`, `too_much_text`,
172
+ `too_many_pages`, `not_text`, `compressed`, `legacy_office`, `encrypted`, `no_text`, `hostile`,
173
+ `timeout`, `out_of_memory`, `busy`, `missing_dependency`, `unreadable`. See
174
+ [`IngestError`](docs/reference/library.md#ingesterror).
175
+
176
+ ```ts
177
+ import { IngestError, type IngestErrorCode } from "llm-large-files";
178
+
179
+ // Your own words for some refusals; the library's message for the rest.
180
+ const hebrew: Partial<Record<IngestErrorCode, string>> = {
181
+ too_large: "הקובץ גדול מדי.",
182
+ no_text: "אין בקובץ טקסט לקריאה (ייתכן שהוא סרוק).",
183
+ busy: "השרת עסוק. נסו שוב בעוד רגע.",
184
+ };
185
+
186
+ try {
187
+ await files.ingest({ name, bytes, owner });
188
+ } catch (error) {
189
+ if (!(error instanceof IngestError)) throw error; // the store, or your own code
190
+ console.log(error.status, hebrew[error.code] ?? error.message);
191
+ }
192
+ ```
193
+
194
+ - **`search_document` arguments** (see [`search_document`](docs/reference/tools.md#search_document)):
195
+ - `from_line` and `to_line`: search part of a file, in every mode; the result says
196
+ `searched_lines`.
197
+ - `next_from_line` in a result of exact or regex search that shows the first matches of more:
198
+ search again from it for the ones after.
199
+ - `order: "last"`: the last `max_results` matching lines, in file order.
200
+ - `group_by`: count the matching lines by group and show none: `"capture"` (the regex's first
201
+ group), `"minute"`, `"hour"`, `"day"` (the timestamp of the line: ISO, nginx, Apache, syslog,
202
+ klog, epoch times of JSON logs) or `"shape"` (the line with its numbers and IDs taken out). The
203
+ result has `groups` of `{ key, count, first_line, last_line }`, `total_groups`, and the lines
204
+ of further groups or with no key apart. Up to 200 groups are shown (`max_results`, default 50).
205
+ - `whole_word`: exact text only as a whole word, letters of every script counted.
206
+ - **`EventError.code`**: the `IngestError` code in `ingest.error` events and in the
207
+ `ingest.error` of an upload with `Accept: text/event-stream`.
208
+
209
+ ### Changed: what works differently
210
+
211
+ Search:
212
+
213
+ - **Every script.** Keyword terms keep a mark with its letter (Hindi, Bengali, Tamil, Thai and
214
+ pointed Hebrew lost their words), split Chinese, Japanese and Thai into words, and drop the
215
+ points of a Hebrew query word, which then finds the word with or without points in the text
216
+ (בראשית finds בְּרֵאשִׁית). A Hebrew word with prefix letters (בחוזה, והחוזה) also searches its
217
+ stem (חוזה), and one that ends in a final letter its plain form too (כסף finds כספים); an acronym
218
+ keeps its gershayim or geresh (ש״ח, עו״ד are one term each).
219
+ - **One way to write a character.** Queries are composed as the text is; a search that ignores
220
+ case also folds Greek final sigma, curly quotes and primes, dashes and the minus sign, no-break
221
+ and thin spaces, Hebrew geresh, gershayim and maqaf, and full-width forms: "don't" finds
222
+ "don’t", צה"ל finds צה״ל.
223
+ - **Regex `\w`, `\W`, `\b` and `\B` know the letters of every script**: `\bחוזה\b` matched
224
+ nothing, and `\w+` stopped at "é". Emoji variation selectors and enclosing marks are not word
225
+ characters, for them and for `whole_word`. A repeated group whose repeats a literal character separates,
226
+ as in `(\d{1,3}\.){3}\d{1,3}` or `(\w+\.)+com`, is no longer refused as a nested quantifier.
227
+ - **Exact search counts every line where a text across lines starts** ("a\na" in "a\na\na" was
228
+ counted once), and skips the rest of a line once it is counted: a short common text costs what
229
+ its lines do, not its occurrences. It runs in slices with pauses, as a regex search does, and
230
+ its count stays whole; with `whole_word` or `group_by`, whose work grows with each occurrence,
231
+ it stops after 3 seconds (the result then says the counts are lower bounds). A document held in
232
+ memory is scanned in pieces too.
233
+ - **`case_sensitive` and `whole_word` given as text or as 1** ("true", "1", 1) are read as true; in
234
+ 0.7.0, `case_sensitive: "true"` searched ignoring case. A search of this kind stored by 0.7.0 is
235
+ run again, not answered from what was stored.
236
+ - **A cut list of matches says how to see the rest**: "search again with from_line 1941, or count
237
+ them with group_by", where it said "narrow the search".
238
+ - **Models count by group.** Live, asked for PAY-5031 errors per hour and the last one, both models
239
+ made one search with `group_by: "hour"` and gave every hourly count and the last line right.
240
+
241
+ Documents:
242
+
243
+ - **Word:** headings from paragraph styles (also in documents written in Hebrew, whose styles keep
244
+ English names), list numbers in Word's formats (decimal, letters, roman numerals, Hebrew letters
245
+ and numerals, bullets as "-", restarted lists), tables with empty and merged cells kept in their
246
+ columns (text another program left in a continued merged cell is kept), lists defined through a
247
+ list style, legal numbering (`w:isLgl`: "Section 1.01"), non-breaking hyphens ("555-0199" read
248
+ "5550199") and symbol characters.
249
+ - **PowerPoint:** slides in the order of `presentation.xml`, numbered by position ("Slide 5" for the
250
+ third slide is gone); tables; speaker notes after `[Speaker notes]`, the notes' own text only (not
251
+ the slide number, date and footer of the notes page).
252
+ - **Excel:** each sheet a section, `## Sheet 1: Sales`, then `Columns: | A | B | C |` and a line a
253
+ row, `Row 12: | East | 2026-03-01 | 1200.5 |`, with shared and inline strings, the values Excel
254
+ last computed for formulas, dates and times from number formats (1900 and 1904 systems),
255
+ percentages, durations of a day or more (`[h]:mm`: 36:00), Excel's `_x000D_` escapes, and hidden
256
+ sheets marked. Every row of every sheet is read, within the text limit.
257
+ - **HTML:** scripts and styles dropped, headings, lists, tables (`colspan` and `rowspan` keep the
258
+ cells in their columns), `text (https://…)` for links, alt text for images, entities decoded
259
+ ("AT&T" is found), text a page hides (`hidden`, an inline `display: none`) marked as Word's hidden
260
+ text is, older encodings read as text files are.
261
+ - **Logs:** the profile reads more timestamps (nginx's error log, access logs, syslog) and levels
262
+ (see **Upgrading**).
263
+ - **Outlines** take no heading from a fenced code block, nor from the `#` comments of a text file
264
+ that reads as code (a script, a configuration file).
265
+ - **Refusals in words for the person:** an Office file of before 2007, an Outlook message or an
266
+ Office file with a password ("This is a Word, Excel or PowerPoint file of before 2007…"), where
267
+ it said "looks binary"; and a PDF with a password, where pdf.js said "No password given".
217
268
 
218
269
  ### Fixed
219
270
 
220
- - **A document deleted on one server is no longer served by another.** Servers sharing a store
221
- kept a document in memory and answered from it until it expired, up to 72 hours after a delete.
222
- Every use of a kept document now asks the store first (`getMeta`, about a millisecond).
223
-
224
- ### Changed
225
-
226
- - **The memory cache is bounded in bytes** (`cacheBytes`, default 256 MB), not in documents. Six
227
- documents of 50 MB took over 600 MB before. `cacheSize` still caps the number when given. Calls
228
- that arrive together for a document that is not in memory open it once.
229
- - **Large documents are read by range on a store that can** (`FileDocumentStore`, or your own with
230
- `readTextRange`): a tool call reads the lines it needs, and a search reads the text 1 MB at a time,
231
- so memory no longer grows with file size and the number of users. Documents up to
232
- `wholeDocumentBytes` (2 MB) are loaded whole as before. Results are the same.
233
- - `FileDocumentStore` writes every file whole (to a temporary name, then renamed), and `sweep` no
234
- longer deletes a document whose metadata cannot be read unless that file is an hour old: on a
235
- shared volume it may be an upload in progress.
236
-
237
- ### Added
238
-
239
- - A line index per document (`<id>.idx` in `FileDocumentStore`, a few bytes a line), written at
240
- ingest. Documents from older versions get one the first time they are used.
241
- - `DocumentStore.readTextRange`, `putIndex` and `getIndex`: optional, for stores of your own.
242
- - `sweep` removes files that belong to no document, and temporary files, once they are an hour old
243
- (`orphanAgeMs`).
244
- - Options `wholeDocumentBytes`, `scanChunkBytes` and `maxConcurrentScans` (at most 4 searches of
245
- large documents at once per process; the others wait, and those of the same document share one
246
- pass over it). Decoded pieces of documents in use are kept within `cacheBytes`.
247
- - `get_document_overview` works out the number of parts of a file once per document, not on every call.
248
-
249
- ## [0.3.6] - 2026-11-11
271
+ Search and documents:
272
+
273
+ - **Keyword queries in scripts with marks found nothing** (LLF-014): see **Changed**.
274
+ - **A common query word no longer skews keyword ranking toward the start of a file** (LLF-015). A
275
+ term counted only up to 200,000 hits gave passages before the cap a score passages after it
276
+ could not get; such a term is now not scored.
277
+ - **Overlapping texts across lines are all counted** (LLF-042), and repeated occurrences on a
278
+ counted line cost nothing (LLF-044, exact search).
279
+ - **Common safe regexes are accepted** (LLF-043): IPv4 addresses, domains, dashed numbers.
280
+ - **Case-insensitive search finds what case-sensitive search finds** (LLF-045): an upper-case
281
+ word that ends in Σ, and composed against decomposed text.
282
+ - **`#` comments in code blocks and scripts are no longer headings** (LLF-016).
283
+ - **Logs with lower-case levels get a profile** (LLF-017).
284
+ - **Slides are numbered in the order of the show** (LLF-023), **non-breaking hyphens and symbols of
285
+ Word are kept** (LLF-024).
286
+ - **Page text can no longer forge a page line** (LLF-025): a line of a PDF page that reads
287
+ "--- Page 3 ---", or one of the extractor's notes, is moved by a space, so search, page numbers
288
+ and `view_pages` are not sent to the wrong page.
289
+ - **A saved line index whose text size is not the document's is not used** (LLF-047): the last line
290
+ read cut short, without an error.
291
+ - **An optional dependency that fails to load is not reported as missing** (LLF-054): the message
292
+ says it is installed but could not be loaded, with the reason, and keeps the failure as `cause`.
293
+ - **A long run of spaces is counted in the token estimate** (LLF-046): about a token for each 16
294
+ spaces after the first. 10,000 spaces were estimated at 0 tokens, so a padded or fixed-width
295
+ report could be planned inline and refused by the provider. Indentation is priced as before.
296
+ - Unused code in `search.ts` is gone (LLF-060).
297
+
298
+ From 0.7.1:
299
+
300
+ Models:
301
+
302
+ - **A Claude stream no longer loses its input counts** (LLF-006). The input fields of the usage in
303
+ `message_delta` may be null, and replaced the numbers of `message_start`: `inputTokens` and
304
+ `cachedInputTokens` read 0, which also took `limits.inputTokens` and the room estimate off. Only
305
+ the numbers of `message_delta` are taken now.
306
+ - **An OpenAI-compatible reply of 200 that holds an error throws it** (LLF-009). A body
307
+ `{ "error": { "code": 502, … } }` with no `choices` (OpenRouter, once generation has started)
308
+ was a reply with no text, and the question could end with no answer and no error. It is now an
309
+ `OpenAiRequestError` with the status the error names, sent again like any 502, in a chat request
310
+ and in a part read, as the same error in a stream already was.
311
+ - **Gemini gets no empty text parts** (LLF-028). A stored answer that came back empty became
312
+ `{ "text": "" }`, which Vertex AI refuses with HTTP 400, so every later question of that
313
+ conversation failed. Empty text parts are left out, and a turn left with none.
314
+ - **A whole-file part that Gemini blocks says why, and is not sent again** (LLF-030). A prompt
315
+ blocked with `promptFeedback.blockReason` failed with "The model returned no text." and was sent
316
+ once more; now "The model returned no text (PROHIBITED_CONTENT).", once.
317
+ - **An adapter class whose `generateText` is a method can read whole files** (LLF-051). It was
318
+ called without its adapter, so a method that used `this` failed on every part.
319
+
320
+ The loop:
321
+
322
+ - **What a refusal showed lasts for the rest of the question** (LLF-040). After a request refused
323
+ as too large, the loop raises its estimate up to 8 times what it counted; the next good reply
324
+ brought it back to twice, the next turns filled the window again, and a question whose provider
325
+ counts more than twice the estimate could fail after two such refusals. The estimate no longer
326
+ falls below what the refusal showed, as [how it works](docs/how-it-works.md#a-request-too-large-for-the-model)
327
+ says.
328
+ - **`limits` and the number options of `createLargeFiles` are checked** (LLF-007, LLF-008), and a
329
+ queue of scans always has at least one slot, whatever it is given: see **Upgrading**.
330
+ - **A missing `pageTokens` no longer takes away the page limit and the room count** (LLF-041).
331
+ - **Questions stopped by one signal no longer get each other's partial result** (LLF-010).
332
+ - **`UsageMeter` keeps any adapter id as an entry of its own** (LLF-050). An id of `"__proto__"`
333
+ counted the usage into `Object.prototype`, which set `requests` and the token counts of every
334
+ object in the process to NaN; `"constructor"` and `"toString"` lost their usage.
335
+
336
+ Documents and uploads:
337
+
338
+ - **A document read by range whose line starts with U+FEFF can be searched** (LLF-013). Each range
339
+ was decoded as a stream of its own, which dropped a U+FEFF at its start: when such a line began a
340
+ piece, every search of the document failed ("did not match its index") and rebuilt the index in
341
+ vain. Ingest has dropped such characters since 0.6.0, so this concerned documents stored by
342
+ 0.5.0. The store example in the [storage guide](docs/guides/storage.md) decodes the same way.
343
+ - **An upload over the limit no longer holds its connection** (LLF-033). The handler stopped
344
+ reading at the limit and answered `413`, but the connection stayed open, with a client still
345
+ sending into it. The comment said the rest was drained, and now it is, up to 8 MB: the client
346
+ reads the `413` and can send its next request on the same connection. Past 8 MB the connection
347
+ is closed. Closing it at once was tried, and lost the answer on Windows, which resets a
348
+ connection closed while data still arrives.
349
+ - **`vertexAi()` checks its location** (LLF-029): see **Upgrading**.
350
+ - **The JSDoc of `ToolCallLimits.maxFileBytes`** gives its default as 3/8 of
351
+ (`maxRequestBytes` − 262,144), 3,651,696 bytes for the default budget, which the code uses
352
+ (LLF-062). It read as 3/8 of `maxRequestBytes`, less 262,144.
353
+
354
+ Tests: vitest 4.1.12 in place of 3.2.7, whose advisories are fixed (LLF-019); `npm audit` is
355
+ clean. The tests run only from `test/`.
356
+
357
+ ## 0.7.0 — 2026-11-22
358
+
359
+ A question and an ingest now say what they do as typed events, in order: the plan, each model
360
+ request with its retries and usage, each tool call with how it ended, the answer's text, and the
361
+ result or the error at the end. `askStream` gives a question's events as an async iterable,
362
+ `writeSseEvents` sends them to a browser as Server-Sent Events, and an upload can answer with its
363
+ progress. The callbacks of 0.6.0 (`onText`, `onActivity`, `onStep`) get the same strings at the
364
+ same moments, and events carry no tool results, which hold document text, unless you ask
365
+ for them. A live check with the
366
+ Gemini API passed: the events of a search, of a question with an explorer and of a whole-file read
367
+ were counted and paired, and a question was sent end to end over SSE. See
368
+ [Events](docs/reference/events.md).
369
+
370
+ ### Upgrading: what you need to change
371
+
372
+ Code written for 0.6.0 compiles with 0.7.0 as it is. Every change to the public types is an
373
+ addition: new optional options and fields, an optional fourth parameter of
374
+ `ToolSet.executeWithFiles`, and new exports. `llm-large-files` adds `askStream`, `eventStream`,
375
+ `newRunId` and the types `AskEvent`, `IngestEvent`, `LibraryEvent`, `EventBase`, `EventError`,
376
+ `EventResult`, `EventStream`, `DocumentRef`, `IngestStage`, `NoticeCode`, `NoticeDisplay`,
377
+ `RequestRole`, `RequestPurpose`, `ToolOutcome`, `ExtractProgress`, `ToolCallHooks`,
378
+ `ToolRequestHandle`, `ToolRequestStart` and `ToolRequestEnd`; `llm-large-files/node` adds
379
+ `writeSseEvents`, `sseMessageOf` and the types `SseMessage` and `SseWriteOptions`;
380
+ `llm-large-files/gemini` adds the type `AskEvent`.
381
+
382
+ Some behavior is different. Check each point against your app:
383
+
384
+ - **Each entry of `AskResult.evidence` now has `callId`.** `askWithFiles` and `askGemini` set it
385
+ to the id of the tool call it came from (`"call_1"`, `"call_2"`…), the id its events use. Code
386
+ or a test that compares `result.evidence` with objects that have no `callId`, by deep equality
387
+ (`toEqual`, `assert.deepStrictEqual`), now fails.
388
+ **What to do:** add `callId` to the objects you compare with, or compare with `toMatchObject`.
389
+ `evidenceOf()` in a loop of your own does not set it.
390
+ - **A throw from `onActivity` during a whole-file read now ends the question.** In 0.6.0, a throw
391
+ of `onActivity` on the progress of `analyze_whole_document` ("Reading app.log: part 3 of 12…")
392
+ became the tool's error: the model was sent your error's message, and the question went on. Now
393
+ the read and the other calls of its turn stop, and `askWithFiles` throws that error. A throw of
394
+ `onEvent` there does the same.
395
+ **What to do:** nothing, unless your `onActivity` can throw, such as one that writes to a
396
+ connection that may have closed. Catch its errors inside it.
397
+ - **`ToolSet.executeWithFiles` takes an optional fourth argument, `hooks`** (`ToolCallHooks`). It
398
+ matters only for a `ToolSet` of your own, such as a wrapper around `files.tools()` in a
399
+ `LargeFiles` of your own. A wrapper that drops the argument still works, but `askWithFiles`
400
+ then gets no `tool.progress` events and no events for the requests of a whole-file read.
401
+ **What to do:** in such a wrapper, pass `hooks` on.
402
+ - **`ExtractInput` has an optional `onProgress`.** An extractor of your own works as before, and
403
+ its file reports no `extract` progress. An extractor that wraps a built-in one with an
404
+ `ExtractInput` of its own should pass `onProgress` on.
405
+ **What to do:** nothing; call it to report progress (see **New**).
406
+
407
+ ### New: what you can add
408
+
409
+ The samples assume what your app already has: `files` from `createLargeFiles()`, `model` from an
410
+ adapter, and the `documentIds` and `question` of the chat.
411
+
412
+ - **The events of a question: `AskOptions.onEvent`.** Every event of the question, in order:
413
+ `run.start`, `plan`, `request.start`, `retry`, `text`, `request.end`, `tool.start`,
414
+ `tool.progress`, `tool.end`, `notice`, and last `run.finish` or `run.error`. Each has `seq`
415
+ (1, 2, 3… without gaps), `runId` and `time`. Requests and tool calls come in pairs with ids
416
+ (`req_1`, `call_1`), and tool ends come in call order. Notices say what the callbacks said, and
417
+ three things they never did (`budget_reached`, `no_room`, `blocked`). Errors in events are told
418
+ in words for users: a model error by its kind and status, never in the provider's words, which
419
+ stay on the error that is thrown. See [`AskEvent`](docs/reference/events.md#askevent) and
420
+ [The order of the events](docs/reference/events.md#the-order-of-the-events).
421
+ - **`askStream(options)`**: `askWithFiles` as an async iterable of its events, with `result` and
422
+ `abort()`. Leaving the loop early stops the question; the loop never throws (read `run.error`,
423
+ or await `result`). The answer is asked for as it is written unless `streamText: false`. See
424
+ [`askStream`](docs/reference/events.md#askstreamoptions).
425
+
426
+ ```ts
427
+ import { askStream } from "llm-large-files";
428
+
429
+ const stream = askStream({ files, model, documentIds, messages: [{ role: "user", text: question }] });
430
+ for await (const event of stream) {
431
+ if (event.type === "tool.start") console.log(`${event.label}…`);
432
+ if (event.type === "text") process.stdout.write(event.delta);
433
+ if (event.type === "run.error") console.log(`Failed: ${event.error.message}`);
434
+ }
435
+ const result = await stream.result.catch(() => undefined); // keep result.toolTurns with the chat
436
+ ```
437
+
438
+ - **`eventStream(run, options?)`**: the same for any function that takes an `onEvent` and a
439
+ `signal`, such as `askGemini` or `files.ingest`. See
440
+ [`eventStream`](docs/reference/events.md#eventstreamrun-options).
441
+ - **`AskOptions.runId`**: the `runId` of the events, to tie them to a request of your app.
442
+ Defaults to `"run_"` and 16 hex digits; `newRunId(prefix?)` makes one.
443
+ - **`AskOptions.eventResults`**: put each tool result in its `tool.end` event, and `toolTurns` and
444
+ the full plan (each document's `DocumentMeta`) in the result of `run.finish` and `run.error`.
445
+ Off by default, since they hold document text: without it, that plan names the documents only. See
446
+ [Documents](docs/reference/events.md#documents-eventresults-and-eventresult).
447
+ - **`AskOptions.streamText`**: whether the model is asked for the answer as it is written. It
448
+ defaults to `true` with `onText` and in `askStream`, and to `false` otherwise, as 0.6.0 did:
449
+ `onEvent` alone never changes how the model is asked. See
450
+ [`streamText`](docs/reference/events.md#streamtext).
451
+ - **The events of an ingest: `IngestInput.onEvent` and `IngestInput.runId`.** `ingest.start`,
452
+ `ingest.progress` for each stage (`check`, `extract`, `pictures`, `decode`, `prepare`, `index`,
453
+ `store`, in pages, parts, bytes or characters, at most one every 12 ms for a stage, and the last
454
+ one), then `ingest.finish` with the `DocumentSummary`, or `ingest.error`. See
455
+ [`IngestEvent`](docs/reference/events.md#ingestevent).
456
+ - **`ExtractInput.onProgress`**, for an extractor of your own to report its progress, as the
457
+ built-in ones do for each page of a PDF and each part of a DOCX or PPTX. See
458
+ [`ExtractInput.onProgress`](docs/reference/events.md#extractinputonprogress-for-an-extractor-of-your-own).
459
+ - **`ToolCallHooks`**, the optional fourth argument of `ToolSet.executeWithFiles`: the progress
460
+ and the model requests of one call, for a loop of your own in which two whole-file reads run at
461
+ once. See [`ToolCallHooks`](docs/reference/events.md#toolcallhooks).
462
+ - **`writeSseEvents(response, events, options?)` and `sseMessageOf(event)`**, in
463
+ `llm-large-files/node`: events to a browser as Server-Sent Events, one message per event
464
+ (`id` is `seq`, `event` is `type`, `data` the event itself), with the event-stream headers,
465
+ keep-alive comments and back-pressure. It stops an `askStream` passed to it when the client goes
466
+ away. `sseMessageOf`, its default, sends the result of `run.finish` without `toolTurns`, `plan`,
467
+ `budget` and `lastUsage`. See
468
+ [`writeSseEvents`](docs/reference/events.md#writesseeventsresponse-events-options).
469
+
470
+ ```ts
471
+ import { askStream } from "llm-large-files";
472
+ import { writeSseEvents } from "llm-large-files/node";
473
+
474
+ // In your route, with Node's response.
475
+ const stream = askStream({ files, model, documentIds, messages: [{ role: "user", text: question }] });
476
+ await writeSseEvents(response, stream);
477
+ ```
478
+
479
+ - **Uploads with progress.** `createDocumentHandlers().upload` answers a request with
480
+ `Accept: text/event-stream` with `200` and the ingest's events, ending with `ingest.finish`
481
+ (its `document` is the summary a `201` holds) or `ingest.error` (its `error` is the message and
482
+ status a JSON answer would have). A missing name, a refused owner and a file too large still get
483
+ an HTTP error in JSON, and without the header nothing changes. See
484
+ [Uploads with progress](docs/reference/events.md#uploads-with-progress).
485
+ - **`askGemini` takes `onEvent`, `runId`, `eventResults` and `streamText`**, and passes them to
486
+ `askWithFiles`. See [`askGemini`](docs/reference/events.md#askgemini).
487
+
488
+ ### Changed: what works differently
489
+
490
+ Besides the points under **Upgrading**:
491
+
492
+ - **`Evidence.callId`**: each entry of `AskResult.evidence`, and of `partialResultOf(error)`,
493
+ names its tool call, as `tool.end` does.
494
+ - **A turn that fails stops its other tool calls.** When a turn ends with an error (the question
495
+ was stopped, or a callback threw), the calls of that turn still waiting for their turn do not
496
+ run, and those running are told to stop. In 0.6.0, after a callback threw, they went on
497
+ running after the question had thrown.
498
+ - **`examples/server.ts`** asks with `askStream` and sends the events with `writeSseEvents`. The
499
+ page shows the tool calls with how each ended, a counter for whole-file reads, the status line
500
+ and the answer, and uploads with progress. The tool rounds of each chat stay on the server, so
501
+ the page no longer sends them back, and the question's body has a size limit.
250
502
 
251
503
  ### Fixed
252
504
 
253
- - **A terminal escape without an end no longer deletes the rest of a file.** An `ESC ]` whose end
254
- (BEL, or `ESC \`) was not on its line removed everything up to the next escape, or to the end of
255
- the file: a log of 10,000 lines whose third line held a logged user agent `ua="evil␛]"` was
256
- stored as 3 lines, with no error. Now only those two characters go. The escapes that save and
257
- restore the cursor (`ESC 7`, `ESC 8`) and the like no longer leave a character behind.
258
- - **DOCX and PPTX files are read in one pass, a piece at a time.** The paragraph pattern scanned
259
- to the end of the file from every paragraph that was not closed: a DOCX of 900 bytes held the
260
- server for 8 seconds, and one of 10 KB would have held it for an hour. The new reader looks at
261
- each character once. It also:
262
- - refuses a file that unpacks to more than 100 times its size (past the first 16 MB) or to more
263
- than 128 MB of XML, as it unpacks, before that much is in memory. A DOCX of 160 KB that unpacked
264
- to 50 MB of XML was stored as 29 million characters; it is now refused at 16 MB, in 0.2 s;
265
- - reads a text box once, after the paragraph it is anchored in. Word writes each text box twice,
266
- and the paragraph it was anchored in lost its text after the box: a resume template lost its
267
- "Objective" heading;
268
- - no longer takes the tab stops of a paragraph for tabs, and reads PowerPoint's line breaks
269
- (`<a:br>` with its run properties inside), which were lost.
270
- - **Picture marks: forms painted inside forms cannot hold the server.** A form was read again each
271
- time it was painted, and the time limit was checked only between pages: a PDF of 3 KB whose
272
- forms each paint the next one 30 times ran the process out of memory. Now each form is decoded
273
- once per file, a page that paints more than 20,000 images or makes the reader go through more
274
- than 16 MB of content is marked as a drawing at once, and the time limit holds within a page.
275
- Such a file is now read in 0.6 s.
276
- - **`llm-large-files/node`: `get` and `remove` answer their errors.** A `getOwner` that threw, or a
277
- store call that failed, rejected the handler's promise, which ends a Node process that has no
278
- handler for it (Express 4, plain `node:http`). All three handlers now answer every error
279
- themselves:
280
- - an error with a `status` between 400 and 599, as `getOwner` can now throw to refuse a request,
281
- is answered with that status and its message;
282
- - a store that fails is a 500 that gives the error's code (`Upload failed (ENOSPC).`). It was a
283
- 422 with the error's message, which named the server's paths;
284
- - `getOwner` runs before the upload is read, so a refused upload is not buffered.
285
-
286
- ## [0.3.5] - 2026-11-11
287
-
288
- ### Added
289
-
290
- - **`explorerModel`: a second model for the searching and reading.** The application chooses the
291
- model, as before, in `geminiApi()` or `vertexAi()`. It can now name two. The explorer makes the
292
- tool calls (search, read, look at pages) and reads a whole file in parts; `model` then writes the
293
- answer from what the tools returned, in one request without tools. So the many requests of a
294
- search through a large file can go to a cheaper or faster model.
295
- `geminiApi({ apiKey, model, explorerModel: process.env.GEMINI_EXPLORER_MODEL })`: left out,
296
- empty, or the same as `model`, one model does both, and the requests are those of 0.3.0 (checked
297
- byte for byte over seven scenarios). See
298
- [An explorer model](docs/configuration.md#an-explorer-model).
299
- - An endpoint of your own takes the explorer's URL as `explorerUrl`. It is called with the same
300
- headers.
301
- - `explorerGenerationConfig` is the explorer's `generationConfig`, for two models that do not
302
- take the same settings. It defaults to `generationConfig`. `analysisConfig` applies to the part
303
- reads of a whole-file read, which are the explorer's when there is one.
304
- - The answering model gets the explorer's tool calls and their results, pages included. It does
305
- not get the explorer's thoughts, thought signatures or words, and `text` and `onText` carry
306
- only the answer. The answer is always a request of its own, so a question takes one request
307
- more than with one model.
308
- - Checked live with Flash-Lite models, on the Gemini API and on Vertex AI, between Gemini 3.1 and
309
- 3.5 and between Gemini 2.5 and 3.5, in both directions, with thinking on and off: counts and
310
- causes from a searched log, a whole-file read, and a chart and a photo from pages that the
311
- explorer looked at. Every answer was right. `gemini-3.5-flash-lite` as explorer stopped with
312
- `DONE` each time, at one output token.
313
- - `EXPLORER_INSTRUCTION` and `FINAL_ANSWER_WITHOUT_TOOLS`: the two texts that `askGemini` adds for
314
- an explorer.
315
-
316
- ## [0.3.0] - 2026-11-10
317
-
318
- The model can look at the pages of a large PDF. Until now such a PDF reached it as text only, and
319
- pictures, charts and diagrams were lost. Everything here is off until you turn it on: an
320
- application that changes nothing, and does not install the new optional dependency, sends the same
321
- requests as with 0.2.0 (checked byte for byte against the published 0.2.0 over eight scenarios).
322
-
323
- ### Added
324
-
325
- - **`view_pages`: the real pages of a PDF, on request.** The tool cuts up to five pages out of the
326
- uploaded file and returns them as one small PDF, which Gemini reads like any PDF. Asked which bar
327
- of a chart is tallest, `gemini-3.5-flash-lite` said from the text alone that it could not see the
328
- chart; with the tool it looked at the page unasked and answered correctly. For ten questions that
329
- the text answers, it did not look at a page once. A page costs about 530 tokens. See
330
- [Pictures in PDFs](docs/configuration.md#pictures-in-pdfs) for the limits and the measurements.
331
- - It needs the new optional dependency `@cantoo/pdf-lib`, and the uploaded file (next item).
332
- - `askGemini` offers it for every PDF whose original is kept, also for one whose text fits in
333
- the prompt (a slide deck of photos has little text). `viewPages: false` turns it off.
334
- It works on the Gemini API and on Vertex AI. `toolFilePlacement: "beside"` sends the pages in
335
- a user turn of their own instead of inside the function response: Gemini 2.5 needs that, as it
336
- does not see a file inside a function response.
337
- - In a loop of your own: `prepare(ids, base, { viewPages: true })` lists the PDFs in
338
- `PreparedContext.viewable`, `tools(documents, { viewPages })` declares the tool, and
339
- `ToolSet.executeWithFiles(name, args, { maxFileBytes, maxPages })` returns `{ result, files }`.
340
- The tool is declared only on request, and `execute()` answers it with an error, because a loop
341
- that drops the file would tell the model that pages are attached with nothing attached.
342
- - Search and read results carry page numbers (`page`, `pages`) for a PDF that can be shown.
343
- - **`keepOriginals`: keep the uploaded file.** `createLargeFiles({ keepOriginals: ["pdf"] })`
344
- stores the file next to its text. It is off by default, because a kept file takes disk space, up
345
- to the upload limit, until the document expires. `DocumentStore` has two new optional methods,
346
- `putOriginal` and `getOriginal`; a store without them works as before and keeps nothing.
347
- `FileDocumentStore` writes `<id>.bin`, and delete, expiry and sweep remove it.
348
- `DocumentMeta.originalKept` records it, and `files.getOriginal(id, { owner })` returns the file
349
- to its owner.
350
- - **Scanned PDFs of up to 30 pages are accepted** when their original is kept: the model reads them
351
- by looking at the pages. `scannedPdfPages` sets the limit, and 0 refuses them as before. A longer
352
- scan, and any scan without a kept original, is still refused.
353
- - `geminiFunctionResponseTurns(answers, { files })`: the turns that answer a model turn's function
354
- calls, for a loop of your own. `geminiFunctionResponses` takes the files of each call and puts
355
- them inside its function response.
356
- - `createPdfExtractor({ pictures })`, `ExtractInput.scannedPages`, `MAX_VIEW_PAGES`,
357
- `FINAL_ANSWER_AFTER_PAGES`, and the types `ToolFile`, `ToolOutput`, `ToolFileLimits`,
358
- `PrepareOptions`, `GeminiToolAnswer` and `GeminiToolFilePlacement`.
359
-
360
- ### Changed
361
-
362
- - **A page of a PDF that shows a picture is marked**, with one line under its header:
363
- `[Picture on this page. This text cannot show it.]`. A picture is images that cover 3% of the
364
- page or more, other than a logo or background that is on most pages; a drawing is shapes filled
365
- in three or more colours, outside the tables. The pages are found from the structure of the file,
366
- without decoding any image: a PDF of 200 photos took 0.3 s to ingest before and takes 0.8 s now.
367
- This needs `@cantoo/pdf-lib`. Without it, and with `createPdfExtractor({ pictures: false })`, the
368
- text is exactly that of 0.2.0. Documents already in a store keep the text they were ingested
369
- with.
370
- - `ToolSet` has a new method, `executeWithFiles`, `LargeFiles` has `getOriginal`, and
371
- `PreparedContext` has `viewable`. Code that builds these objects itself (a test double, for
372
- example) has to add them.
373
-
374
- ### Known limits
375
-
376
- - A chart in one or two colours, and a drawing made only of lines, is not marked. The model can
377
- still look at the page: it did so for a one-colour chart that had only a caption.
378
- - Every look reads the whole PDF into memory: 0.06 s for 100 MB of photos, but 4 to 5 seconds and
379
- 700 MB for a file of 330,000 objects. A file that declares more objects than memory allows is
380
- refused. Reading cannot be interrupted, so a crafted PDF can hold the process for a long time:
381
- see [Security](docs/security.md#reading-pdfs-for-pages-and-pictures).
382
- - Tested with PDFs made by Chrome, Word and PowerPoint. PDFs made by LaTeX and InDesign were not
383
- tested. For FPDF, Ghostscript and scanners, the structures they are known to write were tested
384
- with files made for the purpose, not with files from those tools. Encrypted PDFs were tested
385
- with files encrypted by the library itself, and confirmed as encrypted by pdf.js.
386
-
387
- ## [0.2.0] - 2026-11-10
505
+ - **The status line of the example page shows.** The page of `examples/server.ts` wrote its
506
+ status to `status`, which in a browser is `window.status`, not the element with that id: retries,
507
+ "Writing the answer…", errors and the usage at the end never showed. The page now looks the
508
+ element up by its id.
509
+
510
+ ## 0.6.0 — 2026-11-22
511
+
512
+ Questions fail less often, and when one fails, you can tell why and keep what it found: every
513
+ model error has a kind, a request too large for the model is made smaller and sent again, a model
514
+ that goes silent is stopped after a wait, an empty or broken turn is asked for again, and a call
515
+ whose result is still in the conversation is answered with a pointer, not run again. Uploads
516
+ are guarded: an upload with an empty owner is refused, `files.tools()` checks the owner of each
517
+ document, many files built to exhaust the server are refused, and ingest lets other requests run
518
+ while it reads a file, within limits on its text, its pages and its time; one page of a PDF can
519
+ still hold the server, and a crafted PDF can still run it out of memory. A search shows the last
520
+ matching line, a text file in an older encoding, such as a Hebrew CSV from Excel, is read in that
521
+ encoding, and the rest are fixes in the tool loop, whole-file reads, the three adapters and the
522
+ text the model is sent. Some of these change what the library sends, throws or refuses: read
523
+ **Upgrading** before you update.
524
+
525
+ ### Upgrading: what you need to change
526
+
527
+ Code written for 0.5.0 compiles with 0.6.0 as it is, but for two cases. The turns of
528
+ `geminiFunctionResponses` and `geminiFunctionResponseTurns` now have `GeminiPart[]` parts, where
529
+ they had `unknown[]` (see **Changed**). Code that adds to those `parts` a string, or a value typed
530
+ `unknown`, `object` or by an interface (another SDK's `Part`), no longer compiles: add an object
531
+ literal, or `{ ...part }`. And an object typed as `ModelRequestError` or one of its subclasses,
532
+ but made other than by its constructor, needs the new `kind`. Every other change to the public
533
+ types is an addition: new fields and new optional options (under **New**), wider parameter types
534
+ (`parseSseJson` takes hooks and Node streams), and new exports. `llm-large-files` adds
535
+ `partialResultOf`, `classifyModelError`, `errorKindOf`, the error class `SseEventTooLongError`, the
536
+ constants `DEFAULT_FIRST_BYTE_TIMEOUT_MS`, `DEFAULT_IDLE_TIMEOUT_MS`, `DEFAULT_MAX_TEXT_BYTES`,
537
+ `DEFAULT_MAX_PDF_PAGES` and `DEFAULT_INGEST_TIMEOUT_MS`, and the types `ModelErrorKind`,
538
+ `ModelErrorClass`, `IdleWaits`, `RetryNotice` and `SseHooks`; `llm-large-files/gemini` adds
539
+ `partialResultOf` and `SseEventTooLongError`. One member is marked deprecated:
540
+ `ModelAdapter.estimateTokens` (see "Your own adapter" below).
541
+
542
+ Some behavior is different. Check each point against your app.
543
+
544
+ Uploads and stored documents:
545
+
546
+ - **An upload whose owner is empty is refused.** An owner of `""` (what `user?.id ?? ""` gives a
547
+ caller who is not signed in), of spaces only, or `null` was one owner shared by every such
548
+ caller: each of them could read and delete the documents of the others whose IDs it had.
549
+ `files.ingest` now throws a `TypeError`:
550
+ `owner must be a string that is not empty or only spaces, such as the signed-in user's ID. To let anyone with the document's ID use it, leave owner out.`
551
+ So does an owner from JavaScript that is neither a string nor a finite number (`req.user` in
552
+ place of `req.user.id`, `true`, `NaN`, an array). `createDocumentHandlers` answers such an
553
+ upload with a 500 before it reads the body, and logs nothing:
554
+ `{ "error": "Upload failed (empty owner)." }` when `getOwner` returns `""`, spaces only or `null`
555
+ (a user header that arrives empty gives `""`), and
556
+ `{ "error": "Upload failed (owner is not a string)." }` for the others. 0.5.0 accepted all of
557
+ these owners. Signed-in uploads and numeric owners are unchanged. Reads and deletes with
558
+ `owner: ""` work as before, so the documents stored with that owner stay readable until they
559
+ expire.
560
+ **What to do:** in `getOwner`, return the user's ID, not the user object. Where every upload
561
+ needs a signed-in user, throw an error with `status: 401` for a request without one
562
+ ([Requiring a signed-in user in the handlers](docs/security.md#requiring-a-signed-in-user-in-the-handlers)).
563
+ Only where anonymous uploads are meant, return `undefined` for such a caller
564
+ (`user?.id || undefined`): anyone with the ID of such a document can then read and delete it, as
565
+ the message says. See [Ownership](docs/security.md#ownership) and
566
+ [`DocumentHandlerOptions`](docs/reference/node.md#documenthandleroptions).
567
+ - **Uploads past the new limits are refused.** `files.ingest` throws, and
568
+ `createDocumentHandlers` answers 422 with the message:
569
+ - a PDF of more than `maxPdfPages` pages (5,000 by default), before any page is read:
570
+ `This PDF has 6,200 pages, more than the 5,000 read from one file. Split it, and attach the part you need.`
571
+ - a file whose text takes more than `maxTextBytes` in UTF-8 (100 MB by default, or
572
+ `maxUploadBytes` when you set that higher):
573
+ `This PDF holds more than 100 MB of text, more than is kept from one file. Split it, and attach the part you need.`,
574
+ or for a text file `notes.txt holds more than 100 MB of text, …` with the same end. A file's
575
+ text can be larger than the file: the text of a DOCX is often 2 to 4 times its size, a UTF-16
576
+ file of Chinese or Japanese text grows by half in UTF-8, and a small PDF can draw far more
577
+ text than its size.
578
+ - a DOCX or PPTX of more than 32 million characters of text (about 10,000 dense pages), whatever
579
+ `maxTextBytes` allows:
580
+ `This DOCX holds more than 32 million characters of text, more than is read from one file. Split it, and attach the part you need.`
581
+ - a PDF that draws more than 100 times its size in text, past the first 16 MB:
582
+ `This PDF draws more than 16 MB of text, over 100 times its size. A file that grows that much is not read: it may be built to exhaust the server.`
583
+ Real PDFs hold less text than their size.
584
+ - files built to exhaust the server, which no program writes: a PDF whose page tree lists one
585
+ page more than once; a DOCX or PPTX with paragraphs nested more than 32 deep, more than
586
+ 1,000,000 paragraphs with text, more than 20,000 parts
587
+ (`This DOCX has more than 20,000 parts, more than an Office document has. It may be built to exhaust the server, so it is not read.`),
588
+ or a list of parts that would take JSZip far more memory or time than an Office document needs
589
+ (the list is read before JSZip reads it, the way JSZip will, not from the count the file gives);
590
+ - with `@cantoo/pdf-lib` installed, a PDF with a page whose content would take pdf.js far longer
591
+ to read than its file explains (past about 1 to 1.5 s of pdf.js, or 32 times the size of the
592
+ file when that is more), found before pdf.js reads any page
593
+ ([Pages that would hold the server](docs/guides/pdfs.md#pages-that-would-hold-the-server)):
594
+ `Page 1 of this PDF draws far more than its file holds, and reading it would hold the server for a long time. A file built that way is not read: it may be built to exhaust the server. Print it to a new PDF, and attach that.`
595
+ Pages that each pass but add up to more than four times as much are refused with
596
+ `This PDF draws far more than its file holds, …` with the same end. A page whose content is
597
+ stored in a way that cannot be decoded before pdf.js reads it (a filter that only images use,
598
+ such as JPEG) is refused with
599
+ `Page 1 of this PDF stores its content in a way that cannot be checked before it is read, so it is not read. Print it to a new PDF, and attach that.`
600
+ The pages of the documents tested ran up to 11% of that limit.
601
+
602
+ **What to do:** nothing, unless your users upload PDFs of more than 5,000 pages, or files with
603
+ more than 100 MB of text: then raise `maxPdfPages` or `maxTextBytes`. If real PDFs of your users
604
+ are refused for a page that would hold the server, read them with
605
+ `createPdfExtractor({ checkPages: false })`, in a process of its own. Every message is in
606
+ [PDFs and other formats](docs/guides/pdfs.md#what-is-refused).
607
+ - **An ingest that takes more than 2 minutes throws.** `ingestTimeoutMs` (120,000 by default)
608
+ bounds the extraction, the line index and the log profile, not the store's writes. Past it,
609
+ `ingest` throws
610
+ `report.pdf took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.`,
611
+ stores nothing, and `createDocumentHandlers` answers 422 with that message. An extractor of your
612
+ own that calls a slow service, such as OCR of a long scan, can take longer than that.
613
+ **What to do:** for such an extractor, raise `ingestTimeoutMs`, or set it to 0 for no limit, and
614
+ pass `input.signal` on to the work it does (`fetch(url, { signal: input.signal })`): at the limit
615
+ `ingest` stops waiting for the extractor, but only the extractor can stop its own work. If you
616
+ ingest in a worker or a process with a timer of its own, set that timer above
617
+ `ingestTimeoutMs`, so that the user gets the library's message.
618
+ - **With `@cantoo/pdf-lib` installed, every PDF is read with it before its text.** The PDF
619
+ extractor reads the file into objects before pdf.js reads any page, for the page check and the
620
+ picture marks together; 0.5.0 read it after the text, for the marks only. With picture marks on
621
+ (the default), that costs nothing measurable: PDFs of 300 to 2,000 pages took the same time
622
+ within the spread of three runs, and the longest stall did not grow. With `pictures: false`,
623
+ 0.5.0 did not read the file this way at all, and now does, for the page check: 0.1 to 0.3 s more
624
+ for 300 to 2,000 pages, up to 90 MB more memory at the peak, and, for the first PDF of a process,
625
+ about 0.4 s in one block to load `@cantoo/pdf-lib`, unless the server loads it when it starts
626
+ ([Deployment](docs/guides/deployment.md#uploads-and-ingest)). See
627
+ [Measurements](docs/measurements.md#the-server).
628
+ **What to do:** nothing, unless you set `pictures: false` to keep ingest light, in a process with
629
+ little memory to spare. Then give it that room, or pass
630
+ `createPdfExtractor({ pictures: false, checkPages: false })` to read PDFs as 0.5.0 did, without
631
+ the page check.
632
+ - **`files.tools()` answers a document whose owner does not match as no longer available.** Each
633
+ tool call now compares the owner stored with the document with the `owner` of the `DocumentMeta`
634
+ that `tools()` was handed. When they differ, the call answers the model
635
+ `doc_… is no longer available on the server. Ask the user to attach the file again.`, and
636
+ `view_pages` shows no page. A document stored without an owner is open to any metadata, as
637
+ before. The metadata that `prepare(ids, base, { owner })` and `getMeta(id, { owner })` return
638
+ carries the stored owner, so `askWithFiles`, `askGemini`, and a loop of your own written as the
639
+ docs show, work as before.
640
+ **What to do:** nothing, unless your loop builds `DocumentMeta` objects itself, from IDs or from
641
+ your own database (a `DocumentSummary` has no owner). Take them from `prepare` or `getMeta` with
642
+ the caller's owner. See [Security](docs/security.md#tool-scoping).
643
+ - **A text file that is not UTF-8 is read in the encoding it was saved in.** 0.5.0 decoded every
644
+ text, log, CSV, JSON and Markdown file as UTF-8: a CSV that Excel saved in windows-1255 was
645
+ stored as replacement characters (U+FFFD), and accepted without a word. `files.ingest` now reads
646
+ a file in one of these encodings when the letters of its lines show which, and records it in
647
+ `meta.encoding`: `windows-1255` (Hebrew; ISO-8859-8 too), `windows-1256` (Arabic),
648
+ `windows-1251` (Cyrillic), `shift_jis` (Japanese in Shift_JIS, half-width katakana too) and
649
+ `windows-1252` (Western European; ISO-8859-1 too). The encoding is chosen on the lines that are
650
+ not UTF-8 and hold letters, wherever they are in the file, up to 64 KB of them. A line that is
651
+ valid UTF-8 is read as UTF-8 all the same. A byte that the encoding does not have is stored as
652
+ U+FFFD, and counted in `meta.replacedCharacters`.
653
+
654
+ No text file is refused for its encoding. Valid UTF-8 and UTF-16 files are decoded as before. A
655
+ file is read as UTF-8, as 0.5.0 read it, with its characters that are not valid counted in
656
+ `meta.replacedCharacters`, when its encoding is not recognized, when at least as many of its
657
+ lines count as UTF-8 as count as not, or when at most one line in 200 is not UTF-8 (a log cut at
658
+ a byte count, a log with stray bytes): those lines become U+FFFD even when they are in an older
659
+ encoding. As a rule, these are not recognized: Greek, Turkish, Central European (windows-1250),
660
+ Icelandic, KOI8-R, the DOS code pages (437, 850, 866), Chinese, Korean and Thai, and Japanese
661
+ with few or no kana. Some files are read in a wrong encoding, which `meta.encoding` names:
662
+ Hungarian in windows-1250 or ISO-8859-2 as windows-1252, with õ and û in place of ő and ű (a
663
+ search for a word with ő or ű finds nothing); ISO-8859-15 without œ as windows-1252, with ¤ in
664
+ place of € (with œ in its words, it is most often read as UTF-8 with U+FFFD); and a short file,
665
+ or one long line, whose few stray bytes happen to fit another encoding
666
+ ("Straße" saved in DOS code page 850 as windows-1252 "Straáe"). An editor that opens such a file
667
+ as UTF-8 shows the lines read in an older encoding as �: a person who checks the file there does
668
+ not see what the model reads.
669
+
670
+ A `DocumentStore` of your own must keep the two new fields, as it keeps the rest of `meta`
671
+ ([Writing a store of your own](docs/guides/storage.md#writing-a-store-of-your-own)). One that
672
+ checks `meta` against a fixed list of fields (a MongoDB `$jsonSchema` with
673
+ `additionalProperties: false`) refuses the ingest of every text file that is not valid UTF-8,
674
+ and `createDocumentHandlers` then answers 500 `{ "error": "Upload failed." }`. One that drops
675
+ them (fixed columns of a table, a Mongoose schema in strict mode) keeps the text, read right, but
676
+ the model is not told how it was read. The upload answer (`DocumentSummary`) holds both
677
+ fields when they are set.
678
+ **What to do:** nothing, if your store keeps `meta` whole and your client accepts fields it
679
+ does not know. Show `meta.encoding` to the user ("read as windows-1255"), and when letters look
680
+ wrong, ask for the file in UTF-8 (in Excel, "CSV UTF-8 (Comma delimited)"). Documents stored
681
+ before the upgrade from files in these encodings still hold U+FFFD: ingest them again. See
682
+ [Text encodings](docs/guides/pdfs.md#text-encodings), how the encoding is chosen in
683
+ [How it works](docs/how-it-works.md#text-encodings),
684
+ [Text files that were not UTF-8](docs/security.md#text-files-that-were-not-utf-8) and
685
+ [`DocumentMeta`](docs/reference/library.md#documentmeta).
686
+ - **Some files are stored with other text than 0.5.0 stored.** Besides a text file that is not
687
+ valid UTF-8 (above), ingest now removes characters that show nothing, such as tag characters,
688
+ zero-width spaces and control characters U+0080-U+009F, and the terminal escape sequences that
689
+ start with U+009B; makes U+0085 a line break in a text that has no other; marks text that Word
690
+ hides, line by line; and marks the heading of a slide that the slide show skips (see
691
+ **Changed**). File names lose tag characters, zero-width spaces and the other characters that
692
+ show nothing too. Their control characters, line and paragraph separators and text-direction
693
+ controls, the marks of right-to-left text included, became a space in 0.5.0 already, and still
694
+ do: an escape sequence loses only its ESC (`re\x1b[31mport.txt` is stored as `re [31mport.txt`).
695
+ Lines move in three cases: in a DOCX with hidden text, in a text whose records end with U+0085,
696
+ and after a line of more than 2,000 characters that lost such characters, which can now be cut
697
+ into fewer lines. A file with none of these gets the same text and line index as 0.5.0 gave it,
698
+ and the same outline, but in a document of more than 400 headings with 20 to 399 at the top
699
+ level (see **Fixed**, Ingest). Documents stored before the upgrade keep their text and outline
700
+ until they expire.
701
+ **What to do:** nothing. To have a document stored before the upgrade read the new way, ingest
702
+ its file again.
703
+ - **An `unpdf` that cannot read PDFs on your version of Node is refused, with what to install,
704
+ and unpdf 2 is accepted.** With 0.5.0, on Node 20.19 and 22.12, unpdf 1.5.0 to 1.6.0 stopped the
705
+ whole process at the first PDF (`TypeError: Promise.try is not a function`, thrown where nothing
706
+ could catch it). On Node 20, unpdf 1.9 and later failed every PDF with
707
+ `Serverless PDF.js bundle could not be resolved: ReferenceError: Iterator is not defined`. Now
708
+ `files.ingest` throws, and `createDocumentHandlers` answers 422, with a message that names the
709
+ major version of Node and says what to install:
710
+ - unpdf 1.5.0 to 1.6.0 on Node 22:
711
+ `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.`
712
+ On Node 20 the message ends `Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 24 or later.`
713
+ - unpdf 1.9 and later, 2.x included, on Node 20:
714
+ `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.`
715
+ The part in parentheses is unpdf's own message.
716
+
717
+ The optional peer range of `unpdf` is now `^1.4.0 || ^2.0.0`; it was `^1.4.0`. An app that
718
+ upgrades keeps the unpdf its lock file has. On Node 24 and later, a new `npm install unpdf` next
719
+ to 0.6.0 installs unpdf 2 and saves `^2` in `package.json`, where it got 1.9.1 next to 0.5.0. On
720
+ Node 20 and 22, npm 11 (the version checked) picks a 1.x whose engines fit: 1.7.0 and 1.9.1.
721
+ **What to do:** nothing, if your PDFs are read today. Otherwise install the unpdf that runs on
722
+ your Node: on Node 20, 1.4.0 or 1.6.1 to 1.8.1 (1.7.0 is the last that does not ask for
723
+ Node 22); on Node 22, 1.4.0, or 1.6.1 or a later 1.x; on Node 24 and later, any version from
724
+ 1.4.0, 2.x included. To go back to 0.5.0 after moving to unpdf 2, install both in one command:
725
+ `npm install llm-large-files@0.5.0 unpdf@^1`. `npm install llm-large-files@0.5.0` alone stops
726
+ with `ERESOLVE` and changes nothing. Restoring `package.json` and `package-lock.json` together
727
+ works too. See [PDFs and other formats](docs/guides/pdfs.md#formats).
728
+ - **One page of a PDF still holds the server while it is read, and a crafted PDF can still run it
729
+ out of memory.** 0.5.0 did the same. Between two pages, the PDF extractor lets other requests run
730
+ and looks at the time limit and the signal; within a page it cannot, and neither
731
+ `ingestTimeoutMs` nor `IngestInput.signal` cuts a page short. The page check (above) refuses the
732
+ pages that would take far longer than their file explains. What it leaves:
733
+ - a page that passes holds the server for up to about 1.5 s in a small file, and longer in a
734
+ large one: a page of a 10 MB file may run 320 MB of content, about a minute of pdf.js;
735
+ - without `@cantoo/pdf-lib`, on a file it cannot read or that declares more than 150,000
736
+ objects, and with `checkPages: false`, no page is checked: a 3 KB page of forms inside forms
737
+ held the event loop for 13 s, and one of 4 KB for about 100 s. A file built to be read one way
738
+ by `@cantoo/pdf-lib` and another way by pdf.js passes the check too;
739
+ - `@cantoo/pdf-lib` reads each object in one step, at ingest and on each look of `view_pages`:
740
+ about 0.1 to 0.35 s for each MB of one object (a crafted PDF of 16 MB with one array of numbers
741
+ held the server 1.6 to 3.2 s at ingest, and 1.7 to 3.5 s on each look), and 0.7 s for each
742
+ million objects that a cross-reference stream declares;
743
+ - a DOCX or PPTX packed hundreds of times tighter than documents are holds it for about 0.2 s at
744
+ a time while JSZip unpacks a piece.
745
+
746
+ Nothing checks the memory an object of a PDF takes before pdf.js or `@cantoo/pdf-lib` builds it,
747
+ and a stream unpacked twice packs objects thousands of times. Measured on Node 24: a PDF of 732
748
+ bytes whose object stream holds 4 MB of empty dictionaries ran a heap of 512 MB out of memory at
749
+ ingest; one array of one-digit numbers in a PDF of 16 MB ran a heap of 256 MB out of memory at
750
+ ingest, and one of 512 MB on a look at its pages; a PDF of 1.6 KB whose object stream unpacks to
751
+ 512 MB was read with 20 MB of heap, but the process took 1.6 GB, outside the heap, where
752
+ `--max-old-space-size` does not limit it; and `@cantoo/pdf-lib` keeps every name and reference it
753
+ reads for the life of the process, so that files of 9 KB that each declared a million new objects
754
+ ran a heap of 512 MB out of memory at the fourth ingest. A check of each object before it is
755
+ built is not in 0.6.0: it would be easy to get around. See
756
+ [Objects of a PDF](docs/security.md#uploads) and the [measurements](docs/measurements.md#the-server).
757
+ **What to do:** if your users can upload files you do not trust, ingest them in a child process
758
+ of their own, with its own `--max-old-space-size` and a memory limit of its own, such as a
759
+ container of its own, as [Deployment](docs/guides/deployment.md#uploads-and-ingest) shows: such
760
+ a file then holds or stops that process, not your server, and its time limit stops it. Not in a
761
+ worker thread, as the security page of 0.5.0 suggested: a `--max-old-space-size` of the process,
762
+ on the command line or in `NODE_OPTIONS`, replaces the `resourceLimits.maxOldGenerationSizeMb`
763
+ of every worker (with `--max-old-space-size=1024`, a worker given 512 MB had 1,216 MB on
764
+ Node 24), and a worker that runs out of memory can stop the whole process. If you ingest in a
765
+ worker, move to the child process of `ingestInProcess` in that guide. Do not offer `view_pages`
766
+ on their documents (`viewPages: false`), or keep no PDF originals: a look parses the file again
767
+ on the server that answers the question, can need more memory than the ingest did, and what
768
+ `@cantoo/pdf-lib` keeps there comes back only when that server restarts
769
+ ([Memory on each server](docs/guides/deployment.md#memory-on-each-server)).
770
+ - **An upload whose store fails while it writes is answered 500, not 422.** When `put`,
771
+ `putOriginal` or `putIndex` throws an error that has no `status` or `statusCode` from 400 to 599
772
+ and is not a Node system error, `createDocumentHandlers` answers 500
773
+ `{ "error": "Upload failed." }`. 0.5.0 answered 422 with the error's own message, which may name
774
+ a database host. A thrown value that is not an `Error` also gets 500 "Upload failed.", where it
775
+ was 422 with the value as text. Errors with a status, Node system errors (an `Error` or not) and
776
+ files that cannot be read are answered as before.
777
+ **What to do:** for a more specific answer, throw your store's write errors with a `status` and
778
+ a message of your own (a 503 that says to try again), and log the cause in your store: the
779
+ handlers log nothing. Two paths still answer a store's error 422 with its message: an `ingest` of
780
+ your own that throws a new error in its place, as `ingestInProcess` in
781
+ [Deployment](docs/guides/deployment.md#uploads-and-ingest) does, and a route of your own, as in
782
+ [Web app](docs/guides/web-app.md#filesingest-and-its-errors). A status on the error avoids it.
783
+ See the [node reference](docs/reference/node.md#uploadrequest-response).
784
+
785
+ Model errors and retries:
786
+
787
+ - **A model that sends nothing now fails, after a wait.** In 0.5.0 a chat request had no time
788
+ limit: a provider that stopped answering held the question, and the user, until your own
789
+ timeout. Now each adapter aborts a chat request that gets nothing for 600 s before the first
790
+ piece of its reply, or for 300 s between two pieces, and sends it once more; `onActivity` then
791
+ says "The model sent nothing for too long. Trying again…". If that try is silent too, the
792
+ question throws a `ModelRequestError` with `kind: "timeout"` and `status: 0` ("Gemini sent
793
+ nothing for 600 s."). A reply whose text was already streamed to the user is not sent again: it
794
+ fails at once. Headers do not count as a piece, because a model that thinks sends nothing until
795
+ it has thought; keep-alives count. A reply that keeps arriving has no limit. A reply that is not
796
+ streamed comes whole at the end, so it must be written within `firstByteTimeoutMs`: Gemini and
797
+ OpenAI-compatible requests without `onText` (an explorer's requests among them), Gemini
798
+ requests to an endpoint without `streamUrl`, and every request of `openAiCompatible()` or
799
+ `anthropic()` with `stream: false`. Part reads of a whole-file read are not watched this way:
800
+ they keep their limit of 180 s.
801
+ **What to do:** handle the `"timeout"` kind (see the sample under **New**). With the defaults,
802
+ a model that never answers fails after about 20 minutes (two waits of 600 s). To give up
803
+ sooner, or never, set `firstByteTimeoutMs` and `idleTimeoutMs` on `askGemini`, `gemini()`,
804
+ `openAiCompatible()` or `anthropic()`; `0` waits without end, as 0.5.0 did. A proxy, load
805
+ balancer or gateway that closes a silent connection sooner still closes it first: keep the
806
+ timeouts on the way longer than these waits, or set the waits shorter. See
807
+ [Waits on a silent model](docs/guides/errors-and-reliability.md#waits-on-a-silent-model) and
808
+ [The order of the timeouts](docs/guides/deployment.md#the-order-of-the-timeouts).
809
+ - **A reply cut off on its way is sent again, and can fail a question after its text was shown.**
810
+ A stream that closes without saying why it ended, and DeepSeek's `insufficient_system_resource`,
811
+ are no longer taken for a whole reply (see **Fixed**), and a reply of HTTP 200 whose body is
812
+ empty is no longer a `SyntaxError` (below). Such a reply is sent again when none of it was
813
+ shown (see **Changed**, The adapters). When some of it was already streamed to the user, the
814
+ question throws at once: a `ModelRequestError` with status 0 and kind `"unreachable"`
815
+ ("Gemini's reply ended before it was complete."), or status 503 and kind `"server"` for
816
+ DeepSeek. In 0.5.0 the cut text was returned as the answer.
817
+ **What to do:** if you stream with `onText`, handle an error that comes after part of the
818
+ answer was shown: mark that text as incomplete and offer to ask again. `partialResultOf(error)`
819
+ has what the question found.
820
+ - **Quota errors are not sent again.** These now have `kind: "quota"`, and are thrown at once:
821
+ OpenAI's `insufficient_quota`, inside a stream too (HTTP 429 there); a Gemini quota per day
822
+ (HTTP 429 whose `details` name a quota per day, or, on Vertex AI, only its message); HTTP 402
823
+ (DeepSeek's "Insufficient Balance", OpenRouter's "Insufficient credits"); Claude's "Your credit
824
+ balance is too low" (HTTP 400); and Claude's spending limits ("You have reached your API usage
825
+ limits"), which come as HTTP 429 with `enforced_spend_limit_reached`, or as HTTP 400. 0.5.0 sent
826
+ the ones of HTTP 429 again three times (the default of `retry.retries`). A Gemini quota per
827
+ minute is `"rate_limit"`, and is waited for as before.
828
+ **What to do:** if you show "busy, try again" for every HTTP 429, show another message for
829
+ `"quota"`, and tell whoever runs the service: trying again soon does not help.
830
+ - **A request larger than the tokens a minute allows is made smaller, not sent again as it was.**
831
+ This covers OpenAI's "Request too large for gpt-4o … on tokens per min (TPM): Limit 30000,
832
+ Requested 45237" (HTTP 429) and Groq's "… on tokens per minute (TPM): Limit 6000, Requested 6438"
833
+ (HTTP 413 or 429), and the same per day: kind `"context_overflow"`, with `limitTokens` and
834
+ `requestedTokens`. 0.5.0 sent the 429 again three times as it was, though only a smaller request
835
+ can pass. Now the loop shortens older tool results, or plans the files again for that limit, as
836
+ for a request too large for the model (see **Changed**), and a part read is read in halves. The
837
+ steps say so: "The first request was larger than the 30,000 tokens a minute that the provider
838
+ allows: the files were planned again to fit it", or "The request was larger than the provider
839
+ allows in a minute: older tool results were shortened, and it was sent again". `withRetry` does
840
+ not send an error of kind `"context_overflow"` again, whatever its status.
841
+ **What to do:** nothing, unless an adapter of your own sets `kind: "context_overflow"` on an
842
+ error that a wait would mend. See
843
+ [A request too large for the model](docs/guides/errors-and-reliability.md#a-request-too-large-for-the-model).
844
+ - **A reply of HTTP 200 whose body is not JSON is a `ModelRequestError`, not a `SyntaxError`.** A
845
+ page from a proxy or a gateway that answered in the model's place (a sign-in page) now throws a
846
+ `GeminiRequestError`, `OpenAiRequestError` or `AnthropicRequestError`, with `kind: "invalid"`,
847
+ the status of the response (200), and the `SyntaxError` as `cause`:
848
+ `Gemini's reply could not be read: it was not JSON (text/html). A proxy or gateway may have answered in its place.`
849
+ For an OpenAI-compatible endpoint the message starts "The model's reply …", and for Claude
850
+ "Claude's reply …"; without a content type, the part in parentheses is left out. It is not sent
851
+ again, by the loop or by a part read. 0.5.0 threw the `SyntaxError`, and a streamed Gemini
852
+ request that got such a page returned an empty reply. A reply of HTTP 200 whose body is empty is
853
+ a reply cut off on its way: kind `"unreachable"`, status 0,
854
+ `Gemini could not be reached (the reply was empty).` ("The model could not be reached …" and
855
+ "Claude could not be reached …" for the others), and it is sent again; 0.5.0 threw a
856
+ `SyntaxError` and did not.
857
+ **What to do:** if you test `error instanceof SyntaxError`, test
858
+ `error.cause instanceof SyntaxError` instead (kind `"invalid"`, status 200). Kind `"invalid"`
859
+ alone also covers every other request that the provider refused. See
860
+ [The kind of a model error](docs/guides/errors-and-reliability.md#the-kind-of-a-model-error).
861
+ - **An error inside a stream has the status, and the kind, that its type names.** On an
862
+ OpenAI-compatible endpoint, `context_length_exceeded` is HTTP 400, kind `"context_overflow"`
863
+ (the request is made smaller), `insufficient_quota` HTTP 429, kind `"quota"`, and any other the
864
+ server's failure, HTTP 500 unless it names another status, sent again when none of its text was
865
+ shown. On Claude, `invalid_request_error` is 400, `authentication_error` 401 (kind `"auth"`),
866
+ `billing_error` 402 (kind `"quota"`), `permission_error` 403, `not_found_error` 404 and
867
+ `request_too_large` 413, and a type the adapter does not know is the server's failure, 500, sent
868
+ again when none of the reply was shown. 0.5.0 gave all of these the stream's 200, and sent none
869
+ of them again; only Claude's `overloaded_error`, `rate_limit_error`, `api_error` and
870
+ `timeout_error` had a status of their own, as they still do. `OpenAiRequestError.code` holds the
871
+ code.
872
+ **What to do:** nothing, unless you show your own words by status.
873
+ - **A whole-file read tells the model why a model request failed by its kind, its HTTP status or
874
+ a connection code, never by the error's words.** Its result, its line in `onStep` and `steps`,
875
+ and `toolTurns` now say, for example, "Could not read any part of app.log: The model refused the
876
+ key or token it was sent (HTTP 401)." In 0.5.0 they carried the provider's message, which can
877
+ name a project, a host, a masked key, or a URL with a key in it. The same holds for a part that
878
+ could not be read among others, for a last step that failed (`notes_only`), and for every error
879
+ a `generate` throws, yours included. An error is told by its `kind` ("The model's quota has run
880
+ out", "The model was busy", with " (HTTP 429)" when it has a status), or by the kind that its
881
+ HTTP status (`status`, `statusCode` or `response.status`) and message give, as
882
+ `classifyModelError` works it out. A connection code such as `ECONNREFUSED` gives "The model
883
+ could not be reached.", a timeout (an error named `TimeoutError`, or undici's
884
+ `UND_ERR_HEADERS_TIMEOUT` and `UND_ERR_BODY_TIMEOUT`) "The model took too long to answer.", and
885
+ any other error, such as a plain `Error`, "The model request failed.". A part reader of the
886
+ package's that got a reply with no text is still told "The model returned no text (SAFETY).",
887
+ without the provider's reason when it is not a plain word, and an error of the document store
888
+ keeps its own message.
889
+ **What to do:** if you read the provider's words from the steps, log them in your own `fetch`,
890
+ adapter or `generate` instead. To give the model a specific reason, throw an error with a `kind`
891
+ or an HTTP `status`. See
892
+ [Failures inside tools](docs/guides/errors-and-reliability.md#failures-inside-tools).
893
+ - **A retry option that is not a finite number takes its default.** `retries`, `baseDelayMs` and
894
+ `maxDelayMs` (of the `retry` option and of `withRetry`) count as not set when they are `NaN`,
895
+ `Infinity`, `-Infinity` or not a number at all, such as a string from an environment variable.
896
+ They are then 3, 500 and 60,000. In 0.5.0, `retries: Infinity` sent a failing request again
897
+ without end, `-Infinity` counted as 0, and a string counted as the number in it. For `NaN`, see
898
+ **Fixed**.
899
+ **What to do:** nothing, unless you set one of them to `Infinity`, `-Infinity` or a string. Pass
900
+ a finite number: `retries: 0` to turn retries off, a larger `maxDelayMs` to take a long
901
+ `Retry-After`, and `Number(process.env.RETRIES)` rather than the string. See
902
+ [`RetryOptions`](docs/reference/errors-and-retries.md#retryoptions).
903
+ - **Gemini part reads send no temperature.** By default, the `generationConfig` of a part read in
904
+ a whole-file read, and of `createGeminiGenerateText`, is `{ maxOutputTokens }`. It was
905
+ `{ maxOutputTokens, temperature: 0.2 }`. Gemini 3.6 and later ignore the temperature, and Google
906
+ says later models will refuse it.
907
+ **What to do:** to keep it for an older model, pass
908
+ `analysisConfig: (maxOutputTokens) => ({ maxOutputTokens, temperature: 0.2 })` to `gemini()` or
909
+ `askGemini`, or a `generationConfig` that does the same to `createGeminiGenerateText`. See
910
+ [Whole-file reads in parts](docs/guides/vertex-and-gemini.md#whole-file-reads-in-parts).
911
+
912
+ What the model is sent, and what the loop does:
913
+
914
+ - **The frame around a file sent whole carries a mark, before the file's name.** Its two lines
915
+ were `--- Attached file: report.txt (text, 6 lines) ---` and
916
+ `--- End attached file: report.txt ---`. For every file sent whole, they are now
917
+ `--- Attached file [mark 1f0c3a9e]: "report.txt" (text, 6 lines; it ends only at the line with mark 1f0c3a9e) ---`
918
+ and `--- End attached file [mark 1f0c3a9e] ---`. The mark is eight hex digits made from the
919
+ document ID, which is made after the file's text was written, so a line of the file that copies
920
+ the end of the frame has no mark or a wrong one. The mark is not a secret (someone who knows a
921
+ document's ID can write its mark into a file uploaded later), and it does not make the model
922
+ obey. The name comes after the mark, quoted as JSON. A file that is not valid UTF-8 adds how it
923
+ was read after the count of lines (see **Changed**), and a file of one line says `1 line`. The
924
+ whole first line is
925
+ `--- Attached file [mark <8 hex digits>]: <name as JSON> (<format>, <lines> line|lines[, read as <encoding>[, <n> character|characters not valid in it, shown as �] | , <n> character|characters not valid UTF-8, shown as �]; it ends only at the line with mark <8 hex digits>) ---`,
926
+ with commas in the count of lines (`3,000`). The text between the two lines is the same as
927
+ before. The card of a file too large to send whole keeps its first line,
928
+ `--- Large attached file: app.log ---`.
929
+ **What to do:** if your code or tests look for these lines in `PreparedContext.blocks` or in the
930
+ requests, match the new form. To match the start of any of them, use `--- Attached file [mark `.
931
+ To find one file, look for `]: ` followed by its name as a JSON string (`JSON.stringify(name)`)
932
+ and ` (`: a quote or a backslash in the name is escaped. A test that compares the prompts of two
933
+ uploads must allow for the mark, as it allows for the document ID. See
934
+ [`PreparedContext`](docs/reference/library.md#preparedcontext) and
935
+ [The frame around a file](docs/security.md#the-frame-around-a-file).
936
+ - **The provider's prompt cache misses once after the upgrade, and then on each follow-up
937
+ question from the rounds of the question before it.** The tool guide in the system instruction
938
+ changed (see **Changed**), and so did the descriptions of `search_document` (next point) and
939
+ `analyze_whole_document`, the frame of every file sent whole, and, for a question without
940
+ `analyze_whole_document`, the cards.
941
+ The first request of each conversation after the upgrade therefore shares little or nothing of
942
+ its start with what 0.5.0 sent: its input costs what it costs without a cache (with Claude's
943
+ `cache_control`, a cache write). The mark of a document is the same in every request, so from
944
+ then on the cache reuses the files again. One miss stays: the tool rounds of an earlier
945
+ question are now sent without `tool_turns_left` (see below), so the first request of a
946
+ follow-up question differs from the requests of the question before it from that question's
947
+ first tool round on. Those rounds are billed at the full price once, in that request (with
948
+ Claude's `cache_control`, as a cache write); the cards, and the turns before those rounds, are
949
+ still read from the cache. While servers of both versions answer the same conversation, each
950
+ switch from one version to the other misses again.
951
+ **What to do:** nothing. During a rolling upgrade, keep a conversation on one version if you can
952
+ ([Servers of two versions](docs/guides/deployment.md#servers-of-two-versions)). See
953
+ [Prompt caching](docs/guides/costs-and-limits.md#prompt-caching).
954
+ - **A search in exact or regex mode shows the last matching line too.** When more lines match
955
+ than `max_results` (20 by default, 50 at most), `matches` holds the first `max_results` lines
956
+ and then the last matching line of the file: up to `max_results` + 1 entries. `note` says how
957
+ many are shown:
958
+ `21 of the 442 matching lines are shown: the first 20 and the last (line 15269). To see the ones in between, narrow the search.`
959
+ With `max_results` + 1 matches, every one is shown, and there is no note. A search with no more
960
+ matches than `max_results` is unchanged, unless its result is cut to the room it has. A cut
961
+ result, whatever its number of matches, drops matches from the end of the first ones, so that
962
+ the last one stays, and its note reads
963
+ `Showing 6 of the 442 matching lines to stay within the size limit: the first 5 and the last (line 15269). Narrow the query or read specific lines.`
964
+ In 0.5.0 that note counted the lines the result held, not the lines that matched
965
+ (`Showing 5 of 20 results to stay within the size limit. …`). A search that stopped early shows
966
+ no last line, since it did not reach it. Its note is now
967
+ `The scan stopped early; the total is a lower bound, and the last match in the file is not known.`,
968
+ and when such a result is cut too, the note of the cut follows that sentence. The `evidence` of
969
+ a search, and the stand-in that later replaces its result, list the lines of the last match too.
970
+ The description of the tool, which the model reads, now says that exact mode "finds the lines
971
+ that contain the text", and that "For exact and regex, total_matching_lines counts every
972
+ matching line, and the result shows the first max_results of them and the last one". It said
973
+ that exact mode "returns every line containing the text".
974
+ **What to do:** nothing, unless your code expects at most `max_results` entries in `matches`, or
975
+ your tests compare a search result whole. See
976
+ [`search_document`](docs/reference/tools.md#search_document).
977
+ - **A repeated call is answered with a pointer.** A call whose result is still in the
978
+ conversation in full is not run again: the same search, the same read, the same overview, or a
979
+ read of lines inside a read that is shown, in this question or in the stored tool rounds of an
980
+ earlier one. The model gets a pointer to that result. Its step reads
981
+ "Search app.log (exact) for “timeout” — already shown above", its result in `toolTurns` has
982
+ `already_shown: true` and a note, and it adds no entry to `evidence`. The same call made twice
983
+ in one turn is run once. A call is run again when the earlier result failed, was cut to its
984
+ room, was replaced by a stand-in, or came from a search that stopped early; when it is an exact
985
+ or regex search stored before 0.6.0 with more matches than it shows (it lacks the last match); and
986
+ when it is a read of one line from the rounds of an earlier question, since 0.5.0 cut a long line
987
+ to the room it had without saying so (no `text_cut`). With an adapter whose provider may clear
988
+ old tool results (`clearsToolResults`, under **New**), a call made again is run again.
989
+ **What to do:** if you parse `steps` or the lines of `onStep`, or expect one `evidence` entry
990
+ per call, allow for these. See
991
+ [Repeated calls in a follow-up](docs/guides/conversations.md#repeated-calls-in-a-follow-up).
992
+ - **The tool rounds of an earlier question are sent without `tool_turns_left`.** That count was of
993
+ the turns their own question had left, and a model could take a 0 there for its own. What
994
+ `toolTurns` stores is unchanged. `geminiToolTurns`, `openAiToolTurns` and `anthropicToolTurns`
995
+ leave the field out too, so a history kept in a provider's form gives the same request as one
996
+ kept as `toolTurns`; contents converted before 0.6.0 keep it.
997
+ **What to do:** nothing, unless your tests compare the output of a converter with the stored
998
+ `toolTurns`: leave `tool_turns_left` out of the expected value. See
999
+ [What `toolTurns` holds](docs/guides/conversations.md#what-toolturns-holds).
1000
+ - **An empty or broken turn is asked for once more, at the cost of a request.** When the model's
1001
+ first reply is empty, or holds a tool call that could not be read (Gemini's
1002
+ `MALFORMED_FUNCTION_CALL` or `UNEXPECTED_TOOL_CALL`), it is asked once more with a short note;
1003
+ 0.5.0 wrote the answer from the document cards alone, and it looked like any other. When the
1004
+ request for the answer (the last one of the tool loop, sent with `toolChoice: "none"`) comes back
1005
+ empty, or with a tool call the model was told not to make (`UNEXPECTED_TOOL_CALL`,
1006
+ `MALFORMED_FUNCTION_CALL`, or calls from an adapter of your own), it is sent once more, with a
1007
+ note at its end that is not kept:
1008
+ `Your last reply had no text. No tool can be called in this reply: write the answer now, in text, from what is above.`
1009
+ 0.5.0 ended such a question with `answered: false` and no text; a model that still writes no
1010
+ text ends that way, one request later. A question makes at most two such second tries. Each is a
1011
+ chat request: it counts toward `limits.requests` and takes a turn of `limits.toolTurns`, and the
1012
+ one for the answer can be one request past `limits.toolTurns`. The answer is not asked for again
1013
+ after a refusal, a filter, a reply cut off at the output limit with nothing in it, or once
1014
+ `limits.requests` or `limits.inputTokens` is reached. With an explorer, the answering model gets
1015
+ the note too.
1016
+ **What to do:** if you set `limits.requests` or `limits.toolTurns` close to what a question
1017
+ needs, add two. If a test fake of yours answers with nothing, or answers the answer's request
1018
+ with a tool call, expect one more request and one more step: a fake with a fixed queue of
1019
+ replies runs out. See [Empty or broken turns](docs/guides/errors-and-reliability.md#empty-or-broken-turns)
1020
+ and [The limits of a question](docs/guides/costs-and-limits.md#the-limits-of-a-question).
1021
+ - **Steps say more, on one line of plain text.** New steps say when a call was pointed to
1022
+ ("— already shown above"), when a turn was asked for again ("The model's first reply was empty:
1023
+ it was asked again", "The model's tool call could not be read: it was asked to send it again",
1024
+ "The model's answer was empty: it was asked again", "The model called a tool instead of
1025
+ answering: it was asked again for the answer"), and when a request was made smaller ("The
1026
+ request was larger than the model takes: older tool results were shortened, and it was sent
1027
+ again"). In the lines of `onStep`, `onActivity` and `result.steps`, a line break, a tab or another
1028
+ control character in what the model sent becomes one space, together with the blanks around it,
1029
+ and the characters that ingest drops from file text are dropped (see **Changed**), soft hyphens
1030
+ and byte order marks included. "](" becomes "] (", so that a markdown link or picture in what the
1031
+ model wrote stays text. A query is cut at 80 characters and a task at 100, never in the middle
1032
+ of a character. A call to a tool that does
1033
+ not exist is shown as `Call “do_magic” — failed: Unknown tool “do_magic”.`, with the name cut at
1034
+ 64 characters, and its activity line is `Call “do_magic”…`; 0.5.0 started the step with the
1035
+ whole name. The model gets `Unknown tool “do_magic”.`, and so does `files.tools().execute()`: it
1036
+ was `Unknown tool do_magic.`. Steps still quote the model's words, HTML tags and web addresses
1037
+ included.
1038
+ **What to do:** if you parse steps or match the unknown-tool error, allow for these changes. Show
1039
+ steps and activity lines as plain text, never as markdown or HTML. See
1040
+ [What the library logs](docs/security.md#what-the-library-logs).
1041
+ - **`anthropicToolTurns` and `openAiToolTurns` give a call without an ID a random one**
1042
+ (`toolu_` or `call_` and 24 hex characters). Gemini's calls, for one, may come without an ID.
1043
+ 0.5.0 numbered them from 1 on each call (`toolu_1_1`), so the stored rounds of two questions had
1044
+ the same IDs, which Claude's Messages API refuses. A call that came with an ID keeps it. In
1045
+ `anthropicToolTurns`, an ID the API would refuse is changed (see **Fixed**, The adapters).
1046
+ **What to do:** nothing, unless you compare these IDs, or convert the same tool turns again for
1047
+ each request: each conversion now gives new IDs. Convert once and store the messages when you
1048
+ need the same IDs every time. See
1049
+ [Histories in a provider's own form](docs/guides/conversations.md#histories-in-a-providers-own-form).
1050
+ - **A question stopped while its adapter is being called ends with the signal's reason.** When
1051
+ the signal aborts while the adapter is being called (from `onText`, say), `askWithFiles` now
1052
+ throws the signal's reason, as it does for every other way of stopping, whatever the adapter
1053
+ then does. When the adapter then failed with its own error, 0.5.0 threw that error (a 503, say);
1054
+ when it answered anyway, 0.5.0 returned its reply as the answer, with `answered: true`. The
1055
+ question also stops at once when the adapter does not look at the signal (see **Changed**).
1056
+ **What to do:** if a test expects the adapter's error, or its reply, there, expect the signal's
1057
+ reason.
1058
+
1059
+ Your own adapter or loop:
1060
+
1061
+ - **Your own adapter (optional).** An adapter written for 0.5.0 works as before. To get the new
1062
+ recovery, set `ModelReply.finish` (`"malformed_call"` lets the loop ask again for a call that
1063
+ could not be read), and throw a `ModelRequestError` from `send` and `generateText`. Its `kind`
1064
+ is told from the status and the message, or you pass it: `"context_overflow"` makes the request
1065
+ smaller (and a part read in halves), `"timeout"` with status 0 is sent again once, and
1066
+ `"quota"` is not sent again. In your own loop, `withRetry` follows the same rules: an error of
1067
+ kind `"quota"` or `"context_overflow"` is thrown at once, and one of kind `"timeout"` with
1068
+ status 0 is sent again once (not at all when `retry.retries` is 0). `ModelAdapter.estimateTokens`
1069
+ is now deprecated: the library never called it, and a later version may remove it. An adapter
1070
+ that declares it still compiles; leave it out, and set `capabilities.tokenScale` for a tokenizer
1071
+ that counts differently from the library's estimate. See
1072
+ [Your own adapter or loop](docs/guides/own-adapter-and-loop.md).
1073
+ - **If you call `parseSseJson` yourself.** It also reads the body of node-fetch and other async
1074
+ iterables, and takes `{ onData, onDone, signal, maxEventLength }` (see **New**); calls written
1075
+ for 0.5.0 compile as before. It now takes a CR alone for a line end, as the format allows (0.5.0
1076
+ threw a `SyntaxError` on such a stream). An event of more than 64,000,000 characters ends the
1077
+ stream with an `SseEventTooLongError`. And it no longer waits for the `cancel()` of the stream,
1078
+ or the `return()` of an iterable, when it stops.
1079
+ **What to do:** nothing, unless your stream can send one event of more than 64,000,000
1080
+ characters: then pass a larger `maxEventLength`, or `Infinity`.
1081
+
1082
+ Tests:
1083
+
1084
+ - **Tests that compare exact output need new expectations.** A test that pins what the library
1085
+ writes fails where 0.6.0 writes something else. The cases, each explained above or under
1086
+ **Changed**:
1087
+ - prompts: the tool guide, the description of `analyze_whole_document`, the frame of a file sent
1088
+ whole, and the card (`1 line`, `1 page`, the line on how a file that is not valid UTF-8 was
1089
+ read, and the line of a question without a whole-file read);
1090
+ - searches: up to `max_results` + 1 `matches`, the `note`, the `evidence`, and the description
1091
+ of `search_document`;
1092
+ - steps: the new steps, the cleaned text, the unknown tool, and "1 matching line", "1 passage",
1093
+ "1 part" and "1 more tool call in this turn was not run";
1094
+ - tool results: `already_shown`, `text_cut`, `notes_only` and `answer_shortened`, and the IDs
1095
+ listed with an unknown `document_id`;
1096
+ - fakes: a model with a fixed queue of replies gets one more request after an empty reply, a call
1097
+ that could not be read, or an answer without text, and none for a call repeated while its
1098
+ result is shown; a fake `fetch` given to `gemini()`, `openAiCompatible()` or `anthropic()` gets
1099
+ the request again when it never answers (after `firstByteTimeoutMs`; a second silence fails
1100
+ with kind `"timeout"`), when its stream ends without its end mark (Gemini's `finishReason`, a
1101
+ `finish_reason` or `[DONE]`, Claude's `stop_reason`) or is cut off, and when it answers HTTP 200
1102
+ with an empty body, but fails at once when part of the reply was already shown; a streamed
1103
+ reply that is not of type `text/event-stream` is read by what it holds; an adapter that fails,
1104
+ or answers, after the question was stopped gives the signal's reason;
1105
+ - errors: `error.cause instanceof SyntaxError` for a reply that is not JSON, the status and kind
1106
+ of an error inside a stream, the kinds of `classifyModelError` (a request larger than a minute
1107
+ allows is `{ kind: "context_overflow", limitTokens: 30000, requestedTokens: 45237 }`), and the
1108
+ reasons of a whole-file read that failed;
1109
+ - `geminiToolTurns`, `openAiToolTurns` and `anthropicToolTurns`: no `tool_turns_left`, and
1110
+ random IDs for calls without one; `anthropic().capabilities` with context editing in `body`:
1111
+ `clearsToolResults: true`; the body of a Gemini part read: no `temperature`;
1112
+ - ingest: the stored text of a file with characters that show nothing, text that Word hides, a
1113
+ hidden slide, or an older encoding; `owner: ""`; the 500 of an upload whose store fails; and
1114
+ `MemoryDocumentStore.getMeta(id)`, a new object each time, so `toBe` between two calls fails.
1115
+
1116
+ **What to do:** update those expectations. Compare steps and evidence to the tools that ran
1117
+ rather than to whole sentences, and leave the library's prompts out of what you compare whole,
1118
+ as [What to assert](docs/guides/testing.md#what-to-assert) advises. The testing guide shows the
1119
+ new forms in [Output that 0.6.0 changed](docs/guides/testing.md#output-that-060-changed).
1120
+
1121
+ If you ran main between 0.5.0 and 0.6.0:
1122
+
1123
+ - **Rounds that main stored, its ingest worker, and the kinds it gave.** Tool rounds that main
1124
+ stored can hold pointers (`already_shown: true`). A pointer to a search that lacks its last
1125
+ match, or to a read of one line from an earlier question, is now sent as the stand-in
1126
+ `Not run then: it repeated an earlier call whose result was later dropped from the conversation to make room. Call it again if you need it.`,
1127
+ and so is every pointer of an earlier question when the adapter sets `clearsToolResults`. The
1128
+ ingest worker of main's deployment guide (`ingestInWorker`), which set the heap flag in
1129
+ `NODE_OPTIONS`, did not hold its memory limit (see "One page of a PDF still holds the server"
1130
+ above, under Uploads). Some kinds differ from main's: HTTP 402, Claude's credit balance and
1131
+ spending limits, and a Vertex AI quota per day that only the message names are `"quota"` (they
1132
+ were `"invalid"` or `"rate_limit"`); a request larger than the tokens a minute allow is
1133
+ `"context_overflow"` (it was `"rate_limit"`); `insufficient_quota` inside an OpenAI-compatible
1134
+ stream is 429 `"quota"` (it was 500 `"server"`, sent three more times); Claude's errors inside a
1135
+ stream have their type's status (an `authentication_error` was `"invalid"`, and is `"auth"`);
1136
+ and a streamed Gemini reply that is a page of HTML is `"invalid"` (it was `"unreachable"`, sent
1137
+ three more times).
1138
+ **What to do:** nothing for stored rounds. Replace an ingest worker with the child process of
1139
+ `ingestInProcess` in [Deployment](docs/guides/deployment.md#uploads-and-ingest), and check code
1140
+ that chooses by these kinds.
1141
+
1142
+ ### New: what you can add
1143
+
1144
+ The samples assume what your app already has: `files` from `createLargeFiles()`, `endpoint` from
1145
+ `vertexAi()`, and the `documentIds` and `question` of the chat.
1146
+
1147
+ Errors and failed questions:
1148
+
1149
+ - **The kind of every model error.** `ModelRequestError` has `kind`, and so have the errors that
1150
+ extend it (`GeminiRequestError`, `OpenAiRequestError`, `AnthropicRequestError`):
1151
+ `"context_overflow"`, `"quota"`, `"rate_limit"`, `"timeout"`, `"unreachable"`, `"server"`,
1152
+ `"auth"` or `"invalid"`. It is told from the status, the message and the provider's own code
1153
+ (Gemini's `error.status` and `details`, OpenAI's `code`, Claude's `type`). For a request too
1154
+ large for the model, `limitTokens` and `requestedTokens` are the provider's numbers when its
1155
+ message gives them (the one Vertex AI sent in a live check gave only the limit).
1156
+ `errorKindOf(error)` reads the kind of any error,
1157
+ `classifyModelError(status, message, signals?)` tells it for errors of your own, and the types
1158
+ are `ModelErrorKind` and `ModelErrorClass`. The constructor of each error class takes `kind`,
1159
+ `code` and `details`. See
1160
+ [The kind of a model error](docs/guides/errors-and-reliability.md#the-kind-of-a-model-error) and
1161
+ [`ModelErrorKind`](docs/reference/errors-and-retries.md#modelerrorkind).
1162
+ - **What a failed question found: `partialResultOf(error)`.** The question still throws the
1163
+ provider's error. `partialResultOf(error)` gives what it had done until then, as an `AskResult`
1164
+ with `answered: false`: its steps, evidence, tool rounds and usage. It is undefined for an error
1165
+ thrown before the question started (a document that is missing). Exported from
1166
+ `llm-large-files` and `llm-large-files/gemini`. See
1167
+ [`partialResultOf(error)`](docs/reference/ask.md#partialresultoferror) and
1168
+ [Keeping what a failed question found](docs/guides/errors-and-reliability.md#keeping-what-a-failed-question-found).
1169
+
1170
+ ```ts
1171
+ import { errorKindOf, partialResultOf } from "llm-large-files";
1172
+ import { askGemini } from "llm-large-files/gemini";
1173
+
1174
+ try {
1175
+ const result = await askGemini({ files, endpoint, documentIds, messages: [{ role: "user", text: question }] });
1176
+ console.log(result.text);
1177
+ } catch (error) {
1178
+ const partial = partialResultOf(error);
1179
+ // Not an answer, but paid for: count its usage, and keep its tool rounds if you store them.
1180
+ if (partial) console.log(partial.usage.requests, partial.usage.inputTokens, partial.toolTurns.length);
1181
+ const kind = errorKindOf(error);
1182
+ if (kind === "quota") console.log("The model's quota is used up. Try again later.");
1183
+ else if (kind === "timeout" || kind === "rate_limit") console.log("The model did not answer. Try again in a minute.");
1184
+ else throw error; // another kind, or not a model error (a missing document, a bug)
1185
+ }
1186
+ ```
1187
+
1188
+ ```ts
1189
+ import { classifyModelError } from "llm-large-files";
1190
+
1191
+ classifyModelError(400, "This model's maximum context length is 128000 tokens. However, your messages resulted in 130512 tokens.");
1192
+ // { kind: "context_overflow", limitTokens: 128000, requestedTokens: 130512 }
1193
+ ```
1194
+
1195
+ - **Waits on a silent model: `firstByteTimeoutMs` and `idleTimeoutMs`**, on `askGemini`,
1196
+ `gemini()`, `openAiCompatible()` and `anthropic()`. The defaults are the new exports
1197
+ `DEFAULT_FIRST_BYTE_TIMEOUT_MS` (600,000) and `DEFAULT_IDLE_TIMEOUT_MS` (300,000); the type
1198
+ `IdleWaits` holds the two options. See
1199
+ [Waits on a silent model](docs/guides/errors-and-reliability.md#waits-on-a-silent-model) and
1200
+ [`IdleWaits`](docs/reference/errors-and-retries.md#idlewaits).
1201
+
1202
+ ```ts
1203
+ import { askGemini } from "llm-large-files/gemini";
1204
+ import { openAiCompatible } from "llm-large-files/openai";
1205
+
1206
+ // A chat that streams to a user: give up sooner than the defaults.
1207
+ const result = await askGemini({
1208
+ files,
1209
+ endpoint,
1210
+ documentIds,
1211
+ messages: [{ role: "user", text: question }],
1212
+ firstByteTimeoutMs: 180_000, // the first piece of a reply within 3 minutes
1213
+ idleTimeoutMs: 60_000, // then no pause longer than 1 minute
1214
+ onText: (delta) => process.stdout.write(delta),
1215
+ });
1216
+
1217
+ // A local model that reads a long prompt slowly: wait for its first piece without end.
1218
+ const local = openAiCompatible({ baseUrl: "http://localhost:8000/v1", model: "local-model", firstByteTimeoutMs: 0 });
1219
+ ```
1220
+
1221
+ - **`RetryNotice`**: the type of what `withRetry` passes to `onRetry`: `error`, `attempt` (the
1222
+ number of the retry to come) and `delayMs` (the wait). 0.5.0 passed the same notice but did not
1223
+ export its type. See
1224
+ [Errors, retries and streams](docs/reference/errors-and-retries.md#retrynotice).
1225
+ - **`OpenAiRequestError.param` and `.code`**: the server's `error.param` (`"max_tokens"`) and
1226
+ `error.code` (`"unsupported_parameter"`, `"context_length_exceeded"`). See
1227
+ [`OpenAiRequestError`](docs/reference/openai.md#openairequesterror).
1228
+
1229
+ Your own adapter or loop:
1230
+
1231
+ - **`ModelReply.finish`**: how a reply ended, in terms every adapter maps its own to:
1232
+ `"complete"`, `"cut"` (at the output limit, or Claude's full window), `"filtered"` (by the
1233
+ provider's safety filters) or `"malformed_call"` (a tool call that could not be read: Gemini's
1234
+ `MALFORMED_FUNCTION_CALL` and `UNEXPECTED_TOOL_CALL`). The three adapters set it. See
1235
+ [`ModelReply`](docs/reference/ask.md#modelreply) and
1236
+ [How the reply ended](docs/guides/own-adapter-and-loop.md#how-the-reply-ended-finish).
1237
+ - **`ModelCapabilities.clearsToolResults`**: for an adapter whose provider may clear old tool
1238
+ results on its side. A call made again is then run again, not answered with a pointer to a
1239
+ result the model may no longer have, and the pointers in stored rounds become stand-ins that say
1240
+ to call again. `anthropic()` sets it when `body.context_management` has an edit that clears tool
1241
+ uses (`clear_tool_uses_…`) or compacts the conversation (`compact_…`). The loop still counts
1242
+ every result as sent, so its room runs out at the same point as without context editing. An
1243
+ adapter of your own sets it itself. See [`ModelCapabilities`](docs/reference/ask.md#modelcapabilities).
1244
+ - **`ToolCallLimits.maxRequests`**: the model requests a whole-file read may make. It does not
1245
+ stop the read: a part the model refuses as too large is read as two halves only while it allows.
1246
+ `askWithFiles` passes the read's own requests and a share of what the question has left of
1247
+ `limits.requests`; in your own loop, pass it to `executeWithFiles`. See
1248
+ [Tools](docs/reference/tools.md#toolcalllimits).
1249
+ - **`PrepareOptions.wholeDocumentAnalysis`**: whether your tool set has `analyze_whole_document`.
1250
+ Defaults to `true`. In your own loop, pass `wholeDocumentAnalysis: false` to `files.prepare()`
1251
+ when you call `files.tools()` without `generate`: the tool guide then does not name the tool,
1252
+ and the cards do not offer a whole-file read. See
1253
+ [The library and its documents](docs/reference/library.md#prepareoptions).
1254
+ - **`SseHooks`**: the second argument of `parseSseJson`: `onData` (bytes arrived, keep-alives
1255
+ included), `onDone` (`data: [DONE]` arrived), `signal`, and `maxEventLength`, the most
1256
+ characters one event may hold, counted on its data. It defaults to 64,000,000; `Infinity` sets
1257
+ no limit. A longer event ends the stream with an `SseEventTooLongError`
1258
+ (`An event of the stream held more than 64,000,000 characters.`), whose `limit` holds the limit.
1259
+ The class is exported from `llm-large-files` and `llm-large-files/gemini`. The same event would
1260
+ come again, so an adapter of your own should not send the request again for it. See
1261
+ [`SseHooks`](docs/reference/errors-and-retries.md#ssehooks).
1262
+
1263
+ Uploads:
1264
+
1265
+ - **`maxTextBytes`**: the most text kept from one file, in UTF-8 bytes. Defaults to
1266
+ `DEFAULT_MAX_TEXT_BYTES`, 100 MB, or to `maxUploadBytes` when that is larger. The PDF, DOCX and
1267
+ PPTX extractors refuse a file as soon as its text passes it (a PDF page by page), and `ingest`
1268
+ refuses a larger text from any other extractor, yours included. See
1269
+ [`LargeFilesOptions`](docs/reference/library.md#largefilesoptions).
1270
+ - **`maxPdfPages`**: the most pages read from one PDF. Defaults to `DEFAULT_MAX_PDF_PAGES`, 5,000.
1271
+ A PDF with more is refused before any page is read. See
1272
+ [the library reference](docs/reference/library.md#default_max_pdf_pages).
1273
+ - **`ingestTimeoutMs`**: the most time one `ingest` may take. Defaults to
1274
+ `DEFAULT_INGEST_TIMEOUT_MS`, 120,000 (2 minutes); 0 sets no limit, and so does a value past
1275
+ what a timer can wait (2,147,483,647 ms, 24.8 days). See
1276
+ [`LargeFilesOptions`](docs/reference/library.md#largefilesoptions).
1277
+ - **`IngestInput.signal`**: stops an ingest, for example when the uploader goes away. `ingest`
1278
+ throws the signal's `reason` and stores nothing. The PDF, DOCX and PPTX extractors stop between
1279
+ pages and pieces, and the text extractor between the steps of a file that is not valid UTF-8.
1280
+ `createDocumentHandlers` passes one that aborts when the client closes the connection. See
1281
+ [`IngestInput`](docs/reference/library.md#ingestinput).
1282
+ - **`ExtractInput.signal`, `ExtractInput.maxTextBytes` and `ExtractInput.maxPages`**: the signal
1283
+ of the ingest (aborted at `ingestTimeoutMs` or by `IngestInput.signal`) and the two limits, for
1284
+ an extractor of your own to honour. See
1285
+ [Custom extractors](docs/guides/pdfs.md#custom-extractors).
1286
+ - **`createPdfExtractor({ checkPages: false })`** turns the page check off. With
1287
+ `pictures: false` too, PDFs are not read with `@cantoo/pdf-lib` at ingest. See
1288
+ [`PdfExtractorOptions`](docs/reference/library.md#pdfextractoroptions).
1289
+ - **`DocumentMeta.encoding` and `DocumentMeta.replacedCharacters`**, and the same two fields of
1290
+ `DocumentSummary` and `ExtractedText`: how a text file that is not valid UTF-8 was read.
1291
+ `encoding` is the older encoding the file was read in, as TextDecoder names it
1292
+ (`"windows-1255"`); lines of the file that are valid UTF-8 were read as UTF-8 all the same.
1293
+ `replacedCharacters` is the number of characters that were not valid in the encoding the file
1294
+ was read in (UTF-8, or `encoding`), each stored as U+FFFD. Both are absent for valid UTF-8, for
1295
+ UTF-16, PDF, DOCX and PPTX, and on documents stored before 0.6.0; `encoding` is absent too for a
1296
+ file read as UTF-8 with characters that are not valid. `toDocumentSummary` passes them on, so
1297
+ the upload route of `createDocumentHandlers` answers with them. An extractor of your own may
1298
+ report them in `ExtractedText`: `encoding` is kept when it is a name, such as `iso-8859-2`, other
1299
+ than UTF-8 or UTF-16, and `replacedCharacters` when it is a whole number above 0. See
1300
+ [`DocumentMeta`](docs/reference/library.md#documentmeta).
1301
+
1302
+ ```ts
1303
+ import type { ServerResponse } from "node:http";
1304
+ import { createLargeFiles, FileDocumentStore, type DocumentMeta } from "llm-large-files";
1305
+
1306
+ const files = createLargeFiles({
1307
+ store: new FileDocumentStore("./data/large-files"),
1308
+ maxTextBytes: 50 * 1024 * 1024, // keep at most 50 MB of text from one file
1309
+ maxPdfPages: 2_000, // refuse a longer PDF before reading a page of it
1310
+ ingestTimeoutMs: 60_000, // give up on a file after one minute
1311
+ });
1312
+
1313
+ // In an upload route of your own: stop reading the file when the uploader goes away.
1314
+ async function ingestUpload(response: ServerResponse, name: string, bytes: Uint8Array, owner: string): Promise<DocumentMeta> {
1315
+ const uploaderLeft = new AbortController();
1316
+ response.on("close", () => uploaderLeft.abort(new Error("The upload was cancelled.")));
1317
+ const meta = await files.ingest({ name, bytes, owner, signal: uploaderLeft.signal });
1318
+ // Tell the user how a file that was not in UTF-8 was read.
1319
+ if (meta.encoding) console.log(`${meta.name} was read as ${meta.encoding}.`);
1320
+ if (meta.replacedCharacters) console.log(`${meta.replacedCharacters} characters of ${meta.name} show as �.`);
1321
+ return meta;
1322
+ }
1323
+ ```
1324
+
1325
+ ### Changed: what works differently
1326
+
1327
+ Besides the points under **Upgrading**:
1328
+
1329
+ The tool loop:
1330
+
1331
+ - **A request too large for the model is made smaller and sent again**, where 0.5.0 failed the
1332
+ question. The loop takes the provider's count and window for the rest of the question,
1333
+ replaces older tool results with short stand-ins (the latest round too, if it must), and sends
1334
+ the request again, at most twice a question. When the first requests are too large before any
1335
+ tool ran, the documents are planned again, once, for a smaller window worked out from the
1336
+ provider's numbers, or 7/10 of the window assumed when it gives none. Vertex AI's message names
1337
+ 1,048,576 tokens and no count: with the default window of 1,000,000, the documents are planned
1338
+ for 838,860. What the first try paid for, and the tool turns it took, are counted. When Claude is
1339
+ one of the models, nothing is shortened (its conversation may only grow), so only the second
1340
+ plan applies. The wordings known include those of Text Generation Inference and Together, LM
1341
+ Studio, Amazon Bedrock and vLLM, besides Gemini's, OpenAI's and Claude's. See
1342
+ [A request too large for the model](docs/how-it-works.md#a-request-too-large-for-the-model).
1343
+ - **Two searches in a row that failed in the same mode** get a hint added to the error: after two
1344
+ regex searches, to try exact or keywords mode; after two of another mode, to check the arguments
1345
+ or answer from what the model has.
1346
+ - **An unknown `document_id`** is answered with the IDs the model may use, and their file names
1347
+ (up to 20). An ID longer than 64 characters is quoted cut, in the error and in its step.
1348
+ - **The tool guide, and the description of `analyze_whole_document`, send counting and listing to
1349
+ exact search.** Both sent "every occurrence" to `analyze_whole_document`, which missed items in
1350
+ our live tests (492 of 1,200; 91 of 120), while `search_document` in exact or regex mode gives
1351
+ an exact `total_matching_lines`. The whole-file read is now for what needs meaning: a summary, a
1352
+ timeline, items judged one by one. See [The tool guide](docs/reference/tools.md#the-tool-guide)
1353
+ and [`analyze_whole_document`](docs/reference/tools.md#analyze_whole_document).
1354
+ - **In `askWithFiles` and `askGemini`, the tool guide names `analyze_whole_document`, and the
1355
+ cards offer a whole-file read, only when the question has the tool.** With
1356
+ `wholeDocumentAnalysis: false`, or a model that explores without `generateText`, they still
1357
+ offered a whole-file read when a file was small enough for one, and a model that called it was
1358
+ answered "Unknown tool analyze_whole_document.". Each card now says "Use the document tools to
1359
+ search it and to read line ranges.", and the guide leaves the tool's line out. In your own loop,
1360
+ pass `wholeDocumentAnalysis: false` to `files.prepare()` for the same (see **New**). See
1361
+ [Tools](docs/reference/tools.md#which-tools-are-offered).
1362
+ - **A part of a whole-file read that the model refuses as too large is read as two halves**,
1363
+ while `maxMapChunks` and the requests the question has left allow it.
1364
+ - **A part that the provider stopped before its end is said to be incomplete**, as one cut off at
1365
+ the output limit is: Gemini's `SAFETY` and its other filter reasons, OpenAI's `content_filter`,
1366
+ Claude's `refusal`, and Claude's `model_context_window_exceeded` (its window was full).
1367
+ - **Tool results have new fields**: `already_shown` (a pointer), `text_cut` (a `read_document`
1368
+ whose text was cut to its room), and, on a whole-file read, `notes_only` and
1369
+ `answer_shortened` (see **Fixed**). The step of a whole-file read that returned its notes ends
1370
+ in ", notes only". See [Tools](docs/reference/tools.md).
1371
+ - **A question stops when its signal aborts, even with an adapter that does not.** The loop no
1372
+ longer waits for an adapter (or a part reader of a whole-file read) that does not look at
1373
+ `signal`. With 0.5.0, an adapter whose request never ended held the question for good after an
1374
+ abort. `askWithFiles` now throws the signal's reason at once (310 ms after an abort at 300 ms),
1375
+ also when `onText` stopped it or when it was stopped between two requests, with
1376
+ `partialResultOf`; nothing is sent after the stop, no further part of a whole-file read either;
1377
+ and text that such an adapter sends later is not shown. `partialResultOf(error).usage` is what
1378
+ was counted when the question stopped: a request still running then may be billed by the
1379
+ provider, and is not counted. See [Cancelling](docs/guides/web-app.md#cancelling).
1380
+ - **`geminiFunctionResponses` returns a `GeminiContent & { role: "user" }`, and
1381
+ `geminiFunctionResponseTurns` an array of them**, which go into a `GeminiContent[]` without a
1382
+ cast. Their parts were typed `unknown[]` (see **Upgrading**). See
1383
+ [`llm-large-files/gemini`](docs/reference/gemini.md#geminifunctionresponsescalls).
1384
+
1385
+ Ingest:
1386
+
1387
+ - **Ingest lets other requests run while it reads a file.** Each step works in slices of about
1388
+ 12 ms, with a pause for other requests between two slices: the PDF extractor between pages, the
1389
+ DOCX and PPTX extractors as they unpack, the text extractor as it reads a file that is not valid
1390
+ UTF-8, and then `ingest` as it cleans the text, measures it, and builds the outline, the log
1391
+ profile and the line index. Ingests that run at once take turns, one slice each. Picture marks
1392
+ pause every 12 ms between pages, and their limit of 5 s counts only the work, not the pauses. An
1393
+ ingest of a 99 MB log takes 1.9 s, as before, now in slices.
1394
+ - **`createDocumentHandlers` stops reading an upload when the client goes away.** Its upload
1395
+ handler passes `IngestInput.signal`, aborted when the connection closes before the answer is
1396
+ sent: nothing is stored.
1397
+ - **`ingest` stops waiting for an extractor** when the ingest's signal aborts (`ingestTimeoutMs`,
1398
+ or `IngestInput.signal`), whether or not the extractor looks at the signal.
1399
+ - **DOCX and PPTX take memory by their text, not by their XML.** Each paragraph becomes one string
1400
+ when it closes, and an empty paragraph is dropped. Text is counted as it reads, not as the XML
1401
+ writes it (`&amp;` is one character).
1402
+ - **`view_pages` and picture marks pause by time.** `@cantoo/pdf-lib` reads the whole file into
1403
+ objects first, and on its own pauses for other requests after a count of objects: 0.5.0 used
1404
+ 4,000, which took 0.5 to 0.8 s in a large file, while a file of fewer objects never paused. It
1405
+ now pauses after every 12 ms of work (up to 40 ms on Windows, where a pause takes about 15 ms).
1406
+ Measured on Windows with Node 24: a file of 4,000 large arrays held the event loop for 28 to
1407
+ 32 ms at a time, and a 2,000-page PDF 19 to 38 ms. A whole read takes 0.91 to 0.96 s for a file
1408
+ of 61,000 small objects and 1.35 to 1.43 s for one of large objects, against 1.65 to 1.87 s and
1409
+ 1.13 to 1.22 s with a pause every 500 objects; 0.5.0's pause every 4,000 was not timed this way.
1410
+ Your app's own use of `@cantoo/pdf-lib` is not changed.
1411
+ - **The model is told how a text file that is not valid UTF-8 was read.** The card of a large
1412
+ file gets one more line:
1413
+ `This file is not in UTF-8. Its text was read as windows-1255: if its letters look wrong, ask the user to save it as UTF-8.`
1414
+ When bytes of the file are not in that encoding, the line goes on:
1415
+ ` 1 character of it was not valid in windows-1255, and shows as �.` For a file read as UTF-8
1416
+ with characters that are not valid, the line is
1417
+ `3 characters of this file were not valid UTF-8, and show as �.`
1418
+ The first line of the frame of a file sent whole says the same in short, after the count of
1419
+ lines: `, read as windows-1255`, `, read as windows-1255, 1 character not valid in it, shown as �`,
1420
+ or `, 3 characters not valid UTF-8, shown as �`. A file that is valid UTF-8 or UTF-16 gets no
1421
+ such line. See [The card](docs/how-it-works.md#the-card).
1422
+ - **A text file that is not valid UTF-8 is read in slices,** with pauses for other requests, and
1423
+ it stops when the ingest's signal aborts. Reading it takes about twice as long as 0.5.0's decode,
1424
+ which gave U+FFFD: 0.27 to 0.28 s against 0.11 to 0.16 s for a 30 MB CSV in windows-1255, in
1425
+ steps of 15 ms at most. A file whose lines take turns between UTF-8 and an older encoding takes
1426
+ longer, the shorter its lines are: for 30 MB, 0.50 to 0.53 s in lines of 100 bytes, and 2.1 to
1427
+ 2.2 s in lines of one letter (Node 24, Windows). See
1428
+ [Text encodings](docs/guides/pdfs.md#text-encodings).
1429
+ - **Ingest removes characters that show nothing** from the text: control characters
1430
+ U+0080-U+009F, which 0.5.0 kept (a U+0085 can become a line break instead; see the next point),
1431
+ and an escape sequence that starts with U+009B, such as `\u009b31m`, whole (0.5.0 stored
1432
+ `x\u009b31mERROR` as it was; it is now `xERROR`), but for a U+009B right after a character of
1433
+ U+0080-U+00FF, which is the end of a letter of UTF-8 read as Latin-1 ("ś" is C5 9B) and goes
1434
+ alone ("Coś? Tak" keeps its "? Tak"); Unicode tag characters
1435
+ (U+E0000-U+E007F); the text-direction controls that reorder what a person sees (U+202A-U+202E,
1436
+ U+2066-U+2069); the zero-width space, the word joiner and the invisible operators (U+200B,
1437
+ U+2060-U+2064); the deprecated format characters (U+206A-U+206F); a byte order mark inside the
1438
+ text; and the soft hyphen, except at the end of a line. Kept: the marks right-to-left text needs
1439
+ (U+200E, U+200F, U+061C), zero-width joiners and non-joiners (emoji, Persian), variation
1440
+ selectors, and the flags of England, Scotland and Wales; other flags written with tag characters,
1441
+ such as Texas, keep only the black flag. A file name loses the same characters, but its control
1442
+ characters and text-direction controls become a space, as in 0.5.0. Of these
1443
+ removals, two move lines: in a text with no line feed, where U+0085 ends lines, and after a line
1444
+ of more than 2,000 characters that lost some of them, which can now be cut into fewer lines;
1445
+ hidden text in a DOCX moves lines too (below). A file read as 0.5.0 read it that holds none of
1446
+ these characters, and has no hidden text or hidden slide, is stored as before, byte for byte (25
1447
+ inputs compared, 12 PDFs among them). Cleaning takes 2 to 7% longer on an ASCII log, and 10 to
1448
+ 20% on Hebrew in UTF-8; a whole ingest did not take longer beyond the spread of runs. See
1449
+ [Characters that show nothing](docs/security.md#characters-that-show-nothing).
1450
+ - **U+0085 ends a line in a text that has no other line break.** Some files end each record with
1451
+ U+0085 (NEXT LINE) and contain no line feed, such as z/OS data converted to UTF-8 with iconv
1452
+ (IBM-1047). 0.5.0 stored such a file as one line, with the U+0085 characters in it. Each record
1453
+ is now a line of its own, and an empty record is dropped. A record that ends in a character of
1454
+ U+0080-U+00FF, such as É, ° or £, still runs into the next one: there a U+0085 is taken for the
1455
+ last byte of a UTF-8 letter read as Latin-1 ("ą" is C4 85), and removed. A file of one line,
1456
+ such as minified JSON, has no other line break either, so a U+0085 inside one of its strings
1457
+ becomes a line break too. In a text with other line breaks, a U+0085 is removed with the other
1458
+ C1 control characters. The same export in ISO-8859-1, with a byte 0x85 at the end of each
1459
+ record, is read as windows-1252, where 0x85 is "…", and stays one long line, cut every 2,000
1460
+ characters: convert such a file to UTF-8 instead.
1461
+ - **Text that Word hides is marked.** The text of a run hidden in Word (`<w:vanish/>`) was stored
1462
+ as ordinary text. It now comes after the text of its paragraph that shows, and each of its lines
1463
+ starts with `[Hidden text, not shown in the document]`, so that the model can tell it from what
1464
+ a reader sees; a line break in it starts a new marked line, and a line longer than about 1,950
1465
+ characters is cut into pieces, each marked. The marks count toward `maxTextBytes` and the 32
1466
+ million characters of a DOCX. The mark is a hint, not a filter: text hidden through a style,
1467
+ white or 1-point text, and a few rarer forms are read as ordinary text, and a document's own
1468
+ text can write the mark. See
1469
+ [Hidden text in Word and PowerPoint](docs/security.md#hidden-text-in-word-powerpoint-and-html).
1470
+ - **A hidden slide says so.** The heading of a slide that the slide show skips (`show="0"`) reads
1471
+ `## Slide 2 (hidden, not shown in the slide show)`. Its text is kept. Shapes hidden on a slide
1472
+ that shows are read as ordinary text. See [DOCX and PPTX](docs/guides/pdfs.md#docx-and-pptx).
1473
+ - **`MemoryDocumentStore` copies the metadata** it is given and the metadata it hands out, as a
1474
+ store that writes it somewhere does. `getOriginal` still returns the kept bytes themselves: treat
1475
+ them as read-only. See [`MemoryDocumentStore`](docs/reference/library.md#memorydocumentstore).
1476
+
1477
+ The adapters:
1478
+
1479
+ - **A request sent again after its reply was cut off on its way says so.** `onActivity` gets
1480
+ "The model's reply was cut off on its way. Trying again…" for a stream that closed before its
1481
+ end, a connection that failed once the reply had begun, or a reply of HTTP 200 that came empty.
1482
+ "The model could not be reached. Trying again…" stays for a connection that failed before any
1483
+ reply.
1484
+ - **A reply asked for as a stream is read by what it holds when its content type is not
1485
+ `text/event-stream`.** It is read as events when it starts like them (a field such as `data:`,
1486
+ or a comment), and as JSON when it starts with `{` or `[`. A body that starts with more than
1487
+ 65,536 characters of white space is read as JSON, whatever follows it. A gateway that streams
1488
+ under `application/octet-stream`, or under no type, failed with a `SyntaxError` on the
1489
+ OpenAI-compatible and Claude adapters. Gemini's chunks in a list, as it sends them without
1490
+ `alt=sse`, are read too. See
1491
+ [A stream cut off](docs/guides/errors-and-reliability.md#a-stream-cut-off).
1492
+ - **Claude: `x-should-retry: false` is followed.** A request that the API says not to try again is
1493
+ not sent again, whatever its status, as Anthropic's own SDKs do.
388
1494
 
389
1495
  ### Fixed
390
1496
 
391
- - **Token estimates were far too low for logs and data files.** `estimateTokens` assumed 4
392
- characters per token, which holds for prose only: Gemini counts about one token per digit. A
393
- service log was estimated at 37% of its real size and a CSV of numbers at 26%, so such files were
394
- sent whole, and split into parts, at about three times the configured budget. The estimate now
395
- prices each kind of character and was fitted to Gemini's `countTokens` on 60 texts; it lands
396
- between 0.98 and 1.7 times the real count. Documents already in a store keep the estimate they
397
- were ingested with until they expire.
398
- - **A regex search could freeze the server.** Patterns such as `((a+))+$` and `(a|a)+$` passed the
399
- nested-quantifier check and never finished on a 40-character line; the 3-second limit was only
400
- checked between lines. Regex scans now run under a hard time limit that interrupts a match in
401
- progress.
402
- - **`askGemini` could return a remark instead of an answer.** If the model wrote "Let me search…"
403
- with a tool call and its next turn came back empty (cut off, or a malformed tool call), that
404
- remark was returned as the answer. The tool-free request is now sent whenever the model's last
405
- turn has no text.
406
- - **A blocked prompt resolved as an empty answer with no reason.** The result now has
407
- `answered: false` and `blockReason`.
408
- - **One model request was wasted when the tool turns ran out.** The last request was sent with
409
- tools, its calls were discarded, and then another was sent without tools. `askGemini` now goes
410
- straight to the tool-free request, so it never makes more than `maxToolTurns` requests.
411
- - **Case-insensitive search found nothing in a file containing "İ"** (U+0130), in exact and
412
- keyword mode: the whole file silently fell back to case-sensitive matching.
413
- - **Coloured logs lost their profile.** Only the ESC byte of a terminal colour code was removed,
414
- leaving `[31mERROR[0m`, which no longer matched as a level. Whole escape sequences are removed.
415
- - **Compressed files were accepted as text.** A `.gz` log became a document of garbage. Gzip and
416
- ZIP files are refused with a message that says what to do, and other binary files without zero
417
- bytes are now detected too.
418
- - **Ingest failed with "Maximum call stack size exceeded"** on files with a few hundred thousand
419
- short heading-like lines.
420
- - **A file name could add lines to the prompt.** Control characters, line breaks, and
421
- text-direction overrides are removed from names at ingest, and names are quoted in the system
422
- instruction.
423
- - **Whole-document reads hid that they were incomplete.** When part notes or the final answer
424
- reach the output limit, the tool result now says so (`notes_cut_short`, `answer_cut_short`, and a
425
- `note` telling the model to say so and to use exact search for complete lists). If no part can be
426
- read, the tool returns an error instead of an answer written from nothing.
427
- - `read_document` reported a line range past the end of the file when no end line was given.
428
-
429
- - **Words of right-to-left text in a PDF were glued together** when the file stores them piece by
430
- piece (as Word does): `יתרת סגירה4,167.90`. pdf.js adds the space only between pieces that run
431
- left to right. The space is now added from the positions.
432
-
433
- ### Changed
434
-
435
- - **PDF tables are rebuilt.** A PDF stores text at positions, not tables. In file order, a row
436
- with an empty cell reads like a row without that column, so a model takes the next value for the
437
- missing one. The PDF extractor now finds tables by the position of their text and writes each
438
- row as `| cell | cell | | cell |`. In a live test (`gemini-3.5-flash-lite`, 110 questions about
439
- single cells of seven PDFs made by Word and Chrome), 44 answers were right from the old text and
440
- 110 from the new. It also handles tables in one column of a two-column page, right-to-left and
441
- sideways tables, headings that span columns, and wrapped cells; text that is not a table is left
442
- as it was. Two-column tables are left as text. See
443
- [PDF tables](docs/configuration.md#pdf-tables) for the limits.
444
- `createPdfExtractor({ tables: false })` gives the previous text. Documents already in a store
445
- keep the text they were ingested with.
446
- - **A PDF page without any text is marked** `[No text on this page. It may be a scan, a photo, or a
447
- chart.]` instead of being left empty, so the model can say that it cannot see the page.
448
- - **Documents are placed at the start of the first user turn**, not appended to the latest one.
449
- The document then stays in the same place as the conversation grows, so Gemini's prompt cache
450
- reuses it: in a live test, a follow-up question about a 53,000-token document had 96% of its
451
- input served from cache, against 0% before. Pass `documentPlacement: "last"` to `askGemini` for
452
- the previous layout.
453
- - `maxToolTurns` is now the most requests one question can make, counting the answer. Tools still
454
- run in at most `maxToolTurns - 1` of them, as before.
455
-
456
- ### Added
457
-
458
- - `createPdfExtractor({ tables })`, exported from the main entry point.
459
- - `AskGeminiResult.answered` and `AskGeminiResult.blockReason`.
460
- - `GenerateText` requests carry an optional `onTruncated` callback; `createGeminiGenerateText`
461
- calls it when Gemini stops at `MAX_TOKENS`.
462
-
463
- ## [0.1.0] - 2026-11-06
464
-
465
- First release, extracted from the large-file support in the Gemini Prep chatbot.
466
-
467
- ### Added
468
-
469
- - `createLargeFiles`: ingest, per-request planning against a token *and* byte budget, summary
470
- cards, and scoped tools (`search_document`, `read_document`, `get_document_overview`,
471
- `analyze_whole_document`).
472
- - Extraction for text, Markdown, logs (UTF-8/UTF-16), JSON/JSONL, CSV/TSV, DOCX and PPTX (optional
473
- `jszip`), and PDF (optional `unpdf`).
474
- - Log profiles (levels, time range, most frequent error shapes) and outlines for books and documents.
475
- - Map-reduce over whole documents with parallel part reads, a retry, and rounds of merging.
476
- - `MemoryDocumentStore` and `FileDocumentStore` with expiry.
477
- - Document owners: documents are private to the user who uploaded them.
478
- - `llm-large-files/gemini`: `askGemini` (streaming tool loop that always ends in an answer),
479
- `geminiApi` and `vertexAi` endpoints, and lower-level adapters.
480
- - `llm-large-files/node`: upload, get, and delete handlers for any Node HTTP server.
1497
+ Uploads you do not trust (the numbers before were measured on main at 5157e7f, whose ingest, PDF
1498
+ and Office code is that of 0.5.0):
1499
+
1500
+ - **A DOCX of 1.5 MB no longer stops a server with a heap of 512 MB.** It held 120 MB of empty
1501
+ paragraphs, each of which 0.5.0 kept until the end of the file: the process ran out of memory
1502
+ and stopped, and every answer streaming on it with it. The same file is now refused
1503
+ ("padded.docx did not contain any text.") in 3.0 to 3.2 s, with the process at 115 MB. A DOCX
1504
+ of 3 MB that unpacks to 1,000 MB of XML, which stopped the same server, is refused at its
1505
+ millionth paragraph in 0.9 s, at 165 MB.
1506
+ - **A DOCX of many parts, or with a list of parts built to exhaust JSZip, no longer stops the
1507
+ server.** 0.5.0 had no limit on the parts of an Office file: 300,000 empty parts took over
1508
+ 500 MB in JSZip, and a DOCX of 88 MB with a million parts ran a heap of 1.5 GB out of memory.
1509
+ The parts are now counted, and the list read, before JSZip reads it, as JSZip will read it.
1510
+ Unicode Path fields that ran over the records after them ran a heap of 256 MB out of memory from
1511
+ a DOCX of 0.17 MB, and a ZIP64 end record of a file of 636 bytes held the process until it was
1512
+ killed. Such files are refused in 40 to 90 ms, with the heap at 8 to 9 MB. Real files are read
1513
+ as before (245 ZIP files of Office, Java and other programs compared), and a DOCX just under
1514
+ every limit at once is read in 0.46 to 0.48 s. See [Measurements](docs/measurements.md#the-server).
1515
+ - **A PDF of a few KB no longer stores 100 MB of text, or holds the server for minutes.** These
1516
+ files are now refused, each in under 0.3 s:
1517
+ - a page tree that lists one dense page 150 times (3 KB, 107 MB of text) or 600 times (6 KB:
1518
+ it held the event loop for 205 s with a heap of 1.5 GB, and ran a heap of 512 MB out of
1519
+ memory);
1520
+ - 140 pages that all paint one dense content stream (23 KB, 99.5 MB of text), and 60 pages that
1521
+ all show one stream of 4 MB (25 KB, 1.3 s a page, 38 s in all);
1522
+ - a page that paints a form that paints the next one 50 or 100 times, three levels deep (3 KB,
1523
+ 13 s, 350 to 380 MB; 4 KB, about 100 s), files of 2 to 21 KB built the same way, 2 to 6 levels
1524
+ deep (17 s to 2 minutes), eight forms that each paint all eight (6 s), and forms painted from
1525
+ content that only pdf.js could decode (10 s);
1526
+ - a page that runs 160 MB of text operators packed 250 times (650 KB, 23 to 29 s), and three
1527
+ pages that each run 40 MB (160 KB, 6 to 14 s at a time);
1528
+ - a Type3 font whose one glyph paints a form 390,000 times, which pdf.js ran when a page set the
1529
+ font (3 KB, 9 s at 730 MB).
1530
+
1531
+ All but the first need `@cantoo/pdf-lib` installed (the page check, under **Upgrading**);
1532
+ without it, the 23 KB file is refused at 16 MB of text, in under 6 s. Two forms that paint each
1533
+ other are read, as pdf.js reads them.
1534
+ - **A large upload no longer holds the server while it is read.** An ingest held the event loop
1535
+ for most of its time, and every answer streaming on that server stopped with it. Measured on one
1536
+ machine (Node 24, Windows), three times each, the longest gap of a 5 ms timer during the ingest
1537
+ of a 99 MB log went from 1.9 to 2.0 s down to 31 to 34 ms, and of a 2,000-page PDF from 4.4 to
1538
+ 4.5 s down to 0.16 s. The log took 1.9 s to ingest either way; the PDF 4.9 to 5.0 s, against 4.6
1539
+ to 4.9 s. A line of megabytes is cleaned in pieces too: one line of 30 MB with a control
1540
+ character between its letters held the event loop for 1.9 s, with 761 MB of memory, and now for
1541
+ 71 to 76 ms, with 250 MB. What is left comes from the cut of a long line into lines of 2,000
1542
+ characters, which still runs in one block: 0.21 to 0.23 s for a line of 66 million characters.
1543
+ - **A look at the pages of a PDF lets other requests run while it parses the file, copies the
1544
+ pages and writes the cut.** In 0.5.0 a look held the event loop for nearly its whole time: one
1545
+ page that refers to 20,000 large arrays held it 1.87 to 2.02 s of 3.8 to 3.9 s, and pages of a
1546
+ 2,000-page PDF 159 to 177 ms of 163 to 185 ms. Now the longest holds are 43 to 47 ms and 19 to
1547
+ 20 ms (Windows, Node 24). A cut is the same to the byte as before (65 cuts of 50 PDFs compared).
1548
+ Each look still reads and parses the whole file, and the first look of a process loads
1549
+ `@cantoo/pdf-lib` in one block (about 0.4 s, unless the server loads it when it starts).
1550
+ - **A PDF name escaped again and again no longer holds the server.** A name such as
1551
+ `/#2323...2341` loses one level each time it is decoded, and both the page check and a look at
1552
+ the pages decoded every name of a page until nothing changed, in one block: time grew with the
1553
+ square of its length. A name is now decoded at most three times, and one that would still
1554
+ change is taken as a name that cannot be read: the page check counts it as naming any drawing,
1555
+ and a look keeps every image of the page. Measured on one machine (Linux, Node 22), the ingest
1556
+ of a 0.4 MB PDF with one such name of 400,000 characters in its resources ran over 90 s and now
1557
+ takes 0.27 s, and a look at its page ran over 90 s and now takes under 0.2 s; a PDF of under 20 KB whose content paints 40 such
1558
+ names of 30,000 characters went from 11.7 s to 0.41 s. Names that real files write are read as
1559
+ before.
1560
+
1561
+ Access:
1562
+
1563
+ - **`files.tools()` checks the owner of each document it reads.** In 0.5.0, a loop of your own
1564
+ that built a `DocumentMeta` from an ID a client sent could read the text of another owner's
1565
+ document through the tools, and show the pages of its PDF (see **Upgrading**).
1566
+ - **Changing metadata that `MemoryDocumentStore` handed out no longer changes the document.**
1567
+ `ingest` and `getMeta` returned the store's own object: deleting `owner` from it before sending
1568
+ it to a browser opened the document to every owner. `FileDocumentStore` was not affected.
1569
+
1570
+ Searches:
1571
+
1572
+ - **A model asked when something last happened can now see the last matching line.** In a live
1573
+ check on Vertex AI, with gemini-3.1-flash-lite and a 3 MB production log, the model counted the
1574
+ 442 PAY-5031 errors right, then named line 12,088 as the last one. It was line 15,269: the
1575
+ search showed the first matches only, and said nothing of the others (see **Upgrading**). A way
1576
+ to page through all the matches is planned for 0.7.0.
1577
+ - **A search that stopped early and was cut to the size limit still says that its total is a
1578
+ lower bound.** 0.5.0 replaced that note with the note of the cut.
1579
+ - **Steps say "1 matching line", "1 passage", "1 part" and "1 more tool call in this turn was not
1580
+ run"**, where 0.5.0 said "1 matching lines" and so on. Likewise, a file of one line is `1 line`
1581
+ in its frame and its card, and a PDF of one page is `1 page` in its card.
1582
+
1583
+ Text files and what the model reads:
1584
+
1585
+ - **A Hebrew CSV that Excel saved in windows-1255 can be searched.** 0.5.0 stored its 30 rows as
1586
+ U+FFFD, and "ירושלים" was found in none of them; now it is found in all 30. Arabic in
1587
+ windows-1256, Russian in windows-1251, French in windows-1252, and Japanese in Shift_JIS are read
1588
+ the same way (see **Upgrading**).
1589
+ - **An export in CESU-8 is read with its emoji.** An Oracle database in its character set `UTF8`,
1590
+ and Java's modified UTF-8, write a character past U+FFFF as two halves of a surrogate pair. When
1591
+ that is the only thing wrong with a file, it is read as UTF-8, with the pairs joined. 0.5.0
1592
+ stored each such emoji as six U+FFFD.
1593
+ - **Tag characters, and the controls that reorder what a person sees, are removed at ingest.** A
1594
+ line with 44 Unicode tag characters, which spell out an instruction that a model reads and a
1595
+ person does not see, sent all 44 to the model, and a file name kept them too. Characters that
1596
+ scripts and emoji need are kept, and a crafted file can still carry data a person does not see
1597
+ in them ([Characters that show nothing](docs/security.md#characters-that-show-nothing)). The
1598
+ library does not detect instructions.
1599
+ - **An exact search finds a word split by a zero-width space or a soft hyphen**, in a file
1600
+ ingested from now on: `pass\u200bword` now matches a search for "password".
1601
+ - **A file's own lines, and its name, no longer pass for the end of its frame.** A file sent whole
1602
+ could hold `--- End attached file: report.txt ---`, the same line the library writes. The frame
1603
+ lines now carry a mark that the file cannot know (see **Upgrading**); it does not make the model
1604
+ obey, and it is not a secret ([The frame around a file](docs/security.md#the-frame-around-a-file)).
1605
+ - **No half of an emoji reaches Claude.** 0.5.0 cut text inside a character outside the basic
1606
+ plane, which JSON writes as `\ud83d` and Claude's API refuses: in tool results, search lines,
1607
+ stand-ins, the first lines of a card, log templates, the problem message of a call whose
1608
+ arguments could not be read, and file names, cut at 255 characters. These are now cut before
1609
+ such a character. What 0.5.0 stored cut that way (log templates, search windows in stored tool
1610
+ rounds, names) is sent with U+FFFD in place of the half, and `getMeta` returns a name the same
1611
+ way; the stored data is not changed. An emoji of several characters, such as a flag, can still
1612
+ lose its end at the cut of a name.
1613
+
1614
+ Ingest:
1615
+
1616
+ - **An outline of 20 to 399 top-level headings keeps each of them once, in order.** In a document
1617
+ of more than 400 headings, such an outline took its entries from the first headings only, some
1618
+ more than once: with 20 top-level headings, the first one 20 times. It was so in 0.5.0 and every
1619
+ version before. Ingest a document again to rebuild its outline.
1620
+
1621
+ The tool loop:
1622
+
1623
+ - **The calls of a turn share the room that is left.** Each call took its whole cap in call
1624
+ order, so the first calls could take all the room, and the next were told "no room left, answer
1625
+ now". The room is now shared evenly, and only calls that cannot each get 1,500 characters are
1626
+ refused.
1627
+ - **Whole-file reads in one turn are counted together** against `limits.requests` and
1628
+ `limits.inputTokens`: two reads that each fit passed the ceiling together (16 requests against
1629
+ 11 in a probe). Their input tokens are counted by the `tokenScale` of the model that reads the
1630
+ parts, and the provider's count of a request by that of the model that gave it, not by the
1631
+ largest scale of the question.
1632
+ - **Part reads of a `generateText` that does not call `onUsage` count toward `limits.requests`**
1633
+ and `usage.requests`. They were left out.
1634
+ - **The request for an answer after no tool ran is `FINAL_ANSWER_WITHOUT_TOOLS`**, also when the
1635
+ first reply was empty or no turn was left for tools. It said "using only what the tools returned
1636
+ above".
1637
+
1638
+ Whole-file reads:
1639
+
1640
+ - **A read whose last step failed returns the notes of its parts**, with `notes_only: true`,
1641
+ instead of an error that lost every part already paid for.
1642
+ - **A model that asks again for a read that could read no part is told that it failed, and why**,
1643
+ not to "use the answer of that read". A read that failed before any model request (a store that
1644
+ could not be read) can be made again.
1645
+ - **A long answer is cut at its end**, with `answer_shortened`, and the other fields
1646
+ (`parts_read`, the notes on what is incomplete) are kept. It was cut as JSON, which dropped them.
1647
+ - **A part that could not be read from storage no longer shows the model the server's file
1648
+ path**, only the error code ("The file could not be read from storage (EACCES). Try the call
1649
+ again.").
1650
+ - **One HTTP 400 no longer turns the larger output limit off for every later question.** A part
1651
+ refused as too large for the window with 32,768 output tokens was taken for a model that refuses
1652
+ that limit: every later part on that model, in that process, was sent with 4,096, and a model
1653
+ that thinks got no text.
1654
+ - **One part refused by the per-minute token limit no longer blocks whole-file reads for the rest
1655
+ of the process.** The larger output limit stayed learned, and every later part asked for it
1656
+ again and was refused. Now an allowance of no more than 32,768 tokens turns it off for the model.
1657
+ With a fake OpenAI-compatible server, 12 of 12 parts were read in 15 requests, where main
1658
+ (5157e7f) read none in 34.
1659
+ - **Claude: a part read that thought most of its output limit away is asked again with the larger
1660
+ limit** (`THINKING_OUTPUT_TOKENS`), as Gemini and OpenAI-compatible part reads are. Its notes
1661
+ came back cut: two lines out of 4,096 tokens.
1662
+
1663
+ The adapters:
1664
+
1665
+ - **All three: a connection that failed while the body of a reply arrived is sent again**, like
1666
+ one that failed before the reply. In 0.5.0 a chat reply that came in one piece was not.
1667
+ - **A stream that closes without saying why it ended is not taken for a whole reply**: Gemini's
1668
+ last chunk has a `finishReason`, an OpenAI-compatible stream a `finish_reason` or `[DONE]`, and
1669
+ a Claude stream a `stop_reason`. A proxy or a dropped connection made a cut answer, or a cut turn
1670
+ of tool calls, count as whole (see **Upgrading**). On Claude, a call whose block was never closed
1671
+ is answered "send it again", not run with no arguments. DeepSeek's
1672
+ `insufficient_system_resource` is the server's failure (HTTP 503), not a whole reply.
1673
+ - **OpenAI-compatible and Claude: a stream that said it is whole returns its reply, though the
1674
+ server then left the connection open, or the connection broke.** After `[DONE]` or
1675
+ `message_stop`, the body is read for at most one more second, and then cancelled. With 0.5.0,
1676
+ such a request waited until the server closed the connection, and failed when it broke.
1677
+ - **A streamed reply through a `fetch` whose body is a Node stream** (node-fetch) failed with
1678
+ "stream.getReader is not a function". Both kinds of body are read.
1679
+ - **A streamed event longer than 64,000,000 characters ends the reply**, with an error of kind
1680
+ `"invalid"` and status 200 that is not sent again:
1681
+ `The model's reply could not be read: an event of its stream held more than 64,000,000 characters.`
1682
+ (Claude's and Gemini's say the same). Such a reply now ends after about 62 MB, in 0.4 s, with
1683
+ 165 MB more memory. 0.5.0 had no cap: it grew one string with the event, and searched all of it
1684
+ again for each piece that came (see the next point). On main (5157e7f), whose parser did the
1685
+ same, an event without an end grew a string until it failed, with 600 to 740 MB more memory, or
1686
+ ran the heap out of memory. A reply made of many events, and a reply that is not streamed, have
1687
+ no cap yet.
1688
+ - **`parseSseJson` reads each piece of a body once.** One event of 8 MB in pieces of 16 KB took
1689
+ 0.97 to 1.19 s with 0.5.0; it now takes 10 to 20 ms (ten runs each, Node 24, Windows). See
1690
+ [Measurements](docs/measurements.md#the-server).
1691
+ - **OpenAI-compatible: an error whose message is at the top of the body is read** (`message`
1692
+ from vLLM before its OpenAI-shaped errors, SGLang and FastChat; `detail` from servers built on
1693
+ FastAPI). A request too large for the model failed with "The model returned HTTP 400."; it now
1694
+ carries the server's message, with kind `"context_overflow"`, and is made smaller (see
1695
+ **Changed**).
1696
+ - **OpenAI-compatible: a streamed reply keeps its `refusal`, and OpenRouter's `reasoning` and
1697
+ `reasoning_details`** (the thought signature of a Gemini 3 model behind OpenRouter).
1698
+ - **OpenAI-compatible: a server that sends the name of a tool call again with each piece** no
1699
+ longer makes it `search_documentsearch_document`, an unknown tool.
1700
+ - **OpenAI-compatible: a call whose arguments are empty or not JSON goes back as `"{}"`.** vLLM
1701
+ before 0.29 refused the next request (HTTP 400).
1702
+ - **OpenAI-compatible: part reads send `max_completion_tokens` to every Azure OpenAI host.** When
1703
+ `maxTokensField` is not set, a server that refuses the name it was sent (HTTP 400 naming it) is
1704
+ sent the other, and the adapter keeps it.
1705
+ - **OpenAI-compatible: two user turns in a row are sent as one.** DeepSeek's reasoner and the chat
1706
+ templates of Mistral and Gemma models refuse them.
1707
+ - **Claude: an empty text block is not sent back** ("text content blocks must be non-empty"),
1708
+ unless a thinking block follows it in the turn.
1709
+ - **Claude: calls of other providers and of earlier questions get IDs the API takes**, each once
1710
+ in a request: Kimi's `functions.search:0` becomes `functions_search_0`.
1711
+
1712
+ Retries:
1713
+
1714
+ - **`retries: NaN` no longer sends a failing request again without end.** A `NaN`, such as
1715
+ `Number(process.env.RETRIES)` with the variable unset, never ran out: a request that kept failing
1716
+ with status 0, 408, 409, 429 or 5xx was sent again until the signal aborted. A `baseDelayMs` or
1717
+ `maxDelayMs` of `NaN` cut the waits to about 1 ms. Each now takes its default.
1718
+
1719
+ Packaging:
1720
+
1721
+ - **npm installs llm-large-files next to unpdf 2** (`^1.4.0 || ^2.0.0`; unpdf 2 asks for Node
1722
+ 24). With 0.5.0, an app that already had unpdf 2 could not install llm-large-files: npm stopped
1723
+ with `ERESOLVE`. The 12 PDFs of the tests give the same text, pages, picture marks and page cuts
1724
+ with every unpdf from 1.4.0 to 2.2.1, and CI runs the tests with unpdf 1.7.0 on Node 20, the
1725
+ newest 1.x on Node 22 and 24, and the newest 2.x on Node 24.
1726
+
1727
+ ## 0.5.0 and earlier
1728
+
1729
+ Versions 0.1.0 to 0.5.0 are recorded in the
1730
+ [full history up to 0.5.0](https://github.com/renanbazinin/llm-large-files/blob/v0.5.0/CHANGELOG.md).
1731
+ Each of them but 0.1.0 is a [tag of the repository](https://github.com/renanbazinin/llm-large-files/tags);
1732
+ from 0.6.0 on, each release is also on the
1733
+ [GitHub releases page](https://github.com/renanbazinin/llm-large-files/releases).