spool-sdk 0.0.0-stage → 0.2.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.
@@ -0,0 +1,221 @@
1
+ import type { JsonObject, JsonValue } from "@bufbuild/protobuf";
2
+ import { type Duration } from "./duration.js";
3
+ /** How many times a step may run in all, unless it says otherwise. */
4
+ export declare const DEFAULT_MAX_ATTEMPTS = 3;
5
+ /** The engine's bound on maxAttempts. */
6
+ export declare const MAX_ATTEMPTS = 100;
7
+ /** The name a sleep is recorded under; parenthesised so no step name collides with it. */
8
+ export declare const SLEEP_STEP_NAME = "(sleep)";
9
+ /** The name a wait for `event` is recorded under; renaming the event is a mismatch. */
10
+ export declare function waitStepName(event: string): string;
11
+ /** The name a rate limit's token is recorded under, at the position before its step. */
12
+ export declare function rateStepName(key: string): string;
13
+ /** A step the engine has already recorded for this run. */
14
+ export interface RecordedStep {
15
+ readonly seq: number;
16
+ readonly name: string;
17
+ readonly output: JsonValue;
18
+ }
19
+ export interface StepResult {
20
+ readonly seq: number;
21
+ readonly name: string;
22
+ readonly output: JsonValue;
23
+ readonly durationMs: number;
24
+ /** Set for a model call. */
25
+ readonly llm?: LlmUsage;
26
+ }
27
+ /** What a model call used, as the engine records it. */
28
+ export interface LlmUsage {
29
+ readonly model: string;
30
+ readonly inputTokens: number;
31
+ readonly outputTokens: number;
32
+ }
33
+ /** What a ctx.llm function returns: the answer to keep, and what producing it used. */
34
+ export interface LlmCall<T> extends LlmUsage {
35
+ /** Stored as the step's output and returned by ctx.llm, now and on replay. */
36
+ readonly output: T;
37
+ }
38
+ /**
39
+ * Passed to a ctx.llm function to show its text live as the model produces it: on the
40
+ * run's event stream (`token` events) and in the dashboard, while someone is watching.
41
+ * Best effort and never stored; the step's output is what is kept.
42
+ */
43
+ export interface LlmStream {
44
+ /** Text the model produced since the last call; empty text is ignored. */
45
+ token(text: string): void;
46
+ }
47
+ /** The engine's bound on tokens per direction for one call. */
48
+ export declare const MAX_LLM_TOKENS = 100000000;
49
+ export interface SleepRequest {
50
+ readonly seq: number;
51
+ readonly name: string;
52
+ readonly durationMs: number;
53
+ }
54
+ export interface WaitRequest {
55
+ readonly seq: number;
56
+ readonly name: string;
57
+ readonly eventName: string;
58
+ readonly match: JsonObject;
59
+ readonly timeoutMs: number;
60
+ }
61
+ export interface WaitOptions {
62
+ /**
63
+ * How long to wait before giving up: whole milliseconds or a string such as "24h", at
64
+ * most 365 days. Required, so no run waits forever by accident.
65
+ */
66
+ readonly timeout: Duration;
67
+ }
68
+ export interface StepFailure {
69
+ readonly seq: number;
70
+ readonly name: string;
71
+ readonly error: {
72
+ readonly type: string;
73
+ readonly message: string;
74
+ };
75
+ readonly retryable: boolean;
76
+ readonly maxAttempts: number;
77
+ readonly durationMs: number;
78
+ }
79
+ export interface ThrottleRequest {
80
+ readonly seq: number;
81
+ readonly name: string;
82
+ readonly key: string;
83
+ readonly cost: number;
84
+ }
85
+ export interface StepOptions {
86
+ /**
87
+ * How many times the step may run in all before the run fails, from 1 to 100. Default 3.
88
+ * Retries wait a growing, randomised delay set by the engine.
89
+ */
90
+ readonly maxAttempts?: number;
91
+ /**
92
+ * A rate limit the step must respect, by key (set with LimitsService.SetRateLimit), such as
93
+ * a model provider's account. Before the step runs for the first time the engine takes one
94
+ * token from the key's bucket and records that as its own step, "(rate:<key>)", just
95
+ * before this one. If the token is not due yet the run stops on this worker, without
96
+ * holding it, and resumes once it is; the token is never taken twice, retries of the step
97
+ * included. A key with no limit set does not limit. Adding or removing this option in a
98
+ * running workflow shifts its steps, which is a StepMismatchError.
99
+ */
100
+ readonly rateLimit?: string;
101
+ }
102
+ /** What a workflow function receives. */
103
+ export interface WorkflowContext {
104
+ readonly runId: string;
105
+ readonly workflow: string;
106
+ /** Which attempt at the run this is, from 1. A replay after a crash has a higher one. */
107
+ readonly attempt: number;
108
+ /**
109
+ * Aborts when this worker must stop working on the run: its lease was lost, a step
110
+ * failed, or the worker is shutting down. Pass it to fetches and other long operations
111
+ * so they stop early.
112
+ */
113
+ readonly signal: AbortSignal;
114
+ /**
115
+ * Runs `fn` once per run and records its output. When the run is replayed after a crash,
116
+ * a recorded step returns its stored output without calling `fn` again. Steps run one at
117
+ * a time, in the same order on every replay; their names identify them, so renaming or
118
+ * reordering steps in a running workflow stops the run with a StepMismatchError.
119
+ *
120
+ * If `fn` throws, the failure is recorded and the run stops on this worker: the engine
121
+ * runs it again later from this step, up to `maxAttempts` times, or fails the run at once
122
+ * if the error is a NonRetryableError.
123
+ *
124
+ * The output is stored as JSON and returned in that form, on the first run as on replays.
125
+ */
126
+ step<T>(name: string, fn: () => T | Promise<T>, options?: StepOptions): Promise<T>;
127
+ /**
128
+ * A key for the step that is running, the same on every try of that step: after a
129
+ * failure, after a crash, on another worker. Pass it to APIs that deduplicate requests
130
+ * (payment, email, most HTTP APIs with an `Idempotency-Key` header), so a step that runs
131
+ * twice has its effect once. `${runId}:${position}`. Only available inside a step
132
+ * function; reading it anywhere else throws.
133
+ */
134
+ readonly idempotencyKey: string;
135
+ /**
136
+ * Pauses the run for `duration` without holding this worker: the engine records the sleep
137
+ * as the next step and takes the run back, and once the time has passed any worker picks
138
+ * it up, replays it to here and goes on. A number is milliseconds; a string has a unit,
139
+ * such as "30s", "15m", "24h" or "7d" (at most 365 days). The wait is measured on the
140
+ * database clock and may end up to the engine's waker interval late.
141
+ *
142
+ * On this worker the call never returns: it throws RunSleepingError to stop the run, so
143
+ * do not catch that. Like steps, sleeps run one at a time and in the same order on every
144
+ * replay.
145
+ */
146
+ /**
147
+ * A step that calls a model: `fn` makes the call and returns its answer as `output` with
148
+ * the model's name and the tokens it used. Recorded like ctx.step (run once, replayed
149
+ * from the journal, retried on failure, with ctx.idempotencyKey available) and also as a
150
+ * model call, so the engine keeps the model, tokens, latency and cost (from its price
151
+ * table) for the run's timeline and metrics. A replay returns the stored output without
152
+ * calling the model, so a recorded call is never paid for twice. `fn` may pass the text
153
+ * it streams from the model to `stream.token(text)` for anyone following the run live.
154
+ */
155
+ llm<T>(name: string, fn: (stream: LlmStream) => LlmCall<T> | Promise<LlmCall<T>>, options?: StepOptions): Promise<T>;
156
+ sleep(duration: Duration): Promise<void>;
157
+ /**
158
+ * Pauses the run until an event named `event` arrives whose payload contains `match`
159
+ * (sent with RunService.SendEvent, for example by an approval UI or a webhook), and
160
+ * returns that payload; returns null if none arrives within `timeout`. The run holds no
161
+ * worker while it waits. An event that arrived after the run started, before the wait,
162
+ * counts too, and each event reaches a run at most once.
163
+ *
164
+ * Match on something that identifies the run, such as `{ runId: ctx.runId }`, unless one
165
+ * event should resume every run waiting for that name. Like ctx.sleep, the call stops the
166
+ * run on this worker (throwing RunWaitingError); the run resumes on a worker once the
167
+ * wait ends. Waits are recorded under "(wait:<event>)", so changing the event name of a
168
+ * wait in a running workflow is a StepMismatchError.
169
+ */
170
+ waitForEvent<T extends JsonObject = JsonObject>(event: string, match: JsonObject, options: WaitOptions): Promise<T | null>;
171
+ }
172
+ export interface RunContextOptions {
173
+ readonly runId: string;
174
+ readonly workflow: string;
175
+ readonly attempt: number;
176
+ /** The run's signal; `stop` aborts it. */
177
+ readonly signal: AbortSignal;
178
+ readonly journal: readonly RecordedStep[];
179
+ /** Resolves once the engine acknowledged the step; rejects when it never can. */
180
+ readonly record: (step: StepResult) => Promise<void>;
181
+ /** Resolves once the engine recorded the failure and released the run. */
182
+ readonly recordFailure: (failure: StepFailure) => Promise<void>;
183
+ /** Resolves once the engine recorded the sleep and took the run back. */
184
+ readonly recordSleep: (sleep: SleepRequest) => Promise<void>;
185
+ /** Resolves once the engine registered the wait (or matched an earlier event). */
186
+ readonly recordWait: (wait: WaitRequest) => Promise<void>;
187
+ /** Resolves with how long until the token is due: 0 means go on; more, the run parked. */
188
+ readonly recordThrottle: (throttle: ThrottleRequest) => Promise<number>;
189
+ /** Sends a model call's text to live viewers; fire and forget. None in some tests. */
190
+ readonly sendTokens?: (seq: number, text: string) => void;
191
+ /** Stops the run on this worker. */
192
+ readonly stop: (reason: Error) => void;
193
+ }
194
+ /**
195
+ * The context for one attempt at a run. It walks the journal the engine sent with the task:
196
+ * the first steps the code calls are matched against it by position and name and answered
197
+ * from it; the first step past its end really runs.
198
+ */
199
+ export declare class RunContext implements WorkflowContext {
200
+ #private;
201
+ readonly runId: string;
202
+ readonly workflow: string;
203
+ readonly attempt: number;
204
+ readonly signal: AbortSignal;
205
+ constructor(options: RunContextOptions);
206
+ get idempotencyKey(): string;
207
+ /** The position the next step will take: where a failure outside a step is charged. */
208
+ get nextSeq(): number;
209
+ step<T>(name: string, fn: () => T | Promise<T>, options?: StepOptions): Promise<T>;
210
+ llm<T>(name: string, fn: (stream: LlmStream) => LlmCall<T> | Promise<LlmCall<T>>, options?: StepOptions): Promise<T>;
211
+ sleep(duration: Duration): Promise<void>;
212
+ waitForEvent<T extends JsonObject = JsonObject>(event: string, match: JsonObject, options: WaitOptions): Promise<T | null>;
213
+ }
214
+ /**
215
+ * What the engine keeps of an error: its class and message, bounded and storable. Never the
216
+ * stack, which can carry paths and data.
217
+ */
218
+ export declare function describe(error: unknown): {
219
+ type: string;
220
+ message: string;
221
+ };
@@ -0,0 +1,331 @@
1
+ import { toMilliseconds } from "./duration.js";
2
+ import { NonRetryableError, RunSleepingError, RunThrottledError, RunWaitingError, StepFailedError, StepMismatchError, } from "./errors.js";
3
+ import { toStoredJson } from "./json.js";
4
+ /** How many times a step may run in all, unless it says otherwise. */
5
+ export const DEFAULT_MAX_ATTEMPTS = 3;
6
+ /** The engine's bound on maxAttempts. */
7
+ export const MAX_ATTEMPTS = 100;
8
+ /** The engine keeps at most this much of an error message. */
9
+ const MAX_ERROR_MESSAGE = 4096;
10
+ const MAX_ERROR_TYPE = 128;
11
+ /** The name a sleep is recorded under; parenthesised so no step name collides with it. */
12
+ export const SLEEP_STEP_NAME = "(sleep)";
13
+ /** The name a wait for `event` is recorded under; renaming the event is a mismatch. */
14
+ export function waitStepName(event) {
15
+ return `(wait:${event})`;
16
+ }
17
+ /** The name a rate limit's token is recorded under, at the position before its step. */
18
+ export function rateStepName(key) {
19
+ return `(rate:${key})`;
20
+ }
21
+ /** The engine's bound on rate limit keys. */
22
+ const MAX_RATE_KEY = 128;
23
+ /** The engine's bound on tokens per direction for one call. */
24
+ export const MAX_LLM_TOKENS = 100_000_000;
25
+ /**
26
+ * The context for one attempt at a run. It walks the journal the engine sent with the task:
27
+ * the first steps the code calls are matched against it by position and name and answered
28
+ * from it; the first step past its end really runs.
29
+ */
30
+ export class RunContext {
31
+ runId;
32
+ workflow;
33
+ attempt;
34
+ signal;
35
+ #options;
36
+ #nextSeq = 0;
37
+ #stepRunning = false;
38
+ /** The position whose function is running, for idempotencyKey. */
39
+ #executingSeq;
40
+ constructor(options) {
41
+ this.runId = options.runId;
42
+ this.workflow = options.workflow;
43
+ this.attempt = options.attempt;
44
+ this.signal = options.signal;
45
+ this.#options = options;
46
+ }
47
+ get idempotencyKey() {
48
+ if (this.#executingSeq === undefined) {
49
+ throw new Error("ctx.idempotencyKey is only available inside a step function: outside one, no step is running to name");
50
+ }
51
+ return `${this.runId}:${String(this.#executingSeq)}`;
52
+ }
53
+ /** The position the next step will take: where a failure outside a step is charged. */
54
+ get nextSeq() {
55
+ return this.#nextSeq;
56
+ }
57
+ async step(name, fn, options = {}) {
58
+ checkStepOptions(options);
59
+ await this.#throttle(options, "ctx.step");
60
+ // The caller declares T; the SDK cannot check stored JSON against it.
61
+ return (await this.#runStep(name, "ctx.step", async () => ({ value: await fn() }), options));
62
+ }
63
+ async llm(name, fn, options = {}) {
64
+ checkStepOptions(options);
65
+ await this.#throttle(options, "ctx.llm");
66
+ const output = await this.#runStep(name, "ctx.llm", async () => {
67
+ const stream = new TokenBuffer(this.#executingSeq ?? this.#nextSeq, this.#options.sendTokens);
68
+ try {
69
+ const call = await fn(stream);
70
+ return { value: call.output, llm: checkUsage(call, name) };
71
+ }
72
+ finally {
73
+ stream.close();
74
+ }
75
+ }, options);
76
+ // As for step: T is the caller's declaration of the stored output.
77
+ return output;
78
+ }
79
+ /**
80
+ * One step at the next position: replayed from the journal when recorded, otherwise run,
81
+ * stored as JSON and reported, with its usage when it was a model call. A failure is
82
+ * reported and stops the run.
83
+ */
84
+ async #runStep(name, what, fn, options) {
85
+ const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
86
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1 || maxAttempts > MAX_ATTEMPTS) {
87
+ throw new RangeError(`maxAttempts must be an integer from 1 to ${String(MAX_ATTEMPTS)}`);
88
+ }
89
+ if (this.#stepRunning) {
90
+ // Concurrent steps would take positions in whatever order they were called and
91
+ // report in whatever order they finished, so replays could not match them up.
92
+ throw new Error(`${what}("${name}") was called while another step was running; await each step before starting the next`);
93
+ }
94
+ this.#stepRunning = true;
95
+ try {
96
+ // A run whose lease is gone stops before its next step, recorded or not.
97
+ this.signal.throwIfAborted();
98
+ const seq = this.#nextSeq;
99
+ const recorded = this.#options.journal[seq];
100
+ if (recorded !== undefined) {
101
+ if (recorded.name !== name)
102
+ throw StepMismatchError.at(seq, recorded.name, name);
103
+ this.#nextSeq += 1;
104
+ return recorded.output;
105
+ }
106
+ const started = performance.now();
107
+ let output;
108
+ let llm;
109
+ try {
110
+ this.#executingSeq = seq;
111
+ const result = await fn();
112
+ output = toStoredJson(result.value, `the output of step "${name}"`);
113
+ llm = result.llm;
114
+ }
115
+ catch (error) {
116
+ // Stopped for another reason while fn ran: that reason wins, and nothing is reported.
117
+ this.signal.throwIfAborted();
118
+ const retryable = !(error instanceof NonRetryableError);
119
+ await this.#options.recordFailure({
120
+ seq,
121
+ name,
122
+ error: describe(error),
123
+ retryable,
124
+ maxAttempts,
125
+ durationMs: Math.round(performance.now() - started),
126
+ });
127
+ const stopped = new StepFailedError(name, retryable, { cause: error });
128
+ this.#options.stop(stopped);
129
+ throw stopped;
130
+ }
131
+ const durationMs = Math.round(performance.now() - started);
132
+ // The lease may have been lost while fn ran; the engine would reject the report.
133
+ this.signal.throwIfAborted();
134
+ await this.#options.record({
135
+ seq,
136
+ name,
137
+ output,
138
+ durationMs,
139
+ ...(llm === undefined ? {} : { llm }),
140
+ });
141
+ this.#nextSeq += 1;
142
+ // The JSON form of what fn returned, which is what a replay returns.
143
+ return output;
144
+ }
145
+ finally {
146
+ this.#stepRunning = false;
147
+ this.#executingSeq = undefined;
148
+ }
149
+ }
150
+ /**
151
+ * Takes the step's rate limit token, when it has one: replayed from the journal when
152
+ * recorded; otherwise the engine takes it and records it at this position, and either the
153
+ * step goes on or, if the token is not due yet, the run stops here and resumes later.
154
+ */
155
+ async #throttle(options, what) {
156
+ const key = options.rateLimit;
157
+ if (key === undefined)
158
+ return;
159
+ if (this.#stepRunning) {
160
+ throw new Error(`${what} was called while another step was running; await each step before starting the next`);
161
+ }
162
+ this.#stepRunning = true;
163
+ try {
164
+ this.signal.throwIfAborted();
165
+ const seq = this.#nextSeq;
166
+ const name = rateStepName(key);
167
+ const recorded = this.#options.journal[seq];
168
+ if (recorded !== undefined) {
169
+ if (recorded.name !== name)
170
+ throw StepMismatchError.at(seq, recorded.name, name);
171
+ this.#nextSeq += 1;
172
+ return;
173
+ }
174
+ const waitMs = await this.#options.recordThrottle({ seq, name, key, cost: 1 });
175
+ this.#nextSeq += 1;
176
+ if (waitMs > 0) {
177
+ const reason = new RunThrottledError(key, waitMs);
178
+ this.#options.stop(reason);
179
+ throw reason;
180
+ }
181
+ }
182
+ finally {
183
+ this.#stepRunning = false;
184
+ }
185
+ }
186
+ async sleep(duration) {
187
+ const durationMs = toMilliseconds(duration);
188
+ await this.#park(SLEEP_STEP_NAME, "ctx.sleep", (seq) => this.#options.recordSleep({ seq, name: SLEEP_STEP_NAME, durationMs }), () => new RunSleepingError(durationMs));
189
+ }
190
+ async waitForEvent(event, match, options) {
191
+ if (event.length === 0)
192
+ throw new RangeError("the event name must not be empty");
193
+ const timeoutMs = toMilliseconds(options.timeout);
194
+ const stored = toStoredJson(match, "the match of ctx.waitForEvent");
195
+ if (typeof stored !== "object" || stored === null || Array.isArray(stored)) {
196
+ throw new TypeError("the match of ctx.waitForEvent must be a JSON object");
197
+ }
198
+ const name = waitStepName(event);
199
+ const output = await this.#park(name, "ctx.waitForEvent", (seq) => this.#options.recordWait({ seq, name, eventName: event, match: stored, timeoutMs }), () => new RunWaitingError(event));
200
+ // The engine records the event's payload, an object, or null on a timeout; the caller
201
+ // declares T, which the SDK cannot check against the payload.
202
+ return output;
203
+ }
204
+ /**
205
+ * A step that parks the run: replayed from the journal when recorded (the sleep ended or
206
+ * the wait was resolved), otherwise reported, after which the run stops on this worker.
207
+ */
208
+ async #park(name, what, report, stopped) {
209
+ if (this.#stepRunning) {
210
+ throw new Error(`${what} was called while a step was running; call it between steps, not inside one`);
211
+ }
212
+ this.#stepRunning = true;
213
+ try {
214
+ this.signal.throwIfAborted();
215
+ const seq = this.#nextSeq;
216
+ const recorded = this.#options.journal[seq];
217
+ if (recorded !== undefined) {
218
+ if (recorded.name !== name)
219
+ throw StepMismatchError.at(seq, recorded.name, name);
220
+ this.#nextSeq += 1;
221
+ return recorded.output;
222
+ }
223
+ await report(seq);
224
+ this.#nextSeq += 1;
225
+ const reason = stopped();
226
+ this.#options.stop(reason);
227
+ throw reason;
228
+ }
229
+ finally {
230
+ this.#stepRunning = false;
231
+ }
232
+ }
233
+ }
234
+ /** Rejects options the engine would refuse, before anything is reported or taken. */
235
+ function checkStepOptions(options) {
236
+ const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
237
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1 || maxAttempts > MAX_ATTEMPTS) {
238
+ throw new RangeError(`maxAttempts must be an integer from 1 to ${String(MAX_ATTEMPTS)}`);
239
+ }
240
+ const key = options.rateLimit;
241
+ if (key !== undefined && (key.length === 0 || key.length > MAX_RATE_KEY)) {
242
+ throw new RangeError(`rateLimit must be a key of 1 to ${String(MAX_RATE_KEY)} characters`);
243
+ }
244
+ }
245
+ /**
246
+ * What the engine keeps of an error: its class and message, bounded and storable. Never the
247
+ * stack, which can carry paths and data.
248
+ */
249
+ export function describe(error) {
250
+ const type = error instanceof Error ? error.name : typeof error;
251
+ const message = error instanceof Error ? error.message : String(error);
252
+ return {
253
+ type: storable(type, MAX_ERROR_TYPE) || "Error",
254
+ message: storable(message, MAX_ERROR_MESSAGE) || "(no message)",
255
+ };
256
+ }
257
+ /** Postgres text cannot hold NUL or unpaired surrogates; the engine rejects both. */
258
+ function storable(text, max) {
259
+ return text.replaceAll("\0", "").toWellFormed().slice(0, max).toWellFormed();
260
+ }
261
+ /** A token count the engine accepts. */
262
+ function isTokenCount(value) {
263
+ return (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= MAX_LLM_TOKENS);
264
+ }
265
+ /**
266
+ * The usage a ctx.llm function returned, checked before anything is reported. A bad one is
267
+ * a bug in the function (a missing count, a wrong field), which running it again would not
268
+ * fix, so it fails the step for good.
269
+ */
270
+ function checkUsage(call, step) {
271
+ const { model, inputTokens, outputTokens } = call;
272
+ if (typeof model !== "string" || model.length === 0 || model.length > 128) {
273
+ throw new NonRetryableError(`ctx.llm("${step}") must return the model name (1 to 128 characters)`);
274
+ }
275
+ if (!isTokenCount(inputTokens) || !isTokenCount(outputTokens)) {
276
+ throw new NonRetryableError(`ctx.llm("${step}") must return inputTokens and outputTokens as whole numbers from 0 to ${String(MAX_LLM_TOKENS)}`);
277
+ }
278
+ return { model, inputTokens, outputTokens };
279
+ }
280
+ /** How often streamed text is sent, and the most held before it is sent at once. */
281
+ const TOKEN_FLUSH_MS = 100;
282
+ const TOKEN_FLUSH_BYTES = 16 * 1024;
283
+ /**
284
+ * Collects a ctx.llm call's streamed text and sends it in batches, every TOKEN_FLUSH_MS or
285
+ * once TOKEN_FLUSH_BYTES are waiting, and what is left when the call ends: one message per
286
+ * batch instead of one per token.
287
+ */
288
+ class TokenBuffer {
289
+ seq;
290
+ send;
291
+ #text = "";
292
+ #timer;
293
+ #closed = false;
294
+ constructor(seq, send) {
295
+ this.seq = seq;
296
+ this.send = send;
297
+ }
298
+ token(text) {
299
+ if (this.#closed || this.send === undefined || text === "")
300
+ return;
301
+ this.#text += text;
302
+ if (this.#text.length >= TOKEN_FLUSH_BYTES)
303
+ this.#flush();
304
+ else
305
+ this.#timer ??= setTimeout(() => {
306
+ this.#flush();
307
+ }, TOKEN_FLUSH_MS);
308
+ }
309
+ close() {
310
+ this.#flush();
311
+ this.#closed = true;
312
+ }
313
+ #flush() {
314
+ clearTimeout(this.#timer);
315
+ this.#timer = undefined;
316
+ // Pieces of at most TOKEN_FLUSH_BYTES characters, split between code points, so one
317
+ // large token() never makes a message over the engine's 64 KiB bound.
318
+ let piece = "";
319
+ for (const char of this.#text) {
320
+ if (piece.length + char.length > TOKEN_FLUSH_BYTES) {
321
+ this.send?.(this.seq, piece);
322
+ piece = "";
323
+ }
324
+ piece += char;
325
+ }
326
+ if (piece !== "")
327
+ this.send?.(this.seq, piece);
328
+ this.#text = "";
329
+ }
330
+ }
331
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAiB,MAAM,eAAe,CAAC;AAC9D,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,EACf,eAAe,EACf,iBAAiB,GAClB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,sEAAsE;AACtE,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AACtC,yCAAyC;AACzC,MAAM,CAAC,MAAM,YAAY,GAAG,GAAG,CAAC;AAChC,8DAA8D;AAC9D,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAC/B,MAAM,cAAc,GAAG,GAAG,CAAC;AAE3B,0FAA0F;AAC1F,MAAM,CAAC,MAAM,eAAe,GAAG,SAAS,CAAC;AAEzC,uFAAuF;AACvF,MAAM,UAAU,YAA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AC,MAAM,IAAI,iBAAiB;YAAE,IAAI,CAAC,MAAM,EAAE,CAAC;;YAExD,IAAI,CAAC,MAAM,KAAK,UAAU,CAAC,GAAG,EAAE;gBAC9B,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,CAAC,EAAE,cAAc,CAAC,CAAC;IACvB,CAAC;IAED,KAAK;QACH,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;IACtB,CAAC;IAED,MAAM;QACJ,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC1B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,oFAAoF;QACpF,sEAAsE;QACtE,IAAI,KAAK,GAAG,EAAE,CAAC;QACf,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC9B,IAAI,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,GAAG,iBAAiB,EAAE,CAAC;gBACnD,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;gBAC7B,KAAK,GAAG,EAAE,CAAC;YACb,CAAC;YACD,KAAK,IAAI,IAAI,CAAC;QAChB,CAAC;QACD,IAAI,KAAK,KAAK,EAAE;YAAE,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC/C,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;IAClB,CAAC;CACF"}
@@ -0,0 +1,22 @@
1
+ /** The engine's bound: a sleep longer than a year is refused as a likely bug. */
2
+ export declare const MAX_DURATION_MS: number;
3
+ declare const UNIT_MS: {
4
+ readonly ms: 1;
5
+ readonly s: 1000;
6
+ readonly m: 60000;
7
+ readonly h: 3600000;
8
+ readonly d: 86400000;
9
+ };
10
+ /**
11
+ * A length of time: whole milliseconds as a number, or a number with a unit as a string,
12
+ * such as "500ms", "30s", "5m", "1.5h" or "7d".
13
+ */
14
+ export type Duration = number | `${number}${keyof typeof UNIT_MS}`;
15
+ /** Whole milliseconds from 0 to 365 days; throws a RangeError on anything else. */
16
+ export declare function toMilliseconds(duration: Duration): number;
17
+ /**
18
+ * A duration from text, such as an environment variable: whole milliseconds ("1500") or a
19
+ * number with a unit ("30s", "24h"). Throws a RangeError on anything else.
20
+ */
21
+ export declare function parseDuration(text: string): number;
22
+ export {};
@@ -0,0 +1,39 @@
1
+ /** The engine's bound: a sleep longer than a year is refused as a likely bug. */
2
+ export const MAX_DURATION_MS = 365 * 24 * 60 * 60 * 1000;
3
+ const UNIT_MS = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
4
+ const PATTERN = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/;
5
+ /** Whole milliseconds from 0 to 365 days; throws a RangeError on anything else. */
6
+ export function toMilliseconds(duration) {
7
+ let ms;
8
+ if (typeof duration === "number") {
9
+ if (!Number.isInteger(duration)) {
10
+ throw new RangeError(`a duration in milliseconds must be a whole number, not ${String(duration)}`);
11
+ }
12
+ ms = duration;
13
+ }
14
+ else {
15
+ const match = PATTERN.exec(duration);
16
+ const unit = match?.[2];
17
+ if (match?.[1] === undefined || unit === undefined || !(unit in UNIT_MS)) {
18
+ throw new RangeError(`"${duration}" is not a duration: use a number and one of ms, s, m, h or d, such as "30s"`);
19
+ }
20
+ // The pattern admits only these units, checked just above.
21
+ ms = Math.round(Number(match[1]) * UNIT_MS[unit]);
22
+ }
23
+ if (ms < 0 || ms > MAX_DURATION_MS) {
24
+ throw new RangeError(`a duration must be from 0 to 365 days, not ${String(ms)} ms`);
25
+ }
26
+ return ms;
27
+ }
28
+ /**
29
+ * A duration from text, such as an environment variable: whole milliseconds ("1500") or a
30
+ * number with a unit ("30s", "24h"). Throws a RangeError on anything else.
31
+ */
32
+ export function parseDuration(text) {
33
+ if (/^\d+$/.test(text))
34
+ return toMilliseconds(Number(text));
35
+ // toMilliseconds checks the text against the unit pattern at runtime, which is what the
36
+ // Duration template type describes; this only lets an unchecked string reach that check.
37
+ return toMilliseconds(text);
38
+ }
39
+ //# sourceMappingURL=duration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"duration.js","sourceRoot":"","sources":["../src/duration.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAEzD,MAAM,OAAO,GAAG,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAW,CAAC;AAQpF,MAAM,OAAO,GAAG,+BAA+B,CAAC;AAEhD,mFAAmF;AACnF,MAAM,UAAU,cAAc,CAAC,QAAkB;IAC/C,IAAI,EAAU,CAAC;IACf,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE,CAAC;QACjC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC;YAChC,MAAM,IAAI,UAAU,CAClB,0DAA0D,MAAM,CAAC,QAAQ,CAAC,EAAE,CAC7E,CAAC;QACJ,CAAC;QACD,EAAE,GAAG,QAAQ,CAAC;IAChB,CAAC;SAAM,CAAC;QACN,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACrC,MAAM,IAAI,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;QACxB,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,SAAS,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,CAAC,IAAI,IAAI,OAAO,CAAC,EAAE,CAAC;YACzE,MAAM,IAAI,UAAU,CAClB,IAAI,QAAQ,8EAA8E,CAC3F,CAAC;QACJ,CAAC;QACD,2DAA2D;QAC3D,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KA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