llm-large-files 0.3.6 → 0.4.1

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 (90) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/dist/cache.d.ts +49 -0
  3. package/dist/cache.d.ts.map +1 -0
  4. package/dist/cache.js +110 -0
  5. package/dist/cache.js.map +1 -0
  6. package/dist/errors.d.ts +21 -0
  7. package/dist/errors.d.ts.map +1 -0
  8. package/dist/errors.js +44 -0
  9. package/dist/errors.js.map +1 -0
  10. package/dist/gemini/chat.d.ts +5 -0
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +17 -1
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts +10 -0
  15. package/dist/gemini/generate.d.ts.map +1 -1
  16. package/dist/gemini/generate.js +110 -25
  17. package/dist/gemini/generate.js.map +1 -1
  18. package/dist/gemini/index.d.ts +1 -1
  19. package/dist/gemini/index.d.ts.map +1 -1
  20. package/dist/gemini/index.js +1 -1
  21. package/dist/gemini/index.js.map +1 -1
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/library.d.ts +48 -2
  27. package/dist/library.d.ts.map +1 -1
  28. package/dist/library.js +192 -52
  29. package/dist/library.js.map +1 -1
  30. package/dist/limiter.d.ts +20 -0
  31. package/dist/limiter.d.ts.map +1 -0
  32. package/dist/limiter.js +55 -0
  33. package/dist/limiter.js.map +1 -0
  34. package/dist/map-reduce.d.ts +14 -4
  35. package/dist/map-reduce.d.ts.map +1 -1
  36. package/dist/map-reduce.js +99 -33
  37. package/dist/map-reduce.js.map +1 -1
  38. package/dist/plan.d.ts +25 -7
  39. package/dist/plan.d.ts.map +1 -1
  40. package/dist/plan.js +51 -13
  41. package/dist/plan.js.map +1 -1
  42. package/dist/ranged.d.ts +102 -0
  43. package/dist/ranged.d.ts.map +1 -0
  44. package/dist/ranged.js +321 -0
  45. package/dist/ranged.js.map +1 -0
  46. package/dist/search.d.ts +93 -15
  47. package/dist/search.d.ts.map +1 -1
  48. package/dist/search.js +472 -131
  49. package/dist/search.js.map +1 -1
  50. package/dist/stores.d.ts +26 -2
  51. package/dist/stores.d.ts.map +1 -1
  52. package/dist/stores.js +181 -21
  53. package/dist/stores.js.map +1 -1
  54. package/dist/text-index.d.ts +64 -0
  55. package/dist/text-index.d.ts.map +1 -0
  56. package/dist/text-index.js +211 -0
  57. package/dist/text-index.js.map +1 -0
  58. package/dist/text.d.ts +14 -2
  59. package/dist/text.d.ts.map +1 -1
  60. package/dist/text.js +50 -16
  61. package/dist/text.js.map +1 -1
  62. package/dist/tools.d.ts +14 -2
  63. package/dist/tools.d.ts.map +1 -1
  64. package/dist/tools.js +53 -21
  65. package/dist/tools.js.map +1 -1
  66. package/dist/types.d.ts +20 -0
  67. package/dist/types.d.ts.map +1 -1
  68. package/docs/api.md +24 -10
  69. package/docs/configuration.md +50 -3
  70. package/docs/getting-started.md +2 -0
  71. package/docs/how-it-works.md +11 -3
  72. package/docs/security.md +21 -3
  73. package/package.json +7 -3
  74. package/src/cache.ts +107 -0
  75. package/src/errors.ts +42 -0
  76. package/src/gemini/chat.ts +22 -1
  77. package/src/gemini/generate.ts +107 -25
  78. package/src/gemini/index.ts +1 -1
  79. package/src/index.ts +3 -2
  80. package/src/library.ts +229 -50
  81. package/src/limiter.ts +51 -0
  82. package/src/map-reduce.ts +101 -33
  83. package/src/plan.ts +54 -14
  84. package/src/ranged.ts +355 -0
  85. package/src/search.ts +524 -121
  86. package/src/stores.ts +178 -23
  87. package/src/text-index.ts +228 -0
  88. package/src/text.ts +46 -13
  89. package/src/tools.ts +61 -23
  90. package/src/types.ts +20 -0
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,83 @@ 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
+ /**
26
+ * Whether a part's reply says that the part holds nothing for the task: the sentinel, whatever
27
+ * Markdown or punctuation a model puts around it (`**NOTHING RELEVANT**`). A reply that starts
28
+ * that way and then cites a line did find something, and is kept.
29
+ */
30
+ export function saysNothingRelevant(reply: string): boolean {
31
+ const text = reply.replace(/^[^\p{L}\p{N}]+/u, "");
32
+ return text.toUpperCase().startsWith(NOTHING) && !/\(L\d+/.test(text.slice(NOTHING.length));
33
+ }
34
+
35
+ /** Splits a text, fed a piece at a time, into line ranges that each fit one model request. */
36
+ class PartSplitter {
37
+ private readonly maxTokens: number;
38
+ private readonly maxBytes: number;
39
+ private readonly parts: Parts = [];
40
+ private from = 1;
41
+ private tokens = 0;
42
+ private bytes = 0;
43
+
44
+ constructor(budget: Budget) {
45
+ this.maxTokens = budget.mapChunkTokens;
46
+ this.maxBytes = Math.floor(budget.maxRequestBytes * 0.8);
47
+ }
48
+
49
+ add(chunk: TextChunk): void {
50
+ for (let local = 1; local <= chunk.lines.lineCount; local++) {
51
+ const line = chunk.firstLine + local - 1;
52
+ // Count the "123| " prefix each line carries in the prompt.
53
+ const text = `${line}| ${chunk.lines.line(local)}\n`;
54
+ const lineTokens = estimateTokens(text);
55
+ const lineBytes = jsonBytes(text);
56
+ if (line > this.from && (this.tokens + lineTokens > this.maxTokens || this.bytes + lineBytes > this.maxBytes)) {
57
+ this.parts.push({ from: this.from, to: line - 1 });
58
+ this.from = line;
59
+ this.tokens = 0;
60
+ this.bytes = 0;
61
+ }
62
+ this.tokens += lineTokens;
63
+ this.bytes += lineBytes;
41
64
  }
42
- tokens += lineTokens;
43
- bytes += lineBytes;
44
65
  }
45
- if (document.lines.lineCount >= from) parts.push({ from, to: document.lines.lineCount });
66
+
67
+ finish(lineCount: number): Parts {
68
+ if (lineCount >= this.from) this.parts.push({ from: this.from, to: lineCount });
69
+ return this.parts;
70
+ }
71
+ }
72
+
73
+ /** Splits a document held in memory into line ranges that each fit one model request. */
74
+ export function splitIntoParts(document: SearchableDocument, budget: Budget): Parts {
75
+ const splitter = new PartSplitter(budget);
76
+ splitter.add(document.wholeChunk());
77
+ return splitter.finish(document.lines.lineCount);
78
+ }
79
+
80
+ /** Parts already worked out, by document and budget: counting them reads the whole text. */
81
+ const knownParts = new WeakMap<DocumentSource, Map<string, Parts>>();
82
+
83
+ /** `splitIntoParts` for any document, worked out once per document object and budget. */
84
+ export async function partsOf(source: DocumentSource, budget: Budget, signal?: AbortSignal): Promise<Parts> {
85
+ const key = `${budget.mapChunkTokens}|${budget.maxRequestBytes}`;
86
+ const known = knownParts.get(source)?.get(key);
87
+ if (known) return known;
88
+ let parts: Parts;
89
+ if (source instanceof SearchableDocument) {
90
+ parts = splitIntoParts(source, budget);
91
+ } else {
92
+ const splitter = new PartSplitter(budget);
93
+ await scanSource(source, (chunk) => {
94
+ splitter.add(chunk);
95
+ }, signal);
96
+ parts = splitter.finish(source.lineCount);
97
+ }
98
+ if (!knownParts.has(source)) knownParts.set(source, new Map());
99
+ knownParts.get(source)!.set(key, parts);
46
100
  return parts;
47
101
  }
48
102
 
@@ -88,7 +142,7 @@ async function ask(
88
142
  * then the notes are combined ("reduce"), in several rounds if the notes are still too large.
89
143
  */
90
144
  export async function analyzeWholeDocument(options: {
91
- document: SearchableDocument;
145
+ document: DocumentSource;
92
146
  task: string;
93
147
  generate: GenerateText;
94
148
  budget: Budget;
@@ -98,7 +152,7 @@ export async function analyzeWholeDocument(options: {
98
152
  }): Promise<WholeDocumentResult> {
99
153
  const { document, task, generate, budget, onProgress, signal } = options;
100
154
  const name = document.meta.name;
101
- const parts = splitIntoParts(document, budget);
155
+ const parts = await partsOf(document, budget, signal);
102
156
  if (parts.length > budget.maxMapChunks) {
103
157
  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
158
  }
@@ -112,6 +166,7 @@ export async function analyzeWholeDocument(options: {
112
166
  let text: string;
113
167
  let read = true;
114
168
  try {
169
+ const part = numberLines(await document.readLines(from, to), from);
115
170
  const reply = await ask(generate, {
116
171
  system: "You read one part of a larger document and take notes for a later step that combines the notes from every part.",
117
172
  prompt: [
@@ -121,7 +176,7 @@ export async function analyzeWholeDocument(options: {
121
176
  `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
177
  "",
123
178
  "<part>",
124
- document.lines.numbered(from, to),
179
+ part,
125
180
  "</part>",
126
181
  ].join("\n"),
127
182
  maxOutputTokens: PART_OUTPUT_TOKENS,
@@ -147,7 +202,7 @@ export async function analyzeWholeDocument(options: {
147
202
  // Nothing was read at all: an answer written from here would be invented.
148
203
  if (failed === parts.length) throw new Error(`Could not read any part of ${name}: ${firstFailure}`);
149
204
 
150
- const relevant = notes.filter((note) => !note.text.toUpperCase().startsWith(NOTHING));
205
+ const relevant = notes.filter((note) => !saysNothingRelevant(note.text));
151
206
  const relevantParts = relevant.filter((note) => note.read).length;
152
207
  if (relevantParts === 0) {
153
208
  return {
@@ -188,17 +243,30 @@ export async function analyzeWholeDocument(options: {
188
243
  for (let index = 0; index < layer.length; index += 2) batches.push(layer.slice(index, index + 2));
189
244
  }
190
245
  let combined = 0;
246
+ let unmerged = 0;
191
247
  layer = await pool(batches.length, options.concurrency ?? 4, async (index) => {
192
- const reply = await ask(generate, {
193
- system: "You merge partial notes about a document into shorter notes, keeping every relevant fact and line citation.",
194
- prompt: `Task: ${task}\n\nMerge these notes from ${name} into one set of notes. Keep line citations.\n\n${batches[index]!.join("\n\n")}`,
195
- maxOutputTokens: PART_OUTPUT_TOKENS,
196
- }, signal);
197
- if (reply.truncated) truncatedMerges++;
248
+ const batch = batches[index]!.join("\n\n");
249
+ let merged: string;
250
+ try {
251
+ const reply = await ask(generate, {
252
+ system: "You merge partial notes about a document into shorter notes, keeping every relevant fact and line citation.",
253
+ prompt: `Task: ${task}\n\nMerge these notes from ${name} into one set of notes. Keep line citations.\n\n${batch}`,
254
+ maxOutputTokens: PART_OUTPUT_TOKENS,
255
+ }, signal);
256
+ if (reply.truncated) truncatedMerges++;
257
+ merged = reply.truncated ? `${reply.text}\n[These merged notes were cut off at the output limit.]` : reply.text;
258
+ } catch (error) {
259
+ if (signal?.aborted) throw error;
260
+ // A merge that cannot be made loses nothing: the notes of every part were paid for, and go on as they are.
261
+ unmerged++;
262
+ merged = batch;
263
+ }
198
264
  combined++;
199
265
  onProgress?.({ kind: "reduce", message: `Combining notes on ${name} (round ${round}): ${combined} of ${batches.length}`, done: combined, total: batches.length });
200
- return reply.truncated ? `${reply.text}\n[These merged notes were cut off at the output limit.]` : reply.text;
266
+ return merged;
201
267
  }, signal);
268
+ // Notes that would not merge will not merge in another round either: the answer is written from what there is.
269
+ if (unmerged > 0) break;
202
270
  }
203
271
 
204
272
  onProgress?.({ kind: "reduce", message: `Writing the answer from ${relevantParts} relevant parts of ${name}`, done: 0, total: 1 });
package/src/plan.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { Budget, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
2
- import type { SearchableDocument } from "./search.js";
3
2
 
4
3
  /** Bytes kept free for document cards, the tool declarations, and JSON framing. */
5
4
  export const REQUEST_BYTES_MARGIN = 256 * 1024;
@@ -19,7 +18,7 @@ export function planDocuments(
19
18
  const byteRoom = budget.maxRequestBytes - REQUEST_BYTES_MARGIN - base.bytes;
20
19
  const plan: DocumentPlan = { inline: [], searchable: [], inlineTokens: 0, inlineBytes: 0 };
21
20
  for (const meta of [...documents].sort((left, right) => left.estimatedTokens - right.estimatedTokens)) {
22
- const bytes = Math.ceil(meta.textBytes * 1.08) + 200;
21
+ const bytes = (meta.jsonBytes ?? Math.ceil(meta.textBytes * 1.08)) + 200;
23
22
  if (plan.inlineTokens + meta.estimatedTokens <= tokenRoom && plan.inlineBytes + bytes <= byteRoom) {
24
23
  plan.inline.push(meta);
25
24
  plan.inlineTokens += meta.estimatedTokens;
@@ -31,6 +30,41 @@ export function planDocuments(
31
30
  return plan;
32
31
  }
33
32
 
33
+ /** The digits of the numbers 1 to `count`, written out: what the line numbers of a text take. */
34
+ function digitsUpTo(count: number): number {
35
+ let digits = 0;
36
+ for (let width = 1, first = 1; first <= count; width++, first *= 10) digits += (Math.min(count, first * 10 - 1) - first + 1) * width;
37
+ return digits;
38
+ }
39
+
40
+ /**
41
+ * About how many parts a whole-document read of a document takes, from its metadata alone:
42
+ * counting them exactly means reading the whole text. In the prompt every line carries its number
43
+ * (`12345| `), at about 1.2 tokens a digit and one for the bar, and each line's estimate is
44
+ * rounded up. A part ends at the end of a line, so it is short of full by half a line on average.
45
+ * On logs, prose, tables and blank-heavy text this lands within a few percent of the count.
46
+ */
47
+ export function estimateParts(meta: Pick<DocumentMeta, "estimatedTokens" | "lines" | "textBytes" | "jsonBytes">, budget: Budget): number {
48
+ const lines = Math.max(1, meta.lines);
49
+ const digits = digitsUpTo(lines);
50
+ const tokens = meta.estimatedTokens + 1.2 * digits + 1.5 * lines;
51
+ const bytes = (meta.jsonBytes ?? meta.textBytes * 1.08) + digits + 4 * lines;
52
+ const room = (limit: number, size: number) => Math.max(1, limit - size / lines / 2);
53
+ const maxBytes = Math.floor(budget.maxRequestBytes * 0.8);
54
+ return Math.max(1, Math.ceil(Math.max(tokens / room(budget.mapChunkTokens, tokens), bytes / room(maxBytes, bytes))));
55
+ }
56
+
57
+ /**
58
+ * Whether a whole-document read of a document is within `maxMapChunks`, as far as its metadata
59
+ * tells. The estimate runs a few percent high, so a file just over the limit by it is let through:
60
+ * the read counts its parts, and refuses with the reason if they are too many after all.
61
+ */
62
+ export function canBeReadWhole(meta: Pick<DocumentMeta, "estimatedTokens" | "lines" | "textBytes" | "jsonBytes">, budget: Budget): boolean {
63
+ const parts = estimateParts(meta, budget);
64
+ // Metadata that does not say (a record of a document that an application kept in part): not refused here.
65
+ return !Number.isFinite(parts) || parts <= budget.maxMapChunks * 1.05;
66
+ }
67
+
34
68
  function formatCount(value: number): string {
35
69
  if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
36
70
  if (value >= 10_000) return `${Math.round(value / 1_000)}K`;
@@ -50,22 +84,27 @@ export function outlineLines(outline: OutlineEntry[]): string[] {
50
84
  return outline.map((entry) => `L${entry.line} ${" ".repeat(entry.level - top)}${entry.title}`);
51
85
  }
52
86
 
53
- export function renderInline(document: SearchableDocument): string {
54
- const { meta } = document;
55
- return `--- Attached file: ${meta.name} (${meta.format}, ${meta.lines.toLocaleString("en-US")} lines) ---\n${document.text}\n--- End attached file: ${meta.name} ---`;
87
+ export function renderInline(meta: DocumentMeta, text: string): string {
88
+ return `--- Attached file: ${meta.name} (${meta.format}, ${meta.lines.toLocaleString("en-US")} lines) ---\n${text}\n--- End attached file: ${meta.name} ---`;
56
89
  }
57
90
 
91
+ /** How many lines of a file its card shows. */
92
+ export const CARD_LINES = CARD_HEAD_LINES;
93
+
58
94
  /**
59
- * A compact stand-in for a document that is too large for the prompt. `viewable` adds a line
60
- * saying that its pages can be looked at with `view_pages`.
95
+ * A compact stand-in for a document that is too large for the prompt. `head` is its first
96
+ * `CARD_LINES` lines, numbered. `viewable` adds a line saying that its pages can be looked at
97
+ * with `view_pages`. `readableWhole` is false for a file that a whole-document read would refuse:
98
+ * the card then does not offer one.
61
99
  */
62
- export function renderCard(document: SearchableDocument, viewable = false): string {
63
- const { meta } = document;
100
+ export function renderCard(meta: DocumentMeta, head: string, viewable = false, readableWhole = true): string {
64
101
  const out = [
65
102
  `--- Large attached file: ${meta.name} ---`,
66
103
  `document_id: ${meta.id}`,
67
104
  `${meta.format} · ${formatBytes(meta.bytes)} · ${meta.lines.toLocaleString("en-US")} lines${meta.pages ? ` · ${meta.pages} pages` : ""} · about ${formatCount(meta.estimatedTokens)} tokens`,
68
- "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it.",
105
+ readableWhole
106
+ ? "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it."
107
+ : "This file is NOT in your context. Use the document tools to search it and to read line ranges. It is too large to be analyzed whole.",
69
108
  ...(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."] : []),
70
109
  ];
71
110
  const profile = meta.logProfile;
@@ -82,7 +121,7 @@ export function renderCard(document: SearchableDocument, viewable = false): stri
82
121
  out.push(`Outline (${Math.min(meta.outline.length, CARD_OUTLINE_ENTRIES)} of ${meta.outline.length} headings):`);
83
122
  out.push(...outlineLines(meta.outline.slice(0, CARD_OUTLINE_ENTRIES)).map((line) => ` ${line}`));
84
123
  }
85
- out.push(`First lines:`, document.lines.numbered(1, CARD_HEAD_LINES).split("\n").map((line) => ` ${line.slice(0, 300)}`).join("\n"));
124
+ out.push(`First lines:`, head.split("\n").map((line) => ` ${line.slice(0, 300)}`).join("\n"));
86
125
  out.push(`--- End large attached file: ${meta.name} ---`);
87
126
  return out.join("\n");
88
127
  }
@@ -90,9 +129,10 @@ export function renderCard(document: SearchableDocument, viewable = false): stri
90
129
  /**
91
130
  * The tool guide for the system prompt. `searchable` are the files the model reads through the
92
131
  * text tools. `viewable` are the PDFs whose pages it can look at with `view_pages`: some of them
93
- * may be searchable, and some may have their whole text in the prompt.
132
+ * may be searchable, and some may have their whole text in the prompt. `wholeReads` is false when
133
+ * every searchable file is too large for `analyze_whole_document`: the guide then leaves it out.
94
134
  */
95
- export function documentToolsInstruction(searchable: DocumentMeta[], viewable: DocumentMeta[] = []): string {
135
+ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: DocumentMeta[] = [], wholeReads = true): string {
96
136
  // File names come from uploads. Quoting keeps a name that reads like an instruction a name.
97
137
  const named = (meta: DocumentMeta, detail = "") => `${JSON.stringify(meta.name)} (document_id ${meta.id}${detail})`;
98
138
  const guide: string[] = [];
@@ -103,7 +143,7 @@ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: D
103
143
  "- search_document finds lines (exact or regex) or the most relevant passages (keywords).",
104
144
  "- read_document reads a line range. Read around search hits before you rely on them.",
105
145
  "- get_document_overview returns the outline, log profile, and the start and end of a file.",
106
- "- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of it (a full summary, every occurrence, a timeline). It is slow and costly.",
146
+ ...(wholeReads ? ["- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of it (a full summary, every occurrence, a timeline). It is slow and costly."] : []),
107
147
  "You have a limited number of tool turns. Call several tools in the same turn when the searches do not depend on each other, and answer as soon as you have enough evidence.",
108
148
  "Base your answer on text you actually read. Cite line numbers like (app.log L1203). If the tools did not find something, say so rather than guessing.",
109
149
  );
package/src/ranged.ts ADDED
@@ -0,0 +1,355 @@
1
+ /**
2
+ * A document read from the store a range at a time, for stores that can (`readTextRange`): a tool
3
+ * call reads the lines it needs, and a search reads the text in pieces, so no call holds a whole
4
+ * large file in memory. The line index comes from the store (`getIndex`), or is built from the
5
+ * text the first time an older document without one is opened, and saved for next time.
6
+ */
7
+ import type { Limiter } from "./limiter.js";
8
+ import { pagesOfLines, pause, type DocumentSource, type ScanFeed, type TextChunk } from "./search.js";
9
+ import { canSerialize, parseTextIndex, positionOf, serializeTextIndex, TextIndexBuilder, type TextIndex } from "./text-index.js";
10
+ import { foldCase, LineIndex } from "./text.js";
11
+ import type { DocumentMeta, DocumentStore } from "./types.js";
12
+
13
+ export type RangeStore = Pick<DocumentStore, "getIndex" | "putIndex"> & Required<Pick<DocumentStore, "readTextRange">>;
14
+
15
+ export type ScanSettings = {
16
+ /** About this many bytes of text are read and searched at a time. */
17
+ chunkBytes: number;
18
+ /** Bounds how many scans of whole documents run at once. */
19
+ limiter: Limiter;
20
+ /** Told when the stored text of a document did not agree with its index. */
21
+ onBroken?: (id: string) => void;
22
+ /**
23
+ * Where decoded pieces of frequently searched documents are kept, within the cache's memory
24
+ * limit, so that the next search of them reads and decodes nothing. A document whose decoded
25
+ * text would take more than `maxDocumentBytes` is never kept: one scan of it would push out
26
+ * everything else.
27
+ */
28
+ pieces?: PieceCache;
29
+ };
30
+
31
+ /** A piece of text kept in memory, and what it takes. */
32
+ export type CachedPiece = TextChunk & { readonly memoryBytes: number };
33
+
34
+ export type PieceCache = {
35
+ get(key: string, version: string): CachedPiece | undefined;
36
+ set(key: string, version: string, piece: CachedPiece): void;
37
+ maxDocumentBytes: number;
38
+ };
39
+
40
+ /** The cache key of piece `at` of a document. All of them start with `${id}#`. */
41
+ export const pieceKey = (id: string, at: number) => `${id}#${at}`;
42
+
43
+ /** Bytes read at a time to build an index from the text. */
44
+ const BUILD_READ_BYTES = 4 * 1024 * 1024;
45
+ /** A pass shared by several scans lets other work run after this much time on the main thread. */
46
+ const YIELD_AFTER_MS = 15;
47
+ const decoder = new TextDecoder("utf-8");
48
+
49
+ const gone = (id: string) => new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
50
+
51
+ /** A scan of a document: fed the pieces in order until it says it is done. */
52
+ type Consumer = { feed: ScanFeed; done: boolean; settle: (error?: unknown) => void };
53
+
54
+ export class RangedDocument implements DocumentSource {
55
+ /**
56
+ * Set when the stored text did not agree with the index. The library then drops this object and
57
+ * opens the document again, building its index from the text.
58
+ */
59
+ broken = false;
60
+
61
+ /** The version its pieces are kept under, and whether they are kept at all. */
62
+ private readonly pieceVersion: string;
63
+ private readonly keepPieces: boolean;
64
+ private ranges?: Array<{ firstLine: number; lastLine: number; start: number; end: number }>;
65
+
66
+ constructor(
67
+ private readonly store: RangeStore,
68
+ readonly meta: DocumentMeta,
69
+ readonly index: TextIndex,
70
+ private readonly settings: ScanSettings,
71
+ ) {
72
+ this.pieceVersion = `${meta.createdAt}|${index.textBytes}|${index.characters}|${settings.chunkBytes}`;
73
+ // Decoded text is one byte a character when it is all ASCII, two otherwise; and its lowercased copy as much again.
74
+ const decoded = index.characters * (index.textBytes === index.characters ? 1 : 2) * 2 + index.characterStarts.byteLength;
75
+ this.keepPieces = settings.pieces !== undefined && decoded <= settings.pieces.maxDocumentBytes;
76
+ }
77
+
78
+ get lineCount(): number {
79
+ return this.index.lineCount;
80
+ }
81
+
82
+ get characters(): number {
83
+ return this.index.characters;
84
+ }
85
+
86
+ get passageStarts(): ArrayLike<number> {
87
+ return this.index.passageStarts;
88
+ }
89
+
90
+ get memoryBytes(): number {
91
+ const { lineStarts, characterStarts, passageStarts, pageStarts } = this.index;
92
+ return lineStarts.byteLength + characterStarts.byteLength + passageStarts.byteLength + pageStarts.byteLength + 2_048;
93
+ }
94
+
95
+ pageOfLine(line: number): number | undefined {
96
+ const starts = this.index.pageStarts;
97
+ return starts.length === 0 || line < starts[0]! ? undefined : positionOf(starts, line);
98
+ }
99
+
100
+ pagesOfLines(from: number, to: number): string | undefined {
101
+ return pagesOfLines(this.index.pageStarts, from, to);
102
+ }
103
+
104
+ async readLines(from: number, to: number): Promise<string[]> {
105
+ const first = Math.max(1, from);
106
+ const last = Math.min(to, this.index.lineCount);
107
+ if (first > last) return [];
108
+ const text = await this.read(...this.bytesOf(first, last));
109
+ const lines = (text.endsWith("\n") ? text.slice(0, -1) : text).split("\n");
110
+ if (lines.length !== last - first + 1) throw this.mismatch();
111
+ return lines;
112
+ }
113
+
114
+ async readText(): Promise<string> {
115
+ const text = await this.read(0, this.index.textBytes);
116
+ if (text.length !== this.index.characters) throw this.mismatch();
117
+ return text;
118
+ }
119
+
120
+ /**
121
+ * The text in pieces of whole passages, about `chunkBytes` each. A scan waits for a slot of the
122
+ * limiter first, and holds it until it ends or is abandoned. `scan` does the same for several
123
+ * scans at once.
124
+ */
125
+ async *chunks(signal?: AbortSignal): AsyncGenerator<TextChunk> {
126
+ const release = await this.settings.limiter.acquire(signal);
127
+ try {
128
+ for await (const chunk of this.pieces()) {
129
+ signal?.throwIfAborted();
130
+ yield chunk;
131
+ }
132
+ } finally {
133
+ release();
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Feeds the text, a piece at a time and in order, to `feed` until it returns true or the text
139
+ * ends. Scans asked for while others of this document wait for a slot of the limiter join them:
140
+ * the pieces are then read, decoded and lowercased once, for all of them. A scan asked for once
141
+ * the pass has started waits for the next one, since every scan must see the text from the start.
142
+ */
143
+ scan(feed: ScanFeed, signal?: AbortSignal): Promise<void> {
144
+ return new Promise<void>((resolve, reject) => {
145
+ if (signal?.aborted) {
146
+ reject(signal.reason);
147
+ return;
148
+ }
149
+ const onAbort = () => consumer.settle(signal!.reason);
150
+ const consumer: Consumer = {
151
+ feed,
152
+ done: false,
153
+ settle: (error?: unknown) => {
154
+ if (consumer.done) return;
155
+ consumer.done = true;
156
+ signal?.removeEventListener("abort", onAbort);
157
+ if (error === undefined) resolve();
158
+ else reject(error);
159
+ },
160
+ };
161
+ signal?.addEventListener("abort", onAbort, { once: true });
162
+ if (this.gathering) {
163
+ this.gathering.push(consumer);
164
+ return;
165
+ }
166
+ const group = [consumer];
167
+ this.gathering = group;
168
+ void this.pass(group);
169
+ });
170
+ }
171
+
172
+ /** Scans waiting for a slot, open to more of them. */
173
+ private gathering: Consumer[] | undefined;
174
+
175
+ private async pass(group: Consumer[]): Promise<void> {
176
+ const release = await this.settings.limiter.acquire();
177
+ // From here on the group is closed.
178
+ if (this.gathering === group) this.gathering = undefined;
179
+ try {
180
+ if (group.every((consumer) => consumer.done)) return;
181
+ let slice = performance.now();
182
+ for await (const chunk of this.pieces()) {
183
+ let open = 0;
184
+ for (const consumer of group) {
185
+ if (consumer.done) continue;
186
+ try {
187
+ let more = consumer.feed(chunk);
188
+ // A scan that asks for the same piece again has stopped part-way to let other work run.
189
+ while (more === "again" && !consumer.done) {
190
+ await pause();
191
+ slice = performance.now();
192
+ more = consumer.feed(chunk);
193
+ }
194
+ if (more === true) consumer.settle();
195
+ else if (!consumer.done) open++;
196
+ } catch (error) {
197
+ consumer.settle(error);
198
+ }
199
+ // Many scans on one piece add up: give other work (answers streaming to other users) a turn.
200
+ if (performance.now() - slice > YIELD_AFTER_MS) {
201
+ await pause();
202
+ slice = performance.now();
203
+ }
204
+ }
205
+ if (open === 0) break;
206
+ }
207
+ for (const consumer of group) consumer.settle();
208
+ } catch (error) {
209
+ for (const consumer of group) consumer.settle(error);
210
+ } finally {
211
+ release();
212
+ }
213
+ }
214
+
215
+ /**
216
+ * The pieces, in order: kept ones from memory, the others read and decoded, the next one read
217
+ * while the current one is used. Line breaks are where the index says, which each piece read is
218
+ * checked against.
219
+ */
220
+ private async *pieces(): AsyncGenerator<TextChunk> {
221
+ const count = this.chunkRanges().length;
222
+ const load = (at: number) => {
223
+ const promise = this.piece(at);
224
+ // Read ahead: if the scan stops before it needs this piece, nobody waits for it.
225
+ promise.catch(() => undefined);
226
+ return promise;
227
+ };
228
+ let next = count > 0 ? load(0) : undefined;
229
+ for (let at = 0; at < count; at++) {
230
+ const chunk = await next!;
231
+ next = at + 1 < count ? load(at + 1) : undefined;
232
+ yield chunk;
233
+ }
234
+ }
235
+
236
+ /** Piece `at`, from memory when it is kept there. */
237
+ private async piece(at: number): Promise<TextChunk> {
238
+ const cache = this.keepPieces ? this.settings.pieces : undefined;
239
+ const kept = cache?.get(pieceKey(this.meta.id, at), this.pieceVersion);
240
+ if (kept) return kept;
241
+ const { firstLine, lastLine, start, end } = this.chunkRanges()[at]!;
242
+ const text = await this.read(start, end);
243
+ const { characterStarts, characters, lineCount } = this.index;
244
+ const startCharacter = characterStarts[firstLine - 1]!;
245
+ const endCharacter = lastLine < lineCount ? characterStarts[lastLine]! : characters;
246
+ if (text.length !== endCharacter - startCharacter) throw this.mismatch();
247
+ const starts = new Uint32Array(lastLine - firstLine + 1);
248
+ for (let line = 0; line < starts.length; line++) {
249
+ const lineStart = characterStarts[firstLine - 1 + line]! - startCharacter;
250
+ // Each line but the first starts right after a line break.
251
+ if (line > 0 && text.charCodeAt(lineStart - 1) !== 10) throw this.mismatch();
252
+ starts[line] = lineStart;
253
+ }
254
+ if (lastLine < lineCount && text.charCodeAt(text.length - 1) !== 10) throw this.mismatch();
255
+ let lower: string | undefined;
256
+ const ascii = end - start === text.length;
257
+ const piece: CachedPiece = {
258
+ firstLine,
259
+ startCharacter,
260
+ text,
261
+ lines: new LineIndex(text, starts),
262
+ lower: () => (lower ??= foldCase(text)),
263
+ // The text and, once a search needs it, its lowercased copy.
264
+ memoryBytes: text.length * (ascii ? 1 : 2) * 2 + starts.byteLength + 256,
265
+ };
266
+ cache?.set(pieceKey(this.meta.id, at), this.pieceVersion, piece);
267
+ return piece;
268
+ }
269
+
270
+ /** The bytes of lines `first` to `last`, which must exist. */
271
+ private bytesOf(first: number, last: number): [number, number] {
272
+ const { lineStarts, lineCount, textBytes } = this.index;
273
+ return [lineStarts[first - 1]!, last < lineCount ? lineStarts[last]! : textBytes];
274
+ }
275
+
276
+ /** Line ranges of whole passages, each about `chunkBytes` (one passage at least). */
277
+ private chunkRanges(): Array<{ firstLine: number; lastLine: number; start: number; end: number }> {
278
+ if (this.ranges) return this.ranges;
279
+ const { passageStarts, lineStarts, lineCount, textBytes } = this.index;
280
+ const ranges: Array<{ firstLine: number; lastLine: number; start: number; end: number }> = [];
281
+ for (let passage = 0; passage < passageStarts.length;) {
282
+ const firstLine = passageStarts[passage]!;
283
+ const start = lineStarts[firstLine - 1]!;
284
+ let next = passage + 1;
285
+ while (next < passageStarts.length && lineStarts[passageStarts[next]! - 1]! - start < this.settings.chunkBytes) next++;
286
+ const end = next < passageStarts.length ? lineStarts[passageStarts[next]! - 1]! : textBytes;
287
+ ranges.push({ firstLine, lastLine: next < passageStarts.length ? passageStarts[next]! - 1 : lineCount, start, end });
288
+ passage = next;
289
+ }
290
+ this.ranges = ranges;
291
+ return ranges;
292
+ }
293
+
294
+ private async read(start: number, end: number): Promise<string> {
295
+ const bytes = await this.store.readTextRange(this.meta.id, start, end);
296
+ if (!bytes) throw gone(this.meta.id);
297
+ if (bytes.length !== end - start) throw this.mismatch();
298
+ return decoder.decode(bytes);
299
+ }
300
+
301
+ private mismatch(): Error {
302
+ if (!this.broken) {
303
+ this.broken = true;
304
+ this.settings.onBroken?.(this.meta.id);
305
+ }
306
+ return new Error(`The stored text of ${this.meta.name} did not match its index. Try the call again.`);
307
+ }
308
+ }
309
+
310
+ /** Builds the index of a stored text by reading all of it once. Undefined when the text is gone. */
311
+ export async function buildIndexFromStore(store: RangeStore, id: string, limiter: Limiter): Promise<TextIndex | undefined> {
312
+ const release = await limiter.acquire();
313
+ try {
314
+ const builder = new TextIndexBuilder();
315
+ for (let position = 0; ;) {
316
+ const bytes = await store.readTextRange(id, position, position + BUILD_READ_BYTES);
317
+ if (!bytes) return undefined;
318
+ builder.push(bytes);
319
+ position += bytes.length;
320
+ if (bytes.length < BUILD_READ_BYTES) break;
321
+ }
322
+ const index = builder.finish();
323
+ return index.lineCount > 0 ? index : undefined;
324
+ } finally {
325
+ release();
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Opens a document to be read by range. Uses the saved index when there is one that fits the
331
+ * document; otherwise builds it from the text and saves it (best effort: a store that cannot
332
+ * write, or another server writing the same index, changes nothing). Undefined when the text is gone.
333
+ */
334
+ export async function openRangedDocument(
335
+ store: RangeStore,
336
+ meta: DocumentMeta,
337
+ settings: ScanSettings,
338
+ options: { ignoreSavedIndex?: boolean } = {},
339
+ ): Promise<RangedDocument | undefined> {
340
+ let index: TextIndex | undefined;
341
+ if (!options.ignoreSavedIndex && store.getIndex) {
342
+ const saved = await store.getIndex(meta.id).catch(() => undefined);
343
+ if (saved) index = parseTextIndex(saved, meta);
344
+ }
345
+ if (!index) {
346
+ index = await buildIndexFromStore(store, meta.id, settings.limiter);
347
+ if (!index) return undefined;
348
+ // An index that disagrees with the metadata describes a text that is not what was ingested.
349
+ // It is used, since it is what the store holds, but not saved.
350
+ if (store.putIndex && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters) {
351
+ await store.putIndex(meta.id, serializeTextIndex(index)).catch(() => undefined);
352
+ }
353
+ }
354
+ return new RangedDocument(store, meta, index, settings);
355
+ }