llm-large-files 0.3.6 → 0.4.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 (69) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/cache.d.ts +40 -0
  3. package/dist/cache.d.ts.map +1 -0
  4. package/dist/cache.js +81 -0
  5. package/dist/cache.js.map +1 -0
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/library.d.ts +28 -1
  11. package/dist/library.d.ts.map +1 -1
  12. package/dist/library.js +155 -47
  13. package/dist/library.js.map +1 -1
  14. package/dist/limiter.d.ts +20 -0
  15. package/dist/limiter.d.ts.map +1 -0
  16. package/dist/limiter.js +55 -0
  17. package/dist/limiter.js.map +1 -0
  18. package/dist/map-reduce.d.ts +8 -4
  19. package/dist/map-reduce.d.ts.map +1 -1
  20. package/dist/map-reduce.js +65 -24
  21. package/dist/map-reduce.js.map +1 -1
  22. package/dist/plan.d.ts +7 -5
  23. package/dist/plan.d.ts.map +1 -1
  24. package/dist/plan.js +9 -8
  25. package/dist/plan.js.map +1 -1
  26. package/dist/ranged.d.ts +102 -0
  27. package/dist/ranged.d.ts.map +1 -0
  28. package/dist/ranged.js +314 -0
  29. package/dist/ranged.js.map +1 -0
  30. package/dist/search.d.ts +79 -15
  31. package/dist/search.d.ts.map +1 -1
  32. package/dist/search.js +388 -130
  33. package/dist/search.js.map +1 -1
  34. package/dist/stores.d.ts +22 -2
  35. package/dist/stores.d.ts.map +1 -1
  36. package/dist/stores.js +132 -15
  37. package/dist/stores.js.map +1 -1
  38. package/dist/text-index.d.ts +64 -0
  39. package/dist/text-index.d.ts.map +1 -0
  40. package/dist/text-index.js +211 -0
  41. package/dist/text-index.js.map +1 -0
  42. package/dist/text.d.ts +2 -1
  43. package/dist/text.d.ts.map +1 -1
  44. package/dist/text.js +7 -1
  45. package/dist/text.js.map +1 -1
  46. package/dist/tools.d.ts +2 -2
  47. package/dist/tools.d.ts.map +1 -1
  48. package/dist/tools.js +20 -14
  49. package/dist/tools.js.map +1 -1
  50. package/dist/types.d.ts +15 -0
  51. package/dist/types.d.ts.map +1 -1
  52. package/docs/api.md +12 -5
  53. package/docs/configuration.md +45 -3
  54. package/docs/how-it-works.md +3 -1
  55. package/docs/security.md +3 -0
  56. package/package.json +7 -3
  57. package/src/cache.ts +83 -0
  58. package/src/index.ts +1 -1
  59. package/src/library.ts +176 -44
  60. package/src/limiter.ts +51 -0
  61. package/src/map-reduce.ts +70 -25
  62. package/src/plan.ts +10 -9
  63. package/src/ranged.ts +348 -0
  64. package/src/search.ts +432 -120
  65. package/src/stores.ts +136 -17
  66. package/src/text-index.ts +228 -0
  67. package/src/text.ts +7 -1
  68. package/src/tools.ts +22 -16
  69. package/src/types.ts +15 -0
@@ -191,15 +191,57 @@ interface DocumentStore {
191
191
  put(document: { meta: DocumentMeta; text: string }): Promise<void>;
192
192
  get(id: string): Promise<{ meta: DocumentMeta; text: string } | undefined>; // undefined if expired
193
193
  getMeta(id: string): Promise<DocumentMeta | undefined>;
194
- delete(id: string): Promise<boolean>; // the original file too
194
+ delete(id: string): Promise<boolean>; // the original file and the index too
195
195
  sweep?(now?: Date): Promise<number>;
196
196
  putOriginal?(id: string, bytes: Uint8Array): Promise<void>; // optional: see below
197
197
  getOriginal?(id: string): Promise<Uint8Array | undefined>; // undefined if not kept, or expired
198
+ // Optional: read large documents by range instead of loading them whole (see below).
199
+ readTextRange?(id: string, start: number, end: number): Promise<Uint8Array | undefined>; // UTF-8 bytes
200
+ putIndex?(id: string, index: Uint8Array): Promise<void>;
201
+ getIndex?(id: string): Promise<Uint8Array | undefined>;
198
202
  }
