llm-large-files 0.8.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +631 -0
- package/README.md +9 -10
- package/dist/access.d.ts +86 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +131 -0
- package/dist/access.js.map +1 -0
- package/dist/ask.d.ts +45 -1
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +181 -20
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +57 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +217 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +72 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +102 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +35 -9
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +14 -3
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +46 -35
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +19 -3
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +84 -12
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +18 -6
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +2 -0
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/index.d.ts +9 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +70 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +868 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +176 -34
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +332 -512
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -2
- package/dist/limiter.js +2 -2
- package/dist/map-reduce.js +3 -3
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +43 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +63 -3
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +234 -7
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +482 -121
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +18 -3
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +102 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +365 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +4 -3
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +7 -6
- package/dist/node/sse.js.map +1 -1
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.js.map +1 -1
- package/dist/ranged.d.ts +22 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +50 -12
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- package/dist/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +120 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +582 -139
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +25 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +135 -13
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +116 -13
- package/dist/types.d.ts.map +1 -1
- package/docs/README.md +17 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +12 -8
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +16 -7
- package/docs/guides/deployment.md +309 -87
- package/docs/guides/errors-and-reliability.md +161 -23
- package/docs/guides/own-adapter-and-loop.md +27 -10
- package/docs/guides/pdfs.md +123 -29
- package/docs/guides/storage.md +634 -143
- package/docs/guides/testing.md +78 -129
- package/docs/guides/vertex-and-gemini.md +10 -7
- package/docs/guides/web-app.md +322 -77
- package/docs/how-it-works.md +35 -8
- package/docs/measurements.md +63 -8
- package/docs/publishing.md +112 -36
- package/docs/reference/ask.md +154 -13
- package/docs/reference/errors-and-retries.md +166 -14
- package/docs/reference/events.md +53 -20
- package/docs/reference/gemini.md +70 -21
- package/docs/reference/library.md +709 -165
- package/docs/reference/node.md +633 -104
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +15 -5
- package/docs/security.md +316 -70
- package/docs/troubleshooting.md +165 -58
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +12 -3
- package/src/access.ts +144 -0
- package/src/ask.ts +230 -19
- package/src/cache.ts +20 -5
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +255 -0
- package/src/errors.ts +129 -15
- package/src/events.ts +86 -21
- package/src/evidence.ts +14 -3
- package/src/extract.ts +50 -33
- package/src/gemini/adapter.ts +97 -11
- package/src/gemini/chat.ts +20 -6
- package/src/gemini/index.ts +1 -1
- package/src/index.ts +9 -6
- package/src/ingest.ts +927 -0
- package/src/library.ts +482 -523
- package/src/limiter.ts +2 -2
- package/src/map-reduce.ts +3 -3
- package/src/model.ts +69 -5
- package/src/node/handlers.ts +691 -117
- package/src/node/index.ts +13 -2
- package/src/node/ingest-child.ts +23 -5
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +365 -0
- package/src/node/sse.ts +7 -6
- package/src/pdf-layout.ts +69 -11
- package/src/ranged.ts +42 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/source.ts +178 -0
- package/src/stores.ts +635 -140
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +150 -14
- package/src/types.ts +106 -13
package/src/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 { 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
|
|
@@ -111,10 +117,71 @@ export type LargeFilesOptions = {
|
|
|
111
117
|
* run at once in this process. The others wait their turn. Defaults to 4.
|
|
112
118
|
*/
|
|
113
119
|
maxConcurrentScans?: number;
|
|
120
|
+
/**
|
|
121
|
+
* How many ingests do their work at once in this library. The others wait their turn, in order,
|
|
122
|
+
* and their time limit (`ingestTimeoutMs`) starts when their turn comes. An ingest holds about five
|
|
123
|
+
* times its file in memory while it works, and ingests at once share one thread: more of them do
|
|
124
|
+
* not finish sooner. `Infinity` for no limit (as before 0.8.2). Defaults to 2. New in 0.8.2.
|
|
125
|
+
*/
|
|
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;
|
|
114
158
|
/** Clock override, for tests. */
|
|
115
159
|
now?: () => Date;
|
|
116
160
|
};
|
|
117
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
|
+
|
|
118
185
|
export type IngestInput = {
|
|
119
186
|
name: string;
|
|
120
187
|
mimeType?: string;
|
|
@@ -137,10 +204,63 @@ export type IngestInput = {
|
|
|
137
204
|
onEvent?: (event: IngestEvent) => void;
|
|
138
205
|
/** The `runId` of those events. Defaults to one made for the ingest ("ing_…"). */
|
|
139
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 };
|
|
140
241
|
};
|
|
141
242
|
|
|
142
|
-
/**
|
|
143
|
-
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 };
|
|
144
264
|
|
|
145
265
|
export type PrepareOptions = AccessOptions & {
|
|
146
266
|
/**
|
|
@@ -164,6 +284,14 @@ export type PrepareOptions = AccessOptions & {
|
|
|
164
284
|
};
|
|
165
285
|
|
|
166
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;
|
|
167
295
|
/** Enables `analyze_whole_document`, which reads the entire file in parts. */
|
|
168
296
|
generate?: GenerateText;
|
|
169
297
|
/** Progress of whole-document reads, for status messages. */
|
|
@@ -207,17 +335,37 @@ export interface LargeFiles {
|
|
|
207
335
|
budgetFor(overrides?: Partial<Budget>, limits?: ModelLimits): Budget;
|
|
208
336
|
readonly maxUploadBytes: number;
|
|
209
337
|
/**
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
*
|
|
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.
|
|
213
341
|
*/
|
|
214
|
-
|
|
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>;
|
|
215
352
|
getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
|
|
216
|
-
/**
|
|
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
|
+
*/
|
|
217
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. */
|
|
218
362
|
delete(id: string, access?: AccessOptions): Promise<boolean>;
|
|
219
|
-
/**
|
|
220
|
-
|
|
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>;
|
|
221
369
|
/**
|
|
222
370
|
* Plans one model request: which documents go in whole and which become searchable cards.
|
|
223
371
|
* `base` is the size of everything else in the request (messages, system prompt, other files).
|
|
@@ -227,70 +375,12 @@ export interface LargeFiles {
|
|
|
227
375
|
tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
|
|
228
376
|
}
|
|
229
377
|
|
|
230
|
-
export function isDocumentId(value: unknown): value is string {
|
|
231
|
-
return typeof value === "string" && DOCUMENT_ID_PATTERN.test(value);
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/** The fields of a document that are safe to return to a browser. */
|
|
235
|
-
export function toDocumentSummary(meta: DocumentMeta): DocumentSummary {
|
|
236
|
-
return {
|
|
237
|
-
id: meta.id,
|
|
238
|
-
name: meta.name,
|
|
239
|
-
mimeType: meta.mimeType,
|
|
240
|
-
format: meta.format,
|
|
241
|
-
bytes: meta.bytes,
|
|
242
|
-
lines: meta.lines,
|
|
243
|
-
estimatedTokens: meta.estimatedTokens,
|
|
244
|
-
...(meta.pages ? { pages: meta.pages } : {}),
|
|
245
|
-
...(meta.encoding ? { encoding: meta.encoding } : {}),
|
|
246
|
-
...(meta.replacedCharacters ? { replacedCharacters: meta.replacedCharacters } : {}),
|
|
247
|
-
expiresAt: meta.expiresAt,
|
|
248
|
-
};
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
/** An encoding's name as TextDecoder gives it ("windows-1255"): an extractor of your own may name another. */
|
|
252
|
-
const ENCODING_NAME = /^[a-z0-9][a-z0-9._:-]{0,39}$/i;
|
|
253
|
-
|
|
254
|
-
/**
|
|
255
|
-
* Whether the name is an older encoding, as `DocumentMeta.encoding` records: not UTF-8 or UTF-16,
|
|
256
|
-
* under any of their names ("utf8", "unicode"). The model is told the file is not in UTF-8.
|
|
257
|
-
*/
|
|
258
|
-
function olderEncoding(name: unknown): name is string {
|
|
259
|
-
if (typeof name !== "string" || !ENCODING_NAME.test(name)) return false;
|
|
260
|
-
let known: string;
|
|
261
|
-
try {
|
|
262
|
-
known = new TextDecoder(name).encoding;
|
|
263
|
-
} catch {
|
|
264
|
-
// A name TextDecoder does not know: the extractor read the file itself.
|
|
265
|
-
return true;
|
|
266
|
-
}
|
|
267
|
-
return known !== "utf-8" && known !== "utf-16le" && known !== "utf-16be";
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
/** How the text of a file was read, as its extractor said, in the fields of `DocumentMeta`. */
|
|
271
|
-
function readingOf(extracted: ExtractedText): Pick<DocumentMeta, "encoding" | "replacedCharacters"> {
|
|
272
|
-
const { encoding, replacedCharacters } = extracted;
|
|
273
|
-
return {
|
|
274
|
-
...(olderEncoding(encoding) ? { encoding } : {}),
|
|
275
|
-
...(typeof replacedCharacters === "number" && Number.isSafeInteger(replacedCharacters) && replacedCharacters > 0 ? { replacedCharacters } : {}),
|
|
276
|
-
};
|
|
277
|
-
}
|
|
278
|
-
|
|
279
378
|
/**
|
|
280
|
-
*
|
|
281
|
-
*
|
|
282
|
-
* Names are shown to the model and in UIs, so a name must not be able to start a new line of the
|
|
283
|
-
* prompt, or disguise its extension. Most characters that show nothing are removed (tag characters,
|
|
284
|
-
* zero-width spaces); the variation selectors and joiners that scripts and emoji need are kept, and
|
|
285
|
-
* 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.
|
|
286
381
|
*/
|
|
287
|
-
export function
|
|
288
|
-
|
|
289
|
-
// Control characters, line and paragraph separators, and text-direction controls become a space.
|
|
290
|
-
const spaced = base.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]+/gu, " ");
|
|
291
|
-
const name = removeInvisible(spaced).replace(/\s+/g, " ").trim();
|
|
292
|
-
// At most 255 characters, never half of an emoji. A flag cut short loses the tags left of it.
|
|
293
|
-
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);
|
|
294
384
|
}
|
|
295
385
|
|
|
296
386
|
/**
|
|
@@ -303,43 +393,42 @@ function wholeName(meta: DocumentMeta): DocumentMeta {
|
|
|
303
393
|
return name === meta.name ? meta : { ...meta, name };
|
|
304
394
|
}
|
|
305
395
|
|
|
306
|
-
/**
|
|
307
|
-
* Refuses an owner that every caller without a user would share: an empty string (what
|
|
308
|
-
* `user?.id ?? ""` gives), one of spaces only, or null. Undefined is no owner. A number is let
|
|
309
|
-
* through, as before, for JavaScript code that passes numeric user IDs.
|
|
310
|
-
*/
|
|
311
|
-
export function checkOwner(owner: unknown): void {
|
|
312
|
-
if (owner === undefined || (typeof owner === "string" && owner.trim() !== "") || (typeof owner === "number" && Number.isFinite(owner))) return;
|
|
313
|
-
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.");
|
|
314
|
-
}
|
|
315
|
-
|
|
316
396
|
/**
|
|
317
397
|
* A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
|
|
318
398
|
* could not be read is not a document that is gone, and its own error names paths or hosts.
|
|
319
399
|
*/
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
return await read();
|
|
323
|
-
} catch (error) {
|
|
324
|
-
throw error instanceof DocumentStoreError ? error : new DocumentStoreError(error);
|
|
325
|
-
}
|
|
400
|
+
function reading<T>(read: () => Promise<T>): Promise<T> {
|
|
401
|
+
return storeCall("read", read);
|
|
326
402
|
}
|
|
327
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
|
+
|
|
328
410
|
/**
|
|
329
|
-
*
|
|
330
|
-
*
|
|
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.
|
|
331
413
|
*/
|
|
332
|
-
|
|
414
|
+
const changedOriginal = (file: string) => `${file} changed on the server since it was read. Attach it again to look at its pages.`;
|
|
333
415
|
|
|
334
|
-
|
|
335
|
-
|
|
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;
|
|
336
428
|
}
|
|
337
429
|
|
|
338
430
|
/** Default for `cacheBytes`. */
|
|
339
431
|
export const DEFAULT_CACHE_BYTES = 256 * 1024 * 1024;
|
|
340
|
-
/** The refusal of a file whose text is larger than `maxTextBytes`. */
|
|
341
|
-
const tooMuchText = (name: string, maxTextBytes: number) =>
|
|
342
|
-
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.`);
|
|
343
432
|
|
|
344
433
|
/** Default for `maxPdfPages`. */
|
|
345
434
|
export const DEFAULT_MAX_PDF_PAGES = 5_000;
|
|
@@ -347,136 +436,13 @@ export const DEFAULT_MAX_PDF_PAGES = 5_000;
|
|
|
347
436
|
export const DEFAULT_MAX_TEXT_BYTES = 100 * 1024 * 1024;
|
|
348
437
|
/** Default for `ingestTimeoutMs`: 2 minutes. */
|
|
349
438
|
export const DEFAULT_INGEST_TIMEOUT_MS = 120_000;
|
|
350
|
-
/** The longest a Node.js timer waits: a longer one fires at once. A limit past it is no limit. */
|
|
351
|
-
const LONGEST_TIMER_MS = 2 ** 31 - 1;
|
|
352
|
-
|
|
353
|
-
/** A time limit in the words of a message: "500 ms", "45 s", "2 min". */
|
|
354
|
-
function formatDuration(ms: number): string {
|
|
355
|
-
if (ms < 1_000) return `${Math.max(1, Math.round(ms))} ms`;
|
|
356
|
-
if (ms < 120_000) return `${Number((ms / 1_000).toFixed(1))} s`;
|
|
357
|
-
return `${Number((ms / 60_000).toFixed(1))} min`;
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
/**
|
|
361
|
-
* The signal one ingest runs under: aborted when the caller's is, or when `timeoutMs` has passed
|
|
362
|
-
* (with an error that says the file took too long). `dispose` stops the timer.
|
|
363
|
-
*/
|
|
364
|
-
function ingestSignal(name: string, caller: AbortSignal | undefined, timeoutMs: number): { signal: AbortSignal; dispose(): void } {
|
|
365
|
-
const controller = new AbortController();
|
|
366
|
-
const onAbort = () => controller.abort(caller!.reason);
|
|
367
|
-
if (caller?.aborted) controller.abort(caller.reason);
|
|
368
|
-
else caller?.addEventListener("abort", onAbort, { once: true });
|
|
369
|
-
const timer = timeoutMs > 0 && timeoutMs <= LONGEST_TIMER_MS
|
|
370
|
-
? 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)
|
|
371
|
-
: undefined;
|
|
372
|
-
return {
|
|
373
|
-
signal: controller.signal,
|
|
374
|
-
dispose() {
|
|
375
|
-
clearTimeout(timer);
|
|
376
|
-
caller?.removeEventListener("abort", onAbort);
|
|
377
|
-
},
|
|
378
|
-
};
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
/**
|
|
382
|
-
* `work`, or the signal's reason as soon as it is aborted: an extractor of your own that does not
|
|
383
|
-
* look at the signal is no longer waited for (though the work it does cannot be stopped).
|
|
384
|
-
*/
|
|
385
|
-
function untilAborted<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
386
|
-
if (signal.aborted) return Promise.reject(signal.reason);
|
|
387
|
-
return new Promise<T>((resolve, reject) => {
|
|
388
|
-
const onAbort = () => reject(signal.reason);
|
|
389
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
390
|
-
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
391
|
-
});
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
/** The message of `ingest.error` when the store failed to write the document. */
|
|
395
|
-
const STORE_WRITE_FAILED = "The document could not be stored. Try again later.";
|
|
396
|
-
|
|
397
|
-
/** The least time between two `ingest.progress` events of one stage, in milliseconds: a slice of `TimeSlicer`. */
|
|
398
|
-
const PROGRESS_MS = 12;
|
|
399
|
-
|
|
400
|
-
type ProgressUnit = Extract<IngestEvent, { type: "ingest.progress" }>["unit"];
|
|
401
|
-
const EXTRACT_STAGES = new Set<unknown>(["extract", "check", "pictures", "decode"]);
|
|
402
|
-
const EXTRACT_UNITS = new Set<unknown>(["pages", "parts", "bytes"]);
|
|
403
|
-
const isCount = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
404
|
-
|
|
405
|
-
/** What `ingest.start` says of an ingest, worked out from whatever it was given: the checks come after it. */
|
|
406
|
-
function startOf(input: IngestInput | undefined): { name: string; format: DocumentFormat; bytes: number } {
|
|
407
|
-
try {
|
|
408
|
-
const name = typeof input?.name === "string" ? cleanFileName(input.name) : "";
|
|
409
|
-
const mimeType = (typeof input?.mimeType === "string" ? input.mimeType.trim() : "") || "application/octet-stream";
|
|
410
|
-
const bytes = input?.bytes?.byteLength;
|
|
411
|
-
return { name, format: detectFormat(name, mimeType), bytes: isCount(bytes) ? bytes : 0 };
|
|
412
|
-
} catch {
|
|
413
|
-
return { name: "", format: "text", bytes: 0 };
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
type HeldProgress = { done: number; total: number | undefined; unit: ProgressUnit; sent: boolean };
|
|
418
|
-
|
|
419
|
-
/**
|
|
420
|
-
* Sends the `ingest.progress` events of one ingest: at most one every `PROGRESS_MS` for each stage,
|
|
421
|
-
* however the stages take turns, then the last progress of each stage when the stages end (`end`).
|
|
422
|
-
* A progress that completes its stage goes out at once, the first time, so that stages that run one
|
|
423
|
-
* after the other end in that order. Made only when someone listens.
|
|
424
|
-
*/
|
|
425
|
-
class IngestProgress {
|
|
426
|
-
/** Each stage that reported, in the order it first did: when it last sent, and its last progress. */
|
|
427
|
-
private readonly stages = new Map<IngestStage, { sentAt: number; completed: boolean; last: HeldProgress }>();
|
|
428
|
-
/** Set once a stage after the extractor's began: an extract stage is not reported again. */
|
|
429
|
-
private extractOver = false;
|
|
430
|
-
|
|
431
|
-
constructor(private readonly events: EventEmitter<IngestEvent>) {}
|
|
432
|
-
|
|
433
|
-
report(stage: IngestStage, done: number, total: number | undefined, unit: ProgressUnit): void {
|
|
434
|
-
if (!EXTRACT_STAGES.has(stage)) this.extractOver = true;
|
|
435
|
-
const last: HeldProgress = { done, total, unit, sent: false };
|
|
436
|
-
let state = this.stages.get(stage);
|
|
437
|
-
if (!state) {
|
|
438
|
-
state = { sentAt: Number.NEGATIVE_INFINITY, completed: false, last };
|
|
439
|
-
this.stages.set(stage, state);
|
|
440
|
-
}
|
|
441
|
-
state.last = last;
|
|
442
|
-
const now = performance.now();
|
|
443
|
-
const completes = !state.completed && total !== undefined && done >= total;
|
|
444
|
-
if (completes) state.completed = true;
|
|
445
|
-
if (completes || now - state.sentAt >= PROGRESS_MS) {
|
|
446
|
-
state.sentAt = now;
|
|
447
|
-
this.send(stage, last);
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
/** The progress an extractor reported (`ExtractInput.onProgress`). One of your own may send anything: what does not fit is left out. */
|
|
452
|
-
extracted(progress: ExtractProgress): void {
|
|
453
|
-
if (this.extractOver) return;
|
|
454
|
-
const stage = progress?.stage ?? "extract";
|
|
455
|
-
if (!EXTRACT_STAGES.has(stage) || !EXTRACT_UNITS.has(progress?.unit) || !isCount(progress?.done)) return;
|
|
456
|
-
this.report(stage, progress.done, isCount(progress.total) ? progress.total : undefined, progress.unit);
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
/** The stages so far are over: the last progress of each, when it was held back, goes out, in the order they began. */
|
|
460
|
-
end(): void {
|
|
461
|
-
const held = [...this.stages].filter(([, state]) => !state.last.sent);
|
|
462
|
-
this.stages.clear();
|
|
463
|
-
for (const [stage, state] of held) this.send(stage, state.last);
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
private send(stage: IngestStage, last: HeldProgress): void {
|
|
467
|
-
last.sent = true;
|
|
468
|
-
this.events.emit({
|
|
469
|
-
type: "ingest.progress",
|
|
470
|
-
stage,
|
|
471
|
-
done: last.done,
|
|
472
|
-
...(last.total !== undefined ? { total: last.total } : {}),
|
|
473
|
-
unit: last.unit,
|
|
474
|
-
});
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
439
|
|
|
478
440
|
/** Default for `wholeDocumentBytes`. */
|
|
479
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;
|
|
480
446
|
|
|
481
447
|
/**
|
|
482
448
|
* A number option as it was given, or `fallback` when it was left out. NaN, which
|
|
@@ -507,356 +473,321 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
507
473
|
const now = options.now ?? (() => new Date());
|
|
508
474
|
const { store } = options;
|
|
509
475
|
const cacheBytes = Math.max(0, numberOption("cacheBytes", options.cacheBytes, DEFAULT_CACHE_BYTES));
|
|
510
|
-
/**
|
|
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
|
+
*/
|
|
511
485
|
const cache = new DocumentCache<Sized>(
|
|
512
486
|
cacheBytes,
|
|
513
487
|
Math.max(0, Math.trunc(numberOption("cacheSize", options.cacheSize, Number.POSITIVE_INFINITY))),
|
|
514
488
|
);
|
|
515
|
-
/** 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
|
+
*/
|
|
516
503
|
const forget = (id: string) => {
|
|
517
|
-
cache.
|
|
518
|
-
|
|
504
|
+
cache.deleteWhere((key) => keyOfId(key, id));
|
|
505
|
+
for (const key of rebuildIndex) if (keyOfId(key, id)) rebuildIndex.delete(key);
|
|
519
506
|
};
|
|
520
507
|
/** Documents being opened, so that calls arriving together open each one once. */
|
|
521
508
|
const opening = new Map<string, Promise<DocumentSource | undefined>>();
|
|
522
|
-
/**
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
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
|
+
});
|
|
528
518
|
/** The uploaded file of a document, when the store keeps such files. */
|
|
529
|
-
const loadOriginal =
|
|
519
|
+
const loadOriginal = (id: string, context: DocumentContext) => reading(() => store.getOriginal!(id, context));
|
|
530
520
|
const wholeDocumentBytes = Math.max(0, numberOption("wholeDocumentBytes", options.wholeDocumentBytes, DEFAULT_WHOLE_DOCUMENT_BYTES));
|
|
531
|
-
/** 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. */
|
|
532
522
|
const rebuildIndex = new Set<string>();
|
|
533
523
|
const scan: ScanSettings = {
|
|
534
524
|
chunkBytes: Math.max(1, Math.trunc(numberOption("scanChunkBytes", options.scanChunkBytes, 1024 * 1024, true))),
|
|
535
525
|
limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentScans", options.maxConcurrentScans, 4)))),
|
|
536
|
-
onBroken: (
|
|
537
|
-
rebuildIndex.add(
|
|
538
|
-
|
|
526
|
+
onBroken: (key) => {
|
|
527
|
+
rebuildIndex.add(key);
|
|
528
|
+
forgetKey(key);
|
|
539
529
|
},
|
|
540
530
|
pieces: {
|
|
541
531
|
get: (key, version) => cache.get(key, version) as CachedPiece | undefined,
|
|
542
|
-
// A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with
|
|
543
|
-
|
|
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("#"))),
|
|
544
535
|
// A quarter of the cache: a few documents can be kept, and no one pushes out all the rest.
|
|
545
536
|
maxDocumentBytes: cacheBytes / 4,
|
|
546
537
|
},
|
|
547
538
|
};
|
|
548
539
|
const keepOriginals = new Set<DocumentFormat>(options.keepOriginals ?? []);
|
|
540
|
+
/** The ingests doing their work, and those waiting their turn (`maxConcurrentIngests`). */
|
|
541
|
+
const ingests = new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentIngests", options.maxConcurrentIngests, 2))));
|
|
542
|
+
/** How long work an ingest waits on, or gave up on, may keep its turn (see `IngestSlot`). */
|
|
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
|
+
};
|
|
553
|
+
|
|
549
554
|
const scannedPdfPages = Math.max(0, Math.trunc(numberOption("scannedPdfPages", options.scannedPdfPages, 30)));
|
|
550
|
-
|
|
551
|
-
|
|
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
|
+
};
|
|
552
593
|
|
|
553
594
|
/**
|
|
554
|
-
* The document as the store describes it now
|
|
555
|
-
* 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.
|
|
556
598
|
*/
|
|
557
|
-
async function currentMeta(id: string): Promise<DocumentMeta | undefined> {
|
|
599
|
+
async function currentMeta(id: string, caller: Caller): Promise<DocumentMeta | undefined> {
|
|
558
600
|
if (!isDocumentId(id)) return undefined;
|
|
559
|
-
const meta = await reading(() => store.getMeta(id));
|
|
601
|
+
const meta = metaOf(await reading(() => store.getMeta(id, caller.context)), id);
|
|
602
|
+
if (meta) checkMetaVersion(meta);
|
|
560
603
|
if (!meta || Date.parse(meta.expiresAt) <= now().getTime()) {
|
|
561
|
-
|
|
604
|
+
forgetKey(documentKey(caller, id));
|
|
562
605
|
return undefined;
|
|
563
606
|
}
|
|
564
607
|
return wholeName(meta);
|
|
565
608
|
}
|
|
566
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
|
+
|
|
567
616
|
/**
|
|
568
|
-
* A document ready to read and search. The store is asked first,
|
|
569
|
-
* used only while the store still has the same document. `known` is
|
|
570
|
-
* 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.
|
|
571
620
|
*/
|
|
572
|
-
async function load(id: string, known?: DocumentMeta): Promise<DocumentSource | undefined> {
|
|
573
|
-
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);
|
|
574
623
|
if (!meta) return undefined;
|
|
624
|
+
const key = documentKey(caller, id);
|
|
575
625
|
const version = documentVersion(meta);
|
|
576
|
-
const cached = cache.get(
|
|
626
|
+
const cached = cache.get(key, version) as DocumentSource | undefined;
|
|
577
627
|
if (cached && !cached.broken) return cached;
|
|
578
|
-
const
|
|
579
|
-
let pending = opening.get(
|
|
628
|
+
const opened = `${key}|${version}`;
|
|
629
|
+
let pending = opening.get(opened);
|
|
580
630
|
if (!pending) {
|
|
581
|
-
pending = open(id, meta).finally(() => opening.delete(
|
|
582
|
-
opening.set(
|
|
631
|
+
pending = open(id, meta, caller, key).finally(() => opening.delete(opened));
|
|
632
|
+
opening.set(opened, pending);
|
|
583
633
|
}
|
|
584
634
|
const document = await pending;
|
|
585
|
-
if (document) cache.set(
|
|
635
|
+
if (document) cache.set(key, version, document);
|
|
586
636
|
return document;
|
|
587
637
|
}
|
|
588
638
|
|
|
589
|
-
/**
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
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 });
|
|
594
649
|
}
|
|
595
|
-
const stored = await reading(() => store.get(id));
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
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;
|
|
599
665
|
}
|
|
600
666
|
|
|
601
667
|
/**
|
|
602
|
-
*
|
|
603
|
-
*
|
|
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.
|
|
604
676
|
*/
|
|
605
|
-
async function
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
if (!await currentMeta(id)) return undefined;
|
|
617
|
-
throw error;
|
|
618
|
-
}
|
|
619
|
-
}
|
|
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);
|
|
620
688
|
}
|
|
621
|
-
return
|
|
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;
|
|
622
698
|
}
|
|
623
699
|
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
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;
|
|
627
715
|
}
|
|
628
716
|
|
|
629
717
|
/**
|
|
630
|
-
*
|
|
631
|
-
*
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
detected: DocumentFormat,
|
|
639
|
-
progress: IngestProgress | undefined,
|
|
640
|
-
storeFailed: () => void,
|
|
641
|
-
): Promise<DocumentMeta> {
|
|
642
|
-
if (input.bytes.byteLength === 0) throw new Error(`${name} is empty.`);
|
|
643
|
-
if (input.bytes.byteLength > maxUploadBytes) {
|
|
644
|
-
throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
|
|
645
|
-
}
|
|
646
|
-
let format = detected;
|
|
647
|
-
const { signal, dispose } = ingestSignal(name, input.signal, ingestTimeoutMs);
|
|
648
|
-
// Each long step works in slices, with pauses for other requests: one large upload no longer
|
|
649
|
-
// holds the whole server while it is read.
|
|
650
|
-
const slicer = new TimeSlicer(signal);
|
|
651
|
-
let pages: number | undefined;
|
|
652
|
-
let reading: ReturnType<typeof readingOf>;
|
|
653
|
-
let text: string;
|
|
654
|
-
let wrapped: number;
|
|
655
|
-
let lines: string[];
|
|
656
|
-
let measured: Awaited<ReturnType<typeof measureText>>;
|
|
657
|
-
let outline: DocumentMeta["outline"];
|
|
658
|
-
let logProfile: DocumentMeta["logProfile"];
|
|
659
|
-
let quality: TextQuality = {};
|
|
660
|
-
let index: Awaited<ReturnType<typeof buildTextIndexInSlices>> | undefined;
|
|
661
|
-
try {
|
|
662
|
-
signal.throwIfAborted();
|
|
663
|
-
// In a function of its own, so that the text as extracted is let go once it is prepared:
|
|
664
|
-
// the steps after it hold only the prepared text.
|
|
665
|
-
const read = async () => {
|
|
666
|
-
// What an extractor of your own reports once it has settled (from a timer, a worker) is
|
|
667
|
-
// not reported: the stages after it have begun.
|
|
668
|
-
let extracting = true;
|
|
669
|
-
let extracted: ExtractedText;
|
|
670
|
-
try {
|
|
671
|
-
extracted = await untilAborted(extractText(input.bytes, {
|
|
672
|
-
name,
|
|
673
|
-
mimeType,
|
|
674
|
-
format,
|
|
675
|
-
// A scan is worth storing only if its pages can be shown later: that needs the file itself.
|
|
676
|
-
...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
|
|
677
|
-
signal,
|
|
678
|
-
maxTextBytes,
|
|
679
|
-
maxPages: maxPdfPages,
|
|
680
|
-
...(progress ? { onProgress: (report: ExtractProgress) => { if (extracting) progress.extracted(report); } } : {}),
|
|
681
|
-
}, options.extractors), signal);
|
|
682
|
-
} finally {
|
|
683
|
-
extracting = false;
|
|
684
|
-
}
|
|
685
|
-
progress?.end();
|
|
686
|
-
// A character is at least one byte: a text this long is too large whatever it holds.
|
|
687
|
-
if (extracted.text.length > maxTextBytes) throw tooMuchText(name, maxTextBytes);
|
|
688
|
-
await slicer.pauseNow();
|
|
689
|
-
return { pages: extracted.pages, reading: readingOf(extracted), ...await prepareText(extracted.text, slicer, progress && ((done, total) => progress.report("prepare", done, total, "characters"))) };
|
|
690
|
-
};
|
|
691
|
-
({ pages, reading, text, wrapped, lines } = await read());
|
|
692
|
-
progress?.end();
|
|
693
|
-
if (!text.trim()) throw new Error(`${name} did not contain any text.`);
|
|
694
|
-
if (format === "text" && looksLikeLog(lines)) format = "log";
|
|
695
|
-
measured = await measureText(text, slicer);
|
|
696
|
-
if (measured.utf8 > maxTextBytes) throw tooMuchText(name, maxTextBytes);
|
|
697
|
-
outline = await buildOutlineInSlices(lines, format, slicer);
|
|
698
|
-
logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
|
|
699
|
-
quality = await measureQuality(lines, format, slicer);
|
|
700
|
-
// The line index, so that the text can be read by range: a few bytes a line, built from the
|
|
701
|
-
// UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
|
|
702
|
-
// then loads whole, so that switching to reading by range finds it ready.
|
|
703
|
-
index = typeof store.putIndex === "function"
|
|
704
|
-
? await buildTextIndexInSlices(text, slicer, progress && ((done, total) => progress.report("index", done, total, "characters")))
|
|
705
|
-
: undefined;
|
|
706
|
-
progress?.end();
|
|
707
|
-
signal.throwIfAborted();
|
|
708
|
-
} finally {
|
|
709
|
-
dispose();
|
|
710
|
-
}
|
|
711
|
-
const created = now();
|
|
712
|
-
const expires = created.getTime() + ttlMs;
|
|
713
|
-
const keepOriginal = keeps(format);
|
|
714
|
-
const meta: DocumentMeta = {
|
|
715
|
-
id: `doc_${randomUUID().replaceAll("-", "")}`,
|
|
716
|
-
...(input.owner !== undefined ? { owner: input.owner } : {}),
|
|
717
|
-
name,
|
|
718
|
-
mimeType,
|
|
719
|
-
format,
|
|
720
|
-
bytes: input.bytes.byteLength,
|
|
721
|
-
textBytes: measured.utf8,
|
|
722
|
-
jsonBytes: measured.json,
|
|
723
|
-
characters: text.length,
|
|
724
|
-
lines: lines.length,
|
|
725
|
-
estimatedTokens: measured.tokens,
|
|
726
|
-
wrappedLines: wrapped,
|
|
727
|
-
...(pages ? { pages } : {}),
|
|
728
|
-
...reading,
|
|
729
|
-
...(keepOriginal ? { originalKept: true } : {}),
|
|
730
|
-
outline,
|
|
731
|
-
...(logProfile ? { logProfile } : {}),
|
|
732
|
-
...quality,
|
|
733
|
-
createdAt: created.toISOString(),
|
|
734
|
-
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
735
|
-
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
736
|
-
};
|
|
737
|
-
const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
|
|
738
|
-
? serializeTextIndex(index)
|
|
739
|
-
: undefined;
|
|
740
|
-
// Each write is reported once done. What the listener of the events throws is not the store's failure.
|
|
741
|
-
const writes = (keepOriginal ? 1 : 0) + (savedIndex ? 1 : 0) + 1;
|
|
742
|
-
let written = 0;
|
|
743
|
-
let listenerFailed: { error: unknown } | undefined;
|
|
744
|
-
const wrote = (last: boolean) => {
|
|
745
|
-
if (!progress) return;
|
|
718
|
+
* What a document contributes to the prompt: its text, or its card. Undefined when it is gone
|
|
719
|
+
* by now. A copy found to disagree with the store is opened again once.
|
|
720
|
+
*/
|
|
721
|
+
async function block(id: string, meta: DocumentMeta, caller: Caller, whole: boolean, viewable: boolean, wholeRead: WholeRead): Promise<string | undefined> {
|
|
722
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
723
|
+
const document = await load(id, caller, attempt === 0 ? meta : undefined);
|
|
724
|
+
if (!document) return undefined;
|
|
725
|
+
let text: string;
|
|
746
726
|
try {
|
|
747
|
-
|
|
748
|
-
|
|
727
|
+
text = whole
|
|
728
|
+
? renderInline(document.meta, await document.readText())
|
|
729
|
+
: renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, wholeRead);
|
|
749
730
|
} catch (error) {
|
|
750
|
-
|
|
731
|
+
// The text is gone while its metadata is still there (removed outside the library): the
|
|
732
|
+
// same as missing. It was a plain Error, which failed the whole question.
|
|
733
|
+
if (error instanceof DocumentGoneError) return undefined;
|
|
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;
|
|
751
737
|
throw error;
|
|
752
738
|
}
|
|
753
|
-
|
|
754
|
-
try {
|
|
755
|
-
// The files first, the document last: a document is there once its metadata is.
|
|
756
|
-
if (keepOriginal) {
|
|
757
|
-
await store.putOriginal!(meta.id, input.bytes);
|
|
758
|
-
wrote(false);
|
|
759
|
-
}
|
|
760
|
-
if (savedIndex) {
|
|
761
|
-
await store.putIndex!(meta.id, savedIndex);
|
|
762
|
-
wrote(false);
|
|
763
|
-
}
|
|
764
|
-
await store.put({ meta, text });
|
|
765
|
-
wrote(true);
|
|
766
|
-
} catch (error) {
|
|
767
|
-
// Do not leave a file of up to the upload limit, or a part of one, behind for a document
|
|
768
|
-
// that does not exist.
|
|
769
|
-
await store.delete(meta.id).catch(() => undefined);
|
|
770
|
-
if (listenerFailed?.error !== error) {
|
|
771
|
-
noteStoreWriteFailure(error);
|
|
772
|
-
storeFailed();
|
|
773
|
-
}
|
|
774
|
-
throw error;
|
|
739
|
+
return await stillOpened(document, caller) ? text : undefined;
|
|
775
740
|
}
|
|
776
|
-
return
|
|
741
|
+
return undefined;
|
|
777
742
|
}
|
|
778
743
|
|
|
779
744
|
return {
|
|
780
745
|
budget,
|
|
781
746
|
budgetFor,
|
|
782
747
|
maxUploadBytes,
|
|
748
|
+
access: rules,
|
|
783
749
|
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
// What the caller's listener throws is passed on as it is, not told as a file that could not be read.
|
|
787
|
-
let listenerFailure: { error: unknown } | undefined;
|
|
788
|
-
const listener = input?.onEvent;
|
|
789
|
-
const events = new EventEmitter<IngestEvent>(input?.runId ?? newRunId("ing"), listener && ((event: IngestEvent) => {
|
|
790
|
-
try {
|
|
791
|
-
listener(event);
|
|
792
|
-
} catch (error) {
|
|
793
|
-
listenerFailure ??= { error };
|
|
794
|
-
throw error;
|
|
795
|
-
}
|
|
796
|
-
}));
|
|
797
|
-
let storeFailed = false;
|
|
798
|
-
try {
|
|
799
|
-
if (events.active) events.emit({ type: "ingest.start", ...startOf(input) });
|
|
800
|
-
checkOwner(input.owner);
|
|
801
|
-
const name = cleanFileName(input.name);
|
|
802
|
-
const mimeType = input.mimeType?.trim() || "application/octet-stream";
|
|
803
|
-
// A file whose name and type say nothing is known by its bytes: a PDF, an Office file, a page.
|
|
804
|
-
const format = detectFormat(name, mimeType, input.bytes instanceof Uint8Array ? input.bytes : undefined);
|
|
805
|
-
// Progress is worked out only for someone who listens.
|
|
806
|
-
const progress = events.active ? new IngestProgress(events) : undefined;
|
|
807
|
-
let meta: DocumentMeta;
|
|
808
|
-
try {
|
|
809
|
-
meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true));
|
|
810
|
-
} catch (error) {
|
|
811
|
-
// A store that failed, and a caller that gave up (its own reason), are passed on as they
|
|
812
|
-
// are; a file that could not be read is told with a code.
|
|
813
|
-
if (storeFailed || (input.signal?.aborted && error === input.signal.reason) || isStoreWriteFailure(error) || (listenerFailure && error === listenerFailure.error)) throw error;
|
|
814
|
-
throw toIngestError(error);
|
|
815
|
-
}
|
|
816
|
-
try {
|
|
817
|
-
events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
|
|
818
|
-
} catch (error) {
|
|
819
|
-
// The caller never gets the id: the document goes, as on a throw of the listener a moment earlier.
|
|
820
|
-
await store.delete(meta.id).catch(() => undefined);
|
|
821
|
-
forget(meta.id);
|
|
822
|
-
throw error;
|
|
823
|
-
}
|
|
824
|
-
return meta;
|
|
825
|
-
} catch (error) {
|
|
826
|
-
// A store's own error may name a host or a path, whatever it is: the event, which a browser
|
|
827
|
-
// may see, says only that the document could not be stored.
|
|
828
|
-
events.emit({ type: "ingest.error", error: storeFailed ? { message: STORE_WRITE_FAILED } : eventErrorOf(error) });
|
|
829
|
-
throw error;
|
|
830
|
-
}
|
|
750
|
+
ingest(input) {
|
|
751
|
+
return ingestDocument(ingestContext, input);
|
|
831
752
|
},
|
|
832
753
|
|
|
833
|
-
getMeta
|
|
754
|
+
async getMeta(id, access) {
|
|
755
|
+
return metaFor(id, callerOf(access, rules));
|
|
756
|
+
},
|
|
834
757
|
|
|
835
758
|
async getOriginal(id, access) {
|
|
836
|
-
const
|
|
837
|
-
|
|
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;
|
|
838
764
|
},
|
|
839
765
|
|
|
840
766
|
async delete(id, access) {
|
|
841
|
-
|
|
767
|
+
const caller = callerOf(access, rules);
|
|
768
|
+
if (!await metaFor(id, caller)) return false;
|
|
842
769
|
forget(id);
|
|
843
|
-
return
|
|
770
|
+
return storeCall("delete", () => store.delete(id, caller.context));
|
|
844
771
|
},
|
|
845
772
|
|
|
846
|
-
async sweep() {
|
|
847
|
-
|
|
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)));
|
|
848
778
|
},
|
|
849
779
|
|
|
850
780
|
async prepare(ids, base, access) {
|
|
781
|
+
const caller = callerOf(access, rules);
|
|
851
782
|
const budget = budgetFor(access?.budget);
|
|
852
783
|
const analysis = access?.wholeDocumentAnalysis !== false;
|
|
853
784
|
const unique = [...new Set(ids)];
|
|
854
785
|
let documents: DocumentMeta[] = [];
|
|
855
786
|
const missing: string[] = [];
|
|
856
787
|
for (const id of unique) {
|
|
857
|
-
// A document
|
|
858
|
-
// read at all.
|
|
859
|
-
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);
|
|
860
791
|
if (meta) documents.push(meta);
|
|
861
792
|
else missing.push(id);
|
|
862
793
|
}
|
|
@@ -866,15 +797,13 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
866
797
|
const plan = planDocuments(documents, budget, base);
|
|
867
798
|
const inline = new Set(plan.inline.map((meta) => meta.id));
|
|
868
799
|
// Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
|
|
869
|
-
const viewable = access?.viewPages
|
|
870
|
-
? documents.filter((meta) => meta.format === "pdf" && meta.originalKept)
|
|
871
|
-
: [];
|
|
800
|
+
const viewable = access?.viewPages ? documents.filter(viewableMeta) : [];
|
|
872
801
|
const shown = new Set(viewable.map((meta) => meta.id));
|
|
873
802
|
const blocks = new Map<string, string>();
|
|
874
803
|
const gone: string[] = [];
|
|
875
804
|
for (const meta of documents) {
|
|
876
805
|
const wholeRead = !analysis ? "not_offered" : canBeReadWhole(meta, budget) ? "offered" : "too_large";
|
|
877
|
-
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);
|
|
878
807
|
if (text === undefined) gone.push(meta.id);
|
|
879
808
|
else blocks.set(meta.id, text);
|
|
880
809
|
}
|
|
@@ -890,30 +819,51 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
890
819
|
},
|
|
891
820
|
|
|
892
821
|
tools(documents, toolOptions = {}) {
|
|
893
|
-
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;
|
|
894
829
|
const budget = budgetFor(overrides);
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
//
|
|
899
|
-
//
|
|
900
|
-
|
|
901
|
-
|
|
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);
|
|
902
840
|
// The metadata the store holds now, not that of a copy kept in memory.
|
|
903
841
|
const checkedLoad = async (id: string) => {
|
|
904
|
-
const
|
|
905
|
-
|
|
842
|
+
const caller = callerFor(id);
|
|
843
|
+
const meta = caller && await metaFor(id, caller);
|
|
844
|
+
return meta ? load(id, caller, meta) : undefined;
|
|
906
845
|
};
|
|
907
|
-
const checkedOriginal =
|
|
908
|
-
const
|
|
909
|
-
|
|
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;
|
|
910
855
|
});
|
|
911
856
|
return createDocumentTools({
|
|
912
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
|
+
},
|
|
913
863
|
documentIds: documents.map((meta) => meta.id),
|
|
914
864
|
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
|
|
915
865
|
budget,
|
|
916
|
-
...(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 } : {}),
|
|
917
867
|
// `analyze_whole_document` is declared only when it can read at least one of the documents.
|
|
918
868
|
wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
|
|
919
869
|
// `aggregate_table` only when one may hold a table.
|
|
@@ -922,4 +872,13 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
922
872
|
});
|
|
923
873
|
},
|
|
924
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
|
+
}
|
|
925
884
|
}
|