llm-large-files 0.8.1 → 0.9.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 (204) hide show
  1. package/CHANGELOG.md +631 -0
  2. package/README.md +9 -10
  3. package/dist/access.d.ts +86 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +131 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/ask.d.ts +45 -1
  8. package/dist/ask.d.ts.map +1 -1
  9. package/dist/ask.js +181 -20
  10. package/dist/ask.js.map +1 -1
  11. package/dist/cache.d.ts +12 -3
  12. package/dist/cache.d.ts.map +1 -1
  13. package/dist/cache.js +18 -5
  14. package/dist/cache.js.map +1 -1
  15. package/dist/encoding.js +5 -3
  16. package/dist/encoding.js.map +1 -1
  17. package/dist/error-info.d.ts +57 -0
  18. package/dist/error-info.d.ts.map +1 -0
  19. package/dist/error-info.js +217 -0
  20. package/dist/error-info.js.map +1 -0
  21. package/dist/errors.d.ts +72 -8
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +102 -15
  24. package/dist/errors.js.map +1 -1
  25. package/dist/events.d.ts +35 -9
  26. package/dist/events.d.ts.map +1 -1
  27. package/dist/events.js +42 -11
  28. package/dist/events.js.map +1 -1
  29. package/dist/evidence.d.ts +4 -2
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +14 -3
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +32 -8
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +46 -35
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts +19 -3
  38. package/dist/gemini/adapter.d.ts.map +1 -1
  39. package/dist/gemini/adapter.js +84 -12
  40. package/dist/gemini/adapter.js.map +1 -1
  41. package/dist/gemini/chat.d.ts +18 -6
  42. package/dist/gemini/chat.d.ts.map +1 -1
  43. package/dist/gemini/chat.js +2 -0
  44. package/dist/gemini/chat.js.map +1 -1
  45. package/dist/gemini/index.d.ts +1 -1
  46. package/dist/gemini/index.d.ts.map +1 -1
  47. package/dist/index.d.ts +9 -6
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +4 -3
  50. package/dist/index.js.map +1 -1
  51. package/dist/ingest.d.ts +70 -0
  52. package/dist/ingest.d.ts.map +1 -0
  53. package/dist/ingest.js +868 -0
  54. package/dist/ingest.js.map +1 -0
  55. package/dist/library.d.ts +176 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +332 -512
  58. package/dist/library.js.map +1 -1
  59. package/dist/limiter.d.ts +2 -2
  60. package/dist/limiter.js +2 -2
  61. package/dist/map-reduce.js +3 -3
  62. package/dist/map-reduce.js.map +1 -1
  63. package/dist/model.d.ts +43 -2
  64. package/dist/model.d.ts.map +1 -1
  65. package/dist/model.js +63 -3
  66. package/dist/model.js.map +1 -1
  67. package/dist/node/handlers.d.ts +234 -7
  68. package/dist/node/handlers.d.ts.map +1 -1
  69. package/dist/node/handlers.js +482 -121
  70. package/dist/node/handlers.js.map +1 -1
  71. package/dist/node/index.d.ts +3 -2
  72. package/dist/node/index.d.ts.map +1 -1
  73. package/dist/node/index.js +2 -1
  74. package/dist/node/index.js.map +1 -1
  75. package/dist/node/ingest-child.d.ts +7 -1
  76. package/dist/node/ingest-child.d.ts.map +1 -1
  77. package/dist/node/ingest-child.js +18 -3
  78. package/dist/node/ingest-child.js.map +1 -1
  79. package/dist/node/isolated.d.ts +3 -1
  80. package/dist/node/isolated.d.ts.map +1 -1
  81. package/dist/node/isolated.js +11 -4
  82. package/dist/node/isolated.js.map +1 -1
  83. package/dist/node/originals.d.ts +19 -0
  84. package/dist/node/originals.d.ts.map +1 -0
  85. package/dist/node/originals.js +82 -0
  86. package/dist/node/originals.js.map +1 -0
  87. package/dist/node/spool.d.ts +102 -0
  88. package/dist/node/spool.d.ts.map +1 -0
  89. package/dist/node/spool.js +365 -0
  90. package/dist/node/spool.js.map +1 -0
  91. package/dist/node/sse.d.ts +4 -3
  92. package/dist/node/sse.d.ts.map +1 -1
  93. package/dist/node/sse.js +7 -6
  94. package/dist/node/sse.js.map +1 -1
  95. package/dist/pdf-layout.d.ts.map +1 -1
  96. package/dist/pdf-layout.js +71 -12
  97. package/dist/pdf-layout.js.map +1 -1
  98. package/dist/ranged.d.ts +22 -11
  99. package/dist/ranged.d.ts.map +1 -1
  100. package/dist/ranged.js +50 -12
  101. package/dist/ranged.js.map +1 -1
  102. package/dist/retry.d.ts +3 -1
  103. package/dist/retry.d.ts.map +1 -1
  104. package/dist/retry.js +6 -2
  105. package/dist/retry.js.map +1 -1
  106. package/dist/scope.d.ts +25 -0
  107. package/dist/scope.d.ts.map +1 -0
  108. package/dist/scope.js +60 -0
  109. package/dist/scope.js.map +1 -0
  110. package/dist/source.d.ts +60 -0
  111. package/dist/source.d.ts.map +1 -0
  112. package/dist/source.js +170 -0
  113. package/dist/source.js.map +1 -0
  114. package/dist/stores.d.ts +120 -31
  115. package/dist/stores.d.ts.map +1 -1
  116. package/dist/stores.js +582 -139
  117. package/dist/stores.js.map +1 -1
  118. package/dist/testing/fake-fetch.d.ts +31 -0
  119. package/dist/testing/fake-fetch.d.ts.map +1 -0
  120. package/dist/testing/fake-fetch.js +66 -0
  121. package/dist/testing/fake-fetch.js.map +1 -0
  122. package/dist/testing/fake-model.d.ts +38 -0
  123. package/dist/testing/fake-model.d.ts.map +1 -0
  124. package/dist/testing/fake-model.js +62 -0
  125. package/dist/testing/fake-model.js.map +1 -0
  126. package/dist/testing/index.d.ts +7 -0
  127. package/dist/testing/index.d.ts.map +1 -0
  128. package/dist/testing/index.js +9 -0
  129. package/dist/testing/index.js.map +1 -0
  130. package/dist/testing/store-checks.d.ts +72 -0
  131. package/dist/testing/store-checks.d.ts.map +1 -0
  132. package/dist/testing/store-checks.js +619 -0
  133. package/dist/testing/store-checks.js.map +1 -0
  134. package/dist/tools.d.ts +25 -0
  135. package/dist/tools.d.ts.map +1 -1
  136. package/dist/tools.js +135 -13
  137. package/dist/tools.js.map +1 -1
  138. package/dist/types.d.ts +116 -13
  139. package/dist/types.d.ts.map +1 -1
  140. package/docs/README.md +17 -8
  141. package/docs/getting-started.md +18 -13
  142. package/docs/guides/anthropic.md +12 -8
  143. package/docs/guides/conversations.md +112 -47
  144. package/docs/guides/costs-and-limits.md +16 -7
  145. package/docs/guides/deployment.md +309 -87
  146. package/docs/guides/errors-and-reliability.md +161 -23
  147. package/docs/guides/own-adapter-and-loop.md +27 -10
  148. package/docs/guides/pdfs.md +123 -29
  149. package/docs/guides/storage.md +634 -143
  150. package/docs/guides/testing.md +78 -129
  151. package/docs/guides/vertex-and-gemini.md +10 -7
  152. package/docs/guides/web-app.md +322 -77
  153. package/docs/how-it-works.md +35 -8
  154. package/docs/measurements.md +63 -8
  155. package/docs/publishing.md +112 -36
  156. package/docs/reference/ask.md +154 -13
  157. package/docs/reference/errors-and-retries.md +166 -14
  158. package/docs/reference/events.md +53 -20
  159. package/docs/reference/gemini.md +70 -21
  160. package/docs/reference/library.md +709 -165
  161. package/docs/reference/node.md +633 -104
  162. package/docs/reference/testing.md +311 -0
  163. package/docs/reference/tools.md +15 -5
  164. package/docs/security.md +316 -70
  165. package/docs/troubleshooting.md +165 -58
  166. package/docs/upgrading-0.9.md +890 -0
  167. package/package.json +12 -3
  168. package/src/access.ts +144 -0
  169. package/src/ask.ts +230 -19
  170. package/src/cache.ts +20 -5
  171. package/src/encoding.ts +6 -4
  172. package/src/error-info.ts +255 -0
  173. package/src/errors.ts +129 -15
  174. package/src/events.ts +86 -21
  175. package/src/evidence.ts +14 -3
  176. package/src/extract.ts +50 -33
  177. package/src/gemini/adapter.ts +97 -11
  178. package/src/gemini/chat.ts +20 -6
  179. package/src/gemini/index.ts +1 -1
  180. package/src/index.ts +9 -6
  181. package/src/ingest.ts +927 -0
  182. package/src/library.ts +482 -523
  183. package/src/limiter.ts +2 -2
  184. package/src/map-reduce.ts +3 -3
  185. package/src/model.ts +69 -5
  186. package/src/node/handlers.ts +691 -117
  187. package/src/node/index.ts +13 -2
  188. package/src/node/ingest-child.ts +23 -5
  189. package/src/node/isolated.ts +11 -4
  190. package/src/node/originals.ts +78 -0
  191. package/src/node/spool.ts +365 -0
  192. package/src/node/sse.ts +7 -6
  193. package/src/pdf-layout.ts +69 -11
  194. package/src/ranged.ts +42 -14
  195. package/src/retry.ts +6 -2
  196. package/src/scope.ts +63 -0
  197. package/src/source.ts +178 -0
  198. package/src/stores.ts +635 -140
  199. package/src/testing/fake-fetch.ts +80 -0
  200. package/src/testing/fake-model.ts +78 -0
  201. package/src/testing/index.ts +11 -0
  202. package/src/testing/store-checks.ts +660 -0
  203. package/src/tools.ts +150 -14
  204. package/src/types.ts +106 -13
@@ -10,15 +10,19 @@ import {
10
10
  createLargeFiles, DEFAULT_CACHE_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, DEFAULT_MAX_PDF_PAGES, DEFAULT_MAX_TEXT_BYTES,
11
11
  DEFAULT_INGEST_TIMEOUT_MS, NEVER_EXPIRES, isDocumentId, toDocumentSummary, IngestError, ingestErrorCodeOf,
12
12
  DEFAULT_BUDGET, resolveBudget,
13
- MemoryDocumentStore, FileDocumentStore, DOCUMENT_ID_PATTERN, DocumentStoreError,
13
+ MemoryDocumentStore, FileDocumentStore, isSafeScopeSegment, hashedScopeSegment,
14
+ DOCUMENT_ID_PATTERN, APP_DOCUMENT_ID_PATTERN, DOCUMENT_META_VERSION,
15
+ DocumentStoreError, DocumentScopeError,
14
16
  createPdfExtractor, defaultExtractors, detectFormat,
15
17
  estimateTokens, utf8Bytes, jsonBytes,
16
18
  } from "llm-large-files";
17
19
  import type {
18
20
  LargeFilesOptions, LargeFiles, AccessOptions, IngestInput, PrepareOptions, ToolOptions, PreparedContext, DocumentPlan,
19
- Budget, ModelLimits, DocumentStore, StoredDocument, PdfExtractorOptions, Extractor, ExtractInput, ExtractProgress,
21
+ Budget, ModelLimits, DocumentStore, DocumentContext, DocumentScope, StoredDocument, FileDocumentStoreOptions, FileDocumentScopes,
22
+ PdfExtractorOptions, Extractor, ExtractInput, ExtractProgress,
20
23
  ExtractedText, DocumentMeta, DocumentSummary, DocumentFormat, OutlineEntry, LogIssue, LogProfile, ProgressEvent,
21
24
  ProgressListener, ToolCallHooks, ToolRequestHandle, ToolRequestStart, ToolRequestEnd, IngestEvent, IngestErrorCode,
25
+ DocumentStoreOperation, DocumentScopeErrorCode,
22
26
  } from "llm-large-files";
23
27
  ```
24
28
 
@@ -39,9 +43,14 @@ Contents:
39
43
  [`toDocumentSummary(meta)`](#todocumentsummarymeta)
40
44
  - [The budget](#the-budget): [`Budget`](#budget), [`DEFAULT_BUDGET`](#default_budget),
41
45
  [`resolveBudget(budget?, limits?)`](#resolvebudgetbudget-limits), [`ModelLimits`](#modellimits)
42
- - [Stores](#stores): [`DocumentStore`](#documentstore), [`StoredDocument`](#storeddocument),
46
+ - [Stores](#stores): [`DocumentStore`](#documentstore), [`DocumentContext`](#documentcontext),
47
+ [`DocumentScope`](#documentscope), [`StoredDocument`](#storeddocument),
43
48
  [`MemoryDocumentStore`](#memorydocumentstore), [`FileDocumentStore`](#filedocumentstore),
44
- [`DOCUMENT_ID_PATTERN`](#document_id_pattern), [`DocumentStoreError`](#documentstoreerror)
49
+ [`FileDocumentStoreOptions`](#filedocumentstoreoptions), [`FileDocumentScopes`](#filedocumentscopes),
50
+ [`isSafeScopeSegment(value)`](#issafescopesegmentvalue), [`hashedScopeSegment(value)`](#hashedscopesegmentvalue),
51
+ [`DOCUMENT_ID_PATTERN`](#document_id_pattern), [`APP_DOCUMENT_ID_PATTERN`](#app_document_id_pattern),
52
+ [`DOCUMENT_META_VERSION`](#document_meta_version), [`DocumentStoreError`](#documentstoreerror),
53
+ [`DocumentScopeError`](#documentscopeerror)
45
54
  - [Extraction](#extraction): [`Extractor`](#extractor), [`ExtractInput`](#extractinput),
46
55
  [`ExtractProgress`](#extractprogress), [`ExtractedText`](#extractedtext), [`defaultExtractors`](#defaultextractors),
47
56
  [`createPdfExtractor(options?)`](#createpdfextractoroptions), [`PdfExtractorOptions`](#pdfextractoroptions),
@@ -101,12 +110,18 @@ type LargeFilesOptions = {
101
110
  ingestTimeoutMs?: number;
102
111
  extractors?: Partial<Record<DocumentFormat, Extractor>>;
103
112
  keepOriginals?: DocumentFormat[];
113
+ originals?: OriginalsReader; // new in 0.9.0
104
114
  scannedPdfPages?: number;
105
115
  cacheBytes?: number;
106
116
  cacheSize?: number;
107
117
  wholeDocumentBytes?: number;
108
118
  scanChunkBytes?: number;
109
119
  maxConcurrentScans?: number;
120
+ maxConcurrentIngests?: number;
121
+ maxConcurrentPageLooks?: number; // new in 0.9.0
122
+ pageLookWaitMs?: number; // new in 0.9.0
123
+ requireOwner?: boolean; // new in 0.9.0
124
+ requireScope?: boolean; // new in 0.9.0
110
125
  now?: () => Date;
111
126
  };
112
127
  ```
