llm-large-files 0.5.0 → 0.8.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 +1719 -466
- package/README.md +190 -60
- package/dist/analyze.d.ts +8 -1
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +198 -54
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +194 -40
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +63 -7
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1131 -214
- package/dist/ask.js.map +1 -1
- package/dist/decode.d.ts +19 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +97 -0
- package/dist/decode.js.map +1 -0
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +59 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +80 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +339 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +163 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +9 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +26 -7
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +180 -314
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +117 -66
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +5 -1
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +11 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +33 -10
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/groups.d.ts +54 -0
- package/dist/groups.d.ts.map +1 -0
- package/dist/groups.js +136 -0
- package/dist/groups.js.map +1 -0
- package/dist/html.d.ts +11 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +1112 -0
- package/dist/html.js.map +1 -0
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +13 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -5
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +449 -93
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -1
- package/dist/limiter.d.ts.map +1 -1
- package/dist/limiter.js +3 -2
- package/dist/limiter.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +190 -2
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +184 -28
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +38 -0
- package/dist/node/ingest-child.d.ts.map +1 -0
- package/dist/node/ingest-child.js +42 -0
- package/dist/node/ingest-child.js.map +1 -0
- package/dist/node/isolated.d.ts +88 -0
- package/dist/node/isolated.d.ts.map +1 -0
- package/dist/node/isolated.js +381 -0
- package/dist/node/isolated.js.map +1 -0
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/office.d.ts +105 -0
- package/dist/office.d.ts.map +1 -0
- package/dist/office.js +1092 -0
- package/dist/office.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +325 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +277 -20
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/peers.d.ts +8 -0
- package/dist/peers.d.ts.map +1 -0
- package/dist/peers.js +32 -0
- package/dist/peers.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +4 -2
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +107 -24
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +803 -149
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +9 -1
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +28 -9
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +87 -3
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +526 -24
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +461 -46
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +103 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/word-styles.d.ts +102 -0
- package/dist/word-styles.d.ts.map +1 -0
- package/dist/word-styles.js +419 -0
- package/dist/word-styles.js.map +1 -0
- package/dist/xlsx.d.ts +23 -0
- package/dist/xlsx.d.ts.map +1 -0
- package/dist/xlsx.js +511 -0
- package/dist/xlsx.js.map +1 -0
- package/dist/xml-stream.d.ts +55 -0
- package/dist/xml-stream.d.ts.map +1 -0
- package/dist/xml-stream.js +235 -0
- package/dist/xml-stream.js.map +1 -0
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +728 -0
- package/docs/guides/deployment.md +720 -0
- package/docs/guides/errors-and-reliability.md +748 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +1024 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1203 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1590 -0
- package/docs/how-it-works.md +1035 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +910 -0
- package/docs/reference/errors-and-retries.md +760 -0
- package/docs/reference/events.md +1001 -0
- package/docs/reference/gemini.md +827 -0
- package/docs/reference/library.md +1598 -0
- package/docs/reference/node.md +706 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +1031 -0
- package/docs/security.md +940 -101
- package/docs/troubleshooting.md +1410 -0
- package/package.json +7 -3
- package/src/analyze.ts +204 -49
- package/src/anthropic/adapter.ts +200 -40
- package/src/ask.ts +1151 -210
- package/src/decode.ts +89 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +125 -0
- package/src/events.ts +451 -0
- package/src/evidence.ts +11 -2
- package/src/extract.ts +191 -308
- package/src/gemini/adapter.ts +127 -70
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/endpoints.ts +12 -2
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +42 -13
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/groups.ts +162 -0
- package/src/html.ts +1071 -0
- package/src/http.ts +376 -1
- package/src/index.ts +29 -6
- package/src/library.ts +498 -93
- package/src/limiter.ts +6 -1
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +244 -4
- package/src/node/handlers.ts +196 -31
- package/src/node/index.ts +4 -0
- package/src/node/ingest-child.ts +61 -0
- package/src/node/isolated.ts +464 -0
- package/src/node/sse.ts +198 -0
- package/src/office.ts +1047 -0
- package/src/openai/adapter.ts +319 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +270 -20
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/peers.ts +29 -0
- package/src/plan.ts +70 -12
- package/src/ranged.ts +4 -2
- package/src/retry.ts +49 -5
- package/src/search.ts +800 -155
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +30 -9
- package/src/text.ts +524 -23
- package/src/tools.ts +445 -46
- package/src/types.ts +108 -5
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- package/src/xml-stream.ts +224 -0
- package/src/zip-directory.ts +136 -0
package/dist/library.js
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import {
|
|
2
|
+
import { buildLogProfileInSlices, buildOutlineInSlices, looksLikeLog } from "./analyze.js";
|
|
3
3
|
import { givenBudget, resolveBudget } from "./budget.js";
|
|
4
4
|
import { DocumentCache, documentVersion } from "./cache.js";
|
|
5
|
-
import { DocumentStoreError } from "./errors.js";
|
|
5
|
+
import { DocumentStoreError, isStoreWriteFailure, noteStoreWriteFailure, toIngestError } from "./errors.js";
|
|
6
|
+
import { EventEmitter, eventErrorOf, newRunId } from "./events.js";
|
|
6
7
|
import { detectFormat, extractText } from "./extract.js";
|
|
7
8
|
import { Limiter } from "./limiter.js";
|
|
9
|
+
import { TimeSlicer } from "./pause.js";
|
|
8
10
|
import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
|
|
9
11
|
import { openRangedDocument, pieceKey } from "./ranged.js";
|
|
10
12
|
import { numberLines, SearchableDocument } from "./search.js";
|
|
11
13
|
import { DOCUMENT_ID_PATTERN } from "./stores.js";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
+
import { buildTextIndexInSlices, canSerialize, serializeTextIndex } from "./text-index.js";
|
|
15
|
+
import { measureText, prepareText, removeInvisible, sliceWhole, wellFormed } from "./text.js";
|
|
14
16
|
import { createDocumentTools } from "./tools.js";
|
|
15
17
|
export { DEFAULT_BUDGET } from "./budget.js";
|
|
16
18
|
export function isDocumentId(value) {
|
|
@@ -27,22 +29,72 @@ export function toDocumentSummary(meta) {
|
|
|
27
29
|
lines: meta.lines,
|
|
28
30
|
estimatedTokens: meta.estimatedTokens,
|
|
29
31
|
...(meta.pages ? { pages: meta.pages } : {}),
|
|
32
|
+
...(meta.encoding ? { encoding: meta.encoding } : {}),
|
|
33
|
+
...(meta.replacedCharacters ? { replacedCharacters: meta.replacedCharacters } : {}),
|
|
30
34
|
expiresAt: meta.expiresAt,
|
|
31
35
|
};
|
|
32
36
|
}
|
|
37
|
+
/** An encoding's name as TextDecoder gives it ("windows-1255"): an extractor of your own may name another. */
|
|
38
|
+
const ENCODING_NAME = /^[a-z0-9][a-z0-9._:-]{0,39}$/i;
|
|
33
39
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
|
|
40
|
+
* Whether the name is an older encoding, as `DocumentMeta.encoding` records: not UTF-8 or UTF-16,
|
|
41
|
+
* under any of their names ("utf8", "unicode"). The model is told the file is not in UTF-8.
|
|
42
|
+
*/
|
|
43
|
+
function olderEncoding(name) {
|
|
44
|
+
if (typeof name !== "string" || !ENCODING_NAME.test(name))
|
|
45
|
+
return false;
|
|
46
|
+
let known;
|
|
47
|
+
try {
|
|
48
|
+
known = new TextDecoder(name).encoding;
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
// A name TextDecoder does not know: the extractor read the file itself.
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
return known !== "utf-8" && known !== "utf-16le" && known !== "utf-16be";
|
|
55
|
+
}
|
|
56
|
+
/** How the text of a file was read, as its extractor said, in the fields of `DocumentMeta`. */
|
|
57
|
+
function readingOf(extracted) {
|
|
58
|
+
const { encoding, replacedCharacters } = extracted;
|
|
59
|
+
return {
|
|
60
|
+
...(olderEncoding(encoding) ? { encoding } : {}),
|
|
61
|
+
...(typeof replacedCharacters === "number" && Number.isSafeInteger(replacedCharacters) && replacedCharacters > 0 ? { replacedCharacters } : {}),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A file name as one printable line: the last path segment. Control characters, line and paragraph
|
|
66
|
+
* separators, and text-direction controls (the marks of right-to-left text included) become a space.
|
|
67
|
+
* Names are shown to the model and in UIs, so a name must not be able to start a new line of the
|
|
68
|
+
* prompt, or disguise its extension. Most characters that show nothing are removed (tag characters,
|
|
69
|
+
* zero-width spaces); the variation selectors and joiners that scripts and emoji need are kept, and
|
|
70
|
+
* can still carry data a person does not see.
|
|
37
71
|
*/
|
|
38
72
|
export function cleanFileName(raw) {
|
|
39
73
|
const base = raw.split(/[\\/]/).at(-1) ?? "";
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
74
|
+
// Control characters, line and paragraph separators, and text-direction controls become a space.
|
|
75
|
+
const spaced = base.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]+/gu, " ");
|
|
76
|
+
const name = removeInvisible(spaced).replace(/\s+/g, " ").trim();
|
|
77
|
+
// At most 255 characters, never half of an emoji. A flag cut short loses the tags left of it.
|
|
78
|
+
return (name.length > 255 ? removeInvisible(sliceWhole(name, 255)) : name) || "file";
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Metadata with a whole file name. 0.5.0 and earlier cut a long name at 255 UTF-16 units, at times
|
|
82
|
+
* inside an emoji, and stored it: half of a character is sent as a replacement character, never on
|
|
83
|
+
* its own (Claude's API refuses it). Metadata whose name is whole comes back as it is.
|
|
84
|
+
*/
|
|
85
|
+
function wholeName(meta) {
|
|
86
|
+
const name = wellFormed(meta.name);
|
|
87
|
+
return name === meta.name ? meta : { ...meta, name };
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Refuses an owner that every caller without a user would share: an empty string (what
|
|
91
|
+
* `user?.id ?? ""` gives), one of spaces only, or null. Undefined is no owner. A number is let
|
|
92
|
+
* through, as before, for JavaScript code that passes numeric user IDs.
|
|
93
|
+
*/
|
|
94
|
+
export function checkOwner(owner) {
|
|
95
|
+
if (owner === undefined || (typeof owner === "string" && owner.trim() !== "") || (typeof owner === "number" && Number.isFinite(owner)))
|
|
96
|
+
return;
|
|
97
|
+
throw new TypeError("owner must be a string that is not empty or only spaces, such as the signed-in user's ID. To let anyone with the document's ID use it, leave owner out.");
|
|
46
98
|
}
|
|
47
99
|
/**
|
|
48
100
|
* A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
|
|
@@ -66,20 +118,172 @@ function allowed(meta, access) {
|
|
|
66
118
|
}
|
|
67
119
|
/** Default for `cacheBytes`. */
|
|
68
120
|
export const DEFAULT_CACHE_BYTES = 256 * 1024 * 1024;
|
|
121
|
+
/** The refusal of a file whose text is larger than `maxTextBytes`. */
|
|
122
|
+
const tooMuchText = (name, maxTextBytes) => new Error(`${name} holds more than ${formatBytes(maxTextBytes)} of text, more than is kept from one file. Split it, and attach the part you need.`);
|
|
123
|
+
/** Default for `maxPdfPages`. */
|
|
124
|
+
export const DEFAULT_MAX_PDF_PAGES = 5_000;
|
|
125
|
+
/** Default for `maxTextBytes`, when `maxUploadBytes` is not larger: 100 MB. */
|
|
126
|
+
export const DEFAULT_MAX_TEXT_BYTES = 100 * 1024 * 1024;
|
|
127
|
+
/** Default for `ingestTimeoutMs`: 2 minutes. */
|
|
128
|
+
export const DEFAULT_INGEST_TIMEOUT_MS = 120_000;
|
|
129
|
+
/** The longest a Node.js timer waits: a longer one fires at once. A limit past it is no limit. */
|
|
130
|
+
const LONGEST_TIMER_MS = 2 ** 31 - 1;
|
|
131
|
+
/** A time limit in the words of a message: "500 ms", "45 s", "2 min". */
|
|
132
|
+
function formatDuration(ms) {
|
|
133
|
+
if (ms < 1_000)
|
|
134
|
+
return `${Math.max(1, Math.round(ms))} ms`;
|
|
135
|
+
if (ms < 120_000)
|
|
136
|
+
return `${Number((ms / 1_000).toFixed(1))} s`;
|
|
137
|
+
return `${Number((ms / 60_000).toFixed(1))} min`;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* The signal one ingest runs under: aborted when the caller's is, or when `timeoutMs` has passed
|
|
141
|
+
* (with an error that says the file took too long). `dispose` stops the timer.
|
|
142
|
+
*/
|
|
143
|
+
function ingestSignal(name, caller, timeoutMs) {
|
|
144
|
+
const controller = new AbortController();
|
|
145
|
+
const onAbort = () => controller.abort(caller.reason);
|
|
146
|
+
if (caller?.aborted)
|
|
147
|
+
controller.abort(caller.reason);
|
|
148
|
+
else
|
|
149
|
+
caller?.addEventListener("abort", onAbort, { once: true });
|
|
150
|
+
const timer = timeoutMs > 0 && timeoutMs <= LONGEST_TIMER_MS
|
|
151
|
+
? setTimeout(() => controller.abort(new Error(`${name} took too long to read (more than ${formatDuration(timeoutMs)}). Split it, or save it as plain text, and attach that.`)), timeoutMs)
|
|
152
|
+
: undefined;
|
|
153
|
+
return {
|
|
154
|
+
signal: controller.signal,
|
|
155
|
+
dispose() {
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
caller?.removeEventListener("abort", onAbort);
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* `work`, or the signal's reason as soon as it is aborted: an extractor of your own that does not
|
|
163
|
+
* look at the signal is no longer waited for (though the work it does cannot be stopped).
|
|
164
|
+
*/
|
|
165
|
+
function untilAborted(work, signal) {
|
|
166
|
+
if (signal.aborted)
|
|
167
|
+
return Promise.reject(signal.reason);
|
|
168
|
+
return new Promise((resolve, reject) => {
|
|
169
|
+
const onAbort = () => reject(signal.reason);
|
|
170
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
171
|
+
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
/** The message of `ingest.error` when the store failed to write the document. */
|
|
175
|
+
const STORE_WRITE_FAILED = "The document could not be stored. Try again later.";
|
|
176
|
+
/** The least time between two `ingest.progress` events of one stage, in milliseconds: a slice of `TimeSlicer`. */
|
|
177
|
+
const PROGRESS_MS = 12;
|
|
178
|
+
const EXTRACT_STAGES = new Set(["extract", "check", "pictures", "decode"]);
|
|
179
|
+
const EXTRACT_UNITS = new Set(["pages", "parts", "bytes"]);
|
|
180
|
+
const isCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
181
|
+
/** What `ingest.start` says of an ingest, worked out from whatever it was given: the checks come after it. */
|
|
182
|
+
function startOf(input) {
|
|
183
|
+
try {
|
|
184
|
+
const name = typeof input?.name === "string" ? cleanFileName(input.name) : "";
|
|
185
|
+
const mimeType = (typeof input?.mimeType === "string" ? input.mimeType.trim() : "") || "application/octet-stream";
|
|
186
|
+
const bytes = input?.bytes?.byteLength;
|
|
187
|
+
return { name, format: detectFormat(name, mimeType), bytes: isCount(bytes) ? bytes : 0 };
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
return { name: "", format: "text", bytes: 0 };
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Sends the `ingest.progress` events of one ingest: at most one every `PROGRESS_MS` for each stage,
|
|
195
|
+
* however the stages take turns, then the last progress of each stage when the stages end (`end`).
|
|
196
|
+
* A progress that completes its stage goes out at once, the first time, so that stages that run one
|
|
197
|
+
* after the other end in that order. Made only when someone listens.
|
|
198
|
+
*/
|
|
199
|
+
class IngestProgress {
|
|
200
|
+
events;
|
|
201
|
+
/** Each stage that reported, in the order it first did: when it last sent, and its last progress. */
|
|
202
|
+
stages = new Map();
|
|
203
|
+
/** Set once a stage after the extractor's began: an extract stage is not reported again. */
|
|
204
|
+
extractOver = false;
|
|
205
|
+
constructor(events) {
|
|
206
|
+
this.events = events;
|
|
207
|
+
}
|
|
208
|
+
report(stage, done, total, unit) {
|
|
209
|
+
if (!EXTRACT_STAGES.has(stage))
|
|
210
|
+
this.extractOver = true;
|
|
211
|
+
const last = { done, total, unit, sent: false };
|
|
212
|
+
let state = this.stages.get(stage);
|
|
213
|
+
if (!state) {
|
|
214
|
+
state = { sentAt: Number.NEGATIVE_INFINITY, completed: false, last };
|
|
215
|
+
this.stages.set(stage, state);
|
|
216
|
+
}
|
|
217
|
+
state.last = last;
|
|
218
|
+
const now = performance.now();
|
|
219
|
+
const completes = !state.completed && total !== undefined && done >= total;
|
|
220
|
+
if (completes)
|
|
221
|
+
state.completed = true;
|
|
222
|
+
if (completes || now - state.sentAt >= PROGRESS_MS) {
|
|
223
|
+
state.sentAt = now;
|
|
224
|
+
this.send(stage, last);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/** The progress an extractor reported (`ExtractInput.onProgress`). One of your own may send anything: what does not fit is left out. */
|
|
228
|
+
extracted(progress) {
|
|
229
|
+
if (this.extractOver)
|
|
230
|
+
return;
|
|
231
|
+
const stage = progress?.stage ?? "extract";
|
|
232
|
+
if (!EXTRACT_STAGES.has(stage) || !EXTRACT_UNITS.has(progress?.unit) || !isCount(progress?.done))
|
|
233
|
+
return;
|
|
234
|
+
this.report(stage, progress.done, isCount(progress.total) ? progress.total : undefined, progress.unit);
|
|
235
|
+
}
|
|
236
|
+
/** The stages so far are over: the last progress of each, when it was held back, goes out, in the order they began. */
|
|
237
|
+
end() {
|
|
238
|
+
const held = [...this.stages].filter(([, state]) => !state.last.sent);
|
|
239
|
+
this.stages.clear();
|
|
240
|
+
for (const [stage, state] of held)
|
|
241
|
+
this.send(stage, state.last);
|
|
242
|
+
}
|
|
243
|
+
send(stage, last) {
|
|
244
|
+
last.sent = true;
|
|
245
|
+
this.events.emit({
|
|
246
|
+
type: "ingest.progress",
|
|
247
|
+
stage,
|
|
248
|
+
done: last.done,
|
|
249
|
+
...(last.total !== undefined ? { total: last.total } : {}),
|
|
250
|
+
unit: last.unit,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
}
|
|
69
254
|
/** Default for `wholeDocumentBytes`. */
|
|
70
255
|
export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
|
256
|
+
/**
|
|
257
|
+
* A number option as it was given, or `fallback` when it was left out. NaN, which
|
|
258
|
+
* `Number(process.env.X)` gives for a variable that is not set, and a value that is not a number
|
|
259
|
+
* are an error: NaN passes every `Math.max` and fails every comparison, so it hung the scans or
|
|
260
|
+
* turned a limit off. `finite` refuses `Infinity` too, for an option that cannot be endless.
|
|
261
|
+
*/
|
|
262
|
+
function numberOption(name, value, fallback, finite = false) {
|
|
263
|
+
if (value === undefined)
|
|
264
|
+
return fallback;
|
|
265
|
+
if (typeof value !== "number")
|
|
266
|
+
throw new TypeError(`${name} must be a number, and is ${typeof value === "string" ? JSON.stringify(value) : typeof value}.`);
|
|
267
|
+
if (Number.isNaN(value) || (finite && !Number.isFinite(value)))
|
|
268
|
+
throw new RangeError(`${name} must be a ${finite ? "finite " : ""}number, and is ${value}. Leave it out for the default.`);
|
|
269
|
+
return value;
|
|
270
|
+
}
|
|
71
271
|
export function createLargeFiles(options) {
|
|
72
272
|
/** The fields the application set. The others follow the context window, whichever it is for a request. */
|
|
73
273
|
const ownBudget = givenBudget(options.budget);
|
|
74
274
|
const budget = resolveBudget(ownBudget);
|
|
75
275
|
const budgetFor = (overrides, limits) => (overrides || limits ? resolveBudget({ ...ownBudget, ...givenBudget(overrides) }, limits) : budget);
|
|
76
|
-
const ttlMs = options.ttlMs
|
|
77
|
-
const maxUploadBytes = options.maxUploadBytes
|
|
276
|
+
const ttlMs = numberOption("ttlMs", options.ttlMs, 72 * 60 * 60 * 1000);
|
|
277
|
+
const maxUploadBytes = numberOption("maxUploadBytes", options.maxUploadBytes, 100 * 1024 * 1024);
|
|
278
|
+
const given = (value, fallback) => (typeof value === "number" && !Number.isNaN(value) ? value : fallback);
|
|
279
|
+
const maxTextBytes = Math.max(1, given(options.maxTextBytes, Math.max(maxUploadBytes, DEFAULT_MAX_TEXT_BYTES)));
|
|
280
|
+
const maxPdfPages = Math.max(1, Math.trunc(given(options.maxPdfPages, DEFAULT_MAX_PDF_PAGES)));
|
|
281
|
+
const ingestTimeoutMs = given(options.ingestTimeoutMs, DEFAULT_INGEST_TIMEOUT_MS);
|
|
78
282
|
const now = options.now ?? (() => new Date());
|
|
79
283
|
const { store } = options;
|
|
80
|
-
const cacheBytes = Math.max(0, options.cacheBytes
|
|
284
|
+
const cacheBytes = Math.max(0, numberOption("cacheBytes", options.cacheBytes, DEFAULT_CACHE_BYTES));
|
|
81
285
|
/** Documents ready to search, and decoded pieces of documents read by range, in one memory budget. */
|
|
82
|
-
const cache = new DocumentCache(cacheBytes,
|
|
286
|
+
const cache = new DocumentCache(cacheBytes, Math.max(0, Math.trunc(numberOption("cacheSize", options.cacheSize, Number.POSITIVE_INFINITY))));
|
|
83
287
|
/** Forgets everything kept of a document: the document, and its pieces. */
|
|
84
288
|
const forget = (id) => {
|
|
85
289
|
cache.delete(id);
|
|
@@ -95,12 +299,12 @@ export function createLargeFiles(options) {
|
|
|
95
299
|
} : undefined;
|
|
96
300
|
/** The uploaded file of a document, when the store keeps such files. */
|
|
97
301
|
const loadOriginal = store.getOriginal ? (id) => reading(() => store.getOriginal(id)) : undefined;
|
|
98
|
-
const wholeDocumentBytes = Math.max(0, options.wholeDocumentBytes
|
|
302
|
+
const wholeDocumentBytes = Math.max(0, numberOption("wholeDocumentBytes", options.wholeDocumentBytes, DEFAULT_WHOLE_DOCUMENT_BYTES));
|
|
99
303
|
/** Documents whose saved index did not match their text: the next opening builds it from the text. */
|
|
100
304
|
const rebuildIndex = new Set();
|
|
101
305
|
const scan = {
|
|
102
|
-
chunkBytes: Math.max(1, Math.trunc(options.scanChunkBytes
|
|
103
|
-
limiter: new Limiter(Math.max(1, Math.trunc(options.maxConcurrentScans
|
|
306
|
+
chunkBytes: Math.max(1, Math.trunc(numberOption("scanChunkBytes", options.scanChunkBytes, 1024 * 1024, true))),
|
|
307
|
+
limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentScans", options.maxConcurrentScans, 4)))),
|
|
104
308
|
onBroken: (id) => {
|
|
105
309
|
rebuildIndex.add(id);
|
|
106
310
|
forget(id);
|
|
@@ -114,7 +318,7 @@ export function createLargeFiles(options) {
|
|
|
114
318
|
},
|
|
115
319
|
};
|
|
116
320
|
const keepOriginals = new Set(options.keepOriginals ?? []);
|
|
117
|
-
const scannedPdfPages = Math.max(0, Math.trunc(options.scannedPdfPages
|
|
321
|
+
const scannedPdfPages = Math.max(0, Math.trunc(numberOption("scannedPdfPages", options.scannedPdfPages, 30)));
|
|
118
322
|
/** Whether the uploaded file of a document of this format is kept. */
|
|
119
323
|
const keeps = (format) => keepOriginals.has(format) && typeof options.store.putOriginal === "function";
|
|
120
324
|
/**
|
|
@@ -129,7 +333,7 @@ export function createLargeFiles(options) {
|
|
|
129
333
|
forget(id);
|
|
130
334
|
return undefined;
|
|
131
335
|
}
|
|
132
|
-
return meta;
|
|
336
|
+
return wholeName(meta);
|
|
133
337
|
}
|
|
134
338
|
/**
|
|
135
339
|
* A document ready to read and search. The store is asked first, every time: a kept copy is
|
|
@@ -162,13 +366,16 @@ export function createLargeFiles(options) {
|
|
|
162
366
|
return openRangedDocument(ranged, meta, scan, { ignoreSavedIndex: rebuild });
|
|
163
367
|
}
|
|
164
368
|
const stored = await reading(() => store.get(id));
|
|
165
|
-
|
|
369
|
+
if (!stored)
|
|
370
|
+
return undefined;
|
|
371
|
+
const named = wholeName(stored.meta);
|
|
372
|
+
return new SearchableDocument(named === stored.meta ? stored : { ...stored, meta: named });
|
|
166
373
|
}
|
|
167
374
|
/**
|
|
168
375
|
* What a document contributes to the prompt: its text, or its card. Undefined when it is gone
|
|
169
376
|
* by now. A copy found to disagree with the store is opened again once.
|
|
170
377
|
*/
|
|
171
|
-
async function block(id, meta, whole, viewable,
|
|
378
|
+
async function block(id, meta, whole, viewable, wholeRead) {
|
|
172
379
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
173
380
|
const document = await load(id, attempt === 0 ? meta : undefined);
|
|
174
381
|
if (!document)
|
|
@@ -176,7 +383,7 @@ export function createLargeFiles(options) {
|
|
|
176
383
|
try {
|
|
177
384
|
return whole
|
|
178
385
|
? renderInline(document.meta, await document.readText())
|
|
179
|
-
: renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable,
|
|
386
|
+
: renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, wholeRead);
|
|
180
387
|
}
|
|
181
388
|
catch (error) {
|
|
182
389
|
if (!document.broken) {
|
|
@@ -193,81 +400,213 @@ export function createLargeFiles(options) {
|
|
|
193
400
|
const meta = await currentMeta(id);
|
|
194
401
|
return meta && allowed(meta, access) ? meta : undefined;
|
|
195
402
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
403
|
+
/**
|
|
404
|
+
* The work of `ingest`, once the file is named: `detected` is the format its name and type say.
|
|
405
|
+
* `progress` is given when someone listens to the events of the ingest. `storeFailed` is called
|
|
406
|
+
* when the store fails to write the document, whatever it throws.
|
|
407
|
+
*/
|
|
408
|
+
async function ingestFile(input, name, mimeType, detected, progress, storeFailed) {
|
|
409
|
+
if (input.bytes.byteLength === 0)
|
|
410
|
+
throw new Error(`${name} is empty.`);
|
|
411
|
+
if (input.bytes.byteLength > maxUploadBytes) {
|
|
412
|
+
throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
|
|
413
|
+
}
|
|
414
|
+
let format = detected;
|
|
415
|
+
const { signal, dispose } = ingestSignal(name, input.signal, ingestTimeoutMs);
|
|
416
|
+
// Each long step works in slices, with pauses for other requests: one large upload no longer
|
|
417
|
+
// holds the whole server while it is read.
|
|
418
|
+
const slicer = new TimeSlicer(signal);
|
|
419
|
+
let pages;
|
|
420
|
+
let reading;
|
|
421
|
+
let text;
|
|
422
|
+
let wrapped;
|
|
423
|
+
let lines;
|
|
424
|
+
let measured;
|
|
425
|
+
let outline;
|
|
426
|
+
let logProfile;
|
|
427
|
+
let index;
|
|
428
|
+
try {
|
|
429
|
+
signal.throwIfAborted();
|
|
430
|
+
// In a function of its own, so that the text as extracted is let go once it is prepared:
|
|
431
|
+
// the steps after it hold only the prepared text.
|
|
432
|
+
const read = async () => {
|
|
433
|
+
// What an extractor of your own reports once it has settled (from a timer, a worker) is
|
|
434
|
+
// not reported: the stages after it have begun.
|
|
435
|
+
let extracting = true;
|
|
436
|
+
let extracted;
|
|
437
|
+
try {
|
|
438
|
+
extracted = await untilAborted(extractText(input.bytes, {
|
|
439
|
+
name,
|
|
440
|
+
mimeType,
|
|
441
|
+
format,
|
|
442
|
+
// A scan is worth storing only if its pages can be shown later: that needs the file itself.
|
|
443
|
+
...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
|
|
444
|
+
signal,
|
|
445
|
+
maxTextBytes,
|
|
446
|
+
maxPages: maxPdfPages,
|
|
447
|
+
...(progress ? { onProgress: (report) => { if (extracting)
|
|
448
|
+
progress.extracted(report); } } : {}),
|
|
449
|
+
}, options.extractors), signal);
|
|
450
|
+
}
|
|
451
|
+
finally {
|
|
452
|
+
extracting = false;
|
|
453
|
+
}
|
|
454
|
+
progress?.end();
|
|
455
|
+
// A character is at least one byte: a text this long is too large whatever it holds.
|
|
456
|
+
if (extracted.text.length > maxTextBytes)
|
|
457
|
+
throw tooMuchText(name, maxTextBytes);
|
|
458
|
+
await slicer.pauseNow();
|
|
459
|
+
return { pages: extracted.pages, reading: readingOf(extracted), ...await prepareText(extracted.text, slicer, progress && ((done, total) => progress.report("prepare", done, total, "characters"))) };
|
|
460
|
+
};
|
|
461
|
+
({ pages, reading, text, wrapped, lines } = await read());
|
|
462
|
+
progress?.end();
|
|
217
463
|
if (!text.trim())
|
|
218
464
|
throw new Error(`${name} did not contain any text.`);
|
|
219
|
-
const lines = text.split("\n");
|
|
220
|
-
if (text.endsWith("\n"))
|
|
221
|
-
lines.pop();
|
|
222
465
|
if (format === "text" && looksLikeLog(lines))
|
|
223
466
|
format = "log";
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
id: `doc_${randomUUID().replaceAll("-", "")}`,
|
|
230
|
-
...(input.owner !== undefined ? { owner: input.owner } : {}),
|
|
231
|
-
name,
|
|
232
|
-
mimeType,
|
|
233
|
-
format,
|
|
234
|
-
bytes: input.bytes.byteLength,
|
|
235
|
-
textBytes: sizes.utf8,
|
|
236
|
-
jsonBytes: sizes.json,
|
|
237
|
-
characters: text.length,
|
|
238
|
-
lines: lines.length,
|
|
239
|
-
estimatedTokens: estimateTokens(text),
|
|
240
|
-
wrappedLines: wrapped,
|
|
241
|
-
...(extracted.pages ? { pages: extracted.pages } : {}),
|
|
242
|
-
...(keepOriginal ? { originalKept: true } : {}),
|
|
243
|
-
outline: buildOutline(lines, format),
|
|
244
|
-
...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
|
|
245
|
-
createdAt: created.toISOString(),
|
|
246
|
-
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
247
|
-
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
248
|
-
};
|
|
467
|
+
measured = await measureText(text, slicer);
|
|
468
|
+
if (measured.utf8 > maxTextBytes)
|
|
469
|
+
throw tooMuchText(name, maxTextBytes);
|
|
470
|
+
outline = await buildOutlineInSlices(lines, format, slicer);
|
|
471
|
+
logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
|
|
249
472
|
// The line index, so that the text can be read by range: a few bytes a line, built from the
|
|
250
473
|
// UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
|
|
251
474
|
// then loads whole, so that switching to reading by range finds it ready.
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
? serializeTextIndex(index)
|
|
475
|
+
index = typeof store.putIndex === "function"
|
|
476
|
+
? await buildTextIndexInSlices(text, slicer, progress && ((done, total) => progress.report("index", done, total, "characters")))
|
|
255
477
|
: undefined;
|
|
478
|
+
progress?.end();
|
|
479
|
+
signal.throwIfAborted();
|
|
480
|
+
}
|
|
481
|
+
finally {
|
|
482
|
+
dispose();
|
|
483
|
+
}
|
|
484
|
+
const created = now();
|
|
485
|
+
const expires = created.getTime() + ttlMs;
|
|
486
|
+
const keepOriginal = keeps(format);
|
|
487
|
+
const meta = {
|
|
488
|
+
id: `doc_${randomUUID().replaceAll("-", "")}`,
|
|
489
|
+
...(input.owner !== undefined ? { owner: input.owner } : {}),
|
|
490
|
+
name,
|
|
491
|
+
mimeType,
|
|
492
|
+
format,
|
|
493
|
+
bytes: input.bytes.byteLength,
|
|
494
|
+
textBytes: measured.utf8,
|
|
495
|
+
jsonBytes: measured.json,
|
|
496
|
+
characters: text.length,
|
|
497
|
+
lines: lines.length,
|
|
498
|
+
estimatedTokens: measured.tokens,
|
|
499
|
+
wrappedLines: wrapped,
|
|
500
|
+
...(pages ? { pages } : {}),
|
|
501
|
+
...reading,
|
|
502
|
+
...(keepOriginal ? { originalKept: true } : {}),
|
|
503
|
+
outline,
|
|
504
|
+
...(logProfile ? { logProfile } : {}),
|
|
505
|
+
createdAt: created.toISOString(),
|
|
506
|
+
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
507
|
+
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
508
|
+
};
|
|
509
|
+
const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
|
|
510
|
+
? serializeTextIndex(index)
|
|
511
|
+
: undefined;
|
|
512
|
+
// Each write is reported once done. What the listener of the events throws is not the store's failure.
|
|
513
|
+
const writes = (keepOriginal ? 1 : 0) + (savedIndex ? 1 : 0) + 1;
|
|
514
|
+
let written = 0;
|
|
515
|
+
let listenerFailed;
|
|
516
|
+
const wrote = (last) => {
|
|
517
|
+
if (!progress)
|
|
518
|
+
return;
|
|
256
519
|
try {
|
|
257
|
-
|
|
258
|
-
if (
|
|
259
|
-
|
|
260
|
-
if (savedIndex)
|
|
261
|
-
await store.putIndex(meta.id, savedIndex);
|
|
262
|
-
await store.put({ meta, text });
|
|
520
|
+
progress.report("store", ++written, writes, "parts");
|
|
521
|
+
if (last)
|
|
522
|
+
progress.end();
|
|
263
523
|
}
|
|
264
524
|
catch (error) {
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
525
|
+
listenerFailed = { error };
|
|
526
|
+
throw error;
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
try {
|
|
530
|
+
// The files first, the document last: a document is there once its metadata is.
|
|
531
|
+
if (keepOriginal) {
|
|
532
|
+
await store.putOriginal(meta.id, input.bytes);
|
|
533
|
+
wrote(false);
|
|
534
|
+
}
|
|
535
|
+
if (savedIndex) {
|
|
536
|
+
await store.putIndex(meta.id, savedIndex);
|
|
537
|
+
wrote(false);
|
|
538
|
+
}
|
|
539
|
+
await store.put({ meta, text });
|
|
540
|
+
wrote(true);
|
|
541
|
+
}
|
|
542
|
+
catch (error) {
|
|
543
|
+
// Do not leave a file of up to the upload limit, or a part of one, behind for a document
|
|
544
|
+
// that does not exist.
|
|
545
|
+
await store.delete(meta.id).catch(() => undefined);
|
|
546
|
+
if (listenerFailed?.error !== error) {
|
|
547
|
+
noteStoreWriteFailure(error);
|
|
548
|
+
storeFailed();
|
|
549
|
+
}
|
|
550
|
+
throw error;
|
|
551
|
+
}
|
|
552
|
+
return meta;
|
|
553
|
+
}
|
|
554
|
+
return {
|
|
555
|
+
budget,
|
|
556
|
+
budgetFor,
|
|
557
|
+
maxUploadBytes,
|
|
558
|
+
async ingest(input) {
|
|
559
|
+
// The events first, so that every ingest that throws, even on what it was given, ends with ingest.error.
|
|
560
|
+
// What the caller's listener throws is passed on as it is, not told as a file that could not be read.
|
|
561
|
+
let listenerFailure;
|
|
562
|
+
const listener = input?.onEvent;
|
|
563
|
+
const events = new EventEmitter(input?.runId ?? newRunId("ing"), listener && ((event) => {
|
|
564
|
+
try {
|
|
565
|
+
listener(event);
|
|
566
|
+
}
|
|
567
|
+
catch (error) {
|
|
568
|
+
listenerFailure ??= { error };
|
|
569
|
+
throw error;
|
|
570
|
+
}
|
|
571
|
+
}));
|
|
572
|
+
let storeFailed = false;
|
|
573
|
+
try {
|
|
574
|
+
if (events.active)
|
|
575
|
+
events.emit({ type: "ingest.start", ...startOf(input) });
|
|
576
|
+
checkOwner(input.owner);
|
|
577
|
+
const name = cleanFileName(input.name);
|
|
578
|
+
const mimeType = input.mimeType?.trim() || "application/octet-stream";
|
|
579
|
+
const format = detectFormat(name, mimeType);
|
|
580
|
+
// Progress is worked out only for someone who listens.
|
|
581
|
+
const progress = events.active ? new IngestProgress(events) : undefined;
|
|
582
|
+
let meta;
|
|
583
|
+
try {
|
|
584
|
+
meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true));
|
|
585
|
+
}
|
|
586
|
+
catch (error) {
|
|
587
|
+
// A store that failed, and a caller that gave up (its own reason), are passed on as they
|
|
588
|
+
// are; a file that could not be read is told with a code.
|
|
589
|
+
if (storeFailed || (input.signal?.aborted && error === input.signal.reason) || isStoreWriteFailure(error) || (listenerFailure && error === listenerFailure.error))
|
|
590
|
+
throw error;
|
|
591
|
+
throw toIngestError(error);
|
|
592
|
+
}
|
|
593
|
+
try {
|
|
594
|
+
events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
|
|
595
|
+
}
|
|
596
|
+
catch (error) {
|
|
597
|
+
// The caller never gets the id: the document goes, as on a throw of the listener a moment earlier.
|
|
598
|
+
await store.delete(meta.id).catch(() => undefined);
|
|
599
|
+
forget(meta.id);
|
|
600
|
+
throw error;
|
|
601
|
+
}
|
|
602
|
+
return meta;
|
|
603
|
+
}
|
|
604
|
+
catch (error) {
|
|
605
|
+
// A store's own error may name a host or a path, whatever it is: the event, which a browser
|
|
606
|
+
// may see, says only that the document could not be stored.
|
|
607
|
+
events.emit({ type: "ingest.error", error: storeFailed ? { message: STORE_WRITE_FAILED } : eventErrorOf(error) });
|
|
268
608
|
throw error;
|
|
269
609
|
}
|
|
270
|
-
return meta;
|
|
271
610
|
},
|
|
272
611
|
getMeta: metaFor,
|
|
273
612
|
async getOriginal(id, access) {
|
|
@@ -285,6 +624,7 @@ export function createLargeFiles(options) {
|
|
|
285
624
|
},
|
|
286
625
|
async prepare(ids, base, access) {
|
|
287
626
|
const budget = budgetFor(access?.budget);
|
|
627
|
+
const analysis = access?.wholeDocumentAnalysis !== false;
|
|
288
628
|
const unique = [...new Set(ids)];
|
|
289
629
|
let documents = [];
|
|
290
630
|
const missing = [];
|
|
@@ -310,15 +650,17 @@ export function createLargeFiles(options) {
|
|
|
310
650
|
const blocks = new Map();
|
|
311
651
|
const gone = [];
|
|
312
652
|
for (const meta of documents) {
|
|
313
|
-
const
|
|
653
|
+
const wholeRead = !analysis ? "not_offered" : canBeReadWhole(meta, budget) ? "offered" : "too_large";
|
|
654
|
+
const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id), wholeRead);
|
|
314
655
|
if (text === undefined)
|
|
315
656
|
gone.push(meta.id);
|
|
316
657
|
else
|
|
317
658
|
blocks.set(meta.id, text);
|
|
318
659
|
}
|
|
319
660
|
if (gone.length === 0) {
|
|
320
|
-
// A whole-document read is named only when one of the files is
|
|
321
|
-
|
|
661
|
+
// A whole-document read is named only when the tools have it, and one of the files is
|
|
662
|
+
// small enough for it.
|
|
663
|
+
const wholeReads = analysis && plan.searchable.some((meta) => canBeReadWhole(meta, budget));
|
|
322
664
|
return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable, wholeReads), missing, viewable };
|
|
323
665
|
}
|
|
324
666
|
missing.push(...gone);
|
|
@@ -330,12 +672,26 @@ export function createLargeFiles(options) {
|
|
|
330
672
|
const budget = budgetFor(overrides);
|
|
331
673
|
const viewable = (loadOriginal ? (viewPages === true ? documents : viewPages || []) : [])
|
|
332
674
|
.filter((meta) => meta.format === "pdf" && meta.originalKept);
|
|
675
|
+
// The owner each document was handed in with. The store's owner is checked against it on
|
|
676
|
+
// every call, so metadata built from an ID alone cannot read another owner's document: such
|
|
677
|
+
// a document is answered as no longer available, as `getMeta` reports it missing.
|
|
678
|
+
const handedOwner = new Map([...documents, ...viewable].map((meta) => [meta.id, meta.owner]));
|
|
679
|
+
const mayUse = (meta) => meta.owner === undefined || (handedOwner.has(meta.id) && meta.owner === handedOwner.get(meta.id));
|
|
680
|
+
// The metadata the store holds now, not that of a copy kept in memory.
|
|
681
|
+
const checkedLoad = async (id) => {
|
|
682
|
+
const meta = await currentMeta(id);
|
|
683
|
+
return meta && mayUse(meta) ? load(id, meta) : undefined;
|
|
684
|
+
};
|
|
685
|
+
const checkedOriginal = loadOriginal && (async (id) => {
|
|
686
|
+
const meta = await currentMeta(id);
|
|
687
|
+
return meta && mayUse(meta) ? loadOriginal(id) : undefined;
|
|
688
|
+
});
|
|
333
689
|
return createDocumentTools({
|
|
334
|
-
load,
|
|
690
|
+
load: checkedLoad,
|
|
335
691
|
documentIds: documents.map((meta) => meta.id),
|
|
336
|
-
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, meta.name])),
|
|
692
|
+
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
|
|
337
693
|
budget,
|
|
338
|
-
...(
|
|
694
|
+
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal } : {}),
|
|
339
695
|
// `analyze_whole_document` is declared only when it can read at least one of the documents.
|
|
340
696
|
wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
|
|
341
697
|
...rest,
|