llm-large-files 0.9.0 → 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 (222) hide show
  1. package/CHANGELOG.md +446 -0
  2. package/README.md +13 -7
  3. package/dist/access.d.ts +45 -3
  4. package/dist/access.d.ts.map +1 -1
  5. package/dist/access.js +106 -3
  6. package/dist/access.js.map +1 -1
  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 +115 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +572 -103
  26. package/dist/ask.js.map +1 -1
  27. package/dist/citations.d.ts +36 -0
  28. package/dist/citations.d.ts.map +1 -0
  29. package/dist/citations.js +291 -0
  30. package/dist/citations.js.map +1 -0
  31. package/dist/error-info.d.ts +13 -0
  32. package/dist/error-info.d.ts.map +1 -1
  33. package/dist/error-info.js +37 -1
  34. package/dist/error-info.js.map +1 -1
  35. package/dist/errors.d.ts +3 -1
  36. package/dist/errors.d.ts.map +1 -1
  37. package/dist/errors.js +3 -1
  38. package/dist/errors.js.map +1 -1
  39. package/dist/events.d.ts +25 -7
  40. package/dist/events.d.ts.map +1 -1
  41. package/dist/events.js.map +1 -1
  42. package/dist/evidence.d.ts.map +1 -1
  43. package/dist/evidence.js +21 -2
  44. package/dist/evidence.js.map +1 -1
  45. package/dist/extract.d.ts.map +1 -1
  46. package/dist/extract.js +6 -1
  47. package/dist/extract.js.map +1 -1
  48. package/dist/gemini/adapter.d.ts +35 -4
  49. package/dist/gemini/adapter.d.ts.map +1 -1
  50. package/dist/gemini/adapter.js +68 -29
  51. package/dist/gemini/adapter.js.map +1 -1
  52. package/dist/gemini/chat.d.ts +28 -55
  53. package/dist/gemini/chat.d.ts.map +1 -1
  54. package/dist/gemini/chat.js +20 -27
  55. package/dist/gemini/chat.js.map +1 -1
  56. package/dist/gemini/endpoints.d.ts +59 -11
  57. package/dist/gemini/endpoints.d.ts.map +1 -1
  58. package/dist/gemini/endpoints.js +33 -7
  59. package/dist/gemini/endpoints.js.map +1 -1
  60. package/dist/gemini/errors.d.ts +39 -5
  61. package/dist/gemini/errors.d.ts.map +1 -1
  62. package/dist/gemini/errors.js +70 -9
  63. package/dist/gemini/errors.js.map +1 -1
  64. package/dist/gemini/generate.d.ts +53 -2
  65. package/dist/gemini/generate.d.ts.map +1 -1
  66. package/dist/gemini/generate.js +100 -50
  67. package/dist/gemini/generate.js.map +1 -1
  68. package/dist/gemini/index.d.ts +3 -3
  69. package/dist/gemini/index.d.ts.map +1 -1
  70. package/dist/http.d.ts +41 -3
  71. package/dist/http.d.ts.map +1 -1
  72. package/dist/http.js +40 -2
  73. package/dist/http.js.map +1 -1
  74. package/dist/index.d.ts +6 -4
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +4 -2
  77. package/dist/index.js.map +1 -1
  78. package/dist/ingest.d.ts +9 -1
  79. package/dist/ingest.d.ts.map +1 -1
  80. package/dist/ingest.js +50 -25
  81. package/dist/ingest.js.map +1 -1
  82. package/dist/library.d.ts +129 -2
  83. package/dist/library.d.ts.map +1 -1
  84. package/dist/library.js +224 -149
  85. package/dist/library.js.map +1 -1
  86. package/dist/map-reduce.d.ts +176 -10
  87. package/dist/map-reduce.d.ts.map +1 -1
  88. package/dist/map-reduce.js +804 -58
  89. package/dist/map-reduce.js.map +1 -1
  90. package/dist/model.d.ts +36 -4
  91. package/dist/model.d.ts.map +1 -1
  92. package/dist/model.js +17 -1
  93. package/dist/model.js.map +1 -1
  94. package/dist/node/handlers.d.ts +29 -8
  95. package/dist/node/handlers.d.ts.map +1 -1
  96. package/dist/node/handlers.js +148 -126
  97. package/dist/node/handlers.js.map +1 -1
  98. package/dist/node/index.d.ts +1 -1
  99. package/dist/node/index.d.ts.map +1 -1
  100. package/dist/node/index.js.map +1 -1
  101. package/dist/node/ingest-child.js +2 -2
  102. package/dist/node/ingest-child.js.map +1 -1
  103. package/dist/node/spool.d.ts +9 -5
  104. package/dist/node/spool.d.ts.map +1 -1
  105. package/dist/node/spool.js +28 -15
  106. package/dist/node/spool.js.map +1 -1
  107. package/dist/node/sse.d.ts +6 -5
  108. package/dist/node/sse.d.ts.map +1 -1
  109. package/dist/node/sse.js +8 -7
  110. package/dist/node/sse.js.map +1 -1
  111. package/dist/openai/adapter.d.ts +5 -1
  112. package/dist/openai/adapter.d.ts.map +1 -1
  113. package/dist/openai/adapter.js +53 -12
  114. package/dist/openai/adapter.js.map +1 -1
  115. package/dist/output-limit.d.ts +2 -1
  116. package/dist/output-limit.d.ts.map +1 -1
  117. package/dist/output-limit.js +5 -2
  118. package/dist/output-limit.js.map +1 -1
  119. package/dist/pdf-outline.d.ts +71 -0
  120. package/dist/pdf-outline.d.ts.map +1 -0
  121. package/dist/pdf-outline.js +414 -0
  122. package/dist/pdf-outline.js.map +1 -0
  123. package/dist/plan.d.ts +137 -7
  124. package/dist/plan.d.ts.map +1 -1
  125. package/dist/plan.js +248 -26
  126. package/dist/plan.js.map +1 -1
  127. package/dist/prepare.d.ts +50 -0
  128. package/dist/prepare.d.ts.map +1 -0
  129. package/dist/prepare.js +207 -0
  130. package/dist/prepare.js.map +1 -0
  131. package/dist/ranged.d.ts +2 -1
  132. package/dist/ranged.d.ts.map +1 -1
  133. package/dist/ranged.js +16 -3
  134. package/dist/ranged.js.map +1 -1
  135. package/dist/search.d.ts +7 -0
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +72 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/stores.d.ts +6 -0
  140. package/dist/stores.d.ts.map +1 -1
  141. package/dist/stores.js +82 -11
  142. package/dist/stores.js.map +1 -1
  143. package/dist/tools.d.ts +22 -2
  144. package/dist/tools.d.ts.map +1 -1
  145. package/dist/tools.js +323 -76
  146. package/dist/tools.js.map +1 -1
  147. package/dist/types.d.ts +49 -1
  148. package/dist/types.d.ts.map +1 -1
  149. package/dist/whole-cost.d.ts +37 -0
  150. package/dist/whole-cost.d.ts.map +1 -0
  151. package/dist/whole-cost.js +46 -0
  152. package/dist/whole-cost.js.map +1 -0
  153. package/docs/README.md +4 -0
  154. package/docs/guides/anthropic.md +5 -2
  155. package/docs/guides/conversations.md +1 -1
  156. package/docs/guides/costs-and-limits.md +132 -36
  157. package/docs/guides/deployment.md +106 -13
  158. package/docs/guides/errors-and-reliability.md +157 -45
  159. package/docs/guides/explorer-model.md +4 -1
  160. package/docs/guides/openai-compatible.md +47 -7
  161. package/docs/guides/own-adapter-and-loop.md +33 -6
  162. package/docs/guides/pdfs.md +96 -7
  163. package/docs/guides/storage.md +46 -3
  164. package/docs/guides/testing.md +71 -0
  165. package/docs/guides/vertex-and-gemini.md +159 -50
  166. package/docs/guides/web-app.md +10 -6
  167. package/docs/how-it-works.md +120 -22
  168. package/docs/measurements.md +172 -5
  169. package/docs/publishing.md +76 -4
  170. package/docs/reference/anthropic.md +12 -7
  171. package/docs/reference/ask.md +262 -35
  172. package/docs/reference/errors-and-retries.md +30 -2
  173. package/docs/reference/events.md +27 -10
  174. package/docs/reference/gemini.md +184 -68
  175. package/docs/reference/library.md +190 -23
  176. package/docs/reference/node.md +51 -17
  177. package/docs/reference/openai.md +21 -10
  178. package/docs/reference/tools.md +271 -26
  179. package/docs/security.md +101 -12
  180. package/docs/troubleshooting.md +14 -12
  181. package/docs/upgrading-0.10.md +472 -0
  182. package/package.json +5 -1
  183. package/src/access.ts +127 -4
  184. package/src/aggregate.ts +92 -14
  185. package/src/analyze.ts +2 -2
  186. package/src/answer-info.ts +45 -0
  187. package/src/anthropic/adapter.ts +40 -11
  188. package/src/ask.ts +646 -106
  189. package/src/citations.ts +294 -0
  190. package/src/error-info.ts +36 -1
  191. package/src/errors.ts +3 -1
  192. package/src/events.ts +29 -6
  193. package/src/evidence.ts +21 -2
  194. package/src/extract.ts +6 -1
  195. package/src/gemini/adapter.ts +99 -32
  196. package/src/gemini/chat.ts +53 -82
  197. package/src/gemini/endpoints.ts +89 -16
  198. package/src/gemini/errors.ts +74 -11
  199. package/src/gemini/generate.ts +147 -57
  200. package/src/gemini/index.ts +3 -3
  201. package/src/http.ts +65 -4
  202. package/src/index.ts +6 -4
  203. package/src/ingest.ts +58 -27
  204. package/src/library.ts +336 -142
  205. package/src/map-reduce.ts +855 -67
  206. package/src/model.ts +44 -4
  207. package/src/node/handlers.ts +159 -118
  208. package/src/node/index.ts +1 -0
  209. package/src/node/ingest-child.ts +2 -2
  210. package/src/node/spool.ts +28 -14
  211. package/src/node/sse.ts +8 -7
  212. package/src/openai/adapter.ts +56 -13
  213. package/src/output-limit.ts +5 -2
  214. package/src/pdf-outline.ts +400 -0
  215. package/src/plan.ts +287 -36
  216. package/src/prepare.ts +253 -0
  217. package/src/ranged.ts +16 -3
  218. package/src/search.ts +69 -13
  219. package/src/stores.ts +76 -11
  220. package/src/tools.ts +327 -75
  221. package/src/types.ts +45 -1
  222. package/src/whole-cost.ts +64 -0
