llm-large-files 0.3.5 → 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 (84) hide show
  1. package/CHANGELOG.md +74 -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/extract.d.ts +1 -1
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +204 -22
  9. package/dist/extract.js.map +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/library.d.ts +28 -1
  15. package/dist/library.d.ts.map +1 -1
  16. package/dist/library.js +155 -47
  17. package/dist/library.js.map +1 -1
  18. package/dist/limiter.d.ts +20 -0
  19. package/dist/limiter.d.ts.map +1 -0
  20. package/dist/limiter.js +55 -0
  21. package/dist/limiter.js.map +1 -0
  22. package/dist/map-reduce.d.ts +8 -4
  23. package/dist/map-reduce.d.ts.map +1 -1
  24. package/dist/map-reduce.js +65 -24
  25. package/dist/map-reduce.js.map +1 -1
  26. package/dist/node/handlers.d.ts +9 -0
  27. package/dist/node/handlers.d.ts.map +1 -1
  28. package/dist/node/handlers.js +56 -13
  29. package/dist/node/handlers.js.map +1 -1
  30. package/dist/pdf-pictures.d.ts.map +1 -1
  31. package/dist/pdf-pictures.js +52 -9
  32. package/dist/pdf-pictures.js.map +1 -1
  33. package/dist/plan.d.ts +7 -5
  34. package/dist/plan.d.ts.map +1 -1
  35. package/dist/plan.js +9 -8
  36. package/dist/plan.js.map +1 -1
  37. package/dist/ranged.d.ts +102 -0
  38. package/dist/ranged.d.ts.map +1 -0
  39. package/dist/ranged.js +314 -0
  40. package/dist/ranged.js.map +1 -0
  41. package/dist/search.d.ts +79 -15
  42. package/dist/search.d.ts.map +1 -1
  43. package/dist/search.js +388 -130
  44. package/dist/search.js.map +1 -1
  45. package/dist/stores.d.ts +22 -2
  46. package/dist/stores.d.ts.map +1 -1
  47. package/dist/stores.js +132 -15
  48. package/dist/stores.js.map +1 -1
  49. package/dist/text-index.d.ts +64 -0
  50. package/dist/text-index.d.ts.map +1 -0
  51. package/dist/text-index.js +211 -0
  52. package/dist/text-index.js.map +1 -0
  53. package/dist/text.d.ts +2 -1
  54. package/dist/text.d.ts.map +1 -1
  55. package/dist/text.js +13 -4
  56. package/dist/text.js.map +1 -1
  57. package/dist/tools.d.ts +2 -2
  58. package/dist/tools.d.ts.map +1 -1
  59. package/dist/tools.js +20 -14
  60. package/dist/tools.js.map +1 -1
  61. package/dist/types.d.ts +15 -0
  62. package/dist/types.d.ts.map +1 -1
  63. package/docs/api.md +21 -5
  64. package/docs/configuration.md +50 -4
  65. package/docs/getting-started.md +3 -1
  66. package/docs/how-it-works.md +3 -1
  67. package/docs/security.md +8 -0
  68. package/package.json +7 -3
  69. package/src/cache.ts +83 -0
  70. package/src/extract.ts +198 -19
  71. package/src/index.ts +1 -1
  72. package/src/library.ts +176 -44
  73. package/src/limiter.ts +51 -0
  74. package/src/map-reduce.ts +70 -25
  75. package/src/node/handlers.ts +61 -9
  76. package/src/pdf-pictures.ts +60 -10
  77. package/src/plan.ts +10 -9
  78. package/src/ranged.ts +348 -0
  79. package/src/search.ts +432 -120
  80. package/src/stores.ts +136 -17
  81. package/src/text-index.ts +228 -0
  82. package/src/text.ts +13 -4
  83. package/src/tools.ts +22 -16
  84. package/src/types.ts +15 -0
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
+ }
package/src/map-reduce.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { estimateTokens, jsonBytes } from "./text.js";
2
- import type { SearchableDocument } from "./search.js";
2
+ import { numberLines, scanSource, SearchableDocument, type DocumentSource, type TextChunk } from "./search.js";
3
3
  import type { Budget, GenerateText, ProgressListener } from "./types.js";
4
4
 
