llm-large-files 0.8.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
@@ -10,15 +10,20 @@ 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
- LargeFilesOptions, LargeFiles, AccessOptions, IngestInput, PrepareOptions, ToolOptions, PreparedContext, DocumentPlan,
19
- Budget, ModelLimits, DocumentStore, StoredDocument, PdfExtractorOptions, Extractor, ExtractInput, ExtractProgress,
20
+ LargeFilesOptions, LargeFiles, CreatedLargeFiles, LargeFilesStats, AccessOptions, IngestInput, PrepareOptions, ToolOptions,
21
+ PreparedContext, ToolName, DocumentPlan,
22
+ Budget, ModelLimits, DocumentStore, DocumentContext, DocumentScope, StoredDocument, FileDocumentStoreOptions, FileDocumentScopes,
23
+ PdfExtractorOptions, Extractor, ExtractInput, ExtractProgress,
20
24
  ExtractedText, DocumentMeta, DocumentSummary, DocumentFormat, OutlineEntry, LogIssue, LogProfile, ProgressEvent,
21
25
  ProgressListener, ToolCallHooks, ToolRequestHandle, ToolRequestStart, ToolRequestEnd, IngestEvent, IngestErrorCode,
26
+ DocumentStoreOperation, DocumentScopeErrorCode,
22
27
  } from "llm-large-files";
23
28
  ```
24
29
 
@@ -28,20 +33,26 @@ from the same entry point.
28
33
  Contents:
29
34
 
30
35
  - [The library](#the-library): [`createLargeFiles(options)`](#createlargefilesoptions),
31
- [`LargeFilesOptions`](#largefilesoptions), [`LargeFiles`](#largefiles), [`IngestInput`](#ingestinput),
36
+ [`LargeFilesOptions`](#largefilesoptions), [`LargeFiles`](#largefiles), [`CreatedLargeFiles`](#createdlargefiles),
37
+ [`LargeFilesStats`](#largefilesstats), [`IngestInput`](#ingestinput),
32
38
  [`IngestError`](#ingesterror), [`ingestErrorCodeOf(message)`](#ingesterrorcodeofmessage),
33
39
  [`AccessOptions`](#accessoptions), [`PrepareOptions`](#prepareoptions), [`ToolOptions`](#tooloptions),
34
- [`PreparedContext`](#preparedcontext), [`DocumentPlan`](#documentplan),
35
- [`DEFAULT_CACHE_BYTES`](#default_cache_bytes), [`DEFAULT_WHOLE_DOCUMENT_BYTES`](#default_whole_document_bytes),
40
+ [`PreparedContext`](#preparedcontext), [`ToolName`](#toolname),
41
+ [`DocumentPlan`](#documentplan), [`DEFAULT_CACHE_BYTES`](#default_cache_bytes), [`DEFAULT_WHOLE_DOCUMENT_BYTES`](#default_whole_document_bytes),
36
42
  [`DEFAULT_MAX_PDF_PAGES`](#default_max_pdf_pages), [`DEFAULT_MAX_TEXT_BYTES`](#default_max_text_bytes),
37
43
  [`DEFAULT_INGEST_TIMEOUT_MS`](#default_ingest_timeout_ms),
38
44
  [`NEVER_EXPIRES`](#never_expires), [`isDocumentId(value)`](#isdocumentidvalue),
39
45
  [`toDocumentSummary(meta)`](#todocumentsummarymeta)
40
46
  - [The budget](#the-budget): [`Budget`](#budget), [`DEFAULT_BUDGET`](#default_budget),
41
47
  [`resolveBudget(budget?, limits?)`](#resolvebudgetbudget-limits), [`ModelLimits`](#modellimits)
42
- - [Stores](#stores): [`DocumentStore`](#documentstore), [`StoredDocument`](#storeddocument),
48
+ - [Stores](#stores): [`DocumentStore`](#documentstore), [`DocumentContext`](#documentcontext),
49
+ [`DocumentScope`](#documentscope), [`StoredDocument`](#storeddocument),
43
50
  [`MemoryDocumentStore`](#memorydocumentstore), [`FileDocumentStore`](#filedocumentstore),
44
- [`DOCUMENT_ID_PATTERN`](#document_id_pattern), [`DocumentStoreError`](#documentstoreerror)
51
+ [`FileDocumentStoreOptions`](#filedocumentstoreoptions), [`FileDocumentScopes`](#filedocumentscopes),
52
+ [`isSafeScopeSegment(value)`](#issafescopesegmentvalue), [`hashedScopeSegment(value)`](#hashedscopesegmentvalue),
53
+ [`DOCUMENT_ID_PATTERN`](#document_id_pattern), [`APP_DOCUMENT_ID_PATTERN`](#app_document_id_pattern),
54
+ [`DOCUMENT_META_VERSION`](#document_meta_version), [`DocumentStoreError`](#documentstoreerror),
55
+ [`DocumentScopeError`](#documentscopeerror)
45
56
  - [Extraction](#extraction): [`Extractor`](#extractor), [`ExtractInput`](#extractinput),
46
57
  [`ExtractProgress`](#extractprogress), [`ExtractedText`](#extractedtext), [`defaultExtractors`](#defaultextractors),
47
58
  [`createPdfExtractor(options?)`](#createpdfextractoroptions), [`PdfExtractorOptions`](#pdfextractoroptions),
@@ -66,7 +77,7 @@ model sees ([tools.md](./tools.md)), and the events of a question and of an inge
66
77
  ### createLargeFiles(options)
67
78
 
68
79
  ```ts
69
- declare function createLargeFiles(options: LargeFilesOptions): LargeFiles;
80
+ declare function createLargeFiles(options: LargeFilesOptions): CreatedLargeFiles; // LargeFiles before 0.10.0
70
81
  ```
71
82
 
72
83
  Creates the library over one store. Create it once per process and share it: it keeps the cache of
@@ -101,6 +112,7 @@ type LargeFilesOptions = {
101
112
  ingestTimeoutMs?: number;
102
113
  extractors?: Partial<Record<DocumentFormat, Extractor>>;
103
114
  keepOriginals?: DocumentFormat[];
115
+ originals?: OriginalsReader; // new in 0.9.0
104
116
  scannedPdfPages?: number;
105
117
  cacheBytes?: number;
106
118
  cacheSize?: number;
@@ -108,6 +120,13 @@ type LargeFilesOptions = {
108
120
  scanChunkBytes?: number;
109
121
  maxConcurrentScans?: number;
110
122
  maxConcurrentIngests?: number;
123
+ maxConcurrentPageLooks?: number; // new in 0.9.0
124
+ pageLookWaitMs?: number; // new in 0.9.0
125
+ requireOwner?: boolean; // new in 0.9.0
126
+ requireScope?: boolean; // new in 0.9.0
127
+ storeTimeoutMs?: number; // new in 0.10.0
128
+ maxStuckStoreCalls?: number; // new in 0.10.0
129
+ sweepTimeoutMs?: number; // new in 0.10.0
111
130
  now?: () => Date;
112
131
  };
113
132
  ```
@@ -120,34 +139,43 @@ type LargeFilesOptions = {
120
139
  | `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. |
121
140
  | `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. |
122
141
  | `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. |
123
- | `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 with `The store did not finish writing <name> within 2 min.`, as a failure of the store, and the document is removed once the write ends (new in 0.8.2). 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). |
142
+ | `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). |
124
143
  | `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. |
125
- | `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. |
126
- | `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`. |
144
+ | `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. |
145
+ | `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. |
146
+ | `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`. |
127
147
  | `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. |
128
148
  | `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. |
129
149
  | `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. |
130
150
  | `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. |
131
151
  | `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. |
132
152
  | `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. |
153
+ | `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. |
154
+ | `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. |
155
+ | `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. |
156
+ | `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. |
157
+ | `storeTimeoutMs` | `number` | 30,000 | The most time one store call may take, in milliseconds: `getMeta`, `get`, `readTextRange`, `getIndex` and `putIndex` when a document is opened, `getOriginal` (and `originals.read`), and `delete`. Past it, the call fails with a [`DocumentStoreError`](#documentstoreerror) of code `"ETIMEDOUT"` (status 503, `cause`: `The store did not answer within 30 s.`). The call itself goes on, since nothing can stop it, and counts as stuck until it ends (`maxStuckStoreCalls`). In a question, a tool call that meets it ends the question with `run.error`. `ingest` keeps its own limits (`ingestTimeoutMs`), past which its store calls count as stuck too, and `sweep` has `sweepTimeoutMs`. Keep it above your store's slowest healthy call, such as a `get` of a text of `wholeDocumentBytes`. 0 sets no limit, and so does a time past what a timer can wait. Before 0.10.0 a store call that never settled held its caller forever. New in 0.10.0. [Storage](../guides/storage.md#time-limits). |
158
+ | `maxStuckStoreCalls` | `number` | half of `UV_THREADPOOL_SIZE` (4 when it is not set), at least 1: 2 by default, 16 with 32 threads | While this many calls of the process are stuck (past their time limit, and not ended), every new store call of this library fails at once, without calling the store, with a `DocumentStoreError` of code `"STORE_STUCK"` (status 503): an `ingest` fails at its first store call (operation `"write"`, or `"read"` for the look-up of an application's ID). The removal of what an ingest wrote, once writes that began under the limit end (its caller left, or they failed), still runs. The count is the process's, shared by every library: store calls past `storeTimeoutMs`, whether their caller timed out or left, the store calls of `ingest` past the time it gives them (`ingestTimeoutMs`, 2 minutes when it is 0), and the upload handlers' calls to the disk past `uploadIdleTimeoutMs`. A call that ends within its limit never counts. `UV_THREADPOOL_SIZE` is read when the library is made, as libuv reads it: an empty value, 0, or one that does not start with digits is a pool of 1 thread, so a limit of 1. `Infinity` refuses nothing. New in 0.10.0. [Deployment](../guides/deployment.md#a-store-that-stops-answering). |
159
+ | `sweepTimeoutMs` | `number` | 0 (no limit) | The most time one `sweep` may take, in milliseconds. Past it, `sweep` fails with a `DocumentStoreError` of operation `"sweep"` and code `"ETIMEDOUT"`, and the sweep goes on. A sweep never counts as a stuck call; while `maxStuckStoreCalls` calls are stuck, it is refused at once, as other store calls are. New in 0.10.0. |
133
160
  | `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`. |
134
161
 
135
162
  Since 0.7.1, `ttlMs`, `maxUploadBytes`, `scannedPdfPages`, `cacheBytes`, `cacheSize`,
136
163
  `wholeDocumentBytes`, `scanChunkBytes` and `maxConcurrentScans` (and `maxConcurrentIngests`, new in
137
- 0.8.2) are checked when the library is
164
+ 0.8.2, and `maxConcurrentPageLooks` and `pageLookWaitMs`, new in 0.9.0) are checked when the library is
138
165
  made: NaN, which `Number(process.env.X)` gives for a variable that is not set, throws a
139
166
  `RangeError` ("maxConcurrentScans must be a number, and is NaN. Leave it out for the default."),
140
167
  a value that is not a number throws a `TypeError`, and so does `Infinity` for `scanChunkBytes`. NaN
141
168
  used to pass through: `maxConcurrentScans` left every scan of a document read by range waiting
142
169
  forever, `ttlMs` failed every upload, `maxUploadBytes` took off the upload limit. A number below
143
170
  the least an option takes is raised to it, as before. `maxTextBytes`, `maxPdfPages` and
144
- `ingestTimeoutMs` take NaN as left out, as they have since 0.6.0.
171
+ `ingestTimeoutMs` take NaN as left out, as they have since 0.6.0. `storeTimeoutMs`,
172
+ `maxStuckStoreCalls` and `sweepTimeoutMs`, new in 0.10.0, are checked as the options of 0.7.1 are.
145
173
 
146
174
  Guides: [storage](../guides/storage.md) for the store, owners and retention,
147
175
  [costs and limits](../guides/costs-and-limits.md) for the budget, [PDFs](../guides/pdfs.md) for
148
176
  `keepOriginals`, `scannedPdfPages`, `extractors` and the files the limits refuse,
149
177
  [security](../security.md#uploads) for `maxTextBytes`, `maxPdfPages` and `ingestTimeoutMs`, and
150
- [deployment](../guides/deployment.md) for the memory settings.
178
+ [deployment](../guides/deployment.md) for the memory settings and the looks at pages.
151
179
 
152
180
  ### `LargeFiles`
153
181
 
@@ -156,13 +184,16 @@ interface LargeFiles {
156
184
  readonly budget: Budget;
157
185
  budgetFor(overrides?: Partial<Budget>, limits?: ModelLimits): Budget;
158
186
  readonly maxUploadBytes: number;
159
- ingest(input: IngestInput): Promise<DocumentMeta>;
187
+ readonly access?: { readonly requireOwner: boolean; readonly requireScope: boolean }; // new in 0.9.0
188
+ ingest(input: IngestInput | IngestFromSource): Promise<DocumentMeta>; // IngestFromSource: new in 0.9.0
160
189
  getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
161
190
  getOriginal(id: string, access?: AccessOptions): Promise<Uint8Array | undefined>;
162
191
  delete(id: string, access?: AccessOptions): Promise<boolean>;
163
- sweep(): Promise<number>;
192
+ sweep(options?: { scope?: DocumentScope }): Promise<number>;
164
193
  prepare(ids: string[], base: { tokens: number; bytes: number }, options?: PrepareOptions): Promise<PreparedContext>;
165
194
  tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
195
+ stats?(): LargeFilesStats; // new in 0.10.0
196
+ toolsFor?(ids: string[], options: ToolOptions & { access: AccessOptions }): Promise<{ tools: ToolSet; missing: string[] }>; // new in 0.10.0
166
197
  }
167
198
  ```
168
199
 
