llm-large-files 0.8.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +631 -0
- package/README.md +9 -10
- package/dist/access.d.ts +86 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +131 -0
- package/dist/access.js.map +1 -0
- package/dist/ask.d.ts +45 -1
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +181 -20
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +57 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +217 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +72 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +102 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +35 -9
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +14 -3
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +46 -35
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +19 -3
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +84 -12
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +18 -6
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +2 -0
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/index.d.ts +9 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +70 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +868 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +176 -34
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +332 -512
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -2
- package/dist/limiter.js +2 -2
- package/dist/map-reduce.js +3 -3
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +43 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +63 -3
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +234 -7
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +482 -121
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +18 -3
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +102 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +365 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +4 -3
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +7 -6
- package/dist/node/sse.js.map +1 -1
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.js.map +1 -1
- package/dist/ranged.d.ts +22 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +50 -12
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- package/dist/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +120 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +582 -139
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +25 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +135 -13
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +116 -13
- package/dist/types.d.ts.map +1 -1
- package/docs/README.md +17 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +12 -8
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +16 -7
- package/docs/guides/deployment.md +309 -87
- package/docs/guides/errors-and-reliability.md +161 -23
- package/docs/guides/own-adapter-and-loop.md +27 -10
- package/docs/guides/pdfs.md +123 -29
- package/docs/guides/storage.md +634 -143
- package/docs/guides/testing.md +78 -129
- package/docs/guides/vertex-and-gemini.md +10 -7
- package/docs/guides/web-app.md +322 -77
- package/docs/how-it-works.md +35 -8
- package/docs/measurements.md +63 -8
- package/docs/publishing.md +112 -36
- package/docs/reference/ask.md +154 -13
- package/docs/reference/errors-and-retries.md +166 -14
- package/docs/reference/events.md +53 -20
- package/docs/reference/gemini.md +70 -21
- package/docs/reference/library.md +709 -165
- package/docs/reference/node.md +633 -104
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +15 -5
- package/docs/security.md +316 -70
- package/docs/troubleshooting.md +165 -58
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +12 -3
- package/src/access.ts +144 -0
- package/src/ask.ts +230 -19
- package/src/cache.ts +20 -5
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +255 -0
- package/src/errors.ts +129 -15
- package/src/events.ts +86 -21
- package/src/evidence.ts +14 -3
- package/src/extract.ts +50 -33
- package/src/gemini/adapter.ts +97 -11
- package/src/gemini/chat.ts +20 -6
- package/src/gemini/index.ts +1 -1
- package/src/index.ts +9 -6
- package/src/ingest.ts +927 -0
- package/src/library.ts +482 -523
- package/src/limiter.ts +2 -2
- package/src/map-reduce.ts +3 -3
- package/src/model.ts +69 -5
- package/src/node/handlers.ts +691 -117
- package/src/node/index.ts +13 -2
- package/src/node/ingest-child.ts +23 -5
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +365 -0
- package/src/node/sse.ts +7 -6
- package/src/pdf-layout.ts +69 -11
- package/src/ranged.ts +42 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/source.ts +178 -0
- package/src/stores.ts +635 -140
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +150 -14
- package/src/types.ts +106 -13
package/src/node/index.ts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
|
-
export { createDocumentHandlers } from "./handlers.js";
|
|
2
|
-
export type {
|
|
1
|
+
export { createDocumentHandlers, uploadAnswerOf } from "./handlers.js";
|
|
2
|
+
export type {
|
|
3
|
+
DocumentHandlerOptions,
|
|
4
|
+
DocumentHandlers,
|
|
5
|
+
PreparedUpload,
|
|
6
|
+
PrepareUploadInfo,
|
|
7
|
+
RemovedContext,
|
|
8
|
+
UploadAnswer,
|
|
9
|
+
UploadedContext,
|
|
10
|
+
UploadedResult,
|
|
11
|
+
UploadSpoolOptions,
|
|
12
|
+
} from "./handlers.js";
|
|
3
13
|
export { sseMessageOf, writeSseEvents } from "./sse.js";
|
|
4
14
|
export type { SseMessage, SseWriteOptions } from "./sse.js";
|
|
5
15
|
export { createIsolatedExtractors } from "./isolated.js";
|
|
6
16
|
export type { IsolatedExtractorOptions, IsolatedExtractors } from "./isolated.js";
|
|
17
|
+
export { fileOriginals } from "./originals.js";
|
package/src/node/ingest-child.ts
CHANGED
|
@@ -2,14 +2,21 @@
|
|
|
2
2
|
// the built-in extractors, one at a time, and answers over the IPC channel. It runs with a heap
|
|
3
3
|
// limit of its own: a file that would exhaust the memory kills this process, not the server.
|
|
4
4
|
import { createPdfExtractor, extractText, type PdfExtractorOptions } from "../extract.js";
|
|
5
|
+
import { formatBytes } from "../plan.js";
|
|
6
|
+
import { readSource } from "../source.js";
|
|
5
7
|
import type { DocumentFormat, ExtractedText, ExtractProgress } from "../types.js";
|
|
6
8
|
|
|
7
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* A file to read: its bytes, or, for a file ingested from a path (0.9.0), its path, which the child
|
|
11
|
+
* reads itself, at most `maxUploadBytes + 1` bytes: the bytes are then empty, and the server reads
|
|
12
|
+
* nothing of the file.
|
|
13
|
+
*/
|
|
8
14
|
export type ChildJob = {
|
|
9
15
|
type: "extract";
|
|
10
16
|
id: number;
|
|
11
17
|
bytes: Uint8Array;
|
|
12
|
-
|
|
18
|
+
path?: string;
|
|
19
|
+
input: { name: string; mimeType: string; format: DocumentFormat; scannedPages?: number; maxTextBytes?: number; maxPages?: number; maxUploadBytes?: number; progress: boolean };
|
|
13
20
|
pdf?: PdfExtractorOptions;
|
|
14
21
|
};
|
|
15
22
|
|
|
@@ -37,13 +44,24 @@ async function run(job: ChildJob): Promise<void> {
|
|
|
37
44
|
try {
|
|
38
45
|
const options = JSON.stringify(job.pdf ?? {});
|
|
39
46
|
if (job.input.format === "pdf" && pdfExtractor?.options !== options) pdfExtractor = { options, extract: createPdfExtractor(job.pdf ?? {}) };
|
|
40
|
-
const { progress, ...input } = job.input;
|
|
41
|
-
|
|
47
|
+
const { progress, maxUploadBytes, ...input } = job.input;
|
|
48
|
+
// A file at a path is read here, once, never past the upload limit, and hashed as it is read.
|
|
49
|
+
let bytes = job.bytes;
|
|
50
|
+
let file: ExtractedText["file"];
|
|
51
|
+
if (job.path !== undefined) {
|
|
52
|
+
const most = maxUploadBytes ?? Number.POSITIVE_INFINITY;
|
|
53
|
+
const read = await readSource(job.path, most, { keep: true });
|
|
54
|
+
if (read.size === 0) throw new Error(`${input.name} is empty.`);
|
|
55
|
+
if (read.size > most) throw new Error(`${input.name} is larger than the ${formatBytes(most)} upload limit.`);
|
|
56
|
+
bytes = read.bytes!;
|
|
57
|
+
file = { bytes: read.size, sha256: read.sha256 };
|
|
58
|
+
}
|
|
59
|
+
const result = await extractText(bytes, {
|
|
42
60
|
...input,
|
|
43
61
|
...(progress ? { onProgress: (report: ExtractProgress) => send({ type: "progress", id: job.id, progress: report }) } : {}),
|
|
44
62
|
}, job.input.format === "pdf" && pdfExtractor ? { pdf: pdfExtractor.extract } : {});
|
|
45
63
|
const { text, pages, encoding, replacedCharacters } = result;
|
|
46
|
-
send({ type: "done", id: job.id, result: { text, ...(pages !== undefined ? { pages } : {}), ...(encoding !== undefined ? { encoding } : {}), ...(replacedCharacters !== undefined ? { replacedCharacters } : {}) } });
|
|
64
|
+
send({ type: "done", id: job.id, result: { text, ...(pages !== undefined ? { pages } : {}), ...(encoding !== undefined ? { encoding } : {}), ...(replacedCharacters !== undefined ? { replacedCharacters } : {}), ...(file ? { file } : {}) } });
|
|
47
65
|
} catch (error) {
|
|
48
66
|
// A system error keeps its code and system call: the server tells it apart from a file that cannot be read.
|
|
49
67
|
const { code, syscall } = (error ?? {}) as { code?: unknown; syscall?: unknown };
|
package/src/node/isolated.ts
CHANGED
|
@@ -162,7 +162,9 @@ const MAX_HEAP_MB = 1_048_576;
|
|
|
162
162
|
* });
|
|
163
163
|
* ```
|
|
164
164
|
*
|
|
165
|
-
* A file costs its bytes copied to the child and its text copied back.
|
|
165
|
+
* A file costs its bytes copied to the child and its text copied back. A file ingested from a path
|
|
166
|
+
* (`IngestFromSource`) is read by its child instead (`readsPath`, 0.9.0): the server reads none of
|
|
167
|
+
* it, and holds none of it while it waits for a child. The children load the same
|
|
166
168
|
* optional dependencies (`unpdf`, `jszip`, `@cantoo/pdf-lib`) the server would.
|
|
167
169
|
*/
|
|
168
170
|
export function createIsolatedExtractors(options: IsolatedExtractorOptions = {}): IsolatedExtractors {
|
|
@@ -391,16 +393,20 @@ export function createIsolatedExtractors(options: IsolatedExtractorOptions = {})
|
|
|
391
393
|
if (timeoutMs > 0) {
|
|
392
394
|
timer = setTimeout(() => stop(entry, new IngestError("timeout", `${job.input.name} took too long to read (more than ${formatDuration(timeoutMs)}). Split it, or save it as plain text, and attach that.`)), timeoutMs);
|
|
393
395
|
}
|
|
394
|
-
const { name, mimeType, format, scannedPages, maxTextBytes, maxPages } = job.input;
|
|
396
|
+
const { name, mimeType, format, scannedPages, maxTextBytes, maxPages, path, maxUploadBytes } = job.input;
|
|
397
|
+
// A file at a path (0.9.0) goes as its path: the child reads it, and its bytes never wait here.
|
|
398
|
+
const fromPath = typeof path === "string" && job.bytes.byteLength === 0;
|
|
395
399
|
const message: ChildJob = {
|
|
396
400
|
type: "extract",
|
|
397
401
|
id: job.id,
|
|
398
402
|
bytes: job.bytes,
|
|
403
|
+
...(fromPath ? { path } : {}),
|
|
399
404
|
input: {
|
|
400
405
|
name, mimeType, format,
|
|
401
406
|
...(scannedPages !== undefined ? { scannedPages } : {}),
|
|
402
407
|
...(maxTextBytes !== undefined && Number.isFinite(maxTextBytes) ? { maxTextBytes } : {}),
|
|
403
408
|
...(maxPages !== undefined ? { maxPages } : {}),
|
|
409
|
+
...(fromPath && typeof maxUploadBytes === "number" && Number.isFinite(maxUploadBytes) ? { maxUploadBytes } : {}),
|
|
404
410
|
progress: typeof job.input.onProgress === "function",
|
|
405
411
|
},
|
|
406
412
|
...(options.pdf ? { pdf: options.pdf } : {}),
|
|
@@ -413,7 +419,8 @@ export function createIsolatedExtractors(options: IsolatedExtractorOptions = {})
|
|
|
413
419
|
}, () => undefined);
|
|
414
420
|
}
|
|
415
421
|
|
|
416
|
-
|
|
422
|
+
// Reads a file ingested from a path in the child (`readsPath`): the server does not read it.
|
|
423
|
+
const extract: Extractor = Object.assign((bytes: Uint8Array, input: ExtractInput) => new Promise<ExtractedText>((resolve, reject) => {
|
|
417
424
|
if (closed) {
|
|
418
425
|
reject(new IngestError("busy", "The server is shutting down. Try again in a moment.", { retryAfterMs: BUSY_RETRY_MS }));
|
|
419
426
|
return;
|
|
@@ -440,7 +447,7 @@ export function createIsolatedExtractors(options: IsolatedExtractorOptions = {})
|
|
|
440
447
|
}
|
|
441
448
|
queue.push(job);
|
|
442
449
|
pump();
|
|
443
|
-
});
|
|
450
|
+
}), { readsPath: true });
|
|
444
451
|
|
|
445
452
|
const formats = options.formats ?? DEFAULT_FORMATS;
|
|
446
453
|
return {
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// `fileOriginals`: the uploaded files an application keeps in a folder of its own, read back by
|
|
2
|
+
// their ref (`IngestInput.original`) for `LargeFilesOptions.originals`. Read only: nothing here
|
|
3
|
+
// writes, moves or deletes a file. New in 0.9.0.
|
|
4
|
+
import { realpath } from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import type { OriginalReadContext, OriginalsReader } from "../library.js";
|
|
7
|
+
import { readSource } from "../source.js";
|
|
8
|
+
|
|
9
|
+
/** The longest ref read, as `IngestInput.original.ref` allows. */
|
|
10
|
+
const MAX_REF_LENGTH = 1_024;
|
|
11
|
+
|
|
12
|
+
/** The refusal of a ref that does not name a file inside the folder. It does not repeat the ref. */
|
|
13
|
+
const OUTSIDE = "The ref of an original must be a relative path to a file inside the folder of fileOriginals.";
|
|
14
|
+
|
|
15
|
+
const codeOf = (error: unknown): unknown => (error as { code?: unknown } | null)?.code;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A read that found no file to read: none there, a part of its path that is a file, a link at its
|
|
19
|
+
* name (which is not followed: `O_NOFOLLOW`; Linux and macOS say ELOOP, FreeBSD EMLINK), or a folder
|
|
20
|
+
* or another thing that is not a file (as `readSource` says).
|
|
21
|
+
*/
|
|
22
|
+
const notThere = (error: unknown) => ["ENOENT", "ENOTDIR", "ELOOP", "EMLINK", "EISDIR", "EINVAL"].includes(codeOf(error) as string);
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Reads the uploaded files that an application keeps under the folder `root`, for
|
|
26
|
+
* `createLargeFiles({ originals })`. A ref (`IngestInput.original.ref`) is a path relative to `root`,
|
|
27
|
+
* such as `${userId}/${chatId}/uploads/${uploadId}`:
|
|
28
|
+
*
|
|
29
|
+
* - One that is not inside `root` (absolute elsewhere, or with ".." that leads out) is a TypeError,
|
|
30
|
+
* which the library passes on as a `DocumentStoreError` with it as `cause`.
|
|
31
|
+
* - One with a link at any level below `root`, whether it points inside or out, reads as missing
|
|
32
|
+
* (undefined): its real path must be the path it names. `root` itself may be a link. The file
|
|
33
|
+
* is opened without following a link at its name, where the platform can (not on Windows).
|
|
34
|
+
* - A file that is not there, or a folder, reads as missing.
|
|
35
|
+
* - A file is read once, and no more than one byte past the size it had at ingest
|
|
36
|
+
* (`OriginalReadContext.bytes`): the library then finds that it has changed.
|
|
37
|
+
*
|
|
38
|
+
* New in 0.9.0.
|
|
39
|
+
*/
|
|
40
|
+
export function fileOriginals(root: string): OriginalsReader {
|
|
41
|
+
if (typeof root !== "string" || root.length === 0 || root.includes("\0")) throw new TypeError("fileOriginals needs the path of a folder: a string that is not empty.");
|
|
42
|
+
const base = path.resolve(root);
|
|
43
|
+
const prefix = base.endsWith(path.sep) ? base : `${base}${path.sep}`;
|
|
44
|
+
/** The real path of `root`, found once; found again after a failure. */
|
|
45
|
+
let realBase: Promise<string> | undefined;
|
|
46
|
+
return Object.freeze({
|
|
47
|
+
async read(ref: string, context?: OriginalReadContext): Promise<Uint8Array | undefined> {
|
|
48
|
+
if (typeof ref !== "string" || ref.length === 0 || ref.length > MAX_REF_LENGTH || ref.includes("\0")) throw new TypeError(OUTSIDE);
|
|
49
|
+
const file = path.resolve(base, ref);
|
|
50
|
+
if (!file.startsWith(prefix) || file.length === prefix.length) throw new TypeError(OUTSIDE);
|
|
51
|
+
let real: string;
|
|
52
|
+
try {
|
|
53
|
+
real = await realpath(file);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (notThere(error)) return undefined;
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
realBase ??= realpath(base);
|
|
59
|
+
let realRoot: string;
|
|
60
|
+
try {
|
|
61
|
+
realRoot = await realBase;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
realBase = undefined;
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
// A link at any level below the root: its real path is not the path the ref names.
|
|
67
|
+
if (real !== path.join(realRoot, path.relative(base, file))) return undefined;
|
|
68
|
+
const expected = context?.bytes;
|
|
69
|
+
const most = typeof expected === "number" && Number.isSafeInteger(expected) && expected >= 0 ? expected : Number.POSITIVE_INFINITY;
|
|
70
|
+
try {
|
|
71
|
+
return (await readSource(file, most, { keep: true })).bytes;
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (notThere(error)) return undefined;
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
}
|
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
// The body of an upload, as `createDocumentHandlers` receives it: read into memory, or written to a
|
|
2
|
+
// file as it arrives. The file is the path `prepareUpload` gave (the application's, kept once its
|
|
3
|
+
// document is stored), or a temporary file of the spool (`uploadSpool`), removed once the ingest
|
|
4
|
+
// ends. Either way each piece of the body is counted against the upload limit (413) and waited for
|
|
5
|
+
// no longer than the idle time (408), and so is each call to the disk (500 "ETIMEDOUT"; a removal
|
|
6
|
+
// past it is left to end alone, and the upload answered all the same). A file is always made new:
|
|
7
|
+
// opened with "wx", so that a file or a link already at its name is never written through. New in
|
|
8
|
+
// 0.9.0; the reading into memory moved here from handlers.ts.
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { open, realpath, rm, type FileHandle } from "node:fs/promises";
|
|
11
|
+
import type { IncomingMessage } from "node:http";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { IngestError } from "../errors.js";
|
|
14
|
+
|
|
15
|
+
export class HttpError extends Error {
|
|
16
|
+
/** `close`: answer, then close the connection, without waiting for the rest of the body. */
|
|
17
|
+
constructor(readonly status: number, message: string, readonly close = false) {
|
|
18
|
+
super(message);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** What an upload refused for want of room is told: by `maxPendingUploadBytes`, or `maxSpooledUploadBytes`. */
|
|
23
|
+
const BUSY = "The server is receiving other files right now. Try again in a moment.";
|
|
24
|
+
/** When a client refused for want of room is told to try again. */
|
|
25
|
+
export const BUSY_RETRY_MS = 5_000;
|
|
26
|
+
/** What an upload is told when the disk it is written to is full (`ENOSPC`, `EDQUOT`). */
|
|
27
|
+
const NO_ROOM = "The server has no room for this file right now. Try again later.";
|
|
28
|
+
/** When a client refused for a full disk is told to try again. */
|
|
29
|
+
export const NO_ROOM_RETRY_MS = 30_000;
|
|
30
|
+
/** What an upload is told when a file is already at the path `prepareUpload` gave. */
|
|
31
|
+
const ALREADY_SAVED = "A file is already saved for this upload.";
|
|
32
|
+
|
|
33
|
+
/** The longest a timer can wait. */
|
|
34
|
+
const LONGEST_TIMER_MS = 2_147_483_647;
|
|
35
|
+
|
|
36
|
+
/** Whether `idleMs` is a time a timer can wait: 0 and Infinity are no limit. */
|
|
37
|
+
const timed = (idleMs: number) => idleMs > 0 && idleMs <= LONGEST_TIMER_MS;
|
|
38
|
+
|
|
39
|
+
/** `next`, or the error `late` makes once `idleMs` pass without it. */
|
|
40
|
+
function within<T>(next: Promise<T>, idleMs: number, late: () => Error): Promise<T> {
|
|
41
|
+
// Once the upload is refused, what it waited on ends later (with the connection, or when the
|
|
42
|
+
// disk answers), or never: nobody awaits it.
|
|
43
|
+
next.catch(() => undefined);
|
|
44
|
+
let settled = false;
|
|
45
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
46
|
+
const idle = new Promise<never>((_, reject) => {
|
|
47
|
+
timer = setTimeout(() => {
|
|
48
|
+
// After the thread was held longer than `idleMs`, timers run before the data that came in the
|
|
49
|
+
// meantime is read: it is read first, in this turn of the loop, and the upload goes on.
|
|
50
|
+
setImmediate(() => {
|
|
51
|
+
if (!settled) reject(late());
|
|
52
|
+
});
|
|
53
|
+
}, idleMs);
|
|
54
|
+
});
|
|
55
|
+
return Promise.race([next.finally(() => (settled = true)), idle]).finally(() => clearTimeout(timer));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** `next`, or a 408 once `idleMs` pass without it. */
|
|
59
|
+
function withinIdle<T>(next: Promise<T>, idleMs: number): Promise<T> {
|
|
60
|
+
const after = idleMs >= 1_000 ? `${Math.round(idleMs / 1_000)} s` : `${idleMs} ms`;
|
|
61
|
+
return within(next, idleMs, () => new HttpError(408, `The upload stopped arriving: nothing came for ${after}. Send it again.`, true));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A call to the disk for an upload's file (`syscall`: the check of its folders, its opening, a
|
|
66
|
+
* write, its closing) that did not end within the idle time: the volume stopped answering.
|
|
67
|
+
* Answered as a system error, with its code only: 500 "Upload failed (ETIMEDOUT).".
|
|
68
|
+
*/
|
|
69
|
+
class DiskTimeout extends Error {
|
|
70
|
+
readonly code = "ETIMEDOUT";
|
|
71
|
+
constructor(readonly syscall: string) {
|
|
72
|
+
super("A call to the disk for the upload's file did not end in time.");
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `call`, a call to the disk, or a `DiskTimeout` once `idleMs` pass without it (0 for no limit). */
|
|
77
|
+
const inTime = <T>(call: Promise<T>, idleMs: number, syscall: string): Promise<T> => (timed(idleMs) ? within(call, idleMs, () => new DiskTimeout(syscall)) : call);
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Waits for `call`, a call to the disk whose end nobody needs (a removal), no longer than `idleMs`
|
|
81
|
+
* (0 for no limit): past it, the call goes on alone, and the upload is answered all the same.
|
|
82
|
+
* Never rejects.
|
|
83
|
+
*/
|
|
84
|
+
const atMost = (call: Promise<unknown>, idleMs: number): Promise<void> => inTime(call, idleMs, "unlink").then(() => undefined, () => undefined);
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The body a framework already read into `request.body` (a `Buffer`, as `express.raw()` leaves
|
|
88
|
+
* it), or undefined. An object with fields there (`express.json()`) is a 400.
|
|
89
|
+
*/
|
|
90
|
+
export function parsedBody(request: IncomingMessage): Uint8Array | undefined {
|
|
91
|
+
const parsed = (request as IncomingMessage & { body?: unknown }).body;
|
|
92
|
+
if (parsed instanceof Uint8Array) return parsed;
|
|
93
|
+
if (parsed !== undefined && typeof parsed === "object" && parsed !== null && Object.keys(parsed).length) {
|
|
94
|
+
throw new HttpError(400, "The upload body was already parsed by another middleware. Mount the upload route before body parsers, or send Content-Type: application/octet-stream.");
|
|
95
|
+
}
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Reads the request's body a piece at a time and gives each to `take`, which may wait (a write to a
|
|
101
|
+
* file): the next piece is read once it is done. A body over `limit`, declared or read, is a 413:
|
|
102
|
+
* the piece that passes it is not given. `idleMs`: the longest wait for the next piece (0 for no
|
|
103
|
+
* limit). Returns the size of the body.
|
|
104
|
+
*/
|
|
105
|
+
async function eachPiece(request: IncomingMessage, limit: number, idleMs: number, take: (piece: Buffer) => void | Promise<void>): Promise<number> {
|
|
106
|
+
const declared = Number(request.headers["content-length"]);
|
|
107
|
+
if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, "");
|
|
108
|
+
let size = 0;
|
|
109
|
+
// Leaving the loop early must not destroy the request: the rest of the body is drained after
|
|
110
|
+
// the answer (see `drain` in handlers.ts), which a destroyed request would not do.
|
|
111
|
+
const pieces = request.iterator({ destroyOnReturn: false });
|
|
112
|
+
const waits = timed(idleMs);
|
|
113
|
+
try {
|
|
114
|
+
for (;;) {
|
|
115
|
+
const next = pieces.next();
|
|
116
|
+
const { done, value: chunk } = waits ? await withinIdle(next, idleMs) : await next;
|
|
117
|
+
if (done) break;
|
|
118
|
+
const piece = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
|
|
119
|
+
size += piece.byteLength;
|
|
120
|
+
if (size > limit) throw new HttpError(413, "");
|
|
121
|
+
const taking = take(piece);
|
|
122
|
+
if (taking) await taking;
|
|
123
|
+
}
|
|
124
|
+
} finally {
|
|
125
|
+
// As a `for await` does on leaving early; the request is not destroyed (see above).
|
|
126
|
+
void pieces.return?.().catch(() => undefined);
|
|
127
|
+
}
|
|
128
|
+
return size;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Reads the raw body into memory, or uses one a framework already parsed into a Buffer (e.g.
|
|
133
|
+
* express.raw()). `idleMs`: the longest wait for the next piece of the body (0 for no limit).
|
|
134
|
+
*/
|
|
135
|
+
export async function readBody(request: IncomingMessage, limit: number, idleMs = 0): Promise<Uint8Array> {
|
|
136
|
+
const parsed = parsedBody(request);
|
|
137
|
+
if (parsed) {
|
|
138
|
+
if (parsed.byteLength > limit) throw new HttpError(413, "");
|
|
139
|
+
return parsed;
|
|
140
|
+
}
|
|
141
|
+
const pieces: Buffer[] = [];
|
|
142
|
+
await eachPiece(request, limit, idleMs, (piece) => void pieces.push(piece));
|
|
143
|
+
const body = Buffer.concat(pieces);
|
|
144
|
+
return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** The most bytes given to one write: each is waited for no longer than the idle time. */
|
|
148
|
+
const WRITE_BYTES = 1024 * 1024;
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Writes all of `bytes` at the end of what `handle` has written, a MiB at a time at most (a body a
|
|
152
|
+
* framework read may be the whole upload), each write within `idleMs`.
|
|
153
|
+
*/
|
|
154
|
+
async function writeAll(handle: FileHandle, bytes: Uint8Array, idleMs: number): Promise<void> {
|
|
155
|
+
for (let at = 0; at < bytes.byteLength; ) {
|
|
156
|
+
const { bytesWritten } = await inTime(handle.write(bytes, at, Math.min(WRITE_BYTES, bytes.byteLength - at)), idleMs, "write");
|
|
157
|
+
if (bytesWritten <= 0) throw Object.assign(new Error("The upload could not be written."), { code: "EIO", syscall: "write" });
|
|
158
|
+
at += bytesWritten;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const codeOf = (error: unknown): unknown => (error as { code?: unknown } | null)?.code;
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* An error of writing an upload's file, as the upload is answered: a file already at the path is a
|
|
166
|
+
* 409 (it was not written, nor removed), without the code "exists", which is a document ID's that
|
|
167
|
+
* is taken; and a full disk "busy" (503, with a wait). Any other error is passed on: a 413 or a 408
|
|
168
|
+
* of the body, a client that left, or a system error, answered with its code only (a folder that
|
|
169
|
+
* is not there is `ENOENT`, a disk that does not answer `ETIMEDOUT`).
|
|
170
|
+
*/
|
|
171
|
+
function writeError(error: unknown): unknown {
|
|
172
|
+
const code = codeOf(error);
|
|
173
|
+
if (code === "EEXIST") return new HttpError(409, ALREADY_SAVED);
|
|
174
|
+
if (code === "ENOSPC" || code === "EDQUOT") return new IngestError("busy", NO_ROOM, { cause: error, retryAfterMs: NO_ROOM_RETRY_MS });
|
|
175
|
+
return error;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Removes a file the handlers wrote, once nobody needs it. A removal that fails (a file another
|
|
180
|
+
* process holds open, on Windows) is tried a few times, then left: the upload is answered all the
|
|
181
|
+
* same.
|
|
182
|
+
*/
|
|
183
|
+
export async function removeFile(file: string): Promise<void> {
|
|
184
|
+
await rm(file, { force: true, maxRetries: 3, retryDelay: 50 }).catch(() => undefined);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* After a failure, closes `handle` and removes `file`, each waited for no longer than `idleMs`.
|
|
189
|
+
* When a call to the disk did not end in time (`hung`), or the closing does not, the handle closes
|
|
190
|
+
* only once that call ends, if ever, and the volume may hold a removal too: neither is waited for,
|
|
191
|
+
* and the upload is answered at once. The file is removed now (Node opens a file so that it can be
|
|
192
|
+
* removed while open, on Windows too), and once more when the handle closes if that removal failed.
|
|
193
|
+
*/
|
|
194
|
+
async function discard(handle: FileHandle, file: string, hung: boolean, idleMs: number): Promise<void> {
|
|
195
|
+
const closed = handle.close().catch(() => undefined);
|
|
196
|
+
if (!hung && (await inTime(closed, idleMs, "close").then(() => true, () => false))) {
|
|
197
|
+
await atMost(removeFile(file), idleMs);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
void rm(file, { force: true }).catch(() => closed.then(() => removeFile(file)));
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Writes the request's body to a new file at `file`, as it arrives, and returns its size. The file
|
|
205
|
+
* is opened with "wx": one already there, or a link at its name, is never written through (a 409),
|
|
206
|
+
* and is left as it is. It is made with `mode`, minus the umask. A body a framework already read
|
|
207
|
+
* (`request.body`) is written whole. Each call to the disk (the opening, each write, the closing)
|
|
208
|
+
* is waited for no longer than `idleMs`: past it, the upload fails with a `DiskTimeout`. On any
|
|
209
|
+
* failure (a 413 or a 408, a client that left, a full disk, a disk that does not answer), the file
|
|
210
|
+
* is removed before the error is thrown, or once the disk answers: the closing and the removal are
|
|
211
|
+
* waited for no longer than `idleMs` either.
|
|
212
|
+
*/
|
|
213
|
+
export async function writeBody(request: IncomingMessage, file: string, options: { limit: number; idleMs: number; mode: number }): Promise<number> {
|
|
214
|
+
const parsed = parsedBody(request);
|
|
215
|
+
if (parsed && parsed.byteLength > options.limit) throw new HttpError(413, "");
|
|
216
|
+
const { idleMs } = options;
|
|
217
|
+
const opening = open(file, "wx", options.mode);
|
|
218
|
+
let handle: FileHandle;
|
|
219
|
+
try {
|
|
220
|
+
handle = await inTime(opening, idleMs, "open");
|
|
221
|
+
} catch (error) {
|
|
222
|
+
// An opening that ends after all made the file: it is closed and removed then.
|
|
223
|
+
if (error instanceof DiskTimeout) void opening.then((late) => discard(late, file, false, idleMs), () => undefined);
|
|
224
|
+
throw writeError(error);
|
|
225
|
+
}
|
|
226
|
+
let size: number;
|
|
227
|
+
try {
|
|
228
|
+
if (parsed) {
|
|
229
|
+
await writeAll(handle, parsed, idleMs);
|
|
230
|
+
size = parsed.byteLength;
|
|
231
|
+
} else {
|
|
232
|
+
size = await eachPiece(request, options.limit, idleMs, (piece) => writeAll(handle, piece, idleMs));
|
|
233
|
+
}
|
|
234
|
+
// A disk that is full may say so only when the file is closed, and a network volume writes
|
|
235
|
+
// there what it kept back.
|
|
236
|
+
await inTime(handle.close(), idleMs, "close");
|
|
237
|
+
} catch (error) {
|
|
238
|
+
await discard(handle, file, error instanceof DiskTimeout, idleMs);
|
|
239
|
+
throw writeError(error);
|
|
240
|
+
}
|
|
241
|
+
return size;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Refuses, before the body is read, a `file` that `fileOriginals` could not read back by its `ref`:
|
|
246
|
+
* when the path ends with the ref (`<root>/<ref>`, as `fileOriginals(root)` reads it), a link in a
|
|
247
|
+
* folder below that root (the root itself may be one). `"wx"` refuses a link only at the file's own
|
|
248
|
+
* name: a link in a folder above it is followed, and the upload would be stored with a ref that is
|
|
249
|
+
* never read back, its body written where the link leads. Refused as a system error, `ELOOP`: 500
|
|
250
|
+
* "Upload failed (ELOOP).". A ref that is not the end of the path is one of a reader of your own,
|
|
251
|
+
* and a folder that is not there is the opening's to tell (`ENOENT`): neither is checked here. The
|
|
252
|
+
* check of the folders is waited for no longer than `idleMs` (0 for no limit): past it, the upload
|
|
253
|
+
* fails with a `DiskTimeout`, before anything is written.
|
|
254
|
+
*/
|
|
255
|
+
export async function checkRefFolders(file: string, ref: string, idleMs: number): Promise<void> {
|
|
256
|
+
const target = path.resolve(file);
|
|
257
|
+
let tail = path.normalize(ref);
|
|
258
|
+
while (tail.endsWith(path.sep)) tail = tail.slice(0, -1);
|
|
259
|
+
if (!tail || tail === "." || path.isAbsolute(tail) || tail === ".." || tail.startsWith(`..${path.sep}`) || !target.endsWith(`${path.sep}${tail}`)) return;
|
|
260
|
+
const root = target.slice(0, target.length - tail.length - 1) || path.parse(target).root;
|
|
261
|
+
const folder = path.dirname(target);
|
|
262
|
+
let real: string;
|
|
263
|
+
let realRoot: string;
|
|
264
|
+
try {
|
|
265
|
+
// One look after the other, within the one limit: a look that does not answer holds a thread of
|
|
266
|
+
// libuv's pool (4 by default) until the volume answers, so each upload holds one, not two. The
|
|
267
|
+
// root first: when the folder is the root (a ref of one part), it is looked at once.
|
|
268
|
+
[real, realRoot] = await inTime((async () => {
|
|
269
|
+
const rootFound = await realpath(root);
|
|
270
|
+
return [folder === root ? rootFound : await realpath(folder), rootFound] as const;
|
|
271
|
+
})(), idleMs, "realpath");
|
|
272
|
+
} catch (error) {
|
|
273
|
+
// A volume that does not answer fails the upload; any other error is the opening's to tell.
|
|
274
|
+
if (error instanceof DiskTimeout) throw error;
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
if (real !== path.join(realRoot, path.relative(root, folder))) {
|
|
278
|
+
throw Object.assign(new Error("A folder on the path of the upload's file is a link."), { code: "ELOOP", syscall: "open" });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** A new name for a temporary file of the spool in `directory`: never one that is there ("wx" makes sure). */
|
|
283
|
+
export const spoolFileIn = (directory: string): string => path.join(directory, `llf-upload-${randomUUID()}`);
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* The file an upload's body was written to, while its ingest runs. `kept`: the application's file
|
|
287
|
+
* (`prepareUpload`), which stays once the document is stored, and is removed when the upload fails.
|
|
288
|
+
* Otherwise a temporary file of the spool, removed once the ingest ends, whatever the end. The
|
|
289
|
+
* removal is waited for no longer than `idleMs` (0 for no limit): on a volume that stopped
|
|
290
|
+
* answering it goes on alone, and the upload is answered, and gives its room back, all the same.
|
|
291
|
+
*/
|
|
292
|
+
export class BodyFile {
|
|
293
|
+
#stored = false;
|
|
294
|
+
#removing: Promise<void> | undefined;
|
|
295
|
+
readonly #idleMs: number;
|
|
296
|
+
|
|
297
|
+
constructor(readonly path: string, readonly kept: boolean, idleMs: number) {
|
|
298
|
+
this.#idleMs = idleMs;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Follows the ingest of the file (`ingesting`): when it ends, a temporary file is removed, and
|
|
303
|
+
* the application's file too when it failed. It settles once that is done, as the ingest did.
|
|
304
|
+
*/
|
|
305
|
+
async settle<T>(ingesting: Promise<T>): Promise<T> {
|
|
306
|
+
try {
|
|
307
|
+
const value = await ingesting;
|
|
308
|
+
this.#stored = true;
|
|
309
|
+
return value;
|
|
310
|
+
} finally {
|
|
311
|
+
await this.end();
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Removes the file, once: for an upload that failed after its document was stored (`onUploaded` threw). */
|
|
316
|
+
remove(): Promise<void> {
|
|
317
|
+
return (this.#removing ??= atMost(removeFile(this.path), this.#idleMs));
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** At the end of the upload: removes a temporary file, or the application's file of a document that was not stored. */
|
|
321
|
+
async end(): Promise<void> {
|
|
322
|
+
if (!this.kept || !this.#stored) await this.remove();
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** Room taken by one upload in a `Room`. */
|
|
327
|
+
export type Held = {
|
|
328
|
+
/** The upload's size, once known: its room becomes that. */
|
|
329
|
+
resize(bytes: number): void;
|
|
330
|
+
/** Gives the room back, once. */
|
|
331
|
+
release(): void;
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Bytes of uploads held at once, under `limit`: `maxPendingUploadBytes` for the bodies held in
|
|
336
|
+
* memory, `maxSpooledUploadBytes` for the files of the spool. `Infinity` counts nothing.
|
|
337
|
+
*/
|
|
338
|
+
export class Room {
|
|
339
|
+
#used = 0;
|
|
340
|
+
|
|
341
|
+
constructor(readonly limit: number) {}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Room for an upload of `bytes` (at most the limit itself, so that the count stays a number with
|
|
345
|
+
* an upload limit of Infinity), taken before its body is read. One that would bring the room
|
|
346
|
+
* past its limit while another upload holds some is refused: an `IngestError` "busy", answered
|
|
347
|
+
* 503 with a wait. One upload alone is always taken.
|
|
348
|
+
*/
|
|
349
|
+
take(bytes: number): Held {
|
|
350
|
+
if (this.limit === Number.POSITIVE_INFINITY) return { resize: () => undefined, release: () => undefined };
|
|
351
|
+
let held = Math.min(bytes, this.limit);
|
|
352
|
+
if (this.#used > 0 && this.#used + held > this.limit) throw new IngestError("busy", BUSY, { retryAfterMs: BUSY_RETRY_MS });
|
|
353
|
+
this.#used += held;
|
|
354
|
+
return {
|
|
355
|
+
resize: (size) => {
|
|
356
|
+
this.#used += size - held;
|
|
357
|
+
held = size;
|
|
358
|
+
},
|
|
359
|
+
release: () => {
|
|
360
|
+
this.#used -= held;
|
|
361
|
+
held = 0;
|
|
362
|
+
},
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
}
|
package/src/node/sse.ts
CHANGED
|
@@ -41,20 +41,21 @@ const oneLine = (value: string | number) => String(value).replace(/[\r\n]+/g, "
|
|
|
41
41
|
* What `writeSseEvents` sends for an event by default: the event itself, `type`, `seq`, `runId`
|
|
42
42
|
* and `time` included, with two smaller than they are. `run.finish` has a `result` without
|
|
43
43
|
* `toolTurns`, `plan`, `budget` and `lastUsage`: `{ answered, text, finishReason, blockReason,
|
|
44
|
-
* steps, evidence, turns, usage }` (keep `toolTurns` on the server, with the
|
|
45
|
-
* `run.error` has its `error` and a `partial` with only the `steps`, `evidence
|
|
46
|
-
* partial result. Every other event is sent as it is.
|
|
44
|
+
* steps, evidence, turns, usage, missing }` (keep `toolTurns` on the server, with the
|
|
45
|
+
* conversation). `run.error` has its `error` and a `partial` with only the `steps`, `evidence`,
|
|
46
|
+
* `usage` and `missing` of the partial result. Every other event is sent as it is. `missing`, the
|
|
47
|
+
* documents a question answered without, is new in 0.9.0.
|
|
47
48
|
*/
|
|
48
49
|
export function sseMessageOf<E extends { type: string; seq: number }>(event: E): SseMessage {
|
|
49
50
|
const ask = event as unknown as AskEvent;
|
|
50
51
|
if (ask.type === "run.finish") {
|
|
51
52
|
const { type, seq, runId, time } = ask;
|
|
52
|
-
const { answered, text, finishReason, blockReason, steps, evidence, turns, usage } = ask.result;
|
|
53
|
-
return { event: type, id: seq, data: { type, seq, runId, time, result: { answered, text, finishReason, blockReason, steps, evidence, turns, usage } } };
|
|
53
|
+
const { answered, text, finishReason, blockReason, steps, evidence, turns, usage, missing } = ask.result;
|
|
54
|
+
return { event: type, id: seq, data: { type, seq, runId, time, result: { answered, text, finishReason, blockReason, steps, evidence, turns, usage, missing } } };
|
|
54
55
|
}
|
|
55
56
|
if (ask.type === "run.error") {
|
|
56
57
|
const { type, seq, runId, time, error } = ask;
|
|
57
|
-
const partial = ask.partial && { steps: ask.partial.steps, evidence: ask.partial.evidence, usage: ask.partial.usage };
|
|
58
|
+
const partial = ask.partial && { steps: ask.partial.steps, evidence: ask.partial.evidence, usage: ask.partial.usage, missing: ask.partial.missing };
|
|
58
59
|
return { event: type, id: seq, data: { type, seq, runId, time, error, partial } };
|
|
59
60
|
}
|
|
60
61
|
return { event: event.type, id: event.seq, data: event };
|