5
5
  const NOTHING = "NOTHING RELEVANT";
@@ -20,29 +20,73 @@ export type WholeDocumentResult = {
20
20
  answerTruncated: boolean;
21
21
  };
22
22
 
23
- /** Splits a document into line ranges that each fit one model request. */
24
- export function splitIntoParts(document: SearchableDocument, budget: Budget): Array<{ from: number; to: number }> {
25
- const maxTokens = budget.mapChunkTokens;
26
- const maxBytes = Math.floor(budget.maxRequestBytes * 0.8);
27
- const parts: Array<{ from: number; to: number }> = [];
28
- let from = 1;
29
- let tokens = 0;
30
- let bytes = 0;
31
- for (let line = 1; line <= document.lines.lineCount; line++) {
32
- // Count the "123| " prefix each line carries in the prompt.
33
- const text = `${line}| ${document.lines.line(line)}\n`;
34
- const lineTokens = estimateTokens(text);
35
- const lineBytes = jsonBytes(text);
36
- if (line > from && (tokens + lineTokens > maxTokens || bytes + lineBytes > maxBytes)) {
37
- parts.push({ from, to: line - 1 });
38
- from = line;
39
- tokens = 0;
40
- bytes = 0;
23
+ type Parts = Array<{ from: number; to: number }>;
24
+
25
+ /** Splits a text, fed a piece at a time, into line ranges that each fit one model request. */
26
+ class PartSplitter {
27
+ private readonly maxTokens: number;
28
+ private readonly maxBytes: number;
29
+ private readonly parts: Parts = [];
30
+ private from = 1;
31
+ private tokens = 0;
32
+ private bytes = 0;
33
+
34
+ constructor(budget: Budget) {
35
+ this.maxTokens = budget.mapChunkTokens;
36
+ this.maxBytes = Math.floor(budget.maxRequestBytes * 0.8);
37
+ }
38
+
39
+ add(chunk: TextChunk): void {
40
+ for (let local = 1; local <= chunk.lines.lineCount; local++) {
41
+ const line = chunk.firstLine + local - 1;
42
+ // Count the "123| " prefix each line carries in the prompt.
43
+ const text = `${line}| ${chunk.lines.line(local)}\n`;
44
+ const lineTokens = estimateTokens(text);
45
+ const lineBytes = jsonBytes(text);
46
+ if (line > this.from && (this.tokens + lineTokens > this.maxTokens || this.bytes + lineBytes > this.maxBytes)) {
47
+ this.parts.push({ from: this.from, to: line - 1 });
48
+ this.from = line;
49
+ this.tokens = 0;
50
+ this.bytes = 0;
51
+ }
52
+ this.tokens += lineTokens;
53
+ this.bytes += lineBytes;
41
54
  }
42
- tokens += lineTokens;
43
- bytes += lineBytes;
44
55
  }
45
- if (document.lines.lineCount >= from) parts.push({ from, to: document.lines.lineCount });
56
+
57
+ finish(lineCount: number): Parts {
58
+ if (lineCount >= this.from) this.parts.push({ from: this.from, to: lineCount });
59
+ return this.parts;
60
+ }
61
+ }
62
+
63
+ /** Splits a document held in memory into line ranges that each fit one model request. */
64
+ export function splitIntoParts(document: SearchableDocument, budget: Budget): Parts {
65
+ const splitter = new PartSplitter(budget);
66
+ splitter.add(document.wholeChunk());
67
+ return splitter.finish(document.lines.lineCount);
68
+ }
69
+
70
+ /** Parts already worked out, by document and budget: counting them reads the whole text. */
71
+ const knownParts = new WeakMap<DocumentSource, Map<string, Parts>>();
72
+
73
+ /** `splitIntoParts` for any document, worked out once per document object and budget. */
74
+ export async function partsOf(source: DocumentSource, budget: Budget, signal?: AbortSignal): Promise<Parts> {
75
+ const key = `${budget.mapChunkTokens}|${budget.maxRequestBytes}`;
76
+ const known = knownParts.get(source)?.get(key);
77
+ if (known) return known;
78
+ let parts: Parts;
79
+ if (source instanceof SearchableDocument) {
80
+ parts = splitIntoParts(source, budget);
81
+ } else {
82
+ const splitter = new PartSplitter(budget);
83
+ await scanSource(source, (chunk) => {
84
+ splitter.add(chunk);
85
+ }, signal);
86
+ parts = splitter.finish(source.lineCount);
87
+ }
88
+ if (!knownParts.has(source)) knownParts.set(source, new Map());
89
+ knownParts.get(source)!.set(key, parts);
46
90
  return parts;
47
91
  }
48
92
 
@@ -88,7 +132,7 @@ async function ask(
88
132
  * then the notes are combined ("reduce"), in several rounds if the notes are still too large.
89
133
  */
90
134
  export async function analyzeWholeDocument(options: {
91
- document: SearchableDocument;
135
+ document: DocumentSource;
92
136
  task: string;
93
137
  generate: GenerateText;
94
138
  budget: Budget;
@@ -98,7 +142,7 @@ export async function analyzeWholeDocument(options: {
98
142
  }): Promise<WholeDocumentResult> {
99
143
  const { document, task, generate, budget, onProgress, signal } = options;
100
144
  const name = document.meta.name;
101
- const parts = splitIntoParts(document, budget);
145
+ const parts = await partsOf(document, budget, signal);
102
146
  if (parts.length > budget.maxMapChunks) {
103
147
  throw new Error(`Reading all of ${name} needs ${parts.length} model calls, over the limit of ${budget.maxMapChunks}. Use search_document to narrow the question first.`);
104
148
  }
@@ -112,6 +156,7 @@ export async function analyzeWholeDocument(options: {
112
156
  let text: string;
113
157
  let read = true;
114
158
  try {
159
+ const part = numberLines(await document.readLines(from, to), from);
115
160
  const reply = await ask(generate, {
116
161
  system: "You read one part of a larger document and take notes for a later step that combines the notes from every part.",
117
162
  prompt: [
@@ -121,7 +166,7 @@ export async function analyzeWholeDocument(options: {
121
166
  `Write concise notes on everything in this part that is relevant to the task. Keep exact names, numbers, and quotes that matter. Cite line numbers like (L123). If nothing in this part is relevant, reply exactly: ${NOTHING}`,
122
167
  "",
123
168
  "<part>",
124
- document.lines.numbered(from, to),
169
+ part,
125
170
  "</part>",
126
171
  ].join("\n"),
127
172
  maxOutputTokens: PART_OUTPUT_TOKENS,
@@ -6,10 +6,19 @@ export type DocumentHandlerOptions = {
6
6
  /**
7
7
  * The signed-in user for this request. When set, uploads are owned by that user and other
8
8
  * users cannot read or delete them. Return undefined to allow anonymous access.
9
+ *
10
+ * To refuse a request, throw an error with a `status` (or `statusCode`) between 400 and 599, as
11
+ * the `http-errors` package makes: the handler answers with that status and the error's message.
12
+ * Any other error is answered with a 500 that does not repeat its message. It is called before
13
+ * the upload is read, so a refused upload is not buffered.
9
14
  */
10
15
  getOwner?: (request: IncomingMessage) => string | undefined | Promise<string | undefined>;
11
16
  };
12
17
 
18
+ /**
19
+ * The handlers answer every request themselves, errors included, and never reject: they can be
20
+ * called without a `catch`, from `node:http` or from Express 4.
21
+ */
13
22
  export type DocumentHandlers = {
14
23
  /** POST: the body is the raw file. Name it with an `X-File-Name` header (URI-encoded) or `?name=`. */
15
24
  upload(request: IncomingMessage, response: ServerResponse): Promise<void>;
@@ -25,6 +34,39 @@ class HttpError extends Error {
25
34
  }
26
35
  }
27
36
 
37
+ /** The HTTP status an error carries: this module's, or one `getOwner` throws (`http-errors` style). */
38
+ function statusOf(error: unknown): number | undefined {
39
+ if (error instanceof HttpError) return error.status;
40
+ if (!(error instanceof Error)) return undefined;
41
+ const { status, statusCode } = error as Error & { status?: unknown; statusCode?: unknown };
42
+ const value = typeof status === "number" ? status : statusCode;
43
+ return typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599 ? value : undefined;
44
+ }
45
+
46
+ /**
47
+ * The code of a Node system error (a file or network call that failed, as `ENOSPC`). Its message
48
+ * names server paths or hosts, so only the code is passed on.
49
+ */
50
+ function systemErrorCode(error: unknown): string | undefined {
51
+ const { code, syscall } = (error ?? {}) as { code?: unknown; syscall?: unknown };
52
+ return typeof code === "string" && typeof syscall === "string" ? code : undefined;
53
+ }
54
+
55
+ /**
56
+ * Answers a failed request. An error with a status keeps its status and message. Anything else is
57
+ * the server's trouble: a 500 that says what failed and, for a system error, its code.
58
+ */
59
+ function fail(response: ServerResponse, error: unknown, failed: string, tooLarge: string): void {
60
+ const status = statusOf(error);
61
+ if (status !== undefined) {
62
+ const message = status === 413 ? tooLarge : error instanceof Error && error.message ? error.message : `${failed}.`;
63
+ send(response, status, { error: message });
64
+ return;
65
+ }
66
+ const code = systemErrorCode(error);
67
+ send(response, 500, { error: code ? `${failed} (${code}).` : `${failed}.` });
68
+ }
69
+
28
70
  function send(response: ServerResponse, status: number, value: unknown): void {
29
71
  if (response.headersSent) return;
30
72
  response.statusCode = status;
@@ -85,10 +127,11 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
85
127
  const url = new URL(request.url ?? "/", "http://localhost");
86
128
  const name = header(request, "x-file-name").trim() || url.searchParams.get("name")?.trim() || "";
87
129
  if (!name) throw new HttpError(400, "Name the file with an X-File-Name header or a ?name= query parameter.");
130
+ // Who is asking comes first: a refused upload is not read into memory.
131
+ const currentOwner = await owner(request);
88
132
  const bytes = await readBody(request, files.maxUploadBytes);
89
133
  const contentType = header(request, "content-type");
90
134
  const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
91
- const currentOwner = await owner(request);
92
135
  let meta;
93
136
  try {
94
137
  meta = await files.ingest({
@@ -98,25 +141,34 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
98
141
  ...(currentOwner !== undefined ? { owner: currentOwner } : {}),
99
142
  });
100
143
  } catch (error) {
144
+ // A file that cannot be read is the client's 422. A store that fails is the server's 500.
145
+ if (statusOf(error) !== undefined || systemErrorCode(error) !== undefined) throw error;
101
146
  throw new HttpError(422, error instanceof Error ? error.message : String(error));
102
147
  }
103
148
  send(response, 201, toDocumentSummary(meta));
104
149
  } catch (error) {
105
- if (error instanceof HttpError) send(response, error.status, { error: error.status === 413 ? tooLarge : error.message });
106
- else send(response, 500, { error: error instanceof Error ? error.message : "Upload failed." });
150
+ fail(response, error, "Upload failed", tooLarge);
107
151
  }
108
152
  },
109
153
 
110
154
  async get(request, response, id) {
111
- const currentOwner = await owner(request);
112
- const meta = await files.getMeta(id, currentOwner !== undefined ? { owner: currentOwner } : {});
113
- if (meta) send(response, 200, toDocumentSummary(meta));
114
- else send(response, 404, { error: "This file is no longer available." });
155
+ try {
156
+ const currentOwner = await owner(request);
157
+ const meta = await files.getMeta(id, currentOwner !== undefined ? { owner: currentOwner } : {});
158
+ if (meta) send(response, 200, toDocumentSummary(meta));
159
+ else send(response, 404, { error: "This file is no longer available." });
160
+ } catch (error) {
161
+ fail(response, error, "The file could not be looked up", tooLarge);
162
+ }
115
163
  },
116
164
 
117
165
  async remove(request, response, id) {
118
- const currentOwner = await owner(request);
119
- send(response, 200, { deleted: await files.delete(id, currentOwner !== undefined ? { owner: currentOwner } : {}) });
166
+ try {
167
+ const currentOwner = await owner(request);
168
+ send(response, 200, { deleted: await files.delete(id, currentOwner !== undefined ? { owner: currentOwner } : {}) });
169
+ } catch (error) {
170
+ fail(response, error, "The file could not be deleted", tooLarge);
171
+ }
120
172
  },
121
173
  };
122
174
  }