llm-large-files 0.8.0 → 0.8.2

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 (63) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +2 -0
  3. package/dist/aggregate.d.ts +103 -0
  4. package/dist/aggregate.d.ts.map +1 -0
  5. package/dist/aggregate.js +651 -0
  6. package/dist/aggregate.js.map +1 -0
  7. package/dist/evidence.d.ts.map +1 -1
  8. package/dist/evidence.js +17 -0
  9. package/dist/evidence.js.map +1 -1
  10. package/dist/extract.d.ts +8 -1
  11. package/dist/extract.d.ts.map +1 -1
  12. package/dist/extract.js +40 -2
  13. package/dist/extract.js.map +1 -1
  14. package/dist/library.d.ts +7 -0
  15. package/dist/library.d.ts.map +1 -1
  16. package/dist/library.js +112 -18
  17. package/dist/library.js.map +1 -1
  18. package/dist/limiter.d.ts +2 -2
  19. package/dist/limiter.js +2 -2
  20. package/dist/node/handlers.d.ts +15 -0
  21. package/dist/node/handlers.d.ts.map +1 -1
  22. package/dist/node/handlers.js +155 -36
  23. package/dist/node/handlers.js.map +1 -1
  24. package/dist/plan.d.ts +3 -1
  25. package/dist/plan.d.ts.map +1 -1
  26. package/dist/plan.js +17 -1
  27. package/dist/plan.js.map +1 -1
  28. package/dist/quality.d.ts +16 -0
  29. package/dist/quality.d.ts.map +1 -0
  30. package/dist/quality.js +157 -0
  31. package/dist/quality.js.map +1 -0
  32. package/dist/ranged.d.ts +7 -0
  33. package/dist/ranged.d.ts.map +1 -1
  34. package/dist/ranged.js +8 -1
  35. package/dist/ranged.js.map +1 -1
  36. package/dist/tools.d.ts +9 -0
  37. package/dist/tools.d.ts.map +1 -1
  38. package/dist/tools.js +258 -5
  39. package/dist/tools.js.map +1 -1
  40. package/dist/types.d.ts +20 -0
  41. package/dist/types.d.ts.map +1 -1
  42. package/docs/guides/deployment.md +27 -6
  43. package/docs/guides/storage.md +5 -2
  44. package/docs/guides/web-app.md +14 -3
  45. package/docs/how-it-works.md +7 -0
  46. package/docs/measurements.md +20 -0
  47. package/docs/reference/library.md +22 -8
  48. package/docs/reference/node.md +30 -15
  49. package/docs/reference/tools.md +99 -1
  50. package/docs/security.md +15 -6
  51. package/docs/troubleshooting.md +28 -0
  52. package/package.json +1 -1
  53. package/src/aggregate.ts +674 -0
  54. package/src/evidence.ts +17 -0
  55. package/src/extract.ts +37 -2
  56. package/src/library.ts +116 -16
  57. package/src/limiter.ts +2 -2
  58. package/src/node/handlers.ts +159 -32
  59. package/src/plan.ts +17 -1
  60. package/src/quality.ts +146 -0
  61. package/src/ranged.ts +8 -1
  62. package/src/tools.ts +249 -5
  63. package/src/types.ts +17 -0
package/src/evidence.ts CHANGED
@@ -96,6 +96,13 @@ export function evidenceOf(call: ToolCall, result: ToolResult): Evidence | undef
96
96
  }
97
97
  case TOOL_NAMES.analyze:
98
98
  return { ...entry, whole: true, ...(typeof call.args.task === "string" ? { query: call.args.task } : {}) };
99
+ case TOOL_NAMES.aggregate: {
100
+ // The rows read are all of the table; what can be cited is the header and each group's first rows.
101
+ const groups = (Array.isArray(result.groups) ? result.groups : []) as Array<{ lines?: unknown }>;
102
+ const lines = groups.flatMap((group) => (Array.isArray(group.lines) ? group.lines.filter((line): line is number => typeof line === "number") : []));
103
+ const header = typeof result.header_line === "number" && result.header_line > 0 ? [result.header_line] : [];
104
+ return withRanges([...header, ...lines].map((line): NumberRange => [line, line]), []);
105
+ }
99
106
  case TOOL_NAMES.view:
100
107
  return withRanges([], defined([rangeOf(result.pages)]));
101
108
  default:
@@ -147,6 +154,16 @@ export function stubResult(call: ToolCall, result: ToolResult, hadFiles = false)
147
154
  ...(Array.isArray(result.groups) ? { groups: result.groups.slice(0, KEPT_GROUPS) } : {}),
148
155
  note: "The results of this search were shown to you earlier and were dropped from the conversation to make room. Read the lines listed here with read_document, or search again, if you need them.",
149
156
  };
