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/stores.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import type { DocumentMeta, DocumentStore, StoredDocument } from "./types.js";
4
5
 
@@ -61,31 +62,81 @@ export class MemoryDocumentStore implements DocumentStore {
61
62
  }
62
63
  }
63
64
 
65
+ /** The files of a document, and the temporary files written on the way to them. */
66
+ const FILE_NAME = /^(doc_[a-f0-9]{32})\.(json|txt|bin|idx)(\.[a-f0-9]{8}\.tmp)?$/;
67
+
68
+ /**
69
+ * Errors a rename can meet on Windows while another process (a reader, an antivirus scanner) has
70
+ * the file open for a moment. Retried with growing pauses for up to about three seconds, as
71
+ * graceful-fs does.
72
+ */
73
+ const RETRY_RENAME = new Set(["EPERM", "EACCES", "EBUSY"]);
74
+ const RENAME_PAUSES_MS = [10, 20, 40, 80, 160, 320, 500, 500, 500, 500];
75
+
76
+ const code = (error: unknown) => (error as { code?: unknown } | null)?.code;
77
+
78
+ /**
79
+ * Writes a file whole or not at all, as other processes see it: to a temporary name first, then
80
+ * renamed. A server reading a shared volume never sees half of a file another server is writing.
81
+ */
82
+ async function writeWhole(target: string, data: string | Uint8Array): Promise<void> {
83
+ const temporary = `${target}.${randomUUID().slice(0, 8)}.tmp`;
84
+ try {
85
+ await writeFile(temporary, data);
86
+ for (let attempt = 0; ; attempt++) {
87
+ try {
88
+ await rename(temporary, target);
89
+ return;
90
+ } catch (error) {
91
+ if (attempt >= RENAME_PAUSES_MS.length || !RETRY_RENAME.has(code(error) as string)) throw error;
92
+ await new Promise((resolve) => setTimeout(resolve, RENAME_PAUSES_MS[attempt]));
93
+ }
94
+ }
95
+ } catch (error) {
96
+ await rm(temporary, { force: true }).catch(() => undefined);
97
+ throw error;
98
+ }
99
+ }
100
+
64
101
  /**
65
102
  * Keeps each document as `<id>.txt` plus `<id>.json` in one directory, so files survive a
66
- * server restart, and its original file as `<id>.bin` when one is kept. Only IDs matching
67
- * DOCUMENT_ID_PATTERN ever reach the file system.
103
+ * server restart, its line index as `<id>.idx`, and its original file as `<id>.bin` when one is
104
+ * kept. Only IDs matching DOCUMENT_ID_PATTERN ever reach the file system.
105
+ *
106
+ * Several servers may share the directory (a network volume): every file is written whole under
107
+ * a temporary name and then renamed, a tool call reads only the lines it needs (`readTextRange`),
108
+ * and `sweep` never removes the files of an upload that is still being written.
68
109
  */
