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/src/library.ts
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, type ModelLimits } from "./budget.js";
|
|
4
4
|
import { DocumentCache, documentVersion, type Sized } from "./cache.js";
|
|
5
|
-
import { DocumentStoreError } from "./errors.js";
|
|
5
|
+
import { DocumentStoreError, isStoreWriteFailure, noteStoreWriteFailure, toIngestError } from "./errors.js";
|
|
6
|
+
import { EventEmitter, eventErrorOf, newRunId, type IngestEvent, type IngestStage } from "./events.js";
|
|
6
7
|
import { detectFormat, extractText } from "./extract.js";
|
|
7
8
|
import { Limiter } from "./limiter.js";
|
|
8
|
-
import {
|
|
9
|
+
import { TimeSlicer } from "./pause.js";
|
|
10
|
+
import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline, type WholeRead } from "./plan.js";
|
|
9
11
|
import { openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
|
|
10
12
|
import { numberLines, SearchableDocument, type DocumentSource } 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 type { RetryOptions } from "./retry.js";
|
|
15
17
|
import { createDocumentTools } from "./tools.js";
|
|
16
18
|
import type {
|
|
@@ -19,6 +21,8 @@ import type {
|
|
|
19
21
|
DocumentMeta,
|
|
20
22
|
DocumentStore,
|
|
21
23
|
DocumentSummary,
|
|
24
|
+
ExtractedText,
|
|
25
|
+
ExtractProgress,
|
|
22
26
|
Extractor,
|
|
23
27
|
GenerateText,
|
|
24
28
|
PreparedContext,
|
|
@@ -44,6 +48,25 @@ export type LargeFilesOptions = {
|
|
|
44
48
|
ttlMs?: number;
|
|
45
49
|
/** Largest accepted upload. Defaults to 100 MB. */
|
|
46
50
|
maxUploadBytes?: number;
|
|
51
|
+
/**
|
|
52
|
+
* The most text kept from one file, in UTF-8 bytes. Defaults to 100 MB, or `maxUploadBytes` when
|
|
53
|
+
* that is larger: the text of a DOCX is often 2 to 4 times the size of the file, so a lower upload
|
|
54
|
+
* limit does not lower it. A small PDF can
|
|
55
|
+
* draw far more text than its own size (a 3 KB file built for it held 107 MB), so this is checked
|
|
56
|
+
* as the text is extracted: the built-in extractors refuse a file as soon as its text passes it,
|
|
57
|
+
* and `ingest` refuses a larger result from an extractor of your own.
|
|
58
|
+
*/
|
|
59
|
+
maxTextBytes?: number;
|
|
60
|
+
/** The most pages read from one PDF. Defaults to 5,000. A PDF with more is refused before any page is read. */
|
|
61
|
+
maxPdfPages?: number;
|
|
62
|
+
/**
|
|
63
|
+
* The most time one `ingest` may take, in milliseconds: extracting the text, indexing it and
|
|
64
|
+
* profiling a log. Defaults to 120,000 (2 minutes). Past it, `ingest` throws an error that says
|
|
65
|
+
* the file took too long to read. 0 sets no limit, and so does a time past what a timer can wait
|
|
66
|
+
* (2,147,483,647 ms, 24.8 days). One page of a PDF is not cut short: the limit is looked at
|
|
67
|
+
* between pages.
|
|
68
|
+
*/
|
|
69
|
+
ingestTimeoutMs?: number;
|
|
47
70
|
/** Override or add text extractors per format. */
|
|
48
71
|
extractors?: Partial<Record<DocumentFormat, Extractor>>;
|
|
49
72
|
/**
|
|
@@ -95,8 +118,24 @@ export type IngestInput = {
|
|
|
95
118
|
name: string;
|
|
96
119
|
mimeType?: string;
|
|
97
120
|
bytes: Uint8Array;
|
|
98
|
-
/**
|
|
121
|
+
/**
|
|
122
|
+
* The user (or tenant) the document belongs to. Later calls must pass the same owner. An empty
|
|
123
|
+
* string, or one of spaces only, is refused with a TypeError: it would be one owner shared by
|
|
124
|
+
* every caller without a user.
|
|
125
|
+
*/
|
|
99
126
|
owner?: string;
|
|
127
|
+
/**
|
|
128
|
+
* Stops the ingest when aborted (the uploader went away): it throws `signal.reason`, and nothing
|
|
129
|
+
* is stored. The built-in extractors stop between pages and pieces.
|
|
130
|
+
*/
|
|
131
|
+
signal?: AbortSignal;
|
|
132
|
+
/**
|
|
133
|
+
* What the ingest does as it goes: `ingest.start`, `ingest.progress` for each stage, then
|
|
134
|
+
* `ingest.finish` or `ingest.error`. See docs/reference/events.md. New in 0.7.0.
|
|
135
|
+
*/
|
|
136
|
+
onEvent?: (event: IngestEvent) => void;
|
|
137
|
+
/** The `runId` of those events. Defaults to one made for the ingest ("ing_…"). */
|
|
138
|
+
runId?: string;
|
|
100
139
|
};
|
|
101
140
|
|
|
102
141
|
/** Access options. When a document has an owner, only that owner can use it. */
|
|
@@ -114,6 +153,13 @@ export type PrepareOptions = AccessOptions & {
|
|
|
114
153
|
* tell the model about `view_pages`. Without it, the result is that of 0.2.0.
|
|
115
154
|
*/
|
|
116
155
|
viewPages?: boolean;
|
|
156
|
+
/**
|
|
157
|
+
* Say whether your tool set offers `analyze_whole_document`: pass false when you call `tools()`
|
|
158
|
+
* without `generate`, and the instruction and the cards do not name it. Defaults to true.
|
|
159
|
+
* `askWithFiles` passes false for a model without `generateText`, and for
|
|
160
|
+
* `wholeDocumentAnalysis: false`.
|
|
161
|
+
*/
|
|
162
|
+
wholeDocumentAnalysis?: boolean;
|
|
117
163
|
};
|
|
118
164
|
|
|
119
165
|
export type ToolOptions = {
|
|
@@ -159,7 +205,11 @@ export interface LargeFiles {
|
|
|
159
205
|
*/
|
|
160
206
|
budgetFor(overrides?: Partial<Budget>, limits?: ModelLimits): Budget;
|
|
161
207
|
readonly maxUploadBytes: number;
|
|
162
|
-
/**
|
|
208
|
+
/**
|
|
209
|
+
* Extracts, normalizes, profiles, and stores a file. Throws a user-readable Error on bad input.
|
|
210
|
+
* A store that fails to write throws its own error, as it is: log it, and do not show its
|
|
211
|
+
* message to a user, as it may name a path, a host or a bucket.
|
|
212
|
+
*/
|
|
163
213
|
ingest(input: IngestInput): Promise<DocumentMeta>;
|
|
164
214
|
getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
|
|
165
215
|
/** The uploaded file itself, when it was kept (see `keepOriginals`). Treat the bytes as read-only. */
|
|
@@ -191,23 +241,75 @@ export function toDocumentSummary(meta: DocumentMeta): DocumentSummary {
|
|
|
191
241
|
lines: meta.lines,
|
|
192
242
|
estimatedTokens: meta.estimatedTokens,
|
|
193
243
|
...(meta.pages ? { pages: meta.pages } : {}),
|
|
244
|
+
...(meta.encoding ? { encoding: meta.encoding } : {}),
|
|
245
|
+
...(meta.replacedCharacters ? { replacedCharacters: meta.replacedCharacters } : {}),
|
|
194
246
|
expiresAt: meta.expiresAt,
|
|
195
247
|
};
|
|
196
248
|
}
|
|
197
249
|
|
|
250
|
+
/** An encoding's name as TextDecoder gives it ("windows-1255"): an extractor of your own may name another. */
|
|
251
|
+
const ENCODING_NAME = /^[a-z0-9][a-z0-9._:-]{0,39}$/i;
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Whether the name is an older encoding, as `DocumentMeta.encoding` records: not UTF-8 or UTF-16,
|
|
255
|
+
* under any of their names ("utf8", "unicode"). The model is told the file is not in UTF-8.
|
|
256
|
+
*/
|
|
257
|
+
function olderEncoding(name: unknown): name is string {
|
|
258
|
+
if (typeof name !== "string" || !ENCODING_NAME.test(name)) return false;
|
|
259
|
+
let known: string;
|
|
260
|
+
try {
|
|
261
|
+
known = new TextDecoder(name).encoding;
|
|
262
|
+
} catch {
|
|
263
|
+
// A name TextDecoder does not know: the extractor read the file itself.
|
|
264
|
+
return true;
|
|
265
|
+
}
|
|
266
|
+
return known !== "utf-8" && known !== "utf-16le" && known !== "utf-16be";
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** How the text of a file was read, as its extractor said, in the fields of `DocumentMeta`. */
|
|
270
|
+
function readingOf(extracted: ExtractedText): Pick<DocumentMeta, "encoding" | "replacedCharacters"> {
|
|
271
|
+
const { encoding, replacedCharacters } = extracted;
|
|
272
|
+
return {
|
|
273
|
+
...(olderEncoding(encoding) ? { encoding } : {}),
|
|
274
|
+
...(typeof replacedCharacters === "number" && Number.isSafeInteger(replacedCharacters) && replacedCharacters > 0 ? { replacedCharacters } : {}),
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
198
278
|
/**
|
|
199
|
-
* A file name as one printable line: the last path segment
|
|
200
|
-
*
|
|
201
|
-
* not be able to start a new line of the
|
|
279
|
+
* A file name as one printable line: the last path segment. Control characters, line and paragraph
|
|
280
|
+
* separators, and text-direction controls (the marks of right-to-left text included) become a space.
|
|
281
|
+
* Names are shown to the model and in UIs, so a name must not be able to start a new line of the
|
|
282
|
+
* prompt, or disguise its extension. Most characters that show nothing are removed (tag characters,
|
|
283
|
+
* zero-width spaces); the variation selectors and joiners that scripts and emoji need are kept, and
|
|
284
|
+
* can still carry data a person does not see.
|
|
202
285
|
*/
|
|
203
286
|
export function cleanFileName(raw: string): string {
|
|
204
287
|
const base = raw.split(/[\\/]/).at(-1) ?? "";
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
288
|
+
// Control characters, line and paragraph separators, and text-direction controls become a space.
|
|
289
|
+
const spaced = base.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]+/gu, " ");
|
|
290
|
+
const name = removeInvisible(spaced).replace(/\s+/g, " ").trim();
|
|
291
|
+
// At most 255 characters, never half of an emoji. A flag cut short loses the tags left of it.
|
|
292
|
+
return (name.length > 255 ? removeInvisible(sliceWhole(name, 255)) : name) || "file";
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Metadata with a whole file name. 0.5.0 and earlier cut a long name at 255 UTF-16 units, at times
|
|
297
|
+
* inside an emoji, and stored it: half of a character is sent as a replacement character, never on
|
|
298
|
+
* its own (Claude's API refuses it). Metadata whose name is whole comes back as it is.
|
|
299
|
+
*/
|
|
300
|
+
function wholeName(meta: DocumentMeta): DocumentMeta {
|
|
301
|
+
const name = wellFormed(meta.name);
|
|
302
|
+
return name === meta.name ? meta : { ...meta, name };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Refuses an owner that every caller without a user would share: an empty string (what
|
|
307
|
+
* `user?.id ?? ""` gives), one of spaces only, or null. Undefined is no owner. A number is let
|
|
308
|
+
* through, as before, for JavaScript code that passes numeric user IDs.
|
|
309
|
+
*/
|
|
310
|
+
export function checkOwner(owner: unknown): void {
|
|
311
|
+
if (owner === undefined || (typeof owner === "string" && owner.trim() !== "") || (typeof owner === "number" && Number.isFinite(owner))) return;
|
|
312
|
+
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.");
|
|
211
313
|
}
|
|
212
314
|
|
|
213
315
|
/**
|
|
@@ -234,9 +336,160 @@ function allowed(meta: DocumentMeta, access: AccessOptions | undefined): boolean
|
|
|
234
336
|
|
|
235
337
|
/** Default for `cacheBytes`. */
|
|
236
338
|
export const DEFAULT_CACHE_BYTES = 256 * 1024 * 1024;
|
|
339
|
+
/** The refusal of a file whose text is larger than `maxTextBytes`. */
|
|
340
|
+
const tooMuchText = (name: string, maxTextBytes: number) =>
|
|
341
|
+
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.`);
|
|
342
|
+
|
|
343
|
+
/** Default for `maxPdfPages`. */
|
|
344
|
+
export const DEFAULT_MAX_PDF_PAGES = 5_000;
|
|
345
|
+
/** Default for `maxTextBytes`, when `maxUploadBytes` is not larger: 100 MB. */
|
|
346
|
+
export const DEFAULT_MAX_TEXT_BYTES = 100 * 1024 * 1024;
|
|
347
|
+
/** Default for `ingestTimeoutMs`: 2 minutes. */
|
|
348
|
+
export const DEFAULT_INGEST_TIMEOUT_MS = 120_000;
|
|
349
|
+
/** The longest a Node.js timer waits: a longer one fires at once. A limit past it is no limit. */
|
|
350
|
+
const LONGEST_TIMER_MS = 2 ** 31 - 1;
|
|
351
|
+
|
|
352
|
+
/** A time limit in the words of a message: "500 ms", "45 s", "2 min". */
|
|
353
|
+
function formatDuration(ms: number): string {
|
|
354
|
+
if (ms < 1_000) return `${Math.max(1, Math.round(ms))} ms`;
|
|
355
|
+
if (ms < 120_000) return `${Number((ms / 1_000).toFixed(1))} s`;
|
|
356
|
+
return `${Number((ms / 60_000).toFixed(1))} min`;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* The signal one ingest runs under: aborted when the caller's is, or when `timeoutMs` has passed
|
|
361
|
+
* (with an error that says the file took too long). `dispose` stops the timer.
|
|
362
|
+
*/
|
|
363
|
+
function ingestSignal(name: string, caller: AbortSignal | undefined, timeoutMs: number): { signal: AbortSignal; dispose(): void } {
|
|
364
|
+
const controller = new AbortController();
|
|
365
|
+
const onAbort = () => controller.abort(caller!.reason);
|
|
366
|
+
if (caller?.aborted) controller.abort(caller.reason);
|
|
367
|
+
else caller?.addEventListener("abort", onAbort, { once: true });
|
|
368
|
+
const timer = timeoutMs > 0 && timeoutMs <= LONGEST_TIMER_MS
|
|
369
|
+
? 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)
|
|
370
|
+
: undefined;
|
|
371
|
+
return {
|
|
372
|
+
signal: controller.signal,
|
|
373
|
+
dispose() {
|
|
374
|
+
clearTimeout(timer);
|
|
375
|
+
caller?.removeEventListener("abort", onAbort);
|
|
376
|
+
},
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* `work`, or the signal's reason as soon as it is aborted: an extractor of your own that does not
|
|
382
|
+
* look at the signal is no longer waited for (though the work it does cannot be stopped).
|
|
383
|
+
*/
|
|
384
|
+
function untilAborted<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
385
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
386
|
+
return new Promise<T>((resolve, reject) => {
|
|
387
|
+
const onAbort = () => reject(signal.reason);
|
|
388
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
389
|
+
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** The message of `ingest.error` when the store failed to write the document. */
|
|
394
|
+
const STORE_WRITE_FAILED = "The document could not be stored. Try again later.";
|
|
395
|
+
|
|
396
|
+
/** The least time between two `ingest.progress` events of one stage, in milliseconds: a slice of `TimeSlicer`. */
|
|
397
|
+
const PROGRESS_MS = 12;
|
|
398
|
+
|
|
399
|
+
type ProgressUnit = Extract<IngestEvent, { type: "ingest.progress" }>["unit"];
|
|
400
|
+
const EXTRACT_STAGES = new Set<unknown>(["extract", "check", "pictures", "decode"]);
|
|
401
|
+
const EXTRACT_UNITS = new Set<unknown>(["pages", "parts", "bytes"]);
|
|
402
|
+
const isCount = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
403
|
+
|
|
404
|
+
/** What `ingest.start` says of an ingest, worked out from whatever it was given: the checks come after it. */
|
|
405
|
+
function startOf(input: IngestInput | undefined): { name: string; format: DocumentFormat; bytes: number } {
|
|
406
|
+
try {
|
|
407
|
+
const name = typeof input?.name === "string" ? cleanFileName(input.name) : "";
|
|
408
|
+
const mimeType = (typeof input?.mimeType === "string" ? input.mimeType.trim() : "") || "application/octet-stream";
|
|
409
|
+
const bytes = input?.bytes?.byteLength;
|
|
410
|
+
return { name, format: detectFormat(name, mimeType), bytes: isCount(bytes) ? bytes : 0 };
|
|
411
|
+
} catch {
|
|
412
|
+
return { name: "", format: "text", bytes: 0 };
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
type HeldProgress = { done: number; total: number | undefined; unit: ProgressUnit; sent: boolean };
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Sends the `ingest.progress` events of one ingest: at most one every `PROGRESS_MS` for each stage,
|
|
420
|
+
* however the stages take turns, then the last progress of each stage when the stages end (`end`).
|
|
421
|
+
* A progress that completes its stage goes out at once, the first time, so that stages that run one
|
|
422
|
+
* after the other end in that order. Made only when someone listens.
|
|
423
|
+
*/
|
|
424
|
+
class IngestProgress {
|
|
425
|
+
/** Each stage that reported, in the order it first did: when it last sent, and its last progress. */
|
|
426
|
+
private readonly stages = new Map<IngestStage, { sentAt: number; completed: boolean; last: HeldProgress }>();
|
|
427
|
+
/** Set once a stage after the extractor's began: an extract stage is not reported again. */
|
|
428
|
+
private extractOver = false;
|
|
429
|
+
|
|
430
|
+
constructor(private readonly events: EventEmitter<IngestEvent>) {}
|
|
431
|
+
|
|
432
|
+
report(stage: IngestStage, done: number, total: number | undefined, unit: ProgressUnit): void {
|
|
433
|
+
if (!EXTRACT_STAGES.has(stage)) this.extractOver = true;
|
|
434
|
+
const last: HeldProgress = { done, total, unit, sent: false };
|
|
435
|
+
let state = this.stages.get(stage);
|
|
436
|
+
if (!state) {
|
|
437
|
+
state = { sentAt: Number.NEGATIVE_INFINITY, completed: false, last };
|
|
438
|
+
this.stages.set(stage, state);
|
|
439
|
+
}
|
|
440
|
+
state.last = last;
|
|
441
|
+
const now = performance.now();
|
|
442
|
+
const completes = !state.completed && total !== undefined && done >= total;
|
|
443
|
+
if (completes) state.completed = true;
|
|
444
|
+
if (completes || now - state.sentAt >= PROGRESS_MS) {
|
|
445
|
+
state.sentAt = now;
|
|
446
|
+
this.send(stage, last);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** The progress an extractor reported (`ExtractInput.onProgress`). One of your own may send anything: what does not fit is left out. */
|
|
451
|
+
extracted(progress: ExtractProgress): void {
|
|
452
|
+
if (this.extractOver) return;
|
|
453
|
+
const stage = progress?.stage ?? "extract";
|
|
454
|
+
if (!EXTRACT_STAGES.has(stage) || !EXTRACT_UNITS.has(progress?.unit) || !isCount(progress?.done)) return;
|
|
455
|
+
this.report(stage, progress.done, isCount(progress.total) ? progress.total : undefined, progress.unit);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** The stages so far are over: the last progress of each, when it was held back, goes out, in the order they began. */
|
|
459
|
+
end(): void {
|
|
460
|
+
const held = [...this.stages].filter(([, state]) => !state.last.sent);
|
|
461
|
+
this.stages.clear();
|
|
462
|
+
for (const [stage, state] of held) this.send(stage, state.last);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
private send(stage: IngestStage, last: HeldProgress): void {
|
|
466
|
+
last.sent = true;
|
|
467
|
+
this.events.emit({
|
|
468
|
+
type: "ingest.progress",
|
|
469
|
+
stage,
|
|
470
|
+
done: last.done,
|
|
471
|
+
...(last.total !== undefined ? { total: last.total } : {}),
|
|
472
|
+
unit: last.unit,
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
237
477
|
/** Default for `wholeDocumentBytes`. */
|
|
238
478
|
export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
|
239
479
|
|
|
480
|
+
/**
|
|
481
|
+
* A number option as it was given, or `fallback` when it was left out. NaN, which
|
|
482
|
+
* `Number(process.env.X)` gives for a variable that is not set, and a value that is not a number
|
|
483
|
+
* are an error: NaN passes every `Math.max` and fails every comparison, so it hung the scans or
|
|
484
|
+
* turned a limit off. `finite` refuses `Infinity` too, for an option that cannot be endless.
|
|
485
|
+
*/
|
|
486
|
+
function numberOption(name: string, value: unknown, fallback: number, finite = false): number {
|
|
487
|
+
if (value === undefined) return fallback;
|
|
488
|
+
if (typeof value !== "number") throw new TypeError(`${name} must be a number, and is ${typeof value === "string" ? JSON.stringify(value) : typeof value}.`);
|
|
489
|
+
if (Number.isNaN(value) || (finite && !Number.isFinite(value))) throw new RangeError(`${name} must be a ${finite ? "finite " : ""}number, and is ${value}. Leave it out for the default.`);
|
|
490
|
+
return value;
|
|
491
|
+
}
|
|
492
|
+
|
|
240
493
|
export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
241
494
|
/** The fields the application set. The others follow the context window, whichever it is for a request. */
|
|
242
495
|
const ownBudget = givenBudget(options.budget);
|
|
@@ -244,15 +497,19 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
244
497
|
const budgetFor = (overrides?: Partial<Budget>, limits?: ModelLimits): Budget => (
|
|
245
498
|
overrides || limits ? resolveBudget({ ...ownBudget, ...givenBudget(overrides) }, limits) : budget
|
|
246
499
|
);
|
|
247
|
-
const ttlMs = options.ttlMs
|
|
248
|
-
const maxUploadBytes = options.maxUploadBytes
|
|
500
|
+
const ttlMs = numberOption("ttlMs", options.ttlMs, 72 * 60 * 60 * 1000);
|
|
501
|
+
const maxUploadBytes = numberOption("maxUploadBytes", options.maxUploadBytes, 100 * 1024 * 1024);
|
|
502
|
+
const given = (value: number | undefined, fallback: number) => (typeof value === "number" && !Number.isNaN(value) ? value : fallback);
|
|
503
|
+
const maxTextBytes = Math.max(1, given(options.maxTextBytes, Math.max(maxUploadBytes, DEFAULT_MAX_TEXT_BYTES)));
|
|
504
|
+
const maxPdfPages = Math.max(1, Math.trunc(given(options.maxPdfPages, DEFAULT_MAX_PDF_PAGES)));
|
|
505
|
+
const ingestTimeoutMs = given(options.ingestTimeoutMs, DEFAULT_INGEST_TIMEOUT_MS);
|
|
249
506
|
const now = options.now ?? (() => new Date());
|
|
250
507
|
const { store } = options;
|
|
251
|
-
const cacheBytes = Math.max(0, options.cacheBytes
|
|
508
|
+
const cacheBytes = Math.max(0, numberOption("cacheBytes", options.cacheBytes, DEFAULT_CACHE_BYTES));
|
|
252
509
|
/** Documents ready to search, and decoded pieces of documents read by range, in one memory budget. */
|
|
253
510
|
const cache = new DocumentCache<Sized>(
|
|
254
511
|
cacheBytes,
|
|
255
|
-
|
|
512
|
+
Math.max(0, Math.trunc(numberOption("cacheSize", options.cacheSize, Number.POSITIVE_INFINITY))),
|
|
256
513
|
);
|
|
257
514
|
/** Forgets everything kept of a document: the document, and its pieces. */
|
|
258
515
|
const forget = (id: string) => {
|
|
@@ -269,12 +526,12 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
269
526
|
} : undefined;
|
|
270
527
|
/** The uploaded file of a document, when the store keeps such files. */
|
|
271
528
|
const loadOriginal = store.getOriginal ? (id: string) => reading(() => store.getOriginal!(id)) : undefined;
|
|
272
|
-
const wholeDocumentBytes = Math.max(0, options.wholeDocumentBytes
|
|
529
|
+
const wholeDocumentBytes = Math.max(0, numberOption("wholeDocumentBytes", options.wholeDocumentBytes, DEFAULT_WHOLE_DOCUMENT_BYTES));
|
|
273
530
|
/** Documents whose saved index did not match their text: the next opening builds it from the text. */
|
|
274
531
|
const rebuildIndex = new Set<string>();
|
|
275
532
|
const scan: ScanSettings = {
|
|
276
|
-
chunkBytes: Math.max(1, Math.trunc(options.scanChunkBytes
|
|
277
|
-
limiter: new Limiter(Math.max(1, Math.trunc(options.maxConcurrentScans
|
|
533
|
+
chunkBytes: Math.max(1, Math.trunc(numberOption("scanChunkBytes", options.scanChunkBytes, 1024 * 1024, true))),
|
|
534
|
+
limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentScans", options.maxConcurrentScans, 4)))),
|
|
278
535
|
onBroken: (id) => {
|
|
279
536
|
rebuildIndex.add(id);
|
|
280
537
|
forget(id);
|
|
@@ -288,7 +545,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
288
545
|
},
|
|
289
546
|
};
|
|
290
547
|
const keepOriginals = new Set<DocumentFormat>(options.keepOriginals ?? []);
|
|
291
|
-
const scannedPdfPages = Math.max(0, Math.trunc(options.scannedPdfPages
|
|
548
|
+
const scannedPdfPages = Math.max(0, Math.trunc(numberOption("scannedPdfPages", options.scannedPdfPages, 30)));
|
|
292
549
|
/** Whether the uploaded file of a document of this format is kept. */
|
|
293
550
|
const keeps = (format: DocumentFormat) => keepOriginals.has(format) && typeof options.store.putOriginal === "function";
|
|
294
551
|
|
|
@@ -303,7 +560,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
303
560
|
forget(id);
|
|
304
561
|
return undefined;
|
|
305
562
|
}
|
|
306
|
-
return meta;
|
|
563
|
+
return wholeName(meta);
|
|
307
564
|
}
|
|
308
565
|
|
|
309
566
|
/**
|
|
@@ -335,21 +592,23 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
335
592
|
return openRangedDocument(ranged, meta, scan, { ignoreSavedIndex: rebuild });
|
|
336
593
|
}
|
|
337
594
|
const stored = await reading(() => store.get(id));
|
|
338
|
-
|
|
595
|
+
if (!stored) return undefined;
|
|
596
|
+
const named = wholeName(stored.meta);
|
|
597
|
+
return new SearchableDocument(named === stored.meta ? stored : { ...stored, meta: named });
|
|
339
598
|
}
|
|
340
599
|
|
|
341
600
|
/**
|
|
342
601
|
* What a document contributes to the prompt: its text, or its card. Undefined when it is gone
|
|
343
602
|
* by now. A copy found to disagree with the store is opened again once.
|
|
344
603
|
*/
|
|
345
|
-
async function block(id: string, meta: DocumentMeta, whole: boolean, viewable: boolean,
|
|
604
|
+
async function block(id: string, meta: DocumentMeta, whole: boolean, viewable: boolean, wholeRead: WholeRead): Promise<string | undefined> {
|
|
346
605
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
347
606
|
const document = await load(id, attempt === 0 ? meta : undefined);
|
|
348
607
|
if (!document) return undefined;
|
|
349
608
|
try {
|
|
350
609
|
return whole
|
|
351
610
|
? renderInline(document.meta, await document.readText())
|
|
352
|
-
: renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable,
|
|
611
|
+
: renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, wholeRead);
|
|
353
612
|
} catch (error) {
|
|
354
613
|
if (!document.broken) {
|
|
355
614
|
// Deleted between the look-up and the read: the same as missing.
|
|
@@ -366,75 +625,204 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
366
625
|
return meta && allowed(meta, access) ? meta : undefined;
|
|
367
626
|
}
|
|
368
627
|
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
628
|
+
/**
|
|
629
|
+
* The work of `ingest`, once the file is named: `detected` is the format its name and type say.
|
|
630
|
+
* `progress` is given when someone listens to the events of the ingest. `storeFailed` is called
|
|
631
|
+
* when the store fails to write the document, whatever it throws.
|
|
632
|
+
*/
|
|
633
|
+
async function ingestFile(
|
|
634
|
+
input: IngestInput,
|
|
635
|
+
name: string,
|
|
636
|
+
mimeType: string,
|
|
637
|
+
detected: DocumentFormat,
|
|
638
|
+
progress: IngestProgress | undefined,
|
|
639
|
+
storeFailed: () => void,
|
|
640
|
+
): Promise<DocumentMeta> {
|
|
641
|
+
if (input.bytes.byteLength === 0) throw new Error(`${name} is empty.`);
|
|
642
|
+
if (input.bytes.byteLength > maxUploadBytes) {
|
|
643
|
+
throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
|
|
644
|
+
}
|
|
645
|
+
let format = detected;
|
|
646
|
+
const { signal, dispose } = ingestSignal(name, input.signal, ingestTimeoutMs);
|
|
647
|
+
// Each long step works in slices, with pauses for other requests: one large upload no longer
|
|
648
|
+
// holds the whole server while it is read.
|
|
649
|
+
const slicer = new TimeSlicer(signal);
|
|
650
|
+
let pages: number | undefined;
|
|
651
|
+
let reading: ReturnType<typeof readingOf>;
|
|
652
|
+
let text: string;
|
|
653
|
+
let wrapped: number;
|
|
654
|
+
let lines: string[];
|
|
655
|
+
let measured: Awaited<ReturnType<typeof measureText>>;
|
|
656
|
+
let outline: DocumentMeta["outline"];
|
|
657
|
+
let logProfile: DocumentMeta["logProfile"];
|
|
658
|
+
let index: Awaited<ReturnType<typeof buildTextIndexInSlices>> | undefined;
|
|
659
|
+
try {
|
|
660
|
+
signal.throwIfAborted();
|
|
661
|
+
// In a function of its own, so that the text as extracted is let go once it is prepared:
|
|
662
|
+
// the steps after it hold only the prepared text.
|
|
663
|
+
const read = async () => {
|
|
664
|
+
// What an extractor of your own reports once it has settled (from a timer, a worker) is
|
|
665
|
+
// not reported: the stages after it have begun.
|
|
666
|
+
let extracting = true;
|
|
667
|
+
let extracted: ExtractedText;
|
|
668
|
+
try {
|
|
669
|
+
extracted = await untilAborted(extractText(input.bytes, {
|
|
670
|
+
name,
|
|
671
|
+
mimeType,
|
|
672
|
+
format,
|
|
673
|
+
// A scan is worth storing only if its pages can be shown later: that needs the file itself.
|
|
674
|
+
...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
|
|
675
|
+
signal,
|
|
676
|
+
maxTextBytes,
|
|
677
|
+
maxPages: maxPdfPages,
|
|
678
|
+
...(progress ? { onProgress: (report: ExtractProgress) => { if (extracting) progress.extracted(report); } } : {}),
|
|
679
|
+
}, options.extractors), signal);
|
|
680
|
+
} finally {
|
|
681
|
+
extracting = false;
|
|
682
|
+
}
|
|
683
|
+
progress?.end();
|
|
684
|
+
// A character is at least one byte: a text this long is too large whatever it holds.
|
|
685
|
+
if (extracted.text.length > maxTextBytes) throw tooMuchText(name, maxTextBytes);
|
|
686
|
+
await slicer.pauseNow();
|
|
687
|
+
return { pages: extracted.pages, reading: readingOf(extracted), ...await prepareText(extracted.text, slicer, progress && ((done, total) => progress.report("prepare", done, total, "characters"))) };
|
|
688
|
+
};
|
|
689
|
+
({ pages, reading, text, wrapped, lines } = await read());
|
|
690
|
+
progress?.end();
|
|
390
691
|
if (!text.trim()) throw new Error(`${name} did not contain any text.`);
|
|
391
|
-
const lines = text.split("\n");
|
|
392
|
-
if (text.endsWith("\n")) lines.pop();
|
|
393
692
|
if (format === "text" && looksLikeLog(lines)) format = "log";
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
const meta: DocumentMeta = {
|
|
399
|
-
id: `doc_${randomUUID().replaceAll("-", "")}`,
|
|
400
|
-
...(input.owner !== undefined ? { owner: input.owner } : {}),
|
|
401
|
-
name,
|
|
402
|
-
mimeType,
|
|
403
|
-
format,
|
|
404
|
-
bytes: input.bytes.byteLength,
|
|
405
|
-
textBytes: sizes.utf8,
|
|
406
|
-
jsonBytes: sizes.json,
|
|
407
|
-
characters: text.length,
|
|
408
|
-
lines: lines.length,
|
|
409
|
-
estimatedTokens: estimateTokens(text),
|
|
410
|
-
wrappedLines: wrapped,
|
|
411
|
-
...(extracted.pages ? { pages: extracted.pages } : {}),
|
|
412
|
-
...(keepOriginal ? { originalKept: true } : {}),
|
|
413
|
-
outline: buildOutline(lines, format),
|
|
414
|
-
...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
|
|
415
|
-
createdAt: created.toISOString(),
|
|
416
|
-
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
417
|
-
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
418
|
-
};
|
|
693
|
+
measured = await measureText(text, slicer);
|
|
694
|
+
if (measured.utf8 > maxTextBytes) throw tooMuchText(name, maxTextBytes);
|
|
695
|
+
outline = await buildOutlineInSlices(lines, format, slicer);
|
|
696
|
+
logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
|
|
419
697
|
// The line index, so that the text can be read by range: a few bytes a line, built from the
|
|
420
698
|
// UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
|
|
421
699
|
// then loads whole, so that switching to reading by range finds it ready.
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
? serializeTextIndex(index)
|
|
700
|
+
index = typeof store.putIndex === "function"
|
|
701
|
+
? await buildTextIndexInSlices(text, slicer, progress && ((done, total) => progress.report("index", done, total, "characters")))
|
|
425
702
|
: undefined;
|
|
703
|
+
progress?.end();
|
|
704
|
+
signal.throwIfAborted();
|
|
705
|
+
} finally {
|
|
706
|
+
dispose();
|
|
707
|
+
}
|
|
708
|
+
const created = now();
|
|
709
|
+
const expires = created.getTime() + ttlMs;
|
|
710
|
+
const keepOriginal = keeps(format);
|
|
711
|
+
const meta: DocumentMeta = {
|
|
712
|
+
id: `doc_${randomUUID().replaceAll("-", "")}`,
|
|
713
|
+
...(input.owner !== undefined ? { owner: input.owner } : {}),
|
|
714
|
+
name,
|
|
715
|
+
mimeType,
|
|
716
|
+
format,
|
|
717
|
+
bytes: input.bytes.byteLength,
|
|
718
|
+
textBytes: measured.utf8,
|
|
719
|
+
jsonBytes: measured.json,
|
|
720
|
+
characters: text.length,
|
|
721
|
+
lines: lines.length,
|
|
722
|
+
estimatedTokens: measured.tokens,
|
|
723
|
+
wrappedLines: wrapped,
|
|
724
|
+
...(pages ? { pages } : {}),
|
|
725
|
+
...reading,
|
|
726
|
+
...(keepOriginal ? { originalKept: true } : {}),
|
|
727
|
+
outline,
|
|
728
|
+
...(logProfile ? { logProfile } : {}),
|
|
729
|
+
createdAt: created.toISOString(),
|
|
730
|
+
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
731
|
+
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
732
|
+
};
|
|
733
|
+
const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
|
|
734
|
+
? serializeTextIndex(index)
|
|
735
|
+
: undefined;
|
|
736
|
+
// Each write is reported once done. What the listener of the events throws is not the store's failure.
|
|
737
|
+
const writes = (keepOriginal ? 1 : 0) + (savedIndex ? 1 : 0) + 1;
|
|
738
|
+
let written = 0;
|
|
739
|
+
let listenerFailed: { error: unknown } | undefined;
|
|
740
|
+
const wrote = (last: boolean) => {
|
|
741
|
+
if (!progress) return;
|
|
742
|
+
try {
|
|
743
|
+
progress.report("store", ++written, writes, "parts");
|
|
744
|
+
if (last) progress.end();
|
|
745
|
+
} catch (error) {
|
|
746
|
+
listenerFailed = { error };
|
|
747
|
+
throw error;
|
|
748
|
+
}
|
|
749
|
+
};
|
|
750
|
+
try {
|
|
751
|
+
// The files first, the document last: a document is there once its metadata is.
|
|
752
|
+
if (keepOriginal) {
|
|
753
|
+
await store.putOriginal!(meta.id, input.bytes);
|
|
754
|
+
wrote(false);
|
|
755
|
+
}
|
|
756
|
+
if (savedIndex) {
|
|
757
|
+
await store.putIndex!(meta.id, savedIndex);
|
|
758
|
+
wrote(false);
|
|
759
|
+
}
|
|
760
|
+
await store.put({ meta, text });
|
|
761
|
+
wrote(true);
|
|
762
|
+
} catch (error) {
|
|
763
|
+
// Do not leave a file of up to the upload limit, or a part of one, behind for a document
|
|
764
|
+
// that does not exist.
|
|
765
|
+
await store.delete(meta.id).catch(() => undefined);
|
|
766
|
+
if (listenerFailed?.error !== error) {
|
|
767
|
+
noteStoreWriteFailure(error);
|
|
768
|
+
storeFailed();
|
|
769
|
+
}
|
|
770
|
+
throw error;
|
|
771
|
+
}
|
|
772
|
+
return meta;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
return {
|
|
776
|
+
budget,
|
|
777
|
+
budgetFor,
|
|
778
|
+
maxUploadBytes,
|
|
779
|
+
|
|
780
|
+
async ingest(input) {
|
|
781
|
+
// The events first, so that every ingest that throws, even on what it was given, ends with ingest.error.
|
|
782
|
+
// What the caller's listener throws is passed on as it is, not told as a file that could not be read.
|
|
783
|
+
let listenerFailure: { error: unknown } | undefined;
|
|
784
|
+
const listener = input?.onEvent;
|
|
785
|
+
const events = new EventEmitter<IngestEvent>(input?.runId ?? newRunId("ing"), listener && ((event: IngestEvent) => {
|
|
786
|
+
try {
|
|
787
|
+
listener(event);
|
|
788
|
+
} catch (error) {
|
|
789
|
+
listenerFailure ??= { error };
|
|
790
|
+
throw error;
|
|
791
|
+
}
|
|
792
|
+
}));
|
|
793
|
+
let storeFailed = false;
|
|
426
794
|
try {
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
795
|
+
if (events.active) events.emit({ type: "ingest.start", ...startOf(input) });
|
|
796
|
+
checkOwner(input.owner);
|
|
797
|
+
const name = cleanFileName(input.name);
|
|
798
|
+
const mimeType = input.mimeType?.trim() || "application/octet-stream";
|
|
799
|
+
const format = detectFormat(name, mimeType);
|
|
800
|
+
// Progress is worked out only for someone who listens.
|
|
801
|
+
const progress = events.active ? new IngestProgress(events) : undefined;
|
|
802
|
+
let meta: DocumentMeta;
|
|
803
|
+
try {
|
|
804
|
+
meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true));
|
|
805
|
+
} catch (error) {
|
|
806
|
+
// A store that failed, and a caller that gave up (its own reason), are passed on as they
|
|
807
|
+
// are; a file that could not be read is told with a code.
|
|
808
|
+
if (storeFailed || (input.signal?.aborted && error === input.signal.reason) || isStoreWriteFailure(error) || (listenerFailure && error === listenerFailure.error)) throw error;
|
|
809
|
+
throw toIngestError(error);
|
|
810
|
+
}
|
|
811
|
+
try {
|
|
812
|
+
events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
|
|
813
|
+
} catch (error) {
|
|
814
|
+
// The caller never gets the id: the document goes, as on a throw of the listener a moment earlier.
|
|
815
|
+
await store.delete(meta.id).catch(() => undefined);
|
|
816
|
+
forget(meta.id);
|
|
817
|
+
throw error;
|
|
818
|
+
}
|
|
819
|
+
return meta;
|
|
431
820
|
} catch (error) {
|
|
432
|
-
//
|
|
433
|
-
// that
|
|
434
|
-
|
|
821
|
+
// A store's own error may name a host or a path, whatever it is: the event, which a browser
|
|
822
|
+
// may see, says only that the document could not be stored.
|
|
823
|
+
events.emit({ type: "ingest.error", error: storeFailed ? { message: STORE_WRITE_FAILED } : eventErrorOf(error) });
|
|
435
824
|
throw error;
|
|
436
825
|
}
|
|
437
|
-
return meta;
|
|
438
826
|
},
|
|
439
827
|
|
|
440
828
|
getMeta: metaFor,
|
|
@@ -456,6 +844,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
456
844
|
|
|
457
845
|
async prepare(ids, base, access) {
|
|
458
846
|
const budget = budgetFor(access?.budget);
|
|
847
|
+
const analysis = access?.wholeDocumentAnalysis !== false;
|
|
459
848
|
const unique = [...new Set(ids)];
|
|
460
849
|
let documents: DocumentMeta[] = [];
|
|
461
850
|
const missing: string[] = [];
|
|
@@ -479,13 +868,15 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
479
868
|
const blocks = new Map<string, string>();
|
|
480
869
|
const gone: string[] = [];
|
|
481
870
|
for (const meta of documents) {
|
|
482
|
-
const
|
|
871
|
+
const wholeRead = !analysis ? "not_offered" : canBeReadWhole(meta, budget) ? "offered" : "too_large";
|
|
872
|
+
const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id), wholeRead);
|
|
483
873
|
if (text === undefined) gone.push(meta.id);
|
|
484
874
|
else blocks.set(meta.id, text);
|
|
485
875
|
}
|
|
486
876
|
if (gone.length === 0) {
|
|
487
|
-
// A whole-document read is named only when one of the files is
|
|
488
|
-
|
|
877
|
+
// A whole-document read is named only when the tools have it, and one of the files is
|
|
878
|
+
// small enough for it.
|
|
879
|
+
const wholeReads = analysis && plan.searchable.some((meta) => canBeReadWhole(meta, budget));
|
|
489
880
|
return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable, wholeReads), missing, viewable };
|
|
490
881
|
}
|
|
491
882
|
missing.push(...gone);
|
|
@@ -498,12 +889,26 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
498
889
|
const budget = budgetFor(overrides);
|
|
499
890
|
const viewable = (loadOriginal ? (viewPages === true ? documents : viewPages || []) : [])
|
|
500
891
|
.filter((meta) => meta.format === "pdf" && meta.originalKept);
|
|
892
|
+
// The owner each document was handed in with. The store's owner is checked against it on
|
|
893
|
+
// every call, so metadata built from an ID alone cannot read another owner's document: such
|
|
894
|
+
// a document is answered as no longer available, as `getMeta` reports it missing.
|
|
895
|
+
const handedOwner = new Map<string, string | undefined>([...documents, ...viewable].map((meta) => [meta.id, meta.owner]));
|
|
896
|
+
const mayUse = (meta: DocumentMeta) => meta.owner === undefined || (handedOwner.has(meta.id) && meta.owner === handedOwner.get(meta.id));
|
|
897
|
+
// The metadata the store holds now, not that of a copy kept in memory.
|
|
898
|
+
const checkedLoad = async (id: string) => {
|
|
899
|
+
const meta = await currentMeta(id);
|
|
900
|
+
return meta && mayUse(meta) ? load(id, meta) : undefined;
|
|
901
|
+
};
|
|
902
|
+
const checkedOriginal = loadOriginal && (async (id: string) => {
|
|
903
|
+
const meta = await currentMeta(id);
|
|
904
|
+
return meta && mayUse(meta) ? loadOriginal(id) : undefined;
|
|
905
|
+
});
|
|
501
906
|
return createDocumentTools({
|
|
502
|
-
load,
|
|
907
|
+
load: checkedLoad,
|
|
503
908
|
documentIds: documents.map((meta) => meta.id),
|
|
504
|
-
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, meta.name])),
|
|
909
|
+
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
|
|
505
910
|
budget,
|
|
506
|
-
...(
|
|
911
|
+
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal } : {}),
|
|
507
912
|
// `analyze_whole_document` is declared only when it can read at least one of the documents.
|
|
508
913
|
wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
|
|
509
914
|
...rest,
|