llm-large-files 0.8.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
@@ -12,13 +12,16 @@ parts under the document's ID:
12
12
 
13
13
  | Part | What it is | Written |
14
14
  |---|---|---|
15
- | Metadata | `DocumentMeta`: owner, file name, format, sizes, lines, outline, log profile, `createdAt`, `expiresAt`. | Always, last. |
15
+ | Metadata | `DocumentMeta`: owner, scope, file name, format, sizes, the SHA-256 of the upload (0.9.0), lines, outline, log profile, `createdAt`, `expiresAt`. | Always, last. |
16
16
  | Text | The extracted text, normalized, as one string. | Always. |
17
17
  | Line index | Where each line starts, in bytes and in characters: about 8 bytes a line. With it, a document read by range is opened without first reading all of its text. | When the store has `putIndex`. |
18
- | Original | The uploaded file, byte for byte. | When `keepOriginals` lists the format and the store has `putOriginal`. |
18
+ | Original | The uploaded file, byte for byte. | When `keepOriginals` lists the format and the store has `putOriginal`, unless the ingest gives `original`: then your application keeps the file, and the metadata says where ([Keeping the uploaded files](#keeping-the-uploaded-files)). |
19
19
 
20
20
  The library makes the ID: `doc_` and 32 hexadecimal digits of a random UUID. It is new at every
21
- ingest and never reused. `DOCUMENT_ID_PATTERN` (`/^doc_[a-f0-9]{32}$/`) matches it, and
21
+ ingest and never reused. `DOCUMENT_ID_PATTERN` (`/^doc_[a-f0-9]{32}$/`) matches it. Since 0.9.0 the
22
+ application may give the ID instead ([Application IDs](#application-ids)), of the shape
23
+ `APP_DOCUMENT_ID_PATTERN` (`/^(?!(?:con|prn|aux|nul|com[0-9]|lpt[0-9])$)[a-z0-9][a-z0-9_-]{0,63}$/`:
24
+ no name Windows keeps for a device), which the made IDs fit too.
22
25
  `isDocumentId(value)` tests a value against it: use it on IDs that arrive in a request before they
23
26
  reach your database. The library tests every ID itself before it asks the store. An ID that does
24
27
  not match counts as missing, so a store only ever receives IDs that match.
@@ -55,14 +58,14 @@ export const scratch = createLargeFiles({ store: new MemoryDocumentStore() });
55
58
  - It copies the metadata it is given and the metadata it hands out, as a store that writes it
56
59
  somewhere does: changing the `meta` that `ingest` or `getMeta` returned (deleting its `owner`
57
60
  before you send it to a browser, say) changes nothing stored. Each call returns a new object.
58
- `getOriginal` still returns the kept bytes themselves: treat them as read-only.
61
+ `getOriginal` returns a copy of the kept bytes too, since 0.9.0.
59
62
  - `now` is its clock, `() => new Date()` by default. In a test, give the store and
60
63
  `createLargeFiles({ now })` the same clock: see [Testing](./testing.md).
61
64
 
62
65
  ### `FileDocumentStore`
63
66
 
64
- `new FileDocumentStore(directory, { now, orphanAgeMs })` keeps each document as files in one
65
- directory, which it creates at the first write. There are no subdirectories:
67
+ `new FileDocumentStore(directory, options)` keeps each document as files on a volume. Without
68
+ `scopes`, they are all in `directory`, which it creates at the first write:
66
69
 
67
70
  | File | Holds |
68
71
  |---|---|
@@ -72,35 +75,81 @@ directory, which it creates at the first write. There are no subdirectories:
72
75
  | `<id>.bin` | The uploaded file, with `keepOriginals`. |
73
76
  | `<id>.<ext>.<8 hex digits>.tmp` | A file being written. It is renamed to its own name once complete. |
74
77
 
78
+ With `scopes` (new in 0.9.0), the files of each scope are in a folder of their own:
79
+ `<directory>/<userId>/<chatId>/.llm-large-files/<id>.json`. See
80
+ [Files in a folder per user or per chat](#files-in-a-folder-per-user-or-per-chat).
81
+
82
+ | Option | Default | What it does |
83
+ |---|---|---|
84
+ | `now` | `() => new Date()` | The store's clock: what has expired, and the default time of `sweep`. |
85
+ | `orphanAgeMs` | One hour | How old a file of no document must be before `sweep` removes it. |
86
+ | `scopes` | None | `{ depth, folder, createScopeFolders, unscoped }`: a folder per scope. New in 0.9.0. |
87
+ | `fileMode` | `0o600` | The mode of the files it writes, minus the umask. New in 0.9.0. |
88
+ | `directoryMode` | `0o700` | The mode of the folders it makes, minus the umask. New in 0.9.0. |
89
+ | `sweepConcurrency` | 16 | How many files `sweep` reads at once. New in 0.9.0. |
90
+
75
91
  - Every file is written under a temporary name and then renamed, so no reader, on this server or
76
- another one, sees half a file. A rename that meets `EPERM`, `EACCES` or `EBUSY` (on Windows,
77
- another process has the file open for a moment) is tried again for up to about three seconds.
92
+ another one, sees half a file. A rename or a removal that meets `EPERM`, `EACCES` or `EBUSY` (on
93
+ Windows, another process has the file open for a moment) is tried again for about 2.6 seconds.
94
+ - A text longer than 1,048,576 UTF-16 units is encoded and written a slice of that size at a
95
+ time, never cutting a character in two: the bytes are the same as written at once (new in
96
+ 0.10.0). A 50 MB `put` held the event loop for 379 ms in 0.9; it now holds it for about 20 ms.
78
97
  - `put` writes the text first and the metadata last. `delete` removes the metadata first, and
79
- nothing else when that fails. A document never appears without its text, and is never listed once
80
- its text is gone.
81
- - Only IDs that match `DOCUMENT_ID_PATTERN` reach the file system. A read or a `delete` with another
82
- ID finds nothing, and `put`, `putIndex` and `putOriginal` throw "Invalid document ID."
98
+ nothing else when that fails: it throws, and the document stays whole. Once the metadata is
99
+ gone, the document is gone: `delete` returns true, and a text, index or original it could not
100
+ remove is left for `sweep` (new in 0.9.0: it threw). A document never appears without its text,
101
+ and is never listed once its text is gone.
102
+ - File names are document IDs: the library's (`doc_` and 32 hex digits), or, since 0.9.0, an
103
+ application's ([Application IDs](#application-ids)). `APP_DOCUMENT_ID_PATTERN` leaves out the
104
+ names Windows keeps for devices (`con`, `nul`, `com1` and the like), since `con.json` is not a
105
+ file there: `ingest` refuses them with a `TypeError`. A read or a `delete` with an ID that is not
106
+ valid finds nothing, and `put`, `putIndex` and `putOriginal` throw "Invalid document ID." The
107
+ library's IDs keep the names they had, so servers of 0.8 still read them.
108
+ - The names `<id>.json`, `<id>.txt`, `<id>.idx` and `<id>.bin`, and their temporary files, belong
109
+ to the store for every ID it is given. Without `scopes`, `directory` is a folder where your files
110
+ may sit too: an ingest under the ID `report` writes over your `report.txt`, and a `delete` or
111
+ `ifExists: "replace"` removes it. Keep your own files in a subfolder, or under other names.
112
+ - A read does not follow a link at a file name (new in 0.9.0): a document file that is a link counts
113
+ as missing. Windows cannot refuse such a link, so there it is followed.
114
+ - Files are written `0600` and folders made `0700` (new in 0.9.0: before, `0666` and `0777`, minus
115
+ the umask, which gave `0664` and `0775` under the usual `0002`). Only the user the server runs as
116
+ reads them. Servers or a backup job that run as other users of one group (a Kubernetes `fsGroup`)
117
+ need `fileMode: 0o640` and `directoryMode: 0o750`. Files written before keep their modes.
83
118
  - A missing file means a missing document. Any other failure of a read (a volume that does not
84
119
  answer, too many open files) is thrown, and the library passes it on as a `DocumentStoreError`.
85
120
  There are two exceptions: an index file that cannot be read is built again from the text, and
86
- `sweep` returns 0 when it cannot list the directory. A failed write or delete is thrown as it
87
- came ([Errors](#errors)). Metadata that cannot be parsed counts as absent.
88
- - `getMeta` removes a document that has expired, by the store's own clock (`now`).
121
+ `sweep` counts a folder it cannot list as empty. A failed write or delete is thrown as it came,
122
+ and the library wraps it ([Errors](#errors)). Metadata that cannot be parsed counts as absent.
123
+ - `getMeta` removes a document that has expired, by the store's own clock (`now`), and returns
124
+ undefined. Since 0.9.0 it does so also when the removal fails: the next `sweep` tries again.
89
125
  - `readTextRange` reads only the bytes asked for, so a tool call never loads a large file whole.
90
126
  The whole text is read only when the plan sends it in the prompt.
91
- - `sweep` removes expired documents and returns how many. It also removes files that belong to no
92
- document (an upload that failed, a server that stopped while writing) and temporary files, once
127
+ - A volume that stops answering (a hung NFS mount) is given up on after `storeTimeoutMs`, 30 s by
128
+ default (new in 0.10.0): see [Time limits](#time-limits) and
129
+ [Deployment](./deployment.md#a-store-that-stops-answering) for the thread pool.
130
+ - `sweep` removes expired documents and returns how many: those whose metadata it removed itself,
131
+ so two sweeps at once count each document once. Since 0.10.0 the metadata is first renamed to a
132
+ name of the sweep's own, then removed, so this holds on Windows too, where two removals of one
133
+ file at the same moment can both succeed. `delete` does the same. It also removes files that
134
+ belong to no document (an upload that failed, a server that stopped while writing) and temporary files, once
93
135
  they are `orphanAgeMs` old, one hour by default: a younger one may be an upload in progress on
94
- another server. A document whose metadata could not be read at all is left alone, whatever its
95
- age. One that cannot be removed is left for the next sweep, and does not stop this one.
96
- - The files are plain. The metadata names the owner, the file name, the headings and the log
97
- message templates. A delete removes the files without overwriting them. If that matters, encrypt
98
- the volume: see [Security](../security.md).
136
+ another server. A temporary name of a document's metadata is also young for `orphanAgeMs` after
137
+ it was renamed (its ctime): it may be a delete's, under way on another server. In a folder that may hold files of yours too (`directory` without `scopes`), it
138
+ removes such a file only when its name is an ID the library makes, or a temporary file:
139
+ `notes.txt` may be yours, not the text of a document `notes`. A document whose metadata could not
140
+ be read at all is left alone, whatever its age. One that cannot be removed is left for the next
141
+ sweep, and does not stop this one.
142
+ - `sweep` reads up to `sweepConcurrency` files at once (new in 0.9.0: one after another). A sweep
143
+ of 5,000 documents in one folder on a local SSD took about 2.5 s one file at a time, and about
144
+ 1.1 s 16 at a time.
145
+ - The files are plain. The metadata names the owner, the scope, the file name, the headings and the
146
+ log message templates. A delete removes the files without overwriting them. If that matters,
147
+ encrypt the volume: see [Security](../security.md).
99
148
 
100
149
  Several servers can share the directory on a network volume. What that needs, from where to run the
101
150
  sweep to servers of two versions during an upgrade, is in [Deployment](./deployment.md).
102
151
 
103
- ## Owners
152
+ ## Owners and scopes
104
153
 
105
154
  ### How ownership works
106
155
 
@@ -119,15 +168,15 @@ await files.delete(meta.id, { owner: "user-7" }); // false: nothing is remove
119
168
  await files.delete(meta.id, { owner: "user-42" }); // true
120
169
  ```
121
170
 
122
- | Call | Takes the owner as | A document of another owner |
171
+ | Call | Takes the owner (and the scope) as | A document of another owner or scope |
123
172
  |---|---|---|
124
- | `files.ingest(input)` | `input.owner` | |
125
- | `files.getMeta(id, access)` | `access.owner` | `undefined` |
126
- | `files.getOriginal(id, access)` | `access.owner` | `undefined` |
127
- | `files.delete(id, access)` | `access.owner` | `false`, and nothing is removed |
128
- | `files.prepare(ids, base, options)` | `options.owner` | Listed in `missing`, and never read |
129
- | `files.tools(documents, options)` | the `owner` of each `DocumentMeta` in `documents` (and in `viewPages`) | Each call that reads it answers `doc_… is no longer available on the server. Ask the user to attach the file again.` |
130
- | `askWithFiles(options)`, `askGemini(options)` | `options.owner` | `DocumentsNotFoundError`, before any model request |
173
+ | `files.ingest(input)` | `input.owner`, `input.scope` | |
174
+ | `files.getMeta(id, access)` | `access.owner`, `access.scope` | `undefined` |
175
+ | `files.getOriginal(id, access)` | `access.owner`, `access.scope` | `undefined` |
176
+ | `files.delete(id, access)` | `access.owner`, `access.scope` | `false`, and nothing is removed |
177
+ | `files.prepare(ids, base, options)` | `options.owner`, `options.scope` | Listed in `missing`, and never read |
178
+ | `files.tools(documents, options)` | `options.access` (new in 0.9.0); without it, the `owner` and `scope` of each `DocumentMeta` in `documents` (and in `viewPages`) | Each call that reads it answers `doc_… is no longer available on the server. Ask the user to attach the file again.` |
179
+ | `askWithFiles(options)`, `askStream(options)`, `askGemini(options)` | `options.owner`, `options.scope` | `DocumentsNotFoundError`, before any model request |
131
180
  | `createDocumentHandlers(files, options)` | `options.getOwner(request)` | 404 "This file is no longer available." on GET; `{ "deleted": false }` on DELETE |
132
181
 
133
182
  - An owner is a string that is not empty or only spaces. `ingest` throws a `TypeError` for `""`,
@@ -138,41 +187,163 @@ await files.delete(meta.id, { owner: "user-42" }); // true
138
187
  It throws the same for an owner from JavaScript that is neither a string nor a finite number,
139
188
  such as the user object in place of its ID. A number is accepted, as before. Reads with
140
189
  `owner: ""` work as before, so documents that 0.5.0 stored with that owner stay readable until
141
- they expire.
190
+ they expire (not under `requireOwner`, which refuses `""` on every call).
142
191
  - In `createDocumentHandlers`, a `getOwner` that returns such an owner is the server's mistake: the
143
192
  upload is answered 500 `{ "error": "Upload failed (empty owner)." }` for `""`, spaces only or
144
193
  `null`, and `{ "error": "Upload failed (owner is not a string)." }` for an object, a boolean,
145
194
  `NaN` or an array, before its body is read. Nothing is logged. Where every upload needs a
146
195
  signed-in user, throw an error with `status: 401` from `getOwner`; return `undefined` only where
147
196
  anonymous uploads are meant (`user?.id || undefined`); and return the user's ID, not the user.
197
+ Under `requireOwner`, `undefined` and `null` are a request that is not signed in: `401`
198
+ `{ "error": "Sign in first." }` on every route, and `""` or spaces only a `500` "(empty owner)" on
199
+ every route (new in 0.9.0).
148
200
  - A document of another owner looks exactly like one that does not exist, so a caller cannot learn
149
- that an ID is in use.
201
+ that an ID is in use. There is one exception: `ingest` with an
202
+ [application's ID](#application-ids) answers 409 when the ID is taken, whoever has it.
150
203
  - The comparison is exact (`===`): `"alice"` does not reach a document of `"Alice"` or of
151
204
  `"alice/chat-1"`. There is no hierarchy and no wildcard.
152
205
  - A document ingested without an owner can be used by anyone who has its ID, whether they pass an
153
- owner or not. With signed-in users, always pass one. In `createDocumentHandlers`, a `getOwner` that
206
+ owner or not. With signed-in users, always pass one, and turn on
207
+ [`requireOwner`](#requiring-an-owner-and-a-scope). In `createDocumentHandlers`, a `getOwner` that
154
208
  returns undefined makes an anonymous upload. To refuse a request without a user, throw from it with
155
209
  a status ([Web app](./web-app.md)).
210
+ - An owner of `null` from your store (a MongoDB driver writes a field that was left out as `null`)
211
+ counts as no owner, new in 0.9.0. Before, `getMeta` read such a document as missing for every
212
+ owner, and the tools as open to all.
156
213
  - The owner cannot be changed after ingest. Use a stable, opaque ID, not an email address that may
157
214
  change.
158
- - `files.tools(documents)` takes no owner option: it compares the owner stored with each document
159
- with the `owner` of the metadata it is given, and answers a mismatch as a document that is gone
160
- (`doc_… is no longer available on the server. …`). In a loop of your own, pass it only metadata
161
- from `prepare(ids, base, { owner })` or `getMeta(id, { owner })`
162
- ([Your own adapter and loop](./own-adapter-and-loop.md)). `askWithFiles` does this for you.
215
+ - `files.tools(documents, { access })` asks the store for each document with the owner and scope of
216
+ `access`, and checks the ones the store holds against them, as `getMeta` does. `askWithFiles`
217
+ passes it. Without `access`, as before 0.9.0, `tools` compares the owner and scope stored with
218
+ each document with those of the metadata it is given, and answers a mismatch as a document that
219
+ is gone. In a loop of your own, pass `access`
220
+ ([Your own adapter and loop](./own-adapter-and-loop.md)).
221
+
222
+ ### Scopes
223
+
224
+ A scope says where a document belongs, from the widest part to the narrowest: `[userId, chatId]`.
225
+ It is new in 0.9.0. Pass it at ingest and on every later call, as the owner:
226
+
227
+ ```ts
228
+ // `files` and `bytes` as above.
229
+ const scope = ["user-42", "chat-7"];
230
+ const notes = await files.ingest({ name: "notes.txt", bytes, owner: "user-42", scope });
231
+
232
+ await files.getMeta(notes.id, { owner: "user-42", scope }); // the metadata
233
+ await files.getMeta(notes.id, { owner: "user-42", scope: ["user-42", "chat-8"] }); // undefined
234
+ await files.getMeta(notes.id, { owner: "user-42" }); // undefined
235
+ ```
236
+
237
+ - The library keeps the scope in `meta.scope`, a copy, and passes it to every store call in the
238
+ [context](#writing-a-store-of-your-own). It never reaches the model or a summary. An event holds
239
+ it only with `eventResults: true`, in the full plan of `run.finish` and `run.error`
240
+ ([events](../reference/events.md#documents-eventresults-and-eventresult)).
241
+ - A document with a scope serves only a caller of the same scope, segment by segment: another
242
+ scope, a longer or a shorter one, or none, finds it missing. A document without a scope serves a
243
+ caller of any scope, unless the library has `requireScope`.
244
+ - A store may keep the documents of each scope apart: `MemoryDocumentStore` does, and
245
+ `FileDocumentStore` with [`scopes`](#files-in-a-folder-per-user-or-per-chat), so one ID in two
246
+ scopes is two documents. A store that ignores the context, as every store written for 0.8 does,
247
+ still keeps scopes apart for the library, through `meta.scope`: a caller of scope B never reads a
248
+ document of scope A.
249
+ - What the library keeps in memory is kept by scope too: a cached copy of a document of one scope
250
+ is never served to a caller of another, even when both documents have the same ID. Nor to another
251
+ owner: the copy is checked against the owner of the document the store holds now.
252
+ - A scope has 1 to 8 segments of 1 to 256 characters, with no control character, no `/` or `\`, and
253
+ none of them `.` or `..`. Another is a `DocumentScopeError` of code `"scope_invalid"`, whose
254
+ message never repeats a segment. `null` counts as no scope.
255
+ - Segments are compared exactly: `"Chat-7"` is not `"chat-7"`.
256
+
257
+ The owner says who may use a document. The scope says where it belongs. With both, one user's two
258
+ chats cannot use each other's files, and a store can lay the files of each chat out apart.
259
+
260
+ ### Requiring an owner and a scope
261
+
262
+ New in 0.9.0. On a server where every document belongs to a signed-in user, turn both on:
163
263
 
164
- ### Choosing the owner string
264
+ ```ts
265
+ import { createLargeFiles, MemoryDocumentStore } from "llm-large-files";
266
+
267
+ export const strict = createLargeFiles({ store: new MemoryDocumentStore(), requireOwner: true, requireScope: true });
268
+ ```
165
269
 
166
- The owner is any string you choose. The library has no notion of a chat or session, and cannot list
167
- documents by owner. Two schemes work well:
270
+ - Every call must then name its owner and its scope: `ingest`, `getMeta`, `getOriginal`, `delete`,
271
+ `prepare`, `askWithFiles`, `askStream`, `askGemini`, and `tools`, which needs `access`. A call
272
+ without one throws `TypeError("owner is required: requireOwner is on")` or
273
+ `TypeError("scope is required: requireScope is on")`, before the store is asked anything. A
274
+ forgotten owner fails loudly, instead of reaching every document stored without one.
275
+ - A document stored without an owner, or without a scope, then reads as missing, for every caller.
276
+ - `files.sweep()` needs no scope: it is upkeep of the store, not a user's access.
277
+ - `files.access` says which are on, for code that serves the library (the upload handlers).
278
+
279
+ ### Application IDs
280
+
281
+ New in 0.9.0. Give `ingest` the document's ID, such as the ID of the upload in your database:
282
+
283
+ ```ts
284
+ // `strict` and `bytes` as above; "upload-3f9a" is the ID of the upload in your own records.
285
+ const report = await strict.ingest({ name: "report.txt", bytes, owner: "user-42", scope: ["user-42", "chat-7"], id: "upload-3f9a" });
286
+ ```
168
287
 
169
- | Owner | What the library enforces | What your application does |
288
+ - The ID must match `APP_DOCUMENT_ID_PATTERN`: lowercase letters, digits, `_` and `-`, up to 64
289
+ characters, starting with a letter or a digit. Another is a `TypeError`. Without an `id`, the
290
+ library makes one, as before.
291
+ - The model sees the ID, in the cards and the tool calls. It must hold no personal data: not an
292
+ email address, not a name.
293
+ - `ifExists: "fail"`, the default, refuses an ID that is taken with an `IngestError` of code
294
+ `"exists"` (status 409), before the file is read. `ifExists: "replace"` deletes the document there,
295
+ then stores the new one, but only one of the same owner and scope. A document of another owner or
296
+ scope is `"exists"` too, even when its text seems to be gone: a store that loses the context of a
297
+ read would say that of a document that is there. A document that has expired is written over in
298
+ both cases.
299
+ - The store is asked "is this ID taken?" in the scope of the ingest. Over a store that ignores the
300
+ context, the question spans every scope: one chat cannot write over another chat's document, and
301
+ the IDs must be unique in the whole store.
302
+ - In one library, one ID is stored by one ingest at a time. While an ingest of an ID is under way,
303
+ from its first look at the store to the end of its writes, another ingest of that ID is
304
+ `"exists"`, whatever its `ifExists`, owner or scope. A user who uploads the same file twice at once
305
+ gets a 409 for the second.
306
+ - When the writes (or the clean-up after a write that failed) do not end within `ingestTimeoutMs`,
307
+ the ingest throws, but its writes may still land. So the ID stays held in that library until they have ended, and the removal of what they
308
+ wrote too. This fails closed: a store that never answers keeps that one ID refused in that library
309
+ until the process restarts.
310
+ - Across servers, the store is asked twice: before the file is read, and just before the writes.
311
+ Two servers can still both find an ID free and write it at the same moment. The library assumes
312
+ that two ingests of one ID on two servers at once are the same upload, sent twice: the last write
313
+ wins. Over a store that hides a record until its text is written, as the
314
+ [example](#example-object-storage-and-a-database) does, both usually fail with a 503 instead, and
315
+ nothing is stored. So give each upload an ID of its own.
316
+ - When a write fails, the ingest removes what it wrote, but only while the document under the ID is
317
+ its own. A document whose metadata it finds there, and that is not its own, is left. If that one
318
+ has not expired and is of another owner or scope (another server stored it meanwhile), the ingest
319
+ throws `"exists"`. Otherwise, as when the delete of the document a replace was to remove fails, it
320
+ throws the store's error (503), as for any failed write.
321
+ - The clean-up sees only metadata. The parts of a document that another server is still writing at
322
+ that moment (its original, its index; with a store that hides a record until its text is written,
323
+ as the example does, that record and its text too) may be removed. One more reason to give each
324
+ upload an ID of its own.
325
+ - A 409 tells the caller that the ID is taken, whoever has it: over a store that ignores the
326
+ context, in any scope. So an ID that can be guessed can be probed. Use random IDs, as
327
+ [`attach()` below](#a-layout-per-user-and-per-chat) does
328
+ (`` `up-${randomUUID().replaceAll("-", "")}` ``), or IDs that start with the tenant's own prefix.
329
+ - Replacing a document is not atomic for readers on other servers: for a moment it is missing.
330
+ - An ID you choose keeps the stored rounds of a conversation valid: a file ingested again under the
331
+ same ID is found by the `toolTurns` that name it ([Conversations](./conversations.md)).
332
+
333
+ ### Choosing the owner and the scope
334
+
335
+ The owner and the scope are strings you choose. The library cannot list documents by owner or by
336
+ scope. A good fit for a chat application:
337
+
338
+ | Field | Value | What the library enforces |
170
339
  |---|---|---|
171
- | The user: `userId` | No user can use another user's documents. | Keeps each chat's document IDs in its session record and passes those, never a list from the browser as it came. A document can serve several chats of its user. |
172
- | The user and the chat: `` `${userId}/${sessionId}` `` | A document can be used only in the chat it was uploaded to. | Builds the same string for every call: upload, questions, GET, DELETE. `getOwner` must then know the chat, from the URL or a header. A file used in two chats is uploaded twice. |
340
+ | `owner` | `userId` | No user can use another user's documents. |
341
+ | `scope` | `[userId, chatId]` | A document can be used only in the chat it was uploaded to. A file used in two chats is uploaded twice. |
342
+ | `id` | the upload's ID | The ID your session record keeps is the document's ID. |
173
343
 
174
- The [Conversations](./conversations.md) guide uses the first scheme. To switch to the second,
175
- change the `owner` you pass, everywhere.
344
+ Build the same owner and scope for every call: upload, questions, GET, DELETE. Before 0.9.0, an
345
+ owner of `` `${userId}/${sessionId}` `` did the work of the scope. It still works, but a store
346
+ cannot lay files out by it, and the owner is no longer one user.
176
347
 
177
348
  ### A layout per user and per chat
178
349
 
@@ -183,17 +354,20 @@ list of a chat's documents:
183
354
  ```ts
184
355
  // chat-documents.ts. `files` is your library; `sessions` and `turns` are the collections of the
185
356
  // Conversations guide.
357
+ import { randomUUID } from "node:crypto";
186
358
  import { toDocumentSummary, type DocumentSummary } from "llm-large-files";
187
359
 
188
- /** Adds a file to a chat. The user owns it, and the session record lists it. */
360
+ /** Adds a file to a chat. The user owns it, the chat is its scope, and the session record lists it. */
189
361
  export async function attach(userId: string, sessionId: string, file: { name: string; mimeType?: string; bytes: Uint8Array }): Promise<DocumentSummary> {
190
362
  if (!await sessions.findOne({ _id: sessionId, userId })) throw new Error("No such chat.");
191
- const meta = await files.ingest({ ...file, owner: userId });
363
+ const scope = [userId, sessionId];
364
+ // The document's ID is yours: here a new one, as the ID of an upload record would be.
365
+ const meta = await files.ingest({ ...file, owner: userId, scope, id: `up-${randomUUID().replaceAll("-", "")}` });
192
366
  try {
193
367
  await sessions.updateOne({ _id: sessionId, userId }, { $addToSet: { documentIds: meta.id } });
194
368
  } catch (error) {
195
369
  // A document that no chat lists would stay until it expires.
196
- await files.delete(meta.id, { owner: userId }).catch(() => undefined);
370
+ await files.delete(meta.id, { owner: userId, scope }).catch(() => undefined);
197
371
  throw error;
198
372
  }
199
373
  return toDocumentSummary(meta);
@@ -210,50 +384,145 @@ export async function documentsFor(userId: string, sessionId: string, picked?: s
210
384
  export async function deleteChat(userId: string, sessionId: string): Promise<void> {
211
385
  const session = await sessions.findOne({ _id: sessionId, userId });
212
386
  if (!session) return;
213
- for (const id of session.documentIds) await files.delete(id, { owner: userId });
387
+ for (const id of session.documentIds) await files.delete(id, { owner: userId, scope: [userId, sessionId] });
214
388
  await turns.deleteMany({ sessionId });
215
389
  await sessions.deleteOne({ _id: sessionId, userId });
216
390
  }
217
391
  ```
218
392
 
219
- - Ask with `owner: userId` and `documentIds: await documentsFor(userId, sessionId)`. When documents
220
- have expired, the question throws `DocumentsNotFoundError` with their IDs:
221
- [Conversations](./conversations.md) shows how to take them off the chat and ask the user for them
222
- again.
393
+ - Ask with `owner: userId`, `scope: [userId, sessionId]` and
394
+ `documentIds: await documentsFor(userId, sessionId)`. When documents have expired, the question
395
+ throws `DocumentsNotFoundError` with their IDs, or, with `onMissingDocuments: "drop"` (new in
396
+ 0.9.0), is answered without them and lists them in `result.missing`:
397
+ [Conversations](./conversations.md#documents-that-are-gone) shows how to take them off the chat
398
+ and ask the user for them again.
223
399
  - `files.delete` gives false for a document that has already expired or been deleted. There is
224
400
  nothing left to do for it.
225
- - If your application lets a document serve several chats, delete it only when no other chat lists
226
- it.
227
- - The `upload` handler of `createDocumentHandlers` answers the request itself, so it cannot record
228
- the new ID in your session. Call `attach` from a route of your own, or record the ID the browser
229
- sends back in a second request, after checking it with `files.getMeta(id, { owner })`. Routes are
230
- in [Web app](./web-app.md).
401
+ - Over a `FileDocumentStore` with `scopes`, `deleteChat` can remove the chat's folder in place of
402
+ each document ([below](#files-in-a-folder-per-user-or-per-chat)).
403
+ - The `upload` handler of `createDocumentHandlers` answers the request itself. Since 0.9.0 its
404
+ hooks do what `attach` does: `prepareUpload` gives the upload its ID (and can save the body in the
405
+ chat's folder), and `onUploaded` records the ID in your session, or fails the upload
406
+ ([Web app](./web-app.md#save-each-upload-where-you-keep-it-prepareupload)). Otherwise call
407
+ `attach` from a route of your own.
231
408
  - To delete everything of a user (an account that is closed), collect the IDs from the user's chats.
232
409
  The library cannot find a user's documents. A store of your own can, if it keeps the owner where it
233
- can query it, as the [example store](#example-object-storage-and-a-database) does.
410
+ can query it, as the [example store](#example-object-storage-and-a-database) does: the context of
411
+ every call gives it the owner and the scope.
234
412
 
235
413
  ### Files in a folder per user or per chat
236
414
 
237
- Every call but `put` gives a store the document ID without its metadata. `putOriginal` and
238
- `putIndex` come before `put`, so a store cannot know the owner of a file it is writing.
239
- A store therefore keys its files by document ID, and the layout by user and chat lives in your
240
- database: the session record lists the IDs, and a store of your own can keep the owner next to each
241
- document.
242
-
243
- If your storage rules need each chat's files in a folder of their own, give each chat a library of
244
- its own, over its own `FileDocumentStore`:
415
+ New in 0.9.0. Give `FileDocumentStore` the `scopes` option, and one library serves every user and
416
+ every chat, with each chat's files in a folder of its own:
245
417
 
246
418
  ```ts
419
+ import { mkdir } from "node:fs/promises";
247
420
  import path from "node:path";
248
- import { createLargeFiles, FileDocumentStore, type LargeFiles } from "llm-large-files";
421
+ import { createLargeFiles, FileDocumentStore, isSafeScopeSegment, toDocumentSummary } from "llm-large-files";
422
+
423
+ const DOCUMENTS_DIR = process.env.DOCUMENTS_DIR!;
424
+
425
+ // One store and one library for the process: their limits hold for every chat at once.
426
+ export const store = new FileDocumentStore(DOCUMENTS_DIR, { scopes: { depth: 2 } });
427
+ export const files = createLargeFiles({ store, requireOwner: true, requireScope: true });
428
+
429
+ /**
430
+ * Makes the folder of a chat. Call it once, when you create the chat's record, not on each upload:
431
+ * an upload after you removed the folder must fail, not make it again.
432
+ */
433
+ export async function startChat(userId: string, chatId: string) {
434
+ // Check the IDs before they become a path. For IDs that do not pass, use hashedScopeSegment.
435
+ if (!isSafeScopeSegment(userId) || !isSafeScopeSegment(chatId)) throw new TypeError("The user or chat ID cannot name a folder.");
436
+ await mkdir(path.join(DOCUMENTS_DIR, userId, chatId), { recursive: true, mode: 0o700 });
437
+ }
438
+
439
+ /** Adds a file to a chat. `uploadId` is the ID of the upload in your records: lowercase, as UUIDs are. */
440
+ export async function upload(userId: string, chatId: string, uploadId: string, file: { name: string; bytes: Uint8Array }) {
441
+ // The store makes only its own folder in the chat's. A chat whose folder is gone: "scope_missing".
442
+ const meta = await files.ingest({ ...file, owner: userId, scope: [userId, chatId], id: uploadId });
443
+ return toDocumentSummary(meta);
444
+ }
445
+ ```
446
+
447
+ The volume then holds:
448
+
449
+ ```text
450
+ <DOCUMENTS_DIR>/
451
+ user-42/
452
+ chat-7/
453
+ .llm-large-files/ the store's: upload-3f9a.json, upload-3f9a.txt, upload-3f9a.idx
454
+ uploads/ yours, if you keep the uploads: the sweep never goes in, and fileOriginals reads them
455
+ ```
249
456
 
250
- // One case only: on a volume that ignores case, "Alice" and "alice" would be one folder.
251
- const SAFE_ID = /^[a-z0-9_-]{1,64}$/;
457
+ - Pass the same `scope` on every later call: questions (`askWithFiles({ owner, scope })`),
458
+ `getMeta`, `getOriginal`, `delete`. A document of one chat is not found from another, even under
459
+ the same ID: the folder is the boundary, and the library checks `meta.scope` too.
460
+ - `depth` is the number of segments of every scope: 2 for `[userId, chatId]`. A scope of another
461
+ length, or a call without one, throws a `DocumentScopeError` (`"scope_invalid"`,
462
+ `"scope_required"`).
463
+ - Each segment names a folder, so it must pass `isSafeScopeSegment`: lowercase letters, digits,
464
+ `_` and `-`, up to 64 characters, and no name Windows keeps for a device (`con`, `nul`). Lower
465
+ case only, because SMB and Azure Files ignore case: `Alice` and `alice` would share a folder. IDs
466
+ your database makes (UUIDs, MongoDB ObjectIds in lowercase hex) pass as they are. For IDs in mixed
467
+ case, or in Hebrew, pass `hashedScopeSegment(userId)` as the segment, everywhere: it gives `h` and
468
+ 40 hex digits of the ID's SHA-256. Name the folders you make and remove with it too.
469
+ - The store makes its own folder (`.llm-large-files`, the `folder` option) inside a chat's folder
470
+ that exists, and never the chat's folder itself. To delete a chat, stop its questions, then remove
471
+ its folder: `rm(path.join(DOCUMENTS_DIR, userId, chatId), { recursive: true, force: true, maxRetries: 5 })`.
472
+ An upload that finishes after that throws a `DocumentScopeError` of code `"scope_missing"`,
473
+ instead of making the folder again. Reads in that chat find nothing. An upload being stored at
474
+ that moment can write its files into the folder while `rm` empties it. Without `maxRetries`, `rm`
475
+ then fails with `ENOTEMPTY`; with it, `rm` looks again and removes them. Remove the chat's other
476
+ data (its record, its messages) before the folder: if `rm` still fails, only files are left, for
477
+ a cleanup job. To delete a user, remove the user's folder the same way.
478
+ - `createScopeFolders: true` makes the folders of a chat at its first upload, for an application
479
+ that keeps none of its own. The removal above then cannot stop a late upload. It makes them one
480
+ level at a time, and makes nothing where a link points.
481
+ - `folder: ""` puts the store's files in the chat's folder itself, beside yours. The names
482
+ `<id>.json`, `.txt`, `.idx` and `.bin`, and their temporary files, then belong to the store for
483
+ every ID it is given: an ingest under the ID `report` writes over your `report.txt`. Keep your own
484
+ files in a subfolder, such as `uploads/`, or under other names.
485
+ - `files.sweep()` sweeps every chat: it goes down exactly `depth` levels of folders, into folders
486
+ whose names a segment may have, and never follows a link. `files.sweep({ scope })` sweeps one
487
+ chat's folder. Run it from one server ([Deployment](./deployment.md#sweeping-expired-documents)).
488
+ - A folder of a scope that is a link, or lies under one, is refused with `"scope_invalid"`: a call
489
+ checks that the folder is where its path says, inside `DOCUMENTS_DIR`. Writes, deletes and sweeps
490
+ check every time. A read takes a folder checked less than a second ago as checked, so a link put
491
+ in place of a chat's folder is seen by reads within a second. A link at a file name is not
492
+ followed either, except on Windows.
493
+ - That check costs one `realpath` of the chat's folder, a look at each folder on its path. Reads
494
+ share it for a second, so a search that reads a large document by range checks once a second,
495
+ not once a read. On a local SSD, 10,000 ranged reads in a chat's folder took 0 to 17% longer than
496
+ in the flat layout; when each read checked, they took 40 to 60% longer. On a network volume each
497
+ of those looks can be a round trip.
498
+ - Documents ingested before 0.9.0 are in `DOCUMENTS_DIR` itself. `unscoped: "root"` serves a call
499
+ without a scope from there, as before, until they expire, and `files.sweep()` sweeps them too.
500
+ It cannot go with `requireScope`, which refuses such calls first.
501
+ - A wrapper or a subclass of the store must pass the context on (`super.getMeta(id, context)`).
502
+ Without it, every call but `sweep` throws `"scope_required"`, and a `sweep` sweeps every chat.
503
+ Under `unscoped: "root"` nothing throws: the text and the metadata go to the root folder, outside
504
+ the chat's folder, and removing that folder does not erase them. Another chat still cannot read
505
+ them: the library checks `meta.scope`.
506
+ - Servers of 0.8 do not see these folders, nor documents under an application's ID: during an
507
+ upgrade they find them missing ([Deployment](./deployment.md#servers-of-two-versions)).
508
+
509
+ One library for the process keeps its limits for the whole process: `maxConcurrentIngests` and its
510
+ queue, `cacheBytes` and `maxConcurrentScans` bound every chat together, and a document read in one
511
+ question stays in the cache for the next.
512
+
513
+ #### A library per chat
514
+
515
+ Before 0.9.0, the only way to a folder per chat was a library per chat, each over its own
516
+ `FileDocumentStore`. It still works:
517
+
518
+ ```ts
519
+ import path from "node:path";
520
+ import { createLargeFiles, FileDocumentStore, isSafeScopeSegment, type LargeFiles } from "llm-large-files";
252
521
 
253
522
  /** The library of one chat: its files are in <DOCUMENTS_DIR>/<user>/<chat>/. */
254
523
  export function filesOf(userId: string, sessionId: string): LargeFiles {
255
524
  // The IDs become a path: refuse anything that could lead out of the directory.
256
- if (!SAFE_ID.test(userId) || !SAFE_ID.test(sessionId)) throw new Error("Invalid user or chat ID.");
525
+ if (!isSafeScopeSegment(userId) || !isSafeScopeSegment(sessionId)) throw new Error("Invalid user or chat ID.");
257
526
  return createLargeFiles({
258
527
  store: new FileDocumentStore(path.join(process.env.DOCUMENTS_DIR!, userId, sessionId)),
259
528
  cacheBytes: 32 * 1024 * 1024, // each library has a cache of its own
@@ -261,22 +530,17 @@ export function filesOf(userId: string, sessionId: string): LargeFiles {
261
530
  }
262
531
  ```
263
532
 
264
- On a volume that ignores case (Windows, macOS, SMB shares), IDs that differ only in case would
265
- share a folder, so the check takes lower case only. If your IDs are mixed case and unique
266
- regardless of case, lower-case them before the check. IDs your database makes, such as UUIDs or
267
- MongoDB ObjectIds in lower-case hex, pass it as they are.
268
-
269
- What that costs:
533
+ What that costs, against one library over a store with `scopes`:
270
534
 
271
535
  - `cacheBytes`, `maxConcurrentScans` and `maxConcurrentIngests` bound each library, not the process,
272
- and `maxPendingUploadBytes` each set of upload handlers. With a library per chat, ingests of
273
- different chats all work at once, as before 0.8.2: bound them for the process yourself, with one
274
- queue or count shared by the chats' routes. A library made for one request starts with an empty
275
- cache, so each question reads its documents from the store again.
536
+ and `maxPendingUploadBytes` each set of upload handlers. Ingests of different chats all work at
537
+ once, as before 0.8.2: bound them for the process yourself, with one queue or count shared by the
538
+ chats' routes. A library made for one request starts with an empty cache, so each question reads
539
+ its documents from the store again.
276
540
  - Each chat's folder needs a sweep of its own: `new FileDocumentStore(folder).sweep()` for each one.
277
- The store never removes the folder itself.
278
- - Deleting a chat is removing its folder, once no question of that chat is running.
279
- - A document of another chat is not found: the folder is the boundary.
541
+ - The store makes the chat's folder again at a late upload, after you removed it.
542
+ - The store's files sit in the chat's folder itself, so its sweep leaves files of no document there
543
+ unless their names are the library's own IDs.
280
544
 
281
545
  ## Retention
282
546
 
@@ -324,7 +588,9 @@ setInterval(() => {
324
588
  provider keeps is in [Security](../security.md).
325
589
 
326
590
  A chat that lives longer than `ttlMs` loses its documents, and its next question throws
327
- `DocumentsNotFoundError`. To keep documents as long as their chat:
591
+ `DocumentsNotFoundError`, unless it is asked with `onMissingDocuments` (new in 0.9.0): `"drop"`
592
+ answers without them, and a function can ingest them again from the uploads you kept
593
+ ([missing documents](../reference/ask.md#missing-documents)). To keep documents as long as their chat:
328
594
 
329
595
  - Set a `ttlMs` longer than your chats live.
330
596
  - Or set `ttlMs: Infinity`, and delete the documents yourself: with their chat (`deleteChat` above),
@@ -339,11 +605,24 @@ A chat that lives longer than `ttlMs` loses its documents, and its next question
339
605
 
340
606
  ## Keeping the uploaded files
341
607
 
342
- By default a store keeps only the text of a document. `keepOriginals` also keeps the uploaded file:
608
+ By default only the text of a document is kept. `keepOriginals` keeps the uploaded file too, for
609
+ the formats it lists, so that `view_pages` can show the model the pages of a PDF, and a scanned PDF
610
+ can be accepted ([PDFs](./pdfs.md)). The file is kept in one of two places:
611
+
612
+ - **A copy in the store**, next to the text (`putOriginal`).
613
+ - **Where your application keeps it**, new in 0.9.0: the ingest gives `original: { ref }`, and the
614
+ library reads the file from there through `originals`. The store keeps no second copy.
343
615
 
344
616
  | Option | Default | What it does |
345
617
  |---|---|---|
346
- | `keepOriginals` | `[]` | Formats whose uploaded file is kept next to its text, for example `["pdf"]`. |
618
+ | `keepOriginals` | `[]` | Formats whose uploaded file is kept, for example `["pdf"]`. |
619
+ | `originals` | none | Reads the files your application keeps, by their ref: `fileOriginals(root)` of `llm-large-files/node`, or your own `{ read(ref, context) }`. New in 0.9.0. |
620
+
621
+ Either way, `meta.originalKept` is true, `files.getOriginal(id, { owner, scope })` returns the
622
+ file under the same owner and scope rules as everything else, and `view_pages` reads it. Treat the
623
+ bytes as read-only: they may be the store's own copy.
624
+
625
+ ### A copy in the store
347
626
 
348
627
  ```ts
349
628
  import type { ServerResponse } from "node:http";
@@ -377,29 +656,144 @@ export async function sendOriginal(response: ServerResponse, id: string, owner:
377
656
 
378
657
  - It is off by default because it costs space: a kept file is as large as the upload, up to
379
658
  `maxUploadBytes` (100 MB by default), and stays until the document expires or is deleted.
380
- - A kept original is what `view_pages` shows the model, and what lets a scanned PDF be accepted.
381
- Both are in [PDFs](./pdfs.md).
382
659
  - The store needs `putOriginal` to keep a file and `getOriginal` to give it back. The built-in stores
383
- have both. A store without `putOriginal` keeps nothing, whatever `keepOriginals` says.
384
- - `meta.originalKept` is true when the file of a document is kept. `files.getOriginal(id, { owner })`
385
- returns it, under the same owner rule as everything else. Treat the bytes as read-only: they may be
386
- the store's own copy.
660
+ have both. A store without `putOriginal` keeps no copy, whatever `keepOriginals` says.
661
+ - The bytes are checked when they are read back. Since 0.9.0, `getOriginal` and `view_pages` ask
662
+ the store for the metadata again once the file is read, and the file is missing unless the
663
+ document is still the same one, of the same owner and scope, and the file is that of the upload:
664
+ of its size (`meta.bytes`) and, for documents of 0.9.0 and later, of its SHA-256 (`meta.sha256`).
665
+ Another server may have deleted the document and stored another under its ID meanwhile, and a
666
+ store may give back another file of the same size.
387
667
  - Documents ingested before you turned it on have no original. Upload them again to get one.
388
668
 
669
+ ### The file your application keeps
670
+
671
+ New in 0.9.0. When your application saves each upload anyway (to send it back, or to ingest it
672
+ again later), keep only that one. The ingest says where it is, and the library reads it from there.
673
+ With `createDocumentHandlers`, `prepareUpload` saves the body there and gives the ref
674
+ ([Web app](./web-app.md#save-each-upload-where-you-keep-it-prepareupload)); a route of your own
675
+ saves it, then calls `ingest`:
676
+
677
+ ```ts
678
+ import path from "node:path";
679
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
680
+ import { fileOriginals } from "llm-large-files/node";
681
+
682
+ const VOLUME = process.env.DOCUMENTS_DIR!;
683
+
684
+ export const files = createLargeFiles({
685
+ store: new FileDocumentStore(VOLUME, { scopes: { depth: 2 } }),
686
+ keepOriginals: ["pdf"],
687
+ originals: fileOriginals(VOLUME),
688
+ requireOwner: true,
689
+ requireScope: true,
690
+ });
691
+
692
+ /** Ingests an upload your route saved at <VOLUME>/<user>/<chat>/uploads/<uploadId>. */
693
+ export function ingestSaved(userId: string, chatId: string, uploadId: string, name: string) {
694
+ const ref = `${userId}/${chatId}/uploads/${uploadId}`;
695
+ return files.ingest({
696
+ name,
697
+ source: { path: path.join(VOLUME, ref) }, // read at its turn, not held while it waits
698
+ original: { ref },
699
+ owner: userId,
700
+ scope: [userId, chatId],
701
+ id: uploadId,
702
+ });
703
+ }
704
+ ```
705
+
706
+ - **The ref** is a string of 1 to 1,024 characters that your reader understands: for
707
+ `fileOriginals(root)`, a path relative to `root`. It is never sent to the model, nor in a summary.
708
+ An event holds it only with `eventResults: true`, in the full plan of `run.finish` and
709
+ `run.error` ([events](../reference/events.md#documents-eventresults-and-eventresult)). An ingest with `original` in a library without `originals` throws a `TypeError`. A
710
+ format that `keepOriginals` does not list records nothing, whatever the ref.
711
+ - **What is recorded.** `meta.original` is `{ ref, bytes, sha256 }`: the ref, and the size and
712
+ SHA-256 of the file at ingest. `meta.originalKept` is true, as for a copy. The store's
713
+ `putOriginal` is not called.
714
+ - **Each read is checked.** `getOriginal` and `view_pages` read the ref the store holds (never one
715
+ from metadata handed in), ask the store for the metadata again, then compare the file with the
716
+ size and SHA-256 recorded. A file that has changed gives `undefined` from `getOriginal`, and
717
+ `view_pages` tells the model: "report.pdf changed on the server since it was read. Attach it
718
+ again to look at its pages." A file that is gone reads as missing.
719
+ - **The library never writes, moves or deletes it.** `files.delete` and the sweep leave it. Remove
720
+ it with its chat: over a scoped store, `rm` of the chat's folder removes the store's files and
721
+ your uploads together.
722
+ - **`fileOriginals(root)`** resolves a ref under `root`, and refuses one that leads out of it with a
723
+ `TypeError`, which the library passes on as a `DocumentStoreError`. A link at any level below
724
+ `root` reads as missing. It reads a file once, at most one byte past the size recorded, and never
725
+ writes ([`fileOriginals`](../reference/node.md#fileoriginalsroot)).
726
+ - **A reader of your own** is an object with `read(ref, context)`, which returns the bytes, or
727
+ `undefined` when the file is not there: a bucket key, a database ID. `context` has the scope and
728
+ owner of the call, the document's `id`, and `bytes`, the size recorded; a reader may stop one
729
+ byte past it. What it throws becomes a `DocumentStoreError` (operation `"read"`) with its error as
730
+ `cause` ([`OriginalsReader`](../reference/library.md#originalsreader)).
731
+ - **The same file twice.** Every document of 0.9.0 has `meta.sha256`, the SHA-256 of the upload,
732
+ for bytes and for paths. The library does not look for another document of the same file: to
733
+ give a user the document of a file already in the chat, compare it with the `sha256` your
734
+ session record keeps for the chat's documents. Never across owners.
735
+
389
736
  ## Writing a store of your own
390
737
 
391
738
  A store of your own implements `DocumentStore`: four methods are required, six are optional. The
392
739
  library calls them. Your application calls them only to test the store, or to sweep a store that no
393
740
  library uses.
394
741
 
742
+ Every method takes a last, optional `context`, new in 0.9.0: the scope and the owner of the call
743
+ ([`DocumentContext`](../reference/library.md#documentcontext)), as in `getMeta(id, context?)`. The
744
+ table below leaves it out. A store written for 0.8, without it, still compiles and works, unless
745
+ a method takes a parameter of its own in its place
746
+ ([Does my code compile?](../upgrading-0.9.md#does-my-code-compile)).
747
+
748
+ - Use `context.scope` as the boundary of your storage, if you want one: a key prefix, a folder, a
749
+ filter on a collection. `context.owner` lets you index documents by user. A store that ignores
750
+ the context still keeps scopes apart for the library, through `meta.scope`; an application's IDs
751
+ must then be unique in the whole store.
752
+ - A store that wraps another one, or a subclass that overrides a method, passes the context on.
753
+ One that drops it loses the scope of every call: over a store that keeps scopes apart, such a
754
+ call does not find the documents stored in a scope. Over a `FileDocumentStore` with `scopes`,
755
+ every call but `sweep` throws; with `unscoped: "root"`, the documents go to the root folder,
756
+ outside the chat's folder, without an error. A `sweep` that drops it sweeps every scope.
757
+
758
+ ```ts
759
+ import { FileDocumentStore, type DocumentContext, type DocumentMeta } from "llm-large-files";
760
+
761
+ /** Counts the reads of metadata, and passes the context on, as every method of a wrapper must. */
762
+ export class CountingStore extends FileDocumentStore {
763
+ reads = 0;
764
+
765
+ override async getMeta(id: string, context?: DocumentContext): Promise<DocumentMeta | undefined> {
766
+ this.reads++;
767
+ return super.getMeta(id, context); // not super.getMeta(id)
768
+ }
769
+ }
770
+ ```
771
+
772
+ Which context a call carries:
773
+
774
+ - At ingest, every write and every look-up carries the owner and the scope of the new document.
775
+ - `getMeta`, `getOriginal` and `delete` carry those of the caller.
776
+ - The reads of a document's text carry the caller's scope and the document's owner: `get`,
777
+ `readTextRange`, `getIndex`, and `putIndex` when an index is built again. The library reads them
778
+ only once `getMeta` has found, in the caller's scope, a document the caller may use. So the scope
779
+ is where the document was found, even when its metadata has none (a document of 0.8 that you moved
780
+ into a scope). The owner is left out when the document has none, whoever asked. The library keeps
781
+ one copy of a document for all callers of a scope: its reads carry one context whoever made them.
782
+ A store that logs who reads should log the caller from `getMeta`.
783
+ - A wrapper or a cache in front of a store must never keep what `readTextRange` or `getIndex` gave
784
+ by ID alone: key it by the context too. Bytes read by range carry nothing that the library can
785
+ check them by (see [Reading by range](#reading-by-range)).
786
+ - A store keeps at most one document of an ID in a scope. It may keep the scopes apart; it must not
787
+ keep a document of one ID for each owner in one scope.
788
+
395
789
  ### The methods
396
790
 
397
791
  | Method | Required | When the library calls it | What it must do |
398
792
  |---|---|---|---|
399
793
  | `put(document)` | Yes | `ingest`, last, after `putOriginal` and `putIndex`. | Keep `document.meta` whole, as one object, and `document.text`. Keep the text exactly, as UTF-8: `readTextRange` offsets point into those bytes. Let the document appear only once all of it is written. |
400
- | `getMeta(id)` | Yes | Before every use of a document: `getMeta`, `getOriginal`, `delete`, `prepare` (once a document), and every tool call that reads one. | Return the metadata, or undefined when there is no such document. Keep it cheap: one look-up by key, without reading the text. |
794
+ | `getMeta(id)` | Yes | Before every use of a document: `getMeta`, `getOriginal`, `delete`, `prepare` (once a document), and every tool call that reads one. Once more after a document is read by range, or its original file is read. | Return the metadata, or undefined when there is no such document. Keep it cheap: one look-up by key, without reading the text. Return a field that was left out (`owner`, `scope`) absent, not `null`. |
401
795
  | `get(id)` | Yes | To load a document whole: one whose text is at most `wholeDocumentBytes`, or any document when the store has no `readTextRange`. Once a library while the document stays in the cache. | Return `{ meta, text }` with the text exactly as `put` got it, or undefined. |
402
- | `delete(id)` | Yes | `files.delete`, after the owner check. And `ingest`, to clean up after a write that failed. | Remove the metadata first, then the text, the index and the original. Return true when the document was there. Cope with a document that was only partly written. |
796
+ | `delete(id)` | Yes | `files.delete`, after the owner check. And `ingest`: to clean up after a write that failed, or a listener that threw on `ingest.finish`, only while the document under the ID is that ingest's own; and with `ifExists: "replace"`, to remove the document it replaces. | Remove the metadata first, then the text, the index and the original. When the metadata cannot be removed, throw, and leave the rest. Return true when the document was there. Cope with a document that was only partly written. |
403
797
  | `sweep(now?)` | No | `files.sweep()`, with the library's clock. | Remove the documents whose `expiresAt` is at or before `now`, with all their parts. Return how many. |
404
798
  | `putOriginal(id, bytes)` | No | `ingest`, first, when `keepOriginals` lists the format. | Keep the bytes as they are now: the caller may reuse its buffer afterwards. |
405
799
  | `getOriginal(id)` | No | `files.getOriginal` and `view_pages`, for a document whose `meta.originalKept` is true. | Return the bytes, or undefined. |
@@ -408,15 +802,20 @@ library uses.
408
802
  | `getIndex(id)` | No | When a document read by range is opened. | Return the bytes `putIndex` kept, or undefined. A damaged index is noticed and built again. |
409
803
 
410
804
  The library checks `expiresAt` itself, with its own clock, before every use. Your `getMeta` and
411
- `get` may return a document that has expired; your `sweep` must remove it.
805
+ `get` may return a document that has expired; your `sweep` must remove it. If they remove an expired
806
+ document when they meet one, as the built-in stores do, they return undefined even when the removal
807
+ fails: an error there reaches the user as "try again" for a document that is gone, on every try.
412
808
 
413
809
  Keep every field of `meta`, including those your store does not know. Later versions add optional
414
- fields: 0.4.1 added `jsonBytes`, and 0.6.0 `encoding` and `replacedCharacters`, which say how a
415
- text file that was not valid UTF-8 was read ([PDFs and other formats](./pdfs.md#text-encodings)).
810
+ fields: 0.4.1 added `jsonBytes`, 0.6.0 `encoding` and `replacedCharacters`, which say how a
811
+ text file that was not valid UTF-8 was read ([PDFs and other formats](./pdfs.md#text-encodings)),
812
+ and 0.9.0 `metaVersion`, on every document it ingests
813
+ ([`DOCUMENT_META_VERSION`](../reference/library.md#document_meta_version)).
416
814
  A store that checks `meta` against a fixed list of fields (a `$jsonSchema` with
417
815
  `additionalProperties: false`, a Mongoose schema in strict mode that throws) refuses the ingest of
418
816
  every file that has them: a text file not in UTF-8, a UTF-8 log cut at a byte count, an ASCII log
419
- with a stray byte. `createDocumentHandlers` then answers 500 "Upload failed.". A store that keeps
817
+ with a stray byte. `createDocumentHandlers` then answers 503 "The document could not be stored. Try
818
+ again." (a 500 "Upload failed." before 0.9.0), and a retry fails the same way. A store that keeps
420
819
  fixed columns and drops the others keeps the text, read right, but the model is no longer told how
421
820
  the file was read. [The example below](#example-object-storage-and-a-database) stores `meta` whole.
422
821
 
@@ -442,12 +841,24 @@ time ([the cache](#the-cache) has the sizes). The rules:
442
841
  - Return every byte asked for, unless the text ends first. A read that comes back short in the
443
842
  middle of the text is taken for a text that does not match its index: that call answers "The
444
843
  stored text of report.log did not match its index. Try the call again.", and the index is built
445
- again.
844
+ again. When the index built again has another number of lines or characters than the metadata
845
+ says, the text is not the one that was ingested, and the document reads as missing (new in 0.9.0;
846
+ before, that text was read).
847
+ - When a document is opened through its saved index, one byte is read across the end of the text
848
+ that the index gives (new in 0.9.0): a text that does not end there has its index built again, and
849
+ compared with the metadata as above.
446
850
  - Return fewer bytes at the end of the text, and an empty array when `start` is at or past its end.
447
851
  That happens: the index is built by reading 4 MB at a time until a read comes back short, so a
448
852
  text whose size is a multiple of 4 MB ends with a read that starts at its end.
449
853
  - Return undefined when the document is gone. The call then answers "doc_… is no longer available on
450
854
  the server. Ask the user to attach the file again."
855
+ - The bytes carry nothing to check them by: the library cannot tell them from the text of another
856
+ document laid out the same way. So, since 0.9.0, once a tool call or `prepare` has read a document
857
+ by range, the library asks `getMeta` once more (one call, however many ranges were read). The read
858
+ is missing unless the store still describes the same document, of the same owner and scope. That
859
+ catches a document deleted, and another stored under its ID, while it was read. It cannot catch a
860
+ store whose `readTextRange` or `getIndex` answers from another document while its `getMeta` is
861
+ right, such as a cache keyed by ID alone. Key any cache of those reads by the context too.
451
862
 
452
863
  How that maps to common storage:
453
864
 
@@ -469,7 +880,8 @@ What the library does with what you throw depends on the call:
469
880
 
470
881
  - **Reads** (`get`, `getMeta`, `getOriginal`, `readTextRange`): whatever you throw is passed on as a
471
882
  `DocumentStoreError`. Its message is "The document store could not be read (EIO). Try again.", with
472
- the code in parentheses only when your error has a string `code`. Its `code` and `syscall` are
883
+ the code in parentheses only when your error has a `code` that reads as one (capitals, digits and
884
+ `_`, as `EIO`): a host a driver put in `code` is left out. Its `code` and `syscall` are
473
885
  those of your error, when they are strings, as a Node system error has them. Its `cause` is your
474
886
  error: log that one. The message names no path or host, so it can be shown to a user or a model.
475
887
  `prepare`, `askWithFiles` and `files.getMeta` throw it; a tool call answers the model with its
@@ -478,22 +890,71 @@ What the library does with what you throw depends on the call:
478
890
  to. What to show the user is in [Errors and reliability](./errors-and-reliability.md).
479
891
  - **`getIndex`**: an error is not passed on. The index is built from the text instead.
480
892
  - **Writes at ingest** (`putOriginal`, `putIndex`, `put`): the library calls `delete(id)` to remove
481
- what was written, ignores any error of that, and throws your error as it came. Through the `upload`
482
- handler of `createDocumentHandlers`, an error with a `status` (or `statusCode`) from 400 to 599 is
483
- answered with that status and its message (a 413 with "The file is larger than the … upload
484
- limit.", and an empty message with "Upload failed."). A Node system error (a string `code` and
485
- `syscall`) is answered 500 "Upload failed (CODE).". Any other error, or a thrown value that is not
486
- an `Error`, is answered 500 "Upload failed.", without its message, which may name a database host.
487
- The handlers log nothing: log your error in the store before you throw. Two paths cannot tell
488
- your error from a file that cannot be read, and answer it 422 with its message, host and all: an
489
- `ingest` of your own that throws a new error in place of yours, and a route of your own. See the
490
- [node reference](../reference/node.md#uploadrequest-response). Give your write errors a status and
491
- a message of your own, as the example below does: every path keeps that status.
492
- - **`delete` and `sweep`**: your error comes out of `files.delete` and `files.sweep` as it came. The
493
- DELETE handler answers it 500 without its message, unless it has a status.
893
+ what was written, ignores any error of that, and throws a `DocumentStoreError` of operation
894
+ `"write"`, whose `cause` is your error (new in 0.9.0: it threw your error as it came). Its message
895
+ is "The document could not be stored (EIO). Try again.", with the code only when your error has a
896
+ string `code`, and its status 503. A write that does not end within `ingestTimeoutMs` is one of
897
+ code `"ETIMEDOUT"`. The `upload` handler of `createDocumentHandlers` answers it 503 with that
898
+ message, which names no host or path, and `Retry-After: 5` (before 0.9.0, a 500). The handlers log nothing: log your
899
+ error in the store before you throw, or log `error.cause`. See the
900
+ [node reference](../reference/node.md#uploadrequest-response). Under an application's ID, the
901
+ library first asks `getMeta(id)`, and calls `delete(id)` only when nothing is there or the document
902
+ there is this ingest's own (the same `createdAt`, owner and scope). Another document there is left.
903
+ When it has not expired and is of another owner or scope, stored by another server meanwhile, the
904
+ ingest throws an `IngestError` `"exists"` (409) instead: a `put` that refuses an ID it already has,
905
+ as an insert with a unique key does, ends that way. Such a `put` must refuse before it writes
906
+ anything under the ID. One that writes the text first and then fails at the insert has written
907
+ over the text of the document that is left. The library reads that document as missing when its
908
+ text has another length or number of lines than its metadata says, but cannot tell a text of the
909
+ same length and lines. The [example](#example-object-storage-and-a-database) claims the record
910
+ first, so it never writes over the text of the document that is left; two ingests of one ID that
911
+ overlap then usually both fail with a 503 (its notes say why). The document a replace was to
912
+ remove, when that `delete` failed, is left too, and the error is the 503 above.
913
+ - **`delete` and `sweep`**: your error comes out of `files.delete` and `files.sweep` as a
914
+ `DocumentStoreError` of operation `"delete"` or `"sweep"`, with your error as `cause` (new in
915
+ 0.9.0: it came out as it was). The DELETE handler answers it 503 with its message.
916
+ - **A scope you cannot keep**: throw a `DocumentScopeError` (`"scope_required"`, `"scope_invalid"`,
917
+ `"scope_missing"`). It is passed on as it is from every call, reads and writes alike: it is a
918
+ mistake of the call, not a store to try again. The handlers of `createDocumentHandlers` answer
919
+ `"scope_missing"` `404` "This chat no longer exists.", and the other two `500` (new in 0.9.0).
494
920
  - **`putIndex` on a later read**: an error is ignored. The index is used from memory, and built again
495
921
  the next time.
496
922
 
923
+ ### Time limits
924
+
925
+ Since 0.10.0 the library gives each call of your store a time limit, `storeTimeoutMs` of
926
+ [`LargeFilesOptions`](../reference/library.md#largefilesoptions), 30 seconds by default: `getMeta`,
927
+ `get`, `readTextRange`, `getIndex`, `putIndex` on a later read, `getOriginal` (the reading of the
928
+ bytes as well as the call), and `delete`. A call that does not settle within it is given up on: the
929
+ library throws a `DocumentStoreError` of code `"ETIMEDOUT"` (503, retryable), and a question in a
930
+ tool call ends with `run.error`. Before, a call that never settled held the question forever.
931
+
932
+ - **The call itself is not stopped.** The library cannot cancel your promise, and does not pass a
933
+ signal to your store. Give your client a time limit of its own (a driver's socket or operation
934
+ timeout, an `AbortSignal.timeout` on a `fetch`), shorter than `storeTimeoutMs`, so that a call
935
+ that is given up on also ends.
936
+ - **A call past the limit counts as stuck until it settles**, in the process
937
+ (`files.stats().stuckStoreCalls`). While `maxStuckStoreCalls` calls are stuck (half of
938
+ `UV_THREADPOOL_SIZE`, 2 by default), every new call of the library fails at once with code
939
+ `"STORE_STUCK"`, without calling your store. It matters most for stores on the file system, whose
940
+ calls hold threads of libuv's pool: see [Deployment](./deployment.md#a-store-that-stops-answering).
941
+ - **A caller's signal ends only its own wait** (`AccessOptions.signal`, `askWithFiles`' `signal`).
942
+ One opening of a document serves every caller of its scope, so a call that others wait on goes on
943
+ when one of them leaves.
944
+ - **A saved index that does not answer in time is not built again.** The opening of a document
945
+ read by range fails with `"ETIMEDOUT"`, as any call does; it does not read the whole text from the
946
+ same store to build the index, as it does for an index that is missing or broken.
947
+ - **`delete` runs one at a time** in a library: a delete waits for the one before it to settle. A
948
+ delete ends within `storeTimeoutMs` in all: its look-up, its turn and your store's `delete`
949
+ share it.
950
+ - **`ingest`** keeps its own limits: its writes, and its look-ups of an application's ID, end within
951
+ `ingestTimeoutMs` (2 minutes when it is 0), as before. Past them they count as stuck too, and
952
+ while too many calls are stuck an ingest fails at its first store call with `"STORE_STUCK"`.
953
+ **`sweep`** has `sweepTimeoutMs`, no limit by default, and never counts as stuck.
954
+ - Keep `storeTimeoutMs` above your slowest healthy call: a `get` of the largest text loaded whole
955
+ (`wholeDocumentBytes`, 2 MB by default), or a `getOriginal` of the largest original, at the store's
956
+ busiest. 0 sets no limit.
957
+
497
958
  ### Concurrency and several servers
498
959
 
499
960
  - Every method may run many times at once, for the same document too. Many users ask at once, the
@@ -501,12 +962,25 @@ What the library does with what you throw depends on the call:
501
962
  the current one.
502
963
  - In one library, calls that open the same document at the same time share one opening: one `get`,
503
964
  or one `getIndex`.
504
- - A document is written once: its ID is new at every ingest. Only `putIndex` writes again, later, for
505
- a document whose index was missing or did not match its text. Several servers may do that at once,
506
- with the same bytes: let the last write win.
965
+ - A document is written once. With an ID the library makes, the ID is new at every ingest. With an
966
+ [application's ID](#application-ids), another document can be written under the ID later: after
967
+ `files.delete`, once the document has expired, or with `ifExists: "replace"`, which calls
968
+ `delete(id)` and then writes. The library forgets what it kept in memory of the old one. On other
969
+ servers, the old one is missing for a moment, and their copies are checked against the new
970
+ metadata before any use.
971
+ - Two servers may ingest one application's ID at the same moment, when both find it free. The
972
+ library takes them for the same upload sent twice: let the last write win. Its clean-up after a
973
+ failed write leaves a document whose metadata it finds. The parts of one still being written on
974
+ the other server at that moment may be removed (see [Errors](#errors)).
975
+ - Only `putIndex` writes again, later, for a document whose index was missing or did not match its
976
+ text. Several servers may do that at once, with the same bytes: let the last write win.
507
977
  - Make the metadata the point where a document exists. Write it last, in `put`, after the text, and
508
978
  remove it first in `delete`. A server that finds the metadata must be able to read all of the text.
509
- `FileDocumentStore` gets this on a shared volume by writing under a temporary name and renaming.
979
+ `FileDocumentStore` gets this on a shared volume by writing under a temporary name and renaming. A
980
+ store that inserts the metadata under a unique key can insert it first instead, hidden from
981
+ `getMeta`, and show it once the text is written, as the
982
+ [example](#example-object-storage-and-a-database) does. A `put` that loses a race for an ID then
983
+ fails before it writes over the text of the one that won.
510
984
  - A document deleted by another server between `getMeta` and a read is answered as gone: return
511
985
  undefined from that read.
512
986
 
@@ -520,7 +994,7 @@ SDK, following [Reading by range](#reading-by-range).
520
994
  ```ts
521
995
  // blob-document-store.ts
522
996
  import type { Collection } from "mongodb";
523
- import { DOCUMENT_ID_PATTERN, type DocumentMeta, type DocumentStore, type StoredDocument } from "llm-large-files";
997
+ import { APP_DOCUMENT_ID_PATTERN, type DocumentMeta, type DocumentStore, type StoredDocument } from "llm-large-files";
524
998
 
525
999
  /** The object storage calls the store needs. Write them over S3, Cloud Storage, Azure Blob Storage or a volume. */
526
1000
  export interface Blobs {
@@ -543,6 +1017,8 @@ export type DocumentRecord = {
543
1017
  meta: DocumentMeta;
544
1018
  owner: string | null;
545
1019
  expiresAt: Date;
1020
+ /** Set while `put` writes the text: the document is not there yet. */
1021
+ writing?: true;
546
1022
  };
547
1023
 
548
1024
  /** A write that failed: a 503 from createDocumentHandlers, with a message that names no host. */
@@ -558,25 +1034,32 @@ export class BlobDocumentStore implements DocumentStore {
558
1034
  private readonly prefix = "llm-large-files",
559
1035
  ) {}
560
1036
 
561
- /** Only a document ID becomes part of a key, as in the built-in stores. */
1037
+ /** Only a document ID becomes part of a key, as in the built-in stores: the library's, or the application's. */
562
1038
  private key(id: string, kind: "txt" | "idx" | "bin"): string {
563
- if (!DOCUMENT_ID_PATTERN.test(id)) throw new Error("Invalid document ID.");
1039
+ if (!APP_DOCUMENT_ID_PATTERN.test(id)) throw new Error("Invalid document ID.");
564
1040
  return `${this.prefix}/${id}.${kind}`;
565
1041
  }
566
1042
 
567
- /** Called last at ingest. The text first, the record last: a document exists once its record does. */
1043
+ /**
1044
+ * Called last at ingest. The record first, marked as being written: a put that loses a race for
1045
+ * the ID fails at the unique `_id`, before it writes over the text of the one that won. Then the
1046
+ * text, then the mark goes: a document exists once its record is there without the mark.
1047
+ */
568
1048
  async put({ meta, text }: StoredDocument): Promise<void> {
569
1049
  try {
1050
+ await this.records.insertOne({ _id: meta.id, meta, owner: meta.owner ?? null, expiresAt: new Date(meta.expiresAt), writing: true });
570
1051
  await this.blobs.write(this.key(meta.id, "txt"), new TextEncoder().encode(text));
571
- await this.records.insertOne({ _id: meta.id, meta, owner: meta.owner ?? null, expiresAt: new Date(meta.expiresAt) });
1052
+ // This put's record only: another server may have removed it meanwhile.
1053
+ const { matchedCount } = await this.records.updateOne({ _id: meta.id, writing: true, "meta.createdAt": meta.createdAt }, { $unset: { writing: "" } });
1054
+ if (matchedCount === 0) throw new Error(`The record of ${meta.id} was removed while its text was written.`);
572
1055
  } catch (error) {
573
1056
  throw notStored(error);
574
1057
  }
575
1058
  }
576
1059
 
577
- /** Called before every use of a document: one look-up by key. */
1060
+ /** Called before every use of a document: one look-up by key. A record still being written is not a document yet. */
578
1061
  async getMeta(id: string): Promise<DocumentMeta | undefined> {
579
- return (await this.records.findOne({ _id: id }))?.meta;
1062
+ return (await this.records.findOne({ _id: id, writing: { $exists: false } }))?.meta;
580
1063
  }
581
1064
 
582
1065
  async get(id: string): Promise<StoredDocument | undefined> {
@@ -617,7 +1100,7 @@ export class BlobDocumentStore implements DocumentStore {
617
1100
 
618
1101
  /** The record first: if removing it fails, nothing else is touched and the document stays whole. */
619
1102
  async delete(id: string): Promise<boolean> {
620
- if (!DOCUMENT_ID_PATTERN.test(id)) return false;
1103
+ if (!APP_DOCUMENT_ID_PATTERN.test(id)) return false;
621
1104
  const { deletedCount } = await this.records.deleteOne({ _id: id });
622
1105
  // Also what a failed ingest left behind: an original or an index without a record.
623
1106
  await Promise.all((["txt", "idx", "bin"] as const).map((kind) => this.blobs.remove(this.key(id, kind))));
@@ -655,9 +1138,23 @@ export const files = createLargeFiles({
655
1138
  ```
656
1139
 
657
1140
  - Reads let their errors through: the library turns them into a `DocumentStoreError`. Writes log
658
- theirs, then turn them into an error with status 503 and a message of their own, so an upload that
659
- meets a database that is down is answered 503 "The file could not be stored. Try again.", not 500
660
- "Upload failed.".
1141
+ theirs, then throw. Since 0.9.0 the library turns them into a `DocumentStoreError` too, so an
1142
+ upload that meets a database that is down is answered 503 "The document could not be stored. Try
1143
+ again.", with `Retry-After: 5`, whatever the store's own error says.
1144
+ - `put` inserts the record first, marked `writing`, and `getMeta` does not see it until the text is
1145
+ written. When two servers ingest one ID at the same moment, the one whose insert fails has written
1146
+ no text. Its index and its original were written before `put`, so they can still land over the
1147
+ other's. The library checks both: an index that does not match the metadata is built again from
1148
+ the text, and an original of another size or SHA-256 reads as missing.
1149
+ - While one server's record is still marked, another server's ingest of that ID cannot see it. Its
1150
+ insert fails, and its clean-up finds nothing with `getMeta`, so it calls `delete`, which removes
1151
+ the marked record and its text. Both ingests then fail with a 503, even for one upload sent twice,
1152
+ and nothing wrong is served. If the first `put` ended between that look and the `delete`, its
1153
+ document is removed after its 201 and reads as missing. An ID of its own for each upload, as
1154
+ `attach()` makes, avoids all of this.
1155
+ - A record left marked by a server that stopped in the middle of a `put` is not a document. `sweep`
1156
+ removes it once it has expired. A later ingest of that ID fails once with a 503, and removes it as
1157
+ it cleans up.
661
1158
  - `delete` removes the record first. If removing an object fails after that, the document is gone
662
1159
  and the object stays behind. A lifecycle rule on the bucket that removes objects under the prefix
663
1160
  some time after `ttlMs` cleans those up, when `ttlMs` is finite.
@@ -668,23 +1165,48 @@ export const files = createLargeFiles({
668
1165
 
669
1166
  ### Checking your store
670
1167
 
671
- Before you trust a store with users' files, check these with the library over it:
1168
+ `documentStoreChecks` from `llm-large-files/testing` (new in 0.9.0) checks a store against this
1169
+ page: copies of the metadata, fields it does not know, `null` for a field left out, expiry, every
1170
+ part removed by `delete`, ranges across multi-byte characters, the index, the original byte for
1171
+ byte, the sweep's clock, the application's IDs, the context on every call, scopes kept apart, two
1172
+ servers over one storage, and the library over the store against `MemoryDocumentStore`. Run them
1173
+ in your tests:
1174
+
1175
+ ```ts
1176
+ // blob-document-store.test.ts, with Vitest. Jest: the same with `test`. node:test:
1177
+ // test(check.name, { timeout: check.timeoutMs }, check.run).
1178
+ import { it } from "vitest";
1179
+ import { documentStoreChecks } from "llm-large-files/testing";
1180
+ import { BlobDocumentStore } from "./blob-document-store.js";
1181
+ import { blobsFor, recordsFor, dropStorage } from "./test-storage.js"; // a bucket prefix and a collection for each name
1182
+
1183
+ for (const check of documentStoreChecks({
1184
+ create: ({ storage }) => new BlobDocumentStore(blobsFor(storage), recordsFor(storage)),
1185
+ dispose: (_store, { storage }) => dropStorage(storage),
1186
+ })) it(check.name, check.run, check.timeoutMs);
1187
+ ```
1188
+
1189
+ - `create` makes a store over new storage for each check, named by `storage`. Called twice with
1190
+ the same name, it must give two stores over the same storage, as two servers.
1191
+ - Say what your store does: `isolatesScopes: true` if it keeps the documents of each scope apart,
1192
+ `requiresScope: true` if it refuses a call without a scope, and `skip` for the parts it does not
1193
+ have (`"originals"`, `"ranges"`, `"index"`, `"sweep"`, `"shared"`).
1194
+ - A failed check says what it expected and what came back. The options and every check are in
1195
+ [the reference](../reference/testing.md#documentstorechecksoptions).
1196
+
1197
+ The library's own tests run them on `MemoryDocumentStore`, `FileDocumentStore` in one folder, and
1198
+ `FileDocumentStore` with `scopes`.
1199
+
1200
+ What the checks cannot do for you, by hand:
672
1201
 
673
- - A file ingested, then `prepare` and a `search_document` call give the same results as with
674
- `MemoryDocumentStore`. Do it once more with `wholeDocumentBytes: 0`, which reads every document by
675
- range.
676
1202
  - With the database stopped, `files.getMeta(id)` rejects with a `DocumentStoreError` instead of
677
1203
  giving undefined, and a tool call answers "The document store could not be read. Try again.",
678
1204
  with a code in parentheses when your error has one.
679
- - A text file that is not UTF-8, such as a CSV saved by Excel in windows-1255, is ingested, and
680
- `files.getMeta(id)` gives back its `encoding` (and `replacedCharacters`, for a UTF-8 log cut at a
681
- byte count): your store keeps fields it does not know.
682
1205
  - With a write that fails, `files.ingest` throws, and leaves no record and no object behind.
683
- - `files.delete` removes every part. `getMeta` then gives undefined, and a second delete gives false.
684
- - With a clock past `expiresAt` (the `now` option of `createLargeFiles`), `files.sweep()` removes
685
- the document, every part of it, and counts it.
686
- - `readTextRange(id, size, size + 10)` gives an empty array, where `size` is `meta.textBytes`.
687
- - With `keepOriginals`, `files.getOriginal` gives the uploaded bytes, byte for byte.
1206
+ - A text file that is not UTF-8, such as a CSV saved by Excel in windows-1255, is ingested, and
1207
+ `files.getMeta(id)` gives back its `encoding`. A schema of your database may refuse fields the
1208
+ checks' metadata does not have.
1209
+ - An expired document whose removal fails is still read as missing.
688
1210
 
689
1211
  ## The cache
690
1212
 
@@ -704,7 +1226,16 @@ just those lines.
704
1226
  - The cache never decides whether a document exists. Every use asks the store first (`getMeta`), so
705
1227
  a document deleted or expired on another server is never served from memory here. A kept copy is
706
1228
  used only while the store describes the same text (the same `createdAt`, size, characters and
707
- lines), so a store restored from a backup is read again.
1229
+ lines), so a store restored from a backup is read again. Since 0.9.0 it must also be of the same
1230
+ owner and scope: a document stored under a reused [application's ID](#application-ids) by another
1231
+ owner is read again, even within the same millisecond and with a text of the same size.
1232
+ - A document loaded whole is used only when the document `get` returns is the one `getMeta`
1233
+ described, of the same owner, scope and version (new in 0.9.0). If another server replaced it in
1234
+ between, it is missing for this call.
1235
+ - A document read by range is checked after its reads instead (new in 0.9.0): once a tool call or
1236
+ `prepare` has read it, the store is asked again (`getMeta`). If it no longer describes the same
1237
+ document, the call answers that the document is no longer available, and the copy kept of it, its
1238
+ pieces included, is forgotten.
708
1239
  - A document loaded whole takes, once searched, about twice its size in memory when its text is all
709
1240
  ASCII, and four bytes a character otherwise: the text and a lowercased copy.
710
1241
  - A document read by range keeps its line index in memory, about 8 bytes a line, and, within