llm-large-files 0.4.1 → 0.7.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 +1400 -338
- package/README.md +217 -49
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +117 -0
- package/dist/anthropic/adapter.d.ts.map +1 -0
- package/dist/anthropic/adapter.js +542 -0
- package/dist/anthropic/adapter.js.map +1 -0
- package/dist/anthropic/index.d.ts +3 -0
- package/dist/anthropic/index.d.ts.map +1 -0
- package/dist/anthropic/index.js +2 -0
- package/dist/anthropic/index.js.map +1 -0
- package/dist/ask.d.ts +200 -0
- package/dist/ask.d.ts.map +1 -0
- package/dist/ask.js +1402 -0
- package/dist/ask.js.map +1 -0
- package/dist/budget.d.ts +23 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +64 -0
- package/dist/budget.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 +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +42 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +138 -0
- package/dist/evidence.js.map +1 -0
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +59 -0
- package/dist/gemini/adapter.d.ts.map +1 -0
- package/dist/gemini/adapter.js +226 -0
- package/dist/gemini/adapter.js.map +1 -0
- package/dist/gemini/chat.d.ts +53 -77
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +42 -300
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +16 -0
- package/dist/gemini/errors.d.ts.map +1 -0
- package/dist/gemini/errors.js +46 -0
- package/dist/gemini/errors.js.map +1 -0
- package/dist/gemini/generate.d.ts +18 -21
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +49 -92
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +6 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +4 -3
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -2
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -38
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +136 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +401 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +96 -8
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +414 -96
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +37 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +255 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +278 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +222 -0
- package/dist/model.js.map +1 -0
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- 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/openai/adapter.d.ts +109 -0
- package/dist/openai/adapter.d.ts.map +1 -0
- package/dist/openai/adapter.js +567 -0
- package/dist/openai/adapter.js.map +1 -0
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +2 -0
- package/dist/openai/index.js.map +1 -0
- package/dist/output-limit.d.ts +42 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +121 -0
- package/dist/output-limit.js.map +1 -0
- 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 +275 -14
- 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/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/retry.d.ts +76 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +141 -0
- package/dist/retry.js.map +1 -0
- package/dist/search.d.ts +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +36 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +153 -0
- package/dist/sse.js.map +1 -0
- 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 +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +72 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +341 -60
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +128 -4
- package/dist/types.d.ts.map +1 -1
- 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 +58 -184
- package/docs/configuration.md +34 -490
- package/docs/getting-started.md +412 -177
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -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 +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1022 -138
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +902 -90
- package/docs/troubleshooting.md +1390 -0
- package/package.json +22 -4
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +611 -0
- package/src/anthropic/index.ts +2 -0
- package/src/ask.ts +1560 -0
- package/src/budget.ts +71 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +165 -0
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +271 -0
- package/src/gemini/chat.ts +87 -355
- package/src/gemini/errors.ts +48 -0
- package/src/gemini/generate.ts +67 -94
- package/src/gemini/index.ts +6 -4
- package/src/gemini/sse.ts +1 -34
- package/src/http.ts +434 -0
- package/src/index.ts +55 -4
- package/src/library.ts +497 -97
- package/src/map-reduce.ts +266 -59
- package/src/model.ts +433 -0
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +613 -0
- package/src/openai/index.ts +2 -0
- package/src/output-limit.ts +135 -0
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +176 -0
- package/src/search.ts +63 -10
- package/src/sse.ts +159 -0
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +338 -62
- package/src/types.ts +129 -5
- package/src/zip-directory.ts +136 -0
package/src/library.ts
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import {
|
|
2
|
+
import { buildLogProfileInSlices, buildOutlineInSlices, looksLikeLog } from "./analyze.js";
|
|
3
|
+
import { givenBudget, resolveBudget, type ModelLimits } from "./budget.js";
|
|
3
4
|
import { DocumentCache, documentVersion, type Sized } from "./cache.js";
|
|
4
|
-
import { DocumentStoreError } from "./errors.js";
|
|
5
|
+
import { DocumentStoreError, noteStoreWriteFailure } from "./errors.js";
|
|
6
|
+
import { EventEmitter, eventErrorOf, newRunId, type IngestEvent, type IngestStage } from "./events.js";
|
|
5
7
|
import { detectFormat, extractText } from "./extract.js";
|
|
6
8
|
import { Limiter } from "./limiter.js";
|
|
7
|
-
import {
|
|
9
|
+
import { TimeSlicer } from "./pause.js";
|
|
10
|
+
import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline, type WholeRead } from "./plan.js";
|
|
8
11
|
import { openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
|
|
9
12
|
import { numberLines, SearchableDocument, type DocumentSource } from "./search.js";
|
|
10
13
|
import { DOCUMENT_ID_PATTERN } from "./stores.js";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
14
|
+
import { buildTextIndexInSlices, canSerialize, serializeTextIndex } from "./text-index.js";
|
|
15
|
+
import { measureText, prepareText, removeInvisible, sliceWhole, wellFormed } from "./text.js";
|
|
16
|
+
import type { RetryOptions } from "./retry.js";
|
|
13
17
|
import { createDocumentTools } from "./tools.js";
|
|
14
18
|
import type {
|
|
15
19
|
Budget,
|
|
@@ -17,6 +21,8 @@ import type {
|
|
|
17
21
|
DocumentMeta,
|
|
18
22
|
DocumentStore,
|
|
19
23
|
DocumentSummary,
|
|
24
|
+
ExtractedText,
|
|
25
|
+
ExtractProgress,
|
|
20
26
|
Extractor,
|
|
21
27
|
GenerateText,
|
|
22
28
|
PreparedContext,
|
|
@@ -24,21 +30,16 @@ import type {
|
|
|
24
30
|
ToolSet,
|
|
25
31
|
} from "./types.js";
|
|
26
32
|
|
|
27
|
-
|
|
28
|
-
export const DEFAULT_BUDGET: Budget = {
|
|
29
|
-
contextTokens: 1_000_000,
|
|
30
|
-
maxRequestBytes: 10_000_000,
|
|
31
|
-
inlineTokens: 200_000,
|
|
32
|
-
reservedTokens: 64_000,
|
|
33
|
-
mapChunkTokens: 100_000,
|
|
34
|
-
maxMapChunks: 30,
|
|
35
|
-
toolResultCharacters: 24_000,
|
|
36
|
-
};
|
|
33
|
+
export { DEFAULT_BUDGET } from "./budget.js";
|
|
37
34
|
|
|
38
35
|
export type LargeFilesOptions = {
|
|
39
36
|
/** Where extracted text is kept: `new FileDocumentStore(dir)`, `new MemoryDocumentStore()`, or your own. */
|
|
40
37
|
store: DocumentStore;
|
|
41
|
-
/**
|
|
38
|
+
/**
|
|
39
|
+
* Your model's limits. What is left out follows `contextTokens` (see `resolveBudget`), which is
|
|
40
|
+
* 1M tokens unless you set it: for a model with a smaller window, setting that one number is
|
|
41
|
+
* enough. Values that cannot work together are an error.
|
|
42
|
+
*/
|
|
42
43
|
budget?: Partial<Budget>;
|
|
43
44
|
/**
|
|
44
45
|
* How long uploaded documents are kept. Defaults to 72 hours. `Infinity` keeps them until they
|
|
@@ -47,6 +48,25 @@ export type LargeFilesOptions = {
|
|
|
47
48
|
ttlMs?: number;
|
|
48
49
|
/** Largest accepted upload. Defaults to 100 MB. */
|
|
49
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;
|
|
50
70
|
/** Override or add text extractors per format. */
|
|
51
71
|
extractors?: Partial<Record<DocumentFormat, Extractor>>;
|
|
52
72
|
/**
|
|
@@ -98,20 +118,48 @@ export type IngestInput = {
|
|
|
98
118
|
name: string;
|
|
99
119
|
mimeType?: string;
|
|
100
120
|
bytes: Uint8Array;
|
|
101
|
-
/**
|
|
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
|
+
*/
|
|
102
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;
|
|
103
139
|
};
|
|
104
140
|
|
|
105
141
|
/** Access options. When a document has an owner, only that owner can use it. */
|
|
106
142
|
export type AccessOptions = { owner?: string };
|
|
107
143
|
|
|
108
144
|
export type PrepareOptions = AccessOptions & {
|
|
145
|
+
/**
|
|
146
|
+
* The budget of this request, when it is not the library's own: the fields to change, as in
|
|
147
|
+
* `LargeFilesOptions.budget`. `askWithFiles` passes the budget that fits the model it was given.
|
|
148
|
+
*/
|
|
149
|
+
budget?: Partial<Budget>;
|
|
109
150
|
/**
|
|
110
151
|
* Say that your tool loop can pass files to the model (see `ToolOptions.viewPages`). The result
|
|
111
152
|
* then lists the PDFs whose pages can be shown in `viewable`, and the instruction and the cards
|
|
112
153
|
* tell the model about `view_pages`. Without it, the result is that of 0.2.0.
|
|
113
154
|
*/
|
|
114
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;
|
|
115
163
|
};
|
|
116
164
|
|
|
117
165
|
export type ToolOptions = {
|
|
@@ -127,6 +175,16 @@ export type ToolOptions = {
|
|
|
127
175
|
* cannot get past.
|
|
128
176
|
*/
|
|
129
177
|
regexBudgetMs?: number;
|
|
178
|
+
/**
|
|
179
|
+
* How many times each document may be read whole (`analyze_whole_document`) by this tool set.
|
|
180
|
+
* A call past it answers with an error that tells the model to use what it has. Defaults to 1:
|
|
181
|
+
* make one tool set for each question, as `askWithFiles` does.
|
|
182
|
+
*/
|
|
183
|
+
maxWholeDocumentReads?: number;
|
|
184
|
+
/** How a model request of a whole-document read that failed is sent again. Defaults to three more tries, with a wait that doubles. */
|
|
185
|
+
retry?: RetryOptions;
|
|
186
|
+
/** The budget of these tools, when it is not the library's own: the fields to change. Use the one you planned the request with. */
|
|
187
|
+
budget?: Partial<Budget>;
|
|
130
188
|
/**
|
|
131
189
|
* Offers `view_pages`, which hands the model real pages of a PDF whose original file is kept
|
|
132
190
|
* (see `keepOriginals`). The pages come back as a file, so turn this on only when your loop
|
|
@@ -140,8 +198,18 @@ export type ToolOptions = {
|
|
|
140
198
|
export interface LargeFiles {
|
|
141
199
|
/** The effective budget (defaults merged with your overrides). */
|
|
142
200
|
readonly budget: Budget;
|
|
201
|
+
/**
|
|
202
|
+
* The budget for one request: the library's, with `overrides` in place of its fields, made to
|
|
203
|
+
* fit `limits` (a model's context window and request size, when they are smaller). Fields that
|
|
204
|
+
* neither the library nor `overrides` set follow the context window that results.
|
|
205
|
+
*/
|
|
206
|
+
budgetFor(overrides?: Partial<Budget>, limits?: ModelLimits): Budget;
|
|
143
207
|
readonly maxUploadBytes: number;
|
|
144
|
-
/**
|
|
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
|
+
*/
|
|
145
213
|
ingest(input: IngestInput): Promise<DocumentMeta>;
|
|
146
214
|
getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
|
|
147
215
|
/** The uploaded file itself, when it was kept (see `keepOriginals`). Treat the bytes as read-only. */
|
|
@@ -173,23 +241,75 @@ export function toDocumentSummary(meta: DocumentMeta): DocumentSummary {
|
|
|
173
241
|
lines: meta.lines,
|
|
174
242
|
estimatedTokens: meta.estimatedTokens,
|
|
175
243
|
...(meta.pages ? { pages: meta.pages } : {}),
|
|
244
|
+
...(meta.encoding ? { encoding: meta.encoding } : {}),
|
|
245
|
+
...(meta.replacedCharacters ? { replacedCharacters: meta.replacedCharacters } : {}),
|
|
176
246
|
expiresAt: meta.expiresAt,
|
|
177
247
|
};
|
|
178
248
|
}
|
|
179
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
|
+
|
|
180
253
|
/**
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
|
|
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
|
+
|
|
278
|
+
/**
|
|
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.
|
|
184
285
|
*/
|
|
185
286
|
export function cleanFileName(raw: string): string {
|
|
186
287
|
const base = raw.split(/[\\/]/).at(-1) ?? "";
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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.");
|
|
193
313
|
}
|
|
194
314
|
|
|
195
315
|
/**
|
|
@@ -216,13 +336,160 @@ function allowed(meta: DocumentMeta, access: AccessOptions | undefined): boolean
|
|
|
216
336
|
|
|
217
337
|
/** Default for `cacheBytes`. */
|
|
218
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
|
+
|
|
219
477
|
/** Default for `wholeDocumentBytes`. */
|
|
220
478
|
export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
|
221
479
|
|
|
222
480
|
export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
223
|
-
|
|
481
|
+
/** The fields the application set. The others follow the context window, whichever it is for a request. */
|
|
482
|
+
const ownBudget = givenBudget(options.budget);
|
|
483
|
+
const budget: Budget = resolveBudget(ownBudget);
|
|
484
|
+
const budgetFor = (overrides?: Partial<Budget>, limits?: ModelLimits): Budget => (
|
|
485
|
+
overrides || limits ? resolveBudget({ ...ownBudget, ...givenBudget(overrides) }, limits) : budget
|
|
486
|
+
);
|
|
224
487
|
const ttlMs = options.ttlMs ?? 72 * 60 * 60 * 1000;
|
|
225
488
|
const maxUploadBytes = options.maxUploadBytes ?? 100 * 1024 * 1024;
|
|
489
|
+
const given = (value: number | undefined, fallback: number) => (typeof value === "number" && !Number.isNaN(value) ? value : fallback);
|
|
490
|
+
const maxTextBytes = Math.max(1, given(options.maxTextBytes, Math.max(maxUploadBytes, DEFAULT_MAX_TEXT_BYTES)));
|
|
491
|
+
const maxPdfPages = Math.max(1, Math.trunc(given(options.maxPdfPages, DEFAULT_MAX_PDF_PAGES)));
|
|
492
|
+
const ingestTimeoutMs = given(options.ingestTimeoutMs, DEFAULT_INGEST_TIMEOUT_MS);
|
|
226
493
|
const now = options.now ?? (() => new Date());
|
|
227
494
|
const { store } = options;
|
|
228
495
|
const cacheBytes = Math.max(0, options.cacheBytes ?? DEFAULT_CACHE_BYTES);
|
|
@@ -280,7 +547,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
280
547
|
forget(id);
|
|
281
548
|
return undefined;
|
|
282
549
|
}
|
|
283
|
-
return meta;
|
|
550
|
+
return wholeName(meta);
|
|
284
551
|
}
|
|
285
552
|
|
|
286
553
|
/**
|
|
@@ -312,21 +579,23 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
312
579
|
return openRangedDocument(ranged, meta, scan, { ignoreSavedIndex: rebuild });
|
|
313
580
|
}
|
|
314
581
|
const stored = await reading(() => store.get(id));
|
|
315
|
-
|
|
582
|
+
if (!stored) return undefined;
|
|
583
|
+
const named = wholeName(stored.meta);
|
|
584
|
+
return new SearchableDocument(named === stored.meta ? stored : { ...stored, meta: named });
|
|
316
585
|
}
|
|
317
586
|
|
|
318
587
|
/**
|
|
319
588
|
* What a document contributes to the prompt: its text, or its card. Undefined when it is gone
|
|
320
589
|
* by now. A copy found to disagree with the store is opened again once.
|
|
321
590
|
*/
|
|
322
|
-
async function block(id: string, meta: DocumentMeta, whole: boolean, viewable: boolean,
|
|
591
|
+
async function block(id: string, meta: DocumentMeta, whole: boolean, viewable: boolean, wholeRead: WholeRead): Promise<string | undefined> {
|
|
323
592
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
324
593
|
const document = await load(id, attempt === 0 ? meta : undefined);
|
|
325
594
|
if (!document) return undefined;
|
|
326
595
|
try {
|
|
327
596
|
return whole
|
|
328
597
|
? renderInline(document.meta, await document.readText())
|
|
329
|
-
: renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable,
|
|
598
|
+
: renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, wholeRead);
|
|
330
599
|
} catch (error) {
|
|
331
600
|
if (!document.broken) {
|
|
332
601
|
// Deleted between the look-up and the read: the same as missing.
|
|
@@ -343,74 +612,186 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
343
612
|
return meta && allowed(meta, access) ? meta : undefined;
|
|
344
613
|
}
|
|
345
614
|
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
615
|
+
/**
|
|
616
|
+
* The work of `ingest`, once the file is named: `detected` is the format its name and type say.
|
|
617
|
+
* `progress` is given when someone listens to the events of the ingest. `storeFailed` is called
|
|
618
|
+
* when the store fails to write the document, whatever it throws.
|
|
619
|
+
*/
|
|
620
|
+
async function ingestFile(
|
|
621
|
+
input: IngestInput,
|
|
622
|
+
name: string,
|
|
623
|
+
mimeType: string,
|
|
624
|
+
detected: DocumentFormat,
|
|
625
|
+
progress: IngestProgress | undefined,
|
|
626
|
+
storeFailed: () => void,
|
|
627
|
+
): Promise<DocumentMeta> {
|
|
628
|
+
if (input.bytes.byteLength === 0) throw new Error(`${name} is empty.`);
|
|
629
|
+
if (input.bytes.byteLength > maxUploadBytes) {
|
|
630
|
+
throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
|
|
631
|
+
}
|
|
632
|
+
let format = detected;
|
|
633
|
+
const { signal, dispose } = ingestSignal(name, input.signal, ingestTimeoutMs);
|
|
634
|
+
// Each long step works in slices, with pauses for other requests: one large upload no longer
|
|
635
|
+
// holds the whole server while it is read.
|
|
636
|
+
const slicer = new TimeSlicer(signal);
|
|
637
|
+
let pages: number | undefined;
|
|
638
|
+
let reading: ReturnType<typeof readingOf>;
|
|
639
|
+
let text: string;
|
|
640
|
+
let wrapped: number;
|
|
641
|
+
let lines: string[];
|
|
642
|
+
let measured: Awaited<ReturnType<typeof measureText>>;
|
|
643
|
+
let outline: DocumentMeta["outline"];
|
|
644
|
+
let logProfile: DocumentMeta["logProfile"];
|
|
645
|
+
let index: Awaited<ReturnType<typeof buildTextIndexInSlices>> | undefined;
|
|
646
|
+
try {
|
|
647
|
+
signal.throwIfAborted();
|
|
648
|
+
// In a function of its own, so that the text as extracted is let go once it is prepared:
|
|
649
|
+
// the steps after it hold only the prepared text.
|
|
650
|
+
const read = async () => {
|
|
651
|
+
// What an extractor of your own reports once it has settled (from a timer, a worker) is
|
|
652
|
+
// not reported: the stages after it have begun.
|
|
653
|
+
let extracting = true;
|
|
654
|
+
let extracted: ExtractedText;
|
|
655
|
+
try {
|
|
656
|
+
extracted = await untilAborted(extractText(input.bytes, {
|
|
657
|
+
name,
|
|
658
|
+
mimeType,
|
|
659
|
+
format,
|
|
660
|
+
// A scan is worth storing only if its pages can be shown later: that needs the file itself.
|
|
661
|
+
...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
|
|
662
|
+
signal,
|
|
663
|
+
maxTextBytes,
|
|
664
|
+
maxPages: maxPdfPages,
|
|
665
|
+
...(progress ? { onProgress: (report: ExtractProgress) => { if (extracting) progress.extracted(report); } } : {}),
|
|
666
|
+
}, options.extractors), signal);
|
|
667
|
+
} finally {
|
|
668
|
+
extracting = false;
|
|
669
|
+
}
|
|
670
|
+
progress?.end();
|
|
671
|
+
// A character is at least one byte: a text this long is too large whatever it holds.
|
|
672
|
+
if (extracted.text.length > maxTextBytes) throw tooMuchText(name, maxTextBytes);
|
|
673
|
+
await slicer.pauseNow();
|
|
674
|
+
return { pages: extracted.pages, reading: readingOf(extracted), ...await prepareText(extracted.text, slicer, progress && ((done, total) => progress.report("prepare", done, total, "characters"))) };
|
|
675
|
+
};
|
|
676
|
+
({ pages, reading, text, wrapped, lines } = await read());
|
|
677
|
+
progress?.end();
|
|
366
678
|
if (!text.trim()) throw new Error(`${name} did not contain any text.`);
|
|
367
|
-
const lines = text.split("\n");
|
|
368
|
-
if (text.endsWith("\n")) lines.pop();
|
|
369
679
|
if (format === "text" && looksLikeLog(lines)) format = "log";
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
const meta: DocumentMeta = {
|
|
375
|
-
id: `doc_${randomUUID().replaceAll("-", "")}`,
|
|
376
|
-
...(input.owner !== undefined ? { owner: input.owner } : {}),
|
|
377
|
-
name,
|
|
378
|
-
mimeType,
|
|
379
|
-
format,
|
|
380
|
-
bytes: input.bytes.byteLength,
|
|
381
|
-
textBytes: sizes.utf8,
|
|
382
|
-
jsonBytes: sizes.json,
|
|
383
|
-
characters: text.length,
|
|
384
|
-
lines: lines.length,
|
|
385
|
-
estimatedTokens: estimateTokens(text),
|
|
386
|
-
wrappedLines: wrapped,
|
|
387
|
-
...(extracted.pages ? { pages: extracted.pages } : {}),
|
|
388
|
-
...(keepOriginal ? { originalKept: true } : {}),
|
|
389
|
-
outline: buildOutline(lines, format),
|
|
390
|
-
...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
|
|
391
|
-
createdAt: created.toISOString(),
|
|
392
|
-
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
393
|
-
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
394
|
-
};
|
|
680
|
+
measured = await measureText(text, slicer);
|
|
681
|
+
if (measured.utf8 > maxTextBytes) throw tooMuchText(name, maxTextBytes);
|
|
682
|
+
outline = await buildOutlineInSlices(lines, format, slicer);
|
|
683
|
+
logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
|
|
395
684
|
// The line index, so that the text can be read by range: a few bytes a line, built from the
|
|
396
685
|
// UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
|
|
397
686
|
// then loads whole, so that switching to reading by range finds it ready.
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
? serializeTextIndex(index)
|
|
687
|
+
index = typeof store.putIndex === "function"
|
|
688
|
+
? await buildTextIndexInSlices(text, slicer, progress && ((done, total) => progress.report("index", done, total, "characters")))
|
|
401
689
|
: undefined;
|
|
690
|
+
progress?.end();
|
|
691
|
+
signal.throwIfAborted();
|
|
692
|
+
} finally {
|
|
693
|
+
dispose();
|
|
694
|
+
}
|
|
695
|
+
const created = now();
|
|
696
|
+
const expires = created.getTime() + ttlMs;
|
|
697
|
+
const keepOriginal = keeps(format);
|
|
698
|
+
const meta: DocumentMeta = {
|
|
699
|
+
id: `doc_${randomUUID().replaceAll("-", "")}`,
|
|
700
|
+
...(input.owner !== undefined ? { owner: input.owner } : {}),
|
|
701
|
+
name,
|
|
702
|
+
mimeType,
|
|
703
|
+
format,
|
|
704
|
+
bytes: input.bytes.byteLength,
|
|
705
|
+
textBytes: measured.utf8,
|
|
706
|
+
jsonBytes: measured.json,
|
|
707
|
+
characters: text.length,
|
|
708
|
+
lines: lines.length,
|
|
709
|
+
estimatedTokens: measured.tokens,
|
|
710
|
+
wrappedLines: wrapped,
|
|
711
|
+
...(pages ? { pages } : {}),
|
|
712
|
+
...reading,
|
|
713
|
+
...(keepOriginal ? { originalKept: true } : {}),
|
|
714
|
+
outline,
|
|
715
|
+
...(logProfile ? { logProfile } : {}),
|
|
716
|
+
createdAt: created.toISOString(),
|
|
717
|
+
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
718
|
+
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
719
|
+
};
|
|
720
|
+
const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters
|
|
721
|
+
? serializeTextIndex(index)
|
|
722
|
+
: undefined;
|
|
723
|
+
// Each write is reported once done. What the listener of the events throws is not the store's failure.
|
|
724
|
+
const writes = (keepOriginal ? 1 : 0) + (savedIndex ? 1 : 0) + 1;
|
|
725
|
+
let written = 0;
|
|
726
|
+
let listenerFailed: { error: unknown } | undefined;
|
|
727
|
+
const wrote = (last: boolean) => {
|
|
728
|
+
if (!progress) return;
|
|
402
729
|
try {
|
|
403
|
-
|
|
404
|
-
if (
|
|
405
|
-
if (savedIndex) await store.putIndex!(meta.id, savedIndex);
|
|
406
|
-
await store.put({ meta, text });
|
|
730
|
+
progress.report("store", ++written, writes, "parts");
|
|
731
|
+
if (last) progress.end();
|
|
407
732
|
} catch (error) {
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
733
|
+
listenerFailed = { error };
|
|
734
|
+
throw error;
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
try {
|
|
738
|
+
// The files first, the document last: a document is there once its metadata is.
|
|
739
|
+
if (keepOriginal) {
|
|
740
|
+
await store.putOriginal!(meta.id, input.bytes);
|
|
741
|
+
wrote(false);
|
|
742
|
+
}
|
|
743
|
+
if (savedIndex) {
|
|
744
|
+
await store.putIndex!(meta.id, savedIndex);
|
|
745
|
+
wrote(false);
|
|
746
|
+
}
|
|
747
|
+
await store.put({ meta, text });
|
|
748
|
+
wrote(true);
|
|
749
|
+
} catch (error) {
|
|
750
|
+
// Do not leave a file of up to the upload limit, or a part of one, behind for a document
|
|
751
|
+
// that does not exist.
|
|
752
|
+
await store.delete(meta.id).catch(() => undefined);
|
|
753
|
+
if (listenerFailed?.error !== error) {
|
|
754
|
+
noteStoreWriteFailure(error);
|
|
755
|
+
storeFailed();
|
|
756
|
+
}
|
|
757
|
+
throw error;
|
|
758
|
+
}
|
|
759
|
+
return meta;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
return {
|
|
763
|
+
budget,
|
|
764
|
+
budgetFor,
|
|
765
|
+
maxUploadBytes,
|
|
766
|
+
|
|
767
|
+
async ingest(input) {
|
|
768
|
+
// The events first, so that every ingest that throws, even on what it was given, ends with ingest.error.
|
|
769
|
+
const events = new EventEmitter<IngestEvent>(input?.runId ?? newRunId("ing"), input?.onEvent);
|
|
770
|
+
let storeFailed = false;
|
|
771
|
+
try {
|
|
772
|
+
if (events.active) events.emit({ type: "ingest.start", ...startOf(input) });
|
|
773
|
+
checkOwner(input.owner);
|
|
774
|
+
const name = cleanFileName(input.name);
|
|
775
|
+
const mimeType = input.mimeType?.trim() || "application/octet-stream";
|
|
776
|
+
const format = detectFormat(name, mimeType);
|
|
777
|
+
// Progress is worked out only for someone who listens.
|
|
778
|
+
const progress = events.active ? new IngestProgress(events) : undefined;
|
|
779
|
+
const meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true));
|
|
780
|
+
try {
|
|
781
|
+
events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
|
|
782
|
+
} catch (error) {
|
|
783
|
+
// The caller never gets the id: the document goes, as on a throw of the listener a moment earlier.
|
|
784
|
+
await store.delete(meta.id).catch(() => undefined);
|
|
785
|
+
forget(meta.id);
|
|
786
|
+
throw error;
|
|
787
|
+
}
|
|
788
|
+
return meta;
|
|
789
|
+
} catch (error) {
|
|
790
|
+
// A store's own error may name a host or a path, whatever it is: the event, which a browser
|
|
791
|
+
// may see, says only that the document could not be stored.
|
|
792
|
+
events.emit({ type: "ingest.error", error: storeFailed ? { message: STORE_WRITE_FAILED } : eventErrorOf(error) });
|
|
411
793
|
throw error;
|
|
412
794
|
}
|
|
413
|
-
return meta;
|
|
414
795
|
},
|
|
415
796
|
|
|
416
797
|
getMeta: metaFor,
|
|
@@ -431,6 +812,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
431
812
|
},
|
|
432
813
|
|
|
433
814
|
async prepare(ids, base, access) {
|
|
815
|
+
const budget = budgetFor(access?.budget);
|
|
816
|
+
const analysis = access?.wholeDocumentAnalysis !== false;
|
|
434
817
|
const unique = [...new Set(ids)];
|
|
435
818
|
let documents: DocumentMeta[] = [];
|
|
436
819
|
const missing: string[] = [];
|
|
@@ -454,13 +837,15 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
454
837
|
const blocks = new Map<string, string>();
|
|
455
838
|
const gone: string[] = [];
|
|
456
839
|
for (const meta of documents) {
|
|
457
|
-
const
|
|
840
|
+
const wholeRead = !analysis ? "not_offered" : canBeReadWhole(meta, budget) ? "offered" : "too_large";
|
|
841
|
+
const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id), wholeRead);
|
|
458
842
|
if (text === undefined) gone.push(meta.id);
|
|
459
843
|
else blocks.set(meta.id, text);
|
|
460
844
|
}
|
|
461
845
|
if (gone.length === 0) {
|
|
462
|
-
// A whole-document read is named only when one of the files is
|
|
463
|
-
|
|
846
|
+
// A whole-document read is named only when the tools have it, and one of the files is
|
|
847
|
+
// small enough for it.
|
|
848
|
+
const wholeReads = analysis && plan.searchable.some((meta) => canBeReadWhole(meta, budget));
|
|
464
849
|
return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable, wholeReads), missing, viewable };
|
|
465
850
|
}
|
|
466
851
|
missing.push(...gone);
|
|
@@ -469,15 +854,30 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
469
854
|
},
|
|
470
855
|
|
|
471
856
|
tools(documents, toolOptions = {}) {
|
|
472
|
-
const { viewPages, ...rest } = toolOptions;
|
|
857
|
+
const { viewPages, budget: overrides, ...rest } = toolOptions;
|
|
858
|
+
const budget = budgetFor(overrides);
|
|
473
859
|
const viewable = (loadOriginal ? (viewPages === true ? documents : viewPages || []) : [])
|
|
474
860
|
.filter((meta) => meta.format === "pdf" && meta.originalKept);
|
|
861
|
+
// The owner each document was handed in with. The store's owner is checked against it on
|
|
862
|
+
// every call, so metadata built from an ID alone cannot read another owner's document: such
|
|
863
|
+
// a document is answered as no longer available, as `getMeta` reports it missing.
|
|
864
|
+
const handedOwner = new Map<string, string | undefined>([...documents, ...viewable].map((meta) => [meta.id, meta.owner]));
|
|
865
|
+
const mayUse = (meta: DocumentMeta) => meta.owner === undefined || (handedOwner.has(meta.id) && meta.owner === handedOwner.get(meta.id));
|
|
866
|
+
// The metadata the store holds now, not that of a copy kept in memory.
|
|
867
|
+
const checkedLoad = async (id: string) => {
|
|
868
|
+
const meta = await currentMeta(id);
|
|
869
|
+
return meta && mayUse(meta) ? load(id, meta) : undefined;
|
|
870
|
+
};
|
|
871
|
+
const checkedOriginal = loadOriginal && (async (id: string) => {
|
|
872
|
+
const meta = await currentMeta(id);
|
|
873
|
+
return meta && mayUse(meta) ? loadOriginal(id) : undefined;
|
|
874
|
+
});
|
|
475
875
|
return createDocumentTools({
|
|
476
|
-
load,
|
|
876
|
+
load: checkedLoad,
|
|
477
877
|
documentIds: documents.map((meta) => meta.id),
|
|
478
|
-
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, meta.name])),
|
|
878
|
+
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
|
|
479
879
|
budget,
|
|
480
|
-
...(
|
|
880
|
+
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal } : {}),
|
|
481
881
|
// `analyze_whole_document` is declared only when it can read at least one of the documents.
|
|
482
882
|
wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
|
|
483
883
|
...rest,
|