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/docs/security.md CHANGED
@@ -1,146 +1,985 @@
1
1
  # Security
2
2
 
3
- Uploaded files often contain sensitive data: production logs, contracts, customer exports. Review
4
- these points before deploying.
3
+ Uploaded files often hold sensitive data: production logs, contracts, customer exports. This page
4
+ says what the library does to keep each document to its owner and each question within bounds,
5
+ what it leaves to your application, and what reaches your model provider. Read it before you
6
+ deploy.
5
7
 
6
8
  ## Ownership
7
9
 
8
- Pass the signed-in user (or tenant) as `owner`:
10
+ A document can have an owner: one string, such as the signed-in user's ID or a tenant's, compared
11
+ exactly as it is. Set it at ingest, and pass the same owner to every call that reaches the
12
+ document:
9
13
 
10
14
  ```ts
11
- await files.ingest({ name, bytes, owner: user.id });
12
- await files.prepare(ids, base, { owner: user.id });
13
- await askGemini({ ..., owner: user.id });
14
- createDocumentHandlers(files, { getOwner: (req) => req.user?.id });
15
+ import { askWithFiles } from "llm-large-files";
16
+ import { askGemini } from "llm-large-files/gemini";
17
+
18
+ // `files` is your createLargeFiles() instance, `model` your adapter (for Vertex AI,
19
+ // gemini(vertexAi({ ... }))) and `endpoint` a vertexAi({ ... }) endpoint. `userId` comes from
20
+ // your sign-in session, never from the request body. `bytes`, `documentIds` and `messages` (an
21
+ // array of `ChatTurn` and `ToolTurn`, which both calls take) are yours.
22
+ const owner = userId;
23
+
24
+ const meta = await files.ingest({ name: "app.log", bytes, owner });
25
+ const current = await files.getMeta(meta.id, { owner });
26
+ const original = await files.getOriginal(meta.id, { owner });
27
+ const result = await askWithFiles({ files, model, documentIds, messages, owner });
28
+ // askGemini passes `owner` on to askWithFiles.
29
+ const geminiResult = await askGemini({ files, endpoint, documentIds, messages, owner });
30
+ const deleted = await files.delete(meta.id, { owner });
15
31
  ```
16
32
 