157
+ case TOOL_NAMES.aggregate:
158
+ // Counts cannot be read again from lines: the largest groups are kept as they are.
159
+ return {
160
+ ...base,
161
+ ...(typeof result.table === "string" ? { table: result.table } : {}),
162
+ ...(typeof result.rows_matched === "number" ? { rows_matched: result.rows_matched } : {}),
163
+ ...(typeof result.total_groups === "number" ? { total_groups: result.total_groups } : {}),
164
+ ...(Array.isArray(result.groups) ? { groups: result.groups.slice(0, KEPT_GROUPS) } : {}),
165
+ note: "This result was shown to you earlier and was shortened to make room: the largest groups are kept. Run aggregate_table again for the others.",
166
+ };
150
167
  case TOOL_NAMES.analyze: {
151
168
  const answer = typeof result.answer === "string" ? result.answer : "";
152
169
  return {
package/src/extract.ts CHANGED
@@ -43,12 +43,47 @@ const MIME_FORMATS: Record<string, DocumentFormat> = {
43
43
  * come from the upload: only the tables' own keys count, not "constructor" or "__proto__", which
44
44
  * every object has.
45
45
  */
46
- export function detectFormat(name: string, mimeType: string): DocumentFormat {
46
+ export function detectFormat(name: string, mimeType: string, bytes?: Uint8Array): DocumentFormat {
47
47
  const extension = name.toLowerCase().split(".").at(-1) ?? "";
48
48
  const mime = mimeType.toLowerCase();
49
- return (Object.hasOwn(EXTENSION_FORMATS, extension) ? EXTENSION_FORMATS[extension] : undefined)
49
+ const named = (Object.hasOwn(EXTENSION_FORMATS, extension) ? EXTENSION_FORMATS[extension] : undefined)
50
50
  ?? (Object.hasOwn(MIME_FORMATS, mime) ? MIME_FORMATS[mime] : undefined)
51
51
  ?? "text";
52
+ // A name that says text ("notes.txt") is taken at its word.
53
+ return named === "text" && bytes && extension !== "txt" ? sniffFormat(bytes) ?? named : named;
54
+ }
55
+
56
+ /** Where the part names of an Office file are looked for: its directory at the end, and its first parts. */
57
+ const SNIFFED_HEAD = 64 * 1024;
58
+ const SNIFFED_TAIL = 1024 * 1024;
59
+
60
+ /**
61
+ * The format of a file whose name and type say nothing (no extension, "application/octet-stream"),
62
+ * from its bytes: a PDF by its header, a DOCX, PPTX or XLSX by the names of its parts, an HTML page
63
+ * by its first tag. Undefined for anything else, which is read as text. A DOCX sent without its
64
+ * extension was told "This file is a ZIP archive".
65
+ */
66
+ export function sniffFormat(bytes: Uint8Array): DocumentFormat | undefined {
67
+ const head = latin1(bytes.subarray(0, 1_024));
68
+ const start = head.replace(/^\xef\xbb\xbf/, "").trimStart();
69
+ if (start.startsWith("%PDF-")) return "pdf";
70
+ if (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) {
71
+ const names = latin1(bytes.subarray(0, SNIFFED_HEAD)) + latin1(bytes.subarray(Math.max(SNIFFED_HEAD, bytes.length - SNIFFED_TAIL)));
72
+ if (names.includes("word/document.xml")) return "docx";
73
+ if (names.includes("ppt/presentation.xml") || names.includes("ppt/slides/")) return "pptx";
74
+ if (names.includes("xl/workbook.xml")) return "xlsx";
75
+ return undefined;
76
+ }
77
+ const tag = start.slice(0, 64).toLowerCase();
78
+ if (tag.startsWith("<!doctype html") || tag.startsWith("<html")) return "html";
79
+ return undefined;
80
+ }
81
+
82
+ /** Bytes as Latin-1 text, one character a byte: enough to find ASCII names in them. */
83
+ function latin1(bytes: Uint8Array): string {
84
+ let out = "";
85
+ for (let at = 0; at < bytes.length; at += 8_192) out += String.fromCharCode(...bytes.subarray(at, at + 8_192));
86
+ return out;
52
87
  }
53
88
 
54
89
  export type PdfExtractorOptions = {
package/src/library.ts CHANGED
@@ -7,8 +7,9 @@ import { EventEmitter, eventErrorOf, newRunId, type IngestEvent, type IngestStag
7
7
  import { detectFormat, extractText } from "./extract.js";
8
8
  import { Limiter } from "./limiter.js";
9
9
  import { TimeSlicer } from "./pause.js";
10
- import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline, type WholeRead } from "./plan.js";
11
- import { openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
10
+ import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline, TABLE_FORMATS, type WholeRead } from "./plan.js";
11
+ import { measureQuality, type TextQuality } from "./quality.js";
12
+ import { DocumentGoneError, openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
12
13
  import { numberLines, SearchableDocument, type DocumentSource } from "./search.js";
13
14
  import { DOCUMENT_ID_PATTERN } from "./stores.js";
14
15
  import { buildTextIndexInSlices, canSerialize, serializeTextIndex } from "./text-index.js";
@@ -110,6 +111,13 @@ export type LargeFilesOptions = {
110
111
  * run at once in this process. The others wait their turn. Defaults to 4.
111
112
  */
112
113
  maxConcurrentScans?: number;
114
+ /**
115
+ * How many ingests do their work at once in this library. The others wait their turn, in order,
116
+ * and their time limit (`ingestTimeoutMs`) starts when their turn comes. An ingest holds about five
117
+ * times its file in memory while it works, and ingests at once share one thread: more of them do
118
+ * not finish sooner. `Infinity` for no limit (as before 0.8.2). Defaults to 2. New in 0.8.2.
119
+ */
120
+ maxConcurrentIngests?: number;
113
121
  /** Clock override, for tests. */
114
122
  now?: () => Date;
115
123
  };
@@ -349,6 +357,56 @@ export const DEFAULT_INGEST_TIMEOUT_MS = 120_000;
349
357
  /** The longest a Node.js timer waits: a longer one fires at once. A limit past it is no limit. */
350
358
  const LONGEST_TIMER_MS = 2 ** 31 - 1;
351
359
 
360
+ /** `value` copied through JSON: new strings, none of them a piece of a larger one. */
361
+ function jsonCopy<T>(value: T): T {
362
+ return JSON.parse(JSON.stringify(value)) as T;
363
+ }
364
+
365
+ /** `work`, or the error `late` makes once `ms` have passed without it settling. */
366
+ function settleWithin<T>(work: Promise<T>, ms: number, late: () => Error): Promise<T> {
367
+ let timer: ReturnType<typeof setTimeout> | undefined;
368
+ const timeUp = new Promise<never>((_, reject) => {
369
+ timer = setTimeout(() => reject(late()), ms);
370
+ });
371
+ return Promise.race([work, timeUp]).finally(() => clearTimeout(timer));
372
+ }
373
+
374
+ /**
375
+ * The turn of one ingest (`maxConcurrentIngests`). It is given back when the ingest ends; when the
376
+ * ingest gave up on work that goes on (an extractor that does not stop on the signal, such as a
377
+ * PDF being parsed when its caller left), once that work ends, or `capMs` later when it does not.
378
+ * (Store writes that do not end fail the ingest after `capMs`: see `ingestFile`.)
379
+ */
380
+ class IngestSlot {
381
+ private released = false;
382
+ private timer: ReturnType<typeof setTimeout> | undefined;
383
+
384
+ constructor(private readonly release: () => void, private readonly capMs: number) {}
385
+
386
+ private readonly free = () => {
387
+ if (this.released) return;
388
+ this.released = true;
389
+ clearTimeout(this.timer);
390
+ this.release();
391
+ };
392
+
393
+ /**
394
+ * Gives the turn back `capMs` from now at the latest. The timer keeps the process alive: work
395
+ * that never ends may hold nothing that does, and ingests waiting for the turn would be lost.
396
+ */
397
+ limit(): void {
398
+ if (this.released || this.timer !== undefined) return;
399
+ this.timer = setTimeout(this.free, this.capMs);
400
+ }
401
+
402
+ /** The ingest is over: the turn goes back now, or once `abandoned` ends (`capMs` at the latest). */
403
+ end(abandoned?: Promise<unknown>): void {
404
+ if (!abandoned) return this.free();
405
+ abandoned.then(this.free, this.free);
406
+ this.limit();
407
+ }
408
+ }
409
+
352
410
  /** A time limit in the words of a message: "500 ms", "45 s", "2 min". */
353
411
  function formatDuration(ms: number): string {
354
412
  if (ms < 1_000) return `${Math.max(1, Math.round(ms))} ms`;
@@ -545,6 +603,11 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
545
603
  },
546
604
  };
547
605
  const keepOriginals = new Set<DocumentFormat>(options.keepOriginals ?? []);
606
+ /** The ingests doing their work, and those waiting their turn (`maxConcurrentIngests`). */
607
+ const ingests = new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentIngests", options.maxConcurrentIngests, 2))));
608
+ /** How long work an ingest waits on, or gave up on, may keep its turn (see `IngestSlot`). */
609
+ const slotCapMs = ingestTimeoutMs > 0 && ingestTimeoutMs <= LONGEST_TIMER_MS ? ingestTimeoutMs : DEFAULT_INGEST_TIMEOUT_MS;
610
+
548
611
  const scannedPdfPages = Math.max(0, Math.trunc(numberOption("scannedPdfPages", options.scannedPdfPages, 30)));
549
612
  /** Whether the uploaded file of a document of this format is kept. */
550
613
  const keeps = (format: DocumentFormat) => keepOriginals.has(format) && typeof options.store.putOriginal === "function";
@@ -610,6 +673,9 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
610
673
  ? renderInline(document.meta, await document.readText())
611
674
  : renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, wholeRead);
612
675
  } catch (error) {
676
+ // The text is gone while its metadata is still there (removed outside the library): the
677
+ // same as missing. It was a plain Error, which failed the whole question.
678
+ if (error instanceof DocumentGoneError) return undefined;
613
679
  if (!document.broken) {
614
680
  // Deleted between the look-up and the read: the same as missing.
615
681
  if (!await currentMeta(id)) return undefined;
@@ -637,11 +703,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
637
703
  detected: DocumentFormat,
638
704
  progress: IngestProgress | undefined,
639
705
  storeFailed: () => void,
706
+ work: { abandoned?: Promise<unknown> },
640
707
  ): Promise<DocumentMeta> {
641
- if (input.bytes.byteLength === 0) throw new Error(`${name} is empty.`);
642
- if (input.bytes.byteLength > maxUploadBytes) {
643
- throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
644
- }
645
708
  let format = detected;
646
709
  const { signal, dispose } = ingestSignal(name, input.signal, ingestTimeoutMs);
647
710
  // Each long step works in slices, with pauses for other requests: one large upload no longer
@@ -655,6 +718,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
655
718
  let measured: Awaited<ReturnType<typeof measureText>>;
656
719
  let outline: DocumentMeta["outline"];
657
720
  let logProfile: DocumentMeta["logProfile"];
721
+ let quality: TextQuality = {};
658
722
  let index: Awaited<ReturnType<typeof buildTextIndexInSlices>> | undefined;
659
723
  try {
660
724
  signal.throwIfAborted();
@@ -666,7 +730,9 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
666
730
  let extracting = true;
667
731
  let extracted: ExtractedText;
668
732
  try {
669
- extracted = await untilAborted(extractText(input.bytes, {
733
+ // Kept, so that an ingest that stops waiting for it (its time is up, its caller left)
734
+ // keeps its turn until the extractor is done too: it still holds memory.
735
+ const extraction = extractText(input.bytes, {
670
736
  name,
671
737
  mimeType,
672
738
  format,
@@ -676,7 +742,10 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
676
742
  maxTextBytes,
677
743
  maxPages: maxPdfPages,
678
744
  ...(progress ? { onProgress: (report: ExtractProgress) => { if (extracting) progress.extracted(report); } } : {}),
679
- }, options.extractors), signal);
745
+ }, options.extractors);
746
+ work.abandoned = extraction;
747
+ extracted = await untilAborted(extraction, signal);
748
+ work.abandoned = undefined;
680
749
  } finally {
681
750
  extracting = false;
682
751
  }
@@ -694,6 +763,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
694
763
  if (measured.utf8 > maxTextBytes) throw tooMuchText(name, maxTextBytes);
695
764
  outline = await buildOutlineInSlices(lines, format, slicer);
696
765
  logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
766
+ quality = await measureQuality(lines, format, slicer);
697
767
  // The line index, so that the text can be read by range: a few bytes a line, built from the
698
768
  // UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
699
769
  // then loads whole, so that switching to reading by range finds it ready.
@@ -708,7 +778,11 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
708
778
  const created = now();
709
779
  const expires = created.getTime() + ttlMs;
710
780
  const keepOriginal = keeps(format);
711
- const meta: DocumentMeta = {
781
+ // A copy: the outline's headings and the log's timestamps are pieces of the text, and a piece
782
+ // keeps the whole text in memory as long as it is held. A meta an application kept held its
783
+ // text: 25 MB of heap for a log of 10 MB in Hebrew, 194 MB for one of 100 MB. Copied through
784
+ // JSON, as a store that keeps it as JSON gives it back.
785
+ const meta: DocumentMeta = jsonCopy<DocumentMeta>({
712
786
  id: `doc_${randomUUID().replaceAll("-", "")}`,
713
787
  ...(input.owner !== undefined ? { owner: input.owner } : {}),
714
788
  name,
@@ -726,10 +800,11 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
726
800
  ...(keepOriginal ? { originalKept: true } : {}),
727
801
  outline,
728
802
  ...(logProfile ? { logProfile } : {}),
803
+ ...quality,
729
804
  createdAt: created.toISOString(),
730
805
  // Never, for a time to live without end (or one that runs past what a date can hold).
731
806
  expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
732
- };
807
+ });
733
808
  const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
734
809
  ? serializeTextIndex(index)
735
810
  : undefined;
@@ -747,8 +822,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
747
822
  throw error;
748
823
  }
749
824
  };
750
- try {
751
- // The files first, the document last: a document is there once its metadata is.
825
+ // The files first, the document last: a document is there once its metadata is.
826
+ const storing = (async () => {
752
827
  if (keepOriginal) {
753
828
  await store.putOriginal!(meta.id, input.bytes);
754
829
  wrote(false);
@@ -759,10 +834,17 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
759
834
  }
760
835
  await store.put({ meta, text });
761
836
  wrote(true);
837
+ })();
838
+ try {
839
+ // A store that does not answer fails the ingest after `slotCapMs`: it held the ingest's turn,
840
+ // and the upload handler's room for the file, for as long as it did not answer.
841
+ await settleWithin(storing, slotCapMs, () => new Error(`The store did not finish writing ${name} within ${formatDuration(slotCapMs)}.`));
762
842
  } catch (error) {
763
843
  // Do not leave a file of up to the upload limit, or a part of one, behind for a document
764
- // that does not exist.
765
- await store.delete(meta.id).catch(() => undefined);
844
+ // that does not exist: once the writes have ended, when they have not yet. The removal is not
845
+ // waited for longer than the writes were.
846
+ const removal = storing.then(() => store.delete(meta.id), () => store.delete(meta.id)).catch(() => undefined);
847
+ await settleWithin(removal, slotCapMs, () => new Error("")).catch(() => undefined);
766
848
  if (listenerFailed?.error !== error) {
767
849
  noteStoreWriteFailure(error);
768
850
  storeFailed();
@@ -796,12 +878,28 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
796
878
  checkOwner(input.owner);
797
879
  const name = cleanFileName(input.name);
798
880
  const mimeType = input.mimeType?.trim() || "application/octet-stream";
799
- const format = detectFormat(name, mimeType);
881
+ // A file whose name and type say nothing is known by its bytes: a PDF, an Office file, a page.
882
+ const format = detectFormat(name, mimeType, input.bytes instanceof Uint8Array ? input.bytes : undefined);
800
883
  // Progress is worked out only for someone who listens.
801
884
  const progress = events.active ? new IngestProgress(events) : undefined;
802
885
  let meta: DocumentMeta;
803
886
  try {
804
- meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true));
887
+ // Refused at once, without waiting for a turn.
888
+ if (input.bytes.byteLength === 0) throw new Error(`${name} is empty.`);
889
+ if (input.bytes.byteLength > maxUploadBytes) {
890
+ throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
891
+ }
892
+ // Its turn (`maxConcurrentIngests`): a caller that gives up while it waits gets its own
893
+ // reason, as it would once the work had begun. (An ingest started inside another of this
894
+ // library, by an extractor of your own, waits for a turn like any other. Telling it apart
895
+ // with AsyncLocalStorage made pdf.js about five times slower on Node 22, for every PDF.)
896
+ const slot = new IngestSlot(await ingests.acquire(input.signal), slotCapMs);
897
+ const work: { abandoned?: Promise<unknown> } = {};
898
+ try {
899
+ meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true), work);
900
+ } finally {
901
+ slot.end(work.abandoned);
902
+ }
805
903
  } catch (error) {
806
904
  // A store that failed, and a caller that gave up (its own reason), are passed on as they
807
905
  // are; a file that could not be read is told with a code.
@@ -911,6 +1009,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
911
1009
  ...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal } : {}),
912
1010
  // `analyze_whole_document` is declared only when it can read at least one of the documents.
913
1011
  wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
1012
+ // `aggregate_table` only when one may hold a table.
1013
+ tables: documents.some((meta) => TABLE_FORMATS.has(meta.format)),
914
1014
  ...rest,
915
1015
  });