@@ -170,22 +201,68 @@ The object `createLargeFiles` returns. Below, its members are shown on a `LargeF
170
201
 
171
202
  The members that read the store (`getMeta`, `getOriginal`, `delete` and `prepare`) throw
172
203
  [`DocumentStoreError`](#documentstoreerror) when the store cannot be read: retry, the document is
173
- not gone. A tool call that meets it answers the model with its message instead. What the store
174
- throws while writing (in `ingest`, the removal in `delete`, `sweep`) is passed on unchanged: log it,
175
- and do not show it to a user, since its message may name a path or a host.
204
+ not gone. A tool call that meets it answers the model with its message instead. Since 0.9.0, what
205
+ the store throws while writing is a `DocumentStoreError` too, with the store's own error as
206
+ `cause`: operation `"write"` in `ingest`, `"delete"` in `delete`, `"sweep"` in `sweep`. Before, it
207
+ was passed on unchanged. Log `error.cause`, and do not show it to a user, since its message may name
208
+ a path or a host. A [`DocumentScopeError`](#documentscopeerror) the store throws is passed on as it
209
+ is, for reads and writes alike: it is a mistake of the call, not a store to try again.
210
+
211
+ Every store call carries a [`DocumentContext`](#documentcontext), new in 0.9.0: the scope and the
212
+ owner of the call (of the document, at ingest). It is a frozen object, and a field that is absent is
213
+ left out, so a call without either gets `{}`. A document a store returns for another ID, or with
214
+ the owner `null` (as a MongoDB driver writes a field that was left out), is read as missing, or as
215
+ without an owner.
216
+
217
+ The members new in 0.10.0:
218
+
219
+ | Member | Type | What it is |
220
+ |---|---|---|
221
+ | `stats` | `() => LargeFilesStats`, optional | Counters for metrics and alerts ([`files.stats()`](#filesstats)), read without a store call. Optional, so that a `LargeFiles` of your own still compiles; the one `createLargeFiles` makes has it. New in 0.10.0. |
222
+ | `toolsFor` | `(ids: string[], options: ToolOptions & { access: AccessOptions }) => Promise<{ tools: ToolSet; missing: string[] }>`, optional | Looks each ID up for `options.access`, then makes the tools for the documents found; `missing` lists the others ([`files.toolsFor()`](#filestoolsforids-options)). Optional, as `stats` is. New in 0.10.0. |
176
223
 
177
- #### `files.ingest(input)`
224
+ #### `files.access`
178
225
 
179
- `ingest(input: IngestInput): Promise<DocumentMeta>`
226
+ `readonly access?: { readonly requireOwner: boolean; readonly requireScope: boolean }`
180
227
 
181
- Extracts the text of a file, normalizes it, profiles it, and stores it under a new ID. Returns the
182
- new document's [`DocumentMeta`](#documentmeta).
228
+ New in 0.9.0. What the library requires of every call: `requireOwner` and `requireScope` as they
229
+ were given, `false` when left out. The object is frozen. Code that serves a library, such as the
230
+ upload handlers, reads it to require an owner or a scope too. It is optional in the type, so a
231
+ `LargeFiles` of your own still compiles.
183
232
 
184
- 1. The owner is checked (see [`IngestInput`](#ingestinput)), the name is cleaned, and the format
185
- is picked by [`detectFormat(name, mimeType)`](#detectformatname-mimetype-bytes).
186
- 2. The extractor of that format turns the bytes into text. It receives the limits `maxTextBytes`
233
+ #### `files.ingest(input)`
234
+
235
+ `ingest(input: IngestInput | IngestFromSource): Promise<DocumentMeta>`
236
+
237
+ Extracts the text of a file, normalizes it, profiles it, and stores it under a new ID, or under the
238
+ ID the application gives (`input.id`, new in 0.9.0). Returns the new document's
239
+ [`DocumentMeta`](#documentmeta). The file is given as bytes ([`IngestInput`](#ingestinput)), or,
240
+ new in 0.9.0, as a path ([`IngestFromSource`](#ingestfromsource)), which is read when the ingest's
241
+ turn comes and not held while it waits. `IngestInput` keeps its required `bytes`: a `LargeFiles`
242
+ of your own whose `ingest` declares its parameter `(input: IngestInput)` still compiles, since
243
+ `ingest` is a method. A wrapper whose parameter type is inferred does not:
244
+ `{ ...files, ingest: (input) => … }` now gets `IngestInput | IngestFromSource`, where `bytes` may be
245
+ undefined. Annotate it `(input: IngestInput)`, or narrow it (`if (input.bytes)`, or
246
+ `"source" in input`) before it reads `bytes`.
247
+
248
+ 1. The owner, the scope and the ID are checked (see [`IngestInput`](#ingestinput)), the name and
249
+ the MIME type are cleaned, and the format is picked by
250
+ [`detectFormat(name, mimeType)`](#detectformatname-mimetype-bytes). A file at a path is looked
251
+ at with `lstat` first, and nothing of it is read before its turn but the parts that tell a
252
+ format, when its name and type say nothing. Those looks are given up on when `signal` is
253
+ aborted, and fail after `ingestTimeoutMs` (2 minutes when it is 0) when the volume does not answer.
254
+ With an `id`, the store is asked whether a document of that ID is there
255
+ ([`ifExists`](#ingestinput)), before the file is read. That question is given the same time
256
+ as the writes (`ingestTimeoutMs`), and an aborted `signal` stops waiting for it. An `id` that
257
+ another ingest of this library is storing is refused at once.
258
+ 2. At its turn, a file at a path is read once, at most `maxUploadBytes + 1` bytes, and the SHA-256
259
+ of the file is taken as it is read, a megabyte at a time (new in 0.9.0). The extractor of that
260
+ format turns the bytes into text: an extractor that reads paths (`readsPath`, as the isolated
261
+ readers do) reads the file itself instead. Bytes given are hashed, a megabyte at a time, once the
262
+ extractor is done with them, so the ingests of one turn reach it in the order they came. It receives the limits `maxTextBytes`
187
263
  and `maxPdfPages`, the ingest's signal, and, when someone listens to the ingest's events, an
188
- `onProgress` to report how far it is ([`ExtractInput`](#extractinput)). A text longer
264
+ `onProgress` to report how far it is ([`ExtractInput`](#extractinput)). The bytes read from a
265
+ path are let go as soon as the extractor returns, unless the store keeps a copy. A text longer
189
266
  than `maxTextBytes` is refused, whichever extractor made it. The extractor may say how the text
190
267
  was read ([`ExtractedText`](#extractedtext)): the built-in one reads a text file that is not
191
268
  valid UTF-8 in the older encoding its lines fit, when one does, and `encoding` and
@@ -208,16 +285,23 @@ new document's [`DocumentMeta`](#documentmeta).
208
285
  lines and at least 40% of its first 200 non-blank lines start with a timestamp or a log level
209
286
  (`ERROR`, `WARN`, `INFO`...), or have the shape of an access log of nginx or Apache, a JSON log
210
287
  line, klog or logfmt (since 0.8.0).
211
- 5. The store is written: the original file (when it is kept), then the line index (when the store
212
- has `putIndex`), then `put` last.
288
+ 5. The store is written: the original file (when the store keeps a copy of it), then the line
289
+ index (when the store has `putIndex`), then `put` last. A file kept by its ref
290
+ (`IngestInput.original`) is not written: the metadata records where it is. Each call carries the document's owner and scope. With an
291
+ `id`, the store is asked again just before, for a document stored under it meanwhile; one that
292
+ `ifExists: "replace"` replaces is deleted first.
213
293
 
214
294
  Steps 2 to 4 work in slices of about 12 ms, with a pause for other requests between two slices:
215
295
  between the pages of a PDF, as a DOCX, PPTX or XLSX is unpacked, and while the text is normalized,
216
296
  measured, outlined, profiled and indexed. Ingests that run at once take turns, one slice each.
217
297
  They run under one signal, aborted by `IngestInput.signal` or after `ingestTimeoutMs` (2 minutes
218
298
  by default). When it aborts, `ingest` stops waiting for the extractor, throws, and writes nothing
219
- to the store. The writes of step 5 are not under the signal. One page of a PDF is read without a
220
- pause, and the signal is looked at only between pages.
299
+ to the store. The writes of step 5 are not under the signal, and are not cut short. Since 0.9.0,
300
+ when `IngestInput.signal` has aborted by the time they end, or just before `ingest.finish`, what
301
+ they wrote is removed (only while it is still this ingest's own, as on a failed write, within
302
+ `ingestTimeoutMs`), and `ingest` throws `signal.reason`: a client that left during the write leaves
303
+ nothing behind. Before, the document stayed, for good under `ttlMs: Infinity`. One page of a PDF is
304
+ read without a pause, and the signal is looked at only between pages.
221
305
 
222
306
  **Events.** New in 0.7.0. With `IngestInput.onEvent`, the ingest tells what it does as typed
223
307
  [`IngestEvent`](./events.md#ingestevent)s, in order: `ingest.start` first (the cleaned name, the
@@ -232,41 +316,66 @@ write) ([stages and units](./events.md#stages-and-units)). A stage sends at most
232
316
  `ingest.progress` about every 12 ms, and its last one when it ends. An extractor of your own reports
233
317
  only what it passes to `onProgress`. The error of `ingest.error` is told in words for users, with
234
318
  the `code` of an [`IngestError`](#ingesterror) (new in 0.8.0): a store that failed to write is "The
235
- document could not be stored. Try again later.", whatever it threw, and the store's own error is the
236
- one `ingest` throws. A listener that throws ends the ingest with that error, and nothing is stored;
237
- a throw on `ingest.finish` removes the document that was just stored. `createDocumentHandlers` sends
319
+ document could not be stored. Try again later.", whatever it threw, with `name:
320
+ "DocumentStoreError"` and `status: 503` (new in 0.9.0), and `ingest` throws a
321
+ `DocumentStoreError` whose `cause` is the store's own error (new in 0.9.0: it threw the store's
322
+ error itself). A listener that throws ends the ingest with that error, and nothing is stored;
323
+ a throw on `ingest.finish` removes the document that was just stored. With an `id`, it is removed
324
+ only while it is still this ingest's own: one another server stored under the ID meanwhile stays. `createDocumentHandlers` sends
238
325
  these events to a client that asks for them with `Accept: text/event-stream` ([upload with
239
326
  progress](./node.md#upload-with-progress-accept-textevent-stream)).
240
327
 
241
328
  | It throws | When |
242
329
  |---|---|
243
330
  | `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. |
