llm-large-files 0.4.0 → 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.
- package/CHANGELOG.md +78 -0
- package/dist/cache.d.ts +11 -2
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +36 -7
- package/dist/cache.js.map +1 -1
- package/dist/errors.d.ts +21 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +44 -0
- package/dist/errors.js.map +1 -0
- package/dist/gemini/chat.d.ts +5 -0
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +17 -1
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -0
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +110 -25
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +1 -1
- package/dist/gemini/index.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +21 -2
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +46 -14
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +6 -0
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +34 -9
- package/dist/map-reduce.js.map +1 -1
- package/dist/plan.d.ts +20 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +44 -7
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts +2 -2
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +11 -4
- package/dist/ranged.js.map +1 -1
- package/dist/search.d.ts +16 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +109 -26
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +5 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +58 -15
- package/dist/stores.js.map +1 -1
- package/dist/text.d.ts +12 -1
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +43 -15
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +12 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +37 -11
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +5 -0
- package/dist/types.d.ts.map +1 -1
- package/docs/api.md +13 -6
- package/docs/configuration.md +6 -1
- package/docs/getting-started.md +2 -0
- package/docs/how-it-works.md +8 -2
- package/docs/security.md +18 -3
- package/package.json +1 -1
- package/src/cache.ts +32 -8
- package/src/errors.ts +42 -0
- package/src/gemini/chat.ts +22 -1
- package/src/gemini/generate.ts +107 -25
- package/src/gemini/index.ts +1 -1
- package/src/index.ts +3 -2
- package/src/library.ts +63 -16
- package/src/map-reduce.ts +31 -8
- package/src/plan.ts +46 -7
- package/src/ranged.ts +13 -6
- package/src/search.ts +116 -25
- package/src/stores.ts +51 -15
- package/src/text.ts +39 -12
- package/src/tools.ts +43 -11
- package/src/types.ts +5 -0
package/src/search.ts
CHANGED
|
@@ -6,7 +6,14 @@ import type { DocumentMeta, StoredDocument } from "./types.js";
|
|
|
6
6
|
const MAX_OCCURRENCES_PER_TERM = 200_000;
|
|
7
7
|
const MAX_EXACT_MATCHES = 1_000_000;
|
|
8
8
|
const MAX_PHRASE_PASSAGES = 10_000;
|
|
9
|
-
|
|
9
|
+
/** The most time one regex search may spend matching. */
|
|
10
|
+
export const REGEX_TIME_LIMIT_MS = 3_000;
|
|
11
|
+
/**
|
|
12
|
+
* A regex scan runs in slices of this length, and other work gets a turn between two slices. A
|
|
13
|
+
* line that takes two whole slices is a pattern that backtracks without end on it: the search
|
|
14
|
+
* stops there, long before its time limit.
|
|
15
|
+
*/
|
|
16
|
+
const REGEX_SLICE_MS = 250;
|
|
10
17
|
const SHOWN_LINE_CHARACTERS = 400;
|
|
11
18
|
|
|
12
19
|
const STOPWORDS = new Set([
|
|
@@ -53,13 +60,31 @@ export interface DocumentSource {
|
|
|
53
60
|
* Optional: feeds the pieces in order to `feed` until it returns true, sharing one pass over the
|
|
54
61
|
* text with other scans of the same document where it can.
|
|
55
62
|
*/
|
|
56
|
-
scan?(feed:
|
|
63
|
+
scan?(feed: ScanFeed, signal?: AbortSignal): Promise<void>;
|
|
57
64
|
}
|
|
58
65
|
|
|
66
|
+
/**
|
|
67
|
+
* What a scan does with a piece of the text. True: it has all it needs, so nothing more is read.
|
|
68
|
+
* "again": it stopped part-way through the piece to let other work run, and wants the same piece
|
|
69
|
+
* once more.
|
|
70
|
+
*/
|
|
71
|
+
export type ScanFeed = (chunk: TextChunk) => boolean | void | "again";
|
|
72
|
+
|
|
73
|
+
/** Lets other work on the server run (an answer streaming to another user) before going on. */
|
|
74
|
+
export const pause = () => new Promise<void>((resolve) => setImmediate(resolve));
|
|
75
|
+
|
|
59
76
|
/** Feeds a document's text, a piece at a time, to `feed` until it returns true or the text ends. */
|
|
60
|
-
export async function scanSource(source: DocumentSource, feed:
|
|
77
|
+
export async function scanSource(source: DocumentSource, feed: ScanFeed, signal?: AbortSignal): Promise<void> {
|
|
61
78
|
if (source.scan) return source.scan(feed, signal);
|
|
62
|
-
for await (const chunk of source.chunks(signal))
|
|
79
|
+
for await (const chunk of source.chunks(signal)) {
|
|
80
|
+
let more = feed(chunk);
|
|
81
|
+
while (more === "again") {
|
|
82
|
+
await pause();
|
|
83
|
+
signal?.throwIfAborted();
|
|
84
|
+
more = feed(chunk);
|
|
85
|
+
}
|
|
86
|
+
if (more === true) break;
|
|
87
|
+
}
|
|
63
88
|
}
|
|
64
89
|
|
|
65
90
|
/** Lines as the tools show them: "12| text", one a line. */
|
|
@@ -212,6 +237,8 @@ export type GrepOptions = {
|
|
|
212
237
|
contextLines: number;
|
|
213
238
|
/** Regex mode only. Defaults to 3 seconds of scanning. */
|
|
214
239
|
timeLimitMs?: number;
|
|
240
|
+
/** Regex mode only: the time spent matching is added to `usedMs`, for a caller that keeps a budget over several searches. */
|
|
241
|
+
regexClock?: { usedMs: number };
|
|
215
242
|
};
|
|
216
243
|
|
|
217
244
|
function clip(line: string, column: number): string {
|
|
@@ -263,6 +290,19 @@ export function unsafeRegexReason(pattern: string): string | null {
|
|
|
263
290
|
return null;
|
|
264
291
|
}
|
|
265
292
|
|
|
293
|
+
/**
|
|
294
|
+
* The pattern as a regular expression. With the Unicode flag when the pattern allows it, so that
|
|
295
|
+
* `\p{L}` means a letter and a character outside the basic plane is one character; without it for
|
|
296
|
+
* a pattern that is only valid the old way (`[\w-.]`, `\-`).
|
|
297
|
+
*/
|
|
298
|
+
function compileRegex(pattern: string, flags: string): RegExp {
|
|
299
|
+
try {
|
|
300
|
+
return new RegExp(pattern, `${flags}u`);
|
|
301
|
+
} catch {
|
|
302
|
+
return new RegExp(pattern, flags);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
266
306
|
const newlinesIn = (text: string) => text.split("\n").length - 1;
|
|
267
307
|
|
|
268
308
|
/**
|
|
@@ -308,13 +348,17 @@ class LineSearch {
|
|
|
308
348
|
private lastLine = 0;
|
|
309
349
|
private readonly pattern?: RegExp;
|
|
310
350
|
private timeLeft: number;
|
|
351
|
+
/** Regex mode: the piece whose scan stopped at the end of a time slice, and the next line of it to look at. */
|
|
352
|
+
private unfinished?: { chunk: TextChunk; next: number };
|
|
353
|
+
/** Regex mode: the line that took a whole slice without being finished. A second such slice ends the search. */
|
|
354
|
+
private stuck?: number;
|
|
311
355
|
|
|
312
356
|
constructor(query: string, private readonly settings: GrepOptions, private readonly lineCount: number) {
|
|
313
357
|
if (!query) throw new Error("The search query is empty.");
|
|
314
358
|
if (settings.regex) {
|
|
315
359
|
const problem = unsafeRegexReason(query);
|
|
316
360
|
if (problem) throw new Error(problem);
|
|
317
|
-
this.pattern =
|
|
361
|
+
this.pattern = compileRegex(query, settings.caseSensitive ? "" : "i");
|
|
318
362
|
} else {
|
|
319
363
|
this.needle = settings.caseSensitive ? query : foldCase(query);
|
|
320
364
|
this.newlines = newlinesIn(this.needle);
|
|
@@ -324,10 +368,25 @@ class LineSearch {
|
|
|
324
368
|
this.keep = this.context + this.newlines;
|
|
325
369
|
}
|
|
326
370
|
|
|
371
|
+
/** Scans a piece to its end, without a pause: for a caller that cannot wait. See `addSome`. */
|
|
327
372
|
add(chunk: TextChunk): void {
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
373
|
+
while (!this.addSome(chunk)) {
|
|
374
|
+
// The next slice of a regex scan.
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Scans a piece, or goes on scanning it. False means that a regex scan reached the end of a time
|
|
380
|
+
* slice with lines of this piece still to look at: let other work run, then call this again with
|
|
381
|
+
* the same piece. Exact search always finishes the piece.
|
|
382
|
+
*/
|
|
383
|
+
addSome(chunk: TextChunk): boolean {
|
|
384
|
+
if (this.done) return true;
|
|
385
|
+
if (this.pattern) {
|
|
386
|
+
if (!this.scanRegex(chunk)) return false;
|
|
387
|
+
} else {
|
|
388
|
+
this.scanExact(chunk);
|
|
389
|
+
}
|
|
331
390
|
if (this.unfilled > 0) {
|
|
332
391
|
const last = chunk.firstLine + chunk.lines.lineCount - 1;
|
|
333
392
|
for (const [line, text] of this.shown) {
|
|
@@ -339,6 +398,7 @@ class LineSearch {
|
|
|
339
398
|
}
|
|
340
399
|
}
|
|
341
400
|
this.recent = remember(this.recent, chunk, this.keep);
|
|
401
|
+
return true;
|
|
342
402
|
}
|
|
343
403
|
|
|
344
404
|
/** Lines to show that were not in the pieces read (the scan stopped early). Read them and `fill` them. */
|
|
@@ -410,27 +470,52 @@ class LineSearch {
|
|
|
410
470
|
}
|
|
411
471
|
}
|
|
412
472
|
|
|
413
|
-
|
|
414
|
-
|
|
473
|
+
/**
|
|
474
|
+
* One time slice of a regex scan of a piece. True when the piece is finished, or the search is
|
|
475
|
+
* (out of time, or stopped at a line the pattern cannot get past); false when lines of the piece
|
|
476
|
+
* are left for the next slice.
|
|
477
|
+
*/
|
|
478
|
+
private scanRegex(chunk: TextChunk): boolean {
|
|
479
|
+
const stop = (): true => {
|
|
415
480
|
this.stoppedEarly = true;
|
|
416
481
|
this.done = true;
|
|
417
|
-
return;
|
|
418
|
-
}
|
|
482
|
+
return true;
|
|
483
|
+
};
|
|
484
|
+
// Where to go on: in a piece that was left at the end of a slice, or at the start of a new one.
|
|
485
|
+
let next = this.unfinished?.chunk === chunk ? this.unfinished.next : 1;
|
|
486
|
+
this.unfinished = undefined;
|
|
487
|
+
if (this.timeLeft <= 0) return stop();
|
|
419
488
|
const pattern = this.pattern!;
|
|
420
489
|
const { lines, firstLine } = chunk;
|
|
490
|
+
const from = next;
|
|
491
|
+
const slice = Math.min(this.timeLeft, REGEX_SLICE_MS);
|
|
421
492
|
const started = performance.now();
|
|
422
493
|
const finished = withinTimeLimit(() => {
|
|
423
|
-
for (
|
|
424
|
-
const
|
|
494
|
+
for (; next <= lines.lineCount; next++) {
|
|
495
|
+
const line = firstLine + next - 1;
|
|
496
|
+
const text = lines.line(next);
|
|
425
497
|
const match = pattern.exec(text);
|
|
426
|
-
|
|
498
|
+
// A line is recorded once, also when a slice ended while it was being recorded and it is looked at again.
|
|
499
|
+
if (match && line > this.lastLine) {
|
|
500
|
+
this.lastLine = line;
|
|
501
|
+
this.record(line, match.index, text);
|
|
502
|
+
}
|
|
427
503
|
}
|
|
428
|
-
},
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
504
|
+
}, slice);
|
|
505
|
+
const spent = performance.now() - started;
|
|
506
|
+
this.timeLeft -= spent;
|
|
507
|
+
if (this.settings.regexClock) this.settings.regexClock.usedMs += spent;
|
|
508
|
+
if (finished) return true;
|
|
509
|
+
if (this.timeLeft <= 0) return stop();
|
|
510
|
+
// The slice ended in the middle of line `next`. A whole slice without one line finished can be
|
|
511
|
+
// a stall of the machine, once. Twice on the same line, it is the pattern.
|
|
512
|
+
if (next === from && slice >= REGEX_SLICE_MS) {
|
|
513
|
+
const line = firstLine + next - 1;
|
|
514
|
+
if (this.stuck === line) return stop();
|
|
515
|
+
this.stuck = line;
|
|
433
516
|
}
|
|
517
|
+
this.unfinished = { chunk, next };
|
|
518
|
+
return false;
|
|
434
519
|
}
|
|
435
520
|
}
|
|
436
521
|
|
|
@@ -455,12 +540,18 @@ export function grep(document: SearchableDocument, query: string, options: GrepO
|
|
|
455
540
|
|
|
456
541
|
/** `grep` over any document: one held in memory, or one read from the store a piece at a time. */
|
|
457
542
|
export async function grepSource(source: DocumentSource, query: string, options: GrepOptions & { signal?: AbortSignal }): Promise<GrepResult> {
|
|
458
|
-
if (source instanceof SearchableDocument) return grep(source, query, options);
|
|
459
543
|
const search = new LineSearch(query, options, source.lineCount);
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
544
|
+
if (source instanceof SearchableDocument) {
|
|
545
|
+
const chunk = source.wholeChunk();
|
|
546
|
+
// A regex scan runs a slice at a time, and other work gets a turn between two slices.
|
|
547
|
+
while (!search.addSome(chunk)) {
|
|
548
|
+
await pause();
|
|
549
|
+
options.signal?.throwIfAborted();
|
|
550
|
+
}
|
|
551
|
+
for (const line of search.missing()) search.fill(line, source.lines.line(line));
|
|
552
|
+
return search.result();
|
|
553
|
+
}
|
|
554
|
+
await scanSource(source, (chunk) => (search.addSome(chunk) ? search.done : "again"), options.signal);
|
|
464
555
|
const missing = search.missing();
|
|
465
556
|
if (missing.length) await readSome(source, missing, (line, text) => search.fill(line, text));
|
|
466
557
|
return search.result();
|
package/src/stores.ts
CHANGED
|
@@ -74,6 +74,18 @@ const RETRY_RENAME = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
|
74
74
|
const RENAME_PAUSES_MS = [10, 20, 40, 80, 160, 320, 500, 500, 500, 500];
|
|
75
75
|
|
|
76
76
|
const code = (error: unknown) => (error as { code?: unknown } | null)?.code;
|
|
77
|
+
/** There is no such file. Every other failure (a volume that does not answer, too many open files) says nothing about the file. */
|
|
78
|
+
const missing = (error: unknown) => code(error) === "ENOENT";
|
|
79
|
+
|
|
80
|
+
/** Metadata as it was written, or undefined for text that is not that: cut short, or damaged. */
|
|
81
|
+
function parseMeta(raw: string): DocumentMeta | undefined {
|
|
82
|
+
try {
|
|
83
|
+
const meta = JSON.parse(raw) as DocumentMeta | null;
|
|
84
|
+
return meta !== null && typeof meta === "object" && typeof meta.expiresAt === "string" ? meta : undefined;
|
|
85
|
+
} catch {
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
77
89
|
|
|
78
90
|
/**
|
|
79
91
|
* Writes a file whole or not at all, as other processes see it: to a temporary name first, then
|
|
@@ -142,12 +154,18 @@ export class FileDocumentStore implements DocumentStore {
|
|
|
142
154
|
async getMeta(id: string): Promise<DocumentMeta | undefined> {
|
|
143
155
|
const paths = this.paths(id);
|
|
144
156
|
if (!paths) return undefined;
|
|
145
|
-
let
|
|
157
|
+
let raw: string;
|
|
146
158
|
try {
|
|
147
|
-
|
|
148
|
-
} catch {
|
|
149
|
-
|
|
159
|
+
raw = await readFile(paths.meta, "utf8");
|
|
160
|
+
} catch (error) {
|
|
161
|
+
// Only a file that is not there means that the document is not there. A read that failed for
|
|
162
|
+
// another reason is thrown, so that a busy volume is not taken for a deleted document.
|
|
163
|
+
if (missing(error)) return undefined;
|
|
164
|
+
throw error;
|
|
150
165
|
}
|
|
166
|
+
// Metadata that cannot be parsed is an upload being written by a server of 0.3.x, or damaged: absent.
|
|
167
|
+
const meta = parseMeta(raw);
|
|
168
|
+
if (!meta) return undefined;
|
|
151
169
|
if (expired(meta, this.now())) {
|
|
152
170
|
await this.delete(id);
|
|
153
171
|
return undefined;
|
|
@@ -161,8 +179,9 @@ export class FileDocumentStore implements DocumentStore {
|
|
|
161
179
|
if (!meta || !paths) return undefined;
|
|
162
180
|
try {
|
|
163
181
|
return { meta, text: await readFile(paths.text, "utf8") };
|
|
164
|
-
} catch {
|
|
165
|
-
return undefined;
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if (missing(error)) return undefined;
|
|
184
|
+
throw error;
|
|
166
185
|
}
|
|
167
186
|
}
|
|
168
187
|
|
|
@@ -213,7 +232,11 @@ export class FileDocumentStore implements DocumentStore {
|
|
|
213
232
|
const paths = this.paths(id);
|
|
214
233
|
if (!paths) return false;
|
|
215
234
|
const existed = Boolean(await readFile(paths.meta, "utf8").catch(() => null));
|
|
216
|
-
|
|
235
|
+
// The metadata first: a document is there while its metadata is. If that file cannot be removed,
|
|
236
|
+
// nothing else is, and the document stays whole. The other way round, a document whose text is
|
|
237
|
+
// gone would still be listed.
|
|
238
|
+
await rm(paths.meta, { force: true });
|
|
239
|
+
await Promise.all([paths.text, paths.original, paths.index].map((file) => rm(file, { force: true })));
|
|
217
240
|
return existed;
|
|
218
241
|
}
|
|
219
242
|
|
|
@@ -232,16 +255,21 @@ export class FileDocumentStore implements DocumentStore {
|
|
|
232
255
|
try {
|
|
233
256
|
const file = await readFile(paths.original);
|
|
234
257
|
return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
|
|
235
|
-
} catch {
|
|
236
|
-
return undefined;
|
|
258
|
+
} catch (error) {
|
|
259
|
+
if (missing(error)) return undefined;
|
|
260
|
+
throw error;
|
|
237
261
|
}
|
|
238
262
|
}
|
|
239
263
|
|
|
240
264
|
/**
|
|
241
265
|
* Removes expired documents and returns how many. Also removes files that belong to no
|
|
242
266
|
* document, and temporary files, once they are older than `orphanAgeMs`. A document whose
|
|
243
|
-
* metadata
|
|
267
|
+
* metadata is not valid is removed only when that file is that old too: it may be being
|
|
244
268
|
* written by a server of an older version, which does not write whole files.
|
|
269
|
+
*
|
|
270
|
+
* A document whose metadata could not be read at all (the volume did not answer, too many files
|
|
271
|
+
* were open) is left alone, whatever its age: the next sweep looks at it again. A document that
|
|
272
|
+
* cannot be removed is left for the next sweep too, and does not stop this one.
|
|
245
273
|
*/
|
|
246
274
|
async sweep(now = this.now()): Promise<number> {
|
|
247
275
|
let entries: string[];
|
|
@@ -266,11 +294,19 @@ export class FileDocumentStore implements DocumentStore {
|
|
|
266
294
|
for (const [id, names] of files) {
|
|
267
295
|
const metaFile = `${id}.json`;
|
|
268
296
|
if (names.includes(metaFile)) {
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
await this.
|
|
272
|
-
|
|
273
|
-
|
|
297
|
+
let raw: string | undefined;
|
|
298
|
+
try {
|
|
299
|
+
raw = await readFile(path.join(this.directory, metaFile), "utf8");
|
|
300
|
+
} catch (error) {
|
|
301
|
+
// Not read is not the same as not valid: nothing of this document is touched.
|
|
302
|
+
if (!missing(error)) continue;
|
|
303
|
+
}
|
|
304
|
+
if (raw !== undefined) {
|
|
305
|
+
const meta = parseMeta(raw);
|
|
306
|
+
if (meta ? expired(meta, now) : await old(metaFile)) {
|
|
307
|
+
if (await this.delete(id).then(() => true, () => false)) removed++;
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
274
310
|
}
|
|
275
311
|
}
|
|
276
312
|
// Temporary files of this document, and every file of one without metadata, once they are old.
|
package/src/text.ts
CHANGED
|
@@ -41,6 +41,10 @@ export function foldCase(text: string): string {
|
|
|
41
41
|
return out;
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
/** The first and the second half of a character outside the basic plane, as JavaScript holds it. */
|
|
45
|
+
const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff;
|
|
46
|
+
const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
|
|
47
|
+
|
|
44
48
|
/**
|
|
45
49
|
* Splits lines longer than `limit`, preferring a break after whitespace or punctuation near the
|
|
46
50
|
* end of each piece. Minified JSON or a PDF paragraph becomes many addressable lines.
|
|
@@ -59,7 +63,10 @@ export function wrapLongLines(text: string, limit = MAX_LINE_CHARACTERS): { text
|
|
|
59
63
|
while (rest.length > limit) {
|
|
60
64
|
const window = rest.slice(0, limit);
|
|
61
65
|
const soft = Math.max(window.lastIndexOf(" "), window.lastIndexOf(","), window.lastIndexOf(";"), window.lastIndexOf("}"));
|
|
62
|
-
|
|
66
|
+
let cut = soft > limit * 0.8 ? soft + 1 : limit;
|
|
67
|
+
// Never between the two halves of a character outside the basic plane (an emoji): each half
|
|
68
|
+
// alone is stored as a replacement character.
|
|
69
|
+
if (isHighSurrogate(rest.charCodeAt(cut - 1)) && isLowSurrogate(rest.charCodeAt(cut))) cut--;
|
|
63
70
|
out.push(rest.slice(0, cut));
|
|
64
71
|
rest = rest.slice(cut);
|
|
65
72
|
}
|
|
@@ -172,24 +179,44 @@ export function estimateTokens(text: string): number {
|
|
|
172
179
|
return Math.ceil(tokens);
|
|
173
180
|
}
|
|
174
181
|
|
|
175
|
-
/**
|
|
176
|
-
|
|
177
|
-
|
|
182
|
+
/**
|
|
183
|
+
* The size of a text in one pass: its UTF-8 bytes, and the bytes it takes as a string in a JSON
|
|
184
|
+
* request body, which is what a model connector's request limit counts. JSON writes a quote and a
|
|
185
|
+
* backslash as two characters, a line break or a tab as two, any other control character as six
|
|
186
|
+
* (`\u0007`), and half of a surrogate pair as six: an export full of quotes or tabs grows by a
|
|
187
|
+
* quarter or more, a novel by a hundredth.
|
|
188
|
+
*/
|
|
189
|
+
export function textSizes(text: string): { utf8: number; json: number } {
|
|
190
|
+
let utf8 = 0;
|
|
191
|
+
let escapes = 0;
|
|
178
192
|
for (let index = 0; index < text.length; index++) {
|
|
179
193
|
const code = text.charCodeAt(index);
|
|
180
|
-
if (code < 0x80)
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
194
|
+
if (code < 0x80) {
|
|
195
|
+
utf8 += 1;
|
|
196
|
+
if (code === 0x22 || code === 0x5c) escapes += 1;
|
|
197
|
+
else if (code < 0x20) escapes += code === 0x0a || code === 0x09 || code === 0x0d || code === 0x08 || code === 0x0c ? 1 : 5;
|
|
198
|
+
} else if (code < 0x800) {
|
|
199
|
+
utf8 += 2;
|
|
200
|
+
} else if (isHighSurrogate(code) && isLowSurrogate(text.charCodeAt(index + 1))) {
|
|
201
|
+
utf8 += 4;
|
|
184
202
|
index++;
|
|
185
|
-
} else
|
|
203
|
+
} else {
|
|
204
|
+
utf8 += 3;
|
|
205
|
+
// Half of a pair on its own: three bytes of replacement character as UTF-8, six as \udXXX in JSON.
|
|
206
|
+
if (code >= 0xd800 && code <= 0xdfff) escapes += 3;
|
|
207
|
+
}
|
|
186
208
|
}
|
|
187
|
-
return
|
|
209
|
+
return { utf8, json: utf8 + escapes + 2 };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** UTF-8 byte length without allocating an encoded copy. */
|
|
213
|
+
export function utf8Bytes(text: string): number {
|
|
214
|
+
return textSizes(text).utf8;
|
|
188
215
|
}
|
|
189
216
|
|
|
190
|
-
/** Bytes a string
|
|
217
|
+
/** Bytes a string takes in a JSON request body: its UTF-8 bytes, the escapes JSON adds, and its two quotes. */
|
|
191
218
|
export function jsonBytes(text: string): number {
|
|
192
|
-
return
|
|
219
|
+
return textSizes(text).json;
|
|
193
220
|
}
|
|
194
221
|
|
|
195
222
|
/** Fast line lookups over one text. Line numbers are 1-based. */
|
package/src/tools.ts
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { safeErrorMessage } from "./errors.js";
|
|
2
|
+
import { analyzeWholeDocument } from "./map-reduce.js";
|
|
2
3
|
import { cutPdfPages } from "./pdf-pages.js";
|
|
3
|
-
import { grepSource, numberLines, rankSource, type DocumentSource } from "./search.js";
|
|
4
|
-
import { formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
4
|
+
import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource } from "./search.js";
|
|
5
|
+
import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
5
6
|
import type { Budget, GenerateText, ProgressListener, ToolDeclaration, ToolFileLimits, ToolOutput, ToolResult, ToolSet } from "./types.js";
|
|
6
7
|
|
|
7
8
|
const DEFAULT_READ_LINES = 200;
|
|
8
9
|
const MAX_READ_LINES = 600;
|
|
9
10
|
/** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
|
|
10
11
|
export const MAX_VIEW_PAGES = 5;
|
|
12
|
+
/**
|
|
13
|
+
* The time the regex searches of one tool set (one question, in `askGemini`) may take together,
|
|
14
|
+
* unless `regexBudgetMs` says otherwise. An ordinary search of a 60 MB log takes about 0.15 s.
|
|
15
|
+
*/
|
|
16
|
+
export const REGEX_BUDGET_MS = 6_000;
|
|
11
17
|
/** Below this, no page fits: a cut of one page of plain text is larger. */
|
|
12
18
|
const MIN_FILE_BYTES = 1_024;
|
|
13
19
|
|
|
@@ -161,6 +167,13 @@ export function createDocumentTools(options: {
|
|
|
161
167
|
generate?: GenerateText;
|
|
162
168
|
onProgress?: ProgressListener;
|
|
163
169
|
signal?: AbortSignal;
|
|
170
|
+
/** The most time, in milliseconds, that the regex searches of this tool set may take together. Defaults to `REGEX_BUDGET_MS`. */
|
|
171
|
+
regexBudgetMs?: number;
|
|
172
|
+
/**
|
|
173
|
+
* False when every document is too large for a whole-document read: `analyze_whole_document` is
|
|
174
|
+
* then not declared. A call of it still answers with the reason. Defaults to true.
|
|
175
|
+
*/
|
|
176
|
+
wholeReads?: boolean;
|
|
164
177
|
/**
|
|
165
178
|
* PDFs whose pages `view_pages` may show. The tool is declared only when there is at least one
|
|
166
179
|
* and `loadOriginal` is given. They need not be among `documentIds`: a PDF whose text is in the
|
|
@@ -176,11 +189,17 @@ export function createDocumentTools(options: {
|
|
|
176
189
|
// The text tools are left out only when there are pages to look at and no document to search.
|
|
177
190
|
const textTools = allowed.size > 0 || viewable.size === 0;
|
|
178
191
|
const declarations = [
|
|
179
|
-
...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.generate ? [DECLARATIONS.analyze] : [])] : []),
|
|
192
|
+
...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
|
|
180
193
|
...(viewable.size > 0 ? [DECLARATIONS.view] : []),
|
|
181
194
|
];
|
|
182
195
|
const known = new Set(declarations.map((declaration) => declaration.name));
|
|
196
|
+
// Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
|
|
197
|
+
if (textTools && options.generate) known.add(TOOL_NAMES.analyze);
|
|
183
198
|
const limit = options.budget.toolResultCharacters;
|
|
199
|
+
// The model writes the regex, and a file it reads can ask for a slow one: the time is counted
|
|
200
|
+
// over every search of this tool set, not only within one.
|
|
201
|
+
const regexBudget = Math.max(0, options.regexBudgetMs ?? REGEX_BUDGET_MS);
|
|
202
|
+
const regexClock = { usedMs: 0 };
|
|
184
203
|
// When no limit is given with a call: three eighths of a request, so that two looks still fit.
|
|
185
204
|
const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
|
|
186
205
|
|
|
@@ -221,11 +240,17 @@ export function createDocumentTools(options: {
|
|
|
221
240
|
...(ranked.length === 0 ? { note: "No passage contains these keywords. Try other words, synonyms, or exact mode." } : {}),
|
|
222
241
|
}, "passages", limit);
|
|
223
242
|
}
|
|
243
|
+
const regex = mode === "regex";
|
|
244
|
+
const regexLeft = regexBudget - regexClock.usedMs;
|
|
245
|
+
if (regex && regexLeft <= 0) {
|
|
246
|
+
throw new Error("The time for regex searches is used up for this answer. Search with mode \"exact\" or \"keywords\" instead.");
|
|
247
|
+
}
|
|
224
248
|
const result = await grepSource(document, query, {
|
|
225
|
-
regex
|
|
249
|
+
regex,
|
|
226
250
|
caseSensitive: args.case_sensitive === true,
|
|
227
251
|
maxResults: integer(args.max_results, 20, 1, 50),
|
|
228
252
|
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
253
|
+
...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
|
|
229
254
|
...(options.signal ? { signal: options.signal } : {}),
|
|
230
255
|
});
|
|
231
256
|
return fit({
|
|
@@ -249,7 +274,9 @@ export function createDocumentTools(options: {
|
|
|
249
274
|
const read = await document.readLines(start, end);
|
|
250
275
|
let to = end;
|
|
251
276
|
let body = numberLines(read, start);
|
|
252
|
-
|
|
277
|
+
// The limit is on the result as it is sent, as JSON: quotes, tabs and line breaks each take two characters there.
|
|
278
|
+
const fits = (text: string) => JSON.stringify(text).length <= limit - 500;
|
|
279
|
+
while (!fits(body) && to > start) {
|
|
253
280
|
to = start + Math.max(0, Math.floor((to - start) * 0.7));
|
|
254
281
|
body = numberLines(read.slice(0, to - start + 1), start);
|
|
255
282
|
}
|
|
@@ -259,7 +286,7 @@ export function createDocumentTools(options: {
|
|
|
259
286
|
lines: `${start}-${to}`,
|
|
260
287
|
...(pages ? { pages } : {}),
|
|
261
288
|
total_lines: total,
|
|
262
|
-
text: body.slice(0, limit - 500),
|
|
289
|
+
text: fits(body) ? body : body.slice(0, Math.floor((limit - 500) / 2)),
|
|
263
290
|
...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
|
|
264
291
|
};
|
|
265
292
|
},
|
|
@@ -268,7 +295,10 @@ export function createDocumentTools(options: {
|
|
|
268
295
|
const document = await documentFor(args);
|
|
269
296
|
const { meta, lineCount } = document;
|
|
270
297
|
const tail = Math.max(1, lineCount - 19);
|
|
271
|
-
|
|
298
|
+
// Counting the parts means reading the whole text, for a number that only says how costly a
|
|
299
|
+
// whole-document read is. It is worked out from the metadata instead, to within a part or
|
|
300
|
+
// two; the read itself counts them.
|
|
301
|
+
const parts = estimateParts(meta, options.budget);
|
|
272
302
|
const first = Math.min(30, lineCount);
|
|
273
303
|
return fit({
|
|
274
304
|
document: meta.name,
|
|
@@ -277,7 +307,8 @@ export function createDocumentTools(options: {
|
|
|
277
307
|
lines: meta.lines,
|
|
278
308
|
estimated_tokens: meta.estimatedTokens,
|
|
279
309
|
...(meta.pages ? { pages: meta.pages } : {}),
|
|
280
|
-
parts_for_whole_document_analysis: parts
|
|
310
|
+
parts_for_whole_document_analysis: parts,
|
|
311
|
+
...(parts > options.budget.maxMapChunks ? { whole_document_analysis: `Not available for this file: it would take about ${parts} parts, and the limit is ${options.budget.maxMapChunks}. Use search_document and read_document.` } : {}),
|
|
281
312
|
...(meta.logProfile ? { log_profile: meta.logProfile } : {}),
|
|
282
313
|
first_lines: numberLines(await document.readLines(1, first), 1),
|
|
283
314
|
last_lines: lineCount > 30 ? numberLines(await document.readLines(tail, lineCount), tail) : "",
|
|
@@ -341,7 +372,7 @@ export function createDocumentTools(options: {
|
|
|
341
372
|
try {
|
|
342
373
|
cut = await cutPdfPages(original, from, Math.min(asked, from + mostPages - 1), maxBytes, total);
|
|
343
374
|
} catch (error) {
|
|
344
|
-
throw new Error(`${file}: ${
|
|
375
|
+
throw new Error(`${file}: ${safeErrorMessage(error)}`);
|
|
345
376
|
}
|
|
346
377
|
const pages = pageRange(cut.from, cut.to);
|
|
347
378
|
const shown = cut.to - cut.from + 1;
|
|
@@ -360,7 +391,8 @@ export function createDocumentTools(options: {
|
|
|
360
391
|
};
|
|
361
392
|
}
|
|
362
393
|
|
|
363
|
-
|
|
394
|
+
// What a tool could not do goes to the model, and from there to a user's screen: never a server path.
|
|
395
|
+
const failure = (error: unknown): ToolResult => ({ error: safeErrorMessage(error) });
|
|
364
396
|
|
|
365
397
|
async function execute(name: string, args: Record<string, unknown>): Promise<ToolResult> {
|
|
366
398
|
if (!known.has(name)) return { error: `Unknown tool ${name}.` };
|
package/src/types.ts
CHANGED
|
@@ -38,6 +38,11 @@ export type DocumentMeta = {
|
|
|
38
38
|
bytes: number;
|
|
39
39
|
/** UTF-8 size of the extracted text. */
|
|
40
40
|
textBytes: number;
|
|
41
|
+
/**
|
|
42
|
+
* Bytes the text takes inside a JSON request body, with the escapes JSON adds. Absent on a
|
|
43
|
+
* document ingested before 0.4.1: planning then assumes 8% more than `textBytes`.
|
|
44
|
+
*/
|
|
45
|
+
jsonBytes?: number;
|
|
41
46
|
characters: number;
|
|
42
47
|
lines: number;
|
|
43
48
|
estimatedTokens: number;
|