@@ -17,7 +17,8 @@ import {
17
17
  estimateTokens, utf8Bytes, jsonBytes,
18
18
  } from "llm-large-files";
19
19
  import type {
20
- LargeFilesOptions, LargeFiles, AccessOptions, IngestInput, PrepareOptions, ToolOptions, PreparedContext, DocumentPlan,
20
+ LargeFilesOptions, LargeFiles, CreatedLargeFiles, LargeFilesStats, AccessOptions, IngestInput, PrepareOptions, ToolOptions,
21
+ PreparedContext, ToolName, DocumentPlan,
21
22
  Budget, ModelLimits, DocumentStore, DocumentContext, DocumentScope, StoredDocument, FileDocumentStoreOptions, FileDocumentScopes,
22
23
  PdfExtractorOptions, Extractor, ExtractInput, ExtractProgress,
23
24
  ExtractedText, DocumentMeta, DocumentSummary, DocumentFormat, OutlineEntry, LogIssue, LogProfile, ProgressEvent,
@@ -32,11 +33,12 @@ from the same entry point.
32
33
  Contents:
33
34
 
34
35
  - [The library](#the-library): [`createLargeFiles(options)`](#createlargefilesoptions),
35
- [`LargeFilesOptions`](#largefilesoptions), [`LargeFiles`](#largefiles), [`IngestInput`](#ingestinput),
36
+ [`LargeFilesOptions`](#largefilesoptions), [`LargeFiles`](#largefiles), [`CreatedLargeFiles`](#createdlargefiles),
37
+ [`LargeFilesStats`](#largefilesstats), [`IngestInput`](#ingestinput),
36
38
  [`IngestError`](#ingesterror), [`ingestErrorCodeOf(message)`](#ingesterrorcodeofmessage),
37
39
  [`AccessOptions`](#accessoptions), [`PrepareOptions`](#prepareoptions), [`ToolOptions`](#tooloptions),
38
- [`PreparedContext`](#preparedcontext), [`DocumentPlan`](#documentplan),
39
- [`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),
40
42
  [`DEFAULT_MAX_PDF_PAGES`](#default_max_pdf_pages), [`DEFAULT_MAX_TEXT_BYTES`](#default_max_text_bytes),
41
43
  [`DEFAULT_INGEST_TIMEOUT_MS`](#default_ingest_timeout_ms),
42
44
  [`NEVER_EXPIRES`](#never_expires), [`isDocumentId(value)`](#isdocumentidvalue),
@@ -75,7 +77,7 @@ model sees ([tools.md](./tools.md)), and the events of a question and of an inge
75
77
  ### createLargeFiles(options)
76
78
 
77
79
  ```ts
78
- declare function createLargeFiles(options: LargeFilesOptions): LargeFiles;
80
+ declare function createLargeFiles(options: LargeFilesOptions): CreatedLargeFiles; // LargeFiles before 0.10.0
79
81
  ```
80
82
 
81
83
  Creates the library over one store. Create it once per process and share it: it keeps the cache of
@@ -122,6 +124,9 @@ type LargeFilesOptions = {
122
124
  pageLookWaitMs?: number; // new in 0.9.0
123
125
  requireOwner?: boolean; // new in 0.9.0
124
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
125
130
  now?: () => Date;
126
131
  };
127
132
  ```
@@ -149,6 +154,9 @@ type LargeFilesOptions = {
149
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. |
150
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. |
151
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. |
152
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`. |
153
161
 
154
162
  Since 0.7.1, `ttlMs`, `maxUploadBytes`, `scannedPdfPages`, `cacheBytes`, `cacheSize`,
@@ -160,7 +168,8 @@ a value that is not a number throws a `TypeError`, and so does `Infinity` for `s
160
168
  used to pass through: `maxConcurrentScans` left every scan of a document read by range waiting
161
169
  forever, `ttlMs` failed every upload, `maxUploadBytes` took off the upload limit. A number below
162
170
  the least an option takes is raised to it, as before. `maxTextBytes`, `maxPdfPages` and
163
- `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.
164
173
 
165
174
  Guides: [storage](../guides/storage.md) for the store, owners and retention,
166
175
  [costs and limits](../guides/costs-and-limits.md) for the budget, [PDFs](../guides/pdfs.md) for
@@ -183,6 +192,8 @@ interface LargeFiles {
183
192
  sweep(options?: { scope?: DocumentScope }): Promise<number>;
184
193
  prepare(ids: string[], base: { tokens: number; bytes: number }, options?: PrepareOptions): Promise<PreparedContext>;
185
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
186
197
  }
187
198
  ```
188
199
 
@@ -203,6 +214,13 @@ left out, so a call without either gets `{}`. A document a store returns for ano
203
214
  the owner `null` (as a MongoDB driver writes a field that was left out), is read as missing, or as
204
215
  without an owner.
205
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. |
223
+
206
224
  #### `files.access`
207
225
 
208
226
  `readonly access?: { readonly requireOwner: boolean; readonly requireScope: boolean }`
@@ -317,7 +335,7 @@ progress](./node.md#upload-with-progress-accept-textevent-stream)).
317
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. |
318
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. |
319
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. |
320
- | An error with a system error's `code` and `syscall` | A file at a path that is not there (`ENOENT`), cannot be opened (`EACCES`), is a link (`ELOOP`, from `lstat`, or from the read at its turn when a link was put in its place), a folder (`EISDIR`), or not a file at all (`EINVAL`: a pipe, a device). Or a volume that did not answer the look before the turn within `ingestTimeoutMs` (`ETIMEDOUT`, `syscall` `"lstat"` or `"read"`): `The file to ingest did not answer within 2 min.` Passed on as it is, not as an `IngestError`: it is the server's trouble, not the file's. The messages of the library's own (`ELOOP`, `EISDIR`, `EINVAL`, `ETIMEDOUT`) name no path; Node's do. New in 0.9.0. |
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. |
321
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. |
322
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. |
323
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)). |
@@ -375,7 +393,9 @@ An owner of `null` is left out of the metadata returned (new in 0.9.0). Throws `
375
393
  store cannot be read, and, new in 0.9.0, with code `"NEWER_VERSION"` when a newer version of the
376
394
  package wrote the metadata ([`DOCUMENT_META_VERSION`](#document_meta_version)). A name that 0.5.0
377
395
  or earlier stored cut inside an emoji comes back with a replacement character (U+FFFD) in place of
378
- the half, as the model and the steps get it; the stored metadata is not changed.
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.
379
399
 
380
400
  #### `files.getOriginal(id, access?)`
381
401
 
@@ -404,7 +424,13 @@ deleted. Otherwise it drops what this process keeps of the document in memory, i
404
424
  and returns what `store.delete(id, context)` returns. Throws `DocumentStoreError` when the look-up
405
425
  cannot read the store, and, new in 0.9.0, a `DocumentStoreError` of operation `"delete"` when
406
426
  `store.delete` fails, with the store's error as `cause` (it was passed on unchanged). Its message
407
- names no path: `The document could not be deleted (EPERM). Try again.`
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.
408
434
 
409
435
  #### `files.sweep(options?)`
410
436
 
@@ -415,7 +441,8 @@ removed: 0 when the store has no `sweep`. With `scope` (new in 0.9.0), the store
415
441
  that scope only (`store.sweep(now, { scope })`); without one, every scope (`store.sweep(now, {})`).
416
442
  It needs no scope under `requireScope`. A scope that is not valid is a `DocumentScopeError`. Since
417
443
  0.9.0 a store that fails is a `DocumentStoreError` of operation `"sweep"`, with the store's error as
418
- `cause` (it was passed on unchanged). The library never sweeps on its own: run it on a schedule,
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,
419
446
  from one place (see [deployment](../guides/deployment.md)).
420
447
 
421
448
  #### `files.prepare(ids, base, options?)`
@@ -502,6 +529,54 @@ tools, their arguments and their results are in [tools.md](./tools.md).
502
529
 
503
530
  Throws an `Error` for a `budget` that cannot work.
504
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
+
505
580
  #### `files.budget`
506
581
 
507
582
  `readonly budget: Budget`
@@ -527,6 +602,40 @@ Guide: [costs and limits](../guides/costs-and-limits.md).
527
602
 
528
603
  The upload limit in effect: `options.maxUploadBytes`, or 104,857,600 (100 MB).
529
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
+
530
639
  ### `IngestInput`
531
640
 
532
641
  ```ts
@@ -598,7 +707,9 @@ export const meta = await files.ingest({ name: "report.pdf", source: { path: "/s
598
707
  MB, read for that alone: a DOCX without its extension is still a DOCX.
599
708
  - **At its turn**, the file is read once, opened without following a link at its name (not on
600
709
  Windows), and at most `maxUploadBytes + 1` bytes: a file that has grown past the limit since it
601
- was looked at is refused as `"too_large"`. Its SHA-256 is taken as it is read
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
602
713
  (`DocumentMeta.sha256`), and `bytes` is the size read. The bytes are let go as soon as the
603
714
  extractor returns, before the text is prepared, indexed and stored, unless the store keeps a copy
604
715
  (`keepOriginals` without `original`).
@@ -750,7 +861,11 @@ const error = new IngestError(ingestErrorCodeOf(message), message);
750
861
  ### `AccessOptions`
751
862
 
752
863
  ```ts
753
- type AccessOptions = { owner?: string; scope?: DocumentScope };
864
+ type AccessOptions = {
865
+ owner?: string;
866
+ scope?: DocumentScope;
867
+ signal?: AbortSignal; // new in 0.10.0
868
+ };
754
869
  ```
755
870
 
756
871
  Who is asking. `getMeta`, `getOriginal`, `delete` and `prepare` (through
@@ -761,6 +876,7 @@ takes the same two options. Each store call carries both ([`DocumentContext`](#d
761
876
  |---|---|---|---|
762
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. |
763
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. |
764
880
 
765
881
  The library has no notion of a session and cannot list documents by owner: record the IDs in your
766
882
  own data. See [storage](../guides/storage.md) and [security](../security.md).
@@ -772,10 +888,13 @@ type PrepareOptions = AccessOptions & {
772
888
  budget?: Partial<Budget>;
773
889
  viewPages?: boolean;
774
890
  wholeDocumentAnalysis?: boolean;
891
+ numberInline?: boolean; // new in 0.10.0
892
+ inlineTables?: "tools" | "text"; // new in 0.10.0
775
893
  };
776
894
  ```
777
895
 
778
- 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.
779
898
 
780
899
  | Option | Type | Default | What it does |
781
900
  |---|---|---|---|
@@ -784,6 +903,15 @@ The options of [`files.prepare`](#filesprepareids-base-options).
784
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. |
785
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`. |
786
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.
787
915
 
788
916
  Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
789
917
 
@@ -800,6 +928,8 @@ type ToolOptions = {
800
928
  retry?: RetryOptions;
801
929
  budget?: Partial<Budget>;
802
930
  viewPages?: boolean | DocumentMeta[];
931
+ declare?: readonly ToolName[]; // new in 0.10.0
932
+ inline?: readonly string[]; // new in 0.10.0
803
933
  };
804
934
  ```
805
935
 
@@ -816,6 +946,8 @@ The options of [`files.tools`](#filestoolsdocuments-options).
816
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. |
817
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. |
818
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. |
819
951
 
820
952
  Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
821
953
 
@@ -828,6 +960,7 @@ type PreparedContext = {
828
960
  instruction: string;
829
961
  missing: string[];
830
962
  viewable: DocumentMeta[];
963
+ toolable?: DocumentMeta[]; // new in 0.10.0
831
964
  };
832
965
  ```
833
966
 
@@ -840,6 +973,12 @@ What [`files.prepare`](#filesprepareids-base-options) returns.
840
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. |
841
974
  | `missing` | `string[]` | The IDs that were not found: never uploaded, not a document ID, deleted, expired, or another owner's. |
842
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"`.
843
982
 
844
983
  A document sent whole sits between these two lines (new in 0.6.0, for every document):
845
984
 
@@ -849,6 +988,9 @@ A document sent whole sits between these two lines (new in 0.6.0, for every docu
849
988
  --- End attached file [mark <mark>] ---
850
989
  ```
851
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
+
852
994
  - `<mark>` is eight hex digits made from the document ID, the same in every request, so a
853
995
  provider's prompt cache reuses the file. After an upgrade from 0.5.0, the first request of each
854
996
  conversation reads nothing of the file from the cache, since the frame lines changed. The
@@ -873,7 +1015,8 @@ starts every frame.
873
1015
 
874
1016
  A card starts with `--- Large attached file: <name> ---`, as before. Its third line is
875
1017
  `<format> · <size> · <lines> lines · <pages> pages · about <tokens> tokens`, with `1 line` and
876
- `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
877
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.`,
878
1021
  followed, when some characters were not valid in it, by
879
1022
  ` 3 characters of it were not valid in windows-1255, and show as �.`; or, for a file read as UTF-8,
@@ -883,6 +1026,14 @@ followed, when some characters were not valid in it, by
883
1026
 
884
1027
  Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
885
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
+
886
1037
  ### `DocumentPlan`
887
1038
 
888
1039
  ```ts
@@ -1290,13 +1441,17 @@ documents of each scope are in a folder of their own:
1290
1441
  links in the folders of a scope are refused on every platform (`"scope_invalid"`).
1291
1442
  - `delete` removes the metadata first. When that fails, it throws, and nothing else is removed: the
1292
1443
  document stays whole. Then it removes the text, the index and the original, and returns whether
1293
- the metadata existed. Since 0.9.0, a part that cannot be removed then is left for `sweep`, and
1294
- `delete` still returns `true`: the document is gone once its metadata is.
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.
1295
1451
  - `sweep(now?)` removes expired documents and returns how many, counting a document whose metadata
1296
1452
  is not valid and is older than `orphanAgeMs`. It counts only the documents whose metadata it
1297
- removed itself: of two sweeps at once, on one server or two, each document is counted once
1298
- (since 0.9.0). Not always on Windows: there, two processes that remove one file at the same
1299
- moment can both be told it was removed, so the total can count a document twice. It also
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
1300
1455
  removes files that belong to no document, and temporary files, once they are older than
1301
1456
  `orphanAgeMs` (these are not counted). Where files
1302
1457
  of your own may sit beside the documents (`directory` without `scopes`, or `scopes.folder` `""`),
@@ -1478,7 +1633,7 @@ it, rather than ask the user to upload the file again.
1478
1633
  |---|---|---|
1479
1634
  | `name` | `string` | `"DocumentStoreError"`. |
1480
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. |
1481
- | `code` | `string \| undefined` | The code of the system error behind it (`EIO`, `EMFILE`, `ETIMEDOUT`), when there is one, or the code it was made with: `"NEWER_VERSION"` for metadata a newer version of the package wrote ([`DOCUMENT_META_VERSION`](#document_meta_version)). |
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. |
1482
1637
  | `syscall` | `string \| undefined` | The system call that failed (`open`, `read`), when there is one. |
1483
1638
  | `operation` | `"read" \| "write" \| "delete" \| "sweep"` | What the store was doing. `"read"` unless it was made with another. New in 0.9.0. |
1484
1639
  | `status` | `503` | The HTTP status to answer with. New in 0.9.0. |
@@ -1678,6 +1833,7 @@ type ExtractedText = {
1678
1833
  encoding?: string;
1679
1834
  replacedCharacters?: number;
1680
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
1681
1837
  };
1682
1838
  ```
1683
1839
 
@@ -1688,6 +1844,7 @@ type ExtractedText = {
1688
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. |
1689
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. |
1690
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. |
1691
1848
 
1692
1849
  The model is told of both, on the card and in the frame of a file sent whole (see
1693
1850
  [`PreparedContext`](#preparedcontext)).
@@ -1758,7 +1915,10 @@ writes each page as a line `--- Page N ---` followed by the page's text, and
1758
1915
  `[No text on this page. It may be a scan, a photo, or a chart.]` for a page without text. With
1759
1916
  `pictures`, a page that shows a picture or a drawing gets the line
1760
1917
  `[Picture on this page. This text cannot show it.]` under its page line. It returns the number of
1761
- 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).
1762
1922
 
1763
1923
  ```ts
1764
1924
  import { createLargeFiles, createPdfExtractor, MemoryDocumentStore } from "llm-large-files";
@@ -1918,7 +2078,7 @@ browser instead.
1918
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. |
1919
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. |
1920
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. |
1921
- | `outline` | [`OutlineEntry[]`](#outlineentry) | The headings found in the text, at most 400. Empty for `log`, `json` and `csv`. |
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. |
1922
2082
  | `logProfile` | [`LogProfile`](#logprofile) or `undefined` | The log profile, for a `log` document only. |
1923
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. |
1924
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. |
@@ -1977,7 +2137,12 @@ type OutlineEntry = { line: number; level: number; title: string };
1977
2137
  One heading of a document's outline. The headings are found in the text: Markdown headings (the
1978
2138
  slides of a PPTX are `## Slide N`), lines that start with "Chapter", "Part", "Book", "Section" or
1979
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
1980
- 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
1981
2146
  top-level headings (of the shallowest level found) when there are at least 20 of them, and all the
1982
2147
  headings otherwise. With 20 to 400 top-level headings, each one is kept once, in order. Otherwise
1983
2148
  (more than 400 top-level headings, or fewer than 20) the outline has 400 entries, in order, taken
@@ -2058,6 +2223,7 @@ type ToolCallHooks = {
2058
2223
  onRequest?: (request: ToolRequestStart) => ToolRequestHandle;
2059
2224
  onDocumentGone?: (documentId: string) => void; // new in 0.9.0
2060
2225
  onPagesBusy?: (documentId: string) => void; // new in 0.9.0
2226
+ signal?: AbortSignal; // new in 0.10.0
2061
2227
  };
2062
2228
  ```
2063
2229
 
@@ -2074,6 +2240,7 @@ and `"document_gone"` and `"page_looks_busy"` notices ([events in your own loop]
2074
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. |
2075
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. |
2076
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. |
2077
2244
 
2078
2245
  Do not let them throw. The read takes a throw from `onRequest` or from a handle for a failure of
2079
2246
  that request: the part is reported as not read, and a merge or the answer falls back to the notes.