916
1016
  },
package/src/limiter.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
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.
3
+ * scans of whole documents and for ingests: on one thread more of them at once do not finish
4
+ * sooner, they only hold more memory.
5
5
  */
6
6
  export class Limiter {
7
7
  private active = 0;
@@ -21,6 +21,21 @@ export type DocumentHandlerOptions = {
21
21
  * the upload is read, so a refused upload is not buffered.
22
22
  */
23
23
  getOwner?: (request: IncomingMessage) => string | undefined | Promise<string | undefined>;
24
+ /**
25
+ * The most bytes of uploads these handlers hold at once: an upload is held whole in memory from
26
+ * the moment its body is read until its ingest ends. An upload that would pass it is answered 503
27
+ * with `Retry-After` before its body is read, while another upload is held: one upload alone is
28
+ * always taken. An upload counts its `Content-Length` (or `maxUploadBytes` without one, then its
29
+ * size once read). `Infinity` for no limit (as before 0.8.2). Defaults to twice `maxUploadBytes`.
30
+ * New in 0.8.2.
31
+ */
32
+ maxPendingUploadBytes?: number;
33
+ /**
34
+ * An upload whose body stops arriving for this many milliseconds is answered 408, its connection
35
+ * closed and its room given back: a client that sends its headers and then nothing, or stalls,
36
+ * holds its room no longer. 0 or `Infinity` for no limit. Defaults to 30,000. New in 0.8.2.
37
+ */
38
+ uploadIdleTimeoutMs?: number;
24
39
  };
25
40
 
26
41
  /**
@@ -48,7 +63,8 @@ export type DocumentHandlers = {
48
63
  };
49
64
 
50
65
  class HttpError extends Error {
51
- constructor(readonly status: number, message: string) {
66
+ /** `close`: answer, then close the connection, without waiting for the rest of the body. */
67
+ constructor(readonly status: number, message: string, readonly close = false) {
52
68
  super(message);
53
69
  }
54
70
  }
