llm-large-files 0.8.2 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +535 -0
- package/README.md +9 -10
- package/dist/access.d.ts +86 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +131 -0
- package/dist/access.js.map +1 -0
- package/dist/ask.d.ts +45 -1
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +181 -20
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +57 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +217 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +72 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +102 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +35 -9
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +14 -3
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +46 -35
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +19 -3
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +84 -12
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +18 -6
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +2 -0
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/index.d.ts +9 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +70 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +868 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +169 -34
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +324 -591
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.js +3 -3
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +43 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +63 -3
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +226 -14
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +423 -181
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +18 -3
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +102 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +365 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +4 -3
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +7 -6
- package/dist/node/sse.js.map +1 -1
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.js.map +1 -1
- package/dist/ranged.d.ts +15 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +42 -11
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- package/dist/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +120 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +582 -139
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +25 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +135 -13
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +116 -13
- package/dist/types.d.ts.map +1 -1
- package/docs/README.md +17 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +12 -8
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +16 -7
- package/docs/guides/deployment.md +284 -83
- package/docs/guides/errors-and-reliability.md +161 -23
- package/docs/guides/own-adapter-and-loop.md +27 -10
- package/docs/guides/pdfs.md +123 -29
- package/docs/guides/storage.md +633 -145
- package/docs/guides/testing.md +78 -129
- package/docs/guides/vertex-and-gemini.md +10 -7
- package/docs/guides/web-app.md +312 -78
- package/docs/how-it-works.md +35 -8
- package/docs/measurements.md +43 -8
- package/docs/publishing.md +112 -36
- package/docs/reference/ask.md +154 -13
- package/docs/reference/errors-and-retries.md +166 -14
- package/docs/reference/events.md +53 -20
- package/docs/reference/gemini.md +70 -21
- package/docs/reference/library.md +706 -165
- package/docs/reference/node.md +624 -110
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +15 -5
- package/docs/security.md +304 -67
- package/docs/troubleshooting.md +144 -65
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +12 -3
- package/src/access.ts +144 -0
- package/src/ask.ts +230 -19
- package/src/cache.ts +20 -5
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +255 -0
- package/src/errors.ts +129 -15
- package/src/events.ts +86 -21
- package/src/evidence.ts +14 -3
- package/src/extract.ts +50 -33
- package/src/gemini/adapter.ts +97 -11
- package/src/gemini/chat.ts +20 -6
- package/src/gemini/index.ts +1 -1
- package/src/index.ts +9 -6
- package/src/ingest.ts +927 -0
- package/src/library.ts +467 -601
- package/src/map-reduce.ts +3 -3
- package/src/model.ts +69 -5
- package/src/node/handlers.ts +630 -183
- package/src/node/index.ts +13 -2
- package/src/node/ingest-child.ts +23 -5
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +365 -0
- package/src/node/sse.ts +7 -6
- package/src/pdf-layout.ts +69 -11
- package/src/ranged.ts +34 -13
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/source.ts +178 -0
- package/src/stores.ts +635 -140
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +150 -14
- package/src/types.ts +106 -13
package/src/library.ts
CHANGED
|
@@ -1,29 +1,26 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { buildLogProfileInSlices, buildOutlineInSlices, looksLikeLog } from "./analyze.js";
|
|
1
|
+
import { callerOf, checkMetaVersion, documentContext, mayUse, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext, type AccessRules, type Caller } from "./access.js";
|
|
3
2
|
import { givenBudget, resolveBudget, type ModelLimits } from "./budget.js";
|
|
4
3
|
import { DocumentCache, documentVersion, type Sized } from "./cache.js";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { detectFormat, extractText } from "./extract.js";
|
|
4
|
+
import type { IngestEvent } from "./events.js";
|
|
5
|
+
import { ingestDocument, LONGEST_TIMER_MS, type IngestContext } from "./ingest.js";
|
|
8
6
|
import { Limiter } from "./limiter.js";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { measureQuality, type TextQuality } from "./quality.js";
|
|
12
|
-
import { DocumentGoneError, openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
|
|
7
|
+
import { canBeReadWhole, CARD_LINES, documentToolsInstruction, planDocuments, renderCard, renderInline, TABLE_FORMATS, type WholeRead } from "./plan.js";
|
|
8
|
+
import { DocumentGoneError, openRangedDocument, pieceKey, RangedDocument, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
|
|
13
9
|
import { numberLines, SearchableDocument, type DocumentSource } from "./search.js";
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
10
|
+
import { TimeSlicer } from "./pause.js";
|
|
11
|
+
import { checkScope } from "./scope.js";
|
|
12
|
+
import { isSha256, sha256InSlices } from "./source.js";
|
|
13
|
+
import { APP_DOCUMENT_ID_PATTERN } from "./stores.js";
|
|
14
|
+
import { wellFormed } from "./text.js";
|
|
17
15
|
import type { RetryOptions } from "./retry.js";
|
|
18
|
-
import { createDocumentTools } from "./tools.js";
|
|
16
|
+
import { createDocumentTools, type PageLookTurns } from "./tools.js";
|
|
19
17
|
import type {
|
|
20
18
|
Budget,
|
|
19
|
+
DocumentContext,
|
|
21
20
|
DocumentFormat,
|
|
22
21
|
DocumentMeta,
|
|
22
|
+
DocumentScope,
|
|
23
23
|
DocumentStore,
|
|
24
|
-
DocumentSummary,
|
|
25
|
-
ExtractedText,
|
|
26
|
-
ExtractProgress,
|
|
27
24
|
Extractor,
|
|
28
25
|
GenerateText,
|
|
29
26
|
PreparedContext,
|
|
@@ -32,6 +29,7 @@ import type {
|
|
|
32
29
|
} from "./types.js";
|
|
33
30
|
|
|
34
31
|
export { DEFAULT_BUDGET } from "./budget.js";
|
|
32
|
+
export { checkOwner, cleanFileName, cleanMimeType, NEVER_EXPIRES, toDocumentSummary } from "./ingest.js";
|
|
35
33
|
|
|
36
34
|
export type LargeFilesOptions = {
|
|
37
35
|
/** Where extracted text is kept: `new FileDocumentStore(dir)`, `new MemoryDocumentStore()`, or your own. */
|
|
@@ -71,11 +69,19 @@ export type LargeFilesOptions = {
|
|
|
71
69
|
/** Override or add text extractors per format. */
|
|
72
70
|
extractors?: Partial<Record<DocumentFormat, Extractor>>;
|
|
73
71
|
/**
|
|
74
|
-
* Formats whose uploaded file is kept
|
|
75
|
-
*
|
|
76
|
-
*
|
|
72
|
+
* Formats whose uploaded file is kept, for example `["pdf"]`, so that `view_pages` can show its
|
|
73
|
+
* pages: as a copy in the store, next to its text (`putOriginal`), or, for an ingest with
|
|
74
|
+
* `IngestInput.original`, where the application keeps it (`originals`). Empty by default: a kept
|
|
75
|
+
* file takes disk space, up to the upload limit, until the document expires. A store without
|
|
76
|
+
* `putOriginal` keeps no copies.
|
|
77
77
|
*/
|
|
78
78
|
keepOriginals?: DocumentFormat[];
|
|
79
|
+
/**
|
|
80
|
+
* Reads the uploaded files that the application keeps itself (`IngestInput.original`), in place
|
|
81
|
+
* of a copy in the store: `fileOriginals(root)`, of "llm-large-files/node", reads them from a
|
|
82
|
+
* folder. A file read back is checked against the size and SHA-256 it had at ingest. New in 0.9.0.
|
|
83
|
+
*/
|
|
84
|
+
originals?: OriginalsReader;
|
|
79
85
|
/**
|
|
80
86
|
* A PDF without any text (a scan) has nothing to search, and was always refused. When its
|
|
81
87
|
* original is kept, its pages can be shown to the model instead, so one of up to this many pages
|
|
@@ -118,10 +124,64 @@ export type LargeFilesOptions = {
|
|
|
118
124
|
* not finish sooner. `Infinity` for no limit (as before 0.8.2). Defaults to 2. New in 0.8.2.
|
|
119
125
|
*/
|
|
120
126
|
maxConcurrentIngests?: number;
|
|
127
|
+
/**
|
|
128
|
+
* How many looks at pages (`view_pages`) run at once in this library, over all its questions.
|
|
129
|
+
* The others wait their turn, in order, before the PDF is loaded. A look parses the whole PDF on
|
|
130
|
+
* the one thread the questions share: more at once do not finish sooner, they only hold more
|
|
131
|
+
* memory (six at once held 352 MB more than one). `Infinity` for no limit (as before 0.9.0).
|
|
132
|
+
* Defaults to 1. A look reads its PDF from the store within `ingestTimeoutMs` (2 minutes when
|
|
133
|
+
* that is 0): past it, the turn goes back and the model is told that the file could not be read
|
|
134
|
+
* in time. New in 0.9.0.
|
|
135
|
+
*/
|
|
136
|
+
maxConcurrentPageLooks?: number;
|
|
137
|
+
/**
|
|
138
|
+
* How long a look at pages waits for its turn, in milliseconds. Past it, the model is told that
|
|
139
|
+
* the server is busy and to answer from the text, and the question gets a "page_looks_busy"
|
|
140
|
+
* notice. `Infinity` waits without end; 0 does not wait. Defaults to 30,000. New in 0.9.0.
|
|
141
|
+
*/
|
|
142
|
+
pageLookWaitMs?: number;
|
|
143
|
+
/**
|
|
144
|
+
* Every call must name its owner: `ingest`, `getMeta`, `getOriginal`, `delete`, `prepare`,
|
|
145
|
+
* `askWithFiles` (and `askStream`, `askGemini`), and `tools`, which then needs `access`. A call
|
|
146
|
+
* without one throws a TypeError ("owner is required: requireOwner is on"), and a document stored
|
|
147
|
+
* without an owner reads as missing. For a server where every document belongs to a signed-in
|
|
148
|
+
* user: a call that forgot the owner fails, rather than sees every document without one.
|
|
149
|
+
* Defaults to false. New in 0.9.0.
|
|
150
|
+
*/
|
|
151
|
+
requireOwner?: boolean;
|
|
152
|
+
/**
|
|
153
|
+
* The same for scopes (`DocumentScope`): every call must name its scope, and a document stored
|
|
154
|
+
* without one reads as missing. `sweep` without a scope is still allowed: it is upkeep of the
|
|
155
|
+
* store, not a user's access. Defaults to false. New in 0.9.0.
|
|
156
|
+
*/
|
|
157
|
+
requireScope?: boolean;
|
|
121
158
|
/** Clock override, for tests. */
|
|
122
159
|
now?: () => Date;
|
|
123
160
|
};
|
|
124
161
|
|
|
162
|
+
/**
|
|
163
|
+
* Reads the uploaded files that the application keeps itself (`LargeFilesOptions.originals`). New
|
|
164
|
+
* in 0.9.0.
|
|
165
|
+
*/
|
|
166
|
+
export type OriginalsReader = {
|
|
167
|
+
/**
|
|
168
|
+
* The bytes of the file at `ref` (`IngestInput.original.ref`), or undefined when it is not
|
|
169
|
+
* there. `context` is that of the call (its scope and owner), with the document's `id`, and
|
|
170
|
+
* `bytes`, the size the file had at ingest: a reader may stop one byte past it, as a file of
|
|
171
|
+
* another size has changed. What it throws is passed on as a `DocumentStoreError` (operation
|
|
172
|
+
* "read"), with its error as `cause`, as a store's errors are.
|
|
173
|
+
*/
|
|
174
|
+
read(ref: string, context: OriginalReadContext): Promise<Uint8Array | undefined>;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
/** What `OriginalsReader.read` is told of the call. New in 0.9.0. */
|
|
178
|
+
export type OriginalReadContext = DocumentContext & {
|
|
179
|
+
/** The ID of the document whose file is read. */
|
|
180
|
+
readonly id: string;
|
|
181
|
+
/** The size of the file when it was ingested. */
|
|
182
|
+
readonly bytes: number;
|
|
183
|
+
};
|
|
184
|
+
|
|
125
185
|
export type IngestInput = {
|
|
126
186
|
name: string;
|
|
127
187
|
mimeType?: string;
|
|
@@ -144,10 +204,63 @@ export type IngestInput = {
|
|
|
144
204
|
onEvent?: (event: IngestEvent) => void;
|
|
145
205
|
/** The `runId` of those events. Defaults to one made for the ingest ("ing_…"). */
|
|
146
206
|
runId?: string;
|
|
207
|
+
/**
|
|
208
|
+
* The document's ID, chosen by the application, such as the ID of its upload: lowercase letters,
|
|
209
|
+
* digits, "_" and "-", up to 64 characters, starting with a letter or a digit
|
|
210
|
+
* (`APP_DOCUMENT_ID_PATTERN`). Another ID is a TypeError. The model sees it, so it must hold no
|
|
211
|
+
* personal data. Without it, an ID is made ("doc_" and 32 hex digits), as before. New in 0.9.0.
|
|
212
|
+
*/
|
|
213
|
+
id?: string;
|
|
214
|
+
/**
|
|
215
|
+
* What to do when a document with `id` is already stored, as the store sees it for this scope.
|
|
216
|
+
* "fail" (the default) throws an `IngestError` with code "exists" (status 409). "replace"
|
|
217
|
+
* deletes it, then stores the new one: only a document of the same owner and scope; another is
|
|
218
|
+
* "exists" too, even when its text is gone, unless it has expired. Over a store that keeps no
|
|
219
|
+
* scopes apart, the check spans every scope, so one chat cannot write over another's document.
|
|
220
|
+
* While an ingest of this library stores `id`, another ingest of it is "exists", whatever this
|
|
221
|
+
* says. New in 0.9.0.
|
|
222
|
+
*/
|
|
223
|
+
ifExists?: "fail" | "replace";
|
|
224
|
+
/**
|
|
225
|
+
* Where the document belongs, such as [userId, chatId] (`DocumentScope`). It is passed to every
|
|
226
|
+
* store call, and kept in `DocumentMeta.scope`: only a caller of the same scope may use the
|
|
227
|
+
* document. A scope that is not valid is a `DocumentScopeError`. New in 0.9.0.
|
|
228
|
+
*/
|
|
229
|
+
scope?: DocumentScope;
|
|
230
|
+
/**
|
|
231
|
+
* Where the application keeps the uploaded file: `ref`, up to 1,024 characters, such as a path
|
|
232
|
+
* under the folder of `fileOriginals`. When the format is kept (`keepOriginals`), the library
|
|
233
|
+
* reads the file from there (`LargeFilesOptions.originals`) instead of keeping a copy in the
|
|
234
|
+
* store, and records `DocumentMeta.original`: the ref, and the size and SHA-256 of the file, to
|
|
235
|
+
* tell when it has changed. The ref is never sent to the model, nor in a summary. An event holds
|
|
236
|
+
* it only with `AskOptions.eventResults: true`, in the full plan of `run.finish` and `run.error`.
|
|
237
|
+
* Without `LargeFilesOptions.originals`, it is a TypeError. The library never writes, moves or
|
|
238
|
+
* deletes the file: `delete` leaves it. New in 0.9.0.
|
|
239
|
+
*/
|
|
240
|
+
original?: { ref: string };
|
|
147
241
|
};
|
|
148
242
|
|
|
149
|
-
/**
|
|
150
|
-
export type
|
|
243
|
+
/** A file to ingest from where it is, rather than from bytes in memory (`IngestFromSource`). New in 0.9.0. */
|
|
244
|
+
export type IngestSource = { path: string };
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* An ingest of a file from a path: `IngestInput` with `source` in place of `bytes`. Before the
|
|
248
|
+
* ingest's turn, the path is looked at with `lstat`, and nothing of it is read: a link is refused,
|
|
249
|
+
* not followed, and so is anything that is not a file; an empty file, or one larger than
|
|
250
|
+
* `maxUploadBytes`, is refused at once. When its name and type say nothing of its format, only the
|
|
251
|
+
* parts of it that tell are read (its first KB; for a ZIP its first 64 KB and its last MB). At its
|
|
252
|
+
* turn the file is read once, up to `maxUploadBytes + 1` bytes, so that one that has grown is
|
|
253
|
+
* refused, and its bytes are let go once its text is read. An extractor that reads paths
|
|
254
|
+
* (`Extractor.readsPath`, as the isolated readers do) reads it instead, and the server does not.
|
|
255
|
+
* The library never writes, moves or deletes the file. New in 0.9.0.
|
|
256
|
+
*/
|
|
257
|
+
export type IngestFromSource = Omit<IngestInput, "bytes"> & { source: IngestSource; bytes?: never };
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Access options. When a document has an owner, only that owner can use it. `scope`, new in 0.9.0:
|
|
261
|
+
* the scope of the caller; a document stored with a scope serves only a caller with the same one.
|
|
262
|
+
*/
|
|
263
|
+
export type AccessOptions = { owner?: string; scope?: DocumentScope };
|
|
151
264
|
|
|
152
265
|
export type PrepareOptions = AccessOptions & {
|
|
153
266
|
/**
|
|
@@ -171,6 +284,14 @@ export type PrepareOptions = AccessOptions & {
|
|
|
171
284
|
};
|
|
172
285
|
|
|
173
286
|
export type ToolOptions = {
|
|
287
|
+
/**
|
|
288
|
+
* Who uses these tools. With it, every call of the tools asks the store for the document with
|
|
289
|
+
* this owner and scope, and checks the owner and scope the store holds against them: metadata
|
|
290
|
+
* made by hand, or handed in for another user, reads nothing. Without it, as before 0.9.0: each
|
|
291
|
+
* document is checked against the owner and scope it was handed in with. `askWithFiles` always
|
|
292
|
+
* passes it. Under `requireOwner` or `requireScope` it is required. New in 0.9.0.
|
|
293
|
+
*/
|
|
294
|
+
access?: AccessOptions;
|
|
174
295
|
/** Enables `analyze_whole_document`, which reads the entire file in parts. */
|
|
175
296
|
generate?: GenerateText;
|
|
176
297
|
/** Progress of whole-document reads, for status messages. */
|
|
@@ -214,17 +335,37 @@ export interface LargeFiles {
|
|
|
214
335
|
budgetFor(overrides?: Partial<Budget>, limits?: ModelLimits): Budget;
|
|
215
336
|
readonly maxUploadBytes: number;
|
|
216
337
|
/**
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
338
|
+
* What the library requires of every call (`requireOwner`, `requireScope`), for code that serves
|
|
339
|
+
* it, such as the upload handlers. Optional, so that a `LargeFiles` of your own still compiles.
|
|
340
|
+
* New in 0.9.0.
|
|
220
341
|
*/
|
|
221
|
-
|
|
342
|
+
readonly access?: { readonly requireOwner: boolean; readonly requireScope: boolean };
|
|
343
|
+
/**
|
|
344
|
+
* Extracts, normalizes, profiles, and stores a file: from its bytes (`IngestInput`), or from a
|
|
345
|
+
* path (`IngestFromSource`, new in 0.9.0). Throws a user-readable Error on bad input.
|
|
346
|
+
* A store that fails to write is a `DocumentStoreError` (operation "write", status 503) since
|
|
347
|
+
* 0.9.0, with the store's own error as `cause`: log that one, and do not show its message to a
|
|
348
|
+
* user, as it may name a path, a host or a bucket. A path that is not there, a link or a folder
|
|
349
|
+
* is an error with the `code` of a system error (ENOENT, ELOOP, EISDIR), passed on as it is.
|
|
350
|
+
*/
|
|
351
|
+
ingest(input: IngestInput | IngestFromSource): Promise<DocumentMeta>;
|
|
222
352
|
getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
|
|
223
|
-
/**
|
|
353
|
+
/**
|
|
354
|
+
* The uploaded file itself, when it was kept (see `keepOriginals`): from the store, or from where
|
|
355
|
+
* the application keeps it (`IngestInput.original`, read by `LargeFilesOptions.originals`). Treat
|
|
356
|
+
* the bytes as read-only. Undefined too when, once the bytes are read, the store no longer
|
|
357
|
+
* describes the same document, or the bytes are not those of the upload: of another size, or
|
|
358
|
+
* another SHA-256 (0.9.0).
|
|
359
|
+
*/
|
|
224
360
|
getOriginal(id: string, access?: AccessOptions): Promise<Uint8Array | undefined>;
|
|
361
|
+
/** Deletes a document. A store that fails is a `DocumentStoreError` (operation "delete") since 0.9.0. */
|
|
225
362
|
delete(id: string, access?: AccessOptions): Promise<boolean>;
|
|
226
|
-
/**
|
|
227
|
-
|
|
363
|
+
/**
|
|
364
|
+
* Removes expired documents from the store: those of `scope`, or of every scope without one.
|
|
365
|
+
* Returns how many were removed. A store that fails is a `DocumentStoreError` (operation
|
|
366
|
+
* "sweep") since 0.9.0.
|
|
367
|
+
*/
|
|
368
|
+
sweep(options?: { scope?: DocumentScope }): Promise<number>;
|
|
228
369
|
/**
|
|
229
370
|
* Plans one model request: which documents go in whole and which become searchable cards.
|
|
230
371
|
* `base` is the size of everything else in the request (messages, system prompt, other files).
|
|
@@ -234,70 +375,12 @@ export interface LargeFiles {
|
|
|
234
375
|
tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
|
|
235
376
|
}
|
|
236
377
|
|
|
237
|
-
export function isDocumentId(value: unknown): value is string {
|
|
238
|
-
return typeof value === "string" && DOCUMENT_ID_PATTERN.test(value);
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
/** The fields of a document that are safe to return to a browser. */
|
|
242
|
-
export function toDocumentSummary(meta: DocumentMeta): DocumentSummary {
|
|
243
|
-
return {
|
|
244
|
-
id: meta.id,
|
|
245
|
-
name: meta.name,
|
|
246
|
-
mimeType: meta.mimeType,
|
|
247
|
-
format: meta.format,
|
|
248
|
-
bytes: meta.bytes,
|
|
249
|
-
lines: meta.lines,
|
|
250
|
-
estimatedTokens: meta.estimatedTokens,
|
|
251
|
-
...(meta.pages ? { pages: meta.pages } : {}),
|
|
252
|
-
...(meta.encoding ? { encoding: meta.encoding } : {}),
|
|
253
|
-
...(meta.replacedCharacters ? { replacedCharacters: meta.replacedCharacters } : {}),
|
|
254
|
-
expiresAt: meta.expiresAt,
|
|
255
|
-
};
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
/** An encoding's name as TextDecoder gives it ("windows-1255"): an extractor of your own may name another. */
|
|
259
|
-
const ENCODING_NAME = /^[a-z0-9][a-z0-9._:-]{0,39}$/i;
|
|
260
|
-
|
|
261
|
-
/**
|
|
262
|
-
* Whether the name is an older encoding, as `DocumentMeta.encoding` records: not UTF-8 or UTF-16,
|
|
263
|
-
* under any of their names ("utf8", "unicode"). The model is told the file is not in UTF-8.
|
|
264
|
-
*/
|
|
265
|
-
function olderEncoding(name: unknown): name is string {
|
|
266
|
-
if (typeof name !== "string" || !ENCODING_NAME.test(name)) return false;
|
|
267
|
-
let known: string;
|
|
268
|
-
try {
|
|
269
|
-
known = new TextDecoder(name).encoding;
|
|
270
|
-
} catch {
|
|
271
|
-
// A name TextDecoder does not know: the extractor read the file itself.
|
|
272
|
-
return true;
|
|
273
|
-
}
|
|
274
|
-
return known !== "utf-8" && known !== "utf-16le" && known !== "utf-16be";
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
/** How the text of a file was read, as its extractor said, in the fields of `DocumentMeta`. */
|
|
278
|
-
function readingOf(extracted: ExtractedText): Pick<DocumentMeta, "encoding" | "replacedCharacters"> {
|
|
279
|
-
const { encoding, replacedCharacters } = extracted;
|
|
280
|
-
return {
|
|
281
|
-
...(olderEncoding(encoding) ? { encoding } : {}),
|
|
282
|
-
...(typeof replacedCharacters === "number" && Number.isSafeInteger(replacedCharacters) && replacedCharacters > 0 ? { replacedCharacters } : {}),
|
|
283
|
-
};
|
|
284
|
-
}
|
|
285
|
-
|
|
286
378
|
/**
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
* Names are shown to the model and in UIs, so a name must not be able to start a new line of the
|
|
290
|
-
* prompt, or disguise its extension. Most characters that show nothing are removed (tag characters,
|
|
291
|
-
* zero-width spaces); the variation selectors and joiners that scripts and emoji need are kept, and
|
|
292
|
-
* can still carry data a person does not see.
|
|
379
|
+
* Whether `value` has the shape of a document ID: one the library makes ("doc_" and 32 hex digits),
|
|
380
|
+
* or one an application may give (`APP_DOCUMENT_ID_PATTERN`, since 0.9.0), which the library's fit too.
|
|
293
381
|
*/
|
|
294
|
-
export function
|
|
295
|
-
|
|
296
|
-
// Control characters, line and paragraph separators, and text-direction controls become a space.
|
|
297
|
-
const spaced = base.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]+/gu, " ");
|
|
298
|
-
const name = removeInvisible(spaced).replace(/\s+/g, " ").trim();
|
|
299
|
-
// At most 255 characters, never half of an emoji. A flag cut short loses the tags left of it.
|
|
300
|
-
return (name.length > 255 ? removeInvisible(sliceWhole(name, 255)) : name) || "file";
|
|
382
|
+
export function isDocumentId(value: unknown): value is string {
|
|
383
|
+
return typeof value === "string" && APP_DOCUMENT_ID_PATTERN.test(value);
|
|
301
384
|
}
|
|
302
385
|
|
|
303
386
|
/**
|
|
@@ -310,43 +393,42 @@ function wholeName(meta: DocumentMeta): DocumentMeta {
|
|
|
310
393
|
return name === meta.name ? meta : { ...meta, name };
|
|
311
394
|
}
|
|
312
395
|
|
|
313
|
-
/**
|
|
314
|
-
* Refuses an owner that every caller without a user would share: an empty string (what
|
|
315
|
-
* `user?.id ?? ""` gives), one of spaces only, or null. Undefined is no owner. A number is let
|
|
316
|
-
* through, as before, for JavaScript code that passes numeric user IDs.
|
|
317
|
-
*/
|
|
318
|
-
export function checkOwner(owner: unknown): void {
|
|
319
|
-
if (owner === undefined || (typeof owner === "string" && owner.trim() !== "") || (typeof owner === "number" && Number.isFinite(owner))) return;
|
|
320
|
-
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.");
|
|
321
|
-
}
|
|
322
|
-
|
|
323
396
|
/**
|
|
324
397
|
* A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
|
|
325
398
|
* could not be read is not a document that is gone, and its own error names paths or hosts.
|
|
326
399
|
*/
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
return await read();
|
|
330
|
-
} catch (error) {
|
|
331
|
-
throw error instanceof DocumentStoreError ? error : new DocumentStoreError(error);
|
|
332
|
-
}
|
|
400
|
+
function reading<T>(read: () => Promise<T>): Promise<T> {
|
|
401
|
+
return storeCall("read", read);
|
|
333
402
|
}
|
|
334
403
|
|
|
404
|
+
/** The key a caller's copy of a document is kept under in memory: the key of its scope, then the ID. */
|
|
405
|
+
const documentKey = (caller: Caller, id: string) => `${caller.key}\u0000${id}`;
|
|
406
|
+
|
|
407
|
+
/** A caller with no owner and no scope. */
|
|
408
|
+
const NO_CALLER: Caller = Object.freeze({ context: storeContext(undefined, undefined), key: "" });
|
|
409
|
+
|
|
335
410
|
/**
|
|
336
|
-
*
|
|
337
|
-
*
|
|
411
|
+
* What `view_pages` answers for a file the application keeps (`IngestInput.original`) that is no
|
|
412
|
+
* longer the one that was ingested. New in 0.9.0.
|
|
338
413
|
*/
|
|
339
|
-
|
|
414
|
+
const changedOriginal = (file: string) => `${file} changed on the server since it was read. Attach it again to look at its pages.`;
|
|
340
415
|
|
|
341
|
-
|
|
342
|
-
|
|
416
|
+
/**
|
|
417
|
+
* Where the application keeps the uploaded file of a document (`DocumentMeta.original`), when its
|
|
418
|
+
* metadata says so in the shape the library writes. Undefined for one kept in the store, and for
|
|
419
|
+
* one written by hand in another shape, which reads as missing.
|
|
420
|
+
*/
|
|
421
|
+
function refOf(meta: DocumentMeta): { ref: string; bytes: number; sha256: string } | undefined {
|
|
422
|
+
const original: unknown = meta.original;
|
|
423
|
+
if (typeof original !== "object" || original === null) return undefined;
|
|
424
|
+
const { ref, bytes, sha256 } = original as { ref?: unknown; bytes?: unknown; sha256?: unknown };
|
|
425
|
+
return typeof ref === "string" && ref.length > 0 && typeof bytes === "number" && Number.isSafeInteger(bytes) && bytes >= 0 && isSha256(sha256)
|
|
426
|
+
? { ref, bytes, sha256 }
|
|
427
|
+
: undefined;
|
|
343
428
|
}
|
|
344
429
|
|
|
345
430
|
/** Default for `cacheBytes`. */
|
|
346
431
|
export const DEFAULT_CACHE_BYTES = 256 * 1024 * 1024;
|
|
347
|
-
/** The refusal of a file whose text is larger than `maxTextBytes`. */
|
|
348
|
-
const tooMuchText = (name: string, maxTextBytes: number) =>
|
|
349
|
-
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.`);
|
|
350
432
|
|
|
351
433
|
/** Default for `maxPdfPages`. */
|
|
352
434
|
export const DEFAULT_MAX_PDF_PAGES = 5_000;
|
|
@@ -354,186 +436,13 @@ export const DEFAULT_MAX_PDF_PAGES = 5_000;
|
|
|
354
436
|
export const DEFAULT_MAX_TEXT_BYTES = 100 * 1024 * 1024;
|
|
355
437
|
/** Default for `ingestTimeoutMs`: 2 minutes. */
|
|
356
438
|
export const DEFAULT_INGEST_TIMEOUT_MS = 120_000;
|
|
357
|
-
/** The longest a Node.js timer waits: a longer one fires at once. A limit past it is no limit. */
|
|
358
|
-
const LONGEST_TIMER_MS = 2 ** 31 - 1;
|
|
359
|
-
|
|
360
|
-
/** `value` copied through JSON: new strings, none of them a piece of a larger one. */
|
|
361
|
-
function jsonCopy<T>(value: T): T {
|
|
362
|
-
return JSON.parse(JSON.stringify(value)) as T;
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
/** `work`, or the error `late` makes once `ms` have passed without it settling. */
|
|
366
|
-
function settleWithin<T>(work: Promise<T>, ms: number, late: () => Error): Promise<T> {
|
|
367
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
368
|
-
const timeUp = new Promise<never>((_, reject) => {
|
|
369
|
-
timer = setTimeout(() => reject(late()), ms);
|
|
370
|
-
});
|
|
371
|
-
return Promise.race([work, timeUp]).finally(() => clearTimeout(timer));
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
/**
|
|
375
|
-
* The turn of one ingest (`maxConcurrentIngests`). It is given back when the ingest ends; when the
|
|
376
|
-
* ingest gave up on work that goes on (an extractor that does not stop on the signal, such as a
|
|
377
|
-
* PDF being parsed when its caller left), once that work ends, or `capMs` later when it does not.
|
|
378
|
-
* (Store writes that do not end fail the ingest after `capMs`: see `ingestFile`.)
|
|
379
|
-
*/
|
|
380
|
-
class IngestSlot {
|
|
381
|
-
private released = false;
|
|
382
|
-
private timer: ReturnType<typeof setTimeout> | undefined;
|
|
383
|
-
|
|
384
|
-
constructor(private readonly release: () => void, private readonly capMs: number) {}
|
|
385
|
-
|
|
386
|
-
private readonly free = () => {
|
|
387
|
-
if (this.released) return;
|
|
388
|
-
this.released = true;
|
|
389
|
-
clearTimeout(this.timer);
|
|
390
|
-
this.release();
|
|
391
|
-
};
|
|
392
|
-
|
|
393
|
-
/**
|
|
394
|
-
* Gives the turn back `capMs` from now at the latest. The timer keeps the process alive: work
|
|
395
|
-
* that never ends may hold nothing that does, and ingests waiting for the turn would be lost.
|
|
396
|
-
*/
|
|
397
|
-
limit(): void {
|
|
398
|
-
if (this.released || this.timer !== undefined) return;
|
|
399
|
-
this.timer = setTimeout(this.free, this.capMs);
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/** The ingest is over: the turn goes back now, or once `abandoned` ends (`capMs` at the latest). */
|
|
403
|
-
end(abandoned?: Promise<unknown>): void {
|
|
404
|
-
if (!abandoned) return this.free();
|
|
405
|
-
abandoned.then(this.free, this.free);
|
|
406
|
-
this.limit();
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
/** A time limit in the words of a message: "500 ms", "45 s", "2 min". */
|
|
411
|
-
function formatDuration(ms: number): string {
|
|
412
|
-
if (ms < 1_000) return `${Math.max(1, Math.round(ms))} ms`;
|
|
413
|
-
if (ms < 120_000) return `${Number((ms / 1_000).toFixed(1))} s`;
|
|
414
|
-
return `${Number((ms / 60_000).toFixed(1))} min`;
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
/**
|
|
418
|
-
* The signal one ingest runs under: aborted when the caller's is, or when `timeoutMs` has passed
|
|
419
|
-
* (with an error that says the file took too long). `dispose` stops the timer.
|
|
420
|
-
*/
|
|
421
|
-
function ingestSignal(name: string, caller: AbortSignal | undefined, timeoutMs: number): { signal: AbortSignal; dispose(): void } {
|
|
422
|
-
const controller = new AbortController();
|
|
423
|
-
const onAbort = () => controller.abort(caller!.reason);
|
|
424
|
-
if (caller?.aborted) controller.abort(caller.reason);
|
|
425
|
-
else caller?.addEventListener("abort", onAbort, { once: true });
|
|
426
|
-
const timer = timeoutMs > 0 && timeoutMs <= LONGEST_TIMER_MS
|
|
427
|
-
? 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)
|
|
428
|
-
: undefined;
|
|
429
|
-
return {
|
|
430
|
-
signal: controller.signal,
|
|
431
|
-
dispose() {
|
|
432
|
-
clearTimeout(timer);
|
|
433
|
-
caller?.removeEventListener("abort", onAbort);
|
|
434
|
-
},
|
|
435
|
-
};
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
/**
|
|
439
|
-
* `work`, or the signal's reason as soon as it is aborted: an extractor of your own that does not
|
|
440
|
-
* look at the signal is no longer waited for (though the work it does cannot be stopped).
|
|
441
|
-
*/
|
|
442
|
-
function untilAborted<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
443
|
-
if (signal.aborted) return Promise.reject(signal.reason);
|
|
444
|
-
return new Promise<T>((resolve, reject) => {
|
|
445
|
-
const onAbort = () => reject(signal.reason);
|
|
446
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
447
|
-
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
448
|
-
});
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
/** The message of `ingest.error` when the store failed to write the document. */
|
|
452
|
-
const STORE_WRITE_FAILED = "The document could not be stored. Try again later.";
|
|
453
|
-
|
|
454
|
-
/** The least time between two `ingest.progress` events of one stage, in milliseconds: a slice of `TimeSlicer`. */
|
|
455
|
-
const PROGRESS_MS = 12;
|
|
456
|
-
|
|
457
|
-
type ProgressUnit = Extract<IngestEvent, { type: "ingest.progress" }>["unit"];
|
|
458
|
-
const EXTRACT_STAGES = new Set<unknown>(["extract", "check", "pictures", "decode"]);
|
|
459
|
-
const EXTRACT_UNITS = new Set<unknown>(["pages", "parts", "bytes"]);
|
|
460
|
-
const isCount = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
461
|
-
|
|
462
|
-
/** What `ingest.start` says of an ingest, worked out from whatever it was given: the checks come after it. */
|
|
463
|
-
function startOf(input: IngestInput | undefined): { name: string; format: DocumentFormat; bytes: number } {
|
|
464
|
-
try {
|
|
465
|
-
const name = typeof input?.name === "string" ? cleanFileName(input.name) : "";
|
|
466
|
-
const mimeType = (typeof input?.mimeType === "string" ? input.mimeType.trim() : "") || "application/octet-stream";
|
|
467
|
-
const bytes = input?.bytes?.byteLength;
|
|
468
|
-
return { name, format: detectFormat(name, mimeType), bytes: isCount(bytes) ? bytes : 0 };
|
|
469
|
-
} catch {
|
|
470
|
-
return { name: "", format: "text", bytes: 0 };
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
type HeldProgress = { done: number; total: number | undefined; unit: ProgressUnit; sent: boolean };
|
|
475
|
-
|
|
476
|
-
/**
|
|
477
|
-
* Sends the `ingest.progress` events of one ingest: at most one every `PROGRESS_MS` for each stage,
|
|
478
|
-
* however the stages take turns, then the last progress of each stage when the stages end (`end`).
|
|
479
|
-
* A progress that completes its stage goes out at once, the first time, so that stages that run one
|
|
480
|
-
* after the other end in that order. Made only when someone listens.
|
|
481
|
-
*/
|
|
482
|
-
class IngestProgress {
|
|
483
|
-
/** Each stage that reported, in the order it first did: when it last sent, and its last progress. */
|
|
484
|
-
private readonly stages = new Map<IngestStage, { sentAt: number; completed: boolean; last: HeldProgress }>();
|
|
485
|
-
/** Set once a stage after the extractor's began: an extract stage is not reported again. */
|
|
486
|
-
private extractOver = false;
|
|
487
|
-
|
|
488
|
-
constructor(private readonly events: EventEmitter<IngestEvent>) {}
|
|
489
|
-
|
|
490
|
-
report(stage: IngestStage, done: number, total: number | undefined, unit: ProgressUnit): void {
|
|
491
|
-
if (!EXTRACT_STAGES.has(stage)) this.extractOver = true;
|
|
492
|
-
const last: HeldProgress = { done, total, unit, sent: false };
|
|
493
|
-
let state = this.stages.get(stage);
|
|
494
|
-
if (!state) {
|
|
495
|
-
state = { sentAt: Number.NEGATIVE_INFINITY, completed: false, last };
|
|
496
|
-
this.stages.set(stage, state);
|
|
497
|
-
}
|
|
498
|
-
state.last = last;
|
|
499
|
-
const now = performance.now();
|
|
500
|
-
const completes = !state.completed && total !== undefined && done >= total;
|
|
501
|
-
if (completes) state.completed = true;
|
|
502
|
-
if (completes || now - state.sentAt >= PROGRESS_MS) {
|
|
503
|
-
state.sentAt = now;
|
|
504
|
-
this.send(stage, last);
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
/** The progress an extractor reported (`ExtractInput.onProgress`). One of your own may send anything: what does not fit is left out. */
|
|
509
|
-
extracted(progress: ExtractProgress): void {
|
|
510
|
-
if (this.extractOver) return;
|
|
511
|
-
const stage = progress?.stage ?? "extract";
|
|
512
|
-
if (!EXTRACT_STAGES.has(stage) || !EXTRACT_UNITS.has(progress?.unit) || !isCount(progress?.done)) return;
|
|
513
|
-
this.report(stage, progress.done, isCount(progress.total) ? progress.total : undefined, progress.unit);
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
/** The stages so far are over: the last progress of each, when it was held back, goes out, in the order they began. */
|
|
517
|
-
end(): void {
|
|
518
|
-
const held = [...this.stages].filter(([, state]) => !state.last.sent);
|
|
519
|
-
this.stages.clear();
|
|
520
|
-
for (const [stage, state] of held) this.send(stage, state.last);
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
private send(stage: IngestStage, last: HeldProgress): void {
|
|
524
|
-
last.sent = true;
|
|
525
|
-
this.events.emit({
|
|
526
|
-
type: "ingest.progress",
|
|
527
|
-
stage,
|
|
528
|
-
done: last.done,
|
|
529
|
-
...(last.total !== undefined ? { total: last.total } : {}),
|
|
530
|
-
unit: last.unit,
|
|
531
|
-
});
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
439
|
|
|
535
440
|
/** Default for `wholeDocumentBytes`. */
|
|
536
441
|
export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
|
442
|
+
/** Looks at pages that run at once in a library, unless `maxConcurrentPageLooks` says otherwise. */
|
|
443
|
+
const DEFAULT_PAGE_LOOKS = 1;
|
|
444
|
+
/** How long a look at pages waits for its turn, unless `pageLookWaitMs` says otherwise. */
|
|
445
|
+
const DEFAULT_PAGE_LOOK_WAIT_MS = 30_000;
|
|
537
446
|
|
|
538
447
|
/**
|
|
539
448
|
* A number option as it was given, or `fallback` when it was left out. NaN, which
|
|
@@ -564,40 +473,65 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
564
473
|
const now = options.now ?? (() => new Date());
|
|
565
474
|
const { store } = options;
|
|
566
475
|
const cacheBytes = Math.max(0, numberOption("cacheBytes", options.cacheBytes, DEFAULT_CACHE_BYTES));
|
|
567
|
-
/**
|
|
476
|
+
/** What every call must name (`requireOwner`, `requireScope`). */
|
|
477
|
+
const rules: AccessRules = Object.freeze({ requireOwner: options.requireOwner === true, requireScope: options.requireScope === true });
|
|
478
|
+
/**
|
|
479
|
+
* Documents ready to search, and decoded pieces of documents read by range, in one memory budget.
|
|
480
|
+
* Each is kept under the key of the caller's scope and the document's ID (`documentKey`): one ID
|
|
481
|
+
* in two scopes is two documents, and the copy of one is never served to the other. Its version
|
|
482
|
+
* (`documentVersion`) holds the document's owner and scope too, so a copy is not served to
|
|
483
|
+
* another owner either, once another document is stored under the same ID.
|
|
484
|
+
*/
|
|
568
485
|
const cache = new DocumentCache<Sized>(
|
|
569
486
|
cacheBytes,
|
|
570
487
|
Math.max(0, Math.trunc(numberOption("cacheSize", options.cacheSize, Number.POSITIVE_INFINITY))),
|
|
571
488
|
);
|
|
572
|
-
/** Forgets everything kept of
|
|
489
|
+
/** Forgets everything kept of the document of one key (`documentKey`): the document, and its pieces. */
|
|
490
|
+
const forgetKey = (key: string) => {
|
|
491
|
+
cache.delete(key);
|
|
492
|
+
cache.deletePrefix(pieceKey(key, 0).slice(0, -1));
|
|
493
|
+
};
|
|
494
|
+
/** Whether `key` is that of document `id`, or of one of its pieces, in any scope. */
|
|
495
|
+
const keyOfId = (key: string, id: string) => {
|
|
496
|
+
const rest = key.slice(key.indexOf("\u0000") + 1);
|
|
497
|
+
return rest === id || rest.startsWith(`${id}#`);
|
|
498
|
+
};
|
|
499
|
+
/**
|
|
500
|
+
* Forgets everything kept of document `id`, in every scope: it was deleted, or written again.
|
|
501
|
+
* In a store that keeps no scopes apart, the copies of all scopes are of that one document.
|
|
502
|
+
*/
|
|
573
503
|
const forget = (id: string) => {
|
|
574
|
-
cache.
|
|
575
|
-
|
|
504
|
+
cache.deleteWhere((key) => keyOfId(key, id));
|
|
505
|
+
for (const key of rebuildIndex) if (keyOfId(key, id)) rebuildIndex.delete(key);
|
|
576
506
|
};
|
|
577
507
|
/** Documents being opened, so that calls arriving together open each one once. */
|
|
578
508
|
const opening = new Map<string, Promise<DocumentSource | undefined>>();
|
|
579
|
-
/**
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
509
|
+
/**
|
|
510
|
+
* The store, to read the text of a document by range rather than load it whole: each call carries
|
|
511
|
+
* `context`: the caller's scope, and the document's owner when it has one (`documentContext`).
|
|
512
|
+
*/
|
|
513
|
+
const rangeStore = (context: DocumentContext): RangeStore => ({
|
|
514
|
+
readTextRange: (id, start, end) => reading(() => store.readTextRange!(id, start, end, context)),
|
|
515
|
+
...(store.getIndex ? { getIndex: (id: string) => reading(() => store.getIndex!(id, context)) } : {}),
|
|
516
|
+
...(store.putIndex ? { putIndex: (id: string, index: Uint8Array) => store.putIndex!(id, index, context) } : {}),
|
|
517
|
+
});
|
|
585
518
|
/** The uploaded file of a document, when the store keeps such files. */
|
|
586
|
-
const loadOriginal =
|
|
519
|
+
const loadOriginal = (id: string, context: DocumentContext) => reading(() => store.getOriginal!(id, context));
|
|
587
520
|
const wholeDocumentBytes = Math.max(0, numberOption("wholeDocumentBytes", options.wholeDocumentBytes, DEFAULT_WHOLE_DOCUMENT_BYTES));
|
|
588
|
-
/** Documents whose saved index did not match their text: the next opening builds it from the text. */
|
|
521
|
+
/** Documents (by `documentKey`) whose saved index did not match their text: the next opening builds it from the text. */
|
|
589
522
|
const rebuildIndex = new Set<string>();
|
|
590
523
|
const scan: ScanSettings = {
|
|
591
524
|
chunkBytes: Math.max(1, Math.trunc(numberOption("scanChunkBytes", options.scanChunkBytes, 1024 * 1024, true))),
|
|
592
525
|
limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentScans", options.maxConcurrentScans, 4)))),
|
|
593
|
-
onBroken: (
|
|
594
|
-
rebuildIndex.add(
|
|
595
|
-
|
|
526
|
+
onBroken: (key) => {
|
|
527
|
+
rebuildIndex.add(key);
|
|
528
|
+
forgetKey(key);
|
|
596
529
|
},
|
|
597
530
|
pieces: {
|
|
598
531
|
get: (key, version) => cache.get(key, version) as CachedPiece | undefined,
|
|
599
|
-
// A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with
|
|
600
|
-
|
|
532
|
+
// A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with
|
|
533
|
+
// it. The document's key is all before the last "#", which no ID holds, and no scope key either.
|
|
534
|
+
set: (key, version, piece) => cache.set(key, version, piece, key.slice(0, key.lastIndexOf("#"))),
|
|
601
535
|
// A quarter of the cache: a few documents can be kept, and no one pushes out all the rest.
|
|
602
536
|
maxDocumentBytes: cacheBytes / 4,
|
|
603
537
|
},
|
|
@@ -607,349 +541,253 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
607
541
|
const ingests = new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentIngests", options.maxConcurrentIngests, 2))));
|
|
608
542
|
/** How long work an ingest waits on, or gave up on, may keep its turn (see `IngestSlot`). */
|
|
609
543
|
const slotCapMs = ingestTimeoutMs > 0 && ingestTimeoutMs <= LONGEST_TIMER_MS ? ingestTimeoutMs : DEFAULT_INGEST_TIMEOUT_MS;
|
|
544
|
+
/**
|
|
545
|
+
* The looks at pages of every question of this library take their turns (`maxConcurrentPageLooks`).
|
|
546
|
+
* A look reads its original within the time the library gives its store calls (`slotCapMs`).
|
|
547
|
+
*/
|
|
548
|
+
const pageLooks: PageLookTurns = {
|
|
549
|
+
limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentPageLooks", options.maxConcurrentPageLooks, DEFAULT_PAGE_LOOKS)))),
|
|
550
|
+
waitMs: Math.max(0, numberOption("pageLookWaitMs", options.pageLookWaitMs, DEFAULT_PAGE_LOOK_WAIT_MS)),
|
|
551
|
+
holdMs: slotCapMs,
|
|
552
|
+
};
|
|
610
553
|
|
|
611
554
|
const scannedPdfPages = Math.max(0, Math.trunc(numberOption("scannedPdfPages", options.scannedPdfPages, 30)));
|
|
612
|
-
|
|
613
|
-
|
|
555
|
+
const { originals } = options;
|
|
556
|
+
if (originals !== undefined && (typeof originals !== "object" || originals === null || typeof originals.read !== "function")) {
|
|
557
|
+
throw new TypeError("originals must be an object with a read(ref, context) method, such as fileOriginals(root) gives.");
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Whether the uploaded file of a document of this format is kept: by its ref (`IngestInput.original`),
|
|
561
|
+
* which `originals` reads back, or as a copy in the store (`putOriginal`).
|
|
562
|
+
*/
|
|
563
|
+
const keeps = (format: DocumentFormat, byRef: boolean) => keepOriginals.has(format) && (byRef ? originals !== undefined : typeof store.putOriginal === "function");
|
|
564
|
+
/**
|
|
565
|
+
* Whether the original of a document, which its metadata says is kept, can be read: by its ref,
|
|
566
|
+
* through `originals`, or from the store (`getOriginal`).
|
|
567
|
+
*/
|
|
568
|
+
const readable = (meta: DocumentMeta) => (meta.original !== undefined && meta.original !== null ? originals !== undefined : typeof store.getOriginal === "function");
|
|
569
|
+
/** Whether `view_pages` can show the pages of a document: a PDF whose original is kept, and can be read. */
|
|
570
|
+
const viewableMeta = (meta: DocumentMeta) => meta.format === "pdf" && meta.originalKept === true && readable(meta);
|
|
571
|
+
/** What `ingest` (src/ingest.ts) needs of this library. */
|
|
572
|
+
const ingestContext: IngestContext = {
|
|
573
|
+
store,
|
|
574
|
+
now,
|
|
575
|
+
ttlMs,
|
|
576
|
+
maxUploadBytes,
|
|
577
|
+
maxTextBytes,
|
|
578
|
+
maxPdfPages,
|
|
579
|
+
ingestTimeoutMs,
|
|
580
|
+
scannedPdfPages,
|
|
581
|
+
// Read at each ingest, as before the move: an application may set them after.
|
|
582
|
+
get extractors() {
|
|
583
|
+
return options.extractors;
|
|
584
|
+
},
|
|
585
|
+
ingests,
|
|
586
|
+
slotCapMs,
|
|
587
|
+
keeps,
|
|
588
|
+
readsRefs: originals !== undefined,
|
|
589
|
+
forget,
|
|
590
|
+
rules,
|
|
591
|
+
ingesting: new Set<string>(),
|
|
592
|
+
};
|
|
614
593
|
|
|
615
594
|
/**
|
|
616
|
-
* The document as the store describes it now
|
|
617
|
-
* deleted (by this server or another one sharing the store), or has
|
|
595
|
+
* The document as the store describes it now, asked with the caller's context: undefined when it
|
|
596
|
+
* was never there, has been deleted (by this server or another one sharing the store), or has
|
|
597
|
+
* expired. Whether the caller may use it is `metaFor`'s to say.
|
|
618
598
|
*/
|
|
619
|
-
async function currentMeta(id: string): Promise<DocumentMeta | undefined> {
|
|
599
|
+
async function currentMeta(id: string, caller: Caller): Promise<DocumentMeta | undefined> {
|
|
620
600
|
if (!isDocumentId(id)) return undefined;
|
|
621
|
-
const meta = await reading(() => store.getMeta(id));
|
|
601
|
+
const meta = metaOf(await reading(() => store.getMeta(id, caller.context)), id);
|
|
602
|
+
if (meta) checkMetaVersion(meta);
|
|
622
603
|
if (!meta || Date.parse(meta.expiresAt) <= now().getTime()) {
|
|
623
|
-
|
|
604
|
+
forgetKey(documentKey(caller, id));
|
|
624
605
|
return undefined;
|
|
625
606
|
}
|
|
626
607
|
return wholeName(meta);
|
|
627
608
|
}
|
|
628
609
|
|
|
610
|
+
/** The document, when `caller` may use it: one of another owner or scope is missing, not forbidden. */
|
|
611
|
+
async function metaFor(id: string, caller: Caller): Promise<DocumentMeta | undefined> {
|
|
612
|
+
const meta = await currentMeta(id, caller);
|
|
613
|
+
return meta && mayUse(meta, caller, rules) ? meta : undefined;
|
|
614
|
+
}
|
|
615
|
+
|
|
629
616
|
/**
|
|
630
|
-
* A document ready to read and search. The store is asked first,
|
|
631
|
-
* used only while the store still has the same document. `known` is
|
|
632
|
-
* the store, to save asking twice.
|
|
617
|
+
* A document ready to read and search, for `caller`, who may use it. The store is asked first,
|
|
618
|
+
* every time: a kept copy is used only while the store still has the same document. `known` is
|
|
619
|
+
* metadata just read from the store and checked, to save asking twice.
|
|
633
620
|
*/
|
|
634
|
-
async function load(id: string, known?: DocumentMeta): Promise<DocumentSource | undefined> {
|
|
635
|
-
const meta = known ?? await
|
|
621
|
+
async function load(id: string, caller: Caller, known?: DocumentMeta): Promise<DocumentSource | undefined> {
|
|
622
|
+
const meta = known ?? await metaFor(id, caller);
|
|
636
623
|
if (!meta) return undefined;
|
|
624
|
+
const key = documentKey(caller, id);
|
|
637
625
|
const version = documentVersion(meta);
|
|
638
|
-
const cached = cache.get(
|
|
626
|
+
const cached = cache.get(key, version) as DocumentSource | undefined;
|
|
639
627
|
if (cached && !cached.broken) return cached;
|
|
640
|
-
const
|
|
641
|
-
let pending = opening.get(
|
|
628
|
+
const opened = `${key}|${version}`;
|
|
629
|
+
let pending = opening.get(opened);
|
|
642
630
|
if (!pending) {
|
|
643
|
-
pending = open(id, meta).finally(() => opening.delete(
|
|
644
|
-
opening.set(
|
|
631
|
+
pending = open(id, meta, caller, key).finally(() => opening.delete(opened));
|
|
632
|
+
opening.set(opened, pending);
|
|
645
633
|
}
|
|
646
634
|
const document = await pending;
|
|
647
|
-
if (document) cache.set(
|
|
635
|
+
if (document) cache.set(key, version, document);
|
|
648
636
|
return document;
|
|
649
637
|
}
|
|
650
638
|
|
|
651
|
-
/**
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
639
|
+
/**
|
|
640
|
+
* Reads a document from the store: its index, to read it by range, or all of it. `meta` is what
|
|
641
|
+
* `metaFor` found for `caller`. The reads carry the caller's scope, and the document's owner when it
|
|
642
|
+
* has one (`documentContext`): the copy is kept for every caller of the scope.
|
|
643
|
+
*/
|
|
644
|
+
async function open(id: string, meta: DocumentMeta, caller: Caller, key: string): Promise<DocumentSource | undefined> {
|
|
645
|
+
const context = documentContext(meta, caller);
|
|
646
|
+
if (typeof store.readTextRange === "function" && meta.textBytes > wholeDocumentBytes) {
|
|
647
|
+
const rebuild = rebuildIndex.delete(key);
|
|
648
|
+
return openRangedDocument(rangeStore(context), meta, scan, { ignoreSavedIndex: rebuild, key });
|
|
649
|
+
}
|
|
650
|
+
const stored = await reading(() => store.get(id, context));
|
|
651
|
+
// Another document is not this one: the metadata `get` gives must be of this ID, owner and
|
|
652
|
+
// scope, and of the version `meta` is (not one deleted and stored again since, by another
|
|
653
|
+
// server, nor one a store of your own gave from the wrong scope). And the text must be the one
|
|
654
|
+
// that metadata describes, of its length and its number of lines: a store that writes the text
|
|
655
|
+
// and the metadata apart can give one document's metadata with another's text (two servers that
|
|
656
|
+
// ingest one ID at once, a file read between two writes). A document read by range is checked
|
|
657
|
+
// too: its index against the metadata, and the end of its text against its index
|
|
658
|
+
// (openRangedDocument). Missing, as for a caller who may not use it.
|
|
659
|
+
const found = stored ? metaOf(stored.meta, id) : undefined;
|
|
660
|
+
if (!stored || !found || !mayUse(found, caller, rules) || documentVersion(found) !== documentVersion(meta)) return undefined;
|
|
661
|
+
if (typeof stored.text !== "string" || stored.text.length !== found.characters) return undefined;
|
|
662
|
+
const named = wholeName(found);
|
|
663
|
+
const document = new SearchableDocument(named === stored.meta ? stored : { ...stored, meta: named });
|
|
664
|
+
return document.lineCount === found.lines ? document : undefined;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/**
|
|
668
|
+
* The uploaded file of document `id`, which `meta`, checked for `caller`, says is kept: read from
|
|
669
|
+
* where the application keeps it (`meta.original`, through `originals`), or from the store. Another
|
|
670
|
+
* server may delete the document and store another under its ID while the bytes are read: so the
|
|
671
|
+
* store is asked again once they are. "missing" unless it still describes the same document, of
|
|
672
|
+
* the same owner and scope, and the bytes are the size of the file that was ingested, and have its
|
|
673
|
+
* SHA-256 when it is known (0.9.0): a store that gives back other bytes of the same size is caught
|
|
674
|
+
* too. "changed" for a file kept by the application that is no longer the one that was ingested:
|
|
675
|
+
* of another size or another SHA-256.
|
|
676
|
+
*/
|
|
677
|
+
async function originalOf(id: string, caller: Caller, meta: DocumentMeta): Promise<Uint8Array | "missing" | "changed"> {
|
|
678
|
+
const kept = refOf(meta);
|
|
679
|
+
let read: Uint8Array | undefined;
|
|
680
|
+
if (kept) {
|
|
681
|
+
if (!originals) return "missing";
|
|
682
|
+
const context: OriginalReadContext = Object.freeze({ ...caller.context, id, bytes: kept.bytes });
|
|
683
|
+
read = await reading(() => originals.read(kept.ref, context));
|
|
684
|
+
} else {
|
|
685
|
+
if (meta.original !== undefined && meta.original !== null) return "missing";
|
|
686
|
+
if (!store.getOriginal) return "missing";
|
|
687
|
+
read = await loadOriginal(id, caller.context);
|
|
656
688
|
}
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
const
|
|
660
|
-
|
|
689
|
+
if (!read) return "missing";
|
|
690
|
+
const bytes = read;
|
|
691
|
+
const after = await metaFor(id, caller);
|
|
692
|
+
if (!after || documentVersion(after) !== documentVersion(meta)) return "missing";
|
|
693
|
+
// The SHA-256 of a file of up to the upload limit is taken a slice at a time.
|
|
694
|
+
const same = async (sha256: string) => await sha256InSlices(bytes, new TimeSlicer()) === sha256;
|
|
695
|
+
if (kept) return bytes.byteLength === kept.bytes && await same(kept.sha256) ? bytes : "changed";
|
|
696
|
+
if (bytes.byteLength !== meta.bytes) return "missing";
|
|
697
|
+
return typeof meta.sha256 === "string" && !await same(meta.sha256) ? "missing" : bytes;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Whether `document`, which a call of `caller` has just read, is still the one the store describes
|
|
702
|
+
* for `caller`. A document loaded whole was checked as it was read (see `open`). The bytes of one
|
|
703
|
+
* read by range carry nothing to check them by, and another server, or this one, may delete the
|
|
704
|
+
* document and store another under its ID while they are read, or between the look-up and the
|
|
705
|
+
* reads: so the store is asked again once they are, as `originalOf` does. When it no longer
|
|
706
|
+
* describes the same document, of the same owner and scope, what was read may be another's: the
|
|
707
|
+
* copy kept of it, read from the store too, is forgotten, and the read is missing.
|
|
708
|
+
*/
|
|
709
|
+
async function stillOpened(document: DocumentSource, caller: Caller): Promise<boolean> {
|
|
710
|
+
if (!(document instanceof RangedDocument)) return true;
|
|
711
|
+
const after = await metaFor(document.meta.id, caller);
|
|
712
|
+
if (after && documentVersion(after) === documentVersion(document.meta)) return true;
|
|
713
|
+
forgetKey(documentKey(caller, document.meta.id));
|
|
714
|
+
return false;
|
|
661
715
|
}
|
|
662
716
|
|
|
663
717
|
/**
|
|
664
718
|
* What a document contributes to the prompt: its text, or its card. Undefined when it is gone
|
|
665
719
|
* by now. A copy found to disagree with the store is opened again once.
|
|
666
720
|
*/
|
|
667
|
-
async function block(id: string, meta: DocumentMeta, whole: boolean, viewable: boolean, wholeRead: WholeRead): Promise<string | undefined> {
|
|
721
|
+
async function block(id: string, meta: DocumentMeta, caller: Caller, whole: boolean, viewable: boolean, wholeRead: WholeRead): Promise<string | undefined> {
|
|
668
722
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
669
|
-
const document = await load(id, attempt === 0 ? meta : undefined);
|
|
723
|
+
const document = await load(id, caller, attempt === 0 ? meta : undefined);
|
|
670
724
|
if (!document) return undefined;
|
|
725
|
+
let text: string;
|
|
671
726
|
try {
|
|
672
|
-
|
|
727
|
+
text = whole
|
|
673
728
|
? renderInline(document.meta, await document.readText())
|
|
674
729
|
: renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, wholeRead);
|
|
675
730
|
} catch (error) {
|
|
676
731
|
// The text is gone while its metadata is still there (removed outside the library): the
|
|
677
732
|
// same as missing. It was a plain Error, which failed the whole question.
|
|
678
733
|
if (error instanceof DocumentGoneError) return undefined;
|
|
679
|
-
if (
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
throw error;
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
}
|
|
686
|
-
return undefined;
|
|
687
|
-
}
|
|
688
|
-
|
|
689
|
-
async function metaFor(id: string, access: AccessOptions | undefined): Promise<DocumentMeta | undefined> {
|
|
690
|
-
const meta = await currentMeta(id);
|
|
691
|
-
return meta && allowed(meta, access) ? meta : undefined;
|
|
692
|
-
}
|
|
693
|
-
|
|
694
|
-
/**
|
|
695
|
-
* The work of `ingest`, once the file is named: `detected` is the format its name and type say.
|
|
696
|
-
* `progress` is given when someone listens to the events of the ingest. `storeFailed` is called
|
|
697
|
-
* when the store fails to write the document, whatever it throws.
|
|
698
|
-
*/
|
|
699
|
-
async function ingestFile(
|
|
700
|
-
input: IngestInput,
|
|
701
|
-
name: string,
|
|
702
|
-
mimeType: string,
|
|
703
|
-
detected: DocumentFormat,
|
|
704
|
-
progress: IngestProgress | undefined,
|
|
705
|
-
storeFailed: () => void,
|
|
706
|
-
work: { abandoned?: Promise<unknown> },
|
|
707
|
-
): Promise<DocumentMeta> {
|
|
708
|
-
let format = detected;
|
|
709
|
-
const { signal, dispose } = ingestSignal(name, input.signal, ingestTimeoutMs);
|
|
710
|
-
// Each long step works in slices, with pauses for other requests: one large upload no longer
|
|
711
|
-
// holds the whole server while it is read.
|
|
712
|
-
const slicer = new TimeSlicer(signal);
|
|
713
|
-
let pages: number | undefined;
|
|
714
|
-
let reading: ReturnType<typeof readingOf>;
|
|
715
|
-
let text: string;
|
|
716
|
-
let wrapped: number;
|
|
717
|
-
let lines: string[];
|
|
718
|
-
let measured: Awaited<ReturnType<typeof measureText>>;
|
|
719
|
-
let outline: DocumentMeta["outline"];
|
|
720
|
-
let logProfile: DocumentMeta["logProfile"];
|
|
721
|
-
let quality: TextQuality = {};
|
|
722
|
-
let index: Awaited<ReturnType<typeof buildTextIndexInSlices>> | undefined;
|
|
723
|
-
try {
|
|
724
|
-
signal.throwIfAborted();
|
|
725
|
-
// In a function of its own, so that the text as extracted is let go once it is prepared:
|
|
726
|
-
// the steps after it hold only the prepared text.
|
|
727
|
-
const read = async () => {
|
|
728
|
-
// What an extractor of your own reports once it has settled (from a timer, a worker) is
|
|
729
|
-
// not reported: the stages after it have begun.
|
|
730
|
-
let extracting = true;
|
|
731
|
-
let extracted: ExtractedText;
|
|
732
|
-
try {
|
|
733
|
-
// Kept, so that an ingest that stops waiting for it (its time is up, its caller left)
|
|
734
|
-
// keeps its turn until the extractor is done too: it still holds memory.
|
|
735
|
-
const extraction = extractText(input.bytes, {
|
|
736
|
-
name,
|
|
737
|
-
mimeType,
|
|
738
|
-
format,
|
|
739
|
-
// A scan is worth storing only if its pages can be shown later: that needs the file itself.
|
|
740
|
-
...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
|
|
741
|
-
signal,
|
|
742
|
-
maxTextBytes,
|
|
743
|
-
maxPages: maxPdfPages,
|
|
744
|
-
...(progress ? { onProgress: (report: ExtractProgress) => { if (extracting) progress.extracted(report); } } : {}),
|
|
745
|
-
}, options.extractors);
|
|
746
|
-
work.abandoned = extraction;
|
|
747
|
-
extracted = await untilAborted(extraction, signal);
|
|
748
|
-
work.abandoned = undefined;
|
|
749
|
-
} finally {
|
|
750
|
-
extracting = false;
|
|
751
|
-
}
|
|
752
|
-
progress?.end();
|
|
753
|
-
// A character is at least one byte: a text this long is too large whatever it holds.
|
|
754
|
-
if (extracted.text.length > maxTextBytes) throw tooMuchText(name, maxTextBytes);
|
|
755
|
-
await slicer.pauseNow();
|
|
756
|
-
return { pages: extracted.pages, reading: readingOf(extracted), ...await prepareText(extracted.text, slicer, progress && ((done, total) => progress.report("prepare", done, total, "characters"))) };
|
|
757
|
-
};
|
|
758
|
-
({ pages, reading, text, wrapped, lines } = await read());
|
|
759
|
-
progress?.end();
|
|
760
|
-
if (!text.trim()) throw new Error(`${name} did not contain any text.`);
|
|
761
|
-
if (format === "text" && looksLikeLog(lines)) format = "log";
|
|
762
|
-
measured = await measureText(text, slicer);
|
|
763
|
-
if (measured.utf8 > maxTextBytes) throw tooMuchText(name, maxTextBytes);
|
|
764
|
-
outline = await buildOutlineInSlices(lines, format, slicer);
|
|
765
|
-
logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
|
|
766
|
-
quality = await measureQuality(lines, format, slicer);
|
|
767
|
-
// The line index, so that the text can be read by range: a few bytes a line, built from the
|
|
768
|
-
// UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
|
|
769
|
-
// then loads whole, so that switching to reading by range finds it ready.
|
|
770
|
-
index = typeof store.putIndex === "function"
|
|
771
|
-
? await buildTextIndexInSlices(text, slicer, progress && ((done, total) => progress.report("index", done, total, "characters")))
|
|
772
|
-
: undefined;
|
|
773
|
-
progress?.end();
|
|
774
|
-
signal.throwIfAborted();
|
|
775
|
-
} finally {
|
|
776
|
-
dispose();
|
|
777
|
-
}
|
|
778
|
-
const created = now();
|
|
779
|
-
const expires = created.getTime() + ttlMs;
|
|
780
|
-
const keepOriginal = keeps(format);
|
|
781
|
-
// A copy: the outline's headings and the log's timestamps are pieces of the text, and a piece
|
|
782
|
-
// keeps the whole text in memory as long as it is held. A meta an application kept held its
|
|
783
|
-
// text: 25 MB of heap for a log of 10 MB in Hebrew, 194 MB for one of 100 MB. Copied through
|
|
784
|
-
// JSON, as a store that keeps it as JSON gives it back.
|
|
785
|
-
const meta: DocumentMeta = jsonCopy<DocumentMeta>({
|
|
786
|
-
id: `doc_${randomUUID().replaceAll("-", "")}`,
|
|
787
|
-
...(input.owner !== undefined ? { owner: input.owner } : {}),
|
|
788
|
-
name,
|
|
789
|
-
mimeType,
|
|
790
|
-
format,
|
|
791
|
-
bytes: input.bytes.byteLength,
|
|
792
|
-
textBytes: measured.utf8,
|
|
793
|
-
jsonBytes: measured.json,
|
|
794
|
-
characters: text.length,
|
|
795
|
-
lines: lines.length,
|
|
796
|
-
estimatedTokens: measured.tokens,
|
|
797
|
-
wrappedLines: wrapped,
|
|
798
|
-
...(pages ? { pages } : {}),
|
|
799
|
-
...reading,
|
|
800
|
-
...(keepOriginal ? { originalKept: true } : {}),
|
|
801
|
-
outline,
|
|
802
|
-
...(logProfile ? { logProfile } : {}),
|
|
803
|
-
...quality,
|
|
804
|
-
createdAt: created.toISOString(),
|
|
805
|
-
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
806
|
-
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
807
|
-
});
|
|
808
|
-
const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
|
|
809
|
-
? serializeTextIndex(index)
|
|
810
|
-
: undefined;
|
|
811
|
-
// Each write is reported once done. What the listener of the events throws is not the store's failure.
|
|
812
|
-
const writes = (keepOriginal ? 1 : 0) + (savedIndex ? 1 : 0) + 1;
|
|
813
|
-
let written = 0;
|
|
814
|
-
let listenerFailed: { error: unknown } | undefined;
|
|
815
|
-
const wrote = (last: boolean) => {
|
|
816
|
-
if (!progress) return;
|
|
817
|
-
try {
|
|
818
|
-
progress.report("store", ++written, writes, "parts");
|
|
819
|
-
if (last) progress.end();
|
|
820
|
-
} catch (error) {
|
|
821
|
-
listenerFailed = { error };
|
|
734
|
+
if (document.broken) continue;
|
|
735
|
+
// Deleted between the look-up and the read: the same as missing.
|
|
736
|
+
if (!await metaFor(id, caller)) return undefined;
|
|
822
737
|
throw error;
|
|
823
738
|
}
|
|
824
|
-
|
|
825
|
-
// The files first, the document last: a document is there once its metadata is.
|
|
826
|
-
const storing = (async () => {
|
|
827
|
-
if (keepOriginal) {
|
|
828
|
-
await store.putOriginal!(meta.id, input.bytes);
|
|
829
|
-
wrote(false);
|
|
830
|
-
}
|
|
831
|
-
if (savedIndex) {
|
|
832
|
-
await store.putIndex!(meta.id, savedIndex);
|
|
833
|
-
wrote(false);
|
|
834
|
-
}
|
|
835
|
-
await store.put({ meta, text });
|
|
836
|
-
wrote(true);
|
|
837
|
-
})();
|
|
838
|
-
try {
|
|
839
|
-
// A store that does not answer fails the ingest after `slotCapMs`: it held the ingest's turn,
|
|
840
|
-
// and the upload handler's room for the file, for as long as it did not answer.
|
|
841
|
-
await settleWithin(storing, slotCapMs, () => new Error(`The store did not finish writing ${name} within ${formatDuration(slotCapMs)}.`));
|
|
842
|
-
} catch (error) {
|
|
843
|
-
// Do not leave a file of up to the upload limit, or a part of one, behind for a document
|
|
844
|
-
// that does not exist: once the writes have ended, when they have not yet. The removal is not
|
|
845
|
-
// waited for longer than the writes were.
|
|
846
|
-
const removal = storing.then(() => store.delete(meta.id), () => store.delete(meta.id)).catch(() => undefined);
|
|
847
|
-
await settleWithin(removal, slotCapMs, () => new Error("")).catch(() => undefined);
|
|
848
|
-
if (listenerFailed?.error !== error) {
|
|
849
|
-
noteStoreWriteFailure(error);
|
|
850
|
-
storeFailed();
|
|
851
|
-
}
|
|
852
|
-
throw error;
|
|
739
|
+
return await stillOpened(document, caller) ? text : undefined;
|
|
853
740
|
}
|
|
854
|
-
return
|
|
741
|
+
return undefined;
|
|
855
742
|
}
|
|
856
743
|
|
|
857
744
|
return {
|
|
858
745
|
budget,
|
|
859
746
|
budgetFor,
|
|
860
747
|
maxUploadBytes,
|
|
748
|
+
access: rules,
|
|
861
749
|
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
// What the caller's listener throws is passed on as it is, not told as a file that could not be read.
|
|
865
|
-
let listenerFailure: { error: unknown } | undefined;
|
|
866
|
-
const listener = input?.onEvent;
|
|
867
|
-
const events = new EventEmitter<IngestEvent>(input?.runId ?? newRunId("ing"), listener && ((event: IngestEvent) => {
|
|
868
|
-
try {
|
|
869
|
-
listener(event);
|
|
870
|
-
} catch (error) {
|
|
871
|
-
listenerFailure ??= { error };
|
|
872
|
-
throw error;
|
|
873
|
-
}
|
|
874
|
-
}));
|
|
875
|
-
let storeFailed = false;
|
|
876
|
-
try {
|
|
877
|
-
if (events.active) events.emit({ type: "ingest.start", ...startOf(input) });
|
|
878
|
-
checkOwner(input.owner);
|
|
879
|
-
const name = cleanFileName(input.name);
|
|
880
|
-
const mimeType = input.mimeType?.trim() || "application/octet-stream";
|
|
881
|
-
// A file whose name and type say nothing is known by its bytes: a PDF, an Office file, a page.
|
|
882
|
-
const format = detectFormat(name, mimeType, input.bytes instanceof Uint8Array ? input.bytes : undefined);
|
|
883
|
-
// Progress is worked out only for someone who listens.
|
|
884
|
-
const progress = events.active ? new IngestProgress(events) : undefined;
|
|
885
|
-
let meta: DocumentMeta;
|
|
886
|
-
try {
|
|
887
|
-
// Refused at once, without waiting for a turn.
|
|
888
|
-
if (input.bytes.byteLength === 0) throw new Error(`${name} is empty.`);
|
|
889
|
-
if (input.bytes.byteLength > maxUploadBytes) {
|
|
890
|
-
throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
|
|
891
|
-
}
|
|
892
|
-
// Its turn (`maxConcurrentIngests`): a caller that gives up while it waits gets its own
|
|
893
|
-
// reason, as it would once the work had begun. (An ingest started inside another of this
|
|
894
|
-
// library, by an extractor of your own, waits for a turn like any other. Telling it apart
|
|
895
|
-
// with AsyncLocalStorage made pdf.js about five times slower on Node 22, for every PDF.)
|
|
896
|
-
const slot = new IngestSlot(await ingests.acquire(input.signal), slotCapMs);
|
|
897
|
-
const work: { abandoned?: Promise<unknown> } = {};
|
|
898
|
-
try {
|
|
899
|
-
meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true), work);
|
|
900
|
-
} finally {
|
|
901
|
-
slot.end(work.abandoned);
|
|
902
|
-
}
|
|
903
|
-
} catch (error) {
|
|
904
|
-
// A store that failed, and a caller that gave up (its own reason), are passed on as they
|
|
905
|
-
// are; a file that could not be read is told with a code.
|
|
906
|
-
if (storeFailed || (input.signal?.aborted && error === input.signal.reason) || isStoreWriteFailure(error) || (listenerFailure && error === listenerFailure.error)) throw error;
|
|
907
|
-
throw toIngestError(error);
|
|
908
|
-
}
|
|
909
|
-
try {
|
|
910
|
-
events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
|
|
911
|
-
} catch (error) {
|
|
912
|
-
// The caller never gets the id: the document goes, as on a throw of the listener a moment earlier.
|
|
913
|
-
await store.delete(meta.id).catch(() => undefined);
|
|
914
|
-
forget(meta.id);
|
|
915
|
-
throw error;
|
|
916
|
-
}
|
|
917
|
-
return meta;
|
|
918
|
-
} catch (error) {
|
|
919
|
-
// A store's own error may name a host or a path, whatever it is: the event, which a browser
|
|
920
|
-
// may see, says only that the document could not be stored.
|
|
921
|
-
events.emit({ type: "ingest.error", error: storeFailed ? { message: STORE_WRITE_FAILED } : eventErrorOf(error) });
|
|
922
|
-
throw error;
|
|
923
|
-
}
|
|
750
|
+
ingest(input) {
|
|
751
|
+
return ingestDocument(ingestContext, input);
|
|
924
752
|
},
|
|
925
753
|
|
|
926
|
-
getMeta
|
|
754
|
+
async getMeta(id, access) {
|
|
755
|
+
return metaFor(id, callerOf(access, rules));
|
|
756
|
+
},
|
|
927
757
|
|
|
928
758
|
async getOriginal(id, access) {
|
|
929
|
-
const
|
|
930
|
-
|
|
759
|
+
const caller = callerOf(access, rules);
|
|
760
|
+
const meta = await metaFor(id, caller);
|
|
761
|
+
if (!meta?.originalKept || !readable(meta)) return undefined;
|
|
762
|
+
const original = await originalOf(id, caller, meta);
|
|
763
|
+
return original instanceof Uint8Array ? original : undefined;
|
|
931
764
|
},
|
|
932
765
|
|
|
933
766
|
async delete(id, access) {
|
|
934
|
-
|
|
767
|
+
const caller = callerOf(access, rules);
|
|
768
|
+
if (!await metaFor(id, caller)) return false;
|
|
935
769
|
forget(id);
|
|
936
|
-
return
|
|
770
|
+
return storeCall("delete", () => store.delete(id, caller.context));
|
|
937
771
|
},
|
|
938
772
|
|
|
939
|
-
async sweep() {
|
|
940
|
-
|
|
773
|
+
async sweep(sweepOptions) {
|
|
774
|
+
// Upkeep of the store, not a user's access: allowed without a scope under `requireScope`.
|
|
775
|
+
const scope = checkScope(sweepOptions?.scope ?? undefined);
|
|
776
|
+
if (typeof store.sweep !== "function") return 0;
|
|
777
|
+
return storeCall("sweep", () => store.sweep!(now(), storeContext(scope, undefined)));
|
|
941
778
|
},
|
|
942
779
|
|
|
943
780
|
async prepare(ids, base, access) {
|
|
781
|
+
const caller = callerOf(access, rules);
|
|
944
782
|
const budget = budgetFor(access?.budget);
|
|
945
783
|
const analysis = access?.wholeDocumentAnalysis !== false;
|
|
946
784
|
const unique = [...new Set(ids)];
|
|
947
785
|
let documents: DocumentMeta[] = [];
|
|
948
786
|
const missing: string[] = [];
|
|
949
787
|
for (const id of unique) {
|
|
950
|
-
// A document
|
|
951
|
-
// read at all.
|
|
952
|
-
const meta = await metaFor(id,
|
|
788
|
+
// A document of another owner or scope is reported as missing, not as forbidden, and is
|
|
789
|
+
// not read at all.
|
|
790
|
+
const meta = await metaFor(id, caller);
|
|
953
791
|
if (meta) documents.push(meta);
|
|
954
792
|
else missing.push(id);
|
|
955
793
|
}
|
|
@@ -959,15 +797,13 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
959
797
|
const plan = planDocuments(documents, budget, base);
|
|
960
798
|
const inline = new Set(plan.inline.map((meta) => meta.id));
|
|
961
799
|
// Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
|
|
962
|
-
const viewable = access?.viewPages
|
|
963
|
-
? documents.filter((meta) => meta.format === "pdf" && meta.originalKept)
|
|
964
|
-
: [];
|
|
800
|
+
const viewable = access?.viewPages ? documents.filter(viewableMeta) : [];
|
|
965
801
|
const shown = new Set(viewable.map((meta) => meta.id));
|
|
966
802
|
const blocks = new Map<string, string>();
|
|
967
803
|
const gone: string[] = [];
|
|
968
804
|
for (const meta of documents) {
|
|
969
805
|
const wholeRead = !analysis ? "not_offered" : canBeReadWhole(meta, budget) ? "offered" : "too_large";
|
|
970
|
-
const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id), wholeRead);
|
|
806
|
+
const text = await block(meta.id, meta, caller, inline.has(meta.id), shown.has(meta.id), wholeRead);
|
|
971
807
|
if (text === undefined) gone.push(meta.id);
|
|
972
808
|
else blocks.set(meta.id, text);
|
|
973
809
|
}
|
|
@@ -983,30 +819,51 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
983
819
|
},
|
|
984
820
|
|
|
985
821
|
tools(documents, toolOptions = {}) {
|
|
986
|
-
const { viewPages, budget: overrides, ...rest } = toolOptions;
|
|
822
|
+
const { viewPages, budget: overrides, access, ...rest } = toolOptions;
|
|
823
|
+
// Without `access`, the owner and scope of each document are those it was handed in with: a
|
|
824
|
+
// library that requires them takes them only from the caller.
|
|
825
|
+
if (access === undefined && (rules.requireOwner || rules.requireScope)) {
|
|
826
|
+
throw new TypeError(rules.requireOwner ? OWNER_REQUIRED : SCOPE_REQUIRED);
|
|
827
|
+
}
|
|
828
|
+
const asker = access !== undefined ? callerOf(access, rules) : undefined;
|
|
987
829
|
const budget = budgetFor(overrides);
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
//
|
|
992
|
-
//
|
|
993
|
-
|
|
994
|
-
|
|
830
|
+
// Which PDFs can be looked at, by the metadata handed in: each look reads the metadata the
|
|
831
|
+
// store holds, and the file it names, not the one handed in.
|
|
832
|
+
const viewable = (viewPages === true ? documents : viewPages || []).filter(viewableMeta);
|
|
833
|
+
// Without `access`, as before 0.9.0: the owner and scope each document was handed in with.
|
|
834
|
+
// The store is asked with them, and the owner and scope it holds are checked against them on
|
|
835
|
+
// every call, so metadata built from an ID alone cannot read another owner's document: such a
|
|
836
|
+
// document is answered as no longer available, as `getMeta` reports it missing. A handed scope
|
|
837
|
+
// that is not valid reads nothing.
|
|
838
|
+
const handed = new Map<string, Caller | undefined>(asker ? [] : [...documents, ...viewable].map((meta) => [meta.id, handedCaller(meta)]));
|
|
839
|
+
const callerFor = (id: string): Caller | undefined => asker ?? (handed.has(id) ? handed.get(id) : NO_CALLER);
|
|
995
840
|
// The metadata the store holds now, not that of a copy kept in memory.
|
|
996
841
|
const checkedLoad = async (id: string) => {
|
|
997
|
-
const
|
|
998
|
-
|
|
842
|
+
const caller = callerFor(id);
|
|
843
|
+
const meta = caller && await metaFor(id, caller);
|
|
844
|
+
return meta ? load(id, caller, meta) : undefined;
|
|
999
845
|
};
|
|
1000
|
-
const checkedOriginal =
|
|
1001
|
-
const
|
|
1002
|
-
|
|
846
|
+
const checkedOriginal = (store.getOriginal || originals) && (async (id: string) => {
|
|
847
|
+
const caller = callerFor(id);
|
|
848
|
+
const meta = caller && await metaFor(id, caller);
|
|
849
|
+
if (!meta || !readable(meta)) return undefined;
|
|
850
|
+
const original = await originalOf(id, caller, meta);
|
|
851
|
+
// A file the application keeps that has changed since it was ingested: its pages are not
|
|
852
|
+
// those of the text the model has, and the model is told so.
|
|
853
|
+
if (original === "changed") throw new Error(changedOriginal(meta.name));
|
|
854
|
+
return original === "missing" ? undefined : original;
|
|
1003
855
|
});
|
|
1004
856
|
return createDocumentTools({
|
|
1005
857
|
load: checkedLoad,
|
|
858
|
+
// Once a call has read a document by range: the store is asked again (`stillOpened`).
|
|
859
|
+
checkRead: async (document) => {
|
|
860
|
+
const caller = callerFor(document.meta.id);
|
|
861
|
+
return caller !== undefined && await stillOpened(document, caller);
|
|
862
|
+
},
|
|
1006
863
|
documentIds: documents.map((meta) => meta.id),
|
|
1007
864
|
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
|
|
1008
865
|
budget,
|
|
1009
|
-
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal } : {}),
|
|
866
|
+
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal, pageLooks } : {}),
|
|
1010
867
|
// `analyze_whole_document` is declared only when it can read at least one of the documents.
|
|
1011
868
|
wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
|
|
1012
869
|
// `aggregate_table` only when one may hold a table.
|
|
@@ -1015,4 +872,13 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
1015
872
|
});
|
|
1016
873
|
},
|
|
1017
874
|
};
|
|
875
|
+
|
|
876
|
+
/** The caller a document was handed to `tools` for (without `access`): its owner and scope. Undefined for a scope that is not valid. */
|
|
877
|
+
function handedCaller(meta: DocumentMeta): Caller | undefined {
|
|
878
|
+
try {
|
|
879
|
+
return callerOf({ owner: meta.owner, scope: meta.scope }, rules);
|
|
880
|
+
} catch {
|
|
881
|
+
return undefined;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
1018
884
|
}
|