199
203
  ```
200
204
 
201
- Keep `getMeta` cheap (store the metadata separately from the text). Parsed documents are cached
202
- in memory (`cacheSize`, default 6), so repeated tool calls don't reload the text.
205
+ Keep `getMeta` cheap (store the metadata separately from the text): it is called on every tool
206
+ call. A document ready to search is kept in memory between tool calls, within `cacheBytes`
207
+ (default 256 MB, the least recently used dropped first; `cacheSize` caps their number too). Every
208
+ use of a kept document asks the store first, so a document deleted or expired anywhere is gone
209
+ everywhere at once.
210
+
211
+ ### Large files, many users, several servers
212
+
213
+ With a store that has `readTextRange`, as `FileDocumentStore` does, a document whose text is larger
214
+ than `wholeDocumentBytes` (default 2 MB) is never loaded whole:
215
+
216
+ - At ingest, a line index is written next to the text (`<id>.idx`, four bytes a line: 3 MB for a
217
+ file of 730,000 lines). `read_document`, the card and the overview read only the lines they show.
218
+ - A search reads the text 1 MB at a time (`scanChunkBytes`), reading the next piece while it searches
219
+ the current one, so a search holds a few MB whatever the size of the file. At most
220
+ `maxConcurrentScans` searches (default 4) run at once in a process; the others wait their turn,
221
+ and those waiting for the same file share one pass over it: it is read, decoded and lowercased
222
+ once for all of them. Results are the same as from the whole text: the tests compare them call by call.
223
+ - Decoded pieces of a file are kept in the same `cacheBytes` budget, so the next search of a file in
224
+ use reads nothing. A file whose decoded text would take more than a quarter of the budget is never
225
+ kept: it would push out everything else. A larger `cacheBytes` spends memory to save CPU.
226
+ - A document from an older version, without an index, gets one the first time it is used: it is
227
+ built from the text in one pass and saved for the other servers. A damaged index, or one that
228
+ does not match its document, is noticed and built again.
229
+
230
+ Smaller documents are loaded whole and kept in the cache: for them that is faster, and they are small.
231
+ `wholeDocumentBytes: Infinity` loads every document whole, as before 0.4; `0` reads every one by range.
232
+
233
+ `FileDocumentStore` on a volume that several servers share:
234
+
235
+ - Every file is written under a temporary name and then renamed, so no server reads half a file.
236
+ - `sweep` removes files of no document (an upload that failed, a server that stopped while writing)
237
+ and temporary files once they are an hour old (`orphanAgeMs`), never younger ones: they may be an
238
+ upload in progress on another server. Run `sweep` from one place, such as a scheduled job.
239
+ - Servers of an older version on the same volume (during a rolling update) read the same files and
240
+ ignore the index. An index left behind when one of them deletes a document is swept an hour later.
241
+
242
+ A store of your own can do the same over S3 (`Range` requests), Redis (`GETRANGE`) or a database:
243
+ add `readTextRange`, and `putIndex` with `getIndex` to keep the index. Without `putIndex` the index
244
+ is built in memory each time the document is opened.
203
245
 
204
246
  ### Keeping the uploaded file
205
247
 
@@ -28,7 +28,9 @@ chat turn ─► prepare(ids, size of the rest of the request)
28
28
  by *shape*. Numbers, IDs, IPs, hex, and quoted values are replaced with placeholders, so 800
29
29
  timeouts to different hosts become one entry: `[ERROR ×812, L1203] timeout after <n>ms to <ip>`.
30
30
  4. **Store** the text and metadata, and the uploaded file when its format is in `keepOriginals`.
31
- Nothing else is indexed up front.
31
+ With a store that can read by range (`FileDocumentStore`), also a line index: where each line
32
+ starts, a few bytes a line, so a tool call on a large file reads only the lines it needs
33
+ ([details](configuration.md#large-files-many-users-several-servers)). Nothing else is indexed up front.
32
34
 
33
35
  ## The card
34
36
 
package/docs/security.md CHANGED
@@ -38,6 +38,9 @@ treat the model's output as untrusted.
38
38
 
39
39
  - Files expire after `ttlMs` (default 72 h); expired files are never returned. `sweep()` deletes
40
40
  them from disk. Set the TTL to match your data policy.
41
+ - A delete takes effect on every server that shares the store, from the next tool call on: a
42
+ document kept in memory is used only after the store confirms that it is still there. (Before
43
+ 0.4, another server could keep answering from its memory until the document expired.)
41
44
  - `FileDocumentStore` writes plain text to disk. Use an encrypted volume, or implement
42
45
  `DocumentStore` over storage with encryption at rest.
43
46
  - Only IDs matching `doc_` plus 32 hex characters ever reach the file system, so there's no path
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "llm-large-files",
3
- "version": "0.3.6",
3
+ "version": "0.4.0",
4
4
  "description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, map-reduce, and a look at the pages of a PDF. Gemini and Vertex AI helpers included.",
5
5
  "keywords": [
6
6
  "llm",
@@ -51,8 +51,12 @@
51
51
  },
52
52
  "typesVersions": {
53
53
  "*": {
54
- "gemini": ["./dist/gemini/index.d.ts"],
55
- "node": ["./dist/node/index.d.ts"]
54
+ "gemini": [
55
+ "./dist/gemini/index.d.ts"
56
+ ],
57
+ "node": [
58
+ "./dist/node/index.d.ts"
59
+ ]
56
60
  }
57
61
  },
58
62
  "files": [
package/src/cache.ts ADDED
@@ -0,0 +1,83 @@
1
+ import type { DocumentMeta } from "./types.js";
2
+
3
+ /** Something the cache can hold: it says how much memory it takes. */
4
+ export type Sized = { readonly memoryBytes: number };
5
+
6
+ /**
7
+ * What identifies the contents of a document. A document ID is never reused, but a store can be
8
+ * restored from a backup or written by another program: a cached copy is used only while the
9
+ * store still describes the same text.
10
+ */
11
+ export function documentVersion(meta: DocumentMeta): string {
12
+ return `${meta.createdAt}|${meta.textBytes}|${meta.characters}|${meta.lines}`;
13
+ }
14
+
15
+ /**
16
+ * Documents ready to read and search, kept between tool calls, the least recently used dropped
17
+ * first. Bounded by the memory the documents take, not by their number: six small files and
18
+ * six 50 MB files are not the same load.
19
+ *
20
+ * The cache never decides whether a document still exists. The caller asks the store first,
21
+ * every time (see `createLargeFiles`), so a document deleted or expired on another server is
22
+ * not served from here.
23
+ */
24
+ export class DocumentCache<T extends Sized> {
25
+ private readonly entries = new Map<string, { version: string; value: T; bytes: number }>();
26
+ private total = 0;
27
+
28
+ constructor(
29
+ private readonly maxBytes: number,
30
+ /** An optional cap on the number of documents too (the `cacheSize` of 0.3.x). */
31
+ private readonly maxEntries = Number.POSITIVE_INFINITY,
32
+ ) {}
33
+
34
+ /** Memory taken by the cached documents, by their own estimate. */
35
+ get bytes(): number {
36
+ return this.total;
37
+ }
38
+
39
+ get size(): number {
40
+ return this.entries.size;
41
+ }
42
+
43
+ get(id: string, version: string): T | undefined {
44
+ const entry = this.entries.get(id);
45
+ if (!entry) return undefined;
46
+ if (entry.version !== version) {
47
+ this.delete(id);
48
+ return undefined;
49
+ }
50
+ // Most recently used last.
51
+ this.entries.delete(id);
52
+ this.entries.set(id, entry);
53
+ return entry.value;
54
+ }
55
+
56
+ /** Keeps a document. One larger than the whole cache is not kept: it is used for this call only. */
57
+ set(id: string, version: string, value: T): void {
58
+ const existing = this.entries.get(id);
59
+ if (existing?.value === value && existing.version === version) return;
60
+ this.delete(id);
61
+ const bytes = Math.max(0, value.memoryBytes);
62
+ if (bytes > this.maxBytes || this.maxEntries < 1) return;
63
+ this.entries.set(id, { version, value, bytes });
64
+ this.total += bytes;
65
+ for (const [oldest, entry] of this.entries) {
66
+ if (this.total <= this.maxBytes && this.entries.size <= this.maxEntries) break;
67
+ this.entries.delete(oldest);
68
+ this.total -= entry.bytes;
69
+ }
70
+ }
71
+
72
+ delete(id: string): void {
73
+ const entry = this.entries.get(id);
74
+ if (!entry) return;
75
+ this.entries.delete(id);
76
+ this.total -= entry.bytes;
77
+ }
78
+
79
+ /** Drops every entry whose key starts with `prefix`: all the pieces of one document. */
80
+ deletePrefix(prefix: string): void {
81
+ for (const key of [...this.entries.keys()]) if (key.startsWith(prefix)) this.delete(key);
82
+ }
83
+ }
package/src/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // Core: provider-neutral. Gemini helpers live in "llm-large-files/gemini",
2
2
  // Node HTTP handlers in "llm-large-files/node".
3
- export { createLargeFiles, DEFAULT_BUDGET, isDocumentId, toDocumentSummary } from "./library.js";
3
+ export { createLargeFiles, DEFAULT_BUDGET, DEFAULT_CACHE_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, isDocumentId, toDocumentSummary } from "./library.js";
4
4
  export type { AccessOptions, IngestInput, LargeFiles, LargeFilesOptions, PrepareOptions, ToolOptions } from "./library.js";
5
5
  export { FileDocumentStore, MemoryDocumentStore, DOCUMENT_ID_PATTERN } from "./stores.js";
6
6
  export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";
package/src/library.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { buildLogProfile, buildOutline, looksLikeLog } from "./analyze.js";
3
+ import { DocumentCache, documentVersion, type Sized } from "./cache.js";
3
4
  import { detectFormat, extractText } from "./extract.js";
4
- import { documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
5
- import { SearchableDocument } from "./search.js";
5
+ import { Limiter } from "./limiter.js";
6
+ import { CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
7
+ import { openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
8
+ import { numberLines, SearchableDocument, type DocumentSource } from "./search.js";
6
9
  import { DOCUMENT_ID_PATTERN } from "./stores.js";
10
+ import { buildTextIndex, canSerialize, serializeTextIndex } from "./text-index.js";
7
11
  import { estimateTokens, normalizeText, utf8Bytes, wrapLongLines } from "./text.js";
8
12
  import { createDocumentTools } from "./tools.js";
9
13
  import type {
@@ -53,8 +57,31 @@ export type LargeFilesOptions = {
53
57
  * is accepted. Defaults to 30. 0 refuses every PDF without text, as before.
54
58
  */
55
59
  scannedPdfPages?: number;
56
- /** How many parsed documents to keep in memory for repeated tool calls. Defaults to 6. */
60
+ /**
61
+ * The most memory, in bytes, that documents kept ready for repeated tool calls may take.
62
+ * Defaults to 256 MB. A document larger than this is read again for each call. 0 keeps none.
63
+ *
64
+ * Every use of a kept document first asks the store whether it is still there, so a document
65
+ * deleted or expired on another server sharing the store is never served from memory here.
66
+ */
67
+ cacheBytes?: number;
68
+ /** Also caps the number of documents kept (the only limit before 0.4). Unset: no cap on the number. */
57
69
  cacheSize?: number;
70
+ /**
71
+ * Documents whose text is at most this many bytes are loaded whole into memory (and kept there
72
+ * within `cacheBytes`). Larger ones are read by range, when the store can (`readTextRange`, as
73
+ * `FileDocumentStore` does): a tool call reads the lines it needs, and a search reads the text a
74
+ * piece at a time, so memory does not grow with the size of the files or the number of users.
75
+ * Defaults to 2 MB. `Infinity` loads every document whole, as before 0.4; 0 reads every one by range.
76
+ */
77
+ wholeDocumentBytes?: number;
78
+ /** Reading by range: about this many bytes of text are read and searched at a time. Defaults to 1 MB. */
79
+ scanChunkBytes?: number;
80
+ /**
81
+ * Reading by range: how many scans of whole documents (searches, counting the parts of a file)
82
+ * run at once in this process. The others wait their turn. Defaults to 4.
83
+ */
84
+ maxConcurrentScans?: number;
58
85
  /** Clock override, for tests. */
59
86
  now?: () => Date;
60
87
  };
@@ -154,40 +181,125 @@ function allowed(meta: DocumentMeta, access: AccessOptions | undefined): boolean
154
181
  return meta.owner === undefined || meta.owner === access?.owner;
155
182
  }
156
183
 
184
+ /** Default for `cacheBytes`. */
185
+ export const DEFAULT_CACHE_BYTES = 256 * 1024 * 1024;
186
+ /** Default for `wholeDocumentBytes`. */
187
+ export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
188
+
157
189
  export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
158
190
  const budget: Budget = { ...DEFAULT_BUDGET, ...options.budget };
159
191
  const ttlMs = options.ttlMs ?? 72 * 60 * 60 * 1000;
160
192
  const maxUploadBytes = options.maxUploadBytes ?? 100 * 1024 * 1024;
161
193
  const now = options.now ?? (() => new Date());
162
- const cacheSize = Math.max(1, options.cacheSize ?? 6);
163
- const cache = new Map<string, SearchableDocument>();
194
+ const { store } = options;
195
+ const cacheBytes = Math.max(0, options.cacheBytes ?? DEFAULT_CACHE_BYTES);
196
+ /** Documents ready to search, and decoded pieces of documents read by range, in one memory budget. */
197
+ const cache = new DocumentCache<Sized>(
198
+ cacheBytes,
199
+ options.cacheSize === undefined ? Number.POSITIVE_INFINITY : Math.max(0, Math.trunc(options.cacheSize)),
200
+ );
201
+ /** Forgets everything kept of a document: the document, and its pieces. */
202
+ const forget = (id: string) => {
203
+ cache.delete(id);
204
+ cache.deletePrefix(pieceKey(id, 0).slice(0, -1));
205
+ };
206
+ /** Documents being opened, so that calls arriving together open each one once. */
207
+ const opening = new Map<string, Promise<DocumentSource | undefined>>();
208
+ /** The store, when large documents can be read from it by range rather than loaded whole. */
209
+ const ranged = typeof store.readTextRange === "function" ? store as RangeStore : undefined;
210
+ const wholeDocumentBytes = Math.max(0, options.wholeDocumentBytes ?? DEFAULT_WHOLE_DOCUMENT_BYTES);
211
+ /** Documents whose saved index did not match their text: the next opening builds it from the text. */
212
+ const rebuildIndex = new Set<string>();
213
+ const scan: ScanSettings = {
214
+ chunkBytes: Math.max(1, Math.trunc(options.scanChunkBytes ?? 1024 * 1024)),
215
+ limiter: new Limiter(Math.max(1, Math.trunc(options.maxConcurrentScans ?? 4))),
216
+ onBroken: (id) => {
217
+ rebuildIndex.add(id);
218
+ forget(id);
219
+ },
220
+ pieces: {
221
+ get: (key, version) => cache.get(key, version) as CachedPiece | undefined,
222
+ set: (key, version, piece) => cache.set(key, version, piece),
223
+ // A quarter of the cache: a few documents can be kept, and no one pushes out all the rest.
224
+ maxDocumentBytes: cacheBytes / 4,
225
+ },
226
+ };
164
227
  const keepOriginals = new Set<DocumentFormat>(options.keepOriginals ?? []);
165
228
  const scannedPdfPages = Math.max(0, Math.trunc(options.scannedPdfPages ?? 30));
166
229
  /** Whether the uploaded file of a document of this format is kept. */
167
230
  const keeps = (format: DocumentFormat) => keepOriginals.has(format) && typeof options.store.putOriginal === "function";
168
231
 
169
- async function load(id: string): Promise<SearchableDocument | undefined> {
170
- const cached = cache.get(id);
171
- if (cached) {
172
- if (Date.parse(cached.meta.expiresAt) > now().getTime()) {
173
- // Refresh its place as most recently used.
174
- cache.delete(id);
175
- cache.set(id, cached);
176
- return cached;
177
- }
178
- cache.delete(id);
232
+ /**
233
+ * The document as the store describes it now: undefined when it was never there, has been
234
+ * deleted (by this server or another one sharing the store), or has expired.
235
+ */
236
+ async function currentMeta(id: string): Promise<DocumentMeta | undefined> {
237
+ if (!isDocumentId(id)) return undefined;
238
+ const meta = await options.store.getMeta(id);
239
+ if (!meta || Date.parse(meta.expiresAt) <= now().getTime()) {
240
+ forget(id);
241
+ return undefined;
242
+ }
243
+ return meta;
244
+ }
245
+
246
+ /**
247
+ * A document ready to read and search. The store is asked first, every time: a kept copy is
248
+ * used only while the store still has the same document. `known` is metadata just read from
249
+ * the store, to save asking twice.
250
+ */
251
+ async function load(id: string, known?: DocumentMeta): Promise<DocumentSource | undefined> {
252
+ const meta = known ?? await currentMeta(id);
253
+ if (!meta) return undefined;
254
+ const version = documentVersion(meta);
255
+ const cached = cache.get(id, version) as DocumentSource | undefined;
256
+ if (cached && !cached.broken) return cached;
257
+ const key = `${id}|${version}`;
258
+ let pending = opening.get(key);
259
+ if (!pending) {
260
+ pending = open(id, meta).finally(() => opening.delete(key));
261
+ opening.set(key, pending);
179
262
  }
180
- const stored = await options.store.get(id);
181
- if (!stored) return undefined;
182
- const document = new SearchableDocument(stored);
183
- cache.set(id, document);
184
- while (cache.size > cacheSize) cache.delete(cache.keys().next().value!);
263
+ const document = await pending;
264
+ if (document) cache.set(id, version, document);
185
265
  return document;
186
266
  }
187
267
 
268
+ /** Reads a document from the store: its index, to read it by range, or all of it. */
269
+ async function open(id: string, meta: DocumentMeta): Promise<DocumentSource | undefined> {
270
+ if (ranged && meta.textBytes > wholeDocumentBytes) {
271
+ const rebuild = rebuildIndex.delete(id);
272
+ return openRangedDocument(ranged, meta, scan, { ignoreSavedIndex: rebuild });
273
+ }
274
+ const stored = await store.get(id);
275
+ return stored ? new SearchableDocument(stored) : undefined;
276
+ }
277
+
278
+ /**
279
+ * What a document contributes to the prompt: its text, or its card. Undefined when it is gone
280
+ * by now. A copy found to disagree with the store is opened again once.
281
+ */
282
+ async function block(id: string, meta: DocumentMeta, whole: boolean, viewable: boolean): Promise<string | undefined> {
283
+ for (let attempt = 0; attempt < 2; attempt++) {
284
+ const document = await load(id, attempt === 0 ? meta : undefined);
285
+ if (!document) return undefined;
286
+ try {
287
+ return whole
288
+ ? renderInline(document.meta, await document.readText())
289
+ : renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable);
290
+ } catch (error) {
291
+ if (!document.broken) {
292
+ // Deleted between the look-up and the read: the same as missing.
293
+ if (!await currentMeta(id)) return undefined;
294
+ throw error;
295
+ }
296
+ }
297
+ }
298
+ return undefined;
299
+ }
300
+
188
301
  async function metaFor(id: string, access: AccessOptions | undefined): Promise<DocumentMeta | undefined> {
189
- if (!isDocumentId(id)) return undefined;
190
- const meta = await options.store.getMeta(id);
302
+ const meta = await currentMeta(id);
191
303
  return meta && allowed(meta, access) ? meta : undefined;
192
304
  }
193
305
 
@@ -236,13 +348,22 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
236
348
  createdAt: created.toISOString(),
237
349
  expiresAt: new Date(created.getTime() + ttlMs).toISOString(),
238
350
  };
351
+ // The line index, so that the text can be read by range: a few bytes a line, built from the
352
+ // UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
353
+ // then loads whole, so that switching to reading by range finds it ready.
354
+ const index = typeof store.putIndex === "function" ? buildTextIndex(text) : undefined;
355
+ const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters
356
+ ? serializeTextIndex(index)
357
+ : undefined;
239
358
  try {
240
- // The file first, the document last: a document is there once its metadata is.
241
- if (keepOriginal) await options.store.putOriginal!(meta.id, input.bytes);
242
- await options.store.put({ meta, text });
359
+ // The files first, the document last: a document is there once its metadata is.
360
+ if (keepOriginal) await store.putOriginal!(meta.id, input.bytes);
361
+ if (savedIndex) await store.putIndex!(meta.id, savedIndex);
362
+ await store.put({ meta, text });
243
363
  } catch (error) {
244
- // Do not leave a file of up to the upload limit behind for a document that does not exist.
245
- if (keepOriginal) await options.store.delete(meta.id).catch(() => undefined);
364
+ // Do not leave a file of up to the upload limit, or a part of one, behind for a document
365
+ // that does not exist.
366
+ await store.delete(meta.id).catch(() => undefined);
246
367
  throw error;
247
368
  }
248
369
  return meta;
@@ -257,7 +378,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
257
378
 
258
379
  async delete(id, access) {
259
380
  if (!await metaFor(id, access)) return false;
260
- cache.delete(id);
381
+ forget(id);
261
382
  return options.store.delete(id);
262
383
  },
263
384
 
@@ -267,27 +388,38 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
267
388
 
268
389
  async prepare(ids, base, access) {
269
390
  const unique = [...new Set(ids)];
270
- const documents: SearchableDocument[] = [];
391
+ let documents: DocumentMeta[] = [];
271
392
  const missing: string[] = [];
272
393
  for (const id of unique) {
273
- const document = isDocumentId(id) ? await load(id) : undefined;
274
- // A document owned by someone else is reported as missing, not as forbidden.
275
- if (document && allowed(document.meta, access)) documents.push(document);
394
+ // A document owned by someone else is reported as missing, not as forbidden, and is not
395
+ // read at all.
396
+ const meta = await metaFor(id, access);
397
+ if (meta) documents.push(meta);
276
398
  else missing.push(id);
277
399
  }
278
- const plan = planDocuments(documents.map((document) => document.meta), budget, base);
279
- const inline = new Set(plan.inline.map((meta) => meta.id));
280
- // Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
281
- const viewable = access?.viewPages && options.store.getOriginal
282
- ? documents.map((document) => document.meta).filter((meta) => meta.format === "pdf" && meta.originalKept)
283
- : [];
284
- const shown = new Set(viewable.map((meta) => meta.id));
285
- const blocks = new Map<string, string>();
286
- for (const document of documents) {
287
- const { id } = document.meta;
288
- blocks.set(id, inline.has(id) ? renderInline(document) : renderCard(document, shown.has(id)));
400
+ // Planning needs only the metadata. The text is read for the documents sent whole, and the
401
+ // first lines for the others. One that is gone by then is missing, and the plan is made again.
402
+ for (;;) {
403
+ const plan = planDocuments(documents, budget, base);
404
+ const inline = new Set(plan.inline.map((meta) => meta.id));
405
+ // Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
406
+ const viewable = access?.viewPages && store.getOriginal
407
+ ? documents.filter((meta) => meta.format === "pdf" && meta.originalKept)
408
+ : [];
409
+ const shown = new Set(viewable.map((meta) => meta.id));
410
+ const blocks = new Map<string, string>();
411
+ const gone: string[] = [];
412
+ for (const meta of documents) {
413
+ const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id));
414
+ if (text === undefined) gone.push(meta.id);
415
+ else blocks.set(meta.id, text);
416
+ }
417
+ if (gone.length === 0) {
418
+ return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable), missing, viewable };
419
+ }
420
+ missing.push(...gone);
421
+ documents = documents.filter((meta) => !gone.includes(meta.id));
289
422
  }
290
- return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable), missing, viewable };
291
423
  },
292
424
 
293
425
  tools(documents, toolOptions = {}) {
package/src/limiter.ts ADDED
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Lets at most `max` tasks hold a slot at once; the others wait their turn, in order. Used for
3
+ * scans of whole documents: on one thread more of them at once do not finish sooner, they only
4
+ * hold more memory.
5
+ */
6
+ export class Limiter {
7
+ private active = 0;
8
+ private readonly waiting: Array<() => void> = [];
9
+
10
+ constructor(private readonly max: number) {}
11
+
12
+ /** Waits for a slot. Call the returned function once to give it back. */
13
+ async acquire(signal?: AbortSignal): Promise<() => void> {
14
+ signal?.throwIfAborted();
15
+ if (this.active < this.max) {
16
+ this.active++;
17
+ return this.releaser();
18
+ }
19
+ await new Promise<void>((resolve, reject) => {
20
+ const onAbort = () => {
21
+ const at = this.waiting.indexOf(start);
22
+ if (at !== -1) this.waiting.splice(at, 1);
23
+ reject(signal!.reason);
24
+ };
25
+ const start = () => {
26
+ signal?.removeEventListener("abort", onAbort);
27
+ resolve();
28
+ };
29
+ this.waiting.push(start);
30
+ signal?.addEventListener("abort", onAbort, { once: true });
31
+ });
32
+ // The slot was handed over by the task that gave it back: `active` already counts it.
33
+ return this.releaser();
34
+ }
35
+
36
+ /** Tasks holding a slot, and tasks waiting for one. */
37
+ get load(): { active: number; waiting: number } {
38
+ return { active: this.active, waiting: this.waiting.length };
39
+ }
40
+
41
+ private releaser(): () => void {
42
+ let released = false;
43
+ return () => {
44
+ if (released) return;
45
+ released = true;
46
+ const next = this.waiting.shift();
47
+ if (next) next();
48
+ else this.active--;
49
+ };
50
+ }
51
+ }