llm-large-files 0.8.1 → 0.9.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.
- package/CHANGELOG.md +631 -0
- package/README.md +9 -10
- package/dist/access.d.ts +86 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +131 -0
- package/dist/access.js.map +1 -0
- package/dist/ask.d.ts +45 -1
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +181 -20
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +57 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +217 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +72 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +102 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +35 -9
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +14 -3
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +46 -35
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +19 -3
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +84 -12
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +18 -6
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +2 -0
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/index.d.ts +9 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +70 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +868 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +176 -34
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +332 -512
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -2
- package/dist/limiter.js +2 -2
- package/dist/map-reduce.js +3 -3
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +43 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +63 -3
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +234 -7
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +482 -121
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +18 -3
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +102 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +365 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +4 -3
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +7 -6
- package/dist/node/sse.js.map +1 -1
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.js.map +1 -1
- package/dist/ranged.d.ts +22 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +50 -12
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- package/dist/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +120 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +582 -139
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +25 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +135 -13
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +116 -13
- package/dist/types.d.ts.map +1 -1
- package/docs/README.md +17 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +12 -8
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +16 -7
- package/docs/guides/deployment.md +309 -87
- package/docs/guides/errors-and-reliability.md +161 -23
- package/docs/guides/own-adapter-and-loop.md +27 -10
- package/docs/guides/pdfs.md +123 -29
- package/docs/guides/storage.md +634 -143
- package/docs/guides/testing.md +78 -129
- package/docs/guides/vertex-and-gemini.md +10 -7
- package/docs/guides/web-app.md +322 -77
- package/docs/how-it-works.md +35 -8
- package/docs/measurements.md +63 -8
- package/docs/publishing.md +112 -36
- package/docs/reference/ask.md +154 -13
- package/docs/reference/errors-and-retries.md +166 -14
- package/docs/reference/events.md +53 -20
- package/docs/reference/gemini.md +70 -21
- package/docs/reference/library.md +709 -165
- package/docs/reference/node.md +633 -104
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +15 -5
- package/docs/security.md +316 -70
- package/docs/troubleshooting.md +165 -58
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +12 -3
- package/src/access.ts +144 -0
- package/src/ask.ts +230 -19
- package/src/cache.ts +20 -5
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +255 -0
- package/src/errors.ts +129 -15
- package/src/events.ts +86 -21
- package/src/evidence.ts +14 -3
- package/src/extract.ts +50 -33
- package/src/gemini/adapter.ts +97 -11
- package/src/gemini/chat.ts +20 -6
- package/src/gemini/index.ts +1 -1
- package/src/index.ts +9 -6
- package/src/ingest.ts +927 -0
- package/src/library.ts +482 -523
- package/src/limiter.ts +2 -2
- package/src/map-reduce.ts +3 -3
- package/src/model.ts +69 -5
- package/src/node/handlers.ts +691 -117
- package/src/node/index.ts +13 -2
- package/src/node/ingest-child.ts +23 -5
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +365 -0
- package/src/node/sse.ts +7 -6
- package/src/pdf-layout.ts +69 -11
- package/src/ranged.ts +42 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/source.ts +178 -0
- package/src/stores.ts +635 -140
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +150 -14
- package/src/types.ts +106 -13
package/src/pdf-layout.ts
CHANGED
|
@@ -476,19 +476,77 @@ function isNumeric(text: string): boolean {
|
|
|
476
476
|
return digits > 0 && letters * 2 <= digits;
|
|
477
477
|
}
|
|
478
478
|
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
479
|
+
type Direction = "ltr" | "rtl";
|
|
480
|
+
|
|
481
|
+
/** Arabic-Indic and Persian digits and the Arabic separators: in the right-to-left block, but numbers. */
|
|
482
|
+
const ARABIC_DIGITS = /[\u0660-\u0669\u066b\u066c\u06f0-\u06f9]/g;
|
|
483
|
+
|
|
484
|
+
/** The direction of the letters of a piece; none for a piece without letters, or with as many of each. */
|
|
485
|
+
function letterDirection(text: string): Direction | undefined {
|
|
486
|
+
const rightToLeft = (text.match(RIGHT_TO_LEFT)?.length ?? 0) - (text.match(ARABIC_DIGITS)?.length ?? 0);
|
|
487
|
+
const leftToRight = text.match(LEFT_TO_RIGHT)?.length ?? 0;
|
|
488
|
+
return rightToLeft === leftToRight ? undefined : rightToLeft > leftToRight ? "rtl" : "ltr";
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** The directions of the nearest pieces before and after `index` that have one. */
|
|
492
|
+
function around(directions: Array<Direction | undefined>, index: number): [Direction | undefined, Direction | undefined] {
|
|
493
|
+
let before: Direction | undefined;
|
|
494
|
+
for (let other = index - 1; other >= 0 && !before; other--) before = directions[other];
|
|
495
|
+
let after: Direction | undefined;
|
|
496
|
+
for (let other = index + 1; other < directions.length && !after; other++) after = directions[other];
|
|
497
|
+
return [before, after];
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* The direction each piece is read in, for pieces from left to right; `spaced[i]` says whether a
|
|
502
|
+
* gap shows between pieces i and i + 1. A number reads left to right when it touches, with no gap
|
|
503
|
+
* and through pieces without letters only, a left-to-right word ("AB" + "-12") or another number
|
|
504
|
+
* ("8,300" + ",000"). Any other piece without letters takes the direction of the pieces on both
|
|
505
|
+
* sides when they agree, else the region's: in a right-to-left cell, "09:00 - 17:00" is laid out
|
|
506
|
+
* with the first time on the right, and "16 GB" with the number on the right, as two items.
|
|
507
|
+
*/
|
|
508
|
+
function pieceDirections(pieces: Piece[], spaced: boolean[], rightToLeft: boolean): Direction[] {
|
|
509
|
+
const letters = pieces.map((piece) => letterDirection(piece.text));
|
|
510
|
+
const isNumber = pieces.map((piece, index) => !letters[index] && /[\d\u0660-\u0669\u06f0-\u06f9]/.test(piece.text));
|
|
511
|
+
/** Whether the piece at `index` touches a left-to-right word or a number, walking by `step` through pieces without letters. */
|
|
512
|
+
const touches = (index: number, step: 1 | -1): boolean => {
|
|
513
|
+
for (let other = index + step; other >= 0 && other < pieces.length && !spaced[Math.min(other, other - step)]; other += step) {
|
|
514
|
+
if (letters[other] === "ltr" || isNumber[other]) return true;
|
|
515
|
+
if (letters[other]) return false;
|
|
488
516
|
}
|
|
489
|
-
|
|
517
|
+
return false;
|
|
518
|
+
};
|
|
519
|
+
const numbers = letters.map((direction, index) => {
|
|
520
|
+
if (direction || !isNumber[index]) return direction;
|
|
521
|
+
return touches(index, -1) || touches(index, 1) ? "ltr" : undefined;
|
|
490
522
|
});
|
|
491
|
-
return
|
|
523
|
+
return numbers.map((direction, index) => {
|
|
524
|
+
const [before, after] = around(numbers, index);
|
|
525
|
+
return direction ?? (before && before === after ? before : rightToLeft ? "rtl" : "ltr");
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* The text of one line's pieces in one cell, in reading order. Pieces of the other direction next
|
|
531
|
+
* to each other (a Latin name in a Hebrew cell, a Hebrew phrase in an English one) are a run that
|
|
532
|
+
* reads in its own direction; the runs follow each other in the direction of the region.
|
|
533
|
+
*/
|
|
534
|
+
function joinPieces(pieces: Piece[], rightToLeft: boolean): string {
|
|
535
|
+
const byX = [...pieces].sort((left, right) => left.x0 - right.x0);
|
|
536
|
+
const spaced = byX.slice(1).map((piece, index) => piece.x0 - byX[index]!.x1 > VISIBLE_GAP * Math.max(piece.size, byX[index]!.size));
|
|
537
|
+
const directions = pieceDirections(byX, spaced, rightToLeft);
|
|
538
|
+
// From left to right: each piece, then a space where the gap to the next piece on the page shows.
|
|
539
|
+
const parts = byX.flatMap((piece, index) => (index < spaced.length ? [piece.text, spaced[index] ? " " : ""] : [piece.text]));
|
|
540
|
+
// Turn each run of the other direction around, then the whole cell when it is right to left: a
|
|
541
|
+
// run keeps its order, and each space stays between the two pieces it was between on the page.
|
|
542
|
+
let start = 0;
|
|
543
|
+
directions.forEach((direction, index) => {
|
|
544
|
+
if (directions[index + 1] === direction) return;
|
|
545
|
+
if (direction !== (rightToLeft ? "rtl" : "ltr")) parts.splice(2 * start, 2 * (index - start) + 1, ...parts.slice(2 * start, 2 * index + 1).reverse());
|
|
546
|
+
start = index + 1;
|
|
547
|
+
});
|
|
548
|
+
if (rightToLeft) parts.reverse();
|
|
549
|
+
return parts.join("");
|
|
492
550
|
}
|
|
493
551
|
|
|
494
552
|
/** Columns that are their own run of whole sentences in file order: page columns, not table columns. */
|
package/src/ranged.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* large file in memory. The line index comes from the store (`getIndex`), or is built from the
|
|
5
5
|
* text the first time an older document without one is opened, and saved for next time.
|
|
6
6
|
*/
|
|
7
|
+
import { holderOf } from "./cache.js";
|
|
7
8
|
import type { Limiter } from "./limiter.js";
|
|
8
9
|
import { pagesOfLines, pause, type DocumentSource, type ScanFeed, type TextChunk } from "./search.js";
|
|
9
10
|
import { canSerialize, parseTextIndex, positionOf, serializeTextIndex, TextIndexBuilder, type TextIndex } from "./text-index.js";
|
|
@@ -17,8 +18,8 @@ export type ScanSettings = {
|
|
|
17
18
|
chunkBytes: number;
|
|
18
19
|
/** Bounds how many scans of whole documents run at once. */
|
|
19
20
|
limiter: Limiter;
|
|
20
|
-
/** Told
|
|
21
|
-
onBroken?: (
|
|
21
|
+
/** Told, with the document's key (`RangedDocument.key`), when its stored text did not agree with its index. */
|
|
22
|
+
onBroken?: (key: string) => void;
|
|
22
23
|
/**
|
|
23
24
|
* Where decoded pieces of frequently searched documents are kept, within the cache's memory
|
|
24
25
|
* limit, so that the next search of them reads and decodes nothing. A document whose decoded
|
|
@@ -37,8 +38,12 @@ export type PieceCache = {
|
|
|
37
38
|
maxDocumentBytes: number;
|
|
38
39
|
};
|
|
39
40
|
|
|
40
|
-
/**
|
|
41
|
-
|
|
41
|
+
/**
|
|
42
|
+
* The cache key of piece `at` of the document of key `key` (its ID, or the library's key of the
|
|
43
|
+
* document in one scope). All of them start with `${key}#`, and the document's key is all before
|
|
44
|
+
* the last "#".
|
|
45
|
+
*/
|
|
46
|
+
export const pieceKey = (key: string, at: number) => `${key}#${at}`;
|
|
42
47
|
|
|
43
48
|
/** Bytes read at a time to build an index from the text. */
|
|
44
49
|
const BUILD_READ_BYTES = 4 * 1024 * 1024;
|
|
@@ -48,7 +53,14 @@ const YIELD_AFTER_MS = 15;
|
|
|
48
53
|
// starts at a line, so a line that began with one lost it, and its piece no longer matched the index.
|
|
49
54
|
const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
|
|
50
55
|
|
|
51
|
-
|
|
56
|
+
/**
|
|
57
|
+
* The text of a document is gone from the store while its metadata is still there (removed by hand,
|
|
58
|
+
* or by a cleanup outside the library). Told apart from other read errors, so that a question can
|
|
59
|
+
* report the document as missing.
|
|
60
|
+
*/
|
|
61
|
+
export class DocumentGoneError extends Error {}
|
|
62
|
+
|
|
63
|
+
const gone = (id: string) => new DocumentGoneError(`${id} is no longer available on the server. Ask the user to attach the file again.`);
|
|
52
64
|
|
|
53
65
|
/** A scan of a document: fed the pieces in order until it says it is done. */
|
|
54
66
|
type Consumer = { feed: ScanFeed; done: boolean; settle: (error?: unknown) => void };
|
|
@@ -70,8 +82,11 @@ export class RangedDocument implements DocumentSource {
|
|
|
70
82
|
readonly meta: DocumentMeta,
|
|
71
83
|
readonly index: TextIndex,
|
|
72
84
|
private readonly settings: ScanSettings,
|
|
85
|
+
/** What its pieces are kept under, and what `onBroken` is told: its ID unless given another. */
|
|
86
|
+
readonly key: string = meta.id,
|
|
73
87
|
) {
|
|
74
|
-
|
|
88
|
+
// Whose it is too: a piece of one owner's or scope's text is never served for another's.
|
|
89
|
+
this.pieceVersion = `${meta.createdAt}|${index.textBytes}|${index.characters}|${settings.chunkBytes}|${holderOf(meta)}`;
|
|
75
90
|
// Decoded text is one byte a character when it is all ASCII, two otherwise; and its lowercased copy as much again.
|
|
76
91
|
const decoded = index.characters * (index.textBytes === index.characters ? 1 : 2) * 2 + index.characterStarts.byteLength;
|
|
77
92
|
this.keepPieces = settings.pieces !== undefined && decoded <= settings.pieces.maxDocumentBytes;
|
|
@@ -238,7 +253,7 @@ export class RangedDocument implements DocumentSource {
|
|
|
238
253
|
/** Piece `at`, from memory when it is kept there. */
|
|
239
254
|
private async piece(at: number): Promise<TextChunk> {
|
|
240
255
|
const cache = this.keepPieces ? this.settings.pieces : undefined;
|
|
241
|
-
const kept = cache?.get(pieceKey(this.
|
|
256
|
+
const kept = cache?.get(pieceKey(this.key, at), this.pieceVersion);
|
|
242
257
|
if (kept) return kept;
|
|
243
258
|
const { firstLine, lastLine, start, end } = this.chunkRanges()[at]!;
|
|
244
259
|
const text = await this.read(start, end);
|
|
@@ -265,7 +280,7 @@ export class RangedDocument implements DocumentSource {
|
|
|
265
280
|
// The text and, once a search needs it, its lowercased copy.
|
|
266
281
|
memoryBytes: text.length * (ascii ? 1 : 2) * 2 + starts.byteLength + 256,
|
|
267
282
|
};
|
|
268
|
-
cache?.set(pieceKey(this.
|
|
283
|
+
cache?.set(pieceKey(this.key, at), this.pieceVersion, piece);
|
|
269
284
|
return piece;
|
|
270
285
|
}
|
|
271
286
|
|
|
@@ -303,7 +318,7 @@ export class RangedDocument implements DocumentSource {
|
|
|
303
318
|
private mismatch(): Error {
|
|
304
319
|
if (!this.broken) {
|
|
305
320
|
this.broken = true;
|
|
306
|
-
this.settings.onBroken?.(this.
|
|
321
|
+
this.settings.onBroken?.(this.key);
|
|
307
322
|
}
|
|
308
323
|
return new Error(`The stored text of ${this.meta.name} did not match its index. Try the call again.`);
|
|
309
324
|
}
|
|
@@ -332,26 +347,39 @@ export async function buildIndexFromStore(store: RangeStore, id: string, limiter
|
|
|
332
347
|
* Opens a document to be read by range. Uses the saved index when there is one that fits the
|
|
333
348
|
* document; otherwise builds it from the text and saves it (best effort: a store that cannot
|
|
334
349
|
* write, or another server writing the same index, changes nothing). Undefined when the text is gone.
|
|
350
|
+
* `key` is what its pieces are kept under (see `RangedDocument.key`).
|
|
335
351
|
*/
|
|
336
352
|
export async function openRangedDocument(
|
|
337
353
|
store: RangeStore,
|
|
338
354
|
meta: DocumentMeta,
|
|
339
355
|
settings: ScanSettings,
|
|
340
|
-
options: { ignoreSavedIndex?: boolean } = {},
|
|
356
|
+
options: { ignoreSavedIndex?: boolean; key?: string } = {},
|
|
341
357
|
): Promise<RangedDocument | undefined> {
|
|
342
358
|
let index: TextIndex | undefined;
|
|
343
359
|
if (!options.ignoreSavedIndex && store.getIndex) {
|
|
344
360
|
const saved = await store.getIndex(meta.id).catch(() => undefined);
|
|
345
361
|
if (saved) index = parseTextIndex(saved, meta);
|
|
362
|
+
// A saved index that fits the metadata may still not fit the text: another document's text,
|
|
363
|
+
// written under the ID apart from its metadata and its index (two servers that ingest one ID at
|
|
364
|
+
// once). Its pieces are checked as they are read, but lines of the same lengths would pass. So
|
|
365
|
+
// the text must end where the index says: one byte is read across that end. Otherwise the index
|
|
366
|
+
// is built again from the text, and compared with the metadata below.
|
|
367
|
+
if (index && index.textBytes > 0) {
|
|
368
|
+
const tail = await store.readTextRange(meta.id, index.textBytes - 1, index.textBytes + 1).catch(() => undefined);
|
|
369
|
+
if (tail?.length !== 1) index = undefined;
|
|
370
|
+
}
|
|
346
371
|
}
|
|
347
372
|
if (!index) {
|
|
348
373
|
index = await buildIndexFromStore(store, meta.id, settings.limiter);
|
|
349
374
|
if (!index) return undefined;
|
|
350
|
-
// An index
|
|
351
|
-
//
|
|
352
|
-
|
|
375
|
+
// An index of another number of lines or characters than the metadata describes a text that is
|
|
376
|
+
// not what was ingested: another document's, written under the ID apart from its metadata (two
|
|
377
|
+
// servers that ingest one ID at once). Missing, as a document read whole is (before 0.9.0 it was
|
|
378
|
+
// used, and not saved). Every version counted lines and characters as the index does.
|
|
379
|
+
if (index.lineCount !== meta.lines || index.characters !== meta.characters) return undefined;
|
|
380
|
+
if (store.putIndex && canSerialize(index) && (meta.textBytes === undefined || index.textBytes === meta.textBytes)) {
|
|
353
381
|
await store.putIndex(meta.id, serializeTextIndex(index)).catch(() => undefined);
|
|
354
382
|
}
|
|
355
383
|
}
|
|
356
|
-
return new RangedDocument(store, meta, index, settings);
|
|
384
|
+
return new RangedDocument(store, meta, index, settings, options.key);
|
|
357
385
|
}
|
package/src/retry.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// One rule for sending a model request again, used by the chat loop and by whole-file part reads.
|
|
2
|
+
import { modelErrorOf } from "./model.js";
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* How a model request that failed is sent again. A field that is not a finite number (NaN,
|
|
@@ -118,7 +119,9 @@ export type RetryNotice = {
|
|
|
118
119
|
* - An error of kind "quota" (a daily cap, no credit left) is not retried: a wait does not mend it.
|
|
119
120
|
* Nor is one of kind "context_overflow", whatever its status: only a smaller request can pass
|
|
120
121
|
* (OpenAI's request larger than a minute's allowance of tokens comes as HTTP 429). Nor is one
|
|
121
|
-
* whose provider said not to try again (Claude's `x-should-retry: false`).
|
|
122
|
+
* whose provider said not to try again (Claude's `x-should-retry: false`). An error without a
|
|
123
|
+
* kind of its own (an adapter of your own) has the kind its status and `code` give, as its events
|
|
124
|
+
* do: a 429 of code "insufficient_quota" is a quota.
|
|
122
125
|
* - An error of kind "timeout" with status 0 (nothing came from the model for the adapter's whole
|
|
123
126
|
* wait) is retried once: another such wait is long, and a model that went silent twice will most
|
|
124
127
|
* likely do so again. A timeout the provider reports (HTTP 408) is retried like any other.
|
|
@@ -146,7 +149,8 @@ export async function withRetry<T>(run: () => Promise<T>, options: {
|
|
|
146
149
|
return await run();
|
|
147
150
|
} catch (error) {
|
|
148
151
|
if (options.signal?.aborted || options.canRetry?.() === false) throw error;
|
|
149
|
-
|
|
152
|
+
// As its events and errorInfoOf tell it (modelErrorOf).
|
|
153
|
+
const kind = modelErrorOf(error)?.kind;
|
|
150
154
|
if (kind === "quota" || kind === "context_overflow") throw error;
|
|
151
155
|
if (typeof error === "object" && error !== null && notToRetry.has(error)) throw error;
|
|
152
156
|
if (kind === "timeout" && statusOf(error) === 0) {
|
package/src/scope.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Scopes (`DocumentScope`): where a document belongs, such as [userId, chatId]. New in 0.9.0.
|
|
2
|
+
import { DocumentScopeError } from "./errors.js";
|
|
3
|
+
import type { DocumentScope } from "./types.js";
|
|
4
|
+
|
|
5
|
+
/** The most segments a scope may have. */
|
|
6
|
+
export const MAX_SCOPE_SEGMENTS = 8;
|
|
7
|
+
/** The most UTF-16 units one segment may have. */
|
|
8
|
+
export const MAX_SCOPE_SEGMENT_LENGTH = 256;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* What a segment may not hold: "/" and "\" (path separators on every system), control characters
|
|
12
|
+
* (NUL, line breaks, C1), and half of a surrogate pair, which has no UTF-8 form.
|
|
13
|
+
*/
|
|
14
|
+
const FORBIDDEN = /[/\\\p{Cc}\p{Cs}]/u;
|
|
15
|
+
|
|
16
|
+
const SHAPE = `scope must be an array of 1 to ${MAX_SCOPE_SEGMENTS} strings, such as [userId, chatId].`;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A scope given to the library, checked: a frozen copy of it, or undefined when there is none.
|
|
20
|
+
* Throws a `DocumentScopeError` with code "scope_invalid" unless it is an array of 1 to 8 strings,
|
|
21
|
+
* each of 1 to 256 UTF-16 units, with no control characters, no "/" or "\", and none of them "." or
|
|
22
|
+
* "..". The message says which segment is wrong, not what it holds: a segment may be a user's ID.
|
|
23
|
+
*/
|
|
24
|
+
export function checkScope(scope: unknown): DocumentScope | undefined {
|
|
25
|
+
if (scope === undefined) return undefined;
|
|
26
|
+
if (!Array.isArray(scope) || scope.length < 1 || scope.length > MAX_SCOPE_SEGMENTS) {
|
|
27
|
+
throw new DocumentScopeError("scope_invalid", SHAPE);
|
|
28
|
+
}
|
|
29
|
+
const segments: string[] = [];
|
|
30
|
+
// An index loop, not `map`: a hole in the array is a segment that is missing.
|
|
31
|
+
for (let index = 0; index < scope.length; index++) {
|
|
32
|
+
const segment: unknown = scope[index];
|
|
33
|
+
const which = `scope segment ${index + 1}`;
|
|
34
|
+
if (typeof segment !== "string" || segment.length < 1 || segment.length > MAX_SCOPE_SEGMENT_LENGTH) {
|
|
35
|
+
throw new DocumentScopeError("scope_invalid", `${which} must be a string of 1 to ${MAX_SCOPE_SEGMENT_LENGTH} characters. ${SHAPE}`);
|
|
36
|
+
}
|
|
37
|
+
if (segment === "." || segment === "..") throw new DocumentScopeError("scope_invalid", `${which} cannot be "." or "..".`);
|
|
38
|
+
if (FORBIDDEN.test(segment)) throw new DocumentScopeError("scope_invalid", `${which} cannot hold "/", "\\" or control characters.`);
|
|
39
|
+
segments.push(segment);
|
|
40
|
+
}
|
|
41
|
+
return Object.freeze(segments);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* A scope as one string, to key maps and caches by: its segments, each URI-encoded, joined with
|
|
46
|
+
* "/". Two scopes give the same key only when they are the same, and no scope gives "", which is
|
|
47
|
+
* the key of no scope. Check the scope first (`checkScope`): a segment with half of a surrogate
|
|
48
|
+
* pair cannot be encoded.
|
|
49
|
+
*/
|
|
50
|
+
export function scopeKey(scope: DocumentScope | undefined): string {
|
|
51
|
+
return scope === undefined ? "" : scope.map(encodeURIComponent).join("/");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Whether two scopes are the same, segment by segment. No scope is the same as no scope only; null
|
|
56
|
+
* counts as no scope, as a database may give it for a field that was left out.
|
|
57
|
+
*/
|
|
58
|
+
export function sameScope(left: DocumentScope | null | undefined, right: DocumentScope | null | undefined): boolean {
|
|
59
|
+
if (left === undefined || left === null || right === undefined || right === null) {
|
|
60
|
+
return (left === undefined || left === null) && (right === undefined || right === null);
|
|
61
|
+
}
|
|
62
|
+
return left.length === right.length && left.every((segment, index) => segment === right[index]);
|
|
63
|
+
}
|
package/src/source.ts
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// Files ingested from a path (`IngestFromSource`), and the SHA-256 of what is ingested. New in 0.9.0.
|
|
2
|
+
// A file is looked at before the ingest's turn without being read (its size), read once when its
|
|
3
|
+
// turn comes, never past the upload limit, and hashed a slice at a time as it is read. Nothing
|
|
4
|
+
// here writes, moves or deletes a file.
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { constants, type Stats } from "node:fs";
|
|
7
|
+
import { lstat, open } from "node:fs/promises";
|
|
8
|
+
import nodePath, { type PlatformPath } from "node:path";
|
|
9
|
+
import type { TimeSlicer } from "./pause.js";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* How a file is opened to be read: never through a link at its name, where the platform can
|
|
13
|
+
* (`O_NOFOLLOW`; Windows has none), and without waiting for a writer when it is a pipe
|
|
14
|
+
* (`O_NONBLOCK`, which changes nothing for a file). What is opened is then checked to be a file.
|
|
15
|
+
*/
|
|
16
|
+
export const READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* `path` made absolute, as text: an absolute path as it is, a relative one after the working
|
|
20
|
+
* directory and a separator. Nothing in it is normalized, so a ".." after a link, and a "/" at the
|
|
21
|
+
* end, are the system's to resolve, as they are in an absolute path: both spellings of a path read
|
|
22
|
+
* the same file. (`path.resolve` would remove them as text first.) On Windows, a path relative to
|
|
23
|
+
* the working directory of a drive ("C:notes.txt") is made absolute by `path.resolve`, which alone
|
|
24
|
+
* knows that directory. The working directory is asked for only for a relative path: an absolute
|
|
25
|
+
* one is read even when the working directory has been removed (where `process.cwd()` throws).
|
|
26
|
+
* `paths` and `cwd` are given by tests.
|
|
27
|
+
*/
|
|
28
|
+
export function absolutePath(path: string, paths: PlatformPath = nodePath, cwd?: string): string {
|
|
29
|
+
if (paths.isAbsolute(path)) return path;
|
|
30
|
+
if (paths.sep === "\\" && /^[A-Za-z]:/.test(path)) return paths.resolve(path);
|
|
31
|
+
const base = cwd ?? process.cwd();
|
|
32
|
+
return base.endsWith(paths.sep) ? base + path : base + paths.sep + path;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** How much is read, and hashed, between two looks at the clock: 1 MB. */
|
|
36
|
+
export const SLICE_BYTES = 1024 * 1024;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The error of a path that names no file the library reads, in the shape of a system error: a code
|
|
40
|
+
* and a system call, so that it is passed on as the server's trouble, not told as a file a user
|
|
41
|
+
* sent that cannot be read. Its message names no path.
|
|
42
|
+
*/
|
|
43
|
+
function pathError(message: string, code: string, syscall: string): Error {
|
|
44
|
+
return Object.assign(new Error(message), { code, syscall });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Throws unless `info` is that of a file: not a link, a folder, a pipe or a device. */
|
|
48
|
+
function checkFile(info: Stats, syscall: string): void {
|
|
49
|
+
if (info.isSymbolicLink()) throw pathError("The file to ingest is a link, which is not followed.", "ELOOP", syscall);
|
|
50
|
+
if (info.isDirectory()) throw pathError("The path to ingest is a folder, not a file.", "EISDIR", syscall);
|
|
51
|
+
if (!info.isFile()) throw pathError("The path to ingest is not a file.", "EINVAL", syscall);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The size of the file at `path`, from `lstat`: a link is refused, not followed, and so is anything
|
|
56
|
+
* that is not a file. Nothing of the file is read.
|
|
57
|
+
*/
|
|
58
|
+
export async function statSource(path: string): Promise<number> {
|
|
59
|
+
const info = await lstat(path);
|
|
60
|
+
checkFile(info, "lstat");
|
|
61
|
+
return info.size;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** An array of exactly `size` bytes, not filled: every byte is written before it is used. */
|
|
65
|
+
function unfilled(size: number): Uint8Array {
|
|
66
|
+
const buffer = Buffer.allocUnsafeSlow(size);
|
|
67
|
+
// A plain Uint8Array over the whole of its own memory, which is exactly `size` bytes: once it is
|
|
68
|
+
// filled, nothing under it is left unwritten.
|
|
69
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, size);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** What `readSource` read: the bytes when they were kept, how many there were, and their SHA-256. */
|
|
73
|
+
export type SourceRead = {
|
|
74
|
+
/** The bytes read, in an array of exactly `size` bytes, when they were kept. */
|
|
75
|
+
bytes?: Uint8Array;
|
|
76
|
+
/** How many bytes were read: the size of the file, or `maxBytes + 1` when it has more than `maxBytes`. */
|
|
77
|
+
size: number;
|
|
78
|
+
/** The SHA-256 of the bytes read, as 64 lowercase hex digits. */
|
|
79
|
+
sha256: string;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Reads the file at `path` once, from its start: at most `maxBytes + 1` bytes, so that a file that
|
|
84
|
+
* has grown past `maxBytes` since it was looked at is told (`size` above `maxBytes`) without
|
|
85
|
+
* reading the rest: the caller refuses it. The bytes are hashed a slice (`SLICE_BYTES`) at a time, `slicer` may pause
|
|
86
|
+
* between two slices, and `signal` stops the read between two slices. `keep` false hashes the bytes
|
|
87
|
+
* and lets each slice go: only the size and the SHA-256 come back.
|
|
88
|
+
*/
|
|
89
|
+
export async function readSource(path: string, maxBytes: number, options: { keep: boolean; slicer?: TimeSlicer; signal?: AbortSignal }): Promise<SourceRead> {
|
|
90
|
+
const { keep, slicer, signal } = options;
|
|
91
|
+
signal?.throwIfAborted();
|
|
92
|
+
const limit = maxBytes + 1;
|
|
93
|
+
const handle = await open(path, READ_FLAGS);
|
|
94
|
+
try {
|
|
95
|
+
const info = await handle.stat();
|
|
96
|
+
checkFile(info, "fstat");
|
|
97
|
+
const hash = createHash("sha256");
|
|
98
|
+
// Kept: the first array has the size the file has now (no more than the limit), so the usual
|
|
99
|
+
// file is read into one array of its exact size; a file that grows meanwhile goes on in arrays
|
|
100
|
+
// of a slice. Not kept: one slice is read into again and again.
|
|
101
|
+
const full: Uint8Array[] = [];
|
|
102
|
+
let current = unfilled(keep ? Math.min(info.size, limit) : SLICE_BYTES);
|
|
103
|
+
let filled = 0;
|
|
104
|
+
let size = 0;
|
|
105
|
+
while (size < limit) {
|
|
106
|
+
if (filled === current.byteLength) {
|
|
107
|
+
if (keep) {
|
|
108
|
+
if (filled > 0) full.push(current);
|
|
109
|
+
current = unfilled(Math.min(SLICE_BYTES, limit - size));
|
|
110
|
+
}
|
|
111
|
+
filled = 0;
|
|
112
|
+
}
|
|
113
|
+
// Never past the limit: the slice read into again and again (not kept) is larger than what is left.
|
|
114
|
+
const { bytesRead } = await handle.read(current, filled, Math.min(SLICE_BYTES, current.byteLength - filled, limit - size), size);
|
|
115
|
+
if (bytesRead === 0) break;
|
|
116
|
+
hash.update(current.subarray(filled, filled + bytesRead));
|
|
117
|
+
filled += bytesRead;
|
|
118
|
+
size += bytesRead;
|
|
119
|
+
signal?.throwIfAborted();
|
|
120
|
+
await slicer?.maybePause();
|
|
121
|
+
}
|
|
122
|
+
const sha256 = hash.digest("hex");
|
|
123
|
+
if (!keep) return { size, sha256 };
|
|
124
|
+
if (full.length === 0 && filled === current.byteLength) return { bytes: current, size, sha256 };
|
|
125
|
+
if (full.length === 1 && filled === 0) return { bytes: full[0]!, size, sha256 };
|
|
126
|
+
// A file that shrank, or grew, while it was read: its bytes in one array of their exact size.
|
|
127
|
+
const bytes = unfilled(size);
|
|
128
|
+
let at = 0;
|
|
129
|
+
for (const part of [...full, current.subarray(0, filled)]) {
|
|
130
|
+
bytes.set(part, at);
|
|
131
|
+
at += part.byteLength;
|
|
132
|
+
}
|
|
133
|
+
return { bytes, size, sha256 };
|
|
134
|
+
} finally {
|
|
135
|
+
await handle.close();
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Bytes `start` (inclusive) to `end` (exclusive) of each range of the file at `path`, read in one
|
|
141
|
+
* opening of it, as `readSource` opens it: fewer at the end of a file that has shrunk.
|
|
142
|
+
*/
|
|
143
|
+
export async function readRanges(path: string, ranges: ReadonlyArray<readonly [number, number]>): Promise<Uint8Array[]> {
|
|
144
|
+
const handle = await open(path, READ_FLAGS);
|
|
145
|
+
try {
|
|
146
|
+
checkFile(await handle.stat(), "fstat");
|
|
147
|
+
const parts: Uint8Array[] = [];
|
|
148
|
+
for (const [start, end] of ranges) {
|
|
149
|
+
const part = new Uint8Array(Math.max(0, end - start));
|
|
150
|
+
let filled = 0;
|
|
151
|
+
while (filled < part.byteLength) {
|
|
152
|
+
const { bytesRead } = await handle.read(part, filled, part.byteLength - filled, start + filled);
|
|
153
|
+
if (bytesRead === 0) break;
|
|
154
|
+
filled += bytesRead;
|
|
155
|
+
}
|
|
156
|
+
parts.push(part.subarray(0, filled));
|
|
157
|
+
}
|
|
158
|
+
return parts;
|
|
159
|
+
} finally {
|
|
160
|
+
await handle.close();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* The SHA-256 of `bytes`, as 64 lowercase hex digits, hashed a slice (`SLICE_BYTES`) at a time:
|
|
166
|
+
* `slicer` may pause between two slices, so that a large file does not hold the server.
|
|
167
|
+
*/
|
|
168
|
+
export async function sha256InSlices(bytes: Uint8Array, slicer?: TimeSlicer): Promise<string> {
|
|
169
|
+
const hash = createHash("sha256");
|
|
170
|
+
for (let at = 0; at < bytes.byteLength; at += SLICE_BYTES) {
|
|
171
|
+
hash.update(bytes.subarray(at, at + SLICE_BYTES));
|
|
172
|
+
await slicer?.maybePause();
|
|
173
|
+
}
|
|
174
|
+
return hash.digest("hex");
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Whether `value` is a SHA-256 as the library writes it: 64 lowercase hex digits. */
|
|
178
|
+
export const isSha256 = (value: unknown): value is string => typeof value === "string" && /^[0-9a-f]{64}$/.test(value);
|