llm-large-files 0.8.2 → 0.10.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 +981 -0
- package/README.md +22 -17
- package/dist/access.d.ts +128 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +234 -0
- package/dist/access.js.map +1 -0
- package/dist/aggregate.d.ts +6 -0
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +86 -13
- package/dist/aggregate.js.map +1 -1
- package/dist/analyze.d.ts +4 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +2 -2
- package/dist/analyze.js.map +1 -1
- package/dist/answer-info.d.ts +26 -0
- package/dist/answer-info.d.ts.map +1 -0
- package/dist/answer-info.js +32 -0
- package/dist/answer-info.js.map +1 -0
- package/dist/anthropic/adapter.d.ts +5 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +35 -10
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +159 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +743 -113
- 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/citations.d.ts +36 -0
- package/dist/citations.d.ts.map +1 -0
- package/dist/citations.js +291 -0
- package/dist/citations.js.map +1 -0
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +70 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +253 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +74 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +104 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +57 -13
- 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 +35 -5
- 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 +52 -36
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +54 -7
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +152 -41
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +38 -53
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -25
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +59 -11
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +33 -7
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +39 -5
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +70 -9
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +53 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +100 -50
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +4 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/http.d.ts +41 -3
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +40 -2
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +13 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -5
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +78 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +893 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +295 -33
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +458 -650
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +176 -10
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +807 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +79 -6
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +80 -4
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +247 -14
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +491 -227
- 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 +19 -4
- 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 +106 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +378 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +6 -4
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +9 -7
- package/dist/node/sse.js.map +1 -1
- package/dist/openai/adapter.d.ts +5 -1
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +53 -12
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +2 -1
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +5 -2
- package/dist/output-limit.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/pdf-outline.d.ts +71 -0
- package/dist/pdf-outline.d.ts.map +1 -0
- package/dist/pdf-outline.js +414 -0
- package/dist/pdf-outline.js.map +1 -0
- package/dist/plan.d.ts +137 -7
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +248 -26
- package/dist/plan.js.map +1 -1
- package/dist/prepare.d.ts +50 -0
- package/dist/prepare.d.ts.map +1 -0
- package/dist/prepare.js +207 -0
- package/dist/prepare.js.map +1 -0
- package/dist/ranged.d.ts +16 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +56 -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/search.d.ts +7 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +72 -10
- package/dist/search.js.map +1 -1
- 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 +126 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +655 -141
- 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 +47 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +440 -71
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +165 -14
- package/dist/types.d.ts.map +1 -1
- package/dist/whole-cost.d.ts +37 -0
- package/dist/whole-cost.d.ts.map +1 -0
- package/dist/whole-cost.js +46 -0
- package/dist/whole-cost.js.map +1 -0
- package/docs/README.md +21 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +17 -10
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +147 -42
- package/docs/guides/deployment.md +380 -86
- package/docs/guides/errors-and-reliability.md +317 -67
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +60 -16
- package/docs/guides/pdfs.md +219 -36
- package/docs/guides/storage.md +676 -145
- package/docs/guides/testing.md +149 -129
- package/docs/guides/vertex-and-gemini.md +169 -57
- package/docs/guides/web-app.md +318 -80
- package/docs/how-it-works.md +155 -30
- package/docs/measurements.md +215 -13
- package/docs/publishing.md +185 -37
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +415 -47
- package/docs/reference/errors-and-retries.md +194 -14
- package/docs/reference/events.md +77 -27
- package/docs/reference/gemini.md +252 -87
- package/docs/reference/library.md +886 -178
- package/docs/reference/node.md +659 -111
- package/docs/reference/openai.md +21 -10
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +285 -30
- package/docs/security.md +404 -78
- package/docs/troubleshooting.md +151 -70
- package/docs/upgrading-0.10.md +472 -0
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +16 -3
- package/src/access.ts +267 -0
- package/src/aggregate.ts +92 -14
- package/src/analyze.ts +2 -2
- package/src/answer-info.ts +45 -0
- package/src/anthropic/adapter.ts +40 -11
- package/src/ask.ts +866 -115
- package/src/cache.ts +20 -5
- package/src/citations.ts +294 -0
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +290 -0
- package/src/errors.ts +131 -15
- package/src/events.ts +112 -24
- package/src/evidence.ts +35 -5
- package/src/extract.ts +56 -34
- package/src/gemini/adapter.ts +196 -43
- package/src/gemini/chat.ts +63 -78
- package/src/gemini/endpoints.ts +89 -16
- package/src/gemini/errors.ts +74 -11
- package/src/gemini/generate.ts +147 -57
- package/src/gemini/index.ts +4 -4
- package/src/http.ts +65 -4
- package/src/index.ts +13 -8
- package/src/ingest.ts +958 -0
- package/src/library.ts +711 -651
- package/src/map-reduce.ts +858 -70
- package/src/model.ts +113 -9
- package/src/node/handlers.ts +709 -221
- package/src/node/index.ts +14 -2
- package/src/node/ingest-child.ts +24 -6
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +379 -0
- package/src/node/sse.ts +9 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-layout.ts +69 -11
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +48 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/search.ts +69 -13
- package/src/source.ts +178 -0
- package/src/stores.ts +702 -142
- 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 +461 -73
- package/src/types.ts +151 -14
- package/src/whole-cost.ts +64 -0
package/src/library.ts
CHANGED
|
@@ -1,37 +1,42 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import {
|
|
2
|
+
callerOf, checkMetaVersion, checkStuck, documentContext, isTimeLimit, mayUse, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext, storeTimeout,
|
|
3
|
+
stuckCalls, type AccessRules, type Caller,
|
|
4
|
+
} from "./access.js";
|
|
3
5
|
import { givenBudget, resolveBudget, type ModelLimits } from "./budget.js";
|
|
4
6
|
import { DocumentCache, documentVersion, type Sized } from "./cache.js";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
7
|
+
import type { DocumentStoreOperation } from "./errors.js";
|
|
8
|
+
import type { IngestEvent } from "./events.js";
|
|
9
|
+
import { until } from "./http.js";
|
|
10
|
+
import { ingestDocument, LONGEST_TIMER_MS, type IngestContext } from "./ingest.js";
|
|
8
11
|
import { Limiter } from "./limiter.js";
|
|
12
|
+
import { canBeReadWhole, TABLE_FORMATS } from "./plan.js";
|
|
13
|
+
import { prepareDocuments, type PrepareContext } from "./prepare.js";
|
|
14
|
+
import { openRangedDocument, pieceKey, RangedDocument, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
|
|
15
|
+
import { SearchableDocument, type DocumentSource } from "./search.js";
|
|
9
16
|
import { TimeSlicer } from "./pause.js";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import { DOCUMENT_ID_PATTERN } from "./stores.js";
|
|
15
|
-
import { buildTextIndexInSlices, canSerialize, serializeTextIndex } from "./text-index.js";
|
|
16
|
-
import { measureText, prepareText, removeInvisible, sliceWhole, wellFormed } from "./text.js";
|
|
17
|
+
import { checkScope } from "./scope.js";
|
|
18
|
+
import { isSha256, sha256InSlices } from "./source.js";
|
|
19
|
+
import { APP_DOCUMENT_ID_PATTERN } from "./stores.js";
|
|
20
|
+
import { wellFormed } from "./text.js";
|
|
17
21
|
import type { RetryOptions } from "./retry.js";
|
|
18
|
-
import { createDocumentTools } from "./tools.js";
|
|
22
|
+
import { createDocumentTools, type PageLookTurns } from "./tools.js";
|
|
19
23
|
import type {
|
|
20
24
|
Budget,
|
|
25
|
+
DocumentContext,
|
|
21
26
|
DocumentFormat,
|
|
22
27
|
DocumentMeta,
|
|
28
|
+
DocumentScope,
|
|
23
29
|
DocumentStore,
|
|
24
|
-
DocumentSummary,
|
|
25
|
-
ExtractedText,
|
|
26
|
-
ExtractProgress,
|
|
27
30
|
Extractor,
|
|
28
31
|
GenerateText,
|
|
29
32
|
PreparedContext,
|
|
30
33
|
ProgressListener,
|
|
34
|
+
ToolName,
|
|
31
35
|
ToolSet,
|
|
32
36
|
} from "./types.js";
|
|
33
37
|
|
|
34
38
|
export { DEFAULT_BUDGET } from "./budget.js";
|
|
39
|
+
export { checkOwner, cleanFileName, cleanMimeType, NEVER_EXPIRES, toDocumentSummary } from "./ingest.js";
|
|
35
40
|
|
|
36
41
|
export type LargeFilesOptions = {
|
|
37
42
|
/** Where extracted text is kept: `new FileDocumentStore(dir)`, `new MemoryDocumentStore()`, or your own. */
|
|
@@ -71,11 +76,19 @@ export type LargeFilesOptions = {
|
|
|
71
76
|
/** Override or add text extractors per format. */
|
|
72
77
|
extractors?: Partial<Record<DocumentFormat, Extractor>>;
|
|
73
78
|
/**
|
|
74
|
-
* Formats whose uploaded file is kept
|
|
75
|
-
*
|
|
76
|
-
*
|
|
79
|
+
* Formats whose uploaded file is kept, for example `["pdf"]`, so that `view_pages` can show its
|
|
80
|
+
* pages: as a copy in the store, next to its text (`putOriginal`), or, for an ingest with
|
|
81
|
+
* `IngestInput.original`, where the application keeps it (`originals`). Empty by default: a kept
|
|
82
|
+
* file takes disk space, up to the upload limit, until the document expires. A store without
|
|
83
|
+
* `putOriginal` keeps no copies.
|
|
77
84
|
*/
|
|
78
85
|
keepOriginals?: DocumentFormat[];
|
|
86
|
+
/**
|
|
87
|
+
* Reads the uploaded files that the application keeps itself (`IngestInput.original`), in place
|
|
88
|
+
* of a copy in the store: `fileOriginals(root)`, of "llm-large-files/node", reads them from a
|
|
89
|
+
* folder. A file read back is checked against the size and SHA-256 it had at ingest. New in 0.9.0.
|
|
90
|
+
*/
|
|
91
|
+
originals?: OriginalsReader;
|
|
79
92
|
/**
|
|
80
93
|
* A PDF without any text (a scan) has nothing to search, and was always refused. When its
|
|
81
94
|
* original is kept, its pages can be shown to the model instead, so one of up to this many pages
|
|
@@ -118,10 +131,94 @@ export type LargeFilesOptions = {
|
|
|
118
131
|
* not finish sooner. `Infinity` for no limit (as before 0.8.2). Defaults to 2. New in 0.8.2.
|
|
119
132
|
*/
|
|
120
133
|
maxConcurrentIngests?: number;
|
|
134
|
+
/**
|
|
135
|
+
* How many looks at pages (`view_pages`) run at once in this library, over all its questions.
|
|
136
|
+
* The others wait their turn, in order, before the PDF is loaded. A look parses the whole PDF on
|
|
137
|
+
* the one thread the questions share: more at once do not finish sooner, they only hold more
|
|
138
|
+
* memory (six at once held 352 MB more than one). `Infinity` for no limit (as before 0.9.0).
|
|
139
|
+
* Defaults to 1. A look reads its PDF from the store within `ingestTimeoutMs` (2 minutes when
|
|
140
|
+
* that is 0): past it, the turn goes back and the model is told that the file could not be read
|
|
141
|
+
* in time. New in 0.9.0.
|
|
142
|
+
*/
|
|
143
|
+
maxConcurrentPageLooks?: number;
|
|
144
|
+
/**
|
|
145
|
+
* How long a look at pages waits for its turn, in milliseconds. Past it, the model is told that
|
|
146
|
+
* the server is busy and to answer from the text, and the question gets a "page_looks_busy"
|
|
147
|
+
* notice. `Infinity` waits without end; 0 does not wait. Defaults to 30,000. New in 0.9.0.
|
|
148
|
+
*/
|
|
149
|
+
pageLookWaitMs?: number;
|
|
150
|
+
/**
|
|
151
|
+
* Every call must name its owner: `ingest`, `getMeta`, `getOriginal`, `delete`, `prepare`,
|
|
152
|
+
* `askWithFiles` (and `askStream`, `askGemini`), and `tools`, which then needs `access`. A call
|
|
153
|
+
* without one throws a TypeError ("owner is required: requireOwner is on"), and a document stored
|
|
154
|
+
* without an owner reads as missing. For a server where every document belongs to a signed-in
|
|
155
|
+
* user: a call that forgot the owner fails, rather than sees every document without one.
|
|
156
|
+
* Defaults to false. New in 0.9.0.
|
|
157
|
+
*/
|
|
158
|
+
requireOwner?: boolean;
|
|
159
|
+
/**
|
|
160
|
+
* The same for scopes (`DocumentScope`): every call must name its scope, and a document stored
|
|
161
|
+
* without one reads as missing. `sweep` without a scope is still allowed: it is upkeep of the
|
|
162
|
+
* store, not a user's access. Defaults to false. New in 0.9.0.
|
|
163
|
+
*/
|
|
164
|
+
requireScope?: boolean;
|
|
165
|
+
/**
|
|
166
|
+
* The most time one store call may take, in milliseconds: a look-up of a document (`getMeta`), a
|
|
167
|
+
* read of its text (whole, or a range of it), of its index or of its original, and a delete.
|
|
168
|
+
* Past it, the call fails with a `DocumentStoreError` of code "ETIMEDOUT" (status 503): the call
|
|
169
|
+
* itself goes on, as nothing can stop it, and counts as stuck until it ends. A call inside a
|
|
170
|
+
* question's tool call ends the question. Defaults to 30,000; 0 sets no limit, and so does a time
|
|
171
|
+
* past what a timer can wait. Keep it above the time your store takes to read the largest text
|
|
172
|
+
* loaded whole (`wholeDocumentBytes`). `ingest` keeps its own limits (`ingestTimeoutMs`), past
|
|
173
|
+
* which its store calls count as stuck too, and `sweep` has `sweepTimeoutMs`. New in 0.10.0.
|
|
174
|
+
*/
|
|
175
|
+
storeTimeoutMs?: number;
|
|
176
|
+
/**
|
|
177
|
+
* How many calls of this process may be stuck (past their time limit, and not ended) before every
|
|
178
|
+
* new store call of this library, those of `ingest` included, fails at once, without calling the
|
|
179
|
+
* store, with code "STORE_STUCK" (status 503). A store call is stuck past `storeTimeoutMs`, and
|
|
180
|
+
* one of `ingest` past the time it gives its store calls (`ingestTimeoutMs`, 2 minutes when that
|
|
181
|
+
* is 0). The count is the process's, as the threads of libuv are: a store call that does not
|
|
182
|
+
* answer holds one of them, and with all of them held every file call and DNS look-up of the
|
|
183
|
+
* process waits. Defaults to half of `UV_THREADPOOL_SIZE` (4 when it is not set), read when the
|
|
184
|
+
* library is made as libuv reads it (an empty value, 0, or one without leading digits is 1
|
|
185
|
+
* thread), and at least 1: 2 by default, 16 with 32 threads. `Infinity` refuses nothing. New in
|
|
186
|
+
* 0.10.0.
|
|
187
|
+
*/
|
|
188
|
+
maxStuckStoreCalls?: number;
|
|
189
|
+
/**
|
|
190
|
+
* The most time one `sweep` may take, in milliseconds: past it, `sweep` fails with a
|
|
191
|
+
* `DocumentStoreError` of code "ETIMEDOUT", and the sweep goes on. A sweep never counts as a stuck
|
|
192
|
+
* call. Defaults to 0: no limit. New in 0.10.0.
|
|
193
|
+
*/
|
|
194
|
+
sweepTimeoutMs?: number;
|
|
121
195
|
/** Clock override, for tests. */
|
|
122
196
|
now?: () => Date;
|
|
123
197
|
};
|
|
124
198
|
|
|
199
|
+
/**
|
|
200
|
+
* Reads the uploaded files that the application keeps itself (`LargeFilesOptions.originals`). New
|
|
201
|
+
* in 0.9.0.
|
|
202
|
+
*/
|
|
203
|
+
export type OriginalsReader = {
|
|
204
|
+
/**
|
|
205
|
+
* The bytes of the file at `ref` (`IngestInput.original.ref`), or undefined when it is not
|
|
206
|
+
* there. `context` is that of the call (its scope and owner), with the document's `id`, and
|
|
207
|
+
* `bytes`, the size the file had at ingest: a reader may stop one byte past it, as a file of
|
|
208
|
+
* another size has changed. What it throws is passed on as a `DocumentStoreError` (operation
|
|
209
|
+
* "read"), with its error as `cause`, as a store's errors are.
|
|
210
|
+
*/
|
|
211
|
+
read(ref: string, context: OriginalReadContext): Promise<Uint8Array | undefined>;
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
/** What `OriginalsReader.read` is told of the call. New in 0.9.0. */
|
|
215
|
+
export type OriginalReadContext = DocumentContext & {
|
|
216
|
+
/** The ID of the document whose file is read. */
|
|
217
|
+
readonly id: string;
|
|
218
|
+
/** The size of the file when it was ingested. */
|
|
219
|
+
readonly bytes: number;
|
|
220
|
+
};
|
|
221
|
+
|
|
125
222
|
export type IngestInput = {
|
|
126
223
|
name: string;
|
|
127
224
|
mimeType?: string;
|
|
@@ -144,10 +241,73 @@ export type IngestInput = {
|
|
|
144
241
|
onEvent?: (event: IngestEvent) => void;
|
|
145
242
|
/** The `runId` of those events. Defaults to one made for the ingest ("ing_…"). */
|
|
146
243
|
runId?: string;
|
|
244
|
+
/**
|
|
245
|
+
* The document's ID, chosen by the application, such as the ID of its upload: lowercase letters,
|
|
246
|
+
* digits, "_" and "-", up to 64 characters, starting with a letter or a digit
|
|
247
|
+
* (`APP_DOCUMENT_ID_PATTERN`). Another ID is a TypeError. The model sees it, so it must hold no
|
|
248
|
+
* personal data. Without it, an ID is made ("doc_" and 32 hex digits), as before. New in 0.9.0.
|
|
249
|
+
*/
|
|
250
|
+
id?: string;
|
|
251
|
+
/**
|
|
252
|
+
* What to do when a document with `id` is already stored, as the store sees it for this scope.
|
|
253
|
+
* "fail" (the default) throws an `IngestError` with code "exists" (status 409). "replace"
|
|
254
|
+
* deletes it, then stores the new one: only a document of the same owner and scope; another is
|
|
255
|
+
* "exists" too, even when its text is gone, unless it has expired. Over a store that keeps no
|
|
256
|
+
* scopes apart, the check spans every scope, so one chat cannot write over another's document.
|
|
257
|
+
* While an ingest of this library stores `id`, another ingest of it is "exists", whatever this
|
|
258
|
+
* says. New in 0.9.0.
|
|
259
|
+
*/
|
|
260
|
+
ifExists?: "fail" | "replace";
|
|
261
|
+
/**
|
|
262
|
+
* Where the document belongs, such as [userId, chatId] (`DocumentScope`). It is passed to every
|
|
263
|
+
* store call, and kept in `DocumentMeta.scope`: only a caller of the same scope may use the
|
|
264
|
+
* document. A scope that is not valid is a `DocumentScopeError`. New in 0.9.0.
|
|
265
|
+
*/
|
|
266
|
+
scope?: DocumentScope;
|
|
267
|
+
/**
|
|
268
|
+
* Where the application keeps the uploaded file: `ref`, up to 1,024 characters, such as a path
|
|
269
|
+
* under the folder of `fileOriginals`. When the format is kept (`keepOriginals`), the library
|
|
270
|
+
* reads the file from there (`LargeFilesOptions.originals`) instead of keeping a copy in the
|
|
271
|
+
* store, and records `DocumentMeta.original`: the ref, and the size and SHA-256 of the file, to
|
|
272
|
+
* tell when it has changed. The ref is never sent to the model, nor in a summary. An event holds
|
|
273
|
+
* it only with `AskOptions.eventResults: true`, in the full plan of `run.finish` and `run.error`.
|
|
274
|
+
* Without `LargeFilesOptions.originals`, it is a TypeError. The library never writes, moves or
|
|
275
|
+
* deletes the file: `delete` leaves it. New in 0.9.0.
|
|
276
|
+
*/
|
|
277
|
+
original?: { ref: string };
|
|
147
278
|
};
|
|
148
279
|
|
|
149
|
-
/**
|
|
150
|
-
export type
|
|
280
|
+
/** A file to ingest from where it is, rather than from bytes in memory (`IngestFromSource`). New in 0.9.0. */
|
|
281
|
+
export type IngestSource = { path: string };
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* An ingest of a file from a path: `IngestInput` with `source` in place of `bytes`. Before the
|
|
285
|
+
* ingest's turn, the path is looked at with `lstat`, and nothing of it is read: a link is refused,
|
|
286
|
+
* not followed, and so is anything that is not a file; an empty file, or one larger than
|
|
287
|
+
* `maxUploadBytes`, is refused at once. When its name and type say nothing of its format, only the
|
|
288
|
+
* parts of it that tell are read (its first KB; for a ZIP its first 64 KB and its last MB). At its
|
|
289
|
+
* turn the file is read once, up to `maxUploadBytes + 1` bytes, so that one that has grown is
|
|
290
|
+
* refused, and its bytes are let go once its text is read. An extractor that reads paths
|
|
291
|
+
* (`Extractor.readsPath`, as the isolated readers do) reads it instead, and the server does not.
|
|
292
|
+
* The library never writes, moves or deletes the file. New in 0.9.0.
|
|
293
|
+
*/
|
|
294
|
+
export type IngestFromSource = Omit<IngestInput, "bytes"> & { source: IngestSource; bytes?: never };
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Access options. When a document has an owner, only that owner can use it. `scope`, new in 0.9.0:
|
|
298
|
+
* the scope of the caller; a document stored with a scope serves only a caller with the same one.
|
|
299
|
+
*/
|
|
300
|
+
export type AccessOptions = {
|
|
301
|
+
owner?: string;
|
|
302
|
+
scope?: DocumentScope;
|
|
303
|
+
/**
|
|
304
|
+
* Ends this caller's waits for the store, with the signal's reason: never a store call that other
|
|
305
|
+
* callers wait on too (one opening of a document serves every caller of its scope), and never the
|
|
306
|
+
* store call itself, which nothing can stop. Read by `getMeta`, `getOriginal`, `delete`,
|
|
307
|
+
* `prepare`, `toolsFor`, and `tools` with `access`. New in 0.10.0.
|
|
308
|
+
*/
|
|
309
|
+
signal?: AbortSignal;
|
|
310
|
+
};
|
|
151
311
|
|
|
152
312
|
export type PrepareOptions = AccessOptions & {
|
|
153
313
|
/**
|
|
@@ -168,9 +328,31 @@ export type PrepareOptions = AccessOptions & {
|
|
|
168
328
|
* `wholeDocumentAnalysis: false`.
|
|
169
329
|
*/
|
|
170
330
|
wholeDocumentAnalysis?: boolean;
|
|
331
|
+
/**
|
|
332
|
+
* Number the lines of the documents sent whole, as the tools number them ("12| text"), and plan
|
|
333
|
+
* them at that size. Defaults to false here, so that `prepare` gives the blocks of 0.9;
|
|
334
|
+
* `askWithFiles` asks for true unless `AskOptions.numberInline` is false. A value that is not
|
|
335
|
+
* true or false is a TypeError. New in 0.10.0.
|
|
336
|
+
*/
|
|
337
|
+
numberInline?: boolean;
|
|
338
|
+
/**
|
|
339
|
+
* "tools": list the documents sent whole whose tables the tools can count in `toolable`, with
|
|
340
|
+
* their document_id in the first line of their block; "text": as in 0.9. Defaults to "text"
|
|
341
|
+
* here; `askWithFiles` asks for "tools" unless `AskOptions.inlineTables` is "text". Another value
|
|
342
|
+
* is a TypeError. New in 0.10.0.
|
|
343
|
+
*/
|
|
344
|
+
inlineTables?: "tools" | "text";
|
|
171
345
|
};
|
|
172
346
|
|
|
173
347
|
export type ToolOptions = {
|
|
348
|
+
/**
|
|
349
|
+
* Who uses these tools. With it, every call of the tools asks the store for the document with
|
|
350
|
+
* this owner and scope, and checks the owner and scope the store holds against them: metadata
|
|
351
|
+
* made by hand, or handed in for another user, reads nothing. Without it, as before 0.9.0: each
|
|
352
|
+
* document is checked against the owner and scope it was handed in with. `askWithFiles` always
|
|
353
|
+
* passes it. Under `requireOwner` or `requireScope` it is required. New in 0.9.0.
|
|
354
|
+
*/
|
|
355
|
+
access?: AccessOptions;
|
|
174
356
|
/** Enables `analyze_whole_document`, which reads the entire file in parts. */
|
|
175
357
|
generate?: GenerateText;
|
|
176
358
|
/** Progress of whole-document reads, for status messages. */
|
|
@@ -201,6 +383,19 @@ export type ToolOptions = {
|
|
|
201
383
|
* PDFs that are not searched because their text is already in the prompt.
|
|
202
384
|
*/
|
|
203
385
|
viewPages?: boolean | DocumentMeta[];
|
|
386
|
+
/**
|
|
387
|
+
* Declare exactly these tools, in the order the tool set declares them (search, read, overview,
|
|
388
|
+
* aggregate, analyze, view), in place of those the documents call for. A call of a tool that is
|
|
389
|
+
* not declared is not run, and a declared tool that cannot run (aggregate_table with no table,
|
|
390
|
+
* view_pages with no page to show) answers each call with its reason. `askWithFiles` declares
|
|
391
|
+
* the tools a question over a table sent whole needs. New in 0.10.0.
|
|
392
|
+
*/
|
|
393
|
+
declare?: readonly ToolName[];
|
|
394
|
+
/**
|
|
395
|
+
* The IDs of documents sent whole: `analyze_whole_document` refuses them, as they are shown in
|
|
396
|
+
* full, and `aggregate_table` says how to cite their lines (`cite`). New in 0.10.0.
|
|
397
|
+
*/
|
|
398
|
+
inline?: readonly string[];
|
|
204
399
|
};
|
|
205
400
|
|
|
206
401
|
export interface LargeFiles {
|
|
@@ -214,17 +409,37 @@ export interface LargeFiles {
|
|
|
214
409
|
budgetFor(overrides?: Partial<Budget>, limits?: ModelLimits): Budget;
|
|
215
410
|
readonly maxUploadBytes: number;
|
|
216
411
|
/**
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
412
|
+
* What the library requires of every call (`requireOwner`, `requireScope`), for code that serves
|
|
413
|
+
* it, such as the upload handlers. Optional, so that a `LargeFiles` of your own still compiles.
|
|
414
|
+
* New in 0.9.0.
|
|
415
|
+
*/
|
|
416
|
+
readonly access?: { readonly requireOwner: boolean; readonly requireScope: boolean };
|
|
417
|
+
/**
|
|
418
|
+
* Extracts, normalizes, profiles, and stores a file: from its bytes (`IngestInput`), or from a
|
|
419
|
+
* path (`IngestFromSource`, new in 0.9.0). Throws a user-readable Error on bad input.
|
|
420
|
+
* A store that fails to write is a `DocumentStoreError` (operation "write", status 503) since
|
|
421
|
+
* 0.9.0, with the store's own error as `cause`: log that one, and do not show its message to a
|
|
422
|
+
* user, as it may name a path, a host or a bucket. A path that is not there, a link or a folder
|
|
423
|
+
* is an error with the `code` of a system error (ENOENT, ELOOP, EISDIR), passed on as it is.
|
|
220
424
|
*/
|
|
221
|
-
ingest(input: IngestInput): Promise<DocumentMeta>;
|
|
425
|
+
ingest(input: IngestInput | IngestFromSource): Promise<DocumentMeta>;
|
|
222
426
|
getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
|
|
223
|
-
/**
|
|
427
|
+
/**
|
|
428
|
+
* The uploaded file itself, when it was kept (see `keepOriginals`): from the store, or from where
|
|
429
|
+
* the application keeps it (`IngestInput.original`, read by `LargeFilesOptions.originals`). Treat
|
|
430
|
+
* the bytes as read-only. Undefined too when, once the bytes are read, the store no longer
|
|
431
|
+
* describes the same document, or the bytes are not those of the upload: of another size, or
|
|
432
|
+
* another SHA-256 (0.9.0).
|
|
433
|
+
*/
|
|
224
434
|
getOriginal(id: string, access?: AccessOptions): Promise<Uint8Array | undefined>;
|
|
435
|
+
/** Deletes a document. A store that fails is a `DocumentStoreError` (operation "delete") since 0.9.0. */
|
|
225
436
|
delete(id: string, access?: AccessOptions): Promise<boolean>;
|
|
226
|
-
/**
|
|
227
|
-
|
|
437
|
+
/**
|
|
438
|
+
* Removes expired documents from the store: those of `scope`, or of every scope without one.
|
|
439
|
+
* Returns how many were removed. A store that fails is a `DocumentStoreError` (operation
|
|
440
|
+
* "sweep") since 0.9.0.
|
|
441
|
+
*/
|
|
442
|
+
sweep(options?: { scope?: DocumentScope }): Promise<number>;
|
|
228
443
|
/**
|
|
229
444
|
* Plans one model request: which documents go in whole and which become searchable cards.
|
|
230
445
|
* `base` is the size of everything else in the request (messages, system prompt, other files).
|
|
@@ -232,72 +447,56 @@ export interface LargeFiles {
|
|
|
232
447
|
prepare(ids: string[], base: { tokens: number; bytes: number }, options?: PrepareOptions): Promise<PreparedContext>;
|
|
233
448
|
/** Tools scoped to these documents. Pass `generate` to enable whole-document analysis. */
|
|
234
449
|
tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
|
|
450
|
+
/**
|
|
451
|
+
* Counters for metrics and alerts, read without a store call and without waiting. Optional, so
|
|
452
|
+
* that a `LargeFiles` of your own still compiles; the one `createLargeFiles` makes has it. New in
|
|
453
|
+
* 0.10.0.
|
|
454
|
+
*/
|
|
455
|
+
stats?(): LargeFilesStats;
|
|
456
|
+
/**
|
|
457
|
+
* Looks each ID up for `options.access`, as `getMeta` does, then makes the tools for the
|
|
458
|
+
* documents found (`tools`, with `access`): `missing` lists the others, those of another owner or
|
|
459
|
+
* scope included. A repeated ID counts once. Optional, so that a `LargeFiles` of your own still
|
|
460
|
+
* compiles; the one `createLargeFiles` makes has it. New in 0.10.0.
|
|
461
|
+
*/
|
|
462
|
+
toolsFor?(ids: string[], options: ToolOptions & { access: AccessOptions }): Promise<{ tools: ToolSet; missing: string[] }>;
|
|
235
463
|
}
|
|
236
464
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
/**
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
const ENCODING_NAME = /^[a-z0-9][a-z0-9._:-]{0,39}$/i;
|
|
465
|
+
/** What `files.stats()` counts: plain numbers, for metrics and alerts. New in 0.10.0. */
|
|
466
|
+
export type LargeFilesStats = {
|
|
467
|
+
/** Ingests doing their work, and those waiting their turn (`maxConcurrentIngests`). */
|
|
468
|
+
ingests: { active: number; waiting: number };
|
|
469
|
+
/** Scans of whole documents read by range, and those waiting their turn (`maxConcurrentScans`). */
|
|
470
|
+
scans: { active: number; waiting: number };
|
|
471
|
+
/** Looks at pages, and those waiting their turn (`maxConcurrentPageLooks`). */
|
|
472
|
+
pageLooks: { active: number; waiting: number };
|
|
473
|
+
/**
|
|
474
|
+
* What is kept in memory: its bytes, how many entries (documents, and pieces of documents read by
|
|
475
|
+
* range), and the most bytes they may take (`cacheBytes`).
|
|
476
|
+
*/
|
|
477
|
+
cache: { bytes: number; entries: number; maxBytes: number };
|
|
478
|
+
/**
|
|
479
|
+
* Calls of this process that ran past their time limit and have not settled: the store calls of
|
|
480
|
+
* every library (past `storeTimeoutMs`, or for `ingest` past `ingestTimeoutMs`), and the calls to
|
|
481
|
+
* the disk of the upload handlers (`uploadIdleTimeoutMs`).
|
|
482
|
+
*/
|
|
483
|
+
stuckStoreCalls: number;
|
|
484
|
+
/** This library's limit on them (`maxStuckStoreCalls`). */
|
|
485
|
+
maxStuckStoreCalls: number;
|
|
486
|
+
};
|
|
260
487
|
|
|
261
488
|
/**
|
|
262
|
-
*
|
|
263
|
-
*
|
|
489
|
+
* What `createLargeFiles` returns: a `LargeFiles` whose `stats` and `toolsFor` are always there, so
|
|
490
|
+
* that `files.stats()` needs no `?.`. New in 0.10.0.
|
|
264
491
|
*/
|
|
265
|
-
|
|
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
|
-
}
|
|
492
|
+
export type CreatedLargeFiles = LargeFiles & { stats(): LargeFilesStats; toolsFor: NonNullable<LargeFiles["toolsFor"]> };
|
|
285
493
|
|
|
286
494
|
/**
|
|
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.
|
|
495
|
+
* Whether `value` has the shape of a document ID: one the library makes ("doc_" and 32 hex digits),
|
|
496
|
+
* or one an application may give (`APP_DOCUMENT_ID_PATTERN`, since 0.9.0), which the library's fit too.
|
|
293
497
|
*/
|
|
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";
|
|
498
|
+
export function isDocumentId(value: unknown): value is string {
|
|
499
|
+
return typeof value === "string" && APP_DOCUMENT_ID_PATTERN.test(value);
|
|
301
500
|
}
|
|
302
501
|
|
|
303
502
|
/**
|
|
@@ -310,43 +509,34 @@ function wholeName(meta: DocumentMeta): DocumentMeta {
|
|
|
310
509
|
return name === meta.name ? meta : { ...meta, name };
|
|
311
510
|
}
|
|
312
511
|
|
|
313
|
-
/**
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
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
|
-
}
|
|
512
|
+
/** The key a caller's copy of a document is kept under in memory: the key of its scope, then the ID. */
|
|
513
|
+
const documentKey = (caller: Caller, id: string) => `${caller.key}\u0000${id}`;
|
|
514
|
+
|
|
515
|
+
/** A caller with no owner and no scope. */
|
|
516
|
+
const NO_CALLER: Caller = Object.freeze({ context: storeContext(undefined, undefined), key: "" });
|
|
322
517
|
|
|
323
518
|
/**
|
|
324
|
-
*
|
|
325
|
-
*
|
|
519
|
+
* What `view_pages` answers for a file the application keeps (`IngestInput.original`) that is no
|
|
520
|
+
* longer the one that was ingested. New in 0.9.0.
|
|
326
521
|
*/
|
|
327
|
-
|
|
328
|
-
try {
|
|
329
|
-
return await read();
|
|
330
|
-
} catch (error) {
|
|
331
|
-
throw error instanceof DocumentStoreError ? error : new DocumentStoreError(error);
|
|
332
|
-
}
|
|
333
|
-
}
|
|
522
|
+
const changedOriginal = (file: string) => `${file} changed on the server since it was read. Attach it again to look at its pages.`;
|
|
334
523
|
|
|
335
524
|
/**
|
|
336
|
-
*
|
|
337
|
-
*
|
|
525
|
+
* Where the application keeps the uploaded file of a document (`DocumentMeta.original`), when its
|
|
526
|
+
* metadata says so in the shape the library writes. Undefined for one kept in the store, and for
|
|
527
|
+
* one written by hand in another shape, which reads as missing.
|
|
338
528
|
*/
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
529
|
+
function refOf(meta: DocumentMeta): { ref: string; bytes: number; sha256: string } | undefined {
|
|
530
|
+
const original: unknown = meta.original;
|
|
531
|
+
if (typeof original !== "object" || original === null) return undefined;
|
|
532
|
+
const { ref, bytes, sha256 } = original as { ref?: unknown; bytes?: unknown; sha256?: unknown };
|
|
533
|
+
return typeof ref === "string" && ref.length > 0 && typeof bytes === "number" && Number.isSafeInteger(bytes) && bytes >= 0 && isSha256(sha256)
|
|
534
|
+
? { ref, bytes, sha256 }
|
|
535
|
+
: undefined;
|
|
343
536
|
}
|
|
344
537
|
|
|
345
538
|
/** Default for `cacheBytes`. */
|
|
346
539
|
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
540
|
|
|
351
541
|
/** Default for `maxPdfPages`. */
|
|
352
542
|
export const DEFAULT_MAX_PDF_PAGES = 5_000;
|
|
@@ -354,186 +544,33 @@ export const DEFAULT_MAX_PDF_PAGES = 5_000;
|
|
|
354
544
|
export const DEFAULT_MAX_TEXT_BYTES = 100 * 1024 * 1024;
|
|
355
545
|
/** Default for `ingestTimeoutMs`: 2 minutes. */
|
|
356
546
|
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
547
|
|
|
374
|
-
/**
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
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
|
-
}
|
|
548
|
+
/** Default for `wholeDocumentBytes`. */
|
|
549
|
+
export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
|
550
|
+
/** Default for `storeTimeoutMs`: 30 seconds. */
|
|
551
|
+
export const DEFAULT_STORE_TIMEOUT_MS = 30_000;
|
|
437
552
|
|
|
438
553
|
/**
|
|
439
|
-
*
|
|
440
|
-
*
|
|
554
|
+
* Default for `maxStuckStoreCalls`: half of the threads of libuv's pool, and at least 1. The pool
|
|
555
|
+
* is read from `UV_THREADPOOL_SIZE` as libuv reads it (`atoi`): 4 when it is not set; its leading
|
|
556
|
+
* digits ("32abc" is 32); 1 thread for a value without them or for 0 ("", "x", "0"), which a
|
|
557
|
+
* template with an empty value gives; 1,024 at most, and for a value below 0, which libuv reads as
|
|
558
|
+
* a number without a sign, past the most.
|
|
441
559
|
*/
|
|
442
|
-
function
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
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 };
|
|
560
|
+
function defaultMaxStuck(): number {
|
|
561
|
+
const value = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.UV_THREADPOOL_SIZE;
|
|
562
|
+
let pool = 4;
|
|
563
|
+
if (value !== undefined) {
|
|
564
|
+
const given = Number.parseInt(value, 10);
|
|
565
|
+
pool = Number.isNaN(given) || given === 0 ? 1 : given < 0 ? 1_024 : Math.min(1_024, given);
|
|
471
566
|
}
|
|
567
|
+
return Math.max(1, Math.floor(pool / 2));
|
|
472
568
|
}
|
|
473
569
|
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
/**
|
|
477
|
-
|
|
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
|
-
|
|
535
|
-
/** Default for `wholeDocumentBytes`. */
|
|
536
|
-
export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
|
570
|
+
/** Looks at pages that run at once in a library, unless `maxConcurrentPageLooks` says otherwise. */
|
|
571
|
+
const DEFAULT_PAGE_LOOKS = 1;
|
|
572
|
+
/** How long a look at pages waits for its turn, unless `pageLookWaitMs` says otherwise. */
|
|
573
|
+
const DEFAULT_PAGE_LOOK_WAIT_MS = 30_000;
|
|
537
574
|
|
|
538
575
|
/**
|
|
539
576
|
* A number option as it was given, or `fallback` when it was left out. NaN, which
|
|
@@ -548,7 +585,7 @@ function numberOption(name: string, value: unknown, fallback: number, finite = f
|
|
|
548
585
|
return value;
|
|
549
586
|
}
|
|
550
587
|
|
|
551
|
-
export function createLargeFiles(options: LargeFilesOptions):
|
|
588
|
+
export function createLargeFiles(options: LargeFilesOptions): CreatedLargeFiles {
|
|
552
589
|
/** The fields the application set. The others follow the context window, whichever it is for a request. */
|
|
553
590
|
const ownBudget = givenBudget(options.budget);
|
|
554
591
|
const budget: Budget = resolveBudget(ownBudget);
|
|
@@ -564,40 +601,91 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
564
601
|
const now = options.now ?? (() => new Date());
|
|
565
602
|
const { store } = options;
|
|
566
603
|
const cacheBytes = Math.max(0, numberOption("cacheBytes", options.cacheBytes, DEFAULT_CACHE_BYTES));
|
|
567
|
-
/**
|
|
604
|
+
/** What every call must name (`requireOwner`, `requireScope`). */
|
|
605
|
+
const rules: AccessRules = Object.freeze({ requireOwner: options.requireOwner === true, requireScope: options.requireScope === true });
|
|
606
|
+
/**
|
|
607
|
+
* Documents ready to search, and decoded pieces of documents read by range, in one memory budget.
|
|
608
|
+
* Each is kept under the key of the caller's scope and the document's ID (`documentKey`): one ID
|
|
609
|
+
* in two scopes is two documents, and the copy of one is never served to the other. Its version
|
|
610
|
+
* (`documentVersion`) holds the document's owner and scope too, so a copy is not served to
|
|
611
|
+
* another owner either, once another document is stored under the same ID.
|
|
612
|
+
*/
|
|
568
613
|
const cache = new DocumentCache<Sized>(
|
|
569
614
|
cacheBytes,
|
|
570
615
|
Math.max(0, Math.trunc(numberOption("cacheSize", options.cacheSize, Number.POSITIVE_INFINITY))),
|
|
571
616
|
);
|
|
572
|
-
/** Forgets everything kept of
|
|
617
|
+
/** Forgets everything kept of the document of one key (`documentKey`): the document, and its pieces. */
|
|
618
|
+
const forgetKey = (key: string) => {
|
|
619
|
+
cache.delete(key);
|
|
620
|
+
cache.deletePrefix(pieceKey(key, 0).slice(0, -1));
|
|
621
|
+
};
|
|
622
|
+
/** Whether `key` is that of document `id`, or of one of its pieces, in any scope. */
|
|
623
|
+
const keyOfId = (key: string, id: string) => {
|
|
624
|
+
const rest = key.slice(key.indexOf("\u0000") + 1);
|
|
625
|
+
return rest === id || rest.startsWith(`${id}#`);
|
|
626
|
+
};
|
|
627
|
+
/**
|
|
628
|
+
* Forgets everything kept of document `id`, in every scope: it was deleted, or written again.
|
|
629
|
+
* In a store that keeps no scopes apart, the copies of all scopes are of that one document.
|
|
630
|
+
*/
|
|
573
631
|
const forget = (id: string) => {
|
|
574
|
-
cache.
|
|
575
|
-
|
|
632
|
+
cache.deleteWhere((key) => keyOfId(key, id));
|
|
633
|
+
for (const key of rebuildIndex) if (keyOfId(key, id)) rebuildIndex.delete(key);
|
|
576
634
|
};
|
|
635
|
+
/** The most time one store call may take (`storeTimeoutMs`): 0 for no limit. */
|
|
636
|
+
const storeTimeoutMs = Math.max(0, numberOption("storeTimeoutMs", options.storeTimeoutMs, DEFAULT_STORE_TIMEOUT_MS));
|
|
637
|
+
/** The most time one sweep may take (`sweepTimeoutMs`): 0 for no limit. */
|
|
638
|
+
const sweepTimeoutMs = Math.max(0, numberOption("sweepTimeoutMs", options.sweepTimeoutMs, 0));
|
|
639
|
+
/** While this many calls of the process are stuck, store calls of this library fail at once (`maxStuckStoreCalls`). */
|
|
640
|
+
const maxStuckStoreCalls = Math.max(1, Math.trunc(numberOption("maxStuckStoreCalls", options.maxStuckStoreCalls, defaultMaxStuck())));
|
|
641
|
+
/**
|
|
642
|
+
* A call of the store, within `storeTimeoutMs`, refused at once while too many calls of the
|
|
643
|
+
* process are stuck. `signal` ends the caller's wait, never the call: a call that other callers
|
|
644
|
+
* wait on too (an opening of a document) is given none.
|
|
645
|
+
*/
|
|
646
|
+
const timed = <T>(operation: DocumentStoreOperation, call: () => Promise<T>, signal?: AbortSignal): Promise<T> => (
|
|
647
|
+
storeCall(operation, call, { timeoutMs: storeTimeoutMs, maxStuck: maxStuckStoreCalls, signal })
|
|
648
|
+
);
|
|
649
|
+
/**
|
|
650
|
+
* A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
|
|
651
|
+
* could not be read is not a document that is gone, and its own error names paths or hosts.
|
|
652
|
+
*/
|
|
653
|
+
const reading = <T>(read: () => Promise<T>, signal?: AbortSignal): Promise<T> => timed("read", read, signal);
|
|
577
654
|
/** Documents being opened, so that calls arriving together open each one once. */
|
|
578
655
|
const opening = new Map<string, Promise<DocumentSource | undefined>>();
|
|
579
|
-
/**
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
656
|
+
/**
|
|
657
|
+
* The store, to read the text of a document by range rather than load it whole: each call carries
|
|
658
|
+
* `context`: the caller's scope, and the document's owner when it has one (`documentContext`).
|
|
659
|
+
* A document read by range is shared by every caller of its scope: its reads have a time limit,
|
|
660
|
+
* and no caller's signal.
|
|
661
|
+
*/
|
|
662
|
+
const rangeStore = (context: DocumentContext): RangeStore => ({
|
|
663
|
+
readTextRange: (id, start, end) => reading(() => store.readTextRange!(id, start, end, context)),
|
|
664
|
+
...(store.getIndex ? { getIndex: (id: string) => reading(() => store.getIndex!(id, context)) } : {}),
|
|
665
|
+
...(store.putIndex ? { putIndex: (id: string, index: Uint8Array) => timed("write", () => store.putIndex!(id, index, context)) } : {}),
|
|
666
|
+
});
|
|
585
667
|
/** The uploaded file of a document, when the store keeps such files. */
|
|
586
|
-
const loadOriginal =
|
|
668
|
+
const loadOriginal = (id: string, context: DocumentContext, signal?: AbortSignal) => reading(() => store.getOriginal!(id, context), signal);
|
|
669
|
+
/**
|
|
670
|
+
* Removals of documents (`delete`) take their turns, one at a time: a store that does not answer
|
|
671
|
+
* then holds one thread of the pool for them, not one for each.
|
|
672
|
+
*/
|
|
673
|
+
const removals = new Limiter(1);
|
|
587
674
|
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. */
|
|
675
|
+
/** Documents (by `documentKey`) whose saved index did not match their text: the next opening builds it from the text. */
|
|
589
676
|
const rebuildIndex = new Set<string>();
|
|
590
677
|
const scan: ScanSettings = {
|
|
591
678
|
chunkBytes: Math.max(1, Math.trunc(numberOption("scanChunkBytes", options.scanChunkBytes, 1024 * 1024, true))),
|
|
592
679
|
limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentScans", options.maxConcurrentScans, 4)))),
|
|
593
|
-
onBroken: (
|
|
594
|
-
rebuildIndex.add(
|
|
595
|
-
|
|
680
|
+
onBroken: (key) => {
|
|
681
|
+
rebuildIndex.add(key);
|
|
682
|
+
forgetKey(key);
|
|
596
683
|
},
|
|
597
684
|
pieces: {
|
|
598
685
|
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
|
-
|
|
686
|
+
// A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with
|
|
687
|
+
// it. The document's key is all before the last "#", which no ID holds, and no scope key either.
|
|
688
|
+
set: (key, version, piece) => cache.set(key, version, piece, key.slice(0, key.lastIndexOf("#"))),
|
|
601
689
|
// A quarter of the cache: a few documents can be kept, and no one pushes out all the rest.
|
|
602
690
|
maxDocumentBytes: cacheBytes / 4,
|
|
603
691
|
},
|
|
@@ -607,412 +695,384 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
607
695
|
const ingests = new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentIngests", options.maxConcurrentIngests, 2))));
|
|
608
696
|
/** How long work an ingest waits on, or gave up on, may keep its turn (see `IngestSlot`). */
|
|
609
697
|
const slotCapMs = ingestTimeoutMs > 0 && ingestTimeoutMs <= LONGEST_TIMER_MS ? ingestTimeoutMs : DEFAULT_INGEST_TIMEOUT_MS;
|
|
698
|
+
/**
|
|
699
|
+
* The looks at pages of every question of this library take their turns (`maxConcurrentPageLooks`).
|
|
700
|
+
* A look reads its original within the time the library gives its store calls (`slotCapMs`).
|
|
701
|
+
*/
|
|
702
|
+
const pageLooks: PageLookTurns = {
|
|
703
|
+
limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentPageLooks", options.maxConcurrentPageLooks, DEFAULT_PAGE_LOOKS)))),
|
|
704
|
+
waitMs: Math.max(0, numberOption("pageLookWaitMs", options.pageLookWaitMs, DEFAULT_PAGE_LOOK_WAIT_MS)),
|
|
705
|
+
holdMs: slotCapMs,
|
|
706
|
+
};
|
|
610
707
|
|
|
611
708
|
const scannedPdfPages = Math.max(0, Math.trunc(numberOption("scannedPdfPages", options.scannedPdfPages, 30)));
|
|
612
|
-
|
|
613
|
-
|
|
709
|
+
const { originals } = options;
|
|
710
|
+
if (originals !== undefined && (typeof originals !== "object" || originals === null || typeof originals.read !== "function")) {
|
|
711
|
+
throw new TypeError("originals must be an object with a read(ref, context) method, such as fileOriginals(root) gives.");
|
|
712
|
+
}
|
|
713
|
+
/**
|
|
714
|
+
* Whether the uploaded file of a document of this format is kept: by its ref (`IngestInput.original`),
|
|
715
|
+
* which `originals` reads back, or as a copy in the store (`putOriginal`).
|
|
716
|
+
*/
|
|
717
|
+
const keeps = (format: DocumentFormat, byRef: boolean) => keepOriginals.has(format) && (byRef ? originals !== undefined : typeof store.putOriginal === "function");
|
|
718
|
+
/**
|
|
719
|
+
* Whether the original of a document, which its metadata says is kept, can be read: by its ref,
|
|
720
|
+
* through `originals`, or from the store (`getOriginal`).
|
|
721
|
+
*/
|
|
722
|
+
const readable = (meta: DocumentMeta) => (meta.original !== undefined && meta.original !== null ? originals !== undefined : typeof store.getOriginal === "function");
|
|
723
|
+
/** Whether `view_pages` can show the pages of a document: a PDF whose original is kept, and can be read. */
|
|
724
|
+
const viewableMeta = (meta: DocumentMeta) => meta.format === "pdf" && meta.originalKept === true && readable(meta);
|
|
725
|
+
/** What `ingest` (src/ingest.ts) needs of this library. */
|
|
726
|
+
const ingestContext: IngestContext = {
|
|
727
|
+
store,
|
|
728
|
+
now,
|
|
729
|
+
ttlMs,
|
|
730
|
+
maxUploadBytes,
|
|
731
|
+
maxTextBytes,
|
|
732
|
+
maxPdfPages,
|
|
733
|
+
ingestTimeoutMs,
|
|
734
|
+
scannedPdfPages,
|
|
735
|
+
// Read at each ingest, as before the move: an application may set them after.
|
|
736
|
+
get extractors() {
|
|
737
|
+
return options.extractors;
|
|
738
|
+
},
|
|
739
|
+
ingests,
|
|
740
|
+
slotCapMs,
|
|
741
|
+
maxStuck: maxStuckStoreCalls,
|
|
742
|
+
keeps,
|
|
743
|
+
readsRefs: originals !== undefined,
|
|
744
|
+
forget,
|
|
745
|
+
rules,
|
|
746
|
+
ingesting: new Set<string>(),
|
|
747
|
+
};
|
|
614
748
|
|
|
615
749
|
/**
|
|
616
|
-
* The document as the store describes it now
|
|
617
|
-
* deleted (by this server or another one sharing the store), or has
|
|
750
|
+
* The document as the store describes it now, asked with the caller's context: undefined when it
|
|
751
|
+
* was never there, has been deleted (by this server or another one sharing the store), or has
|
|
752
|
+
* expired. Whether the caller may use it is `metaFor`'s to say.
|
|
618
753
|
*/
|
|
619
|
-
async function currentMeta(id: string): Promise<DocumentMeta | undefined> {
|
|
754
|
+
async function currentMeta(id: string, caller: Caller): Promise<DocumentMeta | undefined> {
|
|
620
755
|
if (!isDocumentId(id)) return undefined;
|
|
621
|
-
const meta = await reading(() => store.getMeta(id));
|
|
756
|
+
const meta = metaOf(await reading(() => store.getMeta(id, caller.context), caller.signal), id);
|
|
757
|
+
if (meta) checkMetaVersion(meta);
|
|
622
758
|
if (!meta || Date.parse(meta.expiresAt) <= now().getTime()) {
|
|
623
|
-
|
|
759
|
+
forgetKey(documentKey(caller, id));
|
|
624
760
|
return undefined;
|
|
625
761
|
}
|
|
626
762
|
return wholeName(meta);
|
|
627
763
|
}
|
|
628
764
|
|
|
765
|
+
/** The document, when `caller` may use it: one of another owner or scope is missing, not forbidden. */
|
|
766
|
+
async function metaFor(id: string, caller: Caller): Promise<DocumentMeta | undefined> {
|
|
767
|
+
const meta = await currentMeta(id, caller);
|
|
768
|
+
return meta && mayUse(meta, caller, rules) ? meta : undefined;
|
|
769
|
+
}
|
|
770
|
+
|
|
629
771
|
/**
|
|
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.
|
|
772
|
+
* A document ready to read and search, for `caller`, who may use it. The store is asked first,
|
|
773
|
+
* every time: a kept copy is used only while the store still has the same document. `known` is
|
|
774
|
+
* metadata just read from the store and checked, to save asking twice. One opening serves every
|
|
775
|
+
* caller of the scope who asks meanwhile: its reads have time limits, and each caller stops
|
|
776
|
+
* waiting for it when its own signal aborts, which leaves the others waiting (0.10.0).
|
|
633
777
|
*/
|
|
634
|
-
async function load(id: string, known?: DocumentMeta): Promise<DocumentSource | undefined> {
|
|
635
|
-
const meta = known ?? await
|
|
778
|
+
async function load(id: string, caller: Caller, known?: DocumentMeta): Promise<DocumentSource | undefined> {
|
|
779
|
+
const meta = known ?? await metaFor(id, caller);
|
|
636
780
|
if (!meta) return undefined;
|
|
781
|
+
const key = documentKey(caller, id);
|
|
637
782
|
const version = documentVersion(meta);
|
|
638
|
-
const cached = cache.get(
|
|
783
|
+
const cached = cache.get(key, version) as DocumentSource | undefined;
|
|
639
784
|
if (cached && !cached.broken) return cached;
|
|
640
|
-
const
|
|
641
|
-
let pending = opening.get(
|
|
785
|
+
const opened = `${key}|${version}`;
|
|
786
|
+
let pending = opening.get(opened);
|
|
642
787
|
if (!pending) {
|
|
643
|
-
|
|
644
|
-
|
|
788
|
+
// Kept once opened, whether or not a caller still waits for it.
|
|
789
|
+
pending = open(id, meta, caller, key)
|
|
790
|
+
.then((document) => {
|
|
791
|
+
if (document) cache.set(key, version, document);
|
|
792
|
+
return document;
|
|
793
|
+
})
|
|
794
|
+
.finally(() => opening.delete(opened));
|
|
795
|
+
opening.set(opened, pending);
|
|
645
796
|
}
|
|
646
|
-
|
|
647
|
-
if (document) cache.set(id, version, document);
|
|
648
|
-
return document;
|
|
797
|
+
return until(pending, caller.signal);
|
|
649
798
|
}
|
|
650
799
|
|
|
651
|
-
/**
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
800
|
+
/**
|
|
801
|
+
* Reads a document from the store: its index, to read it by range, or all of it. `meta` is what
|
|
802
|
+
* `metaFor` found for `caller`. The reads carry the caller's scope, and the document's owner when it
|
|
803
|
+
* has one (`documentContext`): the copy is kept for every caller of the scope.
|
|
804
|
+
*/
|
|
805
|
+
async function open(id: string, meta: DocumentMeta, caller: Caller, key: string): Promise<DocumentSource | undefined> {
|
|
806
|
+
const context = documentContext(meta, caller);
|
|
807
|
+
if (typeof store.readTextRange === "function" && meta.textBytes > wholeDocumentBytes) {
|
|
808
|
+
const rebuild = rebuildIndex.delete(key);
|
|
809
|
+
return openRangedDocument(rangeStore(context), meta, scan, { ignoreSavedIndex: rebuild, key });
|
|
656
810
|
}
|
|
657
|
-
const stored = await reading(() => store.get(id));
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
811
|
+
const stored = await reading(() => store.get(id, context));
|
|
812
|
+
// Another document is not this one: the metadata `get` gives must be of this ID, owner and
|
|
813
|
+
// scope, and of the version `meta` is (not one deleted and stored again since, by another
|
|
814
|
+
// server, nor one a store of your own gave from the wrong scope). And the text must be the one
|
|
815
|
+
// that metadata describes, of its length and its number of lines: a store that writes the text
|
|
816
|
+
// and the metadata apart can give one document's metadata with another's text (two servers that
|
|
817
|
+
// ingest one ID at once, a file read between two writes). A document read by range is checked
|
|
818
|
+
// too: its index against the metadata, and the end of its text against its index
|
|
819
|
+
// (openRangedDocument). Missing, as for a caller who may not use it.
|
|
820
|
+
const found = stored ? metaOf(stored.meta, id) : undefined;
|
|
821
|
+
if (!stored || !found || !mayUse(found, caller, rules) || documentVersion(found) !== documentVersion(meta)) return undefined;
|
|
822
|
+
if (typeof stored.text !== "string" || stored.text.length !== found.characters) return undefined;
|
|
823
|
+
const named = wholeName(found);
|
|
824
|
+
const document = new SearchableDocument(named === stored.meta ? stored : { ...stored, meta: named });
|
|
825
|
+
return document.lineCount === found.lines ? document : undefined;
|
|
661
826
|
}
|
|
662
827
|
|
|
663
828
|
/**
|
|
664
|
-
*
|
|
665
|
-
*
|
|
829
|
+
* The uploaded file of document `id`, which `meta`, checked for `caller`, says is kept: read from
|
|
830
|
+
* where the application keeps it (`meta.original`, through `originals`), or from the store. Another
|
|
831
|
+
* server may delete the document and store another under its ID while the bytes are read: so the
|
|
832
|
+
* store is asked again once they are. "missing" unless it still describes the same document, of
|
|
833
|
+
* the same owner and scope, and the bytes are the size of the file that was ingested, and have its
|
|
834
|
+
* SHA-256 when it is known (0.9.0): a store that gives back other bytes of the same size is caught
|
|
835
|
+
* too. "changed" for a file kept by the application that is no longer the one that was ingested:
|
|
836
|
+
* of another size or another SHA-256.
|
|
666
837
|
*/
|
|
667
|
-
async function
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
if (error instanceof DocumentGoneError) return undefined;
|
|
679
|
-
if (!document.broken) {
|
|
680
|
-
// Deleted between the look-up and the read: the same as missing.
|
|
681
|
-
if (!await currentMeta(id)) return undefined;
|
|
682
|
-
throw error;
|
|
683
|
-
}
|
|
684
|
-
}
|
|
838
|
+
async function originalOf(id: string, caller: Caller, meta: DocumentMeta): Promise<Uint8Array | "missing" | "changed"> {
|
|
839
|
+
const kept = refOf(meta);
|
|
840
|
+
let read: Uint8Array | undefined;
|
|
841
|
+
if (kept) {
|
|
842
|
+
if (!originals) return "missing";
|
|
843
|
+
const context: OriginalReadContext = Object.freeze({ ...caller.context, id, bytes: kept.bytes });
|
|
844
|
+
read = await reading(() => originals.read(kept.ref, context), caller.signal);
|
|
845
|
+
} else {
|
|
846
|
+
if (meta.original !== undefined && meta.original !== null) return "missing";
|
|
847
|
+
if (!store.getOriginal) return "missing";
|
|
848
|
+
read = await loadOriginal(id, caller.context, caller.signal);
|
|
685
849
|
}
|
|
686
|
-
return
|
|
850
|
+
if (!read) return "missing";
|
|
851
|
+
const bytes = read;
|
|
852
|
+
const after = await metaFor(id, caller);
|
|
853
|
+
if (!after || documentVersion(after) !== documentVersion(meta)) return "missing";
|
|
854
|
+
// The SHA-256 of a file of up to the upload limit is taken a slice at a time.
|
|
855
|
+
const same = async (sha256: string) => await sha256InSlices(bytes, new TimeSlicer()) === sha256;
|
|
856
|
+
if (kept) return bytes.byteLength === kept.bytes && await same(kept.sha256) ? bytes : "changed";
|
|
857
|
+
if (bytes.byteLength !== meta.bytes) return "missing";
|
|
858
|
+
return typeof meta.sha256 === "string" && !await same(meta.sha256) ? "missing" : bytes;
|
|
687
859
|
}
|
|
688
860
|
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
861
|
+
/**
|
|
862
|
+
* Whether `document`, which a call of `caller` has just read, is still the one the store describes
|
|
863
|
+
* for `caller`. A document loaded whole was checked as it was read (see `open`). The bytes of one
|
|
864
|
+
* read by range carry nothing to check them by, and another server, or this one, may delete the
|
|
865
|
+
* document and store another under its ID while they are read, or between the look-up and the
|
|
866
|
+
* reads: so the store is asked again once they are, as `originalOf` does. When it no longer
|
|
867
|
+
* describes the same document, of the same owner and scope, what was read may be another's: the
|
|
868
|
+
* copy kept of it, read from the store too, is forgotten, and the read is missing.
|
|
869
|
+
*/
|
|
870
|
+
async function stillOpened(document: DocumentSource, caller: Caller): Promise<boolean> {
|
|
871
|
+
if (!(document instanceof RangedDocument)) return true;
|
|
872
|
+
const after = await metaFor(document.meta.id, caller);
|
|
873
|
+
if (after && documentVersion(after) === documentVersion(document.meta)) return true;
|
|
874
|
+
forgetKey(documentKey(caller, document.meta.id));
|
|
875
|
+
return false;
|
|
692
876
|
}
|
|
693
877
|
|
|
694
878
|
/**
|
|
695
|
-
*
|
|
696
|
-
*
|
|
697
|
-
*
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
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;
|
|
879
|
+
* Removes a document from the store (`store.delete`), in the removals' turn (`removals`). The turn
|
|
880
|
+
* and the store call are waited for until `deadline` aborts (the delete's time limit, which they
|
|
881
|
+
* share), or the caller's signal does; the turn is then held until the store call ends, even past
|
|
882
|
+
* its time limit. The store call counts as stuck once it has itself run `storeTimeoutMs`.
|
|
883
|
+
*/
|
|
884
|
+
async function removal(call: () => Promise<boolean>, signal: AbortSignal | undefined, deadline: AbortSignal): Promise<boolean> {
|
|
885
|
+
checkStuck("delete", maxStuckStoreCalls);
|
|
886
|
+
if (signal?.aborted) throw signal.reason;
|
|
887
|
+
if (deadline.aborted) throw deadline.reason;
|
|
888
|
+
const waits = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
889
|
+
let release: () => void;
|
|
890
|
+
try {
|
|
891
|
+
release = await removals.acquire(waits);
|
|
892
|
+
} catch (error) {
|
|
893
|
+
if (signal?.aborted) throw signal.reason;
|
|
894
|
+
throw deadline.aborted ? deadline.reason : error;
|
|
895
|
+
}
|
|
896
|
+
let started = false;
|
|
723
897
|
try {
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
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;
|
|
898
|
+
return await timed("delete", () => {
|
|
899
|
+
started = true;
|
|
900
|
+
let running: Promise<boolean>;
|
|
732
901
|
try {
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
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;
|
|
902
|
+
running = Promise.resolve(call());
|
|
903
|
+
} catch (error) {
|
|
904
|
+
running = Promise.reject(error);
|
|
751
905
|
}
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
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();
|
|
906
|
+
running.then(release, release);
|
|
907
|
+
return running;
|
|
908
|
+
}, waits);
|
|
775
909
|
} finally {
|
|
776
|
-
|
|
910
|
+
if (!started) release();
|
|
777
911
|
}
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
const
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
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 };
|
|
822
|
-
throw error;
|
|
823
|
-
}
|
|
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;
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
/** What planning a request (`prepareDocuments`, src/prepare.ts) needs of this library. */
|
|
915
|
+
const planning: PrepareContext = { callerOf: (access) => callerOf(access, rules), metaFor, load, stillOpened, budgetFor, viewableMeta, rules };
|
|
916
|
+
|
|
917
|
+
/** `files.tools`: the tools for `documents`. */
|
|
918
|
+
function tools(documents: DocumentMeta[], toolOptions: ToolOptions = {}): ToolSet {
|
|
919
|
+
const { viewPages, budget: overrides, access, ...rest } = toolOptions;
|
|
920
|
+
// Without `access`, the owner and scope of each document are those it was handed in with: a
|
|
921
|
+
// library that requires them takes them only from the caller.
|
|
922
|
+
if (access === undefined && (rules.requireOwner || rules.requireScope)) {
|
|
923
|
+
throw new TypeError(rules.requireOwner ? OWNER_REQUIRED : SCOPE_REQUIRED);
|
|
853
924
|
}
|
|
854
|
-
|
|
925
|
+
// The tool set's signal ends its waits for the store too, unless `access` has a signal of its own.
|
|
926
|
+
// It is taken as it is, as before 0.10.0 (an object made like an AbortSignal too): only
|
|
927
|
+
// `access.signal`, new in 0.10.0, must be an AbortSignal (`callerOf`).
|
|
928
|
+
const signal = access?.signal ?? toolOptions.signal;
|
|
929
|
+
const asker = access !== undefined ? withSignal(callerOf(access, rules), signal) : undefined;
|
|
930
|
+
const budget = budgetFor(overrides);
|
|
931
|
+
// Which PDFs can be looked at, by the metadata handed in: each look reads the metadata the
|
|
932
|
+
// store holds, and the file it names, not the one handed in.
|
|
933
|
+
const viewable = (viewPages === true ? documents : viewPages || []).filter(viewableMeta);
|
|
934
|
+
// Without `access`, as before 0.9.0: the owner and scope each document was handed in with.
|
|
935
|
+
// The store is asked with them, and the owner and scope it holds are checked against them on
|
|
936
|
+
// every call, so metadata built from an ID alone cannot read another owner's document: such a
|
|
937
|
+
// document is answered as no longer available, as `getMeta` reports it missing. A handed scope
|
|
938
|
+
// that is not valid reads nothing.
|
|
939
|
+
const handed = new Map<string, Caller | undefined>(asker ? [] : [...documents, ...viewable].map((meta) => [meta.id, handedCaller(meta, signal)]));
|
|
940
|
+
const noCaller = signal ? { ...NO_CALLER, signal } : NO_CALLER;
|
|
941
|
+
const callerFor = (id: string): Caller | undefined => asker ?? (handed.has(id) ? handed.get(id) : noCaller);
|
|
942
|
+
// The metadata the store holds now, not that of a copy kept in memory.
|
|
943
|
+
const checkedLoad = async (id: string) => {
|
|
944
|
+
const caller = callerFor(id);
|
|
945
|
+
const meta = caller && await metaFor(id, caller);
|
|
946
|
+
return meta ? load(id, caller, meta) : undefined;
|
|
947
|
+
};
|
|
948
|
+
const checkedOriginal = (store.getOriginal || originals) && (async (id: string) => {
|
|
949
|
+
const caller = callerFor(id);
|
|
950
|
+
const meta = caller && await metaFor(id, caller);
|
|
951
|
+
if (!meta || !readable(meta)) return undefined;
|
|
952
|
+
const original = await originalOf(id, caller, meta);
|
|
953
|
+
// A file the application keeps that has changed since it was ingested: its pages are not
|
|
954
|
+
// those of the text the model has, and the model is told so.
|
|
955
|
+
if (original === "changed") throw new Error(changedOriginal(meta.name));
|
|
956
|
+
return original === "missing" ? undefined : original;
|
|
957
|
+
});
|
|
958
|
+
return createDocumentTools({
|
|
959
|
+
load: checkedLoad,
|
|
960
|
+
// Once a call has read a document by range: the store is asked again (`stillOpened`).
|
|
961
|
+
checkRead: async (document) => {
|
|
962
|
+
const caller = callerFor(document.meta.id);
|
|
963
|
+
return caller !== undefined && await stillOpened(document, caller);
|
|
964
|
+
},
|
|
965
|
+
documentIds: documents.map((meta) => meta.id),
|
|
966
|
+
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
|
|
967
|
+
budget,
|
|
968
|
+
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal, pageLooks } : {}),
|
|
969
|
+
// `analyze_whole_document` is declared only when it can read at least one of the documents.
|
|
970
|
+
wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
|
|
971
|
+
// `aggregate_table` only when one may hold a table.
|
|
972
|
+
tables: documents.some((meta) => TABLE_FORMATS.has(meta.format)),
|
|
973
|
+
...rest,
|
|
974
|
+
});
|
|
855
975
|
}
|
|
856
976
|
|
|
857
977
|
return {
|
|
858
978
|
budget,
|
|
859
979
|
budgetFor,
|
|
860
980
|
maxUploadBytes,
|
|
981
|
+
access: rules,
|
|
861
982
|
|
|
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
|
-
}
|
|
983
|
+
ingest(input) {
|
|
984
|
+
return ingestDocument(ingestContext, input);
|
|
924
985
|
},
|
|
925
986
|
|
|
926
|
-
getMeta
|
|
987
|
+
async getMeta(id, access) {
|
|
988
|
+
return metaFor(id, callerOf(access, rules));
|
|
989
|
+
},
|
|
927
990
|
|
|
928
991
|
async getOriginal(id, access) {
|
|
929
|
-
const
|
|
930
|
-
|
|
992
|
+
const caller = callerOf(access, rules);
|
|
993
|
+
const meta = await metaFor(id, caller);
|
|
994
|
+
if (!meta?.originalKept || !readable(meta)) return undefined;
|
|
995
|
+
const original = await originalOf(id, caller, meta);
|
|
996
|
+
return original instanceof Uint8Array ? original : undefined;
|
|
931
997
|
},
|
|
932
998
|
|
|
933
999
|
async delete(id, access) {
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
1000
|
+
const caller = callerOf(access, rules);
|
|
1001
|
+
// One time limit for the whole delete: the look-up (which keeps its own, and its error of a
|
|
1002
|
+
// read), then the wait for the removals' turn and the store's delete. Before, the turn and the
|
|
1003
|
+
// delete had one each: with a slow delete before it, a delete answered after twice the limit.
|
|
1004
|
+
const deadline = new AbortController();
|
|
1005
|
+
const timer = isTimeLimit(storeTimeoutMs) ? setTimeout(() => deadline.abort(storeTimeout("delete", storeTimeoutMs)), storeTimeoutMs) : undefined;
|
|
1006
|
+
try {
|
|
1007
|
+
if (!await metaFor(id, caller)) return false;
|
|
1008
|
+
forget(id);
|
|
1009
|
+
return await removal(() => store.delete(id, caller.context), caller.signal, deadline.signal);
|
|
1010
|
+
} finally {
|
|
1011
|
+
clearTimeout(timer);
|
|
1012
|
+
}
|
|
937
1013
|
},
|
|
938
1014
|
|
|
939
|
-
async sweep() {
|
|
940
|
-
|
|
1015
|
+
async sweep(sweepOptions) {
|
|
1016
|
+
// Upkeep of the store, not a user's access: allowed without a scope under `requireScope`.
|
|
1017
|
+
const scope = checkScope(sweepOptions?.scope ?? undefined);
|
|
1018
|
+
if (typeof store.sweep !== "function") return 0;
|
|
1019
|
+
// Within its own time limit, and never counted as stuck: a sweep of a large volume may take
|
|
1020
|
+
// long. It is refused, as other calls are, while too many calls are stuck.
|
|
1021
|
+
return storeCall("sweep", () => store.sweep!(now(), storeContext(scope, undefined)), { timeoutMs: sweepTimeoutMs, maxStuck: maxStuckStoreCalls, counts: false });
|
|
941
1022
|
},
|
|
942
1023
|
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
const unique = [...new Set(ids)];
|
|
947
|
-
let documents: DocumentMeta[] = [];
|
|
948
|
-
const missing: string[] = [];
|
|
949
|
-
for (const id of unique) {
|
|
950
|
-
// A document owned by someone else is reported as missing, not as forbidden, and is not
|
|
951
|
-
// read at all.
|
|
952
|
-
const meta = await metaFor(id, access);
|
|
953
|
-
if (meta) documents.push(meta);
|
|
954
|
-
else missing.push(id);
|
|
955
|
-
}
|
|
956
|
-
// Planning needs only the metadata. The text is read for the documents sent whole, and the
|
|
957
|
-
// first lines for the others. One that is gone by then is missing, and the plan is made again.
|
|
958
|
-
for (;;) {
|
|
959
|
-
const plan = planDocuments(documents, budget, base);
|
|
960
|
-
const inline = new Set(plan.inline.map((meta) => meta.id));
|
|
961
|
-
// 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 && store.getOriginal
|
|
963
|
-
? documents.filter((meta) => meta.format === "pdf" && meta.originalKept)
|
|
964
|
-
: [];
|
|
965
|
-
const shown = new Set(viewable.map((meta) => meta.id));
|
|
966
|
-
const blocks = new Map<string, string>();
|
|
967
|
-
const gone: string[] = [];
|
|
968
|
-
for (const meta of documents) {
|
|
969
|
-
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);
|
|
971
|
-
if (text === undefined) gone.push(meta.id);
|
|
972
|
-
else blocks.set(meta.id, text);
|
|
973
|
-
}
|
|
974
|
-
if (gone.length === 0) {
|
|
975
|
-
// A whole-document read is named only when the tools have it, and one of the files is
|
|
976
|
-
// small enough for it.
|
|
977
|
-
const wholeReads = analysis && plan.searchable.some((meta) => canBeReadWhole(meta, budget));
|
|
978
|
-
return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable, wholeReads), missing, viewable };
|
|
979
|
-
}
|
|
980
|
-
missing.push(...gone);
|
|
981
|
-
documents = documents.filter((meta) => !gone.includes(meta.id));
|
|
982
|
-
}
|
|
1024
|
+
// The options go on whole: planning (src/prepare.ts) reads the ones it knows.
|
|
1025
|
+
prepare(ids, base, prepareOptions) {
|
|
1026
|
+
return prepareDocuments(planning, ids, base, prepareOptions);
|
|
983
1027
|
},
|
|
984
1028
|
|
|
985
|
-
tools
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
const checkedLoad = async (id: string) => {
|
|
997
|
-
const meta = await currentMeta(id);
|
|
998
|
-
return meta && mayUse(meta) ? load(id, meta) : undefined;
|
|
1029
|
+
tools,
|
|
1030
|
+
|
|
1031
|
+
stats() {
|
|
1032
|
+
// Counters only: no store call, no turn waited for.
|
|
1033
|
+
return {
|
|
1034
|
+
ingests: ingests.load,
|
|
1035
|
+
scans: scan.limiter.load,
|
|
1036
|
+
pageLooks: pageLooks.limiter.load,
|
|
1037
|
+
cache: { bytes: cache.bytes, entries: cache.size, maxBytes: cacheBytes },
|
|
1038
|
+
stuckStoreCalls: stuckCalls(),
|
|
1039
|
+
maxStuckStoreCalls,
|
|
999
1040
|
};
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
}
|
|
1041
|
+
},
|
|
1042
|
+
|
|
1043
|
+
async toolsFor(ids, toolOptions) {
|
|
1044
|
+
const access: unknown = toolOptions?.access;
|
|
1045
|
+
if (typeof access !== "object" || access === null) throw new TypeError("toolsFor needs options.access: the owner and scope of the caller, such as { owner: userId }.");
|
|
1046
|
+
if (!Array.isArray(ids)) throw new TypeError("toolsFor needs an array of document IDs.");
|
|
1047
|
+
const caller = withSignal(callerOf(toolOptions.access, rules), toolOptions.access.signal ?? toolOptions.signal);
|
|
1048
|
+
const found: DocumentMeta[] = [];
|
|
1049
|
+
const missing: string[] = [];
|
|
1050
|
+
// One look-up at a time: a store that does not answer holds one thread of the pool, not one for each ID.
|
|
1051
|
+
for (const id of new Set<string>(ids)) {
|
|
1052
|
+
const meta = await metaFor(id, caller);
|
|
1053
|
+
if (meta) found.push(meta);
|
|
1054
|
+
else missing.push(id);
|
|
1055
|
+
}
|
|
1056
|
+
return { tools: tools(found, toolOptions), missing };
|
|
1016
1057
|
},
|
|
1017
1058
|
};
|
|
1059
|
+
|
|
1060
|
+
/**
|
|
1061
|
+
* The caller a document was handed to `tools` for (without `access`): its owner and scope, and the
|
|
1062
|
+
* tool set's signal. Undefined for a scope that is not valid: only that reads as missing.
|
|
1063
|
+
*/
|
|
1064
|
+
function handedCaller(meta: DocumentMeta, signal: AbortSignal | undefined): Caller | undefined {
|
|
1065
|
+
let caller: Caller;
|
|
1066
|
+
try {
|
|
1067
|
+
caller = callerOf({ owner: meta.owner, scope: meta.scope }, rules);
|
|
1068
|
+
} catch {
|
|
1069
|
+
return undefined;
|
|
1070
|
+
}
|
|
1071
|
+
return withSignal(caller, signal);
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/** `caller`, whose waits for the store end when `signal` aborts. */
|
|
1076
|
+
function withSignal(caller: Caller, signal: AbortSignal | undefined): Caller {
|
|
1077
|
+
return signal === undefined ? caller : { ...caller, signal };
|
|
1018
1078
|
}
|