69
110
  export class FileDocumentStore implements DocumentStore {
70
111
  private readonly now: () => Date;
112
+ private readonly orphanAgeMs: number;
71
113
 
72
- constructor(private readonly directory: string, options: { now?: () => Date } = {}) {
114
+ constructor(private readonly directory: string, options: {
115
+ now?: () => Date;
116
+ /**
117
+ * `sweep` removes files that belong to no document (an upload that failed, a server that
118
+ * stopped while writing) once they are this old. Younger ones may be an upload in progress,
119
+ * on this server or another one. Defaults to one hour.
120
+ */
121
+ orphanAgeMs?: number;
122
+ } = {}) {
73
123
  this.now = options.now ?? (() => new Date());
124
+ this.orphanAgeMs = options.orphanAgeMs ?? 60 * 60 * 1000;
74
125
  }
75
126
 
76
- private paths(id: string): { text: string; meta: string; original: string } | undefined {
127
+ private paths(id: string): { text: string; meta: string; original: string; index: string } | undefined {
77
128
  if (!DOCUMENT_ID_PATTERN.test(id)) return undefined;
78
129
  const file = (extension: string) => path.join(this.directory, `${id}.${extension}`);
79
- return { text: file("txt"), meta: file("json"), original: file("bin") };
130
+ return { text: file("txt"), meta: file("json"), original: file("bin"), index: file("idx") };
80
131
  }
81
132
 
82
133
  async put(document: StoredDocument): Promise<void> {
83
134
  const paths = this.paths(document.meta.id);
84
135
  if (!paths) throw new Error("Invalid document ID.");
85
136
  await mkdir(this.directory, { recursive: true });
86
- await writeFile(paths.text, document.text, "utf8");
137
+ await writeWhole(paths.text, document.text);
87
138
  // Write metadata last: a document without metadata is treated as absent.
88
- await writeFile(paths.meta, JSON.stringify(document.meta), "utf8");
139
+ await writeWhole(paths.meta, JSON.stringify(document.meta));
89
140
  }
90
141
 
91
142
  async getMeta(id: string): Promise<DocumentMeta | undefined> {
@@ -115,11 +166,54 @@ export class FileDocumentStore implements DocumentStore {
115
166
  }
116
167
  }
117
168
 
169
+ async readTextRange(id: string, start: number, end: number): Promise<Uint8Array | undefined> {
170
+ const paths = this.paths(id);
171
+ if (!paths) return undefined;
172
+ let handle;
173
+ try {
174
+ handle = await open(paths.text, "r");
175
+ } catch (error) {
176
+ if (code(error) === "ENOENT") return undefined;
177
+ throw error;
178
+ }
179
+ try {
180
+ // Not zero-filled first: every byte that is returned is read from the file.
181
+ const buffer = Buffer.allocUnsafe(Math.max(0, end - start));
182
+ let filled = 0;
183
+ while (filled < buffer.length) {
184
+ const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, start + filled);
185
+ if (bytesRead === 0) break;
186
+ filled += bytesRead;
187
+ }
188
+ return filled === buffer.length ? buffer : buffer.subarray(0, filled);
189
+ } finally {
190
+ await handle.close();
191
+ }
192
+ }
193
+
194
+ async putIndex(id: string, index: Uint8Array): Promise<void> {
195
+ const paths = this.paths(id);
196
+ if (!paths) throw new Error("Invalid document ID.");
197
+ await mkdir(this.directory, { recursive: true });
198
+ await writeWhole(paths.index, index);
199
+ }
200
+
201
+ async getIndex(id: string): Promise<Uint8Array | undefined> {
202
+ const paths = this.paths(id);
203
+ if (!paths) return undefined;
204
+ try {
205
+ const file = await readFile(paths.index);
206
+ return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
207
+ } catch {
208
+ return undefined;
209
+ }
210
+ }
211
+
118
212
  async delete(id: string): Promise<boolean> {
119
213
  const paths = this.paths(id);
120
214
  if (!paths) return false;
121
215
  const existed = Boolean(await readFile(paths.meta, "utf8").catch(() => null));
122
- await Promise.all([rm(paths.meta, { force: true }), rm(paths.text, { force: true }), rm(paths.original, { force: true })]);
216
+ await Promise.all([paths.meta, paths.text, paths.original, paths.index].map((file) => rm(file, { force: true })));
123
217
  return existed;
124
218
  }
125
219
 
@@ -128,7 +222,7 @@ export class FileDocumentStore implements DocumentStore {
128
222
  if (!paths) throw new Error("Invalid document ID.");
129
223
  await mkdir(this.directory, { recursive: true });
130
224
  // Written before the metadata (see put): until that exists, the document is treated as absent.
131
- await writeFile(paths.original, bytes);
225
+ await writeWhole(paths.original, bytes);
132
226
  }
133
227
 
134
228
  async getOriginal(id: string): Promise<Uint8Array | undefined> {
@@ -143,6 +237,12 @@ export class FileDocumentStore implements DocumentStore {
143
237
  }
144
238
  }
145
239
 
240
+ /**
241
+ * Removes expired documents and returns how many. Also removes files that belong to no
242
+ * document, and temporary files, once they are older than `orphanAgeMs`. A document whose
243
+ * metadata cannot be read is removed only when that file is that old too: it may be being
244
+ * written by a server of an older version, which does not write whole files.
245
+ */
146
246
  async sweep(now = this.now()): Promise<number> {
147
247
  let entries: string[];
148
248
  try {
@@ -150,14 +250,33 @@ export class FileDocumentStore implements DocumentStore {
150
250
  } catch {
151
251
  return 0;
152
252
  }
153
- let removed = 0;
253
+ const files = new Map<string, string[]>();
154
254
  for (const entry of entries) {
155
- const id = entry.replace(/\.(json|txt)$/, "");
156
- if (!entry.endsWith(".json") || !DOCUMENT_ID_PATTERN.test(id)) continue;
157
- const meta = await readFile(path.join(this.directory, entry), "utf8").then((value) => JSON.parse(value) as DocumentMeta).catch(() => null);
158
- if (!meta || expired(meta, now)) {
159
- await this.delete(id);
160
- removed++;
255
+ const match = FILE_NAME.exec(entry);
256
+ if (!match) continue;
257
+ const list = files.get(match[1]!) ?? [];
258
+ list.push(entry);
259
+ files.set(match[1]!, list);
260
+ }
261
+ const old = async (entry: string) => {
262
+ const info = await stat(path.join(this.directory, entry)).catch(() => undefined);
263
+ return info !== undefined && now.getTime() - info.mtimeMs >= this.orphanAgeMs;
264
+ };
265
+ let removed = 0;
266
+ for (const [id, names] of files) {
267
+ const metaFile = `${id}.json`;
268
+ if (names.includes(metaFile)) {
269
+ const meta = await readFile(path.join(this.directory, metaFile), "utf8").then((value) => JSON.parse(value) as DocumentMeta).catch(() => null);
270
+ if (meta ? expired(meta, now) : await old(metaFile)) {
271
+ await this.delete(id);
272
+ removed++;
273
+ continue;
274
+ }
275
+ }
276
+ // Temporary files of this document, and every file of one without metadata, once they are old.
277
+ for (const entry of names) {
278
+ if (entry === metaFile || (!entry.endsWith(".tmp") && names.includes(metaFile))) continue;
279
+ if (await old(entry)) await rm(path.join(this.directory, entry), { force: true }).catch(() => undefined);
161
280
  }
162
281
  }
163
282
  return removed;
@@ -0,0 +1,228 @@
1
+ /**
2
+ * The index of a stored text: where each line starts, as a byte offset into its UTF-8 bytes, and
3
+ * which lines start a passage (keyword search) or a page ("--- Page N ---"). With it a tool call
4
+ * reads only the lines it needs instead of loading the whole text.
5
+ *
6
+ * It is built from the bytes of the text, in one pass, at ingest (and written next to the text
7
+ * with `putIndex`), or the first time an older document without one is used.
8
+ */
9
+ import type { DocumentMeta } from "./types.js";
10
+
11
+ /** A passage, for keyword search, is a run of lines of about this many characters... */
12
+ export const PASSAGE_CHARACTERS = 1_500;
13
+ /** ...and at most this many lines. */
14
+ export const PASSAGE_MAX_LINES = 40;
15
+
16
+ export type TextIndex = {
17
+ /** Lines in the text. A newline at the very end does not start another one. */
18
+ lineCount: number;
19
+ /** UTF-8 bytes of the text. */
20
+ textBytes: number;
21
+ /** UTF-16 code units of the text, which is its `length` as a JavaScript string. */
22
+ characters: number;
23
+ /** Where line n starts: `lineStarts[n - 1]`, in bytes. */
24
+ lineStarts: Uint32Array;
25
+ /** Where line n starts in the text as a string: `characterStarts[n - 1]`, in UTF-16 units. */
26
+ characterStarts: Uint32Array;
27
+ /** The first line of each passage. */
28
+ passageStarts: Uint32Array;
29
+ /** The line of each "--- Page N ---" marker that counts up from 1. */
30
+ pageStarts: Uint32Array;
31
+ };
32
+
33
+ const PAGE_MARKER = Array.from("--- Page ", (character) => character.charCodeAt(0));
34
+ /** The longest line that is looked at as a possible page marker. */
35
+ const HEAD_BYTES = 48;
36
+
37
+ /** Builds a `TextIndex` from the bytes of a text, given in pieces of any size. */
38
+ export class TextIndexBuilder {
39
+ private starts = new Uint32Array(1_024);
40
+ private characterStarts = new Uint32Array(1_024);
41
+ private lineCount = 0;
42
+ private readonly passages: number[] = [];
43
+ private readonly pages: number[] = [];
44
+ private bytes = 0;
45
+ private characters = 0;
46
+ private inLine = false;
47
+ private lineUnits = 0;
48
+ private readonly head = new Uint8Array(HEAD_BYTES);
49
+ private headLength = 0;
50
+ private passageOpen = false;
51
+ private passageCharacters = 0;
52
+ private passageLines = 0;
53
+
54
+ push(chunk: Uint8Array): void {
55
+ for (let index = 0; index < chunk.length; index++) {
56
+ const byte = chunk[index]!;
57
+ if (!this.inLine) this.startLine();
58
+ if (byte === 10) {
59
+ this.endLine();
60
+ this.characters++;
61
+ } else {
62
+ if (this.headLength < HEAD_BYTES) this.head[this.headLength] = byte;
63
+ this.headLength++;
64
+ // A UTF-8 sequence is one UTF-16 unit, or two for one of four bytes (outside the basic plane).
65
+ if ((byte & 0xc0) !== 0x80) {
66
+ const units = byte >= 0xf0 ? 2 : 1;
67
+ this.lineUnits += units;
68
+ this.characters += units;
69
+ }
70
+ }
71
+ this.bytes++;
72
+ }
73
+ }
74
+
75
+ finish(): TextIndex {
76
+ if (this.inLine) this.endLine();
77
+ return {
78
+ lineCount: this.lineCount,
79
+ textBytes: this.bytes,
80
+ characters: this.characters,
81
+ lineStarts: this.starts.slice(0, this.lineCount),
82
+ characterStarts: this.characterStarts.slice(0, this.lineCount),
83
+ passageStarts: Uint32Array.from(this.passages),
84
+ pageStarts: Uint32Array.from(this.pages),
85
+ };
86
+ }
87
+
88
+ private startLine(): void {
89
+ if (this.lineCount === this.starts.length) {
90
+ const grown = new Uint32Array(this.starts.length * 2);
91
+ grown.set(this.starts);
92
+ this.starts = grown;
93
+ const grownCharacters = new Uint32Array(this.characterStarts.length * 2);
94
+ grownCharacters.set(this.characterStarts);
95
+ this.characterStarts = grownCharacters;
96
+ }
97
+ this.characterStarts[this.lineCount] = this.characters;
98
+ this.starts[this.lineCount++] = this.bytes;
99
+ this.inLine = true;
100
+ this.lineUnits = 0;
101
+ this.headLength = 0;
102
+ }
103
+
104
+ private endLine(): void {
105
+ const line = this.lineCount;
106
+ // Passages: the same rule as SearchableDocument.passages, one line at a time.
107
+ if (!this.passageOpen) {
108
+ this.passages.push(line);
109
+ this.passageOpen = true;
110
+ this.passageCharacters = 0;
111
+ this.passageLines = 0;
112
+ }
113
+ this.passageCharacters += this.lineUnits + 1;
114
+ this.passageLines++;
115
+ if (this.passageLines >= PASSAGE_MAX_LINES || this.passageCharacters >= PASSAGE_CHARACTERS) this.passageOpen = false;
116
+ // Pages: a line that is exactly the next marker. The marker is ASCII, so bytes compare as text.
117
+ if (this.headLength <= HEAD_BYTES && this.headLength > PAGE_MARKER.length && PAGE_MARKER.every((code, at) => this.head[at] === code)) {
118
+ let marker = "";
119
+ for (let at = 0; at < this.headLength; at++) marker += String.fromCharCode(this.head[at]!);
120
+ if (marker === `--- Page ${this.pages.length + 1} ---`) this.pages.push(line);
121
+ }
122
+ this.inLine = false;
123
+ }
124
+ }
125
+
126
+ /** The index of a text held as a string, built from its UTF-8 bytes a slice at a time. */
127
+ export function buildTextIndex(text: string): TextIndex {
128
+ const builder = new TextIndexBuilder();
129
+ const slice = 1 << 20;
130
+ for (let at = 0; at < text.length;) {
131
+ let end = Math.min(text.length, at + slice);
132
+ // Never cut between the two halves of a surrogate pair: each half alone encodes as U+FFFD.
133
+ const last = text.charCodeAt(end - 1);
134
+ if (end < text.length && last >= 0xd800 && last <= 0xdbff) end++;
135
+ builder.push(Buffer.from(text.slice(at, end), "utf8"));
136
+ at = end;
137
+ }
138
+ return builder.finish();
139
+ }
140
+
141
+ // The file: a 40-byte header, then the lists of 32-bit numbers (line starts in bytes, line starts
142
+ // in characters, passage starts, page starts), all little-endian.
143
+ // 0 "LLFI" 4 version 8 lineCount 12 passages 16 pages 20 unused
144
+ // 24 textBytes (float64) 32 characters (float64)
145
+ const MAGIC = [0x4c, 0x4c, 0x46, 0x49];
146
+ const VERSION = 1;
147
+ const HEADER = 40;
148
+ const LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
149
+
150
+ /** Whether an index can be written in this format: offsets are 32-bit. */
151
+ export function canSerialize(index: TextIndex): boolean {
152
+ return index.textBytes <= 0xffff_ffff;
153
+ }
154
+
155
+ export function serializeTextIndex(index: TextIndex): Uint8Array {
156
+ const counts = [index.lineStarts.length, index.passageStarts.length, index.pageStarts.length];
157
+ const out = new Uint8Array(HEADER + 4 * (2 * counts[0]! + counts[1]! + counts[2]!));
158
+ const view = new DataView(out.buffer);
159
+ MAGIC.forEach((byte, at) => view.setUint8(at, byte));
160
+ view.setUint32(4, VERSION, true);
161
+ view.setUint32(8, counts[0]!, true);
162
+ view.setUint32(12, counts[1]!, true);
163
+ view.setUint32(16, counts[2]!, true);
164
+ view.setFloat64(24, index.textBytes, true);
165
+ view.setFloat64(32, index.characters, true);
166
+ let at = HEADER;
167
+ for (const list of [index.lineStarts, index.characterStarts, index.passageStarts, index.pageStarts]) {
168
+ if (LITTLE_ENDIAN) out.set(new Uint8Array(list.buffer, list.byteOffset, list.byteLength), at);
169
+ else list.forEach((value, i) => view.setUint32(at + 4 * i, value, true));
170
+ at += list.byteLength;
171
+ }
172
+ return out;
173
+ }
174
+
175
+ function readList(bytes: Uint8Array, at: number, count: number): Uint32Array {
176
+ if (LITTLE_ENDIAN) return new Uint32Array(bytes.slice(at, at + 4 * count).buffer);
177
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
178
+ return Uint32Array.from({ length: count }, (_, i) => view.getUint32(at + 4 * i, true));
179
+ }
180
+
181
+ const ascending = (list: Uint32Array, first: number, last: number): boolean => {
182
+ let previous = -1;
183
+ for (const value of list) {
184
+ if (value <= previous || value < first || value > last) return false;
185
+ previous = value;
186
+ }
187
+ return true;
188
+ };
189
+
190
+ /**
191
+ * Reads an index written by `serializeTextIndex`. Undefined when it is damaged, cut short, of
192
+ * another version, or does not describe the text of `meta`: the caller then builds it again from
193
+ * the text. An index is only a faster way to the same text, so a doubtful one is never used.
194
+ */
195
+ export function parseTextIndex(bytes: Uint8Array, meta?: Pick<DocumentMeta, "lines" | "characters">): TextIndex | undefined {
196
+ if (bytes.length < HEADER || MAGIC.some((byte, at) => bytes[at] !== byte)) return undefined;
197
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
198
+ if (view.getUint32(4, true) !== VERSION) return undefined;
199
+ const lineCount = view.getUint32(8, true);
200
+ const passageCount = view.getUint32(12, true);
201
+ const pageCount = view.getUint32(16, true);
202
+ const textBytes = view.getFloat64(24, true);
203
+ const characters = view.getFloat64(32, true);
204
+ if (bytes.length !== HEADER + 4 * (2 * lineCount + passageCount + pageCount)) return undefined;
205
+ if (!Number.isSafeInteger(textBytes) || !Number.isSafeInteger(characters) || lineCount < 1 || passageCount < 1) return undefined;
206
+ if (meta && (meta.lines !== lineCount || meta.characters !== characters)) return undefined;
207
+ const lineStarts = readList(bytes, HEADER, lineCount);
208
+ const characterStarts = readList(bytes, HEADER + 4 * lineCount, lineCount);
209
+ const passageStarts = readList(bytes, HEADER + 8 * lineCount, passageCount);
210
+ const pageStarts = readList(bytes, HEADER + 4 * (2 * lineCount + passageCount), pageCount);
211
+ if (lineStarts[0] !== 0 || !ascending(lineStarts, 0, textBytes - 1)) return undefined;
212
+ if (characterStarts[0] !== 0 || !ascending(characterStarts, 0, characters - 1)) return undefined;
213
+ if (passageStarts[0] !== 1 || !ascending(passageStarts, 1, lineCount)) return undefined;
214
+ if (!ascending(pageStarts, 1, lineCount)) return undefined;
215
+ return { lineCount, textBytes, characters, lineStarts, characterStarts, passageStarts, pageStarts };
216
+ }
217
+
218
+ /** The 1-based position of `line` among sorted `starts`: the page or passage a line is in. */
219
+ export function positionOf(starts: ArrayLike<number>, line: number): number {
220
+ let low = 0;
221
+ let high = starts.length - 1;
222
+ while (low < high) {
223
+ const middle = (low + high + 1) >> 1;
224
+ if (starts[middle]! <= line) low = middle;
225
+ else high = middle - 1;
226
+ }
227
+ return low + 1;
228
+ }
package/src/text.ts CHANGED
@@ -2,11 +2,14 @@
2
2
  export const MAX_LINE_CHARACTERS = 2_000;
3
3
 
4
4
  /**
5
- * Terminal escape sequences: CSI ("ESC [ 31 m"), OSC ("ESC ] ... BEL"), character-set selection
6
- * ("ESC ( B"), and two-character escapes. Coloured logs are full of them.
5
+ * Terminal escape sequences: CSI ("ESC [ 31 m"), OSC ("ESC ] 0;title BEL", ended by BEL or
6
+ * "ESC \" on the same line), character-set selection ("ESC ( B"), and two-character escapes
7
+ * ("ESC 7", "ESC c"). Coloured logs are full of them. An "ESC ]" whose end is not on its line is
8
+ * not a sequence: only those two characters go. Otherwise one stray "ESC ]", a cut-off window title
9
+ * or two bytes in a logged user agent, would take every line after it.
7
10
  */
8
11
  // eslint-disable-next-line no-control-regex
9
- const ANSI_ESCAPE = /\x1b(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)?|[ -\/]+[0-~]|[@-Z\\-_])/g;
12
+ const ANSI_ESCAPE = /\x1b(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1b\n]*(?:\x07|\x1b\\)|[ -\/]+[0-~]|[0-~])/g;
10
13
 
11
14
  /**
12
15
  * Strips a BOM, unifies line endings, and removes terminal escape sequences and control characters
@@ -194,7 +197,13 @@ export class LineIndex {
194
197
  private readonly starts: Uint32Array;
195
198
  readonly lineCount: number;
196
199
 
197
- constructor(private readonly text: string) {
200
+ /** `knownStarts`, when given, are where each line starts in `text`: they are used as they are. */
201
+ constructor(private readonly text: string, knownStarts?: Uint32Array) {
202
+ if (knownStarts) {
203
+ this.starts = knownStarts;
204
+ this.lineCount = knownStarts.length;
205
+ return;
206
+ }
198
207
  let count = 1;
199
208
  for (let at = text.indexOf("\n"); at !== -1; at = text.indexOf("\n", at + 1)) count++;
200
209
  // A trailing newline does not start another line.
package/src/tools.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { analyzeWholeDocument, splitIntoParts } from "./map-reduce.js";
1
+ import { analyzeWholeDocument, partsOf } from "./map-reduce.js";
2
2
  import { cutPdfPages } from "./pdf-pages.js";
3
- import { grep, rankPassages, type SearchableDocument } from "./search.js";
3
+ import { grepSource, numberLines, rankSource, type DocumentSource } from "./search.js";
4
4
  import { formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
5
5
  import type { Budget, GenerateText, ProgressListener, ToolDeclaration, ToolFileLimits, ToolOutput, ToolResult, ToolSet } from "./types.js";
6
6
 
@@ -153,7 +153,7 @@ export function toolResultSummary(label: string, result: ToolResult): string {
153
153
 
154
154
  export function createDocumentTools(options: {
155
155
  /** Loads a document the tools may access. Return undefined for anything out of scope. */
156
- load(documentId: string): Promise<SearchableDocument | undefined>;
156
+ load(documentId: string): Promise<DocumentSource | undefined>;
157
157
  documentIds: string[];
158
158
  /** File names by document ID, so `describe` can name files before they are loaded. */
159
159
  names?: Record<string, string>;
@@ -184,7 +184,7 @@ export function createDocumentTools(options: {
184
184
  // When no limit is given with a call: three eighths of a request, so that two looks still fit.
185
185
  const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
186
186
 
187
- async function documentFor(args: Record<string, unknown>): Promise<SearchableDocument> {
187
+ async function documentFor(args: Record<string, unknown>): Promise<DocumentSource> {
188
188
  const id = text(args.document_id, "document_id");
189
189
  // Scope check: a model can only reach files attached to this conversation.
190
190
  if (!allowed.has(id)) throw new Error(`Unknown document_id ${id}. Use an ID from a file card.`);
@@ -204,27 +204,29 @@ export function createDocumentTools(options: {
204
204
  const paged = viewable.has(document.meta.id);
205
205
  if (mode === "keywords") {
206
206
  const topK = integer(args.max_results, 5, 1, 10);
207
- const ranked = rankPassages(document, query, topK);
207
+ const ranked = await rankSource(document, query, topK, options.signal);
208
+ const texts = await Promise.all(ranked.map((passage) => document.readLines(passage.from, passage.to)));
208
209
  return fit({
209
210
  document: document.meta.name,
210
211
  mode,
211
- passages: ranked.map((passage) => {
212
+ passages: ranked.map((passage, index) => {
212
213
  const pages = paged ? document.pagesOfLines(passage.from, passage.to) : undefined;
213
214
  return {
214
215
  lines: `${passage.from}-${passage.to}`,
215
216
  ...(pages ? { pages } : {}),
216
217
  score: passage.score,
217
- text: document.lines.numbered(passage.from, passage.to),
218
+ text: numberLines(texts[index]!, passage.from),
218
219
  };
219
220
  }),
220
221
  ...(ranked.length === 0 ? { note: "No passage contains these keywords. Try other words, synonyms, or exact mode." } : {}),
221
222
  }, "passages", limit);
222
223
  }
223
- const result = grep(document, query, {
224
+ const result = await grepSource(document, query, {
224
225
  regex: mode === "regex",
225
226
  caseSensitive: args.case_sensitive === true,
226
227
  maxResults: integer(args.max_results, 20, 1, 50),
227
228
  contextLines: integer(args.context_lines, 0, 0, 5),
229
+ ...(options.signal ? { signal: options.signal } : {}),
228
230
  });
229
231
  return fit({
230
232
  document: document.meta.name,
@@ -240,14 +242,16 @@ export function createDocumentTools(options: {
240
242
 
241
243
  async [TOOL_NAMES.read](args) {
242
244
  const document = await documentFor(args);
243
- const total = document.lines.lineCount;
245
+ const total = document.lineCount;
244
246
  const start = integer(args.start_line, 1, 1, total);
245
247
  const end = integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, Math.min(total, start + MAX_READ_LINES - 1));
248
+ // One read for the range asked; trimming to the size limit works on what was read.
249
+ const read = await document.readLines(start, end);
246
250
  let to = end;
247
- let body = document.lines.numbered(start, to);
251
+ let body = numberLines(read, start);
248
252
  while (body.length > limit - 500 && to > start) {
249
253
  to = start + Math.max(0, Math.floor((to - start) * 0.7));
250
- body = document.lines.numbered(start, to);
254
+ body = numberLines(read.slice(0, to - start + 1), start);
251
255
  }
252
256
  const pages = viewable.has(document.meta.id) ? document.pagesOfLines(start, to) : undefined;
253
257
  return {
@@ -262,8 +266,10 @@ export function createDocumentTools(options: {
262
266
 
263
267
  async [TOOL_NAMES.overview](args) {
264
268
  const document = await documentFor(args);
265
- const { meta, lines } = document;
266
- const tail = Math.max(1, lines.lineCount - 19);
269
+ const { meta, lineCount } = document;
270
+ const tail = Math.max(1, lineCount - 19);
271
+ const parts = await partsOf(document, options.budget, options.signal);
272
+ const first = Math.min(30, lineCount);
267
273
  return fit({
268
274
  document: meta.name,
269
275
  format: meta.format,
@@ -271,10 +277,10 @@ export function createDocumentTools(options: {
271
277
  lines: meta.lines,
272
278
  estimated_tokens: meta.estimatedTokens,
273
279
  ...(meta.pages ? { pages: meta.pages } : {}),
274
- parts_for_whole_document_analysis: splitIntoParts(document, options.budget).length,
280
+ parts_for_whole_document_analysis: parts.length,
275
281
  ...(meta.logProfile ? { log_profile: meta.logProfile } : {}),
276
- first_lines: lines.numbered(1, Math.min(30, lines.lineCount)),
277
- last_lines: lines.lineCount > 30 ? lines.numbered(tail, lines.lineCount) : "",
282
+ first_lines: numberLines(await document.readLines(1, first), 1),
283
+ last_lines: lineCount > 30 ? numberLines(await document.readLines(tail, lineCount), tail) : "",
278
284
  outline: meta.outline.length ? outlineLines(meta.outline) : [],
279
285
  }, "outline", limit);
280
286
  },
package/src/types.ts CHANGED
@@ -87,6 +87,21 @@ export interface DocumentStore {
87
87
  putOriginal?(id: string, bytes: Uint8Array): Promise<void>;
88
88
  /** The uploaded file, or undefined when none was kept or the document is unknown or expired. */
89
89
  getOriginal?(id: string): Promise<Uint8Array | undefined>;
90
+ /**
91
+ * Bytes `start` (inclusive) to `end` (exclusive) of the stored text, as UTF-8. Optional: with it,
92
+ * a tool call reads only the lines it needs, and a search reads the text a piece at a time,
93
+ * instead of loading the whole text into memory. Return fewer bytes at the end of the text, and
94
+ * undefined when the document is gone. It is called only after `getMeta` found the document.
95
+ */
96
+ readTextRange?(id: string, start: number, end: number): Promise<Uint8Array | undefined>;
97
+ /**
98
+ * Keeps the line index of a document (a few bytes a line), so that reading by range needs no
99
+ * pass over the text first. Called at ingest, before `put`, and when an older document without an
100
+ * index is first read. Optional, and only useful with `readTextRange`.
101
+ */
102
+ putIndex?(id: string, index: Uint8Array): Promise<void>;
103
+ /** The index kept by `putIndex`, or undefined. A damaged one is noticed and built again. */
104
+ getIndex?(id: string): Promise<Uint8Array | undefined>;
90
105
  }
91
106
 
92
107
  export type ExtractedText = { text: string; pages?: number };