@@ -119,19 +134,26 @@ type LargeFilesOptions = {
119
134
  | `maxUploadBytes` | `number` | 100 MB (104,857,600) | The largest file `ingest` accepts. The upload handler of [`llm-large-files/node`](./node.md) reads no more than this. |
120
135
  | `maxTextBytes` | `number` | [`DEFAULT_MAX_TEXT_BYTES`](#default_max_text_bytes), 100 MB, or `maxUploadBytes` when that is larger | The most text kept from one file, in UTF-8 bytes. A file's text can be larger than the file: a PDF of 3 KB built for it drew 107 MB. The PDF, DOCX, PPTX and XLSX extractors refuse a file as soon as its text passes this (a PDF page by page, and also past 100 times its size after the first 16 MB; an Office file also past 32 million characters, whatever this allows), and `ingest` refuses a larger text from any other extractor, the text extractor and yours included. Your extractor receives it as `ExtractInput.maxTextBytes`. At least 1. |
121
136
  | `maxPdfPages` | `number` | [`DEFAULT_MAX_PDF_PAGES`](#default_max_pdf_pages), 5,000 | The most pages read from one PDF. A PDF with more is refused before any page is read. Your PDF extractor receives it as `ExtractInput.maxPages`. At least 1. |
122
- | `ingestTimeoutMs` | `number` | [`DEFAULT_INGEST_TIMEOUT_MS`](#default_ingest_timeout_ms), 120,000 (2 minutes) | The most time one `ingest` may take to extract the text, build its line index and profile it, in milliseconds. The store's writes are not counted. Past it, `ingest` throws `<name> took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.`, and stores nothing. 0 sets no limit, and so does a value past what a timer can wait (2,147,483,647 ms, 24.8 days). Your extractor receives the limit as `ExtractInput.signal`. Within one page of a PDF the limit is not looked at: see [security](../security.md#uploads). |
137
+ | `ingestTimeoutMs` | `number` | [`DEFAULT_INGEST_TIMEOUT_MS`](#default_ingest_timeout_ms), 120,000 (2 minutes) | The most time one `ingest` may take to extract the text, build its line index and profile it, in milliseconds. The store's writes are not counted, but a store write that does not end within this time (2 minutes when it is 0) fails the ingest as a failure of the store, and the document is removed once the write ends (new in 0.8.2). Since 0.9.0 that is a `DocumentStoreError` of operation `"write"` and code `"ETIMEDOUT"`, whose `cause` says `The store did not finish writing <name> within 2 min.`; it was a plain `Error` with that message. Past it, `ingest` throws `<name> took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.`, and stores nothing. 0 sets no limit, and so does a value past what a timer can wait (2,147,483,647 ms, 24.8 days). Your extractor receives the limit as `ExtractInput.signal`. Within one page of a PDF the limit is not looked at: see [security](../security.md#uploads). |
123
138
  | `extractors` | `Partial<Record<DocumentFormat, Extractor>>` | the built-ins, [`defaultExtractors`](#defaultextractors) | An [`Extractor`](#extractor) per format, used in place of the built-in one. The formats are fixed ([`DocumentFormat`](#documentformat)): you can replace the extractor of a format, not add a format. |
124
- | `keepOriginals` | `DocumentFormat[]` | `[]` | Formats whose uploaded file is kept in the store next to its text, for example `["pdf"]`, which `view_pages` needs. Takes effect only with a store that has `putOriginal`. A kept file takes as much space as the upload until its document expires or is deleted. |
125
- | `scannedPdfPages` | `number` | 30 | The most pages a PDF without any text (a scan) may have and still be accepted, so that its pages can be shown to the model. It applies only when `"pdf"` is in `keepOriginals` and the store has `putOriginal`. Otherwise, and with 0, such a PDF is refused. Your own PDF extractor receives it as `ExtractInput.scannedPages`. |
139
+ | `keepOriginals` | `DocumentFormat[]` | `[]` | Formats whose uploaded file is kept, for example `["pdf"]`, which `view_pages` needs: as a copy in the store, next to its text, when the store has `putOriginal`; or, for an ingest with `IngestInput.original` (new in 0.9.0), where your application keeps it, read back through `originals`. A copy takes as much space as the upload until its document expires or is deleted. |
140
+ | `originals` | [`OriginalsReader`](#originalsreader) | none | Reads the uploaded files your application keeps itself, by the ref given at ingest (`IngestInput.original`), in place of a copy in the store: `fileOriginals(root)` of [`llm-large-files/node`](./node.md#fileoriginalsroot), or your own. Each read is checked against the size and SHA-256 the file had at ingest. Without it, an ingest with `original` throws a `TypeError`. Not an object with a `read` method: a `TypeError` when the library is made. New in 0.9.0. |
141
+ | `scannedPdfPages` | `number` | 30 | The most pages a PDF without any text (a scan) may have and still be accepted, so that its pages can be shown to the model. It applies only when `"pdf"` is in `keepOriginals` and the file is kept: the store has `putOriginal`, or (0.9.0) the ingest gives `original` and the library has `originals`. Otherwise, and with 0, such a PDF is refused. Your own PDF extractor receives it as `ExtractInput.scannedPages`. |
126
142
  | `cacheBytes` | `number` | [`DEFAULT_CACHE_BYTES`](#default_cache_bytes), 256 MB | The most memory that documents kept ready between tool calls may take, together with the decoded pieces of documents read by range. The least recently used go first. A document that would take more than this is not kept and is read again for each call. A document whose decoded text would take more than a quarter of it keeps no pieces. 0 keeps nothing. Each use of a kept document asks the store first, so a document deleted or expired on another server is never served from memory. |
127
143
  | `cacheSize` | `number` | no limit | Also caps the number of documents kept. The pieces of a document read by range are not counted, and leave with their document. 0 keeps nothing. |
128
144
  | `wholeDocumentBytes` | `number` | [`DEFAULT_WHOLE_DOCUMENT_BYTES`](#default_whole_document_bytes), 2 MB | Documents whose text (`textBytes`) is at most this size are loaded whole into memory. Larger ones are read by range when the store has `readTextRange`, as `FileDocumentStore` does: a tool call reads only the lines it needs, and a search reads the text a piece at a time. `Infinity` loads every document whole; 0 reads every one by range. |
129
145
  | `scanChunkBytes` | `number` | 1 MB (1,048,576) | Reading by range: about how many bytes of text are read and searched at a time. At least 1. |
130
146
  | `maxConcurrentScans` | `number` | 4 | Reading by range: how many scans of whole documents (searches, counting the parts of a file) run at once in this library (each `createLargeFiles` call has its own queue). The others wait their turn. At least 1. |
147
+ | `maxConcurrentIngests` | `number` | 2 | How many ingests do their work at once in this library. The others wait their turn, in the order they came; their `ingestTimeoutMs` starts when their turn comes, and a caller that aborts its `signal` while it waits gets its own reason, with nothing stored. An empty file, or one over `maxUploadBytes`, is refused without waiting. An ingest holds about five times its file in memory while it works, and the steps it runs in your server's thread share that thread with the others: more of them at once do not finish sooner (100 logs of 2 MB: all answered in 28 to 42 s all at once, 28 to 33 s two at a time, with a peak of 817 to 830 MB of memory against 329 to 356 MB). An ingest keeps its turn until its work ends: when its time is up or its caller left while an extractor goes on (one that does not stop on the signal, such as the parse of a PDF by `@cantoo/pdf-lib`), until that extractor ends; such an extractor that never ends gives the turn back after `ingestTimeoutMs` more (2 minutes when that is 0), and a store write that never ends fails the ingest after `ingestTimeoutMs` (above). An extractor of your own must not wait on an ingest of the same library (to store the parts of an archive, say): that ingest waits for a turn like any other, and with every turn held by such extractors, each waits on itself until its time is up. With [`createIsolatedExtractors`](./node.md#createisolatedextractorsoptions), at most this many files reach its readers at once from this library. `Infinity` for no limit, as before 0.8.2. At least 1. New in 0.8.2. |
148
+ | `maxConcurrentPageLooks` | `number` | 1 | How many looks at pages (`view_pages`) run at once in this library, over all its questions. The others wait their turn, in order, before their PDF is loaded: a look that waits holds none of its bytes. A look parses the whole PDF on the thread your server shares: more at once do not finish sooner, they only hold more memory (six at once held 352 MB more than one, and each took four times as long). A look holds its turn while it reads its PDF from the store for at most `ingestTimeoutMs` (2 minutes when that is 0), the time the library gives its store writes. Past it, the turn goes back and the model reads "The original file of ‹file› could not be read in time, so its pages cannot be shown. Answer from the text." The read goes on, so give your store's `getOriginal` a time limit of its own. A question stopped while its PDF is read gives the turn back at once. `Infinity` for no limit, as before 0.9.0. At least 1. New in 0.9.0. |
149
+ | `pageLookWaitMs` | `number` | 30,000 | How long a look at pages waits for its turn, in milliseconds. Past it, the look is not run: the model reads "‹file›: The pages cannot be looked at right now; the server is busy. Answer from the text, or look again later.", and `askWithFiles` gives a `"page_looks_busy"` notice. A question that is stopped stops waiting at once. In `askWithFiles` a wait that ends busy comes once in a tool turn: after a look of the turn was told the server is busy, its other looks run only when a turn is free at once ([`ToolCallLimits.maxWaitMs`](./tools.md#toolcalllimits)). Each look that gets its turn may still have waited up to `pageLookWaitMs`: see [PDFs](../guides/pdfs.md). `Infinity` waits without end; 0 does not wait. New in 0.9.0. |
150
+ | `requireOwner` | `boolean` | `false` | Every call must name its owner: `ingest`, `getMeta`, `getOriginal`, `delete`, `prepare`, `askWithFiles`, `askStream` and `askGemini`, and `tools`, which then needs `access`. A call without one throws `TypeError("owner is required: requireOwner is on")`, before the store is asked anything. An owner that `ingest` would refuse (`""`, spaces only) is refused too. A document stored without an owner reads as missing. Use it on a server where every document belongs to a signed-in user: a call that forgot the owner fails, rather than reaching every document stored without one. New in 0.9.0. |
151
+ | `requireScope` | `boolean` | `false` | The same for scopes ([`DocumentScope`](#documentscope)): a call without one throws `TypeError("scope is required: requireScope is on")`, and a document stored without a scope reads as missing. `files.sweep()` without a scope is still allowed: it is upkeep, not a user's access. New in 0.9.0. |
131
152
  | `now` | `() => Date` | `() => new Date()` | The clock, for tests. It dates `createdAt` and `expiresAt`, decides whether a document has expired, and is passed to the store's `sweep`. |
132
153
 
133
154
  Since 0.7.1, `ttlMs`, `maxUploadBytes`, `scannedPdfPages`, `cacheBytes`, `cacheSize`,
134
- `wholeDocumentBytes`, `scanChunkBytes` and `maxConcurrentScans` are checked when the library is
155
+ `wholeDocumentBytes`, `scanChunkBytes` and `maxConcurrentScans` (and `maxConcurrentIngests`, new in
156
+ 0.8.2, and `maxConcurrentPageLooks` and `pageLookWaitMs`, new in 0.9.0) are checked when the library is
135
157
  made: NaN, which `Number(process.env.X)` gives for a variable that is not set, throws a
136
158
  `RangeError` ("maxConcurrentScans must be a number, and is NaN. Leave it out for the default."),
137
159
  a value that is not a number throws a `TypeError`, and so does `Infinity` for `scanChunkBytes`. NaN
@@ -144,7 +166,7 @@ Guides: [storage](../guides/storage.md) for the store, owners and retention,
144
166
  [costs and limits](../guides/costs-and-limits.md) for the budget, [PDFs](../guides/pdfs.md) for
145
167
  `keepOriginals`, `scannedPdfPages`, `extractors` and the files the limits refuse,
146
168
  [security](../security.md#uploads) for `maxTextBytes`, `maxPdfPages` and `ingestTimeoutMs`, and
147
- [deployment](../guides/deployment.md) for the memory settings.
169
+ [deployment](../guides/deployment.md) for the memory settings and the looks at pages.
148
170
 
149
171
  ### `LargeFiles`
150
172
 
@@ -153,11 +175,12 @@ interface LargeFiles {
153
175
  readonly budget: Budget;
154
176
  budgetFor(overrides?: Partial<Budget>, limits?: ModelLimits): Budget;
155
177
  readonly maxUploadBytes: number;
156
- ingest(input: IngestInput): Promise<DocumentMeta>;
178
+ readonly access?: { readonly requireOwner: boolean; readonly requireScope: boolean }; // new in 0.9.0
179
+ ingest(input: IngestInput | IngestFromSource): Promise<DocumentMeta>; // IngestFromSource: new in 0.9.0
157
180
  getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
158
181
  getOriginal(id: string, access?: AccessOptions): Promise<Uint8Array | undefined>;
159
182
  delete(id: string, access?: AccessOptions): Promise<boolean>;
160
- sweep(): Promise<number>;
183
+ sweep(options?: { scope?: DocumentScope }): Promise<number>;
161
184
  prepare(ids: string[], base: { tokens: number; bytes: number }, options?: PrepareOptions): Promise<PreparedContext>;
162
185
  tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
163
186
  }
@@ -167,22 +190,61 @@ The object `createLargeFiles` returns. Below, its members are shown on a `LargeF
167
190
 
168
191
  The members that read the store (`getMeta`, `getOriginal`, `delete` and `prepare`) throw
169
192
  [`DocumentStoreError`](#documentstoreerror) when the store cannot be read: retry, the document is
170
- not gone. A tool call that meets it answers the model with its message instead. What the store
171
- throws while writing (in `ingest`, the removal in `delete`, `sweep`) is passed on unchanged: log it,
172
- and do not show it to a user, since its message may name a path or a host.
193
+ not gone. A tool call that meets it answers the model with its message instead. Since 0.9.0, what
194
+ the store throws while writing is a `DocumentStoreError` too, with the store's own error as
195
+ `cause`: operation `"write"` in `ingest`, `"delete"` in `delete`, `"sweep"` in `sweep`. Before, it
196
+ was passed on unchanged. Log `error.cause`, and do not show it to a user, since its message may name
197
+ a path or a host. A [`DocumentScopeError`](#documentscopeerror) the store throws is passed on as it
198
+ is, for reads and writes alike: it is a mistake of the call, not a store to try again.
173
199
 
174
- #### `files.ingest(input)`
200
+ Every store call carries a [`DocumentContext`](#documentcontext), new in 0.9.0: the scope and the
201
+ owner of the call (of the document, at ingest). It is a frozen object, and a field that is absent is
202
+ left out, so a call without either gets `{}`. A document a store returns for another ID, or with
203
+ the owner `null` (as a MongoDB driver writes a field that was left out), is read as missing, or as
204
+ without an owner.
205
+
206
+ #### `files.access`
207
+
208
+ `readonly access?: { readonly requireOwner: boolean; readonly requireScope: boolean }`
175
209
 
176
- `ingest(input: IngestInput): Promise<DocumentMeta>`
210
+ New in 0.9.0. What the library requires of every call: `requireOwner` and `requireScope` as they
211
+ were given, `false` when left out. The object is frozen. Code that serves a library, such as the
212
+ upload handlers, reads it to require an owner or a scope too. It is optional in the type, so a
213
+ `LargeFiles` of your own still compiles.
177
214
 
178
- Extracts the text of a file, normalizes it, profiles it, and stores it under a new ID. Returns the
179
- new document's [`DocumentMeta`](#documentmeta).
215
+ #### `files.ingest(input)`
180
216
 
181
- 1. The owner is checked (see [`IngestInput`](#ingestinput)), the name is cleaned, and the format
182
- is picked by [`detectFormat(name, mimeType)`](#detectformatname-mimetype-bytes).
183
- 2. The extractor of that format turns the bytes into text. It receives the limits `maxTextBytes`
217
+ `ingest(input: IngestInput | IngestFromSource): Promise<DocumentMeta>`
218
+
219
+ Extracts the text of a file, normalizes it, profiles it, and stores it under a new ID, or under the
220
+ ID the application gives (`input.id`, new in 0.9.0). Returns the new document's
221
+ [`DocumentMeta`](#documentmeta). The file is given as bytes ([`IngestInput`](#ingestinput)), or,
222
+ new in 0.9.0, as a path ([`IngestFromSource`](#ingestfromsource)), which is read when the ingest's
223
+ turn comes and not held while it waits. `IngestInput` keeps its required `bytes`: a `LargeFiles`
224
+ of your own whose `ingest` declares its parameter `(input: IngestInput)` still compiles, since
225
+ `ingest` is a method. A wrapper whose parameter type is inferred does not:
226
+ `{ ...files, ingest: (input) => … }` now gets `IngestInput | IngestFromSource`, where `bytes` may be
227
+ undefined. Annotate it `(input: IngestInput)`, or narrow it (`if (input.bytes)`, or
228
+ `"source" in input`) before it reads `bytes`.
229
+
230
+ 1. The owner, the scope and the ID are checked (see [`IngestInput`](#ingestinput)), the name and
231
+ the MIME type are cleaned, and the format is picked by
232
+ [`detectFormat(name, mimeType)`](#detectformatname-mimetype-bytes). A file at a path is looked
233
+ at with `lstat` first, and nothing of it is read before its turn but the parts that tell a
234
+ format, when its name and type say nothing. Those looks are given up on when `signal` is
235
+ aborted, and fail after `ingestTimeoutMs` (2 minutes when it is 0) when the volume does not answer.
236
+ With an `id`, the store is asked whether a document of that ID is there
237
+ ([`ifExists`](#ingestinput)), before the file is read. That question is given the same time
238
+ as the writes (`ingestTimeoutMs`), and an aborted `signal` stops waiting for it. An `id` that
239
+ another ingest of this library is storing is refused at once.
240
+ 2. At its turn, a file at a path is read once, at most `maxUploadBytes + 1` bytes, and the SHA-256
241
+ of the file is taken as it is read, a megabyte at a time (new in 0.9.0). The extractor of that
242
+ format turns the bytes into text: an extractor that reads paths (`readsPath`, as the isolated
243
+ readers do) reads the file itself instead. Bytes given are hashed, a megabyte at a time, once the
244
+ extractor is done with them, so the ingests of one turn reach it in the order they came. It receives the limits `maxTextBytes`
184
245
  and `maxPdfPages`, the ingest's signal, and, when someone listens to the ingest's events, an
185
- `onProgress` to report how far it is ([`ExtractInput`](#extractinput)). A text longer
246
+ `onProgress` to report how far it is ([`ExtractInput`](#extractinput)). The bytes read from a
247
+ path are let go as soon as the extractor returns, unless the store keeps a copy. A text longer
186
248
  than `maxTextBytes` is refused, whichever extractor made it. The extractor may say how the text
187
249
  was read ([`ExtractedText`](#extractedtext)): the built-in one reads a text file that is not
188
250
  valid UTF-8 in the older encoding its lines fit, when one does, and `encoding` and
@@ -205,16 +267,23 @@ new document's [`DocumentMeta`](#documentmeta).
205
267
  lines and at least 40% of its first 200 non-blank lines start with a timestamp or a log level
206
268
  (`ERROR`, `WARN`, `INFO`...), or have the shape of an access log of nginx or Apache, a JSON log
207
269
  line, klog or logfmt (since 0.8.0).
208
- 5. The store is written: the original file (when it is kept), then the line index (when the store
209
- has `putIndex`), then `put` last.
270
+ 5. The store is written: the original file (when the store keeps a copy of it), then the line
271
+ index (when the store has `putIndex`), then `put` last. A file kept by its ref
272
+ (`IngestInput.original`) is not written: the metadata records where it is. Each call carries the document's owner and scope. With an
273
+ `id`, the store is asked again just before, for a document stored under it meanwhile; one that
274
+ `ifExists: "replace"` replaces is deleted first.
210
275
 
211
276
  Steps 2 to 4 work in slices of about 12 ms, with a pause for other requests between two slices:
212
277
  between the pages of a PDF, as a DOCX, PPTX or XLSX is unpacked, and while the text is normalized,
213
278
  measured, outlined, profiled and indexed. Ingests that run at once take turns, one slice each.
214
279
  They run under one signal, aborted by `IngestInput.signal` or after `ingestTimeoutMs` (2 minutes
215
280
  by default). When it aborts, `ingest` stops waiting for the extractor, throws, and writes nothing
216
- to the store. The writes of step 5 are not under the signal. One page of a PDF is read without a
217
- pause, and the signal is looked at only between pages.
281
+ to the store. The writes of step 5 are not under the signal, and are not cut short. Since 0.9.0,
282
+ when `IngestInput.signal` has aborted by the time they end, or just before `ingest.finish`, what
283
+ they wrote is removed (only while it is still this ingest's own, as on a failed write, within
284
+ `ingestTimeoutMs`), and `ingest` throws `signal.reason`: a client that left during the write leaves
285
+ nothing behind. Before, the document stayed, for good under `ttlMs: Infinity`. One page of a PDF is
286
+ read without a pause, and the signal is looked at only between pages.
218
287
 
219
288
  **Events.** New in 0.7.0. With `IngestInput.onEvent`, the ingest tells what it does as typed
220
289
  [`IngestEvent`](./events.md#ingestevent)s, in order: `ingest.start` first (the cleaned name, the
@@ -229,41 +298,66 @@ write) ([stages and units](./events.md#stages-and-units)). A stage sends at most
229
298
  `ingest.progress` about every 12 ms, and its last one when it ends. An extractor of your own reports
230
299
  only what it passes to `onProgress`. The error of `ingest.error` is told in words for users, with
231
300
  the `code` of an [`IngestError`](#ingesterror) (new in 0.8.0): a store that failed to write is "The
232
- document could not be stored. Try again later.", whatever it threw, and the store's own error is the
233
- one `ingest` throws. A listener that throws ends the ingest with that error, and nothing is stored;
234
- a throw on `ingest.finish` removes the document that was just stored. `createDocumentHandlers` sends
301
+ document could not be stored. Try again later.", whatever it threw, with `name:
302
+ "DocumentStoreError"` and `status: 503` (new in 0.9.0), and `ingest` throws a
303
+ `DocumentStoreError` whose `cause` is the store's own error (new in 0.9.0: it threw the store's
304
+ error itself). A listener that throws ends the ingest with that error, and nothing is stored;
305
+ a throw on `ingest.finish` removes the document that was just stored. With an `id`, it is removed
306
+ only while it is still this ingest's own: one another server stored under the ID meanwhile stays. `createDocumentHandlers` sends
235
307
  these events to a client that asks for them with `Accept: text/event-stream` ([upload with
236
308
  progress](./node.md#upload-with-progress-accept-textevent-stream)).
237
309
 
238
310
  | It throws | When |
239
311
  |---|---|
240
312
  | `TypeError("owner must be a string that is not empty or only spaces, such as the signed-in user's ID. To let anyone with the document's ID use it, leave owner out.")` | `owner` is `""`, spaces only or `null`, or, from JavaScript, neither a string nor a finite number (an object, `true`, `NaN`). Before anything is read. New in 0.6.0: 0.5.0 accepted them. |
241
- | [`IngestError`](#ingesterror) `"empty"`: `<name> is empty.` | The file has no bytes. |
242
- | `IngestError` `"too_large"`: `<name> is larger than the 100 MB upload limit.` | The file is larger than `maxUploadBytes`. The message gives your limit. |
243
- | An `IngestError` with the extractor's message | The extractor refused the file: a binary or compressed file, an Office file of before 2007 or with a password, a PDF with a password or without text, a missing optional dependency or an `unpdf` that cannot run on this Node, a possible zip bomb, a file past `maxTextBytes` or `maxPdfPages`, a file built to exhaust the server; or a parser failed on a damaged file. The `code` comes from the message ([`ingestErrorCodeOf`](#ingesterrorcodeofmessage)), `"unreadable"` for one the library does not know, and the extractor's error is `cause`. A text file is never refused for its encoding. The built-in messages, listed under [`defaultExtractors`](#defaultextractors), are written for a user. |
313
+ | `TypeError("owner is required: requireOwner is on")`, `TypeError("scope is required: requireScope is on")` | The library requires an owner or a scope, and `input` has none. Before anything is read. New in 0.9.0. |
314
+ | [`DocumentScopeError`](#documentscopeerror) `"scope_invalid"` | `scope` is not a valid [`DocumentScope`](#documentscope). Before anything is read. New in 0.9.0. |
315
+ | `TypeError('id must be lowercase letters, digits, "_" and "-", up to 64 characters, starting with a letter or a digit (APP_DOCUMENT_ID_PATTERN), and not a name Windows keeps for a device (con, nul, com1…).')` | `id` does not match [`APP_DOCUMENT_ID_PATTERN`](#app_document_id_pattern). The message does not repeat the ID. New in 0.9.0. |
316
+ | `TypeError('ifExists must be "fail" or "replace".')` | Another `ifExists`. New in 0.9.0. |
317
+ | `IngestError` `"exists"`: `<name>: a document with this ID already exists.` | A document of `id` is there and `ifExists` does not let it be replaced; or another ingest of this library is storing `id` at the moment, whatever `ifExists` says; or a write failed and the document under `id` by then is another owner's or scope's, and has not expired (stored by another server). Status 409. It says nothing of the document that has the ID, but it does say that the ID is taken ([Application IDs](../guides/storage.md#application-ids)). New in 0.9.0. |
318
+ | `TypeError("Give the file as bytes or as source, not both.")`, `TypeError("source.path must be the path of a file: a string that is not empty.")` | An input with both `bytes` and `source`, or a `source` whose `path` is not a string that is not empty (or holds a NUL). New in 0.9.0. |
319
+ | `TypeError("original.ref must be a string of 1 to 1,024 characters.")`, `TypeError("original needs LargeFilesOptions.originals, which reads the file from its ref.")` | `original` has no ref of that length, or the library has no `originals` to read it back. New in 0.9.0. |
320
+ | An error with a system error's `code` and `syscall` | A file at a path that is not there (`ENOENT`), cannot be opened (`EACCES`), is a link (`ELOOP`, from `lstat`, or from the read at its turn when a link was put in its place), a folder (`EISDIR`), or not a file at all (`EINVAL`: a pipe, a device). Or a volume that did not answer the look before the turn within `ingestTimeoutMs` (`ETIMEDOUT`, `syscall` `"lstat"` or `"read"`): `The file to ingest did not answer within 2 min.` Passed on as it is, not as an `IngestError`: it is the server's trouble, not the file's. The messages of the library's own (`ELOOP`, `EISDIR`, `EINVAL`, `ETIMEDOUT`) name no path; Node's do. New in 0.9.0. |
321
+ | [`IngestError`](#ingesterror) `"empty"`: `<name> is empty.` | The file has no bytes. A file at a path is refused from its `lstat` size, before its turn and without being read. |
322
+ | `IngestError` `"too_large"`: `<name> is larger than the 100 MB upload limit.` | The file is larger than `maxUploadBytes`. The message gives your limit. A file at a path is refused from its `lstat` size, before its turn and without being read; one that has grown past the limit by its turn is refused once `maxUploadBytes + 1` bytes are read. |
323
+ | An `IngestError` with the extractor's message | The extractor refused the file: a binary or compressed file, an Office file of before 2007 or with a password, a PDF with a password or without text, a missing optional dependency or an `unpdf` that cannot run on this Node, a possible zip bomb, a file past `maxTextBytes` or `maxPdfPages`, a file built to exhaust the server; or a parser failed on a damaged file. The `code` comes from the message ([`ingestErrorCodeOf`](#ingesterrorcodeofmessage)), `"unreadable"` for one the library does not know, and the extractor's error is `cause`. A text file is never refused for its encoding. The built-in messages, listed under [`defaultExtractors`](#defaultextractors), are written for a user. The upload handlers answer code `"unreadable"` in fixed words, not with its message (new in 0.9.0, [`Extractor`](#extractor)). |
244
324
  | `IngestError` `"too_much_text"`: `<name> holds more than 100 MB of text, more than is kept from one file. Split it, and attach the part you need.` | The text an extractor returned is larger than `maxTextBytes`. The message gives your limit. |
245
325
  | `IngestError` `"timeout"`: `<name> took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.` | The ingest took longer than `ingestTimeoutMs`. The message gives your limit: "500 ms" below a second, "45 s" below 2 minutes, "2 min" from there. |
246
- | `signal.reason` | `IngestInput.signal` was aborted, before or during the ingest. |
326
+ | `signal.reason` | `IngestInput.signal` was aborted, before or during the ingest. Since 0.9.0 also when it aborts while the store is written: what was written is removed first. |
247
327
  | `IngestError` `"no_text"`: `<name> did not contain any text.` | The extracted text is blank. |
248
328
  | What an extractor of your own threw | An error with a `status` or `statusCode`, a Node system error (one with a `code` and a `syscall`), and a value that is not an `Error`, as they are. Any other `Error` becomes an `IngestError`, as above. |
249
- | The store's own error | A write failed. `ingest` first calls `store.delete(id)` to remove what was written (an error of that call is ignored), then throws the store's error unchanged. It is not a `DocumentStoreError`. |
329
+ | [`DocumentStoreError`](#documentstoreerror), operation `"write"` | A write failed, or did not end within `ingestTimeoutMs` (code `"ETIMEDOUT"`; 2 minutes when that is 0). `ingest` first calls `store.delete(id)` to remove what was written (an error of that call is ignored). With an `id`, only when nothing is under the ID by then, or the document there is this ingest's own (the same `createdAt`, owner and scope). Otherwise it is left, and the ingest throws `IngestError` `"exists"` when that document has not expired and is another owner's or scope's; this error when it is the one a replace was to remove. A write that did not end in time may still land: the `id` stays held in this library until it has ended, with the removal of what it wrote, and another ingest of it is `"exists"` meanwhile. The same holds when a write failed at once but its clean-up does not end in time. A store that never answers keeps that one `id` refused in this library: it fails closed. The store's error is `cause`, and the message names no path or host: `The document could not be stored (EIO). Try again.` New in 0.9.0: it threw the store's error unchanged, and the time limit as `The store did not finish writing <name> within 2 min.`, which is now the message of `cause`. A `DocumentScopeError` of the store is thrown as it is. |
330
+ | `DocumentStoreError`, operation `"read"` | With an `id`: the store could not be read when it was asked whether the ID is taken, or did not answer within `ingestTimeoutMs` (code `"ETIMEDOUT"`), before the file was read or just before the writes. Code `"NEWER_VERSION"` when `ifExists: "replace"` meets a document written by a newer version of the package, which is never replaced. New in 0.9.0. |
250
331
 
251
332
  Until 0.8.0 the refusals were plain `Error`s, with the same messages. The `TypeError` of an owner is
252
333
  a mistake of the server's code, not of the file: the upload handler of
253
334
  [`llm-large-files/node`](./node.md) checks the owner itself, and answers `500` before it reads the
254
- body. The store's error, a listener of the events that threw, and the reason of an aborted signal
255
- are thrown as they are, never as an `IngestError`. The upload handler of
256
- [`llm-large-files/node`](./node.md) takes an error that carries an HTTP `status` or `statusCode`
257
- (400 to 599), or a Node system error (`code` and `syscall`), for the store's: it answers with that
258
- status, or with 500 and the code. An `IngestError` carries a `status` too, and is answered with it:
259
- 422, 413 for `"too_large"`, 503 with `Retry-After` for `"busy"`. `ingest` also keeps a mark of each
260
- error a store throws while it writes. The handler answers a marked error without a status or a code,
261
- and a thrown value that is not an `Error`, with 500 `{ "error": "Upload failed." }`, without its
262
- message. It answers any other `Error` with 422 and its message, as a file that cannot be read. The
263
- package does not export the mark: behind an `ingest` of your own that throws a new error, or in a
264
- route of your own, a store's error is answered as a file that cannot be read (see [the upload
265
- handler](./node.md#uploadrequest-response)). Give your store's write errors a `status` and a message
266
- of your own. See [errors and reliability](../guides/errors-and-reliability.md).
335
+ body. The store's `DocumentStoreError`, a listener of the events that threw, and the reason of an
336
+ aborted signal are thrown as they are, never as an `IngestError`.
337
+
338
+ The upload handler of [`llm-large-files/node`](./node.md) answers these errors by one rule ([how
339
+ errors are answered](./node.md#how-errors-are-answered)):
340
+
341
+ - Only an `IngestError` is answered 422. It carries its `status`: 422, 413 for `"too_large"`, 409
342
+ for `"exists"`, 503 with `Retry-After` for `"busy"`. Its message is the answer, except for code
343
+ `"unreadable"`, which gets fixed words: "This file could not be read. It may be damaged, or not
344
+ of the type its name says.".
345
+ - A `DocumentStoreError` is answered 503, with a message that names no path or host: since 0.9.0 a
346
+ store that failed to write is answered 503 `{ "error": "The document could not be stored (EIO).
347
+ Try again." }`, where it was a 500.
348
+ - An error that carries an HTTP `status` or `statusCode` (400 to 599) is answered with that status
349
+ and its message.
350
+ - A Node system error (`code` and `syscall`) is answered 500 `{ "error": "Upload failed (ENOENT)." }`,
351
+ with its code and not its message. Since 0.9.0, a code that does not read as one (capitals,
352
+ digits and `_`), such as a host a driver put there, is left out: "Upload failed.".
353
+ - Any other `Error`, and a value that is not an `Error`, is answered 500 `{ "error": "Upload
354
+ failed." }`, without its message. In this `ingest`, those are a `TypeError` of the call, the
355
+ reason of an aborted signal and the error of a listener. Before 0.9.0, any other `Error` was
356
+ answered 422 with its message, as a file that cannot be read (S12).
357
+
358
+ Behind an `ingest` of your own, throw an `IngestError` for a file you refuse, and a
359
+ `DocumentStoreError` for a store that failed. See
360
+ [errors and reliability](../guides/errors-and-reliability.md).
267
361
 
268
362
  Guides: [web app](../guides/web-app.md) for uploads, [PDFs](../guides/pdfs.md) for what PDF
269
363
  extraction writes.
@@ -272,23 +366,33 @@ extraction writes.
272
366
 
273
367
  `getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>`
274
368
 
275
- The document's metadata, or `undefined` when the ID does not match
276
- [`DOCUMENT_ID_PATTERN`](#document_id_pattern), the document was never there, was deleted, has
277
- expired (the library compares `expiresAt` with its clock itself, whatever the store returns), or
278
- belongs to another owner ([`AccessOptions`](#accessoptions)). Throws `DocumentStoreError` when the
279
- store cannot be read. A name that 0.5.0 or earlier stored cut inside an emoji comes back with a
280
- replacement character (U+FFFD) in place of the half, as the model and the steps get it; the stored
281
- metadata is not changed.
369
+ The document's metadata, or `undefined` when the ID has neither shape of a document ID
370
+ ([`isDocumentId`](#isdocumentidvalue)), the document was never there, was deleted, has expired (the
371
+ library compares `expiresAt` with its clock itself, whatever the store returns), or belongs to
372
+ another owner or another scope ([`AccessOptions`](#accessoptions)). The store is asked with the
373
+ caller's owner and scope. Metadata the store returns for another ID is missing too (new in 0.9.0).
374
+ An owner of `null` is left out of the metadata returned (new in 0.9.0). Throws `DocumentStoreError` when the
375
+ store cannot be read, and, new in 0.9.0, with code `"NEWER_VERSION"` when a newer version of the
376
+ package wrote the metadata ([`DOCUMENT_META_VERSION`](#document_meta_version)). A name that 0.5.0
377
+ or earlier stored cut inside an emoji comes back with a replacement character (U+FFFD) in place of
378
+ the half, as the model and the steps get it; the stored metadata is not changed.
282
379
 
283
380
  #### `files.getOriginal(id, access?)`
284
381
 
285
382
  `getOriginal(id: string, access?: AccessOptions): Promise<Uint8Array | undefined>`
286
383
 
287
- The uploaded file, when it was kept (`keepOriginals`). `undefined` in every case where `getMeta`
288
- gives `undefined`, and when the document has no `originalKept`, the store has no `getOriginal`, or
289
- the store returns none. Treat the bytes as read-only: `MemoryDocumentStore` returns the very bytes
290
- it keeps, not a copy, so changing them changes the stored file.
291
- Throws `DocumentStoreError` when the store cannot be read.
384
+ The uploaded file, when it was kept (`keepOriginals`): from the store, or, for a document ingested
385
+ with `original` (new in 0.9.0), from where your application keeps it, through `originals`.
386
+ `undefined` in every case where `getMeta` gives `undefined`, and when the document has no
387
+ `originalKept`, the library cannot read it (no `getOriginal` in the store, or no `originals` for a
388
+ file kept by its ref), or none is there. Since 0.9.0 the store is asked for the metadata again once
389
+ the bytes are read: `undefined` too when the document is not the same by then (deleted, and another
390
+ stored under its ID, by another server), or when the bytes are not those of the file that was
391
+ ingested: not of its size (`meta.bytes`), or, when the metadata has `sha256`, not of its SHA-256,
392
+ so that a store that gives back other bytes of the same size is caught. `view_pages` reads the file
393
+ the same way. Treat the bytes as read-only: a store of
394
+ your own may return the bytes it keeps. `MemoryDocumentStore` returns a copy since 0.9.0; it returned the very bytes it kept.
395
+ Throws `DocumentStoreError` as `getMeta` does.
292
396
 
293
397
  #### `files.delete(id, access?)`
294
398
 
@@ -296,17 +400,23 @@ Throws `DocumentStoreError` when the store cannot be read.
296
400
 
297
401
  Removes a document, with its original and its index. It looks the document up as `getMeta` does,
298
402
  and returns `false` when it is not there for this caller: another owner's document is never
299
- deleted. Otherwise it drops what this process keeps of the document in memory and returns what
300
- `store.delete(id)` returns. Throws `DocumentStoreError` when the look-up cannot read the store; an
301
- error of `store.delete` itself is passed on unchanged.
403
+ deleted. Otherwise it drops what this process keeps of the document in memory, in every scope,
404
+ and returns what `store.delete(id, context)` returns. Throws `DocumentStoreError` when the look-up
405
+ cannot read the store, and, new in 0.9.0, a `DocumentStoreError` of operation `"delete"` when
406
+ `store.delete` fails, with the store's error as `cause` (it was passed on unchanged). Its message
407
+ names no path: `The document could not be deleted (EPERM). Try again.`
302
408
 
303
- #### `files.sweep()`
409
+ #### `files.sweep(options?)`
304
410
 
305
- `sweep(): Promise<number>`
411
+ `sweep(options?: { scope?: DocumentScope }): Promise<number>`
306
412
 
307
413
  Calls the store's `sweep` with the library's clock and returns how many expired documents it
308
- removed: 0 when the store has no `sweep`. Errors of the store are passed on unchanged. The library
309
- never sweeps on its own: run it on a schedule, from one place (see [deployment](../guides/deployment.md)).
414
+ removed: 0 when the store has no `sweep`. With `scope` (new in 0.9.0), the store is asked to sweep
415
+ that scope only (`store.sweep(now, { scope })`); without one, every scope (`store.sweep(now, {})`).
416
+ It needs no scope under `requireScope`. A scope that is not valid is a `DocumentScopeError`. Since
417
+ 0.9.0 a store that fails is a `DocumentStoreError` of operation `"sweep"`, with the store's error as
418
+ `cause` (it was passed on unchanged). The library never sweeps on its own: run it on a schedule,
419
+ from one place (see [deployment](../guides/deployment.md)).
310
420
 
311
421
  #### `files.prepare(ids, base, options?)`
312
422
 
@@ -319,7 +429,7 @@ model reads through the tools.
319
429
  |---|---|---|
320
430
  | `ids` | `string[]` | The document IDs of the request. A repeated ID counts once. |
321
431
  | `base` | `{ tokens: number; bytes: number }` | The size of everything else in the request: messages, system prompt, other files. `estimateTokens` and `jsonBytes` measure text the way the plan does. |
322
- | `options` | [`PrepareOptions`](#prepareoptions) | The owner, a budget for this request, whether your loop can show pages, and whether your tools have `analyze_whole_document`. |
432
+ | `options` | [`PrepareOptions`](#prepareoptions) | The owner and the scope, a budget for this request, whether your loop can show pages, and whether your tools have `analyze_whole_document`. |
323
433
 
324
434
  Documents are taken smallest first, by `estimatedTokens`. Each one goes in whole when, with the
325
435
  ones already taken, it still fits both the token room,
@@ -365,13 +475,24 @@ answers with an error that lists the IDs it may use. Pass `prepared.plan.searcha
365
475
  set for each question: the time budget of regex searches and the count of whole-document reads
366
476
  belong to the tool set.
367
477
 
368
- It takes the owner from the metadata it is handed. Each call that reads a document's text or the
369
- pages of its PDF compares the owner stored with the document with the `owner` of the
370
- `DocumentMeta` given for that ID, and answers a document whose owners differ as it answers one
371
- that is gone: `doc_… is no longer available on the server. Ask the user to attach the file again.`
372
- So metadata built from an ID alone, or with another owner, reads nothing of a document that has an
373
- owner. A document stored without an owner is read whatever the metadata says. Pass documents that
374
- you got from `prepare` or `getMeta` with the caller's owner: they carry the stored owner.
478
+ Each call that reads a document's text or the pages of its PDF asks the store for the document,
479
+ and checks the owner and the scope the store holds. A document that the caller may not use is
480
+ answered as one that is gone: `doc_… is no longer available on the server. Ask the user to attach
481
+ the file again.`, and `view_pages` shows no page. A call that read a document by range asks the
482
+ store once more when it ends (new in 0.9.0): if the store no longer describes the same document, of
483
+ the same owner and scope, the call answers the same way, since what it read may be another's.
484
+
485
+ - With `access` (new in 0.9.0), the caller is `access`: the store is asked with its owner and scope,
486
+ and the document's are compared with them, as `getMeta(id, access)` does. The metadata handed in
487
+ decides nothing: metadata read from the store for another user reads nothing. `askWithFiles`
488
+ passes it. Under `requireOwner` or `requireScope`, `access` is required, with the owner or scope:
489
+ without it `tools` throws the `TypeError` of [`LargeFilesOptions`](#largefilesoptions).
490
+ - Without `access`, as before 0.9.0, the caller of each document is the `owner` and `scope` of the
491
+ `DocumentMeta` handed in for it. So metadata built from an ID alone, or with another owner or
492
+ scope, reads nothing of a document that has one. A document stored without an owner is read
493
+ whatever the metadata says. Pass documents that you got from `prepare` or `getMeta` with the
494
+ caller's owner and scope. An owner of `null` counts as none (new in 0.9.0: such a document was
495
+ missing for `getMeta`, and open to the tools).
375
496
 
376
497
  It declares `search_document`, `read_document` and `get_document_overview`;
377
498
  `analyze_whole_document` when `generate` is given and at least one document is small enough to be
@@ -417,6 +538,10 @@ type IngestInput = {
417
538
  signal?: AbortSignal;
418
539
  onEvent?: (event: IngestEvent) => void;
419
540
  runId?: string;
541
+ id?: string; // new in 0.9.0
542
+ ifExists?: "fail" | "replace"; // new in 0.9.0
543
+ scope?: DocumentScope; // new in 0.9.0
544
+ original?: { ref: string }; // new in 0.9.0
420
545
  };
421
546
  ```
422
547
 
@@ -425,15 +550,103 @@ The argument of [`files.ingest`](#filesingestinput).
425
550
  | Field | Type | Default | What it does |
426
551
  |---|---|---|---|
427
552
  | `name` | `string` | required | The file name. It is cleaned to one printable line: the last segment of a path, with control characters, line breaks and text-direction controls replaced by spaces, the characters that show nothing removed as from the text (tag characters, zero-width spaces, word joiners, soft hyphens, a byte-order mark), runs of spaces made one, trimmed, and cut to 255 characters, never in the middle of a character (`"file"` when nothing is left; an emoji of several characters, such as a flag, can lose its end). With the MIME type it picks the format. |
428
- | `mimeType` | `string` | `"application/octet-stream"` | The MIME type, trimmed. Blank counts as absent. Used when the extension names no format. |
553
+ | `mimeType` | `string` | `"application/octet-stream"` | The MIME type. Since 0.9.0 it is kept as its type and subtype, in lower case, without parameters (`"Text/CSV; charset=x"` is `"text/csv"`); one that is not a type/subtype of RFC 9110 token characters of at most 127 characters, or that holds anything but printable ASCII (a line break, a text-direction control, a tag character), is `"application/octet-stream"`. It was only trimmed. Used when the extension names no format. Never sent to the model. |
429
554
  | `bytes` | `Uint8Array` | required | The file. A Node `Buffer` is one. Empty, or larger than `maxUploadBytes`, is refused. |
430
555
  | `owner` | `string` | none | The user or tenant the document belongs to. Every later call must pass the same owner. Without one, anyone who has the ID can use the document. It must be a string that is not empty or only spaces: `""`, spaces only and `null` throw a `TypeError` (see [`files.ingest`](#filesingestinput)), since each would be one owner shared by every caller without a user. A number from JavaScript is taken, as before. Reads with the owner `""` work as before. |
431
- | `signal` | `AbortSignal` | none | Stops the ingest when it aborts, for example when the uploader goes away: `ingest` throws `signal.reason` and stores nothing. The PDF, DOCX, PPTX, XLSX and HTML extractors stop between pages and pieces; `ingest` stops waiting for an extractor of your own at once. A signal that aborts once the store is being written changes nothing. `createDocumentHandlers` passes one that aborts when the client closes the connection before the answer. |
556
+ | `signal` | `AbortSignal` | none | Stops the ingest when it aborts, for example when the uploader goes away: `ingest` throws `signal.reason` and stores nothing. The PDF, DOCX, PPTX, XLSX and HTML extractors stop between pages and pieces; `ingest` stops waiting for an extractor of your own at once. A signal that aborts once the store is being written does not cut the writes short; since 0.9.0, once they end, what they wrote is removed and `ingest` throws `signal.reason` (before, the document stayed). `createDocumentHandlers` passes one that aborts when the client closes the connection before the answer. |
432
557
  | `onEvent` | `(event: IngestEvent) => void` | none | What the ingest does as it goes: `ingest.start`, `ingest.progress` for each stage, then `ingest.finish` or `ingest.error` (see [`files.ingest`](#filesingestinput) and [events](./events.md)). Progress is worked out only when it is given. New in 0.7.0. |
433
558
  | `runId` | `string` | `"ing_"` and 16 hex digits | The `runId` of those events. New in 0.7.0. |
559
+ | `id` | `string` | `"doc_"` and 32 hex digits, made | The document's ID, chosen by the application, such as the ID of its upload. It must match [`APP_DOCUMENT_ID_PATTERN`](#app_document_id_pattern): lowercase letters, digits, `_` and `-`, up to 64 characters, starting with a letter or a digit, and not a name Windows keeps for a device (`con`, `nul`, `com1`). Another ID is a `TypeError`. The model sees the ID (in the cards and the tool calls), so it must hold no personal data, such as an email address. Over a store that keeps no scopes apart, it must be unique in the whole store: `ifExists` makes sure. A 409 tells the caller that the ID is taken, so make IDs random, or prefix them per tenant. New in 0.9.0. |
560
+ | `ifExists` | `"fail" \| "replace"` | `"fail"` | What to do when a document of `id` is already there, as the store sees it for this scope. `"fail"`: an `IngestError` `"exists"` (status 409). `"replace"`: the document is deleted, then the new one is stored; only one of the same owner and scope. One of another owner or scope is `"exists"` too, even when its text is gone. A document that has expired is written over in both cases. The store is asked before the file is read and again just before the writes. While one ingest of this library stores `id`, another ingest of `id` is `"exists"`, whatever its `ifExists`. Replacing is not atomic for readers on other servers: for a moment the document is missing. New in 0.9.0. |
561
+ | `scope` | [`DocumentScope`](#documentscope) | none | Where the document belongs, such as `[userId, chatId]`. Every store call of the ingest carries it, and it is kept in `meta.scope`, a copy: only a caller of the same scope may use the document, segment by segment. Never sent to the model, nor in a summary. An event holds it only with `eventResults: true`, in the full plan of `run.finish` and `run.error` ([events](./events.md#documents-eventresults-and-eventresult)). Not valid: a `DocumentScopeError`. `null` counts as none. New in 0.9.0. |
562
+ | `original` | `{ ref: string }` | none | Where your application keeps the uploaded file: `ref`, 1 to 1,024 characters, which your [`OriginalsReader`](#originalsreader) understands, such as a path under the folder of `fileOriginals`. When `keepOriginals` lists the format, the store keeps no copy (`putOriginal` is not called), and the metadata records `original: { ref, bytes, sha256 }`; `originalKept` is true. Without `originals` in the library: a `TypeError`. A format `keepOriginals` does not list records nothing. The ref is never sent to the model, nor in a summary. An event holds it only with `eventResults: true`, in the full plan of `run.finish` and `run.error` ([events](./events.md#documents-eventresults-and-eventresult)). The library never writes, moves or deletes that file: `delete` and `sweep` leave it. [Storage](../guides/storage.md#keeping-the-uploaded-files). New in 0.9.0. |
434
563
 
435
564
  Guide: [web app](../guides/web-app.md).
436
565
 
566
+ ### `IngestFromSource`
567
+
568
+ ```ts
569
+ type IngestSource = { path: string };
570
+ type IngestFromSource = Omit<IngestInput, "bytes"> & { source: IngestSource; bytes?: never };
571
+ ```
572
+
573
+ New in 0.9.0. An ingest of a file at a path, rather than of bytes in memory: the fields of
574
+ [`IngestInput`](#ingestinput), with `source: { path }` in place of `bytes`. The file is read when
575
+ the ingest's turn comes (`maxConcurrentIngests`), so ingests that wait hold none of their bytes:
576
+ 100 ingests of 2 MB waiting for their turn held 73 MB of memory in all as paths, against 282 to
577
+ 286 MB with their bytes given ([Deployment](../guides/deployment.md#uploads-and-ingest)).
578
+
579
+ ```ts
580
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
581
+
582
+ const files = createLargeFiles({ store: new FileDocumentStore(process.env.DOCUMENTS_DIR!) });
583
+
584
+ // The file your upload route saved. The library reads it, and leaves it where it is.
585
+ export const meta = await files.ingest({ name: "report.pdf", source: { path: "/srv/uploads/3f9a.pdf" }, owner: "user-42" });
586
+ ```
587
+
588
+ - **Before its turn**, the path is looked at with `lstat`, and nothing of the file is read. A link
589
+ is refused, not followed (an error with code `"ELOOP"`), and so is a folder or anything that is
590
+ not a file. An empty file, or one larger than `maxUploadBytes`, is refused at once
591
+ (`IngestError` `"empty"`, `"too_large"`). `ingest.start` gives that size. The ingest's time
592
+ (`ingestTimeoutMs`) begins at its turn, but this look, and the reads for its format (below), are
593
+ not waited for past it either (2 minutes when it is 0): a volume that does not answer fails the
594
+ ingest with an error of code `"ETIMEDOUT"` and `syscall` `"lstat"` or `"read"`, which names no
595
+ path. A caller that aborts `signal` meanwhile gets its own reason at once.
596
+ - **Its format**: from its name and type, as for bytes. When they say nothing (no extension,
597
+ `application/octet-stream`), from its first KB, and for a ZIP from its first 64 KB and its last
598
+ MB, read for that alone: a DOCX without its extension is still a DOCX.
599
+ - **At its turn**, the file is read once, opened without following a link at its name (not on
600
+ Windows), and at most `maxUploadBytes + 1` bytes: a file that has grown past the limit since it
601
+ was looked at is refused as `"too_large"`. Its SHA-256 is taken as it is read
602
+ (`DocumentMeta.sha256`), and `bytes` is the size read. The bytes are let go as soon as the
603
+ extractor returns, before the text is prepared, indexed and stored, unless the store keeps a copy
604
+ (`keepOriginals` without `original`).
605
+ - **An extractor that reads paths** (`Extractor.readsPath`, as those of
606
+ [`createIsolatedExtractors`](./node.md#createisolatedextractorsoptions) do) reads the file itself,
607
+ and the server reads none of it. When the store keeps a copy, the server reads it all the same,
608
+ and the extractor gets the bytes.
609
+ - **The library never writes, moves or deletes the file.** Remove it yourself when you no longer
610
+ need it, or keep it and give `original: { ref }` so that its pages can be shown without a copy in
611
+ the store.
612
+ - A path is a path on the server that ingests it. A relative path is made absolute once, against
613
+ the process's working folder when `ingest` is called: every read of the file, at its turn and in
614
+ the child process of an isolated reader, reads the file named then, even when the working folder
615
+ has changed since. The working folder and a separator are put before it, and nothing else
616
+ changes. An absolute path is used as it is. So a `..` after a link, and a `/` at the end, are
617
+ the system's to resolve, for a relative path and an absolute one alike, as
618
+ `fs.promises.realpath` (or `fs.realpathSync.native`) does. (`path.resolve`, `fs.realpath` and
619
+ `fs.realpathSync` remove them as text first, and can name another file.) On Windows, a path such as `C:notes.txt`, relative to the working
620
+ folder of a drive, goes through `path.resolve`. Never build it from what a client sends: the
621
+ library reads any file the process can read.
622
+
623
+ ### `OriginalsReader`
624
+
625
+ ```ts
626
+ type OriginalsReader = {
627
+ read(ref: string, context: OriginalReadContext): Promise<Uint8Array | undefined>;
628
+ };
629
+ type OriginalReadContext = DocumentContext & { readonly id: string; readonly bytes: number };
630
+ ```
631
+
632
+ New in 0.9.0. Reads the uploaded files your application keeps (`IngestInput.original`), for
633
+ `getOriginal` and `view_pages`: `LargeFilesOptions.originals`. `fileOriginals(root)` of
634
+ [`llm-large-files/node`](./node.md#fileoriginalsroot) is one, for files in a folder.
635
+
636
+ - `read` returns the bytes of the file at `ref`, or `undefined` when it is not there.
637
+ - `context` is the [`DocumentContext`](#documentcontext) of the call (the caller's scope and
638
+ owner), the document's `id`, and `bytes`, the size the file had at ingest. A reader may stop one
639
+ byte past `bytes`: a file of another size has changed. It is frozen.
640
+ - The library reads the ref the store holds, never one from metadata handed to it. Once the bytes
641
+ are read, it asks the store for the metadata again, as for a copy in the store, then compares the
642
+ bytes with the size and SHA-256 recorded at ingest. A file that differs has changed:
643
+ `getOriginal` gives `undefined`, and `view_pages` answers the model
644
+ `<file> changed on the server since it was read. Attach it again to look at its pages.`
645
+ - What `read` throws is passed on as a [`DocumentStoreError`](#documentstoreerror) of operation
646
+ `"read"`, with your error as `cause`, as a store's errors are.
647
+ - A look at pages holds its turn while it reads the file for at most `ingestTimeoutMs`, as it does
648
+ for a copy in the store (`maxConcurrentPageLooks`).
649
+
437
650
  ### `IngestError`
438
651
 
439
652
  ```ts
@@ -442,11 +655,13 @@ declare class IngestError extends Error {
442
655
  readonly status: number;
443
656
  readonly retryAfterMs?: number;
444
657
  constructor(code: IngestErrorCode, message: string, options?: { cause?: unknown; retryAfterMs?: number });
658
+ static is(value: unknown): value is IngestError; // new in 0.9.0
445
659
  }
446
660
 
447
661
  type IngestErrorCode =
448
662
  | "empty" | "too_large" | "too_much_text" | "too_many_pages" | "not_text" | "compressed" | "legacy_office"
449
- | "encrypted" | "no_text" | "hostile" | "timeout" | "out_of_memory" | "busy" | "missing_dependency" | "unreadable";
663
+ | "encrypted" | "no_text" | "hostile" | "timeout" | "out_of_memory" | "busy" | "missing_dependency" | "unreadable"
664
+ | "exists"; // new in 0.9.0
450
665
  ```
451
666
 
452
667
  New in 0.8.0. [`files.ingest`](#filesingestinput) could not read a file. The message says why, in
@@ -459,7 +674,7 @@ that it can tell the user in its own words or language. Until 0.8.0 the same ref
459
674
  | `name` | `string` | `"IngestError"`. |
460
675
  | `message` | `string` | The reason, written for a user: "app.log is empty.", "This PDF has no text layer (it may be scanned). …". |
461
676
  | `code` | `IngestErrorCode` | Why, as one of the codes below. |
462
- | `status` | `number` | The HTTP status the upload handler of [`llm-large-files/node`](./node.md#uploadrequest-response) answers with: 413 for `"too_large"`, 503 for `"busy"`, 422 for every other code. |
677
+ | `status` | `number` | The HTTP status the upload handler of [`llm-large-files/node`](./node.md#uploadrequest-response) answers with: 413 for `"too_large"`, 409 for `"exists"`, 503 for `"busy"`, 422 for every other code. |
463
678
  | `retryAfterMs` | `number \| undefined` | For `"busy"`: how long to wait before trying again, in milliseconds (5,000 from `createIsolatedExtractors`). The upload handler sends it as `Retry-After`, in seconds. |
464
679
  | `cause` | `unknown` | The error of the extractor, the parser or the isolated reader, when there is one. Its message is in `message`. |
465
680
 
@@ -480,6 +695,11 @@ that it can tell the user in its own words or language. Until 0.8.0 the same ref
480
695
  | `"busy"` | Every isolated reader is busy and its queue is full, it is shutting down, or a reader process could not be started for want of process slots or file handles: try again in a moment (`retryAfterMs`). |
481
696
  | `"missing_dependency"` | The optional dependency for the format is not installed, is installed and could not be loaded, or (unpdf) cannot run on this version of Node. |
482
697
  | `"unreadable"` | Any other error of reading the file: it is damaged, or not of the type its name says. |
698
+ | `"exists"` | Not the file: a document with the ID the application gave (`IngestInput.id`) is already stored. Status 409. New in 0.9.0: a `switch` over every code needs a case for it. |
699
+
700
+ `IngestError.is(value)` tells whether a value is one, also when another copy of the package made it,
701
+ where `instanceof` is `false` (see [errors](./errors-and-retries.md#telling-errors-apart-across-copies-of-the-package)).
702
+ New in 0.9.0.
483
703
 
484
704
  `ingest.error` events carry the code as [`EventError.code`](./events.md#errors-eventerror).
485
705
 
@@ -530,15 +750,17 @@ const error = new IngestError(ingestErrorCodeOf(message), message);
530
750
  ### `AccessOptions`
531
751
 
532
752
  ```ts
533
- type AccessOptions = { owner?: string };
753
+ type AccessOptions = { owner?: string; scope?: DocumentScope };
534
754
  ```
535
755
 
536
756
  Who is asking. `getMeta`, `getOriginal`, `delete` and `prepare` (through
537
- [`PrepareOptions`](#prepareoptions)) take it, and so does `askWithFiles`.
757
+ [`PrepareOptions`](#prepareoptions)) take it, `tools` as `ToolOptions.access`, and `askWithFiles`
758
+ takes the same two options. Each store call carries both ([`DocumentContext`](#documentcontext)).
538
759
 
539
760
  | Field | Type | Default | What it does |
540
761
  |---|---|---|---|
541
- | `owner` | `string` | none | Compared with the document's `owner` with `===`. A document that has an owner can be used only with that exact owner. A document without one can be used by anyone. Another owner's document looks exactly like a missing one. |
762
+ | `owner` | `string` | none | Compared with the document's `owner` with `===`. A document that has an owner can be used only with that exact owner. A document without one can be used by anyone, unless the library has `requireOwner`. Another owner's document looks exactly like a missing one. `null` counts as none. |
763
+ | `scope` | [`DocumentScope`](#documentscope) | none | The scope of the caller, such as `[userId, chatId]`. A document stored with a scope serves only a caller of the same scope, segment by segment: a caller with another scope, a longer or shorter one, or none, finds it missing. A document stored without a scope serves any caller, unless the library has `requireScope`. A store that keeps scopes apart (`MemoryDocumentStore`) does not even find a document of another scope. Not valid: a `DocumentScopeError`. `null` counts as none. New in 0.9.0. |
542
764
 
543
765
  The library has no notion of a session and cannot list documents by owner: record the IDs in your
544
766
  own data. See [storage](../guides/storage.md) and [security](../security.md).
@@ -558,6 +780,7 @@ The options of [`files.prepare`](#filesprepareids-base-options).
558
780
  | Option | Type | Default | What it does |
559
781
  |---|---|---|---|
560
782
  | `owner` | `string` | none | As in [`AccessOptions`](#accessoptions). Another owner's documents are listed in `missing` and are not read. |
783
+ | `scope` | [`DocumentScope`](#documentscope) | none | As in [`AccessOptions`](#accessoptions). Documents of another scope are listed in `missing`. New in 0.9.0. |
561
784
  | `budget` | `Partial<Budget>` | the library's | The budget fields to change for this request, as in `LargeFilesOptions.budget`. `askWithFiles` passes the budget fitted to its model. |
562
785
  | `viewPages` | `boolean` | `false` | Says that your loop can pass files to the model. `viewable` then lists the PDFs whose original is kept (with a store that has `getOriginal`), and the instruction and the cards tell the model about `view_pages`. Without it, `viewable` is empty and nothing mentions `view_pages`. |
563
786
  | `wholeDocumentAnalysis` | `boolean` | `true` | Says whether your tool set has `analyze_whole_document`. Pass `false` when you call `tools` without `generate`: the instruction then does not name it, and the cards do not offer a whole-file read or say that a file is too large for one. Each says `This file is NOT in your context. Use the document tools to search it and to read line ranges.` `askWithFiles` passes `false` when the model that explores has no `generateText`, and when its own `wholeDocumentAnalysis` is `false`. |
@@ -568,6 +791,7 @@ Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
568
791
 
569
792
  ```ts
570
793
  type ToolOptions = {
794
+ access?: AccessOptions; // new in 0.9.0
571
795
  generate?: GenerateText;
572
796
  onProgress?: ProgressListener;
573
797
  signal?: AbortSignal;
@@ -583,6 +807,7 @@ The options of [`files.tools`](#filestoolsdocuments-options).
583
807
 
584
808
  | Option | Type | Default | What it does |
585
809
  |---|---|---|---|
810
+ | `access` | [`AccessOptions`](#accessoptions) | none | Who uses the tools. With it, each call checks the owner and scope the store holds against `access`, not against the metadata handed in ([`files.tools`](#filestoolsdocuments-options)). Required under `requireOwner` or `requireScope`. `askWithFiles` passes it. New in 0.9.0. |
586
811
  | `generate` | [`GenerateText`](./ask.md#generatetext) | none | A plain text completion. It enables `analyze_whole_document`, which reads a whole file in parts. The tool is declared only when at least one of the documents is small enough: about `maxMapChunks` parts or fewer. Without `generate`, pass `wholeDocumentAnalysis: false` to `prepare`, so that the instruction does not name the tool and the cards do not offer a whole-file read. |
587
812
  | `onProgress` | [`ProgressListener`](#progresslistener) | none | Progress of whole-document reads, for status messages. |
588
813
  | `signal` | `AbortSignal` | none | Stops searches and whole-document reads. Once it has aborted, a call that fails throws instead of answering `{ error }`. |
@@ -730,9 +955,11 @@ reads it as any other.
730
955
  declare function isDocumentId(value: unknown): value is string;
731
956
  ```
732
957
 
733
- `true` for a string that matches [`DOCUMENT_ID_PATTERN`](#document_id_pattern). Use it to check IDs
734
- that come from a browser. The library's own methods already treat any other string as a missing
735
- document.
958
+ `true` for a string that has the shape of a document ID: one `ingest` makes
959
+ ([`DOCUMENT_ID_PATTERN`](#document_id_pattern)), or, since 0.9.0, one an application gives
960
+ ([`APP_DOCUMENT_ID_PATTERN`](#app_document_id_pattern), which the made ones match too). Use it to
961
+ check IDs that come from a browser. The library's own methods already treat any other string as a
962
+ missing document.
736
963
 
737
964
  ### toDocumentSummary(meta)
738
965
 
@@ -843,16 +1070,16 @@ it. `askWithFiles` builds it from what its adapters declare in
843
1070
 
844
1071
  ```ts
845
1072
  interface DocumentStore {
846
- put(document: StoredDocument): Promise<void>;
847
- get(id: string): Promise<StoredDocument | undefined>;
848
- getMeta(id: string): Promise<DocumentMeta | undefined>;
849
- delete(id: string): Promise<boolean>;
850
- sweep?(now?: Date): Promise<number>;
851
- putOriginal?(id: string, bytes: Uint8Array): Promise<void>;
852
- getOriginal?(id: string): Promise<Uint8Array | undefined>;
853
- readTextRange?(id: string, start: number, end: number): Promise<Uint8Array | undefined>;
854
- putIndex?(id: string, index: Uint8Array): Promise<void>;
855
- getIndex?(id: string): Promise<Uint8Array | undefined>;
1073
+ put(document: StoredDocument, context?: DocumentContext): Promise<void>;
1074
+ get(id: string, context?: DocumentContext): Promise<StoredDocument | undefined>;
1075
+ getMeta(id: string, context?: DocumentContext): Promise<DocumentMeta | undefined>;
1076
+ delete(id: string, context?: DocumentContext): Promise<boolean>;
1077
+ sweep?(now?: Date, context?: DocumentContext): Promise<number>;
1078
+ putOriginal?(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void>;
1079
+ getOriginal?(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
1080
+ readTextRange?(id: string, start: number, end: number, context?: DocumentContext): Promise<Uint8Array | undefined>;
1081
+ putIndex?(id: string, index: Uint8Array, context?: DocumentContext): Promise<void>;
1082
+ getIndex?(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
856
1083
  }
857
1084
  ```
858
1085
 
@@ -860,15 +1087,22 @@ Where the extracted text lives, with its metadata, and optionally the uploaded f
860
1087
  index. Use [`MemoryDocumentStore`](#memorydocumentstore) or [`FileDocumentStore`](#filedocumentstore),
861
1088
  or implement it over a database, Redis or S3.
862
1089
 
1090
+ Every method takes a last, optional `context` ([`DocumentContext`](#documentcontext)): the scope
1091
+ and the owner of the call. New in 0.9.0. A store written for 0.8, whose methods take no context,
1092
+ still compiles and works: TypeScript lets a method with fewer parameters implement one with more.
1093
+ A store that wraps another one, or a subclass that overrides a method, passes the context on:
1094
+ `super.getMeta(id, context)`, `(id, context) => inner.getMeta(id, context)`. Without `context.scope`,
1095
+ `sweep` removes the expired documents of every scope; with one, only those of that scope.
1096
+
863
1097
  | Method | Required | What it must do, and when the library calls it |
864
1098
  |---|---|---|
865
1099
  | `put(document)` | yes | Store the text and the metadata. Called last at ingest. A document should exist once its metadata does: `FileDocumentStore` writes the metadata last. Keep every field of `meta`, the optional ones too, and those a later version adds (0.6.0 added `encoding` and `replacedCharacters`): a store that keeps a fixed list of fields loses them, and one that checks `meta` against a fixed schema refuses the ingest of every file that has them. |
866
1100
  | `get(id)` | yes | The whole document, or `undefined` when there is no such document. It may return an expired one: the library checks `expiresAt` itself. Called to load a document whole: its text is at most `wholeDocumentBytes`, or the store has no `readTextRange`. |
867
- | `getMeta(id)` | yes | The metadata, or `undefined` when there is no such document (an expired one may be returned; the library checks `expiresAt`). Called by every `prepare`, `getMeta`, `getOriginal` and `delete`, and by every tool call: keep it cheap, apart from the text. |
868
- | `delete(id)` | yes | Remove the document, its original and its index, and return whether it existed. Also called by `ingest` after a failed write, so it must cope with a document that was written only in part. |
1101
+ | `getMeta(id)` | yes | The metadata, or `undefined` when there is no such document (an expired one may be returned; the library checks `expiresAt`). Called by every `prepare`, `getMeta`, `getOriginal` and `delete`, by every tool call (once more after a read by range), and by `ingest` with an application's `id`: keep it cheap, apart from the text. Return the owner absent, not `null` (the library reads `null` as none). |
1102
+ | `delete(id)` | yes | Remove the metadata first, then the text, the original and the index, and return whether the document existed. When the metadata cannot be removed, throw and leave the rest. Once it is gone, the document is gone: a part that cannot be removed then may be left for `sweep`. Also called by `ingest` after a failed write, so it must cope with a document that was written only in part, and before a document that `ifExists: "replace"` replaces. |
869
1103
  | `sweep(now?)` | no | Remove the documents expired at `now` (with their originals and indexes) and return how many. Without it, `files.sweep()` returns 0; expire the data another way, such as a TTL index of your database. |
870
1104
  | `putOriginal(id, bytes)` | no | Keep the uploaded file. Called at ingest, before `putIndex` and `put`, for the formats in `keepOriginals`. Without it, no original is kept, whatever `keepOriginals` says. |
871
- | `getOriginal(id)` | no | The kept file, or `undefined` when none was kept or there is no such document. Without it, `view_pages` is never offered. |
1105
+ | `getOriginal(id)` | no | The kept file, or `undefined` when none was kept or there is no such document. Without it, `view_pages` is never offered. A look at pages holds its turn of the library while it waits for this call (`maxConcurrentPageLooks`), and gives it back after `ingestTimeoutMs` (since 0.9.0). Give a read over a network a time limit of its own, shorter than that. |
872
1106
  | `readTextRange(id, start, end)` | no | Bytes `start` (inclusive) to `end` (exclusive) of the text exactly as given to `put`, as UTF-8: the line index is built from those bytes. Return fewer bytes at the end of the text, and `undefined` when the document is gone. Called only after `getMeta` found the document. Without it, every document is loaded whole. |
873
1107
  | `putIndex(id, index)` | no | Keep the line index of a document (a few bytes a line). Called at ingest before `put`, and when a document ingested without an index is first read by range (an error then is ignored). Without it, the index is built from the text each time a large document is opened. |
874
1108
  | `getIndex(id)` | no | The index kept by `putIndex`, or `undefined`. A damaged one is noticed and built again. An error is taken as no index. |
@@ -880,17 +1114,70 @@ Errors:
880
1114
  `readTextRange` and `getOriginal` throw reaches the caller as
881
1115
  [`DocumentStoreError`](#documentstoreerror), so that it retries instead of telling a user that the
882
1116
  file is gone. A `DocumentStoreError` you throw yourself is passed on as it is.
883
- - What `put`, `putOriginal` and `putIndex` throw at ingest is thrown by `ingest` unchanged, after it
884
- calls `delete(id)`. What `delete` and `sweep` throw is passed on unchanged.
1117
+ - What `put`, `putOriginal` and `putIndex` throw at ingest reaches the caller as a
1118
+ `DocumentStoreError` of operation `"write"`, after `ingest` calls `delete(id)`; what `delete` and
1119
+ `sweep` throw, as one of operation `"delete"` or `"sweep"`. Your error is `cause`. Before 0.9.0
1120
+ they were passed on unchanged.
1121
+ - Throw a [`DocumentScopeError`](#documentscopeerror) for a scope your store cannot keep, or a call
1122
+ without one when your store needs one.
1123
+ - Keep fields of `meta` you do not know, `metaVersion` included
1124
+ ([`DOCUMENT_META_VERSION`](#document_meta_version)): a newer version of the package may add some.
885
1125
  - The library compares `expiresAt` with its clock itself, so an expired document is never used. The
886
- store must still remove it, in `sweep` or by its own expiry.
887
-
888
- The library makes the IDs (see [`DOCUMENT_ID_PATTERN`](#document_id_pattern)), and every method
889
- except `put` receives only the ID: no owner, no metadata. A store that lays documents out per user
890
- or per chat session needs its own way from an ID to a place.
1126
+ store must still remove it, in `sweep` or by its own expiry. A store that removes an expired
1127
+ document when it reads it returns `undefined` even when that removal fails: an error there would
1128
+ reach the user as "try again" for a document that is gone.
1129
+ - [`documentStoreChecks`](./testing.md#documentstorechecksoptions) from `llm-large-files/testing`
1130
+ checks a store against these rules, in your tests.
1131
+
1132
+ The library makes the IDs (see [`DOCUMENT_ID_PATTERN`](#document_id_pattern)), or the application
1133
+ gives them ([`APP_DOCUMENT_ID_PATTERN`](#app_document_id_pattern)), and every method except `put`
1134
+ receives only the ID and the context: no metadata. A store that lays documents out per user or per
1135
+ chat session finds the place from `context.scope`. A store that ignores the context still works:
1136
+ the library keeps scopes apart through `meta.scope`, and an application's IDs must then be unique
1137
+ in the whole store.
891
1138
 
892
1139
  Guide: [storage](../guides/storage.md), which also shows a store of your own.
893
1140
 
1141
+ ### `DocumentContext`
1142
+
1143
+ ```ts
1144
+ type DocumentContext = { readonly scope?: DocumentScope; readonly owner?: string };
1145
+ ```
1146
+
1147
+ New in 0.9.0. Who a store call is for: the last argument of every [`DocumentStore`](#documentstore)
1148
+ method. A store may keep the documents of each scope apart, as `MemoryDocumentStore` does. It keeps
1149
+ at most one document of an ID in a scope: the owner says who may use a document, not where it is.
1150
+ The library always passes one, frozen, with the fields that are absent left out: `{}` for a call
1151
+ without a scope or an owner. Which one:
1152
+
1153
+ - At ingest, every call carries the document's owner and scope.
1154
+ - `getMeta`, `getOriginal` and `delete` carry the caller's (`AccessOptions`), or for `tools` without
1155
+ `access`, those of the metadata handed in.
1156
+ - The reads of a document's text (`get`, `readTextRange`, `getIndex`, and `putIndex` when its index
1157
+ is built again) carry the caller's scope and the document's owner, once the library has checked
1158
+ that the caller may use it. The scope is where `getMeta` found the document, even when its metadata
1159
+ has none. The library keeps one copy of a document for every caller of a scope, so these reads
1160
+ carry the same context whoever's call made them. For a document without an owner, they have no
1161
+ owner, whoever asked.
1162
+ - `sweep` gets the scope only.
1163
+
1164
+ | Field | Type | What it holds |
1165
+ |---|---|---|
1166
+ | `scope` | [`DocumentScope`](#documentscope) or `undefined` | Where the document belongs, such as `[userId, chatId]`. |
1167
+ | `owner` | `string \| undefined` | The owner of the call, or of the document for the reads of its text. The library checks the owner of a document itself: a store need not. |
1168
+
1169
+ ### `DocumentScope`
1170
+
1171
+ ```ts
1172
+ type DocumentScope = readonly string[];
1173
+ ```
1174
+
1175
+ New in 0.9.0. Where a document belongs, from the widest part to the narrowest: `[userId, chatId]`.
1176
+ A scope has 1 to 8 segments. Each segment has 1 to 256 characters (UTF-16 units), holds no control
1177
+ character, no `/` and no `\`, and is not `.` or `..`. A scope that breaks these rules is refused with
1178
+ a [`DocumentScopeError`](#documentscopeerror) of code `"scope_invalid"`. Segments are compared
1179
+ exactly: `"Alice"` and `"alice"` are two scopes.
1180
+
894
1181
  ### `StoredDocument`
895
1182
 
896
1183
  ```ts
@@ -909,13 +1196,13 @@ What a store keeps for a document, and what `put` receives and `get` returns.
909
1196
  ```ts
910
1197
  declare class MemoryDocumentStore implements DocumentStore {
911
1198
  constructor(options?: { now?: () => Date });
912
- put(document: StoredDocument): Promise<void>;
913
- get(id: string): Promise<StoredDocument | undefined>;
914
- getMeta(id: string): Promise<DocumentMeta | undefined>;
915
- delete(id: string): Promise<boolean>;
916
- sweep(now?: Date): Promise<number>;
917
- putOriginal(id: string, bytes: Uint8Array): Promise<void>;
918
- getOriginal(id: string): Promise<Uint8Array | undefined>;
1199
+ put(document: StoredDocument, context?: DocumentContext): Promise<void>;
1200
+ get(id: string, context?: DocumentContext): Promise<StoredDocument | undefined>;
1201
+ getMeta(id: string, context?: DocumentContext): Promise<DocumentMeta | undefined>;
1202
+ delete(id: string, context?: DocumentContext): Promise<boolean>;
1203
+ sweep(now?: Date, context?: DocumentContext): Promise<number>;
1204
+ putOriginal(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void>;
1205
+ getOriginal(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
919
1206
  }
920
1207
  ```
921
1208
 
@@ -926,8 +1213,14 @@ one-process demos. They are lost on restart and not shared between processes. It
926
1213
  bytes, so the caller may reuse its buffer. The metadata is copied too, on the way in (`put`) and
927
1214
  on the way out (`get`, `getMeta`), as a store that writes it somewhere does: changing the metadata
928
1215
  that `ingest` or `getMeta` returned (deleting its `owner` before it goes to a browser, say) changes
929
- nothing stored. Until 0.6.0 it handed out its own object. `getOriginal` returns the kept bytes
930
- themselves: treat them as read-only.
1216
+ nothing stored. Until 0.6.0 it handed out its own object. `getOriginal` returns a copy of the kept
1217
+ bytes too, since 0.9.0: until then it returned the bytes themselves.
1218
+
1219
+ The documents of each scope (`context.scope`) are kept apart, new in 0.9.0: one ID in two scopes is
1220
+ two documents, and a call with one scope never sees the documents of another. Calls without a
1221
+ scope share the documents of no scope, as every call did before. `sweep` without a scope removes
1222
+ the expired documents of every scope. A scope that is not valid is a
1223
+ [`DocumentScopeError`](#documentscopeerror).
931
1224
 
932
1225
  | Option | Type | Default | What it does |
933
1226
  |---|---|---|---|
@@ -939,23 +1232,25 @@ Guide: [testing](../guides/testing.md).
939
1232
 
940
1233
  ```ts
941
1234
  declare class FileDocumentStore implements DocumentStore {
942
- constructor(directory: string, options?: { now?: () => Date; orphanAgeMs?: number });
943
- put(document: StoredDocument): Promise<void>;
944
- get(id: string): Promise<StoredDocument | undefined>;
945
- getMeta(id: string): Promise<DocumentMeta | undefined>;
946
- delete(id: string): Promise<boolean>;
947
- sweep(now?: Date): Promise<number>;
948
- putOriginal(id: string, bytes: Uint8Array): Promise<void>;
949
- getOriginal(id: string): Promise<Uint8Array | undefined>;
950
- readTextRange(id: string, start: number, end: number): Promise<Uint8Array | undefined>;
951
- putIndex(id: string, index: Uint8Array): Promise<void>;
952
- getIndex(id: string): Promise<Uint8Array | undefined>;
1235
+ constructor(directory: string, options?: FileDocumentStoreOptions);
1236
+ put(document: StoredDocument, context?: DocumentContext): Promise<void>;
1237
+ get(id: string, context?: DocumentContext): Promise<StoredDocument | undefined>;
1238
+ getMeta(id: string, context?: DocumentContext): Promise<DocumentMeta | undefined>;
1239
+ delete(id: string, context?: DocumentContext): Promise<boolean>;
1240
+ sweep(now?: Date, context?: DocumentContext): Promise<number>;
1241
+ putOriginal(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void>;
1242
+ getOriginal(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
1243
+ readTextRange(id: string, start: number, end: number, context?: DocumentContext): Promise<Uint8Array | undefined>;
1244
+ putIndex(id: string, index: Uint8Array, context?: DocumentContext): Promise<void>;
1245
+ getIndex(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
953
1246
  }
954
1247
  ```
955
1248
 
956
1249
  Keeps each document as files in one directory, so documents survive a restart, and several servers
957
1250
  can share the directory on a network volume. It has every method, `readTextRange`, `putIndex` and
958
- `getIndex` included, so large documents are read by range.
1251
+ `getIndex` included, so large documents are read by range. With `scopes` (new in 0.9.0), the
1252
+ documents of each scope are in a folder of their own:
1253
+ `<directory>/<userId>/<chatId>/.llm-large-files/`.
959
1254
 
960
1255
  | File | What it holds |
961
1256
  |---|---|
@@ -964,33 +1259,166 @@ can share the directory on a network volume. It has every method, `readTextRange
964
1259
  | `<id>.idx` | The line index. |
965
1260
  | `<id>.bin` | The uploaded file, when it is kept. |
966
1261
 
967
- - The directory is created at the first write.
1262
+ - The files are in `directory` itself, without `scopes`. A call's context is then not used: a scope
1263
+ is only an access rule of the library (`meta.scope`). With `scopes`, they are in
1264
+ `<directory>/<scope segments>/<scopes.folder>/` ([`FileDocumentScopes`](#filedocumentscopes)).
1265
+ - The names `<id>.json`, `<id>.txt`, `<id>.idx` and `<id>.bin`, and their temporary files, belong
1266
+ to the store for every ID it is given. Where files of your own may sit (`directory` without
1267
+ `scopes`, or `scopes.folder` `""`), an ingest writes over your file of such a name, and `delete`
1268
+ or `ifExists: "replace"` removes it. Keep your own files in a subfolder, or under other names.
1269
+ - The directory is created at the first write, as are its own folders in the folder of each scope.
1270
+ Since 0.9.0, it writes files with `fileMode` (0o600) and makes folders with `directoryMode`
1271
+ (0o700), minus the umask of the process. Files and folders written before keep their modes.
968
1272
  - Every file is written under a temporary name (`<file>.<8 hex digits>.tmp`) and then renamed, so
969
- no server reads half a file. A rename that meets `EPERM`, `EACCES` or `EBUSY` (on Windows, another
970
- process has the file open for a moment) is tried again, for about 2.6 seconds in all.
971
- - `put` writes the text, then the metadata. `put`, `putOriginal` and `putIndex` throw
972
- `Error("Invalid document ID.")` for an ID that does not match `DOCUMENT_ID_PATTERN`; for such an
973
- ID the reads return `undefined` and `delete` returns `false`. Only matching IDs reach the file system.
1273
+ no server reads half a file. A rename or a removal that meets `EPERM`, `EACCES` or `EBUSY` (on
1274
+ Windows, another process has the file open for a moment) is tried again ten more times, with
1275
+ pauses of 2,630 ms in all: about 2.6 seconds. Removals are tried again since 0.9.0.
1276
+ - File names are document IDs. Since 0.9.0 an ID may be an application's
1277
+ ([`APP_DOCUMENT_ID_PATTERN`](#app_document_id_pattern)), which leaves out the names Windows keeps
1278
+ for devices (`con`, `prn`, `aux`, `nul`, `com0` to `com9`, `lpt0` to `lpt9`). `put`, `putOriginal` and
1279
+ `putIndex` throw `Error("Invalid document ID.")` for another ID; for such an ID the reads return
1280
+ `undefined` and `delete` returns `false`. The IDs the library makes keep their names, so a server
1281
+ of 0.8 still reads them. A server of 0.8 does not read documents under an application's ID.
1282
+ - `put` writes the text, then the metadata.
974
1283
  - `getMeta` returns `undefined` when the metadata file is missing or cannot be parsed (damaged, or
975
- being written by a server of 0.3.x), and removes an expired document and returns `undefined`.
1284
+ being written by a server of 0.3.x). It removes an expired document, as far as it can, and
1285
+ returns `undefined`: since 0.9.0 also when the removal fails, which `sweep` then tries again.
976
1286
  `get`, `readTextRange` and `getOriginal` return `undefined` for a missing file. Any other failure
977
1287
  of a read is thrown. `getIndex` returns `undefined` for any failure.
978
- - `delete` removes the metadata first, then the text, the index and the original, and returns
979
- whether the metadata existed. When the metadata cannot be removed, nothing else is, and the
980
- document stays whole.
1288
+ - Since 0.9.0, a read does not follow a link at a file name (`O_NOFOLLOW`): a document file that is
1289
+ a link counts as missing. Windows has no such flag, so there a link at a file name is followed;
1290
+ links in the folders of a scope are refused on every platform (`"scope_invalid"`).
1291
+ - `delete` removes the metadata first. When that fails, it throws, and nothing else is removed: the
1292
+ document stays whole. Then it removes the text, the index and the original, and returns whether
1293
+ the metadata existed. Since 0.9.0, a part that cannot be removed then is left for `sweep`, and
1294
+ `delete` still returns `true`: the document is gone once its metadata is.
981
1295
  - `sweep(now?)` removes expired documents and returns how many, counting a document whose metadata
982
- is not valid and is older than `orphanAgeMs`. It also removes files that belong to no document,
983
- and temporary files, once they are older than `orphanAgeMs` (these are not counted). A document
984
- whose metadata could not be read at all, or that could not be removed, is left for the next
985
- sweep. When the directory cannot be read, it returns 0.
1296
+ is not valid and is older than `orphanAgeMs`. It counts only the documents whose metadata it
1297
+ removed itself: of two sweeps at once, on one server or two, each document is counted once
1298
+ (since 0.9.0). Not always on Windows: there, two processes that remove one file at the same
1299
+ moment can both be told it was removed, so the total can count a document twice. It also
1300
+ removes files that belong to no document, and temporary files, once they are older than
1301
+ `orphanAgeMs` (these are not counted). Where files
1302
+ of your own may sit beside the documents (`directory` without `scopes`, or `scopes.folder` `""`),
1303
+ a file of no document is removed only when its name is an ID the library makes, or a temporary
1304
+ file: `notes.txt` may be yours, not the text of a document `notes`. A document whose metadata
1305
+ could not be read at all, or that could not be removed, is left for the next sweep. A folder that
1306
+ cannot be read counts as empty.
1307
+ - `sweep` runs its reads of metadata, its listings and its checks of a file's age
1308
+ `sweepConcurrency` at a time (16), since 0.9.0. Until then it read one file after another.
1309
+ - With `scopes`, `sweep(now, { scope })` sweeps the folder of that scope. `sweep(now)`, or with a
1310
+ context without a scope (as `files.sweep()` calls it), sweeps every scope: it goes down exactly
1311
+ `scopes.depth` levels of folders, enters only folders whose names pass
1312
+ [`isSafeScopeSegment`](#issafescopesegmentvalue) (so never `<chat>/uploads`), follows no link,
1313
+ and sweeps the store's folder in each. With `unscoped: "root"`, it sweeps `directory` itself too.
986
1314
 
987
1315
  | Option | Type | Default | What it does |
988
1316
  |---|---|---|---|
989
1317
  | `now` | `() => Date` | `() => new Date()` | The clock that decides expiry, and the default `now` of `sweep`. |
990
1318
  | `orphanAgeMs` | `number` | 3,600,000 (1 hour) | `sweep` removes files that belong to no document (an upload that failed, a server that stopped while writing) and temporary files only once they are this old. Younger ones may be an upload in progress, on this server or another one. |
1319
+ | `scopes` | [`FileDocumentScopes`](#filedocumentscopes) | None | Keep the documents of each scope in a folder of their own. New in 0.9.0. |
1320
+ | `fileMode` | `number` | `0o600` | The mode of each file it writes, minus the umask. `0o640` lets a group read them (pods that share an `fsGroup`, a backup job). New in 0.9.0: until then, `0o666` minus the umask. |
1321
+ | `directoryMode` | `number` | `0o700` | The mode of each folder it makes, minus the umask. `0o750` goes with `fileMode: 0o640`. New in 0.9.0: until then, `0o777` minus the umask. |
1322
+ | `sweepConcurrency` | `number` | 16 | How many reads of metadata, listings and checks of a file's age `sweep` runs at once, over every folder it sweeps. A whole number of 1 or more. New in 0.9.0. |
1323
+
1324
+ The constructor throws a `TypeError` for an option that is not valid: a `depth` outside 1 to 8, a
1325
+ `folder` that is not one folder's name, a mode outside 0 to 0o777, a `sweepConcurrency` below 1.
991
1326
 
992
1327
  Guides: [storage](../guides/storage.md), [deployment](../guides/deployment.md).
993
1328
 
1329
+ ### `FileDocumentStoreOptions`
1330
+
1331
+ ```ts
1332
+ type FileDocumentStoreOptions = {
1333
+ now?: () => Date;
1334
+ orphanAgeMs?: number;
1335
+ scopes?: FileDocumentScopes; // new in 0.9.0
1336
+ fileMode?: number; // new in 0.9.0, default 0o600
1337
+ directoryMode?: number; // new in 0.9.0, default 0o700
1338
+ sweepConcurrency?: number; // new in 0.9.0, default 16
1339
+ };
1340
+ ```
1341
+
1342
+ The options of [`FileDocumentStore`](#filedocumentstore), described there. New in 0.9.0 as a named
1343
+ type.
1344
+
1345
+ ### `FileDocumentScopes`
1346
+
1347
+ ```ts
1348
+ type FileDocumentScopes = {
1349
+ depth: number;
1350
+ folder?: string; // default ".llm-large-files"
1351
+ createScopeFolders?: boolean; // default false
1352
+ unscoped?: "refuse" | "root"; // default "refuse"
1353
+ };
1354
+ ```
1355
+
1356
+ New in 0.9.0. How a [`FileDocumentStore`](#filedocumentstore) keeps the documents of each scope in
1357
+ a folder of their own: `<directory>/<segment 1>/…/<segment depth>/<folder>/<id>.json`.
1358
+
1359
+ | Field | Default | What it does |
1360
+ |---|---|---|
1361
+ | `depth` | Required | How many segments every scope has, from 1 to 8: 2 for `[userId, chatId]`. |
1362
+ | `folder` | `".llm-large-files"` | The store's folder in the folder of each scope. `""` puts the files in the scope's folder itself, beside files of your own. The names `<id>.json`, `.txt`, `.idx` and `.bin`, and their temporary files, then belong to the store for every ID it is given: an ingest writes over your file of such a name. Keep your own files in a subfolder, such as `uploads/`, or under other names. |
1363
+ | `createScopeFolders` | `false` | Whether a write makes the folders of a scope that has none. With `false`, the folders of a scope are yours: the store only makes its own `folder` in one that exists. With `true`, it makes them one level at a time, and checks that each is a folder and not a link before it goes into it: it makes nothing where a link points. |
1364
+ | `unscoped` | `"refuse"` | What a call without a scope does. `"refuse"`: a `DocumentScopeError` of code `"scope_required"`. `"root"`: it uses the files in `directory` itself, as a store without `scopes`, to keep reading documents written there before. |
1365
+
1366
+ What a call's scope must be, or the call throws a [`DocumentScopeError`](#documentscopeerror)
1367
+ whose message names no segment:
1368
+
1369
+ | Code | When |
1370
+ |---|---|
1371
+ | `"scope_invalid"` | The scope has not `depth` segments, or a segment does not pass [`isSafeScopeSegment`](#issafescopesegmentvalue) (lowercase letters, digits, `_` and `-`, up to 64 characters, no device name). Or the folder of the scope, or the store's folder in it, is a link or lies under one: the path must be the folder's real path inside `directory`. |
1372
+ | `"scope_required"` | The call has no scope, under `unscoped: "refuse"`. `sweep` without one sweeps every scope instead. |
1373
+ | `"scope_missing"` | A write into a scope whose folder is not there, with `createScopeFolders` false: the chat was deleted. The folder is not made again. Reads in such a scope find nothing: `undefined`, and `false` from `delete`. |
1374
+
1375
+ - Segments are lowercase only because SMB and Azure Files ignore case: `Alice` and `alice` would
1376
+ be one folder. Pass [`hashedScopeSegment(value)`](#hashedscopesegmentvalue) as the segment for an
1377
+ ID in mixed case or in Hebrew, at ingest and on every later call.
1378
+ - A call checks the real path of its scope's folder (`realpath`). A read takes a folder that passed
1379
+ the check less than a second ago as checked; the store remembers up to 4,096 such folders. A
1380
+ write, a `delete` and a `sweep` with a scope check again every time, and so does the first read
1381
+ after a read that found no file. A read of a scope with no folder costs that one look. Swapping a
1382
+ chat's folder for a link is therefore seen by reads within a second, and by writes at once.
1383
+ - A wrapper or a subclass that does not pass the context on gets `"scope_required"` on every call:
1384
+ pass it on ([Writing a store of your own](../guides/storage.md#writing-a-store-of-your-own)).
1385
+
1386
+ ### isSafeScopeSegment(value)
1387
+
1388
+ ```ts
1389
+ declare function isSafeScopeSegment(value: string): boolean;
1390
+ ```
1391
+
1392
+ New in 0.9.0. Whether a [`FileDocumentStore`](#filedocumentstore) with `scopes` takes `value` as a
1393
+ segment of a scope, that is, as the name of a folder: lowercase letters, digits, `_` and `-`, 1 to
1394
+ 64 characters, starting with a letter or a digit, and not a name Windows keeps for a device
1395
+ (`con`, `prn`, `aux`, `nul`, `com0` to `com9`, `lpt0` to `lpt9`): the shape of
1396
+ [`APP_DOCUMENT_ID_PATTERN`](#app_document_id_pattern). UUIDs and MongoDB ObjectIds in lowercase
1397
+ hex pass it as they are.
1398
+
1399
+ ### hashedScopeSegment(value)
1400
+
1401
+ ```ts
1402
+ declare function hashedScopeSegment(value: string): string;
1403
+ ```
1404
+
1405
+ New in 0.9.0. A segment that [`isSafeScopeSegment`](#issafescopesegmentvalue) accepts, made from any
1406
+ string that is not empty: `h` and the first 40 hexadecimal digits of the SHA-256 of its UTF-8.
1407
+ The same value always gives the same segment. Use it for an ID in mixed case, or in Hebrew, and
1408
+ for every ID of that level of the scope, not only those that would not pass. The store never hashes
1409
+ on its own: pass the result as the segment, at ingest and on every later call, and use it to name
1410
+ the folders you make and remove. `meta.scope` holds what you passed. Throws a `TypeError` for a
1411
+ value that is not a string, or is empty.
1412
+
1413
+ ```ts
1414
+ import { FileDocumentStore, hashedScopeSegment } from "llm-large-files";
1415
+
1416
+ export const store = new FileDocumentStore(process.env.DOCUMENTS_DIR!, { scopes: { depth: 2 } });
1417
+
1418
+ // User IDs in mixed case ("Alice@Example.com"); chat IDs are lowercase UUIDs, which pass as they are.
1419
+ export const scopeOf = (userId: string, chatId: string) => [hashedScopeSegment(userId), chatId];
1420
+ ```
1421
+
994
1422
  ### `DOCUMENT_ID_PATTERN`
995
1423
 
996
1424
  ```ts
@@ -998,33 +1426,74 @@ declare const DOCUMENT_ID_PATTERN: RegExp; // /^doc_[a-f0-9]{32}$/
998
1426
  ```
999
1427
 
1000
1428
  The shape of every document ID that `ingest` makes: `doc_` and 32 lowercase hexadecimal digits
1001
- (a random UUID without its dashes). [`isDocumentId`](#isdocumentidvalue) tests a value against it.
1429
+ (a random UUID without its dashes), when the application gives none (`IngestInput.id`).
1430
+
1431
+ ### `APP_DOCUMENT_ID_PATTERN`
1432
+
1433
+ ```ts
1434
+ declare const APP_DOCUMENT_ID_PATTERN: RegExp; // /^(?!(?:con|prn|aux|nul|com[0-9]|lpt[0-9])$)[a-z0-9][a-z0-9_-]{0,63}$/
1435
+ ```
1436
+
1437
+ New in 0.9.0. The shape of a document ID an application chooses (`IngestInput.id`): lowercase
1438
+ letters, digits, `_` and `-`, up to 64 characters, starting with a letter or a digit. It does not
1439
+ match a name Windows keeps for a device (`con`, `prn`, `aux`, `nul`, `com0` to `com9`, `lpt0` to
1440
+ `lpt9`), since `con.json` is not a file there. Longer names, such as `console` or `com10`, match.
1441
+ `ingest` refuses an `id` that does not match with a `TypeError`, before it calls the store. The IDs
1442
+ `ingest` makes have the shape too. [`isDocumentId`](#isdocumentidvalue) tests a value against it.
1443
+
1444
+ ### `DOCUMENT_META_VERSION`
1445
+
1446
+ ```ts
1447
+ declare const DOCUMENT_META_VERSION: 1;
1448
+ ```
1449
+
1450
+ New in 0.9.0. The version of [`DocumentMeta`](#documentmeta) this version of the package writes, as
1451
+ `metaVersion`, and the highest it reads. Metadata without `metaVersion` (or with `null`) was
1452
+ written before 0.9.0, and is read as before. Metadata with a higher one was written by a newer
1453
+ version: `getMeta`, `getOriginal`, `delete`, `prepare`, `askWithFiles` and the tools refuse it
1454
+ with a [`DocumentStoreError`](#documentstoreerror) of code `"NEWER_VERSION"`, not as a missing
1455
+ document, so that an application does not ingest the file again over newer data. This happens
1456
+ while servers of two versions share a store: let the call be tried again on a newer one.
1002
1457
 
1003
1458
  ### `DocumentStoreError`
1004
1459
 
1005
1460
  ```ts
1461
+ type DocumentStoreOperation = "read" | "write" | "delete" | "sweep";
1462
+
1006
1463
  declare class DocumentStoreError extends Error {
1007
1464
  readonly code?: string;
1008
1465
  readonly syscall?: string;
1009
- constructor(cause: unknown);
1466
+ readonly operation: DocumentStoreOperation; // new in 0.9.0
1467
+ readonly status: 503; // new in 0.9.0
1468
+ constructor(cause: unknown, options?: { operation?: DocumentStoreOperation; code?: string });
1469
+ static is(value: unknown): value is DocumentStoreError; // new in 0.9.0
1010
1470
  }
1011
1471
  ```
1012
1472
 
1013
- The store could not be read just now: a volume that did not answer, too many open files, a database
1014
- that is down. It does not mean that the document is gone, and the same call may work a moment
1015
- later: retry it, rather than ask the user to upload the file again.
1473
+ The store failed just now: a volume that did not answer, too many open files, a database that is
1474
+ down. It does not mean that the document is gone, and the same call may work a moment later: retry
1475
+ it, rather than ask the user to upload the file again.
1016
1476
 
1017
1477
  | Field | Type | What it holds |
1018
1478
  |---|---|---|
1019
1479
  | `name` | `string` | `"DocumentStoreError"`. |
1020
- | `message` | `string` | `The document store could not be read (<code>). Try again.`, or without the code when there is none. It names no path and no host: it is safe to show to a user or a model. |
1021
- | `code` | `string \| undefined` | The code of the system error behind it (`EIO`, `EMFILE`, `ETIMEDOUT`), when there is one. |
1480
+ | `message` | `string` | By `operation`: `The document store could not be read (<code>). Try again.` ("read"), `The document could not be stored (<code>). Try again.` ("write"), `The document could not be deleted (<code>). Try again.` ("delete"), `The document store could not be cleaned up (<code>). Try again.` ("sweep"), each without the code when there is none. For code `"NEWER_VERSION"`: `The document was stored by a newer version of llm-large-files. Try again.` It names no path and no host: it is safe to show to a user or a model. |
1481
+ | `code` | `string \| undefined` | The code of the system error behind it (`EIO`, `EMFILE`, `ETIMEDOUT`), when there is one, or the code it was made with: `"NEWER_VERSION"` for metadata a newer version of the package wrote ([`DOCUMENT_META_VERSION`](#document_meta_version)). |
1022
1482
  | `syscall` | `string \| undefined` | The system call that failed (`open`, `read`), when there is one. |
1483
+ | `operation` | `"read" \| "write" \| "delete" \| "sweep"` | What the store was doing. `"read"` unless it was made with another. New in 0.9.0. |
1484
+ | `status` | `503` | The HTTP status to answer with. New in 0.9.0. |
1023
1485
  | `cause` | `unknown` | What the store threw. Log it on the server; it may name a path or a host. |
1024
1486
 
1487
+ `DocumentStoreError.is(value)` tells whether a value is one, also when another copy of the package
1488
+ made it (two versions installed side by side, or one in a bundle), where `instanceof` is `false`.
1489
+ New in 0.9.0.
1490
+
1025
1491
  `files.getMeta`, `files.getOriginal`, `files.delete` (its look-up) and `files.prepare` throw it,
1026
1492
  and so does `askWithFiles`. A tool call that meets it answers the model with its message instead of
1027
- throwing. Errors of writes are never wrapped in it (see [`DocumentStore`](#documentstore)).
1493
+ throwing. Since 0.9.0 the library also wraps the errors of writes in it: `files.ingest` (operation
1494
+ `"write"`, and code `"ETIMEDOUT"` for a write that did not end in time), `files.delete`
1495
+ (`"delete"`) and `files.sweep` (`"sweep"`). Until then they were passed on unchanged (see
1496
+ [`DocumentStore`](#documentstore)). A `DocumentScopeError` is never wrapped.
1028
1497
 
1029
1498
  ```ts
1030
1499
  import { DocumentStoreError, toDocumentSummary, type LargeFiles } from "llm-large-files";
@@ -1035,27 +1504,66 @@ async function documentSummary(files: LargeFiles, id: string, owner: string) {
1035
1504
  const meta = await files.getMeta(id, { owner });
1036
1505
  return meta ? { status: 200, body: toDocumentSummary(meta) } : { status: 404, body: { error: "Not found." } };
1037
1506
  } catch (error) {
1038
- if (!(error instanceof DocumentStoreError)) throw error;
1507
+ if (!DocumentStoreError.is(error)) throw error;
1039
1508
  console.error(error.cause); // what the store threw: for your log only
1040
- return { status: 503, body: { error: error.message } };
1509
+ return { status: error.status, body: { error: error.message } };
1041
1510
  }
1042
1511
  }
1043
1512
  ```
1044
1513
 
1045
1514
  Guide: [errors and reliability](../guides/errors-and-reliability.md).
1046
1515
 
1516
+ ### `DocumentScopeError`
1517
+
1518
+ ```ts
1519
+ type DocumentScopeErrorCode = "scope_required" | "scope_invalid" | "scope_missing";
1520
+
1521
+ declare class DocumentScopeError extends TypeError {
1522
+ readonly code: DocumentScopeErrorCode;
1523
+ constructor(code: DocumentScopeErrorCode, message?: string, options?: { cause?: unknown });
1524
+ static is(value: unknown): value is DocumentScopeError;
1525
+ }
1526
+ ```
1527
+
1528
+ New in 0.9.0. A scope ([`DocumentScope`](#documentscope)) that cannot be used. It is a mistake in
1529
+ the call, not a failure of the store: the same call fails again, so do not retry it. The library
1530
+ passes it on as it is. Its message never repeats a segment of the scope, which may be a user's ID.
1531
+
1532
+ | Code | When | Message, unless another is given |
1533
+ |---|---|---|
1534
+ | `"scope_invalid"` | The scope breaks the rules of [`DocumentScope`](#documentscope), or the store cannot keep it. | Which rule, and which segment: `scope segment 2 cannot be "." or "..".` |
1535
+ | `"scope_required"` | The store needs a scope, and the call had none. | `A scope is required: pass the scope of the document, such as [userId, chatId].` |
1536
+ | `"scope_missing"` | The store keeps the scope in a place that is gone (the chat was deleted). | `The scope no longer exists.` |
1537
+
1538
+ `DocumentScopeError.is(value)` works across copies of the package, as `DocumentStoreError.is` does.
1539
+
1047
1540
  ## Extraction
1048
1541
 
1049
1542
  ### `Extractor`
1050
1543
 
1051
1544
  ```ts
1052
- type Extractor = (bytes: Uint8Array, input: ExtractInput) => Promise<ExtractedText>;
1545
+ type Extractor = ((bytes: Uint8Array, input: ExtractInput) => Promise<ExtractedText>) & { readsPath?: boolean };
1053
1546
  ```
1054
1547
 
1055
1548
  Turns the bytes of an uploaded file into text, for one format. To refuse a file, throw an `Error`
1056
1549
  whose message a user can read: `ingest` throws it as an [`IngestError`](#ingesterror) with the same
1057
1550
  message, the code its message gives (`"unreadable"` for words the library does not know), and your
1058
- error as `cause`. Throw an `IngestError` yourself to choose the code. The library then normalizes the
1551
+ error as `cause`. Throw an `IngestError` yourself to choose the code.
1552
+
1553
+ The upload handlers ([`createDocumentHandlers`](./node.md#createdocumenthandlersfiles-options)),
1554
+ [`uploadAnswerOf`](./node.md#uploadansweroferror) and
1555
+ [`errorInfoOf`](./errors-and-retries.md#errorinfooferror) do not show the message of code
1556
+ `"unreadable"`: since 0.9.0 they answer "This file could not be read. It may be damaged, or not of
1557
+ the type its name says.", since that message is most often a parser's, and may name a host. Your
1558
+ message stays on the error, for your log. To have your own words shown:
1559
+
1560
+ - Throw an `IngestError` with the code that fits: `new IngestError("no_text", "scan.pdf has no text
1561
+ layer. Run OCR on it first.")`. The handlers answer it 422 with your message, and `errorInfoOf`
1562
+ gives it as its `message`.
1563
+ - Or throw an `Error` with a `status` from 400 to 599: the handlers answer with that status and your
1564
+ message. `errorInfoOf` reads such an error as a model's, though, and does not show its words.
1565
+
1566
+ The library then normalizes the
1059
1567
  text, splits long lines and refuses blank text, as described under
1060
1568
  [`files.ingest`](#filesingestinput). For a PDF, write a line `--- Page N ---` before the text of
1061
1569
  each page, counting from 1, as the built-in one does: the page numbers in tool results and
@@ -1074,6 +1582,17 @@ const text: Extractor = async (bytes, input) => {
1074
1582
  const files = createLargeFiles({ store: new MemoryDocumentStore(), extractors: { text } });
1075
1583
  ```
1076
1584
 
1585
+ `readsPath`, new in 0.9.0: the extractor reads a file ingested from a path
1586
+ ([`IngestFromSource`](#ingestfromsource)) itself, so the server does not read it first. It is then
1587
+ given empty bytes and `ExtractInput.path` (always absolute) and `maxUploadBytes`: read the file once, at most
1588
+ `maxUploadBytes + 1` bytes, refuse it past `maxUploadBytes` with the library's message
1589
+ (`<name> is larger than the 100 MB upload limit.`), never write, move or delete it, and return its
1590
+ size and SHA-256 in `ExtractedText.file`. Without `file`, `ingest` reads the file once more to hash
1591
+ it, a megabyte at a time, holding none of it. When the store keeps a copy of the file, the
1592
+ extractor gets the bytes as before. The extractors of
1593
+ [`createIsolatedExtractors`](./node.md#createisolatedextractorsoptions) set it. A plain function
1594
+ is an extractor that does not read paths, as before.
1595
+
1077
1596
  Guide: [PDFs](../guides/pdfs.md), for OCR and other PDF extractors.
1078
1597
 
1079
1598
  ### `ExtractInput`
@@ -1088,19 +1607,23 @@ type ExtractInput = {
1088
1607
  maxTextBytes?: number;
1089
1608
  maxPages?: number;
1090
1609
  onProgress?: (progress: ExtractProgress) => void;
1610
+ path?: string; // new in 0.9.0
1611
+ maxUploadBytes?: number; // new in 0.9.0
1091
1612
  };
1092
1613
  ```
1093
1614
 
1094
1615
  | Field | Type | What it holds |
1095
1616
  |---|---|---|
1096
1617
  | `name` | `string` | The cleaned file name (see [`IngestInput`](#ingestinput)). |
1097
- | `mimeType` | `string` | The MIME type, `"application/octet-stream"` when none was given. |
1618
+ | `mimeType` | `string` | The MIME type, cleaned (see [`IngestInput`](#ingestinput)): `"application/octet-stream"` when none was given. |
1098
1619
  | `format` | [`DocumentFormat`](#documentformat) | The format from `detectFormat`. A text file that turns out to be a log is still `"text"` here: logs are recognized after extraction. |
1099
- | `scannedPages` | `number \| undefined` | Set for a PDF when one without any text may be accepted: `"pdf"` is in `keepOriginals`, the store has `putOriginal`, and `scannedPdfPages` is above 0. It is the most pages such a PDF may have. Unset, a PDF without text is to be refused. An extractor of your own may ignore it. |
1620
+ | `scannedPages` | `number \| undefined` | Set for a PDF when one without any text may be accepted: `"pdf"` is in `keepOriginals`, the file is kept (the store has `putOriginal`, or the ingest gives `original` and the library has `originals`), and `scannedPdfPages` is above 0. It is the most pages such a PDF may have. Unset, a PDF without text is to be refused. An extractor of your own may ignore it. |
1100
1621
  | `signal` | `AbortSignal \| undefined` | The signal of the ingest: aborted after `ingestTimeoutMs`, or when `IngestInput.signal` aborts. Its `reason` is the error to throw. The PDF, DOCX, PPTX, XLSX and HTML extractors stop between pages and pieces. The text extractor decodes valid UTF-8 and UTF-16 in one step, and a file that is not valid UTF-8 a step at a time, whatever it is read in, stopping between two steps. `ingest` sets it, and stops waiting for your extractor when it aborts, but cannot stop the work your extractor does: pass it on (to `fetch`, for example), or check it between steps with `signal.throwIfAborted()`. |
1101
1622
  | `maxTextBytes` | `number \| undefined` | `LargeFilesOptions.maxTextBytes`: the most text to keep, in UTF-8 bytes. `ingest` sets it, and refuses a larger text from any extractor once it returns. An extractor that refuses as soon as its text grows past it spares the memory. |
1102
1623
  | `maxPages` | `number \| undefined` | `LargeFilesOptions.maxPdfPages`: the most pages to read from one PDF. `ingest` sets it for every format; only the built-in PDF extractor uses it. `ingest` does not check it for you. |
1103
1624
  | `onProgress` | `((progress: ExtractProgress) => void) \| undefined` | Call it as the extraction goes on, so that `ingest` can report progress ([`ExtractProgress`](#extractprogress)). Set only when someone listens to the ingest's events (`IngestInput.onEvent`). The built-in extractors call it for each page of a PDF, each part of a DOCX, each slide of a PPTX and each sheet of an XLSX, and once when an HTML file is decoded. An extractor of your own may ignore it: the ingest then sends no `extract` progress. What it reports after it returned is dropped. It can throw, when the listener of the events throws: let that error end the extraction. New in 0.7.0. |
1625
+ | `path` | `string \| undefined` | Set only for an extractor that reads paths (`readsPath`) and a file ingested from a path: where the file is, as an absolute path (a relative `source.path` is made absolute when `ingest` is called). The bytes are then empty. New in 0.9.0. |
1626
+ | `maxUploadBytes` | `number \| undefined` | Set with `path`: `LargeFilesOptions.maxUploadBytes`, the most bytes the file may have. New in 0.9.0. |
1104
1627
 
1105
1628
  ### `ExtractProgress`
1106
1629
 
@@ -1149,7 +1672,13 @@ const files = createLargeFiles({ store: new MemoryDocumentStore(), extractors: {
1149
1672
  ### `ExtractedText`
1150
1673
 
1151
1674
  ```ts
1152
- type ExtractedText = { text: string; pages?: number; encoding?: string; replacedCharacters?: number };
1675
+ type ExtractedText = {
1676
+ text: string;
1677
+ pages?: number;
1678
+ encoding?: string;
1679
+ replacedCharacters?: number;
1680
+ file?: { bytes: number; sha256: string }; // new in 0.9.0
1681
+ };
1153
1682
  ```
1154
1683
 
1155
1684
  | Field | Type | What it holds |
@@ -1158,6 +1687,7 @@ type ExtractedText = { text: string; pages?: number; encoding?: string; replaced
1158
1687
  | `pages` | `number \| undefined` | The number of pages (the slides of a PPTX, the sheets of an XLSX), stored as `DocumentMeta.pages`. |
1159
1688
  | `encoding` | `string \| undefined` | The older encoding the file was read in, when it is not UTF-8, such as `"windows-1255"`. Stored as `DocumentMeta.encoding` when it is a name (letters, digits, `.`, `_`, `:` and `-`, up to 40 characters) and not a name of UTF-8 or UTF-16 (`utf-8`, `utf8`, `unicode`, `utf-16be`…): a name `TextDecoder` does not know is kept. New in 0.6.0. |
1160
1689
  | `replacedCharacters` | `number \| undefined` | The characters that were not valid in the encoding the file was read in, each now U+FFFD (�). Stored as `DocumentMeta.replacedCharacters` when it is a whole number above 0. New in 0.6.0. |
1690
+ | `file` | `{ bytes, sha256 } \| undefined` | What an extractor that reads paths read from `ExtractInput.path`: the size of the file, and its SHA-256 as 64 lowercase hex digits. Stored as `DocumentMeta.bytes` and `sha256`. Read only for an ingest from a path whose extractor read it; left out otherwise, and ignored in another shape. New in 0.9.0. |
1161
1691
 
1162
1692
  The model is told of both, on the card and in the frame of a file sent whole (see
1163
1693
  [`PreparedContext`](#preparedcontext)).
@@ -1190,8 +1720,8 @@ with the code of its words ([`ingestErrorCodeOf`](#ingesterrorcodeofmessage)):
1190
1720
  - `This PDF is protected by a password, so it cannot be read. Open it, print it to a new PDF without the password, and attach that.` (new in 0.8.0: pdf.js said "No password given")
1191
1721
  - `Reading PDF files needs the optional dependency "unpdf".`
1192
1722
  - `The optional dependency "<name>" is installed but could not be loaded (<the reason>). Reinstall it, or install a version this Node can run.` (new in 0.8.0: it was reported as missing; the failure is `cause`)
1193
- - `The unpdf installed would stop the whole server at the first PDF file on Node <n>, so PDF files are not read.`, followed by what to install: before Node 22 `Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 24 or later.`, on Node 22 and 23 `Install unpdf 1.6.1 or later, or run Node 24 or later.`, on a later Node `Install unpdf 1.6.1 or later.` (an `unpdf` from 1.5.0 to 1.6.0, which loads a pdf.js that calls `Promise.try` where Node does not have it; new in 0.6.0)
1194
- - `The unpdf installed cannot read PDF files on Node <n> (<unpdf's message>). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.` (before Node 22, an `unpdf` that cannot load its pdf.js: 1.9 and later, 2.x included; new in 0.6.0. From Node 22 on, unpdf's own error is thrown as it is.)
1723
+ - `The unpdf installed would stop the whole server at the first PDF file on Node <n>, so PDF files are not read.`, followed by what to install: before Node 24 `Install unpdf 1.6.1 or later, or run Node 24 or later.`, on a later Node `Install unpdf 1.6.1 or later.` (an `unpdf` from 1.5.0 to 1.6.0, which loads a pdf.js that calls `Promise.try` where Node does not have it; new in 0.6.0. Until 0.9.0, Node 20 was told to install unpdf 1.7.0.)
1724
+ - An `unpdf` that cannot load its pdf.js fails with unpdf's own error. (Until 0.9.0, on Node 20, that error was wrapped as `The unpdf installed cannot read PDF files on Node 20 (<unpdf's message>). …`.)
1195
1725
  - `This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.`
1196
1726
  - `This PDF has no text layer (it may be scanned) and <n> pages. Without text it can only be read by looking at its pages, which works for up to <m> pages. It needs OCR first.`
1197
1727
  - `Reading DOCX, PPTX and XLSX files needs the optional dependency "jszip".` (until 0.8.0: `Reading DOCX and PPTX files …`)
@@ -1265,9 +1795,11 @@ else `"text"`. New in 0.8.1: with `bytes`, a file that would be `"text"` and is
1265
1795
  is known by its content: `"pdf"` when it starts with `%PDF-` (after a byte order mark or white
1266
1796
  space), `"docx"`, `"pptx"` or `"xlsx"` for a ZIP archive with the parts of one (`word/document.xml`,
1267
1797
  `ppt/presentation.xml`, `xl/workbook.xml`), `"html"` when it starts with `<!DOCTYPE html` or
1268
- `<html`. `ingest` passes the bytes: a DOCX uploaded without its extension was told "This file is a
1269
- ZIP archive". The MIME type is lowercased and compared whole, so `text/csv; charset=utf-8` names no
1270
- format. A name without a dot is looked up whole, so a file named `log` is a `log`. `ingest` uses it,
1798
+ `<html`. `ingest` passes the bytes (of a file at a path, since 0.9.0, the parts looked at: its
1799
+ first KB, and for a ZIP its first 64 KB and its last MB): a DOCX uploaded without its extension was
1800
+ told "This file is a ZIP archive". The MIME type is lowercased and compared whole, so
1801
+ `text/csv; charset=utf-8` names no format here; `ingest` drops the parameters first (0.9.0), so
1802
+ there it is a CSV. A name without a dot is looked up whole, so a file named `log` is a `log`. `ingest` uses it,
1271
1803
  then turns a `"text"` document that reads like a log into `"log"`.
1272
1804
 
1273
1805
  | Format | Extensions | MIME types |
@@ -1331,7 +1863,11 @@ its own, and the two quotes around it.
1331
1863
  ```ts
1332
1864
  type DocumentMeta = {
1333
1865
  id: string;
1866
+ metaVersion?: number; // new in 0.9.0
1334
1867
  owner?: string;
1868
+ scope?: string[]; // new in 0.9.0
1869
+ sha256?: string; // new in 0.9.0
1870
+ original?: { ref: string; bytes: number; sha256: string }; // new in 0.9.0
1335
1871
  name: string;
1336
1872
  mimeType: string;
1337
1873
  format: DocumentFormat;
@@ -1362,10 +1898,14 @@ browser instead.
1362
1898
 
1363
1899
  | Field | Type | What it holds |
1364
1900
  |---|---|---|
1365
- | `id` | `string` | `doc_` and 32 hexadecimal digits ([`DOCUMENT_ID_PATTERN`](#document_id_pattern)). |
1901
+ | `id` | `string` | `doc_` and 32 hexadecimal digits ([`DOCUMENT_ID_PATTERN`](#document_id_pattern)), or the ID the application gave (`IngestInput.id`, new in 0.9.0). |
1902
+ | `metaVersion` | `number \| undefined` | The version of this shape: [`DOCUMENT_META_VERSION`](#document_meta_version) (1) on documents ingested by 0.9.0 and later, absent on older ones. A higher one is refused. Never sent to the model. New in 0.9.0. |
1366
1903
  | `owner` | `string \| undefined` | The owner given at ingest. Absent when none was given. |
1904
+ | `scope` | `string[] \| undefined` | The scope given at ingest (`IngestInput.scope`), as a copy. Absent when none was given. Only a caller of the same scope may use the document. Never sent to the model, nor in a summary. An event holds it only with `eventResults: true`, in the full plan of `run.finish` and `run.error` ([events](./events.md#documents-eventresults-and-eventresult)). New in 0.9.0. |
1905
+ | `sha256` | `string \| undefined` | The SHA-256 of the uploaded file, as 64 lowercase hex digits. Always set by 0.9.0 and later, for bytes and for a path; absent on older documents. A kept copy in the store is checked against it when it is read back. The library does not look for documents of the same file: to give the user the document of a file already in a chat, compare it with those of the chat's documents in your records. Never sent to the model, nor in a summary. An event holds it only with `eventResults: true`, in the full plan of `run.finish` and `run.error` ([events](./events.md#documents-eventresults-and-eventresult)). New in 0.9.0. |
1906
+ | `original` | `{ ref, bytes, sha256 } \| undefined` | Where your application keeps the uploaded file (`IngestInput.original.ref`), with its size and SHA-256 at ingest, which each read is checked against. Set when the file is kept by its ref; absent for a copy in the store. The ref is never sent to the model, nor in a summary. An event holds it only with `eventResults: true`, in the full plan of `run.finish` and `run.error` ([events](./events.md#documents-eventresults-and-eventresult)). New in 0.9.0. |
1367
1907
  | `name` | `string` | The cleaned file name (see [`IngestInput`](#ingestinput)). |
1368
- | `mimeType` | `string` | The MIME type given, trimmed, or `"application/octet-stream"`. |
1908
+ | `mimeType` | `string` | The MIME type given, cleaned since 0.9.0 to a lowercased type/subtype without parameters (see [`IngestInput`](#ingestinput)), or `"application/octet-stream"`. |
1369
1909
  | `format` | [`DocumentFormat`](#documentformat) | The format. |
1370
1910
  | `bytes` | `number` | The size of the uploaded file. |
1371
1911
  | `textBytes` | `number` | The size of the extracted text in UTF-8. |
@@ -1377,7 +1917,7 @@ browser instead.
1377
1917
  | `pages` | `number \| undefined` | The pages of a PDF, the slides of a PPTX, the sheets of an XLSX, or what your extractor returned. |
1378
1918
  | `encoding` | `string \| undefined` | The older encoding a text file was read in, because it is not UTF-8, as `TextDecoder` names it: `"windows-1255"` for a Hebrew CSV that Excel saved, or `"windows-1256"`, `"windows-1251"`, `"shift_jis"`, `"windows-1252"`. Lines of it that are valid UTF-8 are read as UTF-8 all the same. Absent for valid UTF-8, for a file read as UTF-8 with characters that are not valid (see `replacedCharacters`), for UTF-16, for PDF, DOCX, PPTX and XLSX, and on documents from before 0.6.0. An HTML file is decoded as a text file is, and can have one. An extractor of your own may set another name ([`ExtractedText`](#extractedtext)). How the encoding is chosen: [Text encodings](../guides/pdfs.md#text-encodings). New in 0.6.0. |
1379
1919
  | `replacedCharacters` | `number \| undefined` | The characters of a text file that were not valid in the encoding it was read in (UTF-8, or `encoding`), such as a character cut in two at the end of a UTF-8 log, or a byte that `encoding` does not have: each is stored as U+FFFD (�). Absent when there were none, and on documents from before 0.6.0. New in 0.6.0. |
1380
- | `originalKept` | `boolean \| undefined` | `true` when the uploaded file is kept in the store (`keepOriginals`). Absent otherwise. Documents ingested before you turned `keepOriginals` on have no original. |
1920
+ | `originalKept` | `boolean \| undefined` | `true` when the uploaded file is kept (`keepOriginals`): in the store, or by its ref (`original`, 0.9.0). Absent otherwise. Documents ingested before you turned `keepOriginals` on have no original. |
1381
1921
  | `outline` | [`OutlineEntry[]`](#outlineentry) | The headings found in the text, at most 400. Empty for `log`, `json` and `csv`. |
1382
1922
  | `logProfile` | [`LogProfile`](#logprofile) or `undefined` | The log profile, for a `log` document only. |
1383
1923
  | `pagesWithoutText` | `number[]` or `undefined` | The pages of a PDF with no text at all (scans, photos, charts), up to 200. Absent when there are none, and on documents from before 0.8.1. The card names them, and points to `view_pages` when they can be looked at. New in 0.8.1. |
@@ -1516,20 +2056,24 @@ own `onActivity` instead.
1516
2056
  type ToolCallHooks = {
1517
2057
  onProgress?: ProgressListener;
1518
2058
  onRequest?: (request: ToolRequestStart) => ToolRequestHandle;
2059
+ onDocumentGone?: (documentId: string) => void; // new in 0.9.0
2060
+ onPagesBusy?: (documentId: string) => void; // new in 0.9.0
1519
2061
  };
1520
2062
  ```
1521
2063
 
1522
2064
  New in 0.7.0. Listeners for one tool call: the fourth argument of
1523
2065
  [`executeWithFiles`](./tools.md#toolset), next to its limits. With them, the progress and the model
1524
2066
  requests of two whole-file reads that run at once can be told apart. Only `analyze_whole_document`
1525
- calls them; the other tools ignore them. `askWithFiles` passes its own for each call, and turns
1526
- them into `tool.progress`, `request.start`, `retry` and `request.end` events
1527
- ([events in your own loop](./events.md#toolcallhooks)).
2067
+ calls `onProgress` and `onRequest`; the other tools ignore them. `askWithFiles` passes its own for
2068
+ each call, and turns them into `tool.progress`, `request.start`, `retry` and `request.end` events,
2069
+ and `"document_gone"` and `"page_looks_busy"` notices ([events in your own loop](./events.md#toolcallhooks)).
1528
2070
 
1529
2071
  | Field | Type | What it does |
1530
2072
  |---|---|---|
1531
2073
  | `onProgress` | [`ProgressListener`](#progresslistener), optional | Progress of this call, in place of `ToolOptions.onProgress` for it. Without it, the tool set's own listener is called. |
1532
2074
  | `onRequest` | `(request: ToolRequestStart) => ToolRequestHandle`, optional | Called as each model request of this call starts ([`ToolRequestStart`](#toolrequeststart)). Return a [`ToolRequestHandle`](#toolrequesthandle): the read tells it of each retry of that request, and once when the request ends. |
2075
+ | `onDocumentGone` | `(documentId: string) => void`, optional | Called by any tool when the document the call names is no longer in the store: deleted or expired since it was planned, or not readable by the caller, which looks the same. The model gets "‹id› is no longer available on the server. Ask the user to attach the file again." New in 0.9.0. |
2076
+ | `onPagesBusy` | `(documentId: string) => void`, optional | Called by `view_pages` when the look waited longer than `pageLookWaitMs` for its turn (`maxConcurrentPageLooks`) and was not run. New in 0.9.0. |
1533
2077
 
1534
2078
  Do not let them throw. The read takes a throw from `onRequest` or from a handle for a failure of
1535
2079
  that request: the part is reported as not read, and a merge or the answer falls back to the notes.