llm-large-files 0.9.0 → 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 +446 -0
- package/README.md +13 -7
- package/dist/access.d.ts +45 -3
- package/dist/access.d.ts.map +1 -1
- package/dist/access.js +106 -3
- package/dist/access.js.map +1 -1
- 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 +115 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +572 -103
- package/dist/ask.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/error-info.d.ts +13 -0
- package/dist/error-info.d.ts.map +1 -1
- package/dist/error-info.js +37 -1
- package/dist/error-info.js.map +1 -1
- package/dist/errors.d.ts +3 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +3 -1
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +25 -7
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +21 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +6 -1
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +35 -4
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +68 -29
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +28 -55
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -27
- 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 +3 -3
- 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 +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +9 -1
- package/dist/ingest.d.ts.map +1 -1
- package/dist/ingest.js +50 -25
- package/dist/ingest.js.map +1 -1
- package/dist/library.d.ts +129 -2
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +224 -149
- 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 +804 -58
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +36 -4
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +17 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +29 -8
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +148 -126
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.js +2 -2
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/spool.d.ts +9 -5
- package/dist/node/spool.d.ts.map +1 -1
- package/dist/node/spool.js +28 -15
- package/dist/node/spool.js.map +1 -1
- package/dist/node/sse.d.ts +6 -5
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +8 -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-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 +2 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +16 -3
- package/dist/ranged.js.map +1 -1
- 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/stores.d.ts +6 -0
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +82 -11
- package/dist/stores.js.map +1 -1
- package/dist/tools.d.ts +22 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +323 -76
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +49 -1
- 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 +4 -0
- package/docs/guides/anthropic.md +5 -2
- package/docs/guides/conversations.md +1 -1
- package/docs/guides/costs-and-limits.md +132 -36
- package/docs/guides/deployment.md +106 -13
- package/docs/guides/errors-and-reliability.md +157 -45
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +33 -6
- package/docs/guides/pdfs.md +96 -7
- package/docs/guides/storage.md +46 -3
- package/docs/guides/testing.md +71 -0
- package/docs/guides/vertex-and-gemini.md +159 -50
- package/docs/guides/web-app.md +10 -6
- package/docs/how-it-works.md +120 -22
- package/docs/measurements.md +172 -5
- package/docs/publishing.md +76 -4
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +262 -35
- package/docs/reference/errors-and-retries.md +30 -2
- package/docs/reference/events.md +27 -10
- package/docs/reference/gemini.md +184 -68
- package/docs/reference/library.md +190 -23
- package/docs/reference/node.md +51 -17
- package/docs/reference/openai.md +21 -10
- package/docs/reference/tools.md +271 -26
- package/docs/security.md +101 -12
- package/docs/troubleshooting.md +14 -12
- package/docs/upgrading-0.10.md +472 -0
- package/package.json +5 -1
- package/src/access.ts +127 -4
- 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 +646 -106
- package/src/citations.ts +294 -0
- package/src/error-info.ts +36 -1
- package/src/errors.ts +3 -1
- package/src/events.ts +29 -6
- package/src/evidence.ts +21 -2
- package/src/extract.ts +6 -1
- package/src/gemini/adapter.ts +99 -32
- package/src/gemini/chat.ts +53 -82
- 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 +3 -3
- package/src/http.ts +65 -4
- package/src/index.ts +6 -4
- package/src/ingest.ts +58 -27
- package/src/library.ts +336 -142
- package/src/map-reduce.ts +855 -67
- package/src/model.ts +44 -4
- package/src/node/handlers.ts +159 -118
- package/src/node/index.ts +1 -0
- package/src/node/ingest-child.ts +2 -2
- package/src/node/spool.ts +28 -14
- package/src/node/sse.ts +8 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +16 -3
- package/src/search.ts +69 -13
- package/src/stores.ts +76 -11
- package/src/tools.ts +327 -75
- package/src/types.ts +45 -1
- package/src/whole-cost.ts +64 -0
package/src/model.ts
CHANGED
|
@@ -103,12 +103,25 @@ export type ModelReply = {
|
|
|
103
103
|
/**
|
|
104
104
|
* How the reply ended, in terms every adapter maps its own to: "complete"; "cut" at the output
|
|
105
105
|
* limit; "filtered" by the provider's safety filters; "malformed_call", a tool call the model
|
|
106
|
-
* tried to make that could not be read (Gemini's MALFORMED_FUNCTION_CALL)
|
|
107
|
-
*
|
|
106
|
+
* tried to make that could not be read (Gemini's MALFORMED_FUNCTION_CALL); "other", a known
|
|
107
|
+
* reason that is none of these and that asking again does not mend (Gemini's OTHER or LANGUAGE;
|
|
108
|
+
* new in 0.10.0). The loop does not ask again after "filtered" or "other". Unset when the adapter
|
|
109
|
+
* does not know the reason.
|
|
108
110
|
*/
|
|
109
|
-
finish?: "complete" | "cut" | "filtered" | "malformed_call";
|
|
111
|
+
finish?: "complete" | "cut" | "filtered" | "malformed_call" | "other";
|
|
110
112
|
/** Why the provider refused the prompt, when it did. Nothing more is asked after it. */
|
|
111
113
|
blockReason?: string;
|
|
114
|
+
/**
|
|
115
|
+
* The provider's ID of this response (Gemini's `responseId`, the `id` of OpenAI and Claude), when
|
|
116
|
+
* it gives one. `gemini()`, `openAiCompatible()` and `anthropic()` set it. New in 0.10.0.
|
|
117
|
+
*/
|
|
118
|
+
responseId?: string;
|
|
119
|
+
/**
|
|
120
|
+
* The model that wrote this response, as the provider names it (Gemini's `modelVersion`, the
|
|
121
|
+
* `model` of OpenAI and Claude). `gemini()`, `openAiCompatible()` and `anthropic()` set it. New
|
|
122
|
+
* in 0.10.0.
|
|
123
|
+
*/
|
|
124
|
+
responseModel?: string;
|
|
112
125
|
usage?: Partial<ModelUsage>;
|
|
113
126
|
/** The provider's own usage object, as it came. */
|
|
114
127
|
providerUsage?: Record<string, unknown>;
|
|
@@ -478,13 +491,36 @@ export type UsageTotals = ModelUsage & {
|
|
|
478
491
|
/** Requests that were answered. One that failed and was sent again counts once. */
|
|
479
492
|
requests: number;
|
|
480
493
|
byModel: Record<string, ModelUsage & { requests: number }>;
|
|
494
|
+
/**
|
|
495
|
+
* The input tokens of the requests whose provider said nothing of their input, by the library's
|
|
496
|
+
* estimate, in each model's own tokens: the ceiling of the question (`limits.inputTokens`) counts
|
|
497
|
+
* them with the reported ones. Absent when every request reported its input. New in 0.10.0.
|
|
498
|
+
*/
|
|
499
|
+
estimatedInputTokens?: number;
|
|
500
|
+
/**
|
|
501
|
+
* Requests that were answered without their input tokens from the provider: no usage, or an input
|
|
502
|
+
* of 0 (see `estimatedInputTokens`). Absent when there was none. New in 0.10.0.
|
|
503
|
+
*/
|
|
504
|
+
unmeasuredRequests?: number;
|
|
505
|
+
};
|
|
506
|
+
|
|
507
|
+
/** True when `usage` gives the input tokens of its request: a number above 0. */
|
|
508
|
+
export const reportsInput = (usage: Partial<ModelUsage> | undefined): boolean => {
|
|
509
|
+
const input = usage?.inputTokens;
|
|
510
|
+
return typeof input === "number" && Number.isFinite(input) && input > 0;
|
|
481
511
|
};
|
|
482
512
|
|
|
483
513
|
/** Sums the usage of the requests of one question. */
|
|
484
514
|
export class UsageMeter {
|
|
485
515
|
readonly totals: UsageTotals = { requests: 0, ...EMPTY_USAGE, byModel: {} };
|
|
486
516
|
|
|
487
|
-
|
|
517
|
+
/**
|
|
518
|
+
* Counts one answered request of `model`. `estimatedInputTokens` is the library's estimate of its
|
|
519
|
+
* input, in the model's own tokens: when `usage` does not give the input (no usage, or 0), the
|
|
520
|
+
* estimate goes into `estimatedInputTokens` and the request into `unmeasuredRequests`. Without
|
|
521
|
+
* it, such a request is counted as before 0.10.0.
|
|
522
|
+
*/
|
|
523
|
+
add(model: string, usage: Partial<ModelUsage> | undefined, estimatedInputTokens?: number): void {
|
|
488
524
|
const { byModel } = this.totals;
|
|
489
525
|
// An own entry only: an id such as "__proto__" or "constructor" found what every object
|
|
490
526
|
// inherits, and "__proto__" then counted the usage into Object.prototype.
|
|
@@ -500,5 +536,9 @@ export class UsageMeter {
|
|
|
500
536
|
if (typeof value === "number" && Number.isFinite(value) && value > 0) sum[key] += value;
|
|
501
537
|
}
|
|
502
538
|
}
|
|
539
|
+
if (estimatedInputTokens === undefined || reportsInput(usage)) return;
|
|
540
|
+
this.totals.unmeasuredRequests = (this.totals.unmeasuredRequests ?? 0) + 1;
|
|
541
|
+
const estimate = Number.isFinite(estimatedInputTokens) && estimatedInputTokens > 0 ? Math.ceil(estimatedInputTokens) : 0;
|
|
542
|
+
this.totals.estimatedInputTokens = (this.totals.estimatedInputTokens ?? 0) + estimate;
|
|
503
543
|
}
|
|
504
544
|
}
|
package/src/node/handlers.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
2
|
import { tmpdir } from "node:os";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import { errorInfoOf, STORE_RETRY_AFTER_MS, UNREADABLE_MESSAGE } from "../error-info.js";
|
|
4
|
+
import { errorInfoOf, retryAfterOfCode, STORE_RETRY_AFTER_MS, UNREADABLE_MESSAGE } from "../error-info.js";
|
|
5
5
|
import { DocumentScopeError, DocumentStoreError, IngestError, isErrorCode, type IngestErrorCode } from "../errors.js";
|
|
6
6
|
import { eventStream, newRunId, type EventError, type IngestEvent } from "../events.js";
|
|
7
7
|
import { checkOwner, cleanFileName, toDocumentSummary, type AccessOptions, type IngestInput, type LargeFiles } from "../library.js";
|
|
@@ -165,7 +165,9 @@ export type DocumentHandlerOptions = {
|
|
|
165
165
|
*
|
|
166
166
|
* When it throws, or returns an `answer` that is not such an object, the document is deleted
|
|
167
167
|
* (best effort) and the upload is answered as for an error of `ingest`: with the error's status
|
|
168
|
-
* (400 to 599) and message, or a 500 `{"error":"Upload failed."}`.
|
|
168
|
+
* (400 to 599) and message, or a 500 `{"error":"Upload failed."}`. The delete is waited for within
|
|
169
|
+
* the library's `storeTimeoutMs` (since 0.10.0): past it, it goes on alone, and the upload is
|
|
170
|
+
* answered all the same. New in 0.9.0.
|
|
169
171
|
*/
|
|
170
172
|
onUploaded?: (document: DocumentMeta, context: UploadedContext) => UploadedResult | Promise<UploadedResult>;
|
|
171
173
|
/**
|
|
@@ -224,10 +226,11 @@ export type DocumentHandlerOptions = {
|
|
|
224
226
|
* closed and its room given back: a client that sends its headers and then nothing, or stalls,
|
|
225
227
|
* holds its room no longer. Since 0.9.0 it also bounds each call to the disk for a body written
|
|
226
228
|
* to a file (the check of its folders for a link, its opening, each write, its closing): a volume
|
|
227
|
-
* that stops answering fails the upload with
|
|
228
|
-
*
|
|
229
|
-
*
|
|
230
|
-
*
|
|
229
|
+
* that stops answering fails the upload with "Upload failed (ETIMEDOUT).", a 503 with
|
|
230
|
+
* `Retry-After` since 0.10.0 (a 500 before), and its room is given back; the call then counts as
|
|
231
|
+
* stuck (`LargeFilesStats.stuckStoreCalls`) until it ends. The removal of the file is waited for
|
|
232
|
+
* no longer either: past it, the removal goes on alone, and the upload is answered all the same.
|
|
233
|
+
* 0 or `Infinity` for no limit. Defaults to 30,000. New in 0.8.2.
|
|
231
234
|
*/
|
|
232
235
|
uploadIdleTimeoutMs?: number;
|
|
233
236
|
};
|
|
@@ -257,8 +260,24 @@ export type DocumentHandlers = {
|
|
|
257
260
|
upload(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
258
261
|
/** GET: the document's summary, or 404. With `getScope`, only a document of the request's scope. */
|
|
259
262
|
get(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
|
|
260
|
-
/**
|
|
263
|
+
/**
|
|
264
|
+
* DELETE: removes the document, then calls `onRemoved`. Responds `{ deleted: boolean }`. A store
|
|
265
|
+
* that does not answer within the library's `storeTimeoutMs`, or too many stuck calls, is a 503
|
|
266
|
+
* with `Retry-After` (0.10.0).
|
|
267
|
+
*/
|
|
261
268
|
remove(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
|
|
269
|
+
/** Counters of the uploads these handlers hold, for metrics and alerts: read without waiting. New in 0.10.0. */
|
|
270
|
+
stats(): DocumentHandlerStats;
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
/** What `handlers.stats()` counts. New in 0.10.0. */
|
|
274
|
+
export type DocumentHandlerStats = {
|
|
275
|
+
/** Bytes of the bodies of uploads held in memory now (counted against `maxPendingUploadBytes`). */
|
|
276
|
+
memoryBytes: number;
|
|
277
|
+
/** Bytes of the files of the spool now (counted against `maxSpooledUploadBytes`). */
|
|
278
|
+
spooledBytes: number;
|
|
279
|
+
/** Uploads these handlers are answering now: from the request to the answer, `onUploaded` included. */
|
|
280
|
+
uploadsInFlight: number;
|
|
262
281
|
};
|
|
263
282
|
|
|
264
283
|
/** A whole HTTP status of an error, from 400 to 599. */
|
|
@@ -323,7 +342,10 @@ function answerFor(error: unknown, failed: string): UploadAnswer {
|
|
|
323
342
|
return { status, error: typeof message === "string" && message ? message : plain.error, ...(status === 503 ? retryOf((error as { retryAfterMs?: unknown }).retryAfterMs) : {}) };
|
|
324
343
|
}
|
|
325
344
|
const code = systemErrorCode(error);
|
|
326
|
-
|
|
345
|
+
if (!code) return plain;
|
|
346
|
+
// A disk or a service that did not answer just now, or a full disk: 503, to try again (0.10.0).
|
|
347
|
+
const retryAfterMs = retryAfterOfCode(code);
|
|
348
|
+
return retryAfterMs !== undefined ? { status: 503, error: `${failed} (${code}).`, retryAfterMs } : { status: 500, error: `${failed} (${code}).` };
|
|
327
349
|
} catch {
|
|
328
350
|
return plain;
|
|
329
351
|
}
|
|
@@ -344,8 +366,11 @@ const retryOf = (value: unknown): { retryAfterMs?: number } => (isWait(value) ?
|
|
|
344
366
|
* - a model's error (`ModelRequestError`): the status and words of `errorInfoOf`, never the
|
|
345
367
|
* provider's own;
|
|
346
368
|
* - any other error with a `status` (or `statusCode`) from 400 to 599: that status and its message;
|
|
347
|
-
* - a Node system error (a `code` and a `syscall`): 500 "Upload failed (
|
|
348
|
-
* failed." when its code does not read as one (capitals, digits and "_"), as a host does
|
|
369
|
+
* - a Node system error (a `code` and a `syscall`): 500 "Upload failed (EACCES).", or "Upload
|
|
370
|
+
* failed." when its code does not read as one (capitals, digits and "_"), as a host does. Since
|
|
371
|
+
* 0.10.0 a code that says the disk or a service could not answer just now (ETIMEDOUT,
|
|
372
|
+
* ECONNRESET, EAGAIN, EMFILE…) is a 503 with 5 s to wait, and a full disk (ENOSPC, EDQUOT) a 503
|
|
373
|
+
* with 30 s;
|
|
349
374
|
* - anything else: 500 "Upload failed.", without its message, which may name a host.
|
|
350
375
|
*
|
|
351
376
|
* It reads the errors of every copy of the package, and never throws. New in 0.9.0.
|
|
@@ -691,6 +716,8 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
|
|
|
691
716
|
/** The files of the spool, from the writing of each to its removal (`maxSpooledUploadBytes`). */
|
|
692
717
|
const spoolRoom = new Room(roomLimit("maxSpooledUploadBytes", options.maxSpooledUploadBytes, 10 * files.maxUploadBytes));
|
|
693
718
|
const fileMode = fileModeOf(options.uploadFileMode);
|
|
719
|
+
/** Uploads being answered now (`stats`). */
|
|
720
|
+
let uploadsInFlight = 0;
|
|
694
721
|
|
|
695
722
|
/**
|
|
696
723
|
* Whether the body of an upload goes to a file of the spool: with `uploadSpool`, one over
|
|
@@ -757,115 +784,11 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
|
|
|
757
784
|
|
|
758
785
|
return {
|
|
759
786
|
async upload(request, response) {
|
|
787
|
+
uploadsInFlight++;
|
|
760
788
|
try {
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
// Who is asking comes first: a refused upload is not read into memory.
|
|
765
|
-
const caller = await callerOf(request, "Upload failed", true);
|
|
766
|
-
// Too large is said first, before any wait for room.
|
|
767
|
-
const declared = Number(request.headers["content-length"]);
|
|
768
|
-
const parsed = parsedBody(request);
|
|
769
|
-
if ((Number.isFinite(declared) && declared > files.maxUploadBytes) || (parsed !== undefined && parsed.byteLength > files.maxUploadBytes)) {
|
|
770
|
-
throw new HttpError(413, "");
|
|
771
|
-
}
|
|
772
|
-
const prepared = options.prepareUpload ? preparedOf(await options.prepareUpload(request, { name: cleanFileName(name), ...caller })) : {};
|
|
773
|
-
// A file `fileOriginals` would not read back by its ref is refused before anything is written.
|
|
774
|
-
if (prepared.path !== undefined && prepared.original !== undefined) await checkRefFolders(prepared.path, prepared.original.ref, idleMs);
|
|
775
|
-
// Where the body is while it is ingested: in the application's file (`prepareUpload`), in a
|
|
776
|
-
// file of the spool, or in memory. Room is taken for it before it is read, so that a refused
|
|
777
|
-
// upload is not read: in the spool, or in memory. The application's file takes none: it is
|
|
778
|
-
// on the application's disk, and stays.
|
|
779
|
-
const spooled = prepared.path === undefined && spools(declared, parsed);
|
|
780
|
-
const held: Held | undefined = prepared.path !== undefined ? undefined : (spooled ? spoolRoom : memoryRoom).take(expectedSize(request, files.maxUploadBytes));
|
|
781
|
-
/** Gives the upload's room back, once: when its ingest ended, so that an `onUploaded` that waits on a database of yours does not hold it, or when the upload failed. */
|
|
782
|
-
const release = () => held?.release();
|
|
783
|
-
let file: BodyFile | undefined;
|
|
784
|
-
try {
|
|
785
|
-
let body: Uint8Array | undefined;
|
|
786
|
-
if (prepared.path !== undefined || spooled) {
|
|
787
|
-
const at = prepared.path ?? spoolFileIn(spool!.directory);
|
|
788
|
-
const size = await writeBody(request, at, { limit: files.maxUploadBytes, idleMs, mode: prepared.path !== undefined ? fileMode : 0o600 });
|
|
789
|
-
file = new BodyFile(at, prepared.path !== undefined, idleMs);
|
|
790
|
-
held?.resize(size);
|
|
791
|
-
} else {
|
|
792
|
-
body = await readBody(request, files.maxUploadBytes, idleMs);
|
|
793
|
-
// Counted at its size once read (an upload without a Content-Length was counted at the limit).
|
|
794
|
-
held?.resize(body.byteLength);
|
|
795
|
-
}
|
|
796
|
-
// Content-Type is a header of HTTP, not one the page encodes: it is taken as it came (S11).
|
|
797
|
-
// `ingest` cleans what it keeps of either.
|
|
798
|
-
const contentType = rawHeader(request, "content-type");
|
|
799
|
-
const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
|
|
800
|
-
// A client that goes away before the answer stops the reading of its file: nobody would
|
|
801
|
-
// get the document, and the server has other work.
|
|
802
|
-
const gone = new AbortController();
|
|
803
|
-
const onClose = () => {
|
|
804
|
-
if (!response.writableFinished) gone.abort(new Error("The upload was cancelled: the client closed the connection."));
|
|
805
|
-
};
|
|
806
|
-
response.once("close", onClose);
|
|
807
|
-
// One that left already is told no more: while the last piece of its body was written,
|
|
808
|
-
// or its file closed (where a network volume writes what it held back), or before a body
|
|
809
|
-
// a framework read was taken.
|
|
810
|
-
if (response.destroyed || request.socket?.destroyed) onClose();
|
|
811
|
-
const chosen = { ...(prepared.id !== undefined ? { id: prepared.id } : {}), ...(prepared.original !== undefined ? { original: prepared.original } : {}) };
|
|
812
|
-
/**
|
|
813
|
-
* Starts the upload's ingest, once. A body in memory is then the ingest's alone: it is
|
|
814
|
-
* freed when the ingest ends, while `onUploaded` may still run. The input is built in
|
|
815
|
-
* this function, whose frame ends at once: a value in the frame of `upload`, an async
|
|
816
|
-
* function, is kept until it returns, the hook's wait included. A body in a file is
|
|
817
|
-
* ingested from its path: the file of the spool is removed when the ingest ends, and the
|
|
818
|
-
* application's file when the ingest fails.
|
|
819
|
-
*/
|
|
820
|
-
const start: StartIngest = (more) => {
|
|
821
|
-
const input = { name, ...(mimeType ? { mimeType } : {}), ...chosen, ...caller, signal: gone.signal, ...more };
|
|
822
|
-
if (file) return file.settle(files.ingest({ ...input, source: { path: file.path } }));
|
|
823
|
-
const bytes = body!;
|
|
824
|
-
body = undefined;
|
|
825
|
-
return files.ingest({ ...input, bytes });
|
|
826
|
-
};
|
|
827
|
-
// The path is told only for the application's own file: the spool's is gone by then.
|
|
828
|
-
const saved = file?.kept ? file.path : undefined;
|
|
829
|
-
const hook = async (meta: DocumentMeta): Promise<Hooked> => {
|
|
830
|
-
const hooked = await uploaded(meta, request, caller, gone.signal.aborted, saved);
|
|
831
|
-
// The document is deleted: the file saved for it goes too.
|
|
832
|
-
if ("failure" in hooked) await file?.remove();
|
|
833
|
-
return hooked;
|
|
834
|
-
};
|
|
835
|
-
try {
|
|
836
|
-
if (wantsEvents(request)) {
|
|
837
|
-
// `onUploaded` runs once, for the event before ingest.finish or after the stream.
|
|
838
|
-
let hooking: Promise<Hooked> | undefined;
|
|
839
|
-
return await streamIngest(start, gone.signal, response, tooLarge, (meta) => (hooking ??= hook(meta)), release);
|
|
840
|
-
}
|
|
841
|
-
const meta = await start();
|
|
842
|
-
release();
|
|
843
|
-
const hooked = await hook(meta);
|
|
844
|
-
if ("failure" in hooked) throw hooked.failure;
|
|
845
|
-
// The summary's own fields win over the hook's.
|
|
846
|
-
send(response, 201, { ...hooked.answer, ...toDocumentSummary(meta) });
|
|
847
|
-
} finally {
|
|
848
|
-
response.off("close", onClose);
|
|
849
|
-
}
|
|
850
|
-
} finally {
|
|
851
|
-
release();
|
|
852
|
-
// Whatever happened: the spool's file is gone, and so is the application's unless its document is stored.
|
|
853
|
-
await file?.end();
|
|
854
|
-
}
|
|
855
|
-
} catch (error) {
|
|
856
|
-
// A body that stopped arriving is not drained: the answer ends, and so does the connection.
|
|
857
|
-
if (error instanceof HttpError && error.close) {
|
|
858
|
-
if (!response.headersSent) response.setHeader("Connection", "close");
|
|
859
|
-
send(response, error.status, { error: error.message });
|
|
860
|
-
if (response.writableFinished) request.destroy();
|
|
861
|
-
else response.once("finish", () => request.destroy());
|
|
862
|
-
return;
|
|
863
|
-
}
|
|
864
|
-
// Answered before the body was read to its end (too large, no name): the rest is drained.
|
|
865
|
-
fail(response, error, "Upload failed", tooLarge, request);
|
|
866
|
-
// An event stream that failed after its headers were sent cannot answer with a status. (An
|
|
867
|
-
// answer to a body still being drained is ended by `drain`.)
|
|
868
|
-
if (response.headersSent && !response.writableEnded && request.complete) response.end();
|
|
789
|
+
await answerUpload(request, response);
|
|
790
|
+
} finally {
|
|
791
|
+
uploadsInFlight--;
|
|
869
792
|
}
|
|
870
793
|
},
|
|
871
794
|
|
|
@@ -890,7 +813,125 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
|
|
|
890
813
|
fail(response, error, "The file could not be deleted", tooLarge);
|
|
891
814
|
}
|
|
892
815
|
},
|
|
816
|
+
|
|
817
|
+
stats() {
|
|
818
|
+
return { memoryBytes: memoryRoom.used, spooledBytes: spoolRoom.used, uploadsInFlight };
|
|
819
|
+
},
|
|
893
820
|
};
|
|
821
|
+
|
|
822
|
+
/** Answers one upload (`upload`): never rejects. */
|
|
823
|
+
async function answerUpload(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
|
824
|
+
try {
|
|
825
|
+
const url = new URL(request.url ?? "/", "http://localhost");
|
|
826
|
+
const name = header(request, "x-file-name").trim() || url.searchParams.get("name")?.trim() || "";
|
|
827
|
+
if (!name) throw new HttpError(400, "Name the file with an X-File-Name header or a ?name= query parameter.");
|
|
828
|
+
// Who is asking comes first: a refused upload is not read into memory.
|
|
829
|
+
const caller = await callerOf(request, "Upload failed", true);
|
|
830
|
+
// Too large is said first, before any wait for room.
|
|
831
|
+
const declared = Number(request.headers["content-length"]);
|
|
832
|
+
const parsed = parsedBody(request);
|
|
833
|
+
if ((Number.isFinite(declared) && declared > files.maxUploadBytes) || (parsed !== undefined && parsed.byteLength > files.maxUploadBytes)) {
|
|
834
|
+
throw new HttpError(413, "");
|
|
835
|
+
}
|
|
836
|
+
const prepared = options.prepareUpload ? preparedOf(await options.prepareUpload(request, { name: cleanFileName(name), ...caller })) : {};
|
|
837
|
+
// A file `fileOriginals` would not read back by its ref is refused before anything is written.
|
|
838
|
+
if (prepared.path !== undefined && prepared.original !== undefined) await checkRefFolders(prepared.path, prepared.original.ref, idleMs);
|
|
839
|
+
// Where the body is while it is ingested: in the application's file (`prepareUpload`), in a
|
|
840
|
+
// file of the spool, or in memory. Room is taken for it before it is read, so that a refused
|
|
841
|
+
// upload is not read: in the spool, or in memory. The application's file takes none: it is
|
|
842
|
+
// on the application's disk, and stays.
|
|
843
|
+
const spooled = prepared.path === undefined && spools(declared, parsed);
|
|
844
|
+
const held: Held | undefined = prepared.path !== undefined ? undefined : (spooled ? spoolRoom : memoryRoom).take(expectedSize(request, files.maxUploadBytes));
|
|
845
|
+
/** Gives the upload's room back, once: when its ingest ended, so that an `onUploaded` that waits on a database of yours does not hold it, or when the upload failed. */
|
|
846
|
+
const release = () => held?.release();
|
|
847
|
+
let file: BodyFile | undefined;
|
|
848
|
+
try {
|
|
849
|
+
let body: Uint8Array | undefined;
|
|
850
|
+
if (prepared.path !== undefined || spooled) {
|
|
851
|
+
const at = prepared.path ?? spoolFileIn(spool!.directory);
|
|
852
|
+
const size = await writeBody(request, at, { limit: files.maxUploadBytes, idleMs, mode: prepared.path !== undefined ? fileMode : 0o600 });
|
|
853
|
+
file = new BodyFile(at, prepared.path !== undefined, idleMs);
|
|
854
|
+
held?.resize(size);
|
|
855
|
+
} else {
|
|
856
|
+
body = await readBody(request, files.maxUploadBytes, idleMs);
|
|
857
|
+
// Counted at its size once read (an upload without a Content-Length was counted at the limit).
|
|
858
|
+
held?.resize(body.byteLength);
|
|
859
|
+
}
|
|
860
|
+
// Content-Type is a header of HTTP, not one the page encodes: it is taken as it came (S11).
|
|
861
|
+
// `ingest` cleans what it keeps of either.
|
|
862
|
+
const contentType = rawHeader(request, "content-type");
|
|
863
|
+
const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
|
|
864
|
+
// A client that goes away before the answer stops the reading of its file: nobody would
|
|
865
|
+
// get the document, and the server has other work.
|
|
866
|
+
const gone = new AbortController();
|
|
867
|
+
const onClose = () => {
|
|
868
|
+
if (!response.writableFinished) gone.abort(new Error("The upload was cancelled: the client closed the connection."));
|
|
869
|
+
};
|
|
870
|
+
response.once("close", onClose);
|
|
871
|
+
// One that left already is told no more: while the last piece of its body was written,
|
|
872
|
+
// or its file closed (where a network volume writes what it held back), or before a body
|
|
873
|
+
// a framework read was taken.
|
|
874
|
+
if (response.destroyed || request.socket?.destroyed) onClose();
|
|
875
|
+
const chosen = { ...(prepared.id !== undefined ? { id: prepared.id } : {}), ...(prepared.original !== undefined ? { original: prepared.original } : {}) };
|
|
876
|
+
/**
|
|
877
|
+
* Starts the upload's ingest, once. A body in memory is then the ingest's alone: it is
|
|
878
|
+
* freed when the ingest ends, while `onUploaded` may still run. The input is built in
|
|
879
|
+
* this function, whose frame ends at once: a value in the frame of `upload`, an async
|
|
880
|
+
* function, is kept until it returns, the hook's wait included. A body in a file is
|
|
881
|
+
* ingested from its path: the file of the spool is removed when the ingest ends, and the
|
|
882
|
+
* application's file when the ingest fails.
|
|
883
|
+
*/
|
|
884
|
+
const start: StartIngest = (more) => {
|
|
885
|
+
const input = { name, ...(mimeType ? { mimeType } : {}), ...chosen, ...caller, signal: gone.signal, ...more };
|
|
886
|
+
if (file) return file.settle(files.ingest({ ...input, source: { path: file.path } }));
|
|
887
|
+
const bytes = body!;
|
|
888
|
+
body = undefined;
|
|
889
|
+
return files.ingest({ ...input, bytes });
|
|
890
|
+
};
|
|
891
|
+
// The path is told only for the application's own file: the spool's is gone by then.
|
|
892
|
+
const saved = file?.kept ? file.path : undefined;
|
|
893
|
+
const hook = async (meta: DocumentMeta): Promise<Hooked> => {
|
|
894
|
+
const hooked = await uploaded(meta, request, caller, gone.signal.aborted, saved);
|
|
895
|
+
// The document is deleted: the file saved for it goes too.
|
|
896
|
+
if ("failure" in hooked) await file?.remove();
|
|
897
|
+
return hooked;
|
|
898
|
+
};
|
|
899
|
+
try {
|
|
900
|
+
if (wantsEvents(request)) {
|
|
901
|
+
// `onUploaded` runs once, for the event before ingest.finish or after the stream.
|
|
902
|
+
let hooking: Promise<Hooked> | undefined;
|
|
903
|
+
return await streamIngest(start, gone.signal, response, tooLarge, (meta) => (hooking ??= hook(meta)), release);
|
|
904
|
+
}
|
|
905
|
+
const meta = await start();
|
|
906
|
+
release();
|
|
907
|
+
const hooked = await hook(meta);
|
|
908
|
+
if ("failure" in hooked) throw hooked.failure;
|
|
909
|
+
// The summary's own fields win over the hook's.
|
|
910
|
+
send(response, 201, { ...hooked.answer, ...toDocumentSummary(meta) });
|
|
911
|
+
} finally {
|
|
912
|
+
response.off("close", onClose);
|
|
913
|
+
}
|
|
914
|
+
} finally {
|
|
915
|
+
release();
|
|
916
|
+
// Whatever happened: the spool's file is gone, and so is the application's unless its document is stored.
|
|
917
|
+
await file?.end();
|
|
918
|
+
}
|
|
919
|
+
} catch (error) {
|
|
920
|
+
// A body that stopped arriving is not drained: the answer ends, and so does the connection.
|
|
921
|
+
if (error instanceof HttpError && error.close) {
|
|
922
|
+
if (!response.headersSent) response.setHeader("Connection", "close");
|
|
923
|
+
send(response, error.status, { error: error.message });
|
|
924
|
+
if (response.writableFinished) request.destroy();
|
|
925
|
+
else response.once("finish", () => request.destroy());
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
// Answered before the body was read to its end (too large, no name): the rest is drained.
|
|
929
|
+
fail(response, error, "Upload failed", tooLarge, request);
|
|
930
|
+
// An event stream that failed after its headers were sent cannot answer with a status. (An
|
|
931
|
+
// answer to a body still being drained is ended by `drain`.)
|
|
932
|
+
if (response.headersSent && !response.writableEnded && request.complete) response.end();
|
|
933
|
+
}
|
|
934
|
+
}
|
|
894
935
|
}
|
|
895
936
|
|
|
896
937
|
/** The owner and the scope of a request, as `getOwner` and `getScope` gave them, checked. */
|
package/src/node/index.ts
CHANGED
package/src/node/ingest-child.ts
CHANGED
|
@@ -60,8 +60,8 @@ async function run(job: ChildJob): Promise<void> {
|
|
|
60
60
|
...input,
|
|
61
61
|
...(progress ? { onProgress: (report: ExtractProgress) => send({ type: "progress", id: job.id, progress: report }) } : {}),
|
|
62
62
|
}, job.input.format === "pdf" && pdfExtractor ? { pdf: pdfExtractor.extract } : {});
|
|
63
|
-
const { text, pages, encoding, replacedCharacters } = result;
|
|
64
|
-
send({ type: "done", id: job.id, result: { text, ...(pages !== undefined ? { pages } : {}), ...(encoding !== undefined ? { encoding } : {}), ...(replacedCharacters !== undefined ? { replacedCharacters } : {}), ...(file ? { file } : {}) } });
|
|
63
|
+
const { text, pages, encoding, replacedCharacters, headings } = result;
|
|
64
|
+
send({ type: "done", id: job.id, result: { text, ...(pages !== undefined ? { pages } : {}), ...(encoding !== undefined ? { encoding } : {}), ...(replacedCharacters !== undefined ? { replacedCharacters } : {}), ...(file ? { file } : {}), ...(headings !== undefined ? { headings } : {}) } });
|
|
65
65
|
} catch (error) {
|
|
66
66
|
// A system error keeps its code and system call: the server tells it apart from a file that cannot be read.
|
|
67
67
|
const { code, syscall } = (error ?? {}) as { code?: unknown; syscall?: unknown };
|
package/src/node/spool.ts
CHANGED
|
@@ -2,14 +2,16 @@
|
|
|
2
2
|
// file as it arrives. The file is the path `prepareUpload` gave (the application's, kept once its
|
|
3
3
|
// document is stored), or a temporary file of the spool (`uploadSpool`), removed once the ingest
|
|
4
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 (
|
|
6
|
-
// past it is left to end alone, and the upload
|
|
7
|
-
//
|
|
8
|
-
// 0.9.0; the reading into
|
|
5
|
+
// no longer than the idle time (408), and so is each call to the disk (503 "ETIMEDOUT", with
|
|
6
|
+
// Retry-After, since 0.10.0: a 500 before; a removal past it is left to end alone, and the upload
|
|
7
|
+
// answered all the same; since 0.10.0 it counts as a stuck call of the process until it ends). A file is always made new: opened with "wx", so that a
|
|
8
|
+
// file or a link already at its name is never written through. New in 0.9.0; the reading into
|
|
9
|
+
// memory moved here from handlers.ts.
|
|
9
10
|
import { randomUUID } from "node:crypto";
|
|
10
11
|
import { open, realpath, rm, type FileHandle } from "node:fs/promises";
|
|
11
12
|
import type { IncomingMessage } from "node:http";
|
|
12
13
|
import path from "node:path";
|
|
14
|
+
import { watchStuck } from "../access.js";
|
|
13
15
|
import { IngestError } from "../errors.js";
|
|
14
16
|
|
|
15
17
|
export class HttpError extends Error {
|
|
@@ -64,7 +66,8 @@ function withinIdle<T>(next: Promise<T>, idleMs: number): Promise<T> {
|
|
|
64
66
|
/**
|
|
65
67
|
* A call to the disk for an upload's file (`syscall`: the check of its folders, its opening, a
|
|
66
68
|
* 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:
|
|
69
|
+
* Answered as a system error, with its code only: 503 "Upload failed (ETIMEDOUT).", with
|
|
70
|
+
* Retry-After: 5 (since 0.10.0: a 500 before).
|
|
68
71
|
*/
|
|
69
72
|
class DiskTimeout extends Error {
|
|
70
73
|
readonly code = "ETIMEDOUT";
|
|
@@ -73,8 +76,12 @@ class DiskTimeout extends Error {
|
|
|
73
76
|
}
|
|
74
77
|
}
|
|
75
78
|
|
|
76
|
-
/**
|
|
77
|
-
|
|
79
|
+
/**
|
|
80
|
+
* `call`, a call to the disk, or a `DiskTimeout` once `idleMs` pass without it (0 for no limit).
|
|
81
|
+
* Past `idleMs`, the call counts as stuck in the process until it ends, as a store call past its
|
|
82
|
+
* time limit does (`LargeFilesStats.stuckStoreCalls`, 0.10.0): it holds a thread of the pool.
|
|
83
|
+
*/
|
|
84
|
+
const inTime = <T>(call: Promise<T>, idleMs: number, syscall: string): Promise<T> => (timed(idleMs) ? within(watchStuck(call, idleMs), idleMs, () => new DiskTimeout(syscall)) : call);
|
|
78
85
|
|
|
79
86
|
/**
|
|
80
87
|
* Waits for `call`, a call to the disk whose end nobody needs (a removal), no longer than `idleMs`
|
|
@@ -333,23 +340,30 @@ export type Held = {
|
|
|
333
340
|
|
|
334
341
|
/**
|
|
335
342
|
* Bytes of uploads held at once, under `limit`: `maxPendingUploadBytes` for the bodies held in
|
|
336
|
-
* memory, `maxSpooledUploadBytes` for the files of the spool. `Infinity`
|
|
343
|
+
* memory, `maxSpooledUploadBytes` for the files of the spool. `Infinity` refuses nothing, and since
|
|
344
|
+
* 0.10.0 still counts, for `handlers.stats()`.
|
|
337
345
|
*/
|
|
338
346
|
export class Room {
|
|
339
347
|
#used = 0;
|
|
340
348
|
|
|
341
349
|
constructor(readonly limit: number) {}
|
|
342
350
|
|
|
351
|
+
/** The bytes held now (`handlers.stats()`). */
|
|
352
|
+
get used(): number {
|
|
353
|
+
return this.#used;
|
|
354
|
+
}
|
|
355
|
+
|
|
343
356
|
/**
|
|
344
|
-
* Room for an upload of `bytes` (at most the limit itself,
|
|
345
|
-
*
|
|
346
|
-
*
|
|
347
|
-
*
|
|
357
|
+
* Room for an upload of `bytes` (at most the limit itself), taken before its body is read. One
|
|
358
|
+
* that would bring the room past its limit while another upload holds some is refused: an
|
|
359
|
+
* `IngestError` "busy", answered 503 with a wait. One upload alone is always taken. With no limit,
|
|
360
|
+
* an upload of no known size (the upload limit is Infinity too) counts 0 until it is read, so that
|
|
361
|
+
* the count stays a number.
|
|
348
362
|
*/
|
|
349
363
|
take(bytes: number): Held {
|
|
350
|
-
if (this.limit === Number.POSITIVE_INFINITY) return { resize: () => undefined, release: () => undefined };
|
|
351
364
|
let held = Math.min(bytes, this.limit);
|
|
352
|
-
if (
|
|
365
|
+
if (!Number.isFinite(held)) held = 0;
|
|
366
|
+
if (this.limit !== Number.POSITIVE_INFINITY && this.#used > 0 && this.#used + held > this.limit) throw new IngestError("busy", BUSY, { retryAfterMs: BUSY_RETRY_MS });
|
|
353
367
|
this.#used += held;
|
|
354
368
|
return {
|
|
355
369
|
resize: (size) => {
|
package/src/node/sse.ts
CHANGED
|
@@ -40,18 +40,19 @@ const oneLine = (value: string | number) => String(value).replace(/[\r\n]+/g, "
|
|
|
40
40
|
/**
|
|
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
|
-
* `toolTurns`, `plan`, `budget` and `lastUsage`: `{ answered, text,
|
|
44
|
-
* steps, evidence, turns, usage, missing }` (keep `toolTurns` on the
|
|
45
|
-
* conversation). `run.error` has its `error` and a `partial` with only the
|
|
46
|
-
* `usage` and `missing` of the partial result. Every other event is sent as it
|
|
47
|
-
* documents a question answered without, is new in 0.9.0
|
|
43
|
+
* `toolTurns`, `plan`, `budget` and `lastUsage`: `{ answered, text, finish, finishReason,
|
|
44
|
+
* blockReason, citations, steps, evidence, turns, usage, missing }` (keep `toolTurns` on the
|
|
45
|
+
* server, with the conversation). `run.error` has its `error` and a `partial` with only the
|
|
46
|
+
* `steps`, `evidence`, `usage` and `missing` of the partial result. Every other event is sent as it
|
|
47
|
+
* is. `missing`, the documents a question answered without, is new in 0.9.0; `finish` and
|
|
48
|
+
* `citations`, how the answer ended and what its citations came to, in 0.10.0.
|
|
48
49
|
*/
|
|
49
50
|
export function sseMessageOf<E extends { type: string; seq: number }>(event: E): SseMessage {
|
|
50
51
|
const ask = event as unknown as AskEvent;
|
|
51
52
|
if (ask.type === "run.finish") {
|
|
52
53
|
const { type, seq, runId, time } = ask;
|
|
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
|
+
const { answered, text, finish, finishReason, blockReason, citations, steps, evidence, turns, usage, missing } = ask.result;
|
|
55
|
+
return { event: type, id: seq, data: { type, seq, runId, time, result: { answered, text, finish, finishReason, blockReason, citations, steps, evidence, turns, usage, missing } } };
|
|
55
56
|
}
|
|
56
57
|
if (ask.type === "run.error") {
|
|
57
58
|
const { type, seq, runId, time, error } = ask;
|