244
- | [`IngestError`](#ingesterror) `"empty"`: `<name> is empty.` | The file has no bytes. |
245
- | `IngestError` `"too_large"`: `<name> is larger than the 100 MB upload limit.` | The file is larger than `maxUploadBytes`. The message gives your limit. |
246
- | 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. |
331
+ | `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. |
332
+ | [`DocumentScopeError`](#documentscopeerror) `"scope_invalid"` | `scope` is not a valid [`DocumentScope`](#documentscope). Before anything is read. New in 0.9.0. |
333
+ | `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. |
334
+ | `TypeError('ifExists must be "fail" or "replace".')` | Another `ifExists`. New in 0.9.0. |
335
+ | `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. |
336
+ | `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. |
337
+ | `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. |
338
+ | 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, or (new in 0.10.0) the read at its 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. |
339
+ | [`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. |
340
+ | `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. |
341
+ | 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)). |
247
342
  | `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. |
248
343
  | `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. |
249
- | `signal.reason` | `IngestInput.signal` was aborted, before or during the ingest. |
344
+ | `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. |
250
345
  | `IngestError` `"no_text"`: `<name> did not contain any text.` | The extracted text is blank. |
251
346
  | 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. |
252
- | 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`. |
347
+ | [`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. |
348
+ | `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. |
253
349
 
254
350
  Until 0.8.0 the refusals were plain `Error`s, with the same messages. The `TypeError` of an owner is
255
351
  a mistake of the server's code, not of the file: the upload handler of
256
352
  [`llm-large-files/node`](./node.md) checks the owner itself, and answers `500` before it reads the
257
- body. The store's error, a listener of the events that threw, and the reason of an aborted signal
258
- are thrown as they are, never as an `IngestError`. The upload handler of
259
- [`llm-large-files/node`](./node.md) takes an error that carries an HTTP `status` or `statusCode`
260
- (400 to 599), or a Node system error (`code` and `syscall`), for the store's: it answers with that
261
- status, or with 500 and the code. An `IngestError` carries a `status` too, and is answered with it:
262
- 422, 413 for `"too_large"`, 503 with `Retry-After` for `"busy"`. `ingest` also keeps a mark of each
263
- error a store throws while it writes. The handler answers a marked error without a status or a code,
264
- and a thrown value that is not an `Error`, with 500 `{ "error": "Upload failed." }`, without its
265
- message. It answers any other `Error` with 422 and its message, as a file that cannot be read. The
266
- package does not export the mark: behind an `ingest` of your own that throws a new error, or in a
267
- route of your own, a store's error is answered as a file that cannot be read (see [the upload
268
- handler](./node.md#uploadrequest-response)). Give your store's write errors a `status` and a message
269
- of your own. See [errors and reliability](../guides/errors-and-reliability.md).
353
+ body. The store's `DocumentStoreError`, a listener of the events that threw, and the reason of an
354
+ aborted signal are thrown as they are, never as an `IngestError`.
355
+
356
+ The upload handler of [`llm-large-files/node`](./node.md) answers these errors by one rule ([how
357
+ errors are answered](./node.md#how-errors-are-answered)):
358
+
359
+ - Only an `IngestError` is answered 422. It carries its `status`: 422, 413 for `"too_large"`, 409
360
+ for `"exists"`, 503 with `Retry-After` for `"busy"`. Its message is the answer, except for code
361
+ `"unreadable"`, which gets fixed words: "This file could not be read. It may be damaged, or not
362
+ of the type its name says.".
363
+ - A `DocumentStoreError` is answered 503, with a message that names no path or host: since 0.9.0 a
364
+ store that failed to write is answered 503 `{ "error": "The document could not be stored (EIO).
365
+ Try again." }`, where it was a 500.
366
+ - An error that carries an HTTP `status` or `statusCode` (400 to 599) is answered with that status
367
+ and its message.
368
+ - A Node system error (`code` and `syscall`) is answered 500 `{ "error": "Upload failed (ENOENT)." }`,
369
+ with its code and not its message. Since 0.9.0, a code that does not read as one (capitals,
370
+ digits and `_`), such as a host a driver put there, is left out: "Upload failed.".
371
+ - Any other `Error`, and a value that is not an `Error`, is answered 500 `{ "error": "Upload
372
+ failed." }`, without its message. In this `ingest`, those are a `TypeError` of the call, the
373
+ reason of an aborted signal and the error of a listener. Before 0.9.0, any other `Error` was
374
+ answered 422 with its message, as a file that cannot be read (S12).
375
+
376
+ Behind an `ingest` of your own, throw an `IngestError` for a file you refuse, and a
377
+ `DocumentStoreError` for a store that failed. See
378
+ [errors and reliability](../guides/errors-and-reliability.md).
270
379
 
271
380
  Guides: [web app](../guides/web-app.md) for uploads, [PDFs](../guides/pdfs.md) for what PDF
272
381
  extraction writes.
@@ -275,23 +384,35 @@ extraction writes.
275
384
 
276
385
  `getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>`
277
386
 
278
- The document's metadata, or `undefined` when the ID does not match
279
- [`DOCUMENT_ID_PATTERN`](#document_id_pattern), the document was never there, was deleted, has
280
- expired (the library compares `expiresAt` with its clock itself, whatever the store returns), or
281
- belongs to another owner ([`AccessOptions`](#accessoptions)). Throws `DocumentStoreError` when the
282
- store cannot be read. A name that 0.5.0 or earlier stored cut inside an emoji comes back with a
283
- replacement character (U+FFFD) in place of the half, as the model and the steps get it; the stored
284
- metadata is not changed.
387
+ The document's metadata, or `undefined` when the ID has neither shape of a document ID
388
+ ([`isDocumentId`](#isdocumentidvalue)), the document was never there, was deleted, has expired (the
389
+ library compares `expiresAt` with its clock itself, whatever the store returns), or belongs to
390
+ another owner or another scope ([`AccessOptions`](#accessoptions)). The store is asked with the
391
+ caller's owner and scope. Metadata the store returns for another ID is missing too (new in 0.9.0).
392
+ An owner of `null` is left out of the metadata returned (new in 0.9.0). Throws `DocumentStoreError` when the
393
+ store cannot be read, and, new in 0.9.0, with code `"NEWER_VERSION"` when a newer version of the
394
+ package wrote the metadata ([`DOCUMENT_META_VERSION`](#document_meta_version)). A name that 0.5.0
395
+ or earlier stored cut inside an emoji comes back with a replacement character (U+FFFD) in place of
396
+ the half, as the model and the steps get it; the stored metadata is not changed. Since 0.10.0 a
397
+ store that does not answer within `storeTimeoutMs` is a `DocumentStoreError` of code `"ETIMEDOUT"`,
398
+ and `access.signal` ends the wait with its reason.
285
399
 
286
400
  #### `files.getOriginal(id, access?)`
287
401
 
288
402
  `getOriginal(id: string, access?: AccessOptions): Promise<Uint8Array | undefined>`
289
403
 
290
- The uploaded file, when it was kept (`keepOriginals`). `undefined` in every case where `getMeta`
291
- gives `undefined`, and when the document has no `originalKept`, the store has no `getOriginal`, or
292
- the store returns none. Treat the bytes as read-only: `MemoryDocumentStore` returns the very bytes
293
- it keeps, not a copy, so changing them changes the stored file.
294
- Throws `DocumentStoreError` when the store cannot be read.
404
+ The uploaded file, when it was kept (`keepOriginals`): from the store, or, for a document ingested
405
+ with `original` (new in 0.9.0), from where your application keeps it, through `originals`.
406
+ `undefined` in every case where `getMeta` gives `undefined`, and when the document has no
407
+ `originalKept`, the library cannot read it (no `getOriginal` in the store, or no `originals` for a
408
+ file kept by its ref), or none is there. Since 0.9.0 the store is asked for the metadata again once
409
+ the bytes are read: `undefined` too when the document is not the same by then (deleted, and another
410
+ stored under its ID, by another server), or when the bytes are not those of the file that was
411
+ ingested: not of its size (`meta.bytes`), or, when the metadata has `sha256`, not of its SHA-256,
412
+ so that a store that gives back other bytes of the same size is caught. `view_pages` reads the file
413
+ the same way. Treat the bytes as read-only: a store of
414
+ your own may return the bytes it keeps. `MemoryDocumentStore` returns a copy since 0.9.0; it returned the very bytes it kept.
415
+ Throws `DocumentStoreError` as `getMeta` does.
295
416
 
296
417
  #### `files.delete(id, access?)`
297
418
 
@@ -299,17 +420,30 @@ Throws `DocumentStoreError` when the store cannot be read.
299
420
 
300
421
  Removes a document, with its original and its index. It looks the document up as `getMeta` does,
301
422
  and returns `false` when it is not there for this caller: another owner's document is never
302
- deleted. Otherwise it drops what this process keeps of the document in memory and returns what
303
- `store.delete(id)` returns. Throws `DocumentStoreError` when the look-up cannot read the store; an
304
- error of `store.delete` itself is passed on unchanged.
305
-
306
- #### `files.sweep()`
307
-
308
- `sweep(): Promise<number>`
423
+ deleted. Otherwise it drops what this process keeps of the document in memory, in every scope,
424
+ and returns what `store.delete(id, context)` returns. Throws `DocumentStoreError` when the look-up
425
+ cannot read the store, and, new in 0.9.0, a `DocumentStoreError` of operation `"delete"` when
426
+ `store.delete` fails, with the store's error as `cause` (it was passed on unchanged). Its message
427
+ names no path: `The document could not be deleted (EPERM). Try again.` Since 0.10.0 a delete ends
428
+ within `storeTimeoutMs` in all: its look-up, its wait for its turn and the store's `delete` share
429
+ that time. The deletes of one library run one at a time: each waits for the one before it to end,
430
+ and fails with code `"ETIMEDOUT"` without calling the store when its time is up first; a
431
+ `store.delete` still running when it is up fails the same way and goes on alone, holding the turn
432
+ until it ends, and counts as stuck once it has itself run `storeTimeoutMs`. `access.signal` ends
433
+ the wait.
434
+
435
+ #### `files.sweep(options?)`
436
+
437
+ `sweep(options?: { scope?: DocumentScope }): Promise<number>`
309
438
 
310
439
  Calls the store's `sweep` with the library's clock and returns how many expired documents it
311
- removed: 0 when the store has no `sweep`. Errors of the store are passed on unchanged. The library
312
- never sweeps on its own: run it on a schedule, from one place (see [deployment](../guides/deployment.md)).
440
+ removed: 0 when the store has no `sweep`. With `scope` (new in 0.9.0), the store is asked to sweep
441
+ that scope only (`store.sweep(now, { scope })`); without one, every scope (`store.sweep(now, {})`).
442
+ It needs no scope under `requireScope`. A scope that is not valid is a `DocumentScopeError`. Since
443
+ 0.9.0 a store that fails is a `DocumentStoreError` of operation `"sweep"`, with the store's error as
444
+ `cause` (it was passed on unchanged). Since 0.10.0 `sweepTimeoutMs` bounds it (no limit by default),
445
+ and it never counts as a stuck call. The library never sweeps on its own: run it on a schedule,
446
+ from one place (see [deployment](../guides/deployment.md)).
313
447
 
314
448
  #### `files.prepare(ids, base, options?)`
315
449
 
@@ -322,7 +456,7 @@ model reads through the tools.
322
456
  |---|---|---|
323
457
  | `ids` | `string[]` | The document IDs of the request. A repeated ID counts once. |
324
458
  | `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. |
325
- | `options` | [`PrepareOptions`](#prepareoptions) | The owner, a budget for this request, whether your loop can show pages, and whether your tools have `analyze_whole_document`. |
459
+ | `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`. |
326
460
 
327
461
  Documents are taken smallest first, by `estimatedTokens`. Each one goes in whole when, with the
328
462
  ones already taken, it still fits both the token room,
@@ -368,13 +502,24 @@ answers with an error that lists the IDs it may use. Pass `prepared.plan.searcha
368
502
  set for each question: the time budget of regex searches and the count of whole-document reads
369
503
  belong to the tool set.
370
504
 
371
- It takes the owner from the metadata it is handed. Each call that reads a document's text or the
372
- pages of its PDF compares the owner stored with the document with the `owner` of the
373
- `DocumentMeta` given for that ID, and answers a document whose owners differ as it answers one
374
- that is gone: `doc_… is no longer available on the server. Ask the user to attach the file again.`
375
- So metadata built from an ID alone, or with another owner, reads nothing of a document that has an
376
- owner. A document stored without an owner is read whatever the metadata says. Pass documents that
377
- you got from `prepare` or `getMeta` with the caller's owner: they carry the stored owner.
505
+ Each call that reads a document's text or the pages of its PDF asks the store for the document,
506
+ and checks the owner and the scope the store holds. A document that the caller may not use is
507
+ answered as one that is gone: `doc_… is no longer available on the server. Ask the user to attach
508
+ the file again.`, and `view_pages` shows no page. A call that read a document by range asks the
509
+ store once more when it ends (new in 0.9.0): if the store no longer describes the same document, of
510
+ the same owner and scope, the call answers the same way, since what it read may be another's.
511
+
512
+ - With `access` (new in 0.9.0), the caller is `access`: the store is asked with its owner and scope,
513
+ and the document's are compared with them, as `getMeta(id, access)` does. The metadata handed in
514
+ decides nothing: metadata read from the store for another user reads nothing. `askWithFiles`
515
+ passes it. Under `requireOwner` or `requireScope`, `access` is required, with the owner or scope:
516
+ without it `tools` throws the `TypeError` of [`LargeFilesOptions`](#largefilesoptions).
517
+ - Without `access`, as before 0.9.0, the caller of each document is the `owner` and `scope` of the
518
+ `DocumentMeta` handed in for it. So metadata built from an ID alone, or with another owner or
519
+ scope, reads nothing of a document that has one. A document stored without an owner is read
520
+ whatever the metadata says. Pass documents that you got from `prepare` or `getMeta` with the
521
+ caller's owner and scope. An owner of `null` counts as none (new in 0.9.0: such a document was
522
+ missing for `getMeta`, and open to the tools).
378
523
 
379
524
  It declares `search_document`, `read_document` and `get_document_overview`;
380
525
  `analyze_whole_document` when `generate` is given and at least one document is small enough to be
@@ -384,6 +529,54 @@ tools, their arguments and their results are in [tools.md](./tools.md).
384
529
 
385
530
  Throws an `Error` for a `budget` that cannot work.
386
531
 
532
+ #### `files.stats()`
533
+
534
+ `stats(): LargeFilesStats`
535
+
536
+ New in 0.10.0. Counters of this library, for metrics and alerts: the ingests, scans and looks at
537
+ pages under way and waiting, what the cache keeps, and the calls of the process left stuck past
538
+ their time limit ([`LargeFilesStats`](#largefilesstats)). It reads counters only: no store call, no
539
+ wait, so a metrics endpoint or a readiness probe may call it as often as it likes. Each call gives
540
+ new objects.
541
+
542
+ ```ts
543
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
544
+
545
+ const files = createLargeFiles({ store: new FileDocumentStore("/mnt/documents", { scopes: { depth: 2 } }) });
546
+
547
+ // Every 15 seconds, to your metrics: an alert when stuckStoreCalls stays above 0.
548
+ setInterval(() => {
549
+ const { ingests, pageLooks, cache, stuckStoreCalls, maxStuckStoreCalls } = files.stats();
550
+ console.log(JSON.stringify({ ingestsWaiting: ingests.waiting, looksWaiting: pageLooks.waiting, cacheBytes: cache.bytes, stuckStoreCalls, maxStuckStoreCalls }));
551
+ }, 15_000).unref();
552
+ ```
553
+
554
+ [Deployment](../guides/deployment.md#a-store-that-stops-answering) has a readiness probe built on it.
555
+
556
+ #### `files.toolsFor(ids, options)`
557
+
558
+ `toolsFor(ids: string[], options: ToolOptions & { access: AccessOptions }): Promise<{ tools: ToolSet; missing: string[] }>`
559
+
560
+ New in 0.10.0. The tools of a loop of your own, for document IDs: each ID is looked up for
561
+ `options.access` as [`files.getMeta`](#filesgetmetaid-access) does, one at a time, then
562
+ [`files.tools`](#filestoolsdocuments-options) is called with the documents found and `options`, so
563
+ every call of the tools reads with the same owner and scope. `missing` lists the IDs not found, in
564
+ the order given: never there, deleted, expired, of another owner or of another scope, or not of an
565
+ ID's shape. A repeated ID counts once. `access` is required (a `TypeError` without it); under
566
+ `requireOwner` and `requireScope` it needs the owner and the scope. `access.signal`, or the tool
567
+ set's `signal`, ends the waits for the store. Throws `DocumentStoreError` as `getMeta` does.
568
+
569
+ ```ts
570
+ import type { LargeFiles } from "llm-large-files";
571
+
572
+ // The tools for the documents of one chat, in a loop of your own.
573
+ async function chatTools(files: LargeFiles & { toolsFor: NonNullable<LargeFiles["toolsFor"]> }, ids: string[], userId: string, chatId: string) {
574
+ const { tools, missing } = await files.toolsFor(ids, { access: { owner: userId, scope: [userId, chatId] } });
575
+ if (missing.length > 0) console.warn(`Not found for this chat: ${missing.join(", ")}`);
576
+ return tools;
577
+ }
578
+ ```
579
+
387
580
  #### `files.budget`
388
581
 
389
582
  `readonly budget: Budget`
@@ -409,6 +602,40 @@ Guide: [costs and limits](../guides/costs-and-limits.md).
409
602
 
410
603
  The upload limit in effect: `options.maxUploadBytes`, or 104,857,600 (100 MB).
411
604
 
605
+ ### `CreatedLargeFiles`
606
+
607
+ ```ts
608
+ type CreatedLargeFiles = LargeFiles & { stats(): LargeFilesStats; toolsFor: NonNullable<LargeFiles["toolsFor"]> };
609
+ ```
610
+
611
+ What `createLargeFiles` returns since 0.10.0: a [`LargeFiles`](#largefiles) whose `stats` and
612
+ `toolsFor` are always there, so `files.stats()` needs no `?.` under `strict`. It was `LargeFiles`
613
+ before. Code that types its library as `LargeFiles` still compiles, and calls `files.stats?.()`.
614
+
615
+ ### `LargeFilesStats`
616
+
617
+ ```ts
618
+ type LargeFilesStats = {
619
+ ingests: { active: number; waiting: number };
620
+ scans: { active: number; waiting: number };
621
+ pageLooks: { active: number; waiting: number };
622
+ cache: { bytes: number; entries: number; maxBytes: number };
623
+ stuckStoreCalls: number;
624
+ maxStuckStoreCalls: number;
625
+ };
626
+ ```
627
+
628
+ What `files.stats()` gives. New in 0.10.0.
629
+
630
+ | Field | Type | What it holds |
631
+ |---|---|---|
632
+ | `ingests` | `{ active: number; waiting: number }` | Ingests doing their work, and those waiting their turn (`maxConcurrentIngests`). |
633
+ | `scans` | `{ active: number; waiting: number }` | Scans of whole documents read by range, and those waiting their turn (`maxConcurrentScans`). |
634
+ | `pageLooks` | `{ active: number; waiting: number }` | Looks at pages, and those waiting their turn (`maxConcurrentPageLooks`). |
635
+ | `cache` | `{ bytes: number; entries: number; maxBytes: number }` | What is kept in memory: its bytes, by their own estimate; how many entries, the documents and the decoded pieces of documents read by range; and the most bytes they may take (`cacheBytes`). |
636
+ | `stuckStoreCalls` | `number` | Calls of this process that ran past their time limit and have not settled: the store calls of every library (past `storeTimeoutMs`, or for `ingest` past `ingestTimeoutMs`), and the upload handlers' calls to the disk (past `uploadIdleTimeoutMs`). The same for every library of the process. |
637
+ | `maxStuckStoreCalls` | `number` | This library's limit on them (`maxStuckStoreCalls`): at it, its store calls fail at once with `"STORE_STUCK"`. |
638
+
412
639
  ### `IngestInput`
413
640
 
414
641
  ```ts
@@ -420,6 +647,10 @@ type IngestInput = {
420
647
  signal?: AbortSignal;
421
648
  onEvent?: (event: IngestEvent) => void;
422
649
  runId?: string;
650
+ id?: string; // new in 0.9.0
651
+ ifExists?: "fail" | "replace"; // new in 0.9.0
652
+ scope?: DocumentScope; // new in 0.9.0
653
+ original?: { ref: string }; // new in 0.9.0
423
654
  };
424
655
  ```
425
656
 
@@ -428,15 +659,105 @@ The argument of [`files.ingest`](#filesingestinput).
428
659
  | Field | Type | Default | What it does |
429
660
  |---|---|---|---|
430
661
  | `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. |
431
- | `mimeType` | `string` | `"application/octet-stream"` | The MIME type, trimmed. Blank counts as absent. Used when the extension names no format. |
662
+ | `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. |
432
663
  | `bytes` | `Uint8Array` | required | The file. A Node `Buffer` is one. Empty, or larger than `maxUploadBytes`, is refused. |
433
664
  | `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. |
434
- | `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. |
665
+ | `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. |
435
666
  | `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. |
436
667
  | `runId` | `string` | `"ing_"` and 16 hex digits | The `runId` of those events. New in 0.7.0. |
668
+ | `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. |
669
+ | `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. |
670
+ | `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. |
671
+ | `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. |
437
672
 
438
673
  Guide: [web app](../guides/web-app.md).
439
674
 
675
+ ### `IngestFromSource`
676
+
677
+ ```ts
678
+ type IngestSource = { path: string };
679
+ type IngestFromSource = Omit<IngestInput, "bytes"> & { source: IngestSource; bytes?: never };
680
+ ```
681
+
682
+ New in 0.9.0. An ingest of a file at a path, rather than of bytes in memory: the fields of
683
+ [`IngestInput`](#ingestinput), with `source: { path }` in place of `bytes`. The file is read when
684
+ the ingest's turn comes (`maxConcurrentIngests`), so ingests that wait hold none of their bytes:
685
+ 100 ingests of 2 MB waiting for their turn held 73 MB of memory in all as paths, against 282 to
686
+ 286 MB with their bytes given ([Deployment](../guides/deployment.md#uploads-and-ingest)).
687
+
688
+ ```ts
689
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
690
+
691
+ const files = createLargeFiles({ store: new FileDocumentStore(process.env.DOCUMENTS_DIR!) });
692
+
693
+ // The file your upload route saved. The library reads it, and leaves it where it is.
694
+ export const meta = await files.ingest({ name: "report.pdf", source: { path: "/srv/uploads/3f9a.pdf" }, owner: "user-42" });
695
+ ```
696
+
697
+ - **Before its turn**, the path is looked at with `lstat`, and nothing of the file is read. A link
698
+ is refused, not followed (an error with code `"ELOOP"`), and so is a folder or anything that is
699
+ not a file. An empty file, or one larger than `maxUploadBytes`, is refused at once
700
+ (`IngestError` `"empty"`, `"too_large"`). `ingest.start` gives that size. The ingest's time
701
+ (`ingestTimeoutMs`) begins at its turn, but this look, and the reads for its format (below), are
702
+ not waited for past it either (2 minutes when it is 0): a volume that does not answer fails the
703
+ ingest with an error of code `"ETIMEDOUT"` and `syscall` `"lstat"` or `"read"`, which names no
704
+ path. A caller that aborts `signal` meanwhile gets its own reason at once.
705
+ - **Its format**: from its name and type, as for bytes. When they say nothing (no extension,
706
+ `application/octet-stream`), from its first KB, and for a ZIP from its first 64 KB and its last
707
+ MB, read for that alone: a DOCX without its extension is still a DOCX.
708
+ - **At its turn**, the file is read once, opened without following a link at its name (not on
709
+ Windows), and at most `maxUploadBytes + 1` bytes: a file that has grown past the limit since it
710
+ was looked at is refused as `"too_large"`. A read that does not end within `ingestTimeoutMs` fails
711
+ the ingest with an error of code `"ETIMEDOUT"` and `syscall` `"read"` (new in 0.10.0: it was the
712
+ `IngestError` `"timeout"` of a file that takes too long to read). Its SHA-256 is taken as it is read
713
+ (`DocumentMeta.sha256`), and `bytes` is the size read. The bytes are let go as soon as the
714
+ extractor returns, before the text is prepared, indexed and stored, unless the store keeps a copy
715
+ (`keepOriginals` without `original`).
716
+ - **An extractor that reads paths** (`Extractor.readsPath`, as those of
717
+ [`createIsolatedExtractors`](./node.md#createisolatedextractorsoptions) do) reads the file itself,
718
+ and the server reads none of it. When the store keeps a copy, the server reads it all the same,
719
+ and the extractor gets the bytes.
720
+ - **The library never writes, moves or deletes the file.** Remove it yourself when you no longer
721
+ need it, or keep it and give `original: { ref }` so that its pages can be shown without a copy in
722
+ the store.
723
+ - A path is a path on the server that ingests it. A relative path is made absolute once, against
724
+ the process's working folder when `ingest` is called: every read of the file, at its turn and in
725
+ the child process of an isolated reader, reads the file named then, even when the working folder
726
+ has changed since. The working folder and a separator are put before it, and nothing else
727
+ changes. An absolute path is used as it is. So a `..` after a link, and a `/` at the end, are
728
+ the system's to resolve, for a relative path and an absolute one alike, as
729
+ `fs.promises.realpath` (or `fs.realpathSync.native`) does. (`path.resolve`, `fs.realpath` and
730
+ `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
731
+ folder of a drive, goes through `path.resolve`. Never build it from what a client sends: the
732
+ library reads any file the process can read.
733
+
734
+ ### `OriginalsReader`
735
+
736
+ ```ts
737
+ type OriginalsReader = {
738
+ read(ref: string, context: OriginalReadContext): Promise<Uint8Array | undefined>;
739
+ };
740
+ type OriginalReadContext = DocumentContext & { readonly id: string; readonly bytes: number };
741
+ ```
742
+
743
+ New in 0.9.0. Reads the uploaded files your application keeps (`IngestInput.original`), for
744
+ `getOriginal` and `view_pages`: `LargeFilesOptions.originals`. `fileOriginals(root)` of
745
+ [`llm-large-files/node`](./node.md#fileoriginalsroot) is one, for files in a folder.
746
+
747
+ - `read` returns the bytes of the file at `ref`, or `undefined` when it is not there.
748
+ - `context` is the [`DocumentContext`](#documentcontext) of the call (the caller's scope and
749
+ owner), the document's `id`, and `bytes`, the size the file had at ingest. A reader may stop one
750
+ byte past `bytes`: a file of another size has changed. It is frozen.
751
+ - The library reads the ref the store holds, never one from metadata handed to it. Once the bytes
752
+ are read, it asks the store for the metadata again, as for a copy in the store, then compares the
753
+ bytes with the size and SHA-256 recorded at ingest. A file that differs has changed:
754
+ `getOriginal` gives `undefined`, and `view_pages` answers the model
755
+ `<file> changed on the server since it was read. Attach it again to look at its pages.`
756
+ - What `read` throws is passed on as a [`DocumentStoreError`](#documentstoreerror) of operation
757
+ `"read"`, with your error as `cause`, as a store's errors are.
758
+ - A look at pages holds its turn while it reads the file for at most `ingestTimeoutMs`, as it does
759
+ for a copy in the store (`maxConcurrentPageLooks`).
760
+
440
761
  ### `IngestError`
441
762
 
442
763
  ```ts
@@ -445,11 +766,13 @@ declare class IngestError extends Error {
445
766
  readonly status: number;
446
767
  readonly retryAfterMs?: number;
447
768
  constructor(code: IngestErrorCode, message: string, options?: { cause?: unknown; retryAfterMs?: number });
769
+ static is(value: unknown): value is IngestError; // new in 0.9.0
448
770
  }
449
771
 
450
772
  type IngestErrorCode =
451
773
  | "empty" | "too_large" | "too_much_text" | "too_many_pages" | "not_text" | "compressed" | "legacy_office"
452
- | "encrypted" | "no_text" | "hostile" | "timeout" | "out_of_memory" | "busy" | "missing_dependency" | "unreadable";
774
+ | "encrypted" | "no_text" | "hostile" | "timeout" | "out_of_memory" | "busy" | "missing_dependency" | "unreadable"
775
+ | "exists"; // new in 0.9.0
453
776
  ```
454
777
 
455
778
  New in 0.8.0. [`files.ingest`](#filesingestinput) could not read a file. The message says why, in
@@ -462,7 +785,7 @@ that it can tell the user in its own words or language. Until 0.8.0 the same ref
462
785
  | `name` | `string` | `"IngestError"`. |
463
786
  | `message` | `string` | The reason, written for a user: "app.log is empty.", "This PDF has no text layer (it may be scanned). …". |
464
787
  | `code` | `IngestErrorCode` | Why, as one of the codes below. |
465
- | `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. |
788
+ | `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. |
466
789
  | `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. |
467
790
  | `cause` | `unknown` | The error of the extractor, the parser or the isolated reader, when there is one. Its message is in `message`. |
468
791
 
@@ -483,6 +806,11 @@ that it can tell the user in its own words or language. Until 0.8.0 the same ref
483
806
  | `"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`). |
484
807
  | `"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. |
485
808
  | `"unreadable"` | Any other error of reading the file: it is damaged, or not of the type its name says. |
809
+ | `"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. |
810
+
811
+ `IngestError.is(value)` tells whether a value is one, also when another copy of the package made it,
812
+ where `instanceof` is `false` (see [errors](./errors-and-retries.md#telling-errors-apart-across-copies-of-the-package)).
813
+ New in 0.9.0.
486
814
 
487
815
  `ingest.error` events carry the code as [`EventError.code`](./events.md#errors-eventerror).
488
816
 
@@ -533,15 +861,22 @@ const error = new IngestError(ingestErrorCodeOf(message), message);
533
861
  ### `AccessOptions`
534
862
 
535
863
  ```ts
536
- type AccessOptions = { owner?: string };
864
+ type AccessOptions = {
865
+ owner?: string;
866
+ scope?: DocumentScope;
867
+ signal?: AbortSignal; // new in 0.10.0
868
+ };
537
869
  ```
538
870
 
539
871
  Who is asking. `getMeta`, `getOriginal`, `delete` and `prepare` (through
540
- [`PrepareOptions`](#prepareoptions)) take it, and so does `askWithFiles`.
872
+ [`PrepareOptions`](#prepareoptions)) take it, `tools` as `ToolOptions.access`, and `askWithFiles`
873
+ takes the same two options. Each store call carries both ([`DocumentContext`](#documentcontext)).
541
874
 
542
875
  | Field | Type | Default | What it does |
543
876
  |---|---|---|---|
544
- | `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. |
877
+ | `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. |
878
+ | `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. |
879
+ | `signal` | `AbortSignal` | none | Ends this caller's waits for the store, with the signal's reason, as it is: in `getMeta`, `getOriginal`, `delete`, `prepare`, `toolsFor`, and the calls of `tools` with `access`. Never a store call that other callers wait on too (one opening of a document serves every caller of its scope: the others go on waiting), and never the store call itself, which nothing can stop. A signal already aborted starts no store call. Not an `AbortSignal`: a `TypeError`. New in 0.10.0. |
545
880
 
546
881
  The library has no notion of a session and cannot list documents by owner: record the IDs in your
547
882
  own data. See [storage](../guides/storage.md) and [security](../security.md).
@@ -553,17 +888,30 @@ type PrepareOptions = AccessOptions & {
553
888
  budget?: Partial<Budget>;
554
889
  viewPages?: boolean;
555
890
  wholeDocumentAnalysis?: boolean;
891
+ numberInline?: boolean; // new in 0.10.0
892
+ inlineTables?: "tools" | "text"; // new in 0.10.0
556
893
  };
557
894
  ```
558
895
 
559
- The options of [`files.prepare`](#filesprepareids-base-options).
896
+ The options of [`files.prepare`](#filesprepareids-base-options). Without the two options new in
897
+ 0.10.0, `prepare` gives the plan, the blocks and the instruction of 0.9.
560
898
 
561
899
  | Option | Type | Default | What it does |
562
900
  |---|---|---|---|
563
901
  | `owner` | `string` | none | As in [`AccessOptions`](#accessoptions). Another owner's documents are listed in `missing` and are not read. |
902
+ | `scope` | [`DocumentScope`](#documentscope) | none | As in [`AccessOptions`](#accessoptions). Documents of another scope are listed in `missing`. New in 0.9.0. |
564
903
  | `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. |
565
904
  | `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`. |
566
905
  | `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`. |
906
+ | `numberInline` | `boolean` | `false` | Numbers the lines of each document sent whole, as the tools number them: `12| ` before each line, from 1, a line ending at each newline and none after the last. The document is planned by its numbered size, about 8% to 16% more tokens (see below), so a document at the edge of `inlineTokens` may become a card. `instruction` asks for line citations only when a file is searched: when none is, add `Cite line numbers like (report.docx L12).` after it. `plan.inlineTokens` and `plan.inlineBytes` are the numbered sizes. The frame lines do not change. A value that is not a boolean throws a `TypeError`. New in 0.10.0. |
907
+ | `inlineTables` | `"tools" \| "text"` | `"text"` | `"tools"`: `toolable` lists the documents sent whole whose tables the tools can count (see [`PreparedContext`](#preparedcontext)), and the block of each gives its document_id in its first frame line (`; document_id doc_…;`), for the tools. `instruction` does not say that they can be counted: add a line after it, such as the one `askWithFiles` adds, `Files shown in full can still be counted exactly: use aggregate_table for counts, sums and groups over their tables, and search_document exact for matching lines. In a spreadsheet, give the Row number when asked which row.` `"text"`: no `toolable`, and the blocks of 0.9. Another value throws a `TypeError`. New in 0.10.0. |
908
+
909
+ `numberInline` counts a document as `estimatedTokens` + 1.2 tokens a digit of its line numbers + 1.5
910
+ tokens a line, and its bytes as its JSON bytes + the digits + 4 a line: the formula of
911
+ `estimateParts`. That is 15.5% more tokens for a CSV of 3,000 short rows, 9.4% for a service log,
912
+ and 8.4% for Hebrew prose. It can count short: a line that starts with 16 spaces costs about 2
913
+ tokens more with its number. So `prepare` also measures the numbered text of each document it
914
+ sends whole, and plans again when that is larger: such a document is counted at its measured size.
567
915
 
568
916
  Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
569
917
 
@@ -571,6 +919,7 @@ Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
571
919
 
572
920
  ```ts
573
921
  type ToolOptions = {
922
+ access?: AccessOptions; // new in 0.9.0
574
923
  generate?: GenerateText;
575
924
  onProgress?: ProgressListener;
576
925
  signal?: AbortSignal;
@@ -579,6 +928,8 @@ type ToolOptions = {
579
928
  retry?: RetryOptions;
580
929
  budget?: Partial<Budget>;
581
930
  viewPages?: boolean | DocumentMeta[];
931
+ declare?: readonly ToolName[]; // new in 0.10.0
932
+ inline?: readonly string[]; // new in 0.10.0
582
933
  };
583
934
  ```
584
935
 
@@ -586,6 +937,7 @@ The options of [`files.tools`](#filestoolsdocuments-options).
586
937
 
587
938
  | Option | Type | Default | What it does |
588
939
  |---|---|---|---|
940
+ | `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. |
589
941
  | `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. |
590
942
  | `onProgress` | [`ProgressListener`](#progresslistener) | none | Progress of whole-document reads, for status messages. |
591
943
  | `signal` | `AbortSignal` | none | Stops searches and whole-document reads. Once it has aborted, a call that fails throws instead of answering `{ error }`. |
@@ -594,6 +946,8 @@ The options of [`files.tools`](#filestoolsdocuments-options).
594
946
  | `retry` | [`RetryOptions`](./errors-and-retries.md#retryoptions) | 3 retries, a first wait of 250 to 500 ms (500 ms before the jitter) that doubles, 60 s at most | How a failed model request of a whole-document read is sent again. An error without an HTTP status is sent again once, at once. |
595
947
  | `budget` | `Partial<Budget>` | the library's | The budget fields to change for these tools: their result cap and part size. Use the budget you planned the request with. |
596
948
  | `viewPages` | `boolean \| DocumentMeta[]` | none | Offers `view_pages`, which hands the model real pages of a PDF as a file. `true` offers it for the PDFs among `documents`; a list offers it for exactly those, which may include PDFs whose text is already in the prompt: pass `prepared.viewable`. Only PDFs with `originalKept` count, and only with a store that has `getOriginal`. Turn it on only when your loop runs tools with `executeWithFiles` and sends the files to the model. |
949
+ | `declare` | `readonly `[`ToolName`](#toolname)`[]` | none | Declare exactly these tools, in the order the tool set declares them (search, read, overview, aggregate, analyze, view). A declared tool that cannot run answers with its reason. New in 0.10.0. |
950
+ | `inline` | `readonly string[]` | none | The IDs of documents sent whole: `analyze_whole_document` refuses them, as they are shown in full, and `aggregate_table` says how to cite their lines (`cite`). New in 0.10.0. |
597
951
 
598
952
  Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
599
953
 
@@ -606,6 +960,7 @@ type PreparedContext = {
606
960
  instruction: string;
607
961
  missing: string[];
608
962
  viewable: DocumentMeta[];
963
+ toolable?: DocumentMeta[]; // new in 0.10.0
609
964
  };
610
965
  ```
611
966
 
@@ -618,6 +973,12 @@ What [`files.prepare`](#filesprepareids-base-options) returns.
618
973
  | `instruction` | `string` | The guide to the tools, for the system prompt, when a document is searchable or viewable; `""` otherwise. It names `analyze_whole_document` when a searchable file is small enough for it and `prepare` was not given `wholeDocumentAnalysis: false`. Then give `generate` to `tools`, or a call of it is answered as an unknown tool. |
619
974
  | `missing` | `string[]` | The IDs that were not found: never uploaded, not a document ID, deleted, expired, or another owner's. |
620
975
  | `viewable` | `DocumentMeta[]` | The PDFs whose pages `view_pages` can show, whether their text is in the prompt or searched. Empty unless `prepare` was called with `viewPages: true`. Pass it to `tools(..., { viewPages })`. |
976
+ | `toolable` | `DocumentMeta[]`, optional | With `inlineTables: "tools"`: the documents sent whole whose tables the tools can still count and search. A CSV or an XLSX workbook always; a DOCX, PPTX, PDF, HTML or Markdown file when its text has a table of at least 3 `\| cell \|` rows (a run of lines that start and end with `\|`, a `\| --- \|` separator not counted), as `aggregate_table` reads a table. Absent with `"text"`. Give them to `tools` with the searched documents, and declare for them `search_document`, `read_document` and `aggregate_table`. New in 0.10.0. |
977
+
978
+ `toolable` is optional, so that a `LargeFiles` of your own still compiles. With a `prepare` of your
979
+ own that gives the fields of 0.9 alone, `askWithFiles` works as in 0.9: no table sent whole gets the
980
+ tools, and the system text gets no citation line for the files sent whole. The one
981
+ `createLargeFiles` makes gives `toolable` with `inlineTables: "tools"`.
621
982
 
622
983
  A document sent whole sits between these two lines (new in 0.6.0, for every document):
623
984
 
@@ -627,6 +988,9 @@ A document sent whole sits between these two lines (new in 0.6.0, for every docu
627
988
  --- End attached file [mark <mark>] ---
628
989
  ```
629
990
 
991
+ With `numberInline` (new in 0.10.0), `<the text>` has its lines numbered as `read_document` shows
992
+ them: `1| first line`, `2| `, `3| third line`. The frame lines are the same.
993
+
630
994
  - `<mark>` is eight hex digits made from the document ID, the same in every request, so a
631
995
  provider's prompt cache reuses the file. After an upgrade from 0.5.0, the first request of each
632
996
  conversation reads nothing of the file from the cache, since the frame lines changed. The
@@ -651,7 +1015,8 @@ starts every frame.
651
1015
 
652
1016
  A card starts with `--- Large attached file: <name> ---`, as before. Its third line is
653
1017
  `<format> · <size> · <lines> lines · <pages> pages · about <tokens> tokens`, with `1 line` and
654
- `1 page` for one. For a text file that was not valid UTF-8, a line after the way to read it says
1018
+ `1 page` for one. A size that rounds to 1,024 KB reads `1 MB`, and a count that rounds to 1,000K
1019
+ reads `1.0M` (since 0.10.0; `1024 KB` and `1000K` before). For a text file that was not valid UTF-8, a line after the way to read it says
655
1020
  `This file is not in UTF-8. Its text was read as windows-1255: if its letters look wrong, ask the user to save it as UTF-8.`,
656
1021
  followed, when some characters were not valid in it, by
657
1022
  ` 3 characters of it were not valid in windows-1255, and show as �.`; or, for a file read as UTF-8,
@@ -661,6 +1026,14 @@ followed, when some characters were not valid in it, by
661
1026
 
662
1027
  Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
663
1028
 
1029
+ ### `ToolName`
1030
+
1031
+ ```ts
1032
+ type ToolName = "search_document" | "read_document" | "get_document_overview" | "analyze_whole_document" | "view_pages" | "aggregate_table";
1033
+ ```
1034
+
1035
+ The name of a document tool, as the model calls it ([`TOOL_NAMES`](./tools.md#tool_names)). New in 0.10.0.
1036
+
664
1037
  ### `DocumentPlan`
665
1038
 
666
1039
  ```ts
@@ -733,9 +1106,11 @@ reads it as any other.
733
1106
  declare function isDocumentId(value: unknown): value is string;
734
1107
  ```
735
1108
 
736
- `true` for a string that matches [`DOCUMENT_ID_PATTERN`](#document_id_pattern). Use it to check IDs
737
- that come from a browser. The library's own methods already treat any other string as a missing
738
- document.
1109
+ `true` for a string that has the shape of a document ID: one `ingest` makes
1110
+ ([`DOCUMENT_ID_PATTERN`](#document_id_pattern)), or, since 0.9.0, one an application gives
1111
+ ([`APP_DOCUMENT_ID_PATTERN`](#app_document_id_pattern), which the made ones match too). Use it to
1112
+ check IDs that come from a browser. The library's own methods already treat any other string as a
1113
+ missing document.
739
1114
 
740
1115
  ### toDocumentSummary(meta)
741
1116
 
@@ -846,16 +1221,16 @@ it. `askWithFiles` builds it from what its adapters declare in
846
1221
 
847
1222
  ```ts
848
1223
  interface DocumentStore {
849
- put(document: StoredDocument): Promise<void>;
850
- get(id: string): Promise<StoredDocument | undefined>;
851
- getMeta(id: string): Promise<DocumentMeta | undefined>;
852
- delete(id: string): Promise<boolean>;
853
- sweep?(now?: Date): Promise<number>;
854
- putOriginal?(id: string, bytes: Uint8Array): Promise<void>;
855
- getOriginal?(id: string): Promise<Uint8Array | undefined>;
856
- readTextRange?(id: string, start: number, end: number): Promise<Uint8Array | undefined>;
857
- putIndex?(id: string, index: Uint8Array): Promise<void>;
858
- getIndex?(id: string): Promise<Uint8Array | undefined>;
1224
+ put(document: StoredDocument, context?: DocumentContext): Promise<void>;
1225
+ get(id: string, context?: DocumentContext): Promise<StoredDocument | undefined>;
1226
+ getMeta(id: string, context?: DocumentContext): Promise<DocumentMeta | undefined>;
1227
+ delete(id: string, context?: DocumentContext): Promise<boolean>;
1228
+ sweep?(now?: Date, context?: DocumentContext): Promise<number>;
1229
+ putOriginal?(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void>;
1230
+ getOriginal?(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
1231
+ readTextRange?(id: string, start: number, end: number, context?: DocumentContext): Promise<Uint8Array | undefined>;
1232
+ putIndex?(id: string, index: Uint8Array, context?: DocumentContext): Promise<void>;
1233
+ getIndex?(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
859
1234
  }
860
1235
  ```
861
1236
 
@@ -863,15 +1238,22 @@ Where the extracted text lives, with its metadata, and optionally the uploaded f
863
1238
  index. Use [`MemoryDocumentStore`](#memorydocumentstore) or [`FileDocumentStore`](#filedocumentstore),
864
1239
  or implement it over a database, Redis or S3.
865
1240
 
1241
+ Every method takes a last, optional `context` ([`DocumentContext`](#documentcontext)): the scope
1242
+ and the owner of the call. New in 0.9.0. A store written for 0.8, whose methods take no context,
1243
+ still compiles and works: TypeScript lets a method with fewer parameters implement one with more.
1244
+ A store that wraps another one, or a subclass that overrides a method, passes the context on:
1245
+ `super.getMeta(id, context)`, `(id, context) => inner.getMeta(id, context)`. Without `context.scope`,
1246
+ `sweep` removes the expired documents of every scope; with one, only those of that scope.
1247
+
866
1248
  | Method | Required | What it must do, and when the library calls it |
867
1249
  |---|---|---|
868
1250
  | `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. |
869
1251
  | `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`. |
870
- | `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. |
871
- | `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. |
1252
+ | `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). |
1253
+ | `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. |
872
1254
  | `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. |
873
1255
  | `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. |
874
- | `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. |
1256
+ | `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. |
875
1257
  | `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. |
876
1258
  | `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. |
877
1259
  | `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. |
@@ -883,17 +1265,70 @@ Errors:
883
1265
  `readTextRange` and `getOriginal` throw reaches the caller as
884
1266
  [`DocumentStoreError`](#documentstoreerror), so that it retries instead of telling a user that the
885
1267
  file is gone. A `DocumentStoreError` you throw yourself is passed on as it is.
886
- - What `put`, `putOriginal` and `putIndex` throw at ingest is thrown by `ingest` unchanged, after it
887
- calls `delete(id)`. What `delete` and `sweep` throw is passed on unchanged.
1268
+ - What `put`, `putOriginal` and `putIndex` throw at ingest reaches the caller as a
1269
+ `DocumentStoreError` of operation `"write"`, after `ingest` calls `delete(id)`; what `delete` and
1270
+ `sweep` throw, as one of operation `"delete"` or `"sweep"`. Your error is `cause`. Before 0.9.0
1271
+ they were passed on unchanged.
1272
+ - Throw a [`DocumentScopeError`](#documentscopeerror) for a scope your store cannot keep, or a call
1273
+ without one when your store needs one.
1274
+ - Keep fields of `meta` you do not know, `metaVersion` included
1275
+ ([`DOCUMENT_META_VERSION`](#document_meta_version)): a newer version of the package may add some.
888
1276
  - The library compares `expiresAt` with its clock itself, so an expired document is never used. The
889
- store must still remove it, in `sweep` or by its own expiry.
890
-
891
- The library makes the IDs (see [`DOCUMENT_ID_PATTERN`](#document_id_pattern)), and every method
892
- except `put` receives only the ID: no owner, no metadata. A store that lays documents out per user
893
- or per chat session needs its own way from an ID to a place.
1277
+ store must still remove it, in `sweep` or by its own expiry. A store that removes an expired
1278
+ document when it reads it returns `undefined` even when that removal fails: an error there would
1279
+ reach the user as "try again" for a document that is gone.
1280
+ - [`documentStoreChecks`](./testing.md#documentstorechecksoptions) from `llm-large-files/testing`
1281
+ checks a store against these rules, in your tests.
1282
+
1283
+ The library makes the IDs (see [`DOCUMENT_ID_PATTERN`](#document_id_pattern)), or the application
1284
+ gives them ([`APP_DOCUMENT_ID_PATTERN`](#app_document_id_pattern)), and every method except `put`
1285
+ receives only the ID and the context: no metadata. A store that lays documents out per user or per
1286
+ chat session finds the place from `context.scope`. A store that ignores the context still works:
1287
+ the library keeps scopes apart through `meta.scope`, and an application's IDs must then be unique
1288
+ in the whole store.
894
1289
 
895
1290
  Guide: [storage](../guides/storage.md), which also shows a store of your own.
896
1291
 
1292
+ ### `DocumentContext`
1293
+
1294
+ ```ts
1295
+ type DocumentContext = { readonly scope?: DocumentScope; readonly owner?: string };
1296
+ ```
1297
+
1298
+ New in 0.9.0. Who a store call is for: the last argument of every [`DocumentStore`](#documentstore)
1299
+ method. A store may keep the documents of each scope apart, as `MemoryDocumentStore` does. It keeps
1300
+ at most one document of an ID in a scope: the owner says who may use a document, not where it is.
1301
+ The library always passes one, frozen, with the fields that are absent left out: `{}` for a call
1302
+ without a scope or an owner. Which one:
1303
+
1304
+ - At ingest, every call carries the document's owner and scope.
1305
+ - `getMeta`, `getOriginal` and `delete` carry the caller's (`AccessOptions`), or for `tools` without
1306
+ `access`, those of the metadata handed in.
1307
+ - The reads of a document's text (`get`, `readTextRange`, `getIndex`, and `putIndex` when its index
1308
+ is built again) carry the caller's scope and the document's owner, once the library has checked
1309
+ that the caller may use it. The scope is where `getMeta` found the document, even when its metadata
1310
+ has none. The library keeps one copy of a document for every caller of a scope, so these reads
1311
+ carry the same context whoever's call made them. For a document without an owner, they have no
1312
+ owner, whoever asked.
1313
+ - `sweep` gets the scope only.
1314
+
1315
+ | Field | Type | What it holds |
1316
+ |---|---|---|
1317
+ | `scope` | [`DocumentScope`](#documentscope) or `undefined` | Where the document belongs, such as `[userId, chatId]`. |
1318
+ | `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. |
1319
+
1320
+ ### `DocumentScope`
1321
+
1322
+ ```ts
1323
+ type DocumentScope = readonly string[];
1324
+ ```
1325
+
1326
+ New in 0.9.0. Where a document belongs, from the widest part to the narrowest: `[userId, chatId]`.
1327
+ A scope has 1 to 8 segments. Each segment has 1 to 256 characters (UTF-16 units), holds no control
1328
+ character, no `/` and no `\`, and is not `.` or `..`. A scope that breaks these rules is refused with
1329
+ a [`DocumentScopeError`](#documentscopeerror) of code `"scope_invalid"`. Segments are compared
1330
+ exactly: `"Alice"` and `"alice"` are two scopes.
1331
+
897
1332
  ### `StoredDocument`
898
1333
 
899
1334
  ```ts
@@ -912,13 +1347,13 @@ What a store keeps for a document, and what `put` receives and `get` returns.
912
1347
  ```ts
913
1348
  declare class MemoryDocumentStore implements DocumentStore {
914
1349
  constructor(options?: { now?: () => Date });
915
- put(document: StoredDocument): Promise<void>;
916
- get(id: string): Promise<StoredDocument | undefined>;
917
- getMeta(id: string): Promise<DocumentMeta | undefined>;
918
- delete(id: string): Promise<boolean>;
919
- sweep(now?: Date): Promise<number>;
920
- putOriginal(id: string, bytes: Uint8Array): Promise<void>;
921
- getOriginal(id: string): Promise<Uint8Array | undefined>;
1350
+ put(document: StoredDocument, context?: DocumentContext): Promise<void>;
1351
+ get(id: string, context?: DocumentContext): Promise<StoredDocument | undefined>;
1352
+ getMeta(id: string, context?: DocumentContext): Promise<DocumentMeta | undefined>;
1353
+ delete(id: string, context?: DocumentContext): Promise<boolean>;
1354
+ sweep(now?: Date, context?: DocumentContext): Promise<number>;
1355
+ putOriginal(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void>;
1356
+ getOriginal(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
922
1357
  }
923
1358
  ```
924
1359
 
@@ -929,8 +1364,14 @@ one-process demos. They are lost on restart and not shared between processes. It
929
1364
  bytes, so the caller may reuse its buffer. The metadata is copied too, on the way in (`put`) and
930
1365
  on the way out (`get`, `getMeta`), as a store that writes it somewhere does: changing the metadata
931
1366
  that `ingest` or `getMeta` returned (deleting its `owner` before it goes to a browser, say) changes
932
- nothing stored. Until 0.6.0 it handed out its own object. `getOriginal` returns the kept bytes
933
- themselves: treat them as read-only.
1367
+ nothing stored. Until 0.6.0 it handed out its own object. `getOriginal` returns a copy of the kept
1368
+ bytes too, since 0.9.0: until then it returned the bytes themselves.
1369
+
1370
+ The documents of each scope (`context.scope`) are kept apart, new in 0.9.0: one ID in two scopes is
1371
+ two documents, and a call with one scope never sees the documents of another. Calls without a
1372
+ scope share the documents of no scope, as every call did before. `sweep` without a scope removes
1373
+ the expired documents of every scope. A scope that is not valid is a
1374
+ [`DocumentScopeError`](#documentscopeerror).
934
1375
 
935
1376
  | Option | Type | Default | What it does |
936
1377
  |---|---|---|---|
@@ -942,23 +1383,25 @@ Guide: [testing](../guides/testing.md).
942
1383
 
943
1384
  ```ts
944
1385
  declare class FileDocumentStore implements DocumentStore {
945
- constructor(directory: string, options?: { now?: () => Date; orphanAgeMs?: number });
946
- put(document: StoredDocument): Promise<void>;
947
- get(id: string): Promise<StoredDocument | undefined>;
948
- getMeta(id: string): Promise<DocumentMeta | undefined>;
949
- delete(id: string): Promise<boolean>;
950
- sweep(now?: Date): Promise<number>;
951
- putOriginal(id: string, bytes: Uint8Array): Promise<void>;
952
- getOriginal(id: string): Promise<Uint8Array | undefined>;
953
- readTextRange(id: string, start: number, end: number): Promise<Uint8Array | undefined>;
954
- putIndex(id: string, index: Uint8Array): Promise<void>;
955
- getIndex(id: string): Promise<Uint8Array | undefined>;
1386
+ constructor(directory: string, options?: FileDocumentStoreOptions);
1387
+ put(document: StoredDocument, context?: DocumentContext): Promise<void>;
1388
+ get(id: string, context?: DocumentContext): Promise<StoredDocument | undefined>;
1389
+ getMeta(id: string, context?: DocumentContext): Promise<DocumentMeta | undefined>;
1390
+ delete(id: string, context?: DocumentContext): Promise<boolean>;
1391
+ sweep(now?: Date, context?: DocumentContext): Promise<number>;
1392
+ putOriginal(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void>;
1393
+ getOriginal(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
1394
+ readTextRange(id: string, start: number, end: number, context?: DocumentContext): Promise<Uint8Array | undefined>;
1395
+ putIndex(id: string, index: Uint8Array, context?: DocumentContext): Promise<void>;
1396
+ getIndex(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
956
1397
  }
957
1398
  ```
958
1399
 
959
1400
  Keeps each document as files in one directory, so documents survive a restart, and several servers
960
1401
  can share the directory on a network volume. It has every method, `readTextRange`, `putIndex` and
961
- `getIndex` included, so large documents are read by range.
1402
+ `getIndex` included, so large documents are read by range. With `scopes` (new in 0.9.0), the
1403
+ documents of each scope are in a folder of their own:
1404
+ `<directory>/<userId>/<chatId>/.llm-large-files/`.
962
1405
 
963
1406
  | File | What it holds |
964
1407
  |---|---|
@@ -967,33 +1410,170 @@ can share the directory on a network volume. It has every method, `readTextRange
967
1410
  | `<id>.idx` | The line index. |
968
1411
  | `<id>.bin` | The uploaded file, when it is kept. |
969
1412
 
970
- - The directory is created at the first write.
1413
+ - The files are in `directory` itself, without `scopes`. A call's context is then not used: a scope
1414
+ is only an access rule of the library (`meta.scope`). With `scopes`, they are in
1415
+ `<directory>/<scope segments>/<scopes.folder>/` ([`FileDocumentScopes`](#filedocumentscopes)).
1416
+ - The names `<id>.json`, `<id>.txt`, `<id>.idx` and `<id>.bin`, and their temporary files, belong
1417
+ to the store for every ID it is given. Where files of your own may sit (`directory` without
1418
+ `scopes`, or `scopes.folder` `""`), an ingest writes over your file of such a name, and `delete`
1419
+ or `ifExists: "replace"` removes it. Keep your own files in a subfolder, or under other names.
1420
+ - The directory is created at the first write, as are its own folders in the folder of each scope.
1421
+ Since 0.9.0, it writes files with `fileMode` (0o600) and makes folders with `directoryMode`
1422
+ (0o700), minus the umask of the process. Files and folders written before keep their modes.
971
1423
  - Every file is written under a temporary name (`<file>.<8 hex digits>.tmp`) and then renamed, so
972
- no server reads half a file. A rename that meets `EPERM`, `EACCES` or `EBUSY` (on Windows, another
973
- process has the file open for a moment) is tried again, for about 2.6 seconds in all.
974
- - `put` writes the text, then the metadata. `put`, `putOriginal` and `putIndex` throw
975
- `Error("Invalid document ID.")` for an ID that does not match `DOCUMENT_ID_PATTERN`; for such an
976
- ID the reads return `undefined` and `delete` returns `false`. Only matching IDs reach the file system.
1424
+ no server reads half a file. A rename or a removal that meets `EPERM`, `EACCES` or `EBUSY` (on
1425
+ Windows, another process has the file open for a moment) is tried again ten more times, with
1426
+ pauses of 2,630 ms in all: about 2.6 seconds. Removals are tried again since 0.9.0.
1427
+ - File names are document IDs. Since 0.9.0 an ID may be an application's
1428
+ ([`APP_DOCUMENT_ID_PATTERN`](#app_document_id_pattern)), which leaves out the names Windows keeps
1429
+ for devices (`con`, `prn`, `aux`, `nul`, `com0` to `com9`, `lpt0` to `lpt9`). `put`, `putOriginal` and
1430
+ `putIndex` throw `Error("Invalid document ID.")` for another ID; for such an ID the reads return
1431
+ `undefined` and `delete` returns `false`. The IDs the library makes keep their names, so a server
1432
+ of 0.8 still reads them. A server of 0.8 does not read documents under an application's ID.
1433
+ - `put` writes the text, then the metadata.
977
1434
  - `getMeta` returns `undefined` when the metadata file is missing or cannot be parsed (damaged, or
978
- being written by a server of 0.3.x), and removes an expired document and returns `undefined`.
1435
+ being written by a server of 0.3.x). It removes an expired document, as far as it can, and
1436
+ returns `undefined`: since 0.9.0 also when the removal fails, which `sweep` then tries again.
979
1437
  `get`, `readTextRange` and `getOriginal` return `undefined` for a missing file. Any other failure
980
1438
  of a read is thrown. `getIndex` returns `undefined` for any failure.
981
- - `delete` removes the metadata first, then the text, the index and the original, and returns
982
- whether the metadata existed. When the metadata cannot be removed, nothing else is, and the
983
- document stays whole.
1439
+ - Since 0.9.0, a read does not follow a link at a file name (`O_NOFOLLOW`): a document file that is
1440
+ a link counts as missing. Windows has no such flag, so there a link at a file name is followed;
1441
+ links in the folders of a scope are refused on every platform (`"scope_invalid"`).
1442
+ - `delete` removes the metadata first. When that fails, it throws, and nothing else is removed: the
1443
+ document stays whole. Then it removes the text, the index and the original, and returns whether
1444
+ it removed the metadata itself. Since 0.9.0, a part that cannot be removed then is left for
1445
+ `sweep`, and `delete` still returns `true`: the document is gone once its metadata is. Since
1446
+ 0.10.0 the metadata is first renamed to a name of the call's own (`<id>.json.<8 hex>.tmp`), and
1447
+ that name is then removed: of two deletes of one document at once, on one server or two, only
1448
+ one returns `true`, on Windows too. The rename keeps the time the metadata was written, so
1449
+ `sweep` reads the age of such a name from its last change (ctime), which the rename sets: a sweep
1450
+ on another server meanwhile leaves it to the delete.
984
1451
  - `sweep(now?)` removes expired documents and returns how many, counting a document whose metadata
985
- is not valid and is older than `orphanAgeMs`. It also removes files that belong to no document,
986
- and temporary files, once they are older than `orphanAgeMs` (these are not counted). A document
987
- whose metadata could not be read at all, or that could not be removed, is left for the next
988
- sweep. When the directory cannot be read, it returns 0.
1452
+ is not valid and is older than `orphanAgeMs`. It counts only the documents whose metadata it
1453
+ removed itself, as `delete` does: of two sweeps at once, on one server or two, each document is
1454
+ counted once (since 0.9.0; on Windows too since 0.10.0). It also
1455
+ removes files that belong to no document, and temporary files, once they are older than
1456
+ `orphanAgeMs` (these are not counted). Where files
1457
+ of your own may sit beside the documents (`directory` without `scopes`, or `scopes.folder` `""`),
1458
+ a file of no document is removed only when its name is an ID the library makes, or a temporary
1459
+ file: `notes.txt` may be yours, not the text of a document `notes`. A document whose metadata
1460
+ could not be read at all, or that could not be removed, is left for the next sweep. A folder that
1461
+ cannot be read counts as empty.
1462
+ - `sweep` runs its reads of metadata, its listings and its checks of a file's age
1463
+ `sweepConcurrency` at a time (16), since 0.9.0. Until then it read one file after another.
1464
+ - With `scopes`, `sweep(now, { scope })` sweeps the folder of that scope. `sweep(now)`, or with a
1465
+ context without a scope (as `files.sweep()` calls it), sweeps every scope: it goes down exactly
1466
+ `scopes.depth` levels of folders, enters only folders whose names pass
1467
+ [`isSafeScopeSegment`](#issafescopesegmentvalue) (so never `<chat>/uploads`), follows no link,
1468
+ and sweeps the store's folder in each. With `unscoped: "root"`, it sweeps `directory` itself too.
989
1469
 
990
1470
  | Option | Type | Default | What it does |
991
1471
  |---|---|---|---|
992
1472
  | `now` | `() => Date` | `() => new Date()` | The clock that decides expiry, and the default `now` of `sweep`. |
993
1473
  | `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. |
1474
+ | `scopes` | [`FileDocumentScopes`](#filedocumentscopes) | None | Keep the documents of each scope in a folder of their own. New in 0.9.0. |
1475
+ | `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. |
1476
+ | `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. |
1477
+ | `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. |
1478
+
1479
+ The constructor throws a `TypeError` for an option that is not valid: a `depth` outside 1 to 8, a
1480
+ `folder` that is not one folder's name, a mode outside 0 to 0o777, a `sweepConcurrency` below 1.
994
1481
 
995
1482
  Guides: [storage](../guides/storage.md), [deployment](../guides/deployment.md).
996
1483
 
1484
+ ### `FileDocumentStoreOptions`
1485
+
1486
+ ```ts
1487
+ type FileDocumentStoreOptions = {
1488
+ now?: () => Date;
1489
+ orphanAgeMs?: number;
1490
+ scopes?: FileDocumentScopes; // new in 0.9.0
1491
+ fileMode?: number; // new in 0.9.0, default 0o600
1492
+ directoryMode?: number; // new in 0.9.0, default 0o700
1493
+ sweepConcurrency?: number; // new in 0.9.0, default 16
1494
+ };
1495
+ ```
1496
+
1497
+ The options of [`FileDocumentStore`](#filedocumentstore), described there. New in 0.9.0 as a named
1498
+ type.
1499
+
1500
+ ### `FileDocumentScopes`
1501
+
1502
+ ```ts
1503
+ type FileDocumentScopes = {
1504
+ depth: number;
1505
+ folder?: string; // default ".llm-large-files"
1506
+ createScopeFolders?: boolean; // default false
1507
+ unscoped?: "refuse" | "root"; // default "refuse"
1508
+ };
1509
+ ```
1510
+
1511
+ New in 0.9.0. How a [`FileDocumentStore`](#filedocumentstore) keeps the documents of each scope in
1512
+ a folder of their own: `<directory>/<segment 1>/…/<segment depth>/<folder>/<id>.json`.
1513
+
1514
+ | Field | Default | What it does |
1515
+ |---|---|---|
1516
+ | `depth` | Required | How many segments every scope has, from 1 to 8: 2 for `[userId, chatId]`. |
1517
+ | `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. |
1518
+ | `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. |
1519
+ | `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. |
1520
+
1521
+ What a call's scope must be, or the call throws a [`DocumentScopeError`](#documentscopeerror)
1522
+ whose message names no segment:
1523
+
1524
+ | Code | When |
1525
+ |---|---|
1526
+ | `"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`. |
1527
+ | `"scope_required"` | The call has no scope, under `unscoped: "refuse"`. `sweep` without one sweeps every scope instead. |
1528
+ | `"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`. |
1529
+
1530
+ - Segments are lowercase only because SMB and Azure Files ignore case: `Alice` and `alice` would
1531
+ be one folder. Pass [`hashedScopeSegment(value)`](#hashedscopesegmentvalue) as the segment for an
1532
+ ID in mixed case or in Hebrew, at ingest and on every later call.
1533
+ - A call checks the real path of its scope's folder (`realpath`). A read takes a folder that passed
1534
+ the check less than a second ago as checked; the store remembers up to 4,096 such folders. A
1535
+ write, a `delete` and a `sweep` with a scope check again every time, and so does the first read
1536
+ after a read that found no file. A read of a scope with no folder costs that one look. Swapping a
1537
+ chat's folder for a link is therefore seen by reads within a second, and by writes at once.
1538
+ - A wrapper or a subclass that does not pass the context on gets `"scope_required"` on every call:
1539
+ pass it on ([Writing a store of your own](../guides/storage.md#writing-a-store-of-your-own)).
1540
+
1541
+ ### isSafeScopeSegment(value)
1542
+
1543
+ ```ts
1544
+ declare function isSafeScopeSegment(value: string): boolean;
1545
+ ```
1546
+
1547
+ New in 0.9.0. Whether a [`FileDocumentStore`](#filedocumentstore) with `scopes` takes `value` as a
1548
+ segment of a scope, that is, as the name of a folder: lowercase letters, digits, `_` and `-`, 1 to
1549
+ 64 characters, starting with a letter or a digit, and not a name Windows keeps for a device
1550
+ (`con`, `prn`, `aux`, `nul`, `com0` to `com9`, `lpt0` to `lpt9`): the shape of
1551
+ [`APP_DOCUMENT_ID_PATTERN`](#app_document_id_pattern). UUIDs and MongoDB ObjectIds in lowercase
1552
+ hex pass it as they are.
1553
+
1554
+ ### hashedScopeSegment(value)
1555
+
1556
+ ```ts
1557
+ declare function hashedScopeSegment(value: string): string;
1558
+ ```
1559
+
1560
+ New in 0.9.0. A segment that [`isSafeScopeSegment`](#issafescopesegmentvalue) accepts, made from any
1561
+ string that is not empty: `h` and the first 40 hexadecimal digits of the SHA-256 of its UTF-8.
1562
+ The same value always gives the same segment. Use it for an ID in mixed case, or in Hebrew, and
1563
+ for every ID of that level of the scope, not only those that would not pass. The store never hashes
1564
+ on its own: pass the result as the segment, at ingest and on every later call, and use it to name
1565
+ the folders you make and remove. `meta.scope` holds what you passed. Throws a `TypeError` for a
1566
+ value that is not a string, or is empty.
1567
+
1568
+ ```ts
1569
+ import { FileDocumentStore, hashedScopeSegment } from "llm-large-files";
1570
+
1571
+ export const store = new FileDocumentStore(process.env.DOCUMENTS_DIR!, { scopes: { depth: 2 } });
1572
+
1573
+ // User IDs in mixed case ("Alice@Example.com"); chat IDs are lowercase UUIDs, which pass as they are.
1574
+ export const scopeOf = (userId: string, chatId: string) => [hashedScopeSegment(userId), chatId];
1575
+ ```
1576
+
997
1577
  ### `DOCUMENT_ID_PATTERN`
998
1578
 
999
1579
  ```ts
@@ -1001,33 +1581,74 @@ declare const DOCUMENT_ID_PATTERN: RegExp; // /^doc_[a-f0-9]{32}$/
1001
1581
  ```
1002
1582
 
1003
1583
  The shape of every document ID that `ingest` makes: `doc_` and 32 lowercase hexadecimal digits
1004
- (a random UUID without its dashes). [`isDocumentId`](#isdocumentidvalue) tests a value against it.
1584
+ (a random UUID without its dashes), when the application gives none (`IngestInput.id`).
1585
+
1586
+ ### `APP_DOCUMENT_ID_PATTERN`
1587
+
1588
+ ```ts
1589
+ 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}$/
1590
+ ```
1591
+
1592
+ New in 0.9.0. The shape of a document ID an application chooses (`IngestInput.id`): lowercase
1593
+ letters, digits, `_` and `-`, up to 64 characters, starting with a letter or a digit. It does not
1594
+ match a name Windows keeps for a device (`con`, `prn`, `aux`, `nul`, `com0` to `com9`, `lpt0` to
1595
+ `lpt9`), since `con.json` is not a file there. Longer names, such as `console` or `com10`, match.
1596
+ `ingest` refuses an `id` that does not match with a `TypeError`, before it calls the store. The IDs
1597
+ `ingest` makes have the shape too. [`isDocumentId`](#isdocumentidvalue) tests a value against it.
1598
+
1599
+ ### `DOCUMENT_META_VERSION`
1600
+
1601
+ ```ts
1602
+ declare const DOCUMENT_META_VERSION: 1;
1603
+ ```
1604
+
1605
+ New in 0.9.0. The version of [`DocumentMeta`](#documentmeta) this version of the package writes, as
1606
+ `metaVersion`, and the highest it reads. Metadata without `metaVersion` (or with `null`) was
1607
+ written before 0.9.0, and is read as before. Metadata with a higher one was written by a newer
1608
+ version: `getMeta`, `getOriginal`, `delete`, `prepare`, `askWithFiles` and the tools refuse it
1609
+ with a [`DocumentStoreError`](#documentstoreerror) of code `"NEWER_VERSION"`, not as a missing
1610
+ document, so that an application does not ingest the file again over newer data. This happens
1611
+ while servers of two versions share a store: let the call be tried again on a newer one.
1005
1612
 
1006
1613
  ### `DocumentStoreError`
1007
1614
 
1008
1615
  ```ts
1616
+ type DocumentStoreOperation = "read" | "write" | "delete" | "sweep";
1617
+
1009
1618
  declare class DocumentStoreError extends Error {
1010
1619
  readonly code?: string;
1011
1620
  readonly syscall?: string;
1012
- constructor(cause: unknown);
1621
+ readonly operation: DocumentStoreOperation; // new in 0.9.0
1622
+ readonly status: 503; // new in 0.9.0
1623
+ constructor(cause: unknown, options?: { operation?: DocumentStoreOperation; code?: string });
1624
+ static is(value: unknown): value is DocumentStoreError; // new in 0.9.0
1013
1625
  }
1014
1626
  ```
1015
1627
 
1016
- The store could not be read just now: a volume that did not answer, too many open files, a database
1017
- that is down. It does not mean that the document is gone, and the same call may work a moment
1018
- later: retry it, rather than ask the user to upload the file again.
1628
+ The store failed just now: a volume that did not answer, too many open files, a database that is
1629
+ down. It does not mean that the document is gone, and the same call may work a moment later: retry
1630
+ it, rather than ask the user to upload the file again.
1019
1631
 
1020
1632
  | Field | Type | What it holds |
1021
1633
  |---|---|---|
1022
1634
  | `name` | `string` | `"DocumentStoreError"`. |
1023
- | `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. |
1024
- | `code` | `string \| undefined` | The code of the system error behind it (`EIO`, `EMFILE`, `ETIMEDOUT`), when there is one. |
1635
+ | `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. |
1636
+ | `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)); since 0.10.0, `"ETIMEDOUT"` for a store call that did not end within `storeTimeoutMs` (or `sweepTimeoutMs`), and `"STORE_STUCK"` for one refused at once because `maxStuckStoreCalls` calls of the process are stuck. |
1025
1637
  | `syscall` | `string \| undefined` | The system call that failed (`open`, `read`), when there is one. |
1638
+ | `operation` | `"read" \| "write" \| "delete" \| "sweep"` | What the store was doing. `"read"` unless it was made with another. New in 0.9.0. |
1639
+ | `status` | `503` | The HTTP status to answer with. New in 0.9.0. |
1026
1640
  | `cause` | `unknown` | What the store threw. Log it on the server; it may name a path or a host. |
1027
1641
 
1642
+ `DocumentStoreError.is(value)` tells whether a value is one, also when another copy of the package
1643
+ made it (two versions installed side by side, or one in a bundle), where `instanceof` is `false`.
1644
+ New in 0.9.0.
1645
+
1028
1646
  `files.getMeta`, `files.getOriginal`, `files.delete` (its look-up) and `files.prepare` throw it,
1029
1647
  and so does `askWithFiles`. A tool call that meets it answers the model with its message instead of
1030
- throwing. Errors of writes are never wrapped in it (see [`DocumentStore`](#documentstore)).
1648
+ throwing. Since 0.9.0 the library also wraps the errors of writes in it: `files.ingest` (operation
1649
+ `"write"`, and code `"ETIMEDOUT"` for a write that did not end in time), `files.delete`
1650
+ (`"delete"`) and `files.sweep` (`"sweep"`). Until then they were passed on unchanged (see
1651
+ [`DocumentStore`](#documentstore)). A `DocumentScopeError` is never wrapped.
1031
1652
 
1032
1653
  ```ts
1033
1654
  import { DocumentStoreError, toDocumentSummary, type LargeFiles } from "llm-large-files";
@@ -1038,27 +1659,66 @@ async function documentSummary(files: LargeFiles, id: string, owner: string) {
1038
1659
  const meta = await files.getMeta(id, { owner });
1039
1660
  return meta ? { status: 200, body: toDocumentSummary(meta) } : { status: 404, body: { error: "Not found." } };
1040
1661
  } catch (error) {
1041
- if (!(error instanceof DocumentStoreError)) throw error;
1662
+ if (!DocumentStoreError.is(error)) throw error;
1042
1663
  console.error(error.cause); // what the store threw: for your log only
1043
- return { status: 503, body: { error: error.message } };
1664
+ return { status: error.status, body: { error: error.message } };
1044
1665
  }
1045
1666
  }
1046
1667
  ```
1047
1668
 
1048
1669
  Guide: [errors and reliability](../guides/errors-and-reliability.md).
1049
1670
 
1671
+ ### `DocumentScopeError`
1672
+
1673
+ ```ts
1674
+ type DocumentScopeErrorCode = "scope_required" | "scope_invalid" | "scope_missing";
1675
+
1676
+ declare class DocumentScopeError extends TypeError {
1677
+ readonly code: DocumentScopeErrorCode;
1678
+ constructor(code: DocumentScopeErrorCode, message?: string, options?: { cause?: unknown });
1679
+ static is(value: unknown): value is DocumentScopeError;
1680
+ }
1681
+ ```
1682
+
1683
+ New in 0.9.0. A scope ([`DocumentScope`](#documentscope)) that cannot be used. It is a mistake in
1684
+ the call, not a failure of the store: the same call fails again, so do not retry it. The library
1685
+ passes it on as it is. Its message never repeats a segment of the scope, which may be a user's ID.
1686
+
1687
+ | Code | When | Message, unless another is given |
1688
+ |---|---|---|
1689
+ | `"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 "..".` |
1690
+ | `"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].` |
1691
+ | `"scope_missing"` | The store keeps the scope in a place that is gone (the chat was deleted). | `The scope no longer exists.` |
1692
+
1693
+ `DocumentScopeError.is(value)` works across copies of the package, as `DocumentStoreError.is` does.
1694
+
1050
1695
  ## Extraction
1051
1696
 
1052
1697
  ### `Extractor`
1053
1698
 
1054
1699
  ```ts
1055
- type Extractor = (bytes: Uint8Array, input: ExtractInput) => Promise<ExtractedText>;
1700
+ type Extractor = ((bytes: Uint8Array, input: ExtractInput) => Promise<ExtractedText>) & { readsPath?: boolean };
1056
1701
  ```
1057
1702
 
1058
1703
  Turns the bytes of an uploaded file into text, for one format. To refuse a file, throw an `Error`
1059
1704
  whose message a user can read: `ingest` throws it as an [`IngestError`](#ingesterror) with the same
1060
1705
  message, the code its message gives (`"unreadable"` for words the library does not know), and your
1061
- error as `cause`. Throw an `IngestError` yourself to choose the code. The library then normalizes the
1706
+ error as `cause`. Throw an `IngestError` yourself to choose the code.
1707
+
1708
+ The upload handlers ([`createDocumentHandlers`](./node.md#createdocumenthandlersfiles-options)),
1709
+ [`uploadAnswerOf`](./node.md#uploadansweroferror) and
1710
+ [`errorInfoOf`](./errors-and-retries.md#errorinfooferror) do not show the message of code
1711
+ `"unreadable"`: since 0.9.0 they answer "This file could not be read. It may be damaged, or not of
1712
+ the type its name says.", since that message is most often a parser's, and may name a host. Your
1713
+ message stays on the error, for your log. To have your own words shown:
1714
+
1715
+ - Throw an `IngestError` with the code that fits: `new IngestError("no_text", "scan.pdf has no text
1716
+ layer. Run OCR on it first.")`. The handlers answer it 422 with your message, and `errorInfoOf`
1717
+ gives it as its `message`.
1718
+ - Or throw an `Error` with a `status` from 400 to 599: the handlers answer with that status and your
1719
+ message. `errorInfoOf` reads such an error as a model's, though, and does not show its words.
1720
+
1721
+ The library then normalizes the
1062
1722
  text, splits long lines and refuses blank text, as described under
1063
1723
  [`files.ingest`](#filesingestinput). For a PDF, write a line `--- Page N ---` before the text of
1064
1724
  each page, counting from 1, as the built-in one does: the page numbers in tool results and
@@ -1077,6 +1737,17 @@ const text: Extractor = async (bytes, input) => {
1077
1737
  const files = createLargeFiles({ store: new MemoryDocumentStore(), extractors: { text } });
1078
1738
  ```
1079
1739
 
1740
+ `readsPath`, new in 0.9.0: the extractor reads a file ingested from a path
1741
+ ([`IngestFromSource`](#ingestfromsource)) itself, so the server does not read it first. It is then
1742
+ given empty bytes and `ExtractInput.path` (always absolute) and `maxUploadBytes`: read the file once, at most
1743
+ `maxUploadBytes + 1` bytes, refuse it past `maxUploadBytes` with the library's message
1744
+ (`<name> is larger than the 100 MB upload limit.`), never write, move or delete it, and return its
1745
+ size and SHA-256 in `ExtractedText.file`. Without `file`, `ingest` reads the file once more to hash
1746
+ it, a megabyte at a time, holding none of it. When the store keeps a copy of the file, the
1747
+ extractor gets the bytes as before. The extractors of
1748
+ [`createIsolatedExtractors`](./node.md#createisolatedextractorsoptions) set it. A plain function
1749
+ is an extractor that does not read paths, as before.
1750
+
1080
1751
  Guide: [PDFs](../guides/pdfs.md), for OCR and other PDF extractors.
1081
1752
 
1082
1753
  ### `ExtractInput`
@@ -1091,19 +1762,23 @@ type ExtractInput = {
1091
1762
  maxTextBytes?: number;
1092
1763
  maxPages?: number;
1093
1764
  onProgress?: (progress: ExtractProgress) => void;
1765
+ path?: string; // new in 0.9.0
1766
+ maxUploadBytes?: number; // new in 0.9.0
1094
1767
  };
1095
1768
  ```
1096
1769
 
1097
1770
  | Field | Type | What it holds |
1098
1771
  |---|---|---|
1099
1772
  | `name` | `string` | The cleaned file name (see [`IngestInput`](#ingestinput)). |
1100
- | `mimeType` | `string` | The MIME type, `"application/octet-stream"` when none was given. |
1773
+ | `mimeType` | `string` | The MIME type, cleaned (see [`IngestInput`](#ingestinput)): `"application/octet-stream"` when none was given. |
1101
1774
  | `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. |
1102
- | `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. |
1775
+ | `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. |
1103
1776
  | `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()`. |
1104
1777
  | `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. |
1105
1778
  | `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. |
1106
1779
  | `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. |
1780
+ | `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. |
1781
+ | `maxUploadBytes` | `number \| undefined` | Set with `path`: `LargeFilesOptions.maxUploadBytes`, the most bytes the file may have. New in 0.9.0. |
1107
1782
 
1108
1783
  ### `ExtractProgress`
1109
1784
 
@@ -1152,7 +1827,14 @@ const files = createLargeFiles({ store: new MemoryDocumentStore(), extractors: {
1152
1827
  ### `ExtractedText`
1153
1828
 
1154
1829
  ```ts
1155
- type ExtractedText = { text: string; pages?: number; encoding?: string; replacedCharacters?: number };
1830
+ type ExtractedText = {
1831
+ text: string;
1832
+ pages?: number;
1833
+ encoding?: string;
1834
+ replacedCharacters?: number;
1835
+ file?: { bytes: number; sha256: string }; // new in 0.9.0
1836
+ headings?: Array<{ page: number; level: number; title: string; skip?: number }>; // new in 0.10.0
1837
+ };
1156
1838
  ```
1157
1839
 
1158
1840
  | Field | Type | What it holds |
@@ -1161,6 +1843,8 @@ type ExtractedText = { text: string; pages?: number; encoding?: string; replaced
1161
1843
  | `pages` | `number \| undefined` | The number of pages (the slides of a PPTX, the sheets of an XLSX), stored as `DocumentMeta.pages`. |
1162
1844
  | `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. |
1163
1845
  | `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. |
1846
+ | `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. |
1847
+ | `headings` | `{ page, level, title, skip? }[] \| undefined` | A PDF's headings, found from the size of its type: each line set larger than the body, with its page (from 1), its level (1 is the top) and its text as pdf.js gives it (the words of right-to-left text can run together), in the order of the text; and `skip`, when lines above it on its page read the same (a contents list, a running header), how many. The built-in PDF extractor returns them when it finds any ([PDF outline](../guides/pdfs.md#pdf-outline)). `ingest` looks for each among the lines of its page (after the line `--- Page N ---`, the pages counted from 1), comparing the text without its spaces and passing over the first `skip` lines that match, and makes those it finds the outline when the text's own rules find fewer than 3 headings and it finds 3 or more (see [`OutlineEntry`](#outlineentry)). Read for a PDF only: the first 10,000 entries, each with a page and a level that are whole numbers (the level from 1 to 6), a title of up to 1,000 characters, and a `skip` that is a whole number from 0 or none; other entries are skipped. An extractor that wraps the built-in one passes them on to keep that outline. New in 0.10.0. |
1164
1848
 
1165
1849
  The model is told of both, on the card and in the frame of a file sent whole (see
1166
1850
  [`PreparedContext`](#preparedcontext)).
@@ -1193,8 +1877,8 @@ with the code of its words ([`ingestErrorCodeOf`](#ingesterrorcodeofmessage)):
1193
1877
  - `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")
1194
1878
  - `Reading PDF files needs the optional dependency "unpdf".`
1195
1879
  - `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`)
1196
- - `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)
1197
- - `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.)
1880
+ - `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.)
1881
+ - 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>). …`.)
1198
1882
  - `This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.`
1199
1883
  - `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.`
1200
1884
  - `Reading DOCX, PPTX and XLSX files needs the optional dependency "jszip".` (until 0.8.0: `Reading DOCX and PPTX files …`)
@@ -1231,7 +1915,10 @@ writes each page as a line `--- Page N ---` followed by the page's text, and
1231
1915
  `[No text on this page. It may be a scan, a photo, or a chart.]` for a page without text. With
1232
1916
  `pictures`, a page that shows a picture or a drawing gets the line
1233
1917
  `[Picture on this page. This text cannot show it.]` under its page line. It returns the number of
1234
- pages. It throws the PDF messages listed under [`defaultExtractors`](#defaultextractors).
1918
+ pages, and since 0.10.0 the lines set larger than the body as `headings`
1919
+ ([`ExtractedText`](#extractedtext)), which `ingest` makes the outline of a PDF whose text gives
1920
+ fewer than 3 headings, when it finds 3 or more of these.
1921
+ It throws the PDF messages listed under [`defaultExtractors`](#defaultextractors).
1235
1922
 
1236
1923
  ```ts
1237
1924
  import { createLargeFiles, createPdfExtractor, MemoryDocumentStore } from "llm-large-files";
@@ -1268,9 +1955,11 @@ else `"text"`. New in 0.8.1: with `bytes`, a file that would be `"text"` and is
1268
1955
  is known by its content: `"pdf"` when it starts with `%PDF-` (after a byte order mark or white
1269
1956
  space), `"docx"`, `"pptx"` or `"xlsx"` for a ZIP archive with the parts of one (`word/document.xml`,
1270
1957
  `ppt/presentation.xml`, `xl/workbook.xml`), `"html"` when it starts with `<!DOCTYPE html` or
1271
- `<html`. `ingest` passes the bytes: a DOCX uploaded without its extension was told "This file is a
1272
- ZIP archive". The MIME type is lowercased and compared whole, so `text/csv; charset=utf-8` names no
1273
- format. A name without a dot is looked up whole, so a file named `log` is a `log`. `ingest` uses it,
1958
+ `<html`. `ingest` passes the bytes (of a file at a path, since 0.9.0, the parts looked at: its
1959
+ first KB, and for a ZIP its first 64 KB and its last MB): a DOCX uploaded without its extension was
1960
+ told "This file is a ZIP archive". The MIME type is lowercased and compared whole, so
1961
+ `text/csv; charset=utf-8` names no format here; `ingest` drops the parameters first (0.9.0), so
1962
+ 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,
1274
1963
  then turns a `"text"` document that reads like a log into `"log"`.
1275
1964
 
1276
1965
  | Format | Extensions | MIME types |
@@ -1334,7 +2023,11 @@ its own, and the two quotes around it.
1334
2023
  ```ts
1335
2024
  type DocumentMeta = {
1336
2025
  id: string;
2026
+ metaVersion?: number; // new in 0.9.0
1337
2027
  owner?: string;
2028
+ scope?: string[]; // new in 0.9.0
2029
+ sha256?: string; // new in 0.9.0
2030
+ original?: { ref: string; bytes: number; sha256: string }; // new in 0.9.0
1338
2031
  name: string;
1339
2032
  mimeType: string;
1340
2033
  format: DocumentFormat;
@@ -1365,10 +2058,14 @@ browser instead.
1365
2058
 
1366
2059
  | Field | Type | What it holds |
1367
2060
  |---|---|---|
1368
- | `id` | `string` | `doc_` and 32 hexadecimal digits ([`DOCUMENT_ID_PATTERN`](#document_id_pattern)). |
2061
+ | `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). |
2062
+ | `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. |
1369
2063
  | `owner` | `string \| undefined` | The owner given at ingest. Absent when none was given. |
2064
+ | `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. |
2065
+ | `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. |
2066
+ | `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. |
1370
2067
  | `name` | `string` | The cleaned file name (see [`IngestInput`](#ingestinput)). |
1371
- | `mimeType` | `string` | The MIME type given, trimmed, or `"application/octet-stream"`. |
2068
+ | `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"`. |
1372
2069
  | `format` | [`DocumentFormat`](#documentformat) | The format. |
1373
2070
  | `bytes` | `number` | The size of the uploaded file. |
1374
2071
  | `textBytes` | `number` | The size of the extracted text in UTF-8. |
@@ -1380,8 +2077,8 @@ browser instead.
1380
2077
  | `pages` | `number \| undefined` | The pages of a PDF, the slides of a PPTX, the sheets of an XLSX, or what your extractor returned. |
1381
2078
  | `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. |
1382
2079
  | `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. |
1383
- | `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. |
1384
- | `outline` | [`OutlineEntry[]`](#outlineentry) | The headings found in the text, at most 400. Empty for `log`, `json` and `csv`. |
2080
+ | `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. |
2081
+ | `outline` | [`OutlineEntry[]`](#outlineentry) | The headings found in the text, at most 400. Empty for `log`, `json` and `csv`. For a PDF whose text gives fewer than 3, the lines set larger than its body when there are 3 or more, since 0.10.0. |
1385
2082
  | `logProfile` | [`LogProfile`](#logprofile) or `undefined` | The log profile, for a `log` document only. |
1386
2083
  | `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. |
1387
2084
  | `garbledPages` | `number[]` or `undefined` | The pages of a PDF whose text looks garbled: of at least 40 characters, fewer than 3 in 10 letters or digits, or more than max(6, 3%) replacement characters (a font without a Unicode map). Up to 200. The card says not to rely on them. New in 0.8.1. |
@@ -1440,7 +2137,12 @@ type OutlineEntry = { line: number; level: number; title: string };
1440
2137
  One heading of a document's outline. The headings are found in the text: Markdown headings (the
1441
2138
  slides of a PPTX are `## Slide N`), lines that start with "Chapter", "Part", "Book", "Section" or
1442
2139
  "Appendix" (or the Hebrew words for chapter, part and appendix), numbered headings such as `2.1 Results`, and short lines in capitals; all but the
1443
- Markdown ones only after a blank line. When there are more than 400, the outline keeps only the
2140
+ Markdown ones only after a blank line. A PDF whose text gives fewer than 3 such headings (pdf.js
2141
+ gives no blank line between paragraphs, and Hebrew has no capitals) gets, since 0.10.0, the lines its
2142
+ extractor found set larger than its body ([`ExtractedText.headings`](#extractedtext)), when 3 or
2143
+ more of them are found: each is the line of the text it points to, and its level comes from its size, 1 to 3
2144
+ ([PDF outline](../guides/pdfs.md#pdf-outline)). A PDF ingested before 0.10.0 keeps the outline it
2145
+ was given until it is uploaded again. When there are more than 400, the outline keeps only the
1444
2146
  top-level headings (of the shallowest level found) when there are at least 20 of them, and all the
1445
2147
  headings otherwise. With 20 to 400 top-level headings, each one is kept once, in order. Otherwise
1446
2148
  (more than 400 top-level headings, or fewer than 20) the outline has 400 entries, in order, taken
@@ -1519,20 +2221,26 @@ own `onActivity` instead.
1519
2221
  type ToolCallHooks = {
1520
2222
  onProgress?: ProgressListener;
1521
2223
  onRequest?: (request: ToolRequestStart) => ToolRequestHandle;
2224
+ onDocumentGone?: (documentId: string) => void; // new in 0.9.0
2225
+ onPagesBusy?: (documentId: string) => void; // new in 0.9.0
2226
+ signal?: AbortSignal; // new in 0.10.0
1522
2227
  };
1523
2228
  ```
1524
2229
 
1525
2230
  New in 0.7.0. Listeners for one tool call: the fourth argument of
1526
2231
  [`executeWithFiles`](./tools.md#toolset), next to its limits. With them, the progress and the model
1527
2232
  requests of two whole-file reads that run at once can be told apart. Only `analyze_whole_document`
1528
- calls them; the other tools ignore them. `askWithFiles` passes its own for each call, and turns
1529
- them into `tool.progress`, `request.start`, `retry` and `request.end` events
1530
- ([events in your own loop](./events.md#toolcallhooks)).
2233
+ calls `onProgress` and `onRequest`; the other tools ignore them. `askWithFiles` passes its own for
2234
+ each call, and turns them into `tool.progress`, `request.start`, `retry` and `request.end` events,
2235
+ and `"document_gone"` and `"page_looks_busy"` notices ([events in your own loop](./events.md#toolcallhooks)).
1531
2236
 
1532
2237
  | Field | Type | What it does |
1533
2238
  |---|---|---|
1534
2239
  | `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. |
1535
2240
  | `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. |
2241
+ | `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. |
2242
+ | `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. |
2243
+ | `signal` | `AbortSignal`, optional | Ends this call alone: its scans, regex searches, whole-file read, look at pages and loads. Joined with `ToolOptions.signal`. New in 0.10.0. |
1536
2244
 
1537
2245
  Do not let them throw. The read takes a throw from `onRequest` or from a handle for a failure of
1538
2246
  that request: the part is reported as not read, and a merge or the answer falls back to the notes.