17
- A document with an owner is invisible to every other owner, and to callers that pass no owner. It
18
- counts as missing in `prepare`, `getMeta`, `delete`, and `askGemini`. Documents ingested without an
19
- owner are usable by anyone who has the ID.
33
+ A document that has an owner is used only by calls that pass that owner. A call with another
34
+ owner, or with none, gets what it gets for a document that does not exist: `undefined`, `false`,
35
+ `missing`, `DocumentsNotFoundError` or a 404 (the table is in
36
+ [Storage](./guides/storage.md#how-ownership-works)).
37
+
38
+ A caller cannot tell a document of another owner from one that never existed or has expired.
39
+ `toDocumentSummary`, which the upload handlers answer with, leaves the owner out.
40
+
41
+ **An owner must be a string that is not empty.** `files.ingest` throws a `TypeError` for an owner
42
+ of `""`, of spaces only, or `null`:
43
+ `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.`
44
+ Such an owner, which `user?.id ?? ""` gives a caller who is not signed in, would be one owner
45
+ shared by every caller without a user: each of them could read and delete the documents of the
46
+ others whose IDs it has. From JavaScript, an owner that is neither a string nor a finite number
47
+ (the user object in place of its ID, `true`, `NaN`, an array) is refused with the same error. A
48
+ number is accepted, as before. Only `ingest` and the upload handler refuse: calls that read with
49
+ `owner: ""` work as before, so documents that 0.5.0 stored with that owner stay readable until
50
+ they expire.
51
+
52
+ **A document ingested without an owner is open to every call that has its ID**, with an owner or
53
+ without. Its ID then works like a password. An ID is `doc_` and 32 hex digits, a random UUID with
54
+ 122 random bits: it cannot be guessed, but it can leak. The ID of a document the model reads
55
+ through tools is in its card and in the system instruction your model provider receives (so a
56
+ model can repeat it in an answer), and IDs end up in your URLs, in browser storage and in logs.
57
+ Give every document an owner.
58
+
59
+ What the owner should be (a user, or a user and a chat session), and how to keep a list of a
60
+ session's documents, is in [Storage](./guides/storage.md). The owner stops one user from reaching
61
+ another's documents. It does not stop one user from mixing documents of their own sessions: take
62
+ `documentIds` from your session record, not from the browser.
20
63
 
21
- **Without owners, a document ID works like a password.** IDs are random 128-bit values, but they
22
- can leak through logs, browser storage, or shared links.
64
+ ### Requiring a signed-in user in the handlers
65
+
66
+ `createDocumentHandlers` calls `getOwner` for every request but an upload with no file name (no
67
+ `X-File-Name` header and no `?name=`), which is answered 400 before `getOwner` runs. When
68
+ `getOwner` returns `undefined`, the request is anonymous: an upload is stored without an owner, and
69
+ GET and DELETE reach only documents that have none. To refuse a request instead, throw an error
70
+ with a `status` (or `statusCode`) between 400 and 599: the handler answers with that status and the
71
+ error's message. Any other error is answered with a 500 that does not repeat its message.
72
+ `getOwner` runs before the body is read, so a refused upload is not buffered.
73
+
74
+ An owner that `ingest` refuses is the server's mistake, and the upload is answered with a 500
75
+ before its body is read: `{ "error": "Upload failed (empty owner)." }` when `getOwner` returns
76
+ `""`, a string of spaces or `null`, and `{ "error": "Upload failed (owner is not a string)." }`
77
+ when it returns something that is neither a string nor a finite number, such as the user object in
78
+ place of its ID. Nothing is logged. Where every upload needs a signed-in user, throw a 401 as
79
+ below. Return `undefined` only where anonymous uploads are meant (`user?.id || undefined`). GET and
80
+ DELETE pass such an owner on as before.
81
+
82
+ ```ts
83
+ import type { IncomingMessage } from "node:http";
84
+ import { createDocumentHandlers } from "llm-large-files/node";
85
+
86
+ // `files` is your createLargeFiles() instance. Your sign-in middleware sets `request.user`.
87
+ type SignedInRequest = IncomingMessage & { user?: { id: string } };
88
+
89
+ export const documentHandlers = createDocumentHandlers(files, {
90
+ getOwner(request) {
91
+ const user = (request as SignedInRequest).user;
92
+ // Returning undefined would store the upload without an owner, open to anyone with its ID.
93
+ if (!user) throw Object.assign(new Error("Sign in first."), { status: 401 });
94
+ return user.id;
95
+ },
96
+ });
97
+ ```
98
+
99
+ The routes, statuses and the rest of the upload flow are in [Web app](./guides/web-app.md) and the
100
+ [node reference](./reference/node.md).
23
101
 
24
102
  ## Tool scoping
25
103
 
26
- `files.tools(documents)` accepts only the IDs it was created with. A model (or a prompt injected
27
- into a file) can't reach another conversation's documents by naming their IDs. `view_pages` has
28
- its own list, the PDFs passed as `viewPages`, and checks it the same way.
104
+ `files.tools(documents)` reads only the documents it was made with. A model, or a prompt injected
105
+ into a file, that names any other document ID is answered `Unknown document_id …`, with the IDs it
106
+ may use. `view_pages` has its own list: the PDFs whose original is kept (in a store that has
107
+ `getOriginal`), among the documents passed to `tools()` (`viewPages: true`) or in the list given as
108
+ `viewPages`. A call for any other document is refused: one that `tools()` reads as text is answered
109
+ that only its text was kept, any other is an unknown `document_id`.
110
+
111
+ `askWithFiles` and `askGemini` make one tool set per question, from the plan that `prepare` made
112
+ with the question's owner. You have nothing to do.
113
+
114
+ **`files.tools()` checks owners through the metadata it is given.** It has no owner option. On
115
+ every call that reads a document's text or the pages of its PDF, it checks that the document is
116
+ still in the store and has not expired, and compares the owner stored with the document with the
117
+ `owner` of the `DocumentMeta` you passed for that ID. When they differ, the call answers
118
+ `doc_… is no longer available on the server. Ask the user to attach the file again.`, as for a
119
+ document that is gone, and `view_pages` shows no page. So metadata built from an ID a client sent,
120
+ with no owner or another one, reads nothing of a document that has an owner. The check compares
121
+ strings: metadata that carries the stored owner reads the document, wherever it came from, and a
122
+ document stored without an owner is open to any metadata. (Before 0.6.0, `tools()` checked no
123
+ owner.) In a tool loop of your own, give it only metadata that `prepare(ids, base, { owner })` or
124
+ `getMeta(id, { owner })` returned, never objects built from IDs a client sent:
125
+
126
+ ```ts
127
+ import { DocumentsNotFoundError } from "llm-large-files";
128
+
129
+ // Your own loop: `base` is the size of the rest of your request. The tools below have no
130
+ // `generate`: `wholeDocumentAnalysis: false` keeps the instruction from naming
131
+ // `analyze_whole_document`, and the cards from offering a whole-file read.
132
+ const prepared = await files.prepare(documentIds, base, { owner, wholeDocumentAnalysis: false });
133
+ if (prepared.missing.length > 0) throw new DocumentsNotFoundError(prepared.missing);
134
+ const tools = files.tools(prepared.plan.searchable);
135
+ ```
136
+
137
+ Writing your own loop is covered in [Your own adapter and loop](./guides/own-adapter-and-loop.md),
138
+ and every tool, its arguments and its limits in the [tools reference](./reference/tools.md).
139
+
140
+ ## What is sent to model providers
141
+
142
+ The library sends data only through the adapters: to the provider's API (each adapter's default),
143
+ or to the URL you configure instead (an endpoint, a `baseUrl` or `url`, or your own gateway). It
144
+ makes no other network request and sends no telemetry.
145
+
146
+ A question's requests can hold:
147
+
148
+ - **The whole text of every document that fits**, framed by its name, at the start of the first
149
+ user turn by default (`documentPlacement`). It is in every request of the question, and it is
150
+ planned again, and sent again, for every later question that names the document.
151
+ - **A card for each document too large to send whole**: its name, ID, format, size, lines, pages
152
+ and estimated tokens; for a log, its levels, time range and up to 8 message templates; up to 40
153
+ outline headings; and its first 25 lines.
154
+ - **Tool results**: excerpts of the text (search hits, line ranges, the first and last lines), each
155
+ up to `toolResultCharacters` (24,000 characters by default); the answer of a whole-file read is a
156
+ tool result too, up to 40,000 characters (or `toolResultCharacters` when that is larger).
157
+ - **The whole text of a file read whole** (`analyze_whole_document`), in parts of up to
158
+ `mapChunkTokens`, through the adapter's `generateText`.
159
+ - **Pages**: with `view_pages`, a small PDF of up to 5 pages cut from the kept original, for each
160
+ call. The pages stay in the later requests of that question, unless room runs out: older
161
+ results, pages included, are then replaced by a note of what they showed (never for a model whose
162
+ conversation may only grow, as Claude's). They are not kept in `toolTurns`: only that they were
163
+ shown.
164
+ - **File names, and the IDs of the documents read through tools.** Not the owner, and no original
165
+ file other than those page cuts.
166
+ - **Whatever you pass in `messages`**: earlier questions' `toolTurns`, which hold excerpts of the
167
+ files, and parts in a provider's own form.
168
+
169
+ The words of a failed model request are not among them. When a request of a whole-file read fails,
170
+ the model is told why by the error's kind, its HTTP status, the code of a connection that failed,
171
+ or a timeout, never by the error's message, which can name a project, a host, a masked key or a URL
172
+ with a key in it ([What the library logs](#what-the-library-logs)).
173
+
174
+ All of this but the parts of a whole-file read goes to every model of the question. With an
175
+ [explorer model](./guides/explorer-model.md), both models get the conversation with the
176
+ documents; the explorer makes the tool calls and alone reads files whole in parts, and the
177
+ answering model gets those calls and their results (the read's answer, not its parts), pages
178
+ included. When the two are of different providers, the files reach both.
179
+
180
+ What a provider keeps, for how long, and where it processes the data is set by your agreement with
181
+ it and by the endpoint you choose: for Vertex AI, the `location` of `vertexAi()`, which is
182
+ `"global"` by default ([Gemini API and Vertex AI](./guides/vertex-and-gemini.md)). Prompt caching
183
+ keeps a copy at the provider for a while: the Claude adapter asks for it by default (`cache: true`,
184
+ five minutes; `false` sends none), and `documentPlacement: "first"`, the default, puts the
185
+ documents where a provider's own cache can reuse them.
186
+
187
+ What comes back is read with one bound of its own. One event of a streamed reply holds at most
188
+ 64,000,000 characters: a longer one ends the reply with an error of kind `"invalid"`, such as
189
+ `The model's reply could not be read: an event of its stream held more than 64,000,000 characters.`,
190
+ and the request is not sent again. A reply made of many events has no cap on its size, nor on its
191
+ time while it keeps arriving. An endpoint you do not trust, such as a gateway run by someone else,
192
+ can still take the memory of your server.
29
193
 
30
194
  ## Prompt injection
31
195
 
32
- File content goes to the model as text. A file can contain instructions ("ignore previous
33
- instructions…"). The tools here only read the user's own documents, so the possible damage is
34
- limited to the answer. If you combine them with tools that *act* (send email, change tickets),
35
- treat the model's output as untrusted.
196
+ The model reads text you do not control: the content of the files, their names, the pages it looks
197
+ at. A file can hold instructions ("ignore previous instructions…"). The library does not filter or
198
+ detect instructions. It keeps the frame around a file intact, removes most characters that show
199
+ nothing, and marks text that Word and PowerPoint hide, so that what the model takes for a file's
200
+ text is closer to what a person sees in it. None of this stops an instruction written in plain
201
+ sight.
202
+
203
+ What limits the damage:
204
+
205
+ - **The tools only read**, and only the documents of the question ([Tool scoping](#tool-scoping)).
206
+ No tool changes your data or reaches anything but the store and the models of the question (a
207
+ whole-file read sends the file to the model that explores, in parts).
208
+ - **The cost of a question is bounded** ([What a question can cost](#what-a-question-can-cost)),
209
+ whatever a file asks for.
210
+ - **A file cannot pass for the end of its frame.** The lines around a file sent whole carry a mark
211
+ that its text cannot know, and the first one tells the model that the file ends only at the line
212
+ with that mark. The mark does not make the model obey, and it is not a secret
213
+ ([The frame around a file](#the-frame-around-a-file)).
214
+ - **Most characters that show nothing are removed** at ingest, from the text and from the file name:
215
+ tag characters, zero-width spaces, the controls that reorder what a person sees
216
+ ([Characters that show nothing](#characters-that-show-nothing)).
217
+ - **Text of hidden runs in Word, and slides the slide show skips, are marked** as such; text hidden
218
+ in other ways is not ([Hidden text in Word, PowerPoint and HTML](#hidden-text-in-word-powerpoint-and-html)).
219
+ - **A file name cannot add lines to the instruction.** At ingest it is reduced to one printable line
220
+ without most characters that show nothing (see [Uploads](#uploads)), and the system instruction
221
+ and the frame quote it as a JSON string. It is still text the model reads, like the file's
222
+ content.
223
+
224
+ What a hostile file can still do:
225
+
226
+ - **Steer the answer**: state false things, leave things out, claim that another file says
227
+ something. `result.evidence` lists the documents, lines and pages each tool call showed the model,
228
+ and the model is asked to cite line numbers: show them, so a user can check.
229
+ - **Bring another document of the same question into the answer.** Every document of the question
230
+ is within reach of the tools, so a file can ask for another's text to be written into the answer,
231
+ for example inside a link or an image URL. Treat the answer, the text that `onText` streams, and
232
+ the steps and activity lines, which quote what the model sent, as untrusted: show them as plain
233
+ text or escape them, and do not load images or open links from them on your own. The library
234
+ does not render anything; this is up to your interface.
235
+ - **Hide text from a person, but not from the model**, in what the cleaning and the marks leave:
236
+ characters that scripts and emoji need, Word text hidden by a style, a text file in an older
237
+ encoding that an editor shows as � ([Characters that show nothing](#characters-that-show-nothing),
238
+ [Hidden text in Word, PowerPoint and HTML](#hidden-text-in-word-powerpoint-and-html),
239
+ [Text files that were not UTF-8](#text-files-that-were-not-utf-8)).
240
+ - **Reach every model of the question**, an explorer model included.
241
+ - **Stay in the conversation.** The `toolTurns` you store hold the text the tools returned,
242
+ injected instructions included, and they go back to the model with every later question. A
243
+ search, read or overview that repeats one of them is not run again: the model is pointed to the
244
+ stored result, unless that result failed, was cut, came from a search that stopped early, is no
245
+ longer there in full, or the provider may have cleared it
246
+ ([How it works](./how-it-works.md#pointers-to-repeated-calls)).
247
+
248
+ **Tools that act.** `askWithFiles` takes no tools of your own. To give a model tools that act
249
+ (send an email, change a ticket), write your own loop
250
+ ([Your own adapter and loop](./guides/own-adapter-and-loop.md)), and treat every call the model
251
+ makes as untrusted input: check it, and ask the user before anything that cannot be undone.
252
+
253
+ **History from the client.** Keep each conversation, with its `toolTurns`, on your server. The loop
254
+ sends stored tool rounds, and parts in a provider's own form, as they are. A client that could send
255
+ its own could put any text into what the model takes for a tool result, that is, for what a file
256
+ says, and any provider part (for Gemini, any part of `contents`) into the request.
257
+ [Conversations](./guides/conversations.md) covers storing them.
258
+
259
+ ### The frame around a file
260
+
261
+ A file sent whole sits between two frame lines:
262
+
263
+ ```text
264
+ --- Attached file [mark 1f0c3a9e]: "report.txt" (text, 6 lines; it ends only at the line with mark 1f0c3a9e) ---
265
+ …the text of the file…
266
+ --- End attached file [mark 1f0c3a9e] ---
267
+ ```
268
+
269
+ The mark is eight hex digits made from the document ID. The ID is made at random when the file is
270
+ stored, after its text was written, so the text cannot know the mark. A line of the file that
271
+ copies the frame (`--- End attached file … ---`, then the first line of a file that was never
272
+ attached), in whatever letters, has no mark or a wrong one, and the first frame line tells the
273
+ model that only the line with the mark ends the file. The uploader chooses the name along with the
274
+ text, so the mark comes before the name, the name is quoted as a JSON string, and the closing line
275
+ holds the mark alone: a name cannot put a mark of its own first. The mark is the same in every
276
+ request, so a provider's prompt cache can reuse the file from one request to the next. After an
277
+ upgrade from 0.5.0, the first request of each conversation reads nothing of the file from the
278
+ cache, since the frame lines changed.
279
+
280
+ What the mark does not do:
281
+
282
+ - **It does not make the model obey.** It tells the model where the file ends; a model can still
283
+ follow an instruction inside the file.
284
+ - **It is not a secret.** It is made from the ID by a fixed hash. A file attached after another, by
285
+ someone who knows the first one's ID, can hold its mark. IDs are in cards, in the system
286
+ instruction and in your URLs ([Ownership](#ownership)).
287
+ - **Cards have no mark.** A file too large to send whole is shown as a card between
288
+ `--- Large attached file: … ---` lines, with its first lines numbered and indented by two spaces,
289
+ and the tools return lines as JSON. A line separator (U+2028) inside a line of the file, which a
290
+ model may read as a line break, can make text look like the start of a line in a card.
291
+
292
+ ### Characters that show nothing
293
+
294
+ Ingest removes these characters from the text of every file (file names differ in two ways; see
295
+ below):
296
+
297
+ - control characters other than tab and line breaks, C1 (U+0080-U+009F) included, and terminal
298
+ escape sequences;
299
+ - Unicode tag characters (U+E0000-U+E007F), each of which spells out one ASCII character that a
300
+ model reads and a person does not see. In 0.5.0, a line with 44 of them sent all 44 to the model,
301
+ in the prompt and in tool results. The flags of England, Scotland and Wales, which are written
302
+ with them, are kept; any other flag written with them keeps only its black flag;
303
+ - the text-direction controls that change the order a person sees: embeddings and overrides
304
+ (U+202A-U+202E) and isolates (U+2066-U+2069);
305
+ - the zero-width space (U+200B), the word joiner and the invisible operators (U+2060-U+2064), the
306
+ deprecated format characters (U+206A-U+206F), a byte order mark inside the text (U+FEFF), and the
307
+ soft hyphen (U+00AD), but not one at the end of a line, where it shows.
308
+
309
+ Kept, because scripts and emoji need them: the marks that right-to-left text needs (U+200E, U+200F,
310
+ U+061C), zero-width joiners and non-joiners (U+200C, U+200D), variation selectors (U+FE00-U+FE0F,
311
+ U+E0100-U+E01EF), Hangul fillers, and the line and paragraph separators (U+2028, U+2029). A few
312
+ others that show nothing pass too, such as U+034F, U+180E, U+FFF9-U+FFFB and the private use area.
313
+ A crafted file can still carry text a person does not see in them: in the review of 0.6.0, 32 bytes
314
+ written as variation selectors after one emoji reached the model whole, in the prompt and in a
315
+ tool result, and the line showed only the emoji. The library does not detect instructions there,
316
+ nor anywhere else.
317
+
318
+ File names lose the same characters, with two differences. A control character, a line or
319
+ paragraph separator and every text-direction control, the marks of right-to-left text included,
320
+ become a space. And an escape sequence is not removed whole: its ESC becomes a space, and the rest
321
+ stays (`re\x1b[31mport.txt` is stored as `re [31mport.txt`).
322
+
323
+ No line break is added or removed, except in a text with no line feed, where U+0085 ends lines
324
+ ([Uploads](#uploads)). A line of more than 2,000 characters that held such characters can be split
325
+ into fewer pieces than 0.5.0 split it, which moves the lines after it. Documents stored by an
326
+ earlier version keep their text until they expire. Steps and activity lines drop the same
327
+ characters ([What the library logs](#what-the-library-logs)).
328
+
329
+ ### Hidden text in Word, PowerPoint and HTML
330
+
331
+ A DOCX can hold text that Word does not show, a PPTX slides that the slide show skips, and an HTML
332
+ page text that a browser does not show. Their text is kept, and marked:
333
+
334
+ - **Text of a hidden run** (`<w:vanish/>` in the run's own properties) comes after the text of its
335
+ paragraph that shows, and each of its lines starts with
336
+ `[Hidden text, not shown in the document]`. A carriage return, a U+0085 or a line separator in it
337
+ starts a new marked line. A line longer than about 1,950 characters is cut into pieces, each
338
+ marked, so that no piece is stored without its mark. The text of a run inside a hidden run, such
339
+ as the reading of a ruby, is marked too, and so is the rest of the hidden run after it.
340
+ - **A hidden slide** (`show="0"`) has the heading
341
+ `## Slide 2 (hidden, not shown in the slide show)`. Its text is kept.
342
+ - **Text an HTML page hides** (an element with the `hidden` attribute, or an inline style of
343
+ `display: none` or `visibility: hidden` or `collapse`) is marked the same way, line by line and
344
+ in pieces. Hidden text inside a line that shows comes after that line, not where it stood. A row
345
+ of a table that the page hides is written marked, in its place. The hiding ends where the element
346
+ does; an element the page never closes hides the rest of its parent. A `hidden` attribute or a
347
+ style is read in the first 4,096 characters of its value.
348
+
349
+ The attributes of `w:vanish` and of a slide's `p:sld` are read however long the tag is, and by
350
+ their exact names, as XML reads them: `W:VAL="0"` is another attribute, and the run stays hidden.
351
+
352
+ The mark is a hint, not a filter. Text without it may still be hidden, and a document's own text
353
+ can write the mark. Not told apart, and read as text that shows:
354
+
355
+ - text hidden through a character or paragraph style, and white or tiny text;
356
+ - in HTML, text hidden by a style sheet, a class, a script, `opacity`, a position off the page or
357
+ a `<template>` (dropped, like scripts), and an `aria-hidden` element, which a browser shows;
358
+ - hidden shapes on a slide that shows;
359
+ - the content of `mc:Choice`, which the library reads where Word may show `mc:Fallback` instead
360
+ (the Fallback is not read);
361
+ - tags written with a namespace prefix other than `w:` or `p:`, and a text box inside a hidden run;
362
+ - a `show` value written as a character reference (`show="&#48;"`); the same in a `w:val` marks
363
+ text that shows as hidden;
364
+ - parts that no relationship references, such as an orphan header (a slide that
365
+ `ppt/presentation.xml` does not list is not read, unless the deck lists none).
366
+
367
+ Speaker notes are read since 0.8.0, after a line `[Speaker notes]` under their slide, and so are
368
+ the comments of a DOCX, under `# Comments`: they are text a reader of the slide show or the page
369
+ does not see either. The marks count toward `maxTextBytes` and the limit of 32 million
370
+ characters.
371
+
372
+ ### Text files that were not UTF-8
373
+
374
+ A text file that is not valid UTF-8 is read in the older encoding that its lines with letters fit,
375
+ when one does: windows-1255, windows-1256, windows-1251, Shift_JIS or windows-1252
376
+ ([How it works](./how-it-works.md#text-encodings)). `meta.encoding` names it, and the model is told.
377
+ An editor that opens the file as UTF-8 shows those lines as �, so a person who checks the file there
378
+ does not see what the model reads. Three lines of instructions in windows-1251 between two lines of
379
+ UTF-8 reach the model as Cyrillic text, while the editor shows the two lines and �. Lines that are
380
+ valid UTF-8 read the same in both. Show `meta.encoding` to the user ("read as windows-1251"), and
381
+ check such a file in an editor set to that encoding.
382
+
383
+ The choice is made line by line. A line counts as UTF-8 when it holds at least as many characters
384
+ of more than one byte as characters that are not valid, and the file is read as UTF-8 when at least
385
+ as many lines count as UTF-8 as count as not, or when at most one line in 200 is not UTF-8. So lines
386
+ in an older encoding inside a mostly UTF-8 file become U+FFFD, and a few lines of half-width
387
+ katakana in Shift_JIS, whose bytes can pair into valid UTF-8 by chance, can be read as UTF-8 with
388
+ U+FFFD. `meta.replacedCharacters` counts the U+FFFD, and the model is told of them.
36
389
 
37
390
  ## Storage and retention
38
391
 
39
- - Files expire after `ttlMs` (default 72 h); expired files are never returned. `sweep()` deletes
40
- them from disk. Set the TTL to match your data policy.
41
- - A delete takes effect on every server that shares the store, from the next tool call on: a
42
- document kept in memory is used only after the store confirms that it is still there. (Before
43
- 0.4, another server could keep answering from its memory until the document expired.)
44
- - `FileDocumentStore` writes plain text to disk. Use an encrypted volume, or implement
45
- `DocumentStore` over storage with encryption at rest.
46
- - Only IDs matching `doc_` plus 32 hex characters ever reach the file system, so there's no path
47
- traversal.
392
+ - **Expiry.** A document expires `ttlMs` after its upload (72 hours by default). Its `expiresAt` is
393
+ set at ingest and no call moves it. `ttlMs: Infinity` keeps documents until they are deleted
394
+ (`expiresAt` is then `NEVER_EXPIRES`). An expired document is never returned, by any call, on any
395
+ server. Set the time to live to match your data policy.
396
+ - **Removing expired files is up to you.** `files.sweep()` asks the store to remove expired
397
+ documents and returns how many it removed. Nothing calls it for you: run it on a schedule, from
398
+ one place ([Deployment](./guides/deployment.md)). A store without `sweep` removes nothing, and
399
+ `files.sweep()` returns 0. `FileDocumentStore` also removes an expired document when it next reads
400
+ its metadata, and its `sweep` removes the files of failed uploads once they are `orphanAgeMs` old
401
+ (one hour by default). `FileDocumentStore`'s `sweep` throws nothing: a directory it cannot read
402
+ gives 0, and a document it cannot remove is left for the next sweep. Watch the count it returns,
403
+ and the volume, to know that expired files really go.
404
+ - **A delete takes effect on every server that shares the store, from the next tool call on.**
405
+ Every use of a document first asks the store whether it is still there. A copy kept in memory
406
+ (within `cacheBytes`, 256 MB by default) is used only after that, and dropped when the document
407
+ is gone.
408
+ - **What a delete or an expiry does not reach.** The `toolTurns` you stored with a conversation hold
409
+ excerpts of the files word for word, up to `toolResultCharacters` each, and are sent again with
410
+ later questions. Neither reaches the answers, steps and evidence you stored, your logs, or what
411
+ your model provider keeps. To forget a document, also drop the tool rounds that name it from the
412
+ stored conversation ([Conversations](./guides/conversations.md)).
413
+ - **`FileDocumentStore` writes plain files** in one directory: `<id>.txt`, the text; `<id>.json`,
414
+ the metadata (owner, file name, MIME type, sizes, dates, outline headings and, for a log, its
415
+ message templates); `<id>.idx`, a line index; `<id>.bin`, the original with `keepOriginals`; and
416
+ `.tmp` files while it writes. Nothing is encrypted, and a delete removes the files without
417
+ overwriting them. Use an encrypted volume, or write a `DocumentStore` over storage with encryption
418
+ at rest ([Storage](./guides/storage.md)).
419
+ - **No path traversal.** Only IDs that match `DOCUMENT_ID_PATTERN` (`doc_` and 32 lowercase hex
420
+ digits) reach the file system. File names never become paths.
421
+ - `MemoryDocumentStore` keeps everything in the memory of one process, until it restarts. It is for
422
+ tests and single-process demos. It copies the metadata it is given and the metadata it hands out,
423
+ so deleting `owner` from what `ingest` or `getMeta` returned, before you send it to a browser,
424
+ changes nothing stored. (In 0.5.0 it opened the document to every owner.) The original it returns
425
+ is the stored bytes themselves: treat them as read-only.
48
426
 
49
427
  ## Original files
50
428
 
51
- With `keepOriginals`, the uploaded file itself is stored next to its text (`<id>.bin` in
52
- `FileDocumentStore`). That is off by default. When you turn it on:
429
+ With `keepOriginals` (for example `["pdf"]`), the uploaded file itself is stored next to its text
430
+ (`<id>.bin` in `FileDocumentStore`). That is off by default, and a store without `putOriginal`
431
+ keeps none. When you turn it on:
53
432
 
54
433
  - **More is kept than before.** The text of a PDF leaves out its pictures, signatures, stamps and
55
- hidden layers; the file has them all, and its metadata (author, software, dates). Treat the
56
- store as you treat the uploads themselves.
57
- - **It follows the document.** The file has the document's owner and its expiry: it is returned
58
- only to the owner (`files.getOriginal(id, { owner })`), it is gone for every reader once the
59
- document has expired, and `delete` and `sweep` remove it from disk. A store of your own must do
60
- the same in its `delete` and `sweep`.
61
- - **It takes space.** Up to `maxUploadBytes` (100 MB) per document, for `ttlMs` (72 h). Lower
434
+ hidden layers; the file has them all, and its metadata (author, software, dates). Treat the store
435
+ as you treat the uploads themselves.
436
+ - **It follows the document.** The file has the document's owner and its expiry.
437
+ `files.getOriginal(id, { owner })` returns it only to the document's owner, or to any caller with
438
+ the ID when the document has none. It returns `undefined` once the document has expired, and
439
+ `delete` and `sweep` remove the file from disk. A store of your own must do the same in its
440
+ `delete` and `sweep`.
441
+ - **Serving it is up to you.** `createDocumentHandlers` has no route that returns an original. If
442
+ you send the bytes of `getOriginal` to a browser, do not take the content type from the stored
443
+ `mimeType`: the client declared it at upload ([Uploads](#uploads)). Choose it from `format`, and
444
+ send the file as a download (`Content-Disposition: attachment`).
445
+ - **It takes space.** Up to `maxUploadBytes` (100 MB) per document, for `ttlMs` (72 hours). Lower
62
446
  either, or sweep more often, if disk is short.
63
- - **Pages go to the model.** `view_pages` sends the pages the model asks for to your model
64
- provider, as the text of the file already goes. A PDF that is encrypted only to restrict printing
65
- or copying is opened, and the cut is not encrypted: the restriction does not travel with it.
447
+ - **Pages go to the model.** `view_pages` sends the pages the model asks for to every model of the
448
+ question, as the text of the file already goes. A PDF that is encrypted only to restrict printing
449
+ or copying is opened with an empty password, and the cut is not encrypted: the restriction does
450
+ not travel with it. A PDF that needs a password to open is not shown.
451
+
452
+ How `view_pages` works, and what to weigh before you keep originals, is in [PDFs](./guides/pdfs.md).
66
453
 
67
454
  ## Reading PDFs for pages and pictures
68
455
 
69
- Showing pages and marking pictures read the whole PDF into objects with `@cantoo/pdf-lib`, in your
70
- process, on a file a user uploaded.
456
+ Three features read the whole PDF into objects with `@cantoo/pdf-lib`, in your process, on a file
457
+ a user uploaded:
458
+
459
+ - **`view_pages`** reads the kept original again for every call, to cut the pages out of it.
460
+ - **Picture marks** and **the page check** read every PDF at ingest, once for both, when
461
+ `@cantoo/pdf-lib` is installed, whether or not originals are kept. The page check refuses a page
462
+ that would hold the server while pdf.js reads it ([Uploads](#uploads)), before pdf.js reads any
463
+ page. A page that shows a picture or a drawing gets the line
464
+ `[Picture on this page. This text cannot show it.]`.
465
+
466
+ What bounds them:
467
+
468
+ - **Memory.** About twice the size of the file, plus 1 to 1.6 KB for each object in it
469
+ ([measured](./measurements.md#what-a-cut-costs-the-server)). A crafted file can take far more.
470
+ Each object is built in one step, and nothing checks it before: one MB of a file took 6 to
471
+ 91 MB of heap, by what it holds (empty dictionaries the most), and a stream unpacked twice packs
472
+ such objects thousands of times. An upload of 16 MB that is one array of one-digit numbers ran a
473
+ heap of 256 MB (`--max-old-space-size=256`) out of memory at ingest, a look at the pages of one
474
+ of 8 MB did the same, and a file of 32 KB, an array of 32 MB packed in an object stream, ran a
475
+ heap of 512 MB out of memory at ingest ([measured](./measurements.md#the-server)). What a stream
476
+ unpacks to is outside the heap, where `--max-old-space-size` does not limit it: a look at a PDF
477
+ of 1.6 KB whose object stream unpacks to 512 MB took 1.1 GB of the process's memory and 1.0 s in
478
+ one block, with 20 MB of heap. Such files declare few objects, so the limits below do not see
479
+ them. Before reading, the library looks up the number of
480
+ objects the file declares. `view_pages` refuses a file that
481
+ declares more than 1,000,000 objects, or more than 60% of the free heap holds at 1,700 bytes an
482
+ object: the model is told
483
+ `report.pdf: This PDF has 1,200,000 objects, too many to cut pages from it in memory.`
484
+ Picture marks and the page check skip a file past 150,000 objects: it is ingested with no page
485
+ marked, and no page checked. Both limits trust the number the file declares at its end: a file
486
+ that declares fewer objects than it has, or none, is read, and so is one with a cross-reference
487
+ stream inside it that declares more. `@cantoo/pdf-lib` makes an entry for each object such a
488
+ stream declares, whatever it holds: in a file of 8.7 KB, a million of them took 0.7 s, and four
489
+ million ran a heap of 512 MB out of memory.
490
+ - **Memory kept.** `@cantoo/pdf-lib` keeps every name and every reference it reads, for the life of
491
+ the process: in the server that ingests, and in the one that answers `view_pages`. After the
492
+ document was dropped, 2 MB of different names still took 37 MB of heap, and the million entries
493
+ above about 140 MB. A file read again adds nothing, and real PDFs add little: names such as
494
+ `/Type`, and references to the same object numbers, are kept once for all files. But each file
495
+ with other names or other object numbers adds its own: files of 9 KB that each declared a million
496
+ new objects added about 140 MB each, and the fourth ingest ran a heap of 512 MB out of memory. On
497
+ the server that answers `view_pages`, the seventh look at such files ran a heap of 1 GB out of
498
+ memory, and that memory comes back only when the server restarts. A process of its own for each
499
+ ingest, as [Deployment](./guides/deployment.md#uploads-and-ingest) shows, gives it all back when
500
+ it ends, and so do the child processes of
501
+ [`createIsolatedExtractors`](./reference/node.md#createisolatedextractorsoptions), each replaced
502
+ after 50 files and stopped when idle. For the documents of users you do not trust, do not offer
503
+ `view_pages` (`viewPages: false`), or keep no PDF originals.
504
+ - **Time.** Reading cannot be interrupted once it has started, not even by the question's `signal`.
505
+ It pauses so that other requests get a turn after every 12 ms of work, or up to 40 ms where a
506
+ pause itself takes long, as a timer does on Windows. (Until 0.6.0 it paused every 4,000 objects,
507
+ and 4,000 objects of a large file took 0.5 to 0.8 s.) `view_pages` pauses the same way while it
508
+ copies the pages and writes the cut. What `@cantoo/pdf-lib` reads in one step still holds the
509
+ server, and grows with the file: one object takes about 0.1 to 0.35 s for each MB, by what it
510
+ holds, so a crafted PDF of 16 MB that is one array of numbers held the server for 1.6 to 3.2 s at
511
+ ingest and 1.7 to 3.5 s on each look, on a heap that could hold it (up to 984 MB for a look), and
512
+ a cross-reference table written as text takes 0.15 s for 150,000 objects. The first PDF of a process also loads `@cantoo/pdf-lib`, in one block of
513
+ about 0.4 s, unless the server loads it when it starts ([measured](./measurements.md#the-server)).
514
+ `view_pages` has no time limit.
515
+ Picture marks pause every 12 ms or so between pages, and stop after 5 seconds of work once the
516
+ file is read (the pauses do not count): then no page is marked. At ingest, picture marks also
517
+ stop between two pages when `ingestTimeoutMs` (2 minutes) passes or `IngestInput.signal` aborts;
518
+ a reading of the file already under way goes on in the background until it ends
519
+ ([Uploads](#uploads)).
520
+ - **Errors** are caught. `view_pages` tells the model why the pages cannot be shown, and the model
521
+ answers from the text. Picture marks that fail leave every page unmarked.
522
+
523
+ To turn them off: without `keepOriginals` for PDFs, `view_pages` is never offered
524
+ (`viewPages: false` turns it off for one question). Picture marks and the page check are turned off
525
+ in the PDF extractor, or by not installing `@cantoo/pdf-lib`; a `view_pages` call then fails too,
526
+ so keep no PDF originals either. Without the page check, a page that is slow to read holds the
527
+ server for as long as pdf.js takes ([Uploads](#uploads)): read PDFs in child processes with
528
+ `createIsolatedExtractors`, whose kill timer stops such a page, or ingest in a process of its own.
529
+
530
+ ```ts
531
+ import { createLargeFiles, createPdfExtractor, FileDocumentStore } from "llm-large-files";
532
+
533
+ const files = createLargeFiles({
534
+ store: new FileDocumentStore("./data/documents"),
535
+ // No picture marks and no page check: PDFs are not read with @cantoo/pdf-lib at ingest.
536
+ extractors: { pdf: createPdfExtractor({ pictures: false, checkPages: false }) },
537
+ // No keepOriginals: no original is kept, so view_pages is never offered.
538
+ });
539
+ ```
540
+
541
+ For uploads you do not trust, parse them in a process of their own, with a memory limit and a
542
+ timeout. Since 0.8.0 the library does it: the `extractors` of
543
+ [`createIsolatedExtractors`](./reference/node.md#createisolatedextractorsoptions), from
544
+ `llm-large-files/node`, read PDF, DOCX, PPTX and XLSX files in child processes, each with a heap
545
+ flag (`maxHeapMb`, 512 by default: a heap limit of 560 to 704 MB, depending on the version of Node,
546
+ [The heap limit](./reference/node.md#createisolatedextractorsoptions)) and a kill timer
547
+ (`timeoutMs`, 120 s). A file that runs its child out of memory is refused with the code
548
+ `"out_of_memory"`, one that takes too long with `"timeout"`, and your server goes on
549
+ ([Uploads](#uploads)). To run the whole ingest apart, an
550
+ extractor of your own included, fork a process for it
551
+ ([Deployment](./guides/deployment.md#uploads-and-ingest)). If you keep their PDFs for
552
+ `view_pages`, run the questions in a process of their own too (the tool loop of each question, in a
553
+ process you fork), or do not offer `view_pages` on their documents (`viewPages: false`): a look
554
+ parses the file again, in the server that answers. The limits of the library bound
555
+ what a file can make it keep, but not the memory a parser takes for its own work, and in your
556
+ server that memory is the server's heap. Choose the isolation with care:
71
557
 
72
- - **Memory.** About twice the size of the file, plus 1 to 1.6 KB for each object in it. A file of
73
- 54 MB with 330,000 objects needed 700 MB. A file that declares more objects than the free heap
74
- can hold, or more than a million, is refused before it is read (150,000 for the picture marks).
75
- That check trusts what the file declares: a file that lies about it is still read.
76
- - **Time, and no hard limit.** Reading cannot be interrupted once it has started. It pauses every
77
- 4,000 objects so other requests get a turn, but a crafted file can hold the process: 1 MB of
78
- junk between two objects took 3.6 seconds to skip. Errors are caught and the model is told that
79
- the pages cannot be shown; a file that only takes long is not stopped.
80
- - For uploads you do not trust, run ingest and the document tools in a worker thread or a separate
81
- process with a memory limit and a timeout, as recommended for PDF text extraction below.
558
+ - **A child process contains running out of memory.** A process started with `child_process.fork`,
559
+ as `createIsolatedExtractors` starts its children, or a service of its own, with its own
560
+ `--max-old-space-size`, stops alone, and your server goes on. `createIsolatedExtractors` does not
561
+ pass the server's `NODE_OPTIONS` to its children, so a heap flag there does not replace theirs.
562
+ That flag bounds the heap only. What a parser unpacks is held outside it: a PDF of 1.6 KB took 1.6
563
+ GB of memory at ingest with 20 MB of heap ([Objects of a PDF](#uploads)). Give that process a
564
+ memory limit of its own too, such as a container or a cgroup of its own.
565
+ - **A worker thread does not reliably contain it.** In the 0.6 review, on the code before this
566
+ release ([Measurements](./measurements.md#how-to-read-this-page)), a worker given
567
+ `resourceLimits: { maxOldGenerationSizeMb: 512 }` ran out of memory on a hostile DOCX and took
568
+ the whole process down with it.
569
+ - **A heap flag of the process silently replaces a worker's limit.** With `--max-old-space-size`
570
+ on the command line or in `NODE_OPTIONS`, every worker gets the process's heap limit in place of
571
+ its `resourceLimits.maxOldGenerationSizeMb`. With `--max-old-space-size=1024`, a worker given 512
572
+ MB had a heap limit of 1,216 MB, the process's, where it has 704 MB without the flag (Node 24,
573
+ `v8.getHeapStatistics().heap_size_limit`). Clearing `execArgv` or `NODE_OPTIONS` for the worker
574
+ does not change it.
575
+
576
+ [Deployment](./guides/deployment.md#uploads-and-ingest) has the recipes.
82
577
 
83
578
  ## Uploads
84
579
 
85
- - `maxUploadBytes` (default 100 MB) is enforced while reading, before the body is buffered fully.
86
- - The handlers buffer the upload in memory before extraction. Under heavy concurrent uploads, put a
87
- limit in front (a reverse proxy or a rate limiter).
88
- - A DOCX or PPTX is unpacked a piece at a time, and refused as it grows past 100 times its size
89
- (after the first 16 MB) or past 128 MB of XML: a zip bomb of 160 KB that unpacks to 50 MB is
90
- stopped at 16 MB. Its XML is read in one pass, so its shape cannot make reading slower.
91
- - A terminal escape sequence (`ESC ]` …) is removed only up to its end on the same line: one
92
- without an end loses its two escape characters, not the lines after it.
93
- - Binary files are rejected, including compressed ones (`.gz`, `.zip`), which get a message
94
- telling the user to decompress first. PDF parsing runs `unpdf` (pdf.js), and with it installed
95
- `@cantoo/pdf-lib`, on untrusted input in your process. Keep them updated, or move extraction to a
96
- worker or sandbox for high-risk deployments.
97
- - File names are reduced to one printable line at ingest (no path, control characters, line
98
- breaks, or text-direction overrides) and quoted in the system instruction, so a name can't add
99
- lines to the prompt. The name is still text the model reads, like the file's content.
580
+ - **Size.** `maxUploadBytes` is 100 MB by default. `createDocumentHandlers` refuses a larger
581
+ `Content-Length` before reading, and counts the body as it reads it, stopping at the limit: 413
582
+ "The file is larger than the 100 MB upload limit." When a body parser in front (such as
583
+ `express.raw()`) has already read the body, it buffered it under its own `limit`: set that one
584
+ too. `files.ingest` checks the bytes you give it, which are already in memory.
585
+ - **Memory.** The handlers buffer the whole upload, up to `maxUploadBytes`, before reading its
586
+ text, and an ingest then holds several copies of the text at once (several times the size of the
587
+ text), in your server's heap. Cap concurrent uploads in front (a reverse proxy, a rate limiter),
588
+ or read PDF and Office files with `createIsolatedExtractors`, whose `concurrency` (2) and
589
+ `maxQueue` (8) bound how many are read and wait, or ingest in a process of its own:
590
+ [Deployment](./guides/deployment.md) has measurements and recipes.
591
+ - **Text.** A small file can hold far more text than its size: a PDF of 3 KB whose page tree listed
592
+ one dense page 150 times drew 107 MB of text in 0.5.0. `maxTextBytes` (100 MB by default, or
593
+ `maxUploadBytes` when that is larger) bounds the text kept from one file, in UTF-8 bytes. The PDF
594
+ extractor counts it page by page, and DOCX, PPTX and XLSX as they are unpacked; each refuses the
595
+ file as soon as it passes. The text of any other extractor is checked when it returns. A PDF whose
596
+ page tree lists one page more than once is refused before its text grows: "This PDF lists the same
597
+ page more than once. A file built that way can hold far more text than its size, so it is not
598
+ read. Print it to a new PDF, and attach that." A PDF whose pages paint forms inside forms draws
599
+ the text of the innermost one each time it is painted: past the first 16 MB, a PDF that draws more
600
+ than 100 times its size in text is refused as it is read ("This PDF draws more than 16 MB of text,
601
+ over 100 times its size. …"), whatever `maxTextBytes` allows.
602
+ - **Pages.** A PDF of more than `maxPdfPages` pages (5,000 by default) is refused before any page
603
+ is read.
604
+ - **Time.** One ingest may take `ingestTimeoutMs` (2 minutes by default) to extract, index and
605
+ profile the text. Past it, `ingest` throws "report.pdf took too long to read (more than 2 min).
606
+ …", and nothing is stored. `IngestInput.signal` stops it sooner, when your route knows that the
607
+ uploader left; the upload handler of `createDocumentHandlers` aborts it when the client closes
608
+ the connection. The PDF, DOCX, PPTX and XLSX extractors stop between two pages or two pieces. At
609
+ the limit, `ingest` stops waiting, but a step already under way (one page of pdf.js, JSZip reading
610
+ the directory of a ZIP, a parse of `@cantoo/pdf-lib`, an extractor of your own that does not
611
+ look at `ExtractInput.signal`) runs on to its end in the background. With
612
+ `createIsolatedExtractors`, the child process that reads the file is killed then, step and all,
613
+ and also at its own `timeoutMs`.
614
+ - **Work of a PDF page.** pdf.js reads the text of a page in one block that neither the time limit
615
+ nor a signal cuts short, and a page can be built to make it run far more than its file holds: a
616
+ 3 KB page that paints a form that paints another, 50 times at each of three levels, held the
617
+ event loop for 13 s, and one of 4 KB for about 100 s. With `@cantoo/pdf-lib` installed, the PDF
618
+ extractor adds up, before pdf.js reads any page, what each page would make it run (its content,
619
+ each form every time it is painted, and the fonts it sets, Type3 glyph programs included), and
620
+ refuses a page past about 1 to 1.5 s of pdf.js, or past 32 times the size of the file when that
621
+ is more: "Page 1 of this PDF draws far more than its file holds, and reading it would hold the
622
+ server for a long time. A file built that way is not read: it may be built to exhaust the
623
+ server. Print it to a new PDF, and attach that." Pages that add up to more than four such pages
624
+ are refused with "This PDF draws far more than its file holds, …", and a page whose content
625
+ cannot be decoded before pdf.js reads it with "Page 1 of this PDF stores its content in a way
626
+ that cannot be checked before it is read, so it is not read. …". The hostile files of the review
627
+ are refused in under 0.06 s. The check narrows what an upload can do; it does not bound it (see
628
+ Stalls). How it counts: [Pages that would hold the server](./guides/pdfs.md#pages-that-would-hold-the-server).
629
+ - **Objects of a PDF.** Both parsers build each object of a PDF in one step, and an object can
630
+ take far more memory than file: one MB of empty dictionaries took 91 MB of heap, and a stream
631
+ unpacked twice packs such objects thousands of times. Nothing checks an object before it is
632
+ built, and the limits on the number of objects a file declares do not see such files.
633
+ `@cantoo/pdf-lib` builds every object of the file for the page check and the picture marks: an
634
+ upload of 16 MB that is one array of one-digit numbers ran a heap of 256 MB out of memory, and
635
+ one of 32 KB, an array of 32 MB packed in an object stream, a heap of 512 MB
636
+ ([Reading PDFs for pages and pictures](#reading-pdfs-for-pages-and-pictures)). pdf.js builds the
637
+ objects a page needs, and every object of an object stream once it needs one of them: a file of
638
+ 759 bytes whose object stream, unpacked twice, held the catalog and 8 MB of empty dictionaries
639
+ ran a heap of 512 MB out of memory in pdf.js alone, with the page check and the picture marks
640
+ off. With them on, as by default, both build such objects, and a file of 732 bytes with 4 MB of
641
+ them did so ([measured](./measurements.md#the-server)). 0.5.0 did the same. What a stream unpacks
642
+ to is held outside the heap, where `--max-old-space-size` does not limit it: a PDF of 1,633 bytes
643
+ whose object stream holds the catalog after 512 MB of spaces was read with 20 MB of heap, but the
644
+ process took 1.6 GB of memory. The same spaces in the content of a page are refused by the page
645
+ check, in under 0.07 s. A check of each object before it is built is not in 0.6.0:
646
+ pdf.js reads an object where the cross-reference table points, also inside what reads as the
647
+ data of a stream, and the object streams of an encrypted file cannot be unpacked before they are
648
+ decrypted, so such a check would be easy to get around. Read files you do not trust with
649
+ `createIsolatedExtractors`, whose children have a heap limit, and for what a stream unpacks
650
+ outside the heap, ingest in a container of its own with a memory limit of its own
651
+ ([Deployment](./guides/deployment.md#uploads-and-ingest)). A look at their
652
+ pages parses the file again on the server that answers the question: do not offer `view_pages`
653
+ on their documents (`viewPages: false`), or keep no PDF originals
654
+ ([Reading PDFs for pages and pictures](#reading-pdfs-for-pages-and-pictures)).
655
+ - **Stalls.** Ingest pauses for other requests about every 12 ms of its work: between the pages of
656
+ a PDF, as a DOCX or PPTX is unpacked, as a text file that is not UTF-8 is decoded, and in every
657
+ step after extraction, a line of megabytes included. In a measurement on one machine, the longest
658
+ stall of the event loop was 31 to 34 ms for a 99 MB log and 0.16 s for a 2,000-page PDF, against
659
+ 1.9 to 2.0 s and 4.4 to 4.5 s with the ingest of 0.5.0
660
+ ([Measurements](./measurements.md#the-server)). Some steps still hold the server, and neither the
661
+ time limit nor a signal cuts them short:
662
+ - A PDF page, for as long as pdf.js takes to read it: up to about 1.5 s for a page that passes
663
+ the check in a small file, longer in a large file, and without limit when the page check does
664
+ not run (without `@cantoo/pdf-lib`, on a file it cannot read or that declares more than 150,000
665
+ objects, with `checkPages: false`) or on a file built to be read one way by `@cantoo/pdf-lib`
666
+ and another way by pdf.js.
667
+ - One object of a PDF, while `@cantoo/pdf-lib` reads it for the page check and the picture
668
+ marks: about 0.1 to 0.35 s for each MB, by what the object holds. A crafted PDF of 16 MB held
669
+ the server for 1.6 to 3.2 s, and one of 8 KB, an array of 8 MB packed in an object stream, for
670
+ 1.5 to 3.5 s.
671
+ A cross-reference stream that declares a million entries held it for 0.7 s
672
+ ([Reading PDFs for pages and pictures](#reading-pdfs-for-pages-and-pictures)).
673
+ - One object of a PDF that a page needs, while pdf.js reads it: 1.1 to 1.3 s for an array of
674
+ 32 MB ([Objects of a PDF](#uploads)).
675
+ - A stream that pdf.js unpacks to reach an object: 6.1 to 6.4 s for an object stream that
676
+ unpacks to 512 MB, in a file of 1.6 KB. `@cantoo/pdf-lib` took 1.0 s for it at a look.
677
+ - A piece of a DOCX, PPTX or XLSX packed hundreds of times tighter than documents are, about
678
+ 0.2 s at a time while JSZip unpacks it.
679
+
680
+ Read files you do not trust with `createIsolatedExtractors`, or ingest them in a process of their
681
+ own ([Deployment](./guides/deployment.md#uploads-and-ingest)): only that process waits, and it is
682
+ stopped at its time limit.
683
+ - **Parsers.** PDF text is read with `unpdf` (pdf.js), pages, pictures and the page check with
684
+ `@cantoo/pdf-lib`, and DOCX, PPTX and XLSX are unpacked with `jszip`. They are optional
685
+ dependencies, and they run on untrusted input in your process, or in the child processes of
686
+ `createIsolatedExtractors`. Keep them updated, and for high-risk deployments move extraction out
687
+ of the server: into those child processes, a container of its own or a sandbox ([Reading PDFs for
688
+ pages and pictures](#reading-pdfs-for-pages-and-pictures) says why a worker thread is not enough).
689
+ - **Zip bombs.** A DOCX, PPTX or XLSX is unpacked a piece at a time, and refused as it grows past
690
+ 100 times its size (after the first 16 MB) or past 128 MB of XML: "This DOCX unpacks to more than
691
+ 16 MB, over 100 times its size. A file that grows that much is not read: it may be a zip bomb.
692
+ Save it as text or PDF, and attach that." Only the parts that hold text are unpacked (in a DOCX
693
+ the document, its footnotes, endnotes, comments, headers and footers, and its styles and
694
+ numbering; in a PPTX the slides and their speaker notes; in an XLSX the workbook, its styles, its
695
+ shared strings and its sheets). Pictures and fonts stay packed. What is kept in memory is bounded
696
+ by the text, not by the XML: each paragraph becomes one string when it closes, and an empty one is
697
+ dropped. A file is refused with more than 32 million characters of text (or `maxTextBytes`, when
698
+ that is smaller), more than 1,000,000 paragraphs with text, paragraphs nested more than 32 deep,
699
+ or more than 20,000 parts in its ZIP directory. In 0.5.0, a DOCX of 1.5 MB that held 120 MB of
700
+ empty paragraphs ran a heap of 512 MB out of memory and stopped the server; it is now refused with
701
+ the process at 115 MB.
702
+ - **The ZIP directory of a DOCX, PPTX or XLSX** is read before JSZip reads it, the way JSZip 3.10 will
703
+ read it: from where JSZip finds it (the last end record of the file, and for a ZIP64 file the
704
+ last locator and the record it points to), record by record, each by its own lengths. JSZip reads
705
+ every record of the directory into memory before it unpacks any part, and the count of parts that
706
+ the file gives does not bound it: 300,002 parts with a count of 2 took 440 to 490 MB. What JSZip
707
+ would keep is added up, and the file is refused before JSZip sees it:
708
+ - more than 20,000 parts (JSZip keeps about 2 KB for each): "This DOCX has more than 20,000
709
+ parts, more than an Office document has. It may be built to exhaust the server, so it is not
710
+ read." The parts are not counted past the limit.
711
+ - more than 80,000 extra fields (JSZip keeps about 250 bytes for each field of 4 bytes), or more
712
+ than 8 MB of what JSZip turns into text or goes through byte by byte: for each part, the name
713
+ in the local header it points to, its comment, and the data of its ZIP64, Unicode Path and
714
+ Unicode Comment fields. The size of the file does not bound these. A name is decoded once for
715
+ each part that points to its header, and a field gives all the data it says it has, even when
716
+ that runs past its record over the records after it: 2,000 parts of a DOCX of 0.17 MB ran a
717
+ heap of 256 MB out of memory, and the ZIP64 fields of a DOCX of 1 MB held the event loop for
718
+ 4.5 s. "This DOCX lists its parts in a way that no Office program does: reading the list would
719
+ take far more memory or time than an Office document needs. It may be built to exhaust the
720
+ server, so it is not read." Office writes no extra fields, other ZIP programs one to three for
721
+ each part, and the Office files we tried had at most 68 KB of names and comments.
722
+ - a ZIP64 end record that says it is longer than its fields: JSZip reads the rest in a loop that
723
+ does not move on, until it runs out of data or forever. "This DOCX ends with a ZIP64 record
724
+ that cannot be read, and reading it could hold the server without end. It may be built to
725
+ exhaust the server, so it is not read."
726
+
727
+ Real files are not refused: 245 ZIP files of Word, PowerPoint, Excel, Java and other programs,
728
+ and of Python, Info-ZIP, git, .NET and other ZIP writers, gave the parts, and the bytes of text,
729
+ that JSZip reads. What the limits still let through is bounded: a DOCX just under all three at
730
+ once took JSZip 0.46 to 0.48 s in one block, with the heap at 126 to 140 MB. The reading takes
731
+ under 4 ms for a directory of 46,000 parts, and 30 to 70 ms to search 100 MB for an end record
732
+ that is not at the end (0.2 s for 100 MB built of near signatures), before JSZip searches the
733
+ file again ([Measurements](./measurements.md#the-server)).
734
+ - **Binary files are refused**, with a message for the user: "This file looks binary, not text…".
735
+ Compressed ones (`.gz`, `.zip`) get a message that says to decompress first, and an Office file
736
+ of before 2007, an Outlook message or an Office file with a password one that says to save it
737
+ again (since 0.8.0).
738
+ - **Refusals carry a code.** Since 0.8.0 `ingest` throws every refusal as an
739
+ [`IngestError`](./reference/library.md#ingesterror), and `ingest.error` events carry its `code`.
740
+ The files built the way files that exhaust a server are, which the checks above recognize (a zip
741
+ bomb, a ZIP directory or a tag no Office program writes, a PDF that lists a page twice, draws far
742
+ more text than its size or has a page that would hold the server), have the code `"hostile"`:
743
+ count or log them apart, by user. `"out_of_memory"` and `"timeout"` from the child processes of
744
+ `createIsolatedExtractors` can be such files too.
745
+ - **Scanned PDFs** (no text at all) are refused, unless PDF originals are kept (`keepOriginals`
746
+ includes `"pdf"` and the store has `putOriginal`) and the file has at most `scannedPdfPages` pages
747
+ (30 by default): their pages can then be shown.
748
+ - **File names** are reduced at ingest to one printable line: the last path segment. Control
749
+ characters, line and paragraph separators and text-direction controls become a space, and the
750
+ characters that show nothing which file text loses (tag characters, zero-width spaces, word
751
+ joiners, soft hyphens, a byte order mark) are removed
752
+ ([Characters that show nothing](#characters-that-show-nothing)). A name has at most 255
753
+ characters, and is never cut in the middle of a character (`file` when nothing is left). An
754
+ emoji of several characters, such as a flag, can lose its end at the cut. A name that an
755
+ earlier version cut in the middle of a character is sent with U+FFFD in place of the half.
756
+ - **The MIME type is the client's word.** The handlers take it from an `X-File-Type` header, or
757
+ from `Content-Type` unless that is `application/octet-stream`. The format is picked from the file
758
+ name first, then from it. It is stored, and returned in summaries: do not trust it.
759
+ - **Text is cleaned.** Terminal escape sequences are removed, and so are control characters other
760
+ than tab and line breaks, C1 (U+0080-U+009F) included, and the other characters listed in
761
+ [Characters that show nothing](#characters-that-show-nothing). An `ESC ]` without its end on the
762
+ same line loses only those two characters, not the lines after it. A sequence that starts with
763
+ U+009B and a parameter (`\u009b31m`) is removed whole; a lone U+009B, or one right after a
764
+ character of U+0080-U+00FF, is more often the end of a letter of UTF-8 read as Latin-1 ("ś" is
765
+ C5 9B), and goes alone: "Coś? Tak" read as Latin-1 keeps its "? Tak". A line of megabytes is
766
+ cleaned in pieces, with pauses for other requests.
767
+ - **U+0085 (next line).** In a text with no other line break (one at its very end aside), such as
768
+ a mainframe file converted to UTF-8, it ends a line, except right after U+0080-U+00FF, where it
769
+ is the last byte of a UTF-8 letter read as Latin-1 and is removed. So a record that ends in
770
+ such a character (É, °, £) runs into the next one, and an empty record is dropped. A file of
771
+ one line, such as minified JSON, has no other line break either, so a U+0085 inside one of its
772
+ strings becomes a line break too. In a text with other line breaks it is removed with the other
773
+ C1 characters: there it is more often inside a JSON string or a CSV field, or a windows-1252 "…"
774
+ read as Latin-1, where a line break would split the record. This applies to text in UTF-8 (or
775
+ UTF-16 with a byte order mark): the same export converted to ISO-8859-1 is read as
776
+ windows-1252, where its byte 0x85 is "…", and stays one long line.
777
+ - **What changes in text that is not hostile.** A word joiner (U+2060, which French text may put
778
+ before a "!"), a zero-width space (which Thai, Khmer and Lao text may put between words),
779
+ embeddings around Arabic, and a byte order mark or a soft hyphen inside a line are removed,
780
+ and a flag written with tag characters, other than those of England, Scotland and Wales, keeps
781
+ only its black flag. Text with none of the characters that cleaning removes or changes is
782
+ stored as before, byte for byte.
783
+
784
+ Formats, optional dependencies and the messages of refused files are in [PDFs](./guides/pdfs.md);
785
+ the upload routes in [Web app](./guides/web-app.md).
100
786
 
101
787
  ## Regex search
102
788
 
103
- The model writes the regex, and the model reads untrusted file text, so a file can ask for a
104
- slow pattern. Two things bound the cost:
789
+ The model writes the regex, and the model reads untrusted file text, so a file can ask for a slow
790
+ pattern. These bound the cost:
105
791
 
106
- - Regexes with nested quantifiers (`(a+)+`) are refused up front. This is a quick filter, not a
792
+ - **Refused up front:** a pattern longer than 300 characters, one that is not valid, and one with a
793
+ nested quantifier such as `(a+)+`. The model reads why. Since 0.8.0 a repeated group whose
794
+ repeats end at a literal character that none of its quantified parts can match, as in
795
+ `(\d{1,3}\.){3}\d{1,3}` or `(\w+\.)+com`, passes: each repeat ends at the next such character,
796
+ so it takes time in proportion to the line. The nested-quantifier check is a quick filter, not a
107
797
  guarantee: `(a|a)+$` and `((a+))+$` pass it.
108
- - Every regex scan runs under a 3-second limit enforced by Node's `vm` timeout, which interrupts a
109
- match that is still backtracking. The search returns what it found with a note that it stopped
110
- early.
111
- - The scan runs in slices of 250 ms, and other requests get a turn between two slices. A line
112
- that takes two whole slices ends the search: `(a|a)+$` on a line it cannot get past costs
113
- about 0.8 seconds, not 3.
114
- - The regex searches of one tool set, which is one question in `askGemini`, share 6 seconds
115
- (`regexBudgetMs`). Past that, a regex search is refused and the model is told to search
116
- another way.
117
- - `askGemini` runs at most 8 tool calls of one model turn (`maxToolCallsPerTurn`).
118
-
119
- A slice is synchronous, so a slow pattern still holds the event loop for up to a quarter of a
120
- second at a time, and twice that at the start of a search. If that matters for your latency, run
121
- the document tools in a worker thread.
798
+ - **3 seconds for one search.** Node's `vm` timeout interrupts a match that is still backtracking.
799
+ The search returns what it found, with the note "The scan stopped early; the total is a lower
800
+ bound, and the last match in the file is not known."
801
+ - **Slices of 250 ms.** The scan runs a slice at a time, and other requests get a turn between two
802
+ slices. A line that two whole slices cannot get past ends the search: a pattern stuck on one line
803
+ costs three slices at most, under a second, not 3 seconds.
804
+ - **6 seconds for the regex searches of one tool set** (`REGEX_BUDGET_MS`). `askWithFiles` and
805
+ `askGemini` make one tool set per question; in your own loop, `regexBudgetMs` of `files.tools()`
806
+ sets it. Past it, a regex search is refused: "The time for regex searches is used up for this
807
+ answer. Search with mode "exact" or "keywords" instead." The regex searches of one turn run one
808
+ after another, each with what the ones before it left.
809
+ - **8 tool calls of one model turn** are run (`limits.callsPerTurn`), 4 at a time. The others are
810
+ answered "Not run: one turn runs at most 8 tool calls. Send this call again if you still need it."
811
+
812
+ The 6 seconds are per question, not per process: several questions at once each have their own. A
813
+ slice is synchronous, so a slow pattern holds the event loop for up to a quarter of a second at a
814
+ time. If that matters for the latency of other users' streams, run the questions in a worker thread.
815
+
816
+ What does hold per library (per `createLargeFiles` call, so per process when you create it once
817
+ per process, as [Deployment](./guides/deployment.md#what-lives-where) advises): scans of documents
818
+ read by range (searches, counting the parts of a file) run at most `maxConcurrentScans` (4) at a
819
+ time, and the others wait their turn; the documents kept ready in memory between tool calls take at
820
+ most `cacheBytes` (256 MB).
122
821
 
123
822
  ## What a question can cost
124
823
 
125
- A file can ask a model to do expensive things, and a model can decide to on its own. These bound
126
- one question, whatever the model:
824
+ A file can ask a model to do expensive things, and a model can decide to on its own. These bound one
825
+ question, whatever the model:
826
+
827
+ - **Chat requests:** `limits.toolTurns` (12), counting the answer. Tools run in all but the last,
828
+ with at most `limits.callsPerTurn` (8) calls run in each.
829
+ - **Whole-file reads:** one of each document (`limits.wholeDocumentReads`). A read is up to
830
+ `maxMapChunks` (30) part requests of up to `mapChunkTokens` each (100,000 at the default window of
831
+ 1M tokens: 3M input tokens), plus the requests that merge the notes and write the read's answer.
832
+ With an explorer model, that model reads the parts.
833
+ - **Pages:** at most 5 a call, and for the question what half of `reservedTokens` holds at the
834
+ adapter's `pageTokens`. They stay in the later requests of the question, which bills them again,
835
+ unless room runs out and older results are replaced by a note of what they showed (never for a
836
+ model whose conversation may only grow, as Claude's).
837
+ - **Requests sent again:** a request that failed is retried (`retry.retries`, 3 by default). One
838
+ the provider refuses as too large is sent again smaller, at most twice a question (never for a
839
+ model whose conversation may only grow, as Claude's), and a question whose first request is too
840
+ large, before any tool ran, is planned again once. None of these takes a tool turn. A retried
841
+ request counts once in the usage.
842
+ - **Ceilings, unset by default:** `limits.inputTokens` and `limits.requests` cover the whole question,
843
+ part reads included. A whole-file read that would pass one is refused before it starts. Once
844
+ `inputTokens` is reached, no more tools run, but the request that crosses it has already been
845
+ sent, and the answer request is still sent with the whole conversation: a question can pass the
846
+ ceiling by up to about two requests (the one that crosses it, and the answer). `requests` counts
847
+ answered requests and keeps one for the answer.
848
+
849
+ `result.usage` is what a question used, in all and for each model. A question that fails or is
850
+ stopped returns nothing: `partialResultOf(error)` gives what it had used until then. Log both per
851
+ user. [Costs and limits](./guides/costs-and-limits.md) explains every lever, the budget, and cost
852
+ per user or session.
853
+
854
+ ## How long a question can take
855
+
856
+ There is no overall time limit on a question. Each model request waits up to 600 s for its first
857
+ piece and 300 s between pieces, and is retried after waits of up to 60 s
858
+ ([Errors and reliability](./guides/errors-and-reliability.md#waits-on-a-silent-model)). A question
859
+ is up to 12 chat requests, not counting retries, and part reads besides, so it can run for many
860
+ minutes. Give it a deadline with `signal`, and abort it too when the client goes away
861
+ ([Web app](./guides/web-app.md)). This sample sets a deadline and logs what each question used,
862
+ failed ones included:
863
+
864
+ ```ts
865
+ import { askWithFiles, partialResultOf, type UsageTotals } from "llm-large-files";
866
+
867
+ function recordUsage(owner: string, usage: UsageTotals): void {
868
+ console.log(JSON.stringify({ owner, requests: usage.requests, inputTokens: usage.inputTokens, outputTokens: usage.outputTokens }));
869
+ }
127
870
 
128
- - `limits.toolTurns` (12) chat requests, with at most `limits.callsPerTurn` (8) tool calls run in
129
- each.
130
- - One whole-file read of each document (`limits.wholeDocumentReads`). A read is up to
131
- `maxMapChunks` requests of up to `mapChunkTokens` each: 3M input tokens with the defaults. In a
132
- probe a model asked for the same file to be read whole six times in one question.
133
- - `limits.inputTokens` and `limits.requests`, unset by default, are ceilings for the whole
134
- question, part reads included. Set them if a question must not pass a cost.
135
- - The request is kept inside the model's window ([Room in the request](configuration.md#room-in-the-request)),
136
- so a turn of many large reads cannot build a request that the model refuses.
871
+ // `files`, `model`, `documentIds`, `messages` and `owner` as in the first sample.
872
+ try {
873
+ const result = await askWithFiles({
874
+ files, model, documentIds, messages, owner,
875
+ limits: { inputTokens: 2_000_000, requests: 40 },
876
+ // 15 minutes: above firstByteTimeoutMs (10 minutes), so a silent request can be sent again.
877
+ // Work that cannot be interrupted (reading a PDF for view_pages) finishes first.
878
+ signal: AbortSignal.timeout(15 * 60_000),
879
+ });
880
+ recordUsage(owner, result.usage);
881
+ } catch (error) {
882
+ // A question that failed, or was stopped, was still paid for until then.
883
+ const partial = partialResultOf(error);
884
+ if (partial) recordUsage(owner, partial.usage);
885
+ throw error;
886
+ }
887
+ ```
137
888
 
138
- `result.usage` is what the question used: every request that was answered, for each model. Log it
139
- per user to see who spends what.
889
+ Waits, retries and deadlines are explained in
890
+ [Errors and reliability](./guides/errors-and-reliability.md).
140
891
 
141
892
  ## Storage errors
142
893
 
143
- A file-system error names the path it failed on, and a database error its host. Neither is shown
144
- to a model or a user: a read of the store that fails becomes a `DocumentStoreError` whose message
145
- holds the error code at most (`The document store could not be read (EACCES). Try again.`), and a
146
- tool call answers with that message. The original error is its `cause`. Log that one.
894
+ A store's own errors can name paths and hosts. Reads reach users and models only as
895
+ `DocumentStoreError`, whose message names neither, with the original error as its `cause`. Writes
896
+ are passed on as they came, and the upload handler answers a write error that has neither a
897
+ `status` (or `statusCode`) from 400 to 599 nor a Node system error's `code` and `syscall` with 500
898
+ "Upload failed.", without the error's own message. A write error with such a status, such as an
899
+ SDK's error with `statusCode`, is answered with that status and its own message, which can name a
900
+ host. Two paths answer a store's write error 422 with its own message, so a database driver's host
901
+ can reach the browser through them: an `ingest` of your own that throws a new error in place of the
902
+ store's, as `ingestInProcess` in [Deployment](./guides/deployment.md#uploads-and-ingest) does, and a
903
+ route of your own, as in [Web app](./guides/web-app.md#filesingest-and-its-errors). Give your
904
+ store's write errors a status and a message of your own, and log the cause yourself, since the
905
+ handlers log nothing: see [Storage](./guides/storage.md#errors) and the
906
+ [node reference](./reference/node.md#uploadrequest-response). What to show a user is in
907
+ [Errors and reliability](./guides/errors-and-reliability.md).
908
+
909
+ ## What the library logs
910
+
911
+ Nothing. It writes no log, reads no environment variable, and makes no network request but the
912
+ adapters' requests: to the provider's API (each adapter's default), or to the URL you configure
913
+ instead. Two of its optional dependencies do write: pdf.js, which `unpdf` bundles, prints its own
914
+ warnings with `console.warn` (for example `Warning: Indexing all PDF objects`, for a damaged PDF),
915
+ and `@cantoo/pdf-lib` warns the same way about some malformed PDFs (for example
916
+ `Removing parsed object: 0 0 R`) when it reads one for picture marks or `view_pages`.
917
+
918
+ What you log is your choice, and some of what the library hands you holds user data:
919
+
920
+ - **Steps and activity.** The lines of `onStep`, `onActivity` and `result.steps` name the files,
921
+ quote what the model searched for (up to 80 characters) or asked a whole-file read to do (up to
922
+ 100), and a failed step ends with the error the tool returned. Each is one line of plain text. A
923
+ line break, a tab or another control character in what the model sent becomes one space, with
924
+ the blanks around it. The characters that file text drops are dropped
925
+ ([Characters that show nothing](#characters-that-show-nothing)), and those it keeps are kept.
926
+ `](` becomes `] (`, so that a markdown link or picture written as `[text](https://…)` stays
927
+ text. A call to a tool that does not exist is shown as `Call “<name>”`, with the name cut at 64
928
+ characters, so that no line starts with the model's words. The lines still quote those words,
929
+ HTML tags and web addresses included: show them as plain text, never as markdown or HTML.
930
+ - **`result.toolTurns`** hold the text of the files; `result.evidence` names the documents, lines
931
+ and pages that were shown.
932
+ - **Errors.** The `cause` of a `DocumentStoreError` names paths or hosts. A `ModelRequestError`
933
+ carries the provider's own message, unfiltered, and "could not be reached (…)" adds the HTTP
934
+ client's message. Log them on the server, and show users a message of your own.
935
+ - **Errors in a whole-file read.** A model request of the read that failed is told to the model,
936
+ and in steps and `toolTurns`, by the error's kind, its HTTP status (`status`, `statusCode` or
937
+ `response.status`), the code of a connection that failed, or a timeout, never by its message:
938
+ `Could not read any part of app.log: The model refused the key or token it was sent (HTTP 401).`
939
+ This holds for the errors of the package's adapters and for those of a `generate` of your own,
940
+ such as a provider SDK's. An error with none of these is told as `The model request failed.`, and
941
+ a reply with no text to a part reader of the package as `The model returned no text (SAFETY).`,
942
+ with the provider's reason only when it is a plain word. To give the model a reason of your own,
943
+ throw an error with a `kind` or an HTTP `status`, and log the provider's words yourself. A read of
944
+ the store that failed is told by the message of its `DocumentStoreError`, which names no path or
945
+ host (`The document store could not be read (EIO). Try again.`).
946
+
947
+ ## Before you deploy
948
+
949
+ - Give every document an owner, pass it to every call, and refuse anonymous requests in `getOwner`
950
+ ([Ownership](#ownership)). Never pass `""` for a caller without a user: `ingest` refuses it.
951
+ - Take `documentIds` and the conversation, `toolTurns` included, from your server, not from the
952
+ browser ([Prompt injection](#prompt-injection)).
953
+ - Set `ttlMs` to your data policy, run `sweep` on a schedule, and make your deletion rules cover
954
+ stored `toolTurns` ([Storage and retention](#storage-and-retention)).
955
+ - Keep the store on encrypted storage.
956
+ - Turn on `keepOriginals` only if you want `view_pages`, and knowing what it keeps
957
+ ([Original files](#original-files)).
958
+ - Set `limits` and a deadline, and log `usage` for failed questions too
959
+ ([What a question can cost](#what-a-question-can-cost)).
960
+ - Cap concurrent uploads, and set the limit of any body parser in front of the handlers
961
+ ([Uploads](#uploads)).
962
+ - Keep the limits on one file (`maxTextBytes`, `maxPdfPages`, `ingestTimeoutMs`) as low as your
963
+ users allow ([Uploads](#uploads)).
964
+ - For untrusted uploads, parse them in a process of their own with a memory limit, not in a worker
965
+ thread: pass the `extractors` of `createIsolatedExtractors` to `createLargeFiles`
966
+ ([Reading PDFs for pages and pictures](#reading-pdfs-for-pages-and-pictures)), and keep
967
+ `unpdf`, `@cantoo/pdf-lib` and `jszip` updated.
968
+ - Render answers as untrusted text, and steps and activity lines as plain text
969
+ ([What the library logs](#what-the-library-logs)).
970
+ - Show users `meta.encoding` for a text file read in an older encoding
971
+ ([Text files that were not UTF-8](#text-files-that-were-not-utf-8)).
972
+ - Check what your model provider keeps, and where it processes the data
973
+ ([What is sent to model providers](#what-is-sent-to-model-providers)).
974
+
975
+ ## Related pages
976
+
977
+ - [Storage](./guides/storage.md): owners per user or per session, a store of your own, retention.
978
+ - [Web app](./guides/web-app.md): uploads, streaming, cancelling.
979
+ - [Conversations](./guides/conversations.md): what `toolTurns` hold and how to store them.
980
+ - [PDFs](./guides/pdfs.md): formats, `view_pages`, picture marks, scans.
981
+ - [Costs and limits](./guides/costs-and-limits.md) and
982
+ [Errors and reliability](./guides/errors-and-reliability.md).
983
+ - [Deployment](./guides/deployment.md): several servers, workers, memory, sweep.
984
+ - [library.md](./reference/library.md) (`createLargeFiles`, stores, `DocumentStoreError`),
985
+ [ask.md](./reference/ask.md), [tools.md](./reference/tools.md) and [node.md](./reference/node.md).