@@ -164,6 +180,9 @@ async function streamIngest(files: LargeFiles, input: IngestInput, response: Ser
164
180
  // Each message is the event itself, as for a question: `ingest.finish` holds the summary a 201
165
181
  // answer would (`document`), `ingest.error` the message and status a JSON answer would (`error`).
166
182
  await writeSseEvents(response, events());
183
+ // A client that went away ends the stream at once, while the ingest stops (a store write may still
184
+ // be under way): the upload is held until then, as on the JSON path.
185
+ await stream.result.catch(() => undefined);
167
186
  }
168
187
 
169
188
  /**
@@ -192,8 +211,33 @@ function header(request: IncomingMessage, name: string): string {
192
211
  }
193
212
  }
194
213
 
195
- /** Reads the raw body, or uses one a framework already parsed into a Buffer (e.g. express.raw()). */
196
- async function readBody(request: IncomingMessage, limit: number): Promise<Uint8Array> {
214
+ /** The longest a timer can wait. */
215
+ const LONGEST_TIMER_MS = 2_147_483_647;
216
+
217
+ /** `next`, or a 408 once `idleMs` pass without it. */
218
+ function withinIdle<T>(next: Promise<T>, idleMs: number): Promise<T> {
219
+ // Once the upload is refused, the read it waited on ends with the connection: nobody awaits it.
220
+ next.catch(() => undefined);
221
+ let settled = false;
222
+ let timer: ReturnType<typeof setTimeout> | undefined;
223
+ const idle = new Promise<never>((_, reject) => {
224
+ const after = idleMs >= 1_000 ? `${Math.round(idleMs / 1_000)} s` : `${idleMs} ms`;
225
+ timer = setTimeout(() => {
226
+ // After the thread was held longer than `idleMs`, timers run before the data that came in the
227
+ // meantime is read: it is read first, in this turn of the loop, and the upload goes on.
228
+ setImmediate(() => {
229
+ if (!settled) reject(new HttpError(408, `The upload stopped arriving: nothing came for ${after}. Send it again.`, true));
230
+ });
231
+ }, idleMs);
232
+ });
233
+ return Promise.race([next.finally(() => (settled = true)), idle]).finally(() => clearTimeout(timer));
234
+ }
235
+
236
+ /**
237
+ * Reads the raw body, or uses one a framework already parsed into a Buffer (e.g. express.raw()).
238
+ * `idleMs`: the longest wait for the next piece of the body (0 for no limit).
239
+ */
240
+ async function readBody(request: IncomingMessage, limit: number, idleMs = 0): Promise<Uint8Array> {
197
241
  const parsed = (request as IncomingMessage & { body?: unknown }).body;
198
242
  if (parsed instanceof Uint8Array) {
199
243
  if (parsed.byteLength > limit) throw new HttpError(413, "");
@@ -208,16 +252,60 @@ async function readBody(request: IncomingMessage, limit: number): Promise<Uint8A
208
252
  let size = 0;
209
253
  // Leaving the loop early must not destroy the request: the rest of the body is drained after
210
254
  // the answer (see `drain`), which a destroyed request would not do.
211
- for await (const chunk of request.iterator({ destroyOnReturn: false })) {
212
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
213
- size += buffer.byteLength;
214
- if (size > limit) throw new HttpError(413, "");
215
- chunks.push(buffer);
255
+ const pieces = request.iterator({ destroyOnReturn: false });
256
+ const timed = idleMs > 0 && idleMs <= LONGEST_TIMER_MS;
257
+ try {
258
+ for (;;) {
259
+ const next = pieces.next();
260
+ const { done, value: chunk } = timed ? await withinIdle(next, idleMs) : await next;
261
+ if (done) break;
262
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
263
+ size += buffer.byteLength;
264
+ if (size > limit) throw new HttpError(413, "");
265
+ chunks.push(buffer);
266
+ }
267
+ } finally {
268
+ // As a `for await` does on leaving early; the request is not destroyed (see above).
269
+ void pieces.return?.().catch(() => undefined);
216
270
  }
217
271
  const body = Buffer.concat(chunks);
218
272
  return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
219
273
  }
220
274
 
275
+ const BUSY = "The server is receiving other files right now. Try again in a moment.";
276
+ /** When a client refused for `maxPendingUploadBytes` is told to try again. */
277
+ const BUSY_RETRY_MS = 5_000;
278
+
279
+ /** `uploadIdleTimeoutMs`, checked: a number of 0 or more (0 and Infinity for no limit). */
280
+ function idleLimit(value: unknown): number {
281
+ if (value === undefined) return 30_000;
282
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) {
283
+ throw new RangeError(`uploadIdleTimeoutMs must be a number of 0 or more, and is ${typeof value === "number" ? value : typeof value}. Leave it out for the default.`);
284
+ }
285
+ return value;
286
+ }
287
+
288
+ /** `maxPendingUploadBytes`, checked: a number above 0 (Infinity for no limit). */
289
+ function pendingLimit(value: unknown, maxUploadBytes: number): number {
290
+ if (value === undefined) return 2 * maxUploadBytes;
291
+ if (typeof value !== "number" || Number.isNaN(value) || value <= 0) {
292
+ throw new RangeError(`maxPendingUploadBytes must be a number above 0, and is ${typeof value === "number" ? value : typeof value}. Leave it out for the default.`);
293
+ }
294
+ return value;
295
+ }
296
+
297
+ /**
298
+ * The bytes an upload will hold: a body a framework already read, its declared `Content-Length`,
299
+ * or the upload limit when it declares none. Never more than the limit: a larger one is refused
300
+ * when it is read (413).
301
+ */
302
+ function expectedSize(request: IncomingMessage, limit: number): number {
303
+ const parsed = (request as IncomingMessage & { body?: unknown }).body;
304
+ if (parsed instanceof Uint8Array) return Math.min(parsed.byteLength, limit);
305
+ const declared = Number(request.headers["content-length"]);
306
+ return Number.isFinite(declared) && declared >= 0 ? Math.min(declared, limit) : limit;
307
+ }
308
+
221
309
  /**
222
310
  * The most bytes of an upload's body that are read and dropped after it was answered before the
223
311
  * body was read to its end (too large, no name). Past it the connection is closed.
@@ -262,6 +350,17 @@ function drain(request: IncomingMessage, response: ServerResponse): void {
262
350
  export function createDocumentHandlers(files: LargeFiles, options: DocumentHandlerOptions = {}): DocumentHandlers {
263
351
  const tooLarge = `The file is larger than the ${formatBytes(files.maxUploadBytes)} upload limit.`;
264
352
  const owner = async (request: IncomingMessage) => options.getOwner?.(request);
353
+ // The upload limit bounds each body, and the room for all of them: a LargeFiles of your own
354
+ // without it (from JavaScript) had neither.
355
+ if (typeof files.maxUploadBytes !== "number" || !(files.maxUploadBytes > 0)) {
356
+ throw new TypeError(`createDocumentHandlers needs files.maxUploadBytes, a number above 0, and it is ${String(files.maxUploadBytes)}. A LargeFiles of your own must keep the one of the library it wraps.`);
357
+ }
358
+ const maxPending = pendingLimit(options.maxPendingUploadBytes, files.maxUploadBytes);
359
+ const idleMs = idleLimit(options.uploadIdleTimeoutMs);
360
+ /** Whether uploads are counted at all (`maxPendingUploadBytes` is not Infinity). */
361
+ const counted = maxPending !== Number.POSITIVE_INFINITY;
362
+ /** The bytes of the uploads held now, from the reading of their body to the end of their ingest. */
363
+ let pending = 0;
265
364
 
266
365
  return {
267
366
  async upload(request, response) {
@@ -280,34 +379,62 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
280
379
  const empty = typeof currentOwner === "string" || currentOwner === null;
281
380
  throw new HttpError(500, empty ? "Upload failed (empty owner)." : "Upload failed (owner is not a string).");
282
381
  }
283
- const bytes = await readBody(request, files.maxUploadBytes);
284
- const contentType = header(request, "content-type");
285
- const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
286
- // A client that goes away before the answer stops the reading of its file: nobody would
287
- // get the document, and the server has other work.
288
- const gone = new AbortController();
289
- const onClose = () => {
290
- if (!response.writableFinished) gone.abort(new Error("The upload was cancelled: the client closed the connection."));
291
- };
292
- response.once("close", onClose);
293
- const input: IngestInput = {
294
- name,
295
- bytes,
296
- ...(mimeType ? { mimeType } : {}),
297
- ...(currentOwner !== undefined ? { owner: currentOwner } : {}),
298
- signal: gone.signal,
299
- };
300
- let meta;
382
+ // Too large is said first, before any wait for room.
383
+ const declared = Number(request.headers["content-length"]);
384
+ const parsed = (request as IncomingMessage & { body?: unknown }).body;
385
+ if ((Number.isFinite(declared) && declared > files.maxUploadBytes) || (parsed instanceof Uint8Array && parsed.byteLength > files.maxUploadBytes)) {
386
+ throw new HttpError(413, "");
387
+ }
388
+ // Room for the upload, before its body is read: a refused upload is not buffered. Never
389
+ // more than the room itself, so that the count stays a number with an upload limit of Infinity.
390
+ let held = counted ? Math.min(expectedSize(request, files.maxUploadBytes), maxPending) : 0;
391
+ if (pending > 0 && pending + held > maxPending) throw new IngestError("busy", BUSY, { retryAfterMs: BUSY_RETRY_MS });
392
+ pending += held;
301
393
  try {
302
- if (wantsEvents(request)) return await streamIngest(files, input, response, tooLarge);
303
- meta = await files.ingest(input);
304
- } catch (error) {
305
- throw ingestFailure(error);
394
+ const bytes = await readBody(request, files.maxUploadBytes, idleMs);
395
+ // Counted at its size once read (an upload without a Content-Length was counted at the limit).
396
+ if (counted) {
397
+ pending += bytes.byteLength - held;
398
+ held = bytes.byteLength;
399
+ }
400
+ const contentType = header(request, "content-type");
401
+ const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
402
+ // A client that goes away before the answer stops the reading of its file: nobody would
403
+ // get the document, and the server has other work.
404
+ const gone = new AbortController();
405
+ const onClose = () => {
406
+ if (!response.writableFinished) gone.abort(new Error("The upload was cancelled: the client closed the connection."));
407
+ };
408
+ response.once("close", onClose);
409
+ const input: IngestInput = {
410
+ name,
411
+ bytes,
412
+ ...(mimeType ? { mimeType } : {}),
413
+ ...(currentOwner !== undefined ? { owner: currentOwner } : {}),
414
+ signal: gone.signal,
415
+ };
416
+ let meta;
417
+ try {
418
+ if (wantsEvents(request)) return await streamIngest(files, input, response, tooLarge);
419
+ meta = await files.ingest(input);
420
+ } catch (error) {
421
+ throw ingestFailure(error);
422
+ } finally {
423
+ response.off("close", onClose);
424
+ }
425
+ send(response, 201, toDocumentSummary(meta));
306
426
  } finally {
307
- response.off("close", onClose);
427
+ pending -= held;
308
428
  }
309
- send(response, 201, toDocumentSummary(meta));
310
429
  } catch (error) {
430
+ // A body that stopped arriving is not drained: the answer ends, and so does the connection.
431
+ if (error instanceof HttpError && error.close) {
432
+ if (!response.headersSent) response.setHeader("Connection", "close");
433
+ send(response, error.status, { error: error.message });
434
+ if (response.writableFinished) request.destroy();
435
+ else response.once("finish", () => request.destroy());
436
+ return;
437
+ }
311
438
  // Answered before the body was read to its end (too large, no name): the rest is drained.
312
439
  fail(response, error, "Upload failed", tooLarge, request);
313
440
  // An event stream that failed after its headers were sent cannot answer with a status. (An
package/src/plan.ts CHANGED
@@ -1,5 +1,9 @@
1
+ import { pageList } from "./quality.js";
1
2
  import { plural, sliceWhole, wellFormed } from "./text.js";
2
- import type { Budget, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
3
+ import type { Budget, DocumentFormat, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
4
+
5
+ /** Formats whose documents may hold a table that `aggregate_table` reads. */
6
+ export const TABLE_FORMATS: ReadonlySet<DocumentFormat> = new Set<DocumentFormat>(["csv", "xlsx", "docx", "pptx", "pdf", "html", "markdown"]);
3
7
 
4
8
  /** Bytes kept free for document cards, the tool declarations, and JSON framing. */
5
9
  export const REQUEST_BYTES_MARGIN = 256 * 1024;
@@ -159,6 +163,7 @@ export function renderCard(meta: DocumentMeta, head: string, viewable = false, w
159
163
  HOW_TO_READ[wholeRead],
160
164
  ...(viewable ? ["Its text cannot show pictures. To see a picture, a chart or the layout of a page, look at the page with view_pages."] : []),
161
165
  ...(note ? [note] : []),
166
+ ...qualityLines(meta, viewable),
162
167
  ];
163
168
  const profile = meta.logProfile;
164
169
  if (profile) {
@@ -180,6 +185,16 @@ export function renderCard(meta: DocumentMeta, head: string, viewable = false, w
180
185
  return out.join("\n");
181
186
  }
182
187
 
188
+ /** What the card says of the quality of a document's text (see `measureQuality`). */
189
+ function qualityLines(meta: DocumentMeta, viewable: boolean): string[] {
190
+ const out: string[] = [];
191
+ const look = viewable ? " Look at them with view_pages." : "";
192
+ if (meta.pagesWithoutText?.length) out.push(`Pages without text (scans, photos or charts, whose content is not in the text): ${pageList(meta.pagesWithoutText)}.${look}`);
193
+ if (meta.garbledPages?.length) out.push(`Pages whose text looks garbled, not to be relied on: ${pageList(meta.garbledPages)}.${look}`);
194
+ if (meta.scripts?.length) out.push(`Written in: ${meta.scripts.map((share) => `${share.script} ${share.percent}%`).join(", ")}. Search in the language of the text.`);
195
+ return out;
196
+ }
197
+
183
198
  /**
184
199
  * The tool guide for the system prompt. `searchable` are the files the model reads through the
185
200
  * text tools. `viewable` are the PDFs whose pages it can look at with `view_pages`: some of them
@@ -199,6 +214,7 @@ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: D
199
214
  "- To count or list what can be matched as text (a word, an ID, an error code, a log level, a pattern), use search_document in exact or regex mode: its total_matching_lines is exact.",
200
215
  "- To count per group (per hour or day, per error code or ID with a regex group, per message shape), pass group_by: one call gives every count. For more matches than a result shows, search again from its next_from_line, or with order \"last\" for the last ones.",
201
216
  "- Search for the bare form of a word: a search matches inside longer words, so \"timeout\" also finds \"timeouts\", and a Hebrew word without its prefix letters (חוזה, not בחוזה) finds every form of it.",
217
+ ...(searchable.some((meta) => TABLE_FORMATS.has(meta.format)) ? ["- To add up, average, count or group the rows of a table (a CSV, an Excel sheet, a | cell | table), use aggregate_table: it reads every row, and its numbers are exact. Do not add numbers up from rows you read."] : []),
202
218
  "- read_document reads a line range. Read around search hits before you rely on them.",
203
219
  "- get_document_overview returns the outline, log profile, and the start and end of a file.",
204
220
  ...(wholeReads ? ["- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of the file and cannot be done by matching text: a full summary, a timeline, or items that must be judged by meaning. It is slow and costly, and it can miss items of a long list."] : []),