@oona/vlo 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/NOTICE +5 -0
- package/README.md +53 -2
- package/dist/agent.d.ts +107 -0
- package/dist/agent.js +324 -0
- package/dist/cli.d.ts +8 -0
- package/dist/cli.js +1540 -0
- package/dist/define-DwM_Qhbw.js +74 -0
- package/dist/domain-Bs8TeDCv.js +338 -0
- package/dist/domain-CJN6n_JD.d.ts +860 -0
- package/dist/host.d.ts +844 -0
- package/dist/host.js +314 -0
- package/dist/index-CIIcdblQ.d.ts +824 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +4 -0
- package/dist/roles-D25bG980.js +3869 -0
- package/dist/src-DVCYkPA7.js +734 -0
- package/dist/testing.d.ts +58 -0
- package/dist/testing.js +511 -0
- package/dist/types-BLQQMmkc.d.ts +746 -0
- package/dist/vlo_kernel-CtzHHfHA.js +276 -0
- package/package.json +93 -4
- package/wasm/vlo_kernel.d.ts +82 -0
- package/wasm/vlo_kernel.js +382 -0
- package/wasm/vlo_kernel_bg.wasm +0 -0
- package/wasm/vlo_kernel_bg.wasm.d.ts +15 -0
|
@@ -0,0 +1,734 @@
|
|
|
1
|
+
import { v as contentHash } from "./domain-Bs8TeDCv.js";
|
|
2
|
+
// src/core/commands.ts
|
|
3
|
+
/** Thrown synchronously by `cmd.task` when the input does not match the activity's schema. */
|
|
4
|
+
var ActivityInputError = class extends Error {
|
|
5
|
+
/** Name of the activity whose input schema rejected the value. */
|
|
6
|
+
activity;
|
|
7
|
+
/** @param detail - The Zod issues, joined as `path: message; …`. */
|
|
8
|
+
constructor(activity, detail) {
|
|
9
|
+
super(`Invalid input for activity "${activity}": ${detail}`);
|
|
10
|
+
this.name = "ActivityInputError";
|
|
11
|
+
this.activity = activity;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Requests one attempt-tracked execution of `target` with `input`.
|
|
16
|
+
*
|
|
17
|
+
* `input` is parsed with the activity's Zod schema; the parsed value (defaults applied) is
|
|
18
|
+
* what travels. The activity's `queue`, `retry`, `leaseMs` and `timeoutMs` are copied onto
|
|
19
|
+
* the command; `options.queue` overrides the queue for this call.
|
|
20
|
+
*
|
|
21
|
+
* @throws {@link ActivityInputError} when the input does not match the activity's schema.
|
|
22
|
+
*/
|
|
23
|
+
function task(target, input, options) {
|
|
24
|
+
const parsed = target.input.safeParse(input);
|
|
25
|
+
if (!parsed.success) {
|
|
26
|
+
const detail = parsed.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
|
|
27
|
+
throw new ActivityInputError(target.name, detail);
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
type: "task",
|
|
31
|
+
activity: target.name,
|
|
32
|
+
schema_ref: target.schemaRef,
|
|
33
|
+
input: parsed.data,
|
|
34
|
+
queue: options?.queue ?? target.queue,
|
|
35
|
+
retry: target.retry,
|
|
36
|
+
lease_ttl_ms: target.leaseMs,
|
|
37
|
+
...target.timeoutMs !== void 0 ? { timeout_ms: target.timeoutMs } : {},
|
|
38
|
+
...options?.id !== void 0 ? { id: options.id } : {}
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Schedules a `timer` event for the run. `ms` is relative to the timestamp of the event
|
|
43
|
+
* being reduced; `atMs` is absolute epoch milliseconds.
|
|
44
|
+
*
|
|
45
|
+
* Throws a `TypeError` synchronously when neither or both of `ms` / `atMs` are given.
|
|
46
|
+
*/
|
|
47
|
+
function timer(options) {
|
|
48
|
+
if (options.ms === void 0 && options.atMs === void 0) throw new TypeError("cmd.timer requires either `ms` or `atMs`");
|
|
49
|
+
if (options.ms !== void 0 && options.atMs !== void 0) throw new TypeError("cmd.timer takes either `ms` or `atMs`, not both");
|
|
50
|
+
return {
|
|
51
|
+
type: "timer",
|
|
52
|
+
...options.ms !== void 0 ? { fire_in_ms: options.ms } : {},
|
|
53
|
+
...options.atMs !== void 0 ? { fire_at_ms: options.atMs } : {},
|
|
54
|
+
...options.id !== void 0 ? { id: options.id } : {}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Starts a child run of `workflow` (a name, or anything with a `name` such as a
|
|
59
|
+
* {@link Workflow}) with `input`. The child's terminal status and output come back to this
|
|
60
|
+
* run as a `child_done` event on the spawn's step id. The workflow must be registered on
|
|
61
|
+
* the host that dispatches the command.
|
|
62
|
+
*/
|
|
63
|
+
function spawn(workflow, input, options) {
|
|
64
|
+
return {
|
|
65
|
+
type: "spawn",
|
|
66
|
+
workflow: typeof workflow === "string" ? workflow : workflow.name,
|
|
67
|
+
input,
|
|
68
|
+
...options?.id !== void 0 ? { id: options.id } : {}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Parks the run until a signal named after `definition` is delivered; the payload arrives
|
|
73
|
+
* on a `signal` event. A signal that arrived before the wait was opened is buffered and
|
|
74
|
+
* delivered immediately, oldest first. The run holds no compute while parked. With
|
|
75
|
+
* `timeoutMs` the kernel also opens a timer step `<id>:timeout` and cancels whichever of
|
|
76
|
+
* the two loses; see {@link signalTimeoutStepId}.
|
|
77
|
+
*/
|
|
78
|
+
function awaitSignal(definition, options) {
|
|
79
|
+
return {
|
|
80
|
+
type: "await_signal",
|
|
81
|
+
name: definition.name,
|
|
82
|
+
schema_ref: definition.schemaRef,
|
|
83
|
+
...options?.timeoutMs !== void 0 ? { timeout_ms: options.timeoutMs } : {},
|
|
84
|
+
...options?.id !== void 0 ? { id: options.id } : {}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Publishes `data` on a side channel. Emits never enter the run's history and never come
|
|
89
|
+
* back to the reducer; the host forwards them to event-stream subscribers, which is where
|
|
90
|
+
* progress ticks and UI hints belong.
|
|
91
|
+
*/
|
|
92
|
+
function emit(channel, data) {
|
|
93
|
+
return {
|
|
94
|
+
type: "emit",
|
|
95
|
+
channel,
|
|
96
|
+
data
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Closes the run as `completed` with `output`. It must be the last command of the reduction;
|
|
101
|
+
* the kernel rejects any command after it.
|
|
102
|
+
*/
|
|
103
|
+
function complete(output) {
|
|
104
|
+
return {
|
|
105
|
+
type: "complete",
|
|
106
|
+
output
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Closes the run as `continued`, carrying `input` as the start input of a successor run. It
|
|
111
|
+
* must be the last command of the reduction. The host starts the successor (same workflow,
|
|
112
|
+
* this `input`) in the same transaction and links the two runs by `continued_from` and
|
|
113
|
+
* `continued_to`; a parent run is notified once, by the run that finally closes.
|
|
114
|
+
*/
|
|
115
|
+
function continueAsNew(input) {
|
|
116
|
+
return {
|
|
117
|
+
type: "continue_as_new",
|
|
118
|
+
input
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Step id of the timer the kernel pairs with a signal wait `id` that carries a
|
|
123
|
+
* `timeoutMs`. A `timer` event with this step id means the deadline won the race.
|
|
124
|
+
*/
|
|
125
|
+
function signalTimeoutStepId(id) {
|
|
126
|
+
return `${id}:timeout`;
|
|
127
|
+
}
|
|
128
|
+
/** @deprecated Use {@link signalTimeoutStepId}; same string. */
|
|
129
|
+
const humanTimeoutStepId = signalTimeoutStepId;
|
|
130
|
+
/**
|
|
131
|
+
* Ask a human. Sugar over `await_signal` (with its deadline) + `emit`: the wait reserves
|
|
132
|
+
* `id` and the kernel opens `${id}:timeout` beside it, so whichever arrives first wins and
|
|
133
|
+
* the kernel cancels the loser. Returns commands — spread it into a reduction.
|
|
134
|
+
*/
|
|
135
|
+
function awaitHuman(definition, options) {
|
|
136
|
+
const commands = [awaitSignal(definition, {
|
|
137
|
+
id: options.id,
|
|
138
|
+
...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
|
|
139
|
+
})];
|
|
140
|
+
if (options.context !== void 0) commands.push(emit("human", {
|
|
141
|
+
signal: definition.name,
|
|
142
|
+
id: options.id,
|
|
143
|
+
context: options.context
|
|
144
|
+
}));
|
|
145
|
+
return commands;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* The command constructors a reducer returns to the engine. Each builds a plain
|
|
149
|
+
* {@link Command}; nothing runs until the host applies the reduction. `task`, `timer`,
|
|
150
|
+
* `spawn` and `awaitSignal` open a step, `emit` records a side effect, `complete` and
|
|
151
|
+
* `continueAsNew` close the run and must come last.
|
|
152
|
+
*
|
|
153
|
+
* @example
|
|
154
|
+
* ```ts
|
|
155
|
+
* import { cmd, defineWorkflow } from "@oona/vlo";
|
|
156
|
+
* import { approve, work } from "./activities.ts";
|
|
157
|
+
*
|
|
158
|
+
* export default defineWorkflow("review", {
|
|
159
|
+
* init: (input: { item: string }) => ({ item: input.item, upper: null as string | null }),
|
|
160
|
+
* on: {
|
|
161
|
+
* started: (s) => [s, [cmd.task(work, { item: s.item })]],
|
|
162
|
+
* task_done: (s, e) => [
|
|
163
|
+
* { ...s, upper: (e.output as { upper: string }).upper },
|
|
164
|
+
* cmd.awaitHuman(approve, { id: "approval", timeoutMs: 86_400_000 }),
|
|
165
|
+
* ],
|
|
166
|
+
* signal: (s) => [s, [cmd.complete({ upper: s.upper })]],
|
|
167
|
+
* timer: (s) => [s, [cmd.complete(null)]],
|
|
168
|
+
* },
|
|
169
|
+
* });
|
|
170
|
+
* ```
|
|
171
|
+
*/
|
|
172
|
+
const cmd = {
|
|
173
|
+
/** Runs an activity once, with retries. Throws {@link ActivityInputError} on bad input. */
|
|
174
|
+
task,
|
|
175
|
+
/** Fires a `timer` event after `ms` or at `atMs`. */
|
|
176
|
+
timer,
|
|
177
|
+
/** Starts a child run; its result arrives as `child_done`. */
|
|
178
|
+
spawn,
|
|
179
|
+
/** Parks the run until the named signal is delivered. */
|
|
180
|
+
awaitSignal,
|
|
181
|
+
/** `awaitSignal` with a deadline + `emit("human", …)`; returns a `Command[]`. */
|
|
182
|
+
awaitHuman,
|
|
183
|
+
/** Publishes on a side channel; never journaled. */
|
|
184
|
+
emit,
|
|
185
|
+
/** Closes the run as `completed`. Must be last. */
|
|
186
|
+
complete,
|
|
187
|
+
/** Closes the run as `continued` with a fresh start input. Must be last. */
|
|
188
|
+
continueAsNew
|
|
189
|
+
};
|
|
190
|
+
// src/core/workflow.ts
|
|
191
|
+
/**
|
|
192
|
+
* Fails the run. There is no `cmd.fail`: a run fails when its reducer throws, which keeps
|
|
193
|
+
* failure out of the command vocabulary and off the happy path.
|
|
194
|
+
*
|
|
195
|
+
* Host contract: the host catches a throw from `Workflow.reduce`, appends a `failed` event
|
|
196
|
+
* (`cause: "app_error"`, `error` = this message) and marks the run `failed`. The state
|
|
197
|
+
* checkpoint from before the event is kept, so the run can be rewound and forked.
|
|
198
|
+
*/
|
|
199
|
+
var WorkflowFailure = class extends Error {
|
|
200
|
+
/** Structured context for the failure, as given; `undefined` when none was. */
|
|
201
|
+
details;
|
|
202
|
+
/** @param details - Anything JSON that helps explain the failure, e.g. the step id and cause. */
|
|
203
|
+
constructor(message, details) {
|
|
204
|
+
super(message);
|
|
205
|
+
this.name = "WorkflowFailure";
|
|
206
|
+
this.details = details;
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
/**
|
|
210
|
+
* Defines a workflow: a named, pure reducer over the run's events.
|
|
211
|
+
*
|
|
212
|
+
* `def` is either a hand-written {@link WorkflowDef} or the output of {@link sequence}.
|
|
213
|
+
* Handlers must not read a clock, generate randomness or do I/O; time and randomness arrive
|
|
214
|
+
* on the event. State must be JSON-serialisable: it is stringified after every reduction.
|
|
215
|
+
* A handler that throws fails the run (see {@link WorkflowFailure}); so does an event
|
|
216
|
+
* whose handler is not registered, or a handler returning anything but `[state, Command[]]`.
|
|
217
|
+
*
|
|
218
|
+
* @example
|
|
219
|
+
* ```ts
|
|
220
|
+
* import { cmd, defineWorkflow } from "@oona/vlo";
|
|
221
|
+
* import { work } from "./activities.ts";
|
|
222
|
+
*
|
|
223
|
+
* export default defineWorkflow("uppercase", {
|
|
224
|
+
* init: (input: { item: string }) => ({ item: input.item }),
|
|
225
|
+
* on: {
|
|
226
|
+
* started: (s) => [s, [cmd.task(work, { item: s.item })]],
|
|
227
|
+
* task_done: (s, e) => [s, [cmd.complete(e.output ?? null)]],
|
|
228
|
+
* },
|
|
229
|
+
* });
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
function defineWorkflow(name, def) {
|
|
233
|
+
return {
|
|
234
|
+
kind: "workflow",
|
|
235
|
+
name,
|
|
236
|
+
digest: contentHash({
|
|
237
|
+
name,
|
|
238
|
+
v: 1
|
|
239
|
+
}),
|
|
240
|
+
def,
|
|
241
|
+
reduce(stateJson, event, initInput) {
|
|
242
|
+
const state = initialState(name, def, stateJson, initInput);
|
|
243
|
+
const handler = def.on[event.type];
|
|
244
|
+
if (typeof handler !== "function") throw new Error(`workflow "${name}": no handler for event "${event.type}"`);
|
|
245
|
+
return toWire(name, handler(state, event));
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
function initialState(name, def, stateJson, initInput) {
|
|
250
|
+
if (initInput !== void 0) return def.init(initInput);
|
|
251
|
+
if (stateJson === null) throw new Error(`workflow "${name}": reduce() needs either a state checkpoint or initInput`);
|
|
252
|
+
return JSON.parse(stateJson);
|
|
253
|
+
}
|
|
254
|
+
function toWire(name, result) {
|
|
255
|
+
if (!Array.isArray(result) || result.length !== 2 || !Array.isArray(result[1])) throw new TypeError(`workflow "${name}": a handler must return [state, Command[]]`);
|
|
256
|
+
const state = JSON.stringify(result[0]);
|
|
257
|
+
if (state === void 0) throw new TypeError(`workflow "${name}": state must be JSON-serialisable`);
|
|
258
|
+
return {
|
|
259
|
+
state,
|
|
260
|
+
commands: [...result[1]]
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
/** A sleep's step id is derived from its phase, so a replay asks for the same timer. */
|
|
264
|
+
const sleepStepId = (phase) => `sleep#${phase}`;
|
|
265
|
+
/** Likewise for a wait, which also names its deadline timer `${waitStepId}:timeout`. */
|
|
266
|
+
const waitStepId = (phase) => `wait#${phase}`;
|
|
267
|
+
/** Every handler folds the event's banked usage into state before anything else. */
|
|
268
|
+
function withUsage(state, event) {
|
|
269
|
+
return {
|
|
270
|
+
...state,
|
|
271
|
+
usage: event.usage_total
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
function enterPhase(steps, options, state, phase) {
|
|
275
|
+
const { fan: _fan, ...rest } = state;
|
|
276
|
+
const at = {
|
|
277
|
+
...rest,
|
|
278
|
+
phase
|
|
279
|
+
};
|
|
280
|
+
const spec = steps[phase];
|
|
281
|
+
if (spec === void 0) return [at, [cmd.complete(options.output ? options.output(at) : at.results)]];
|
|
282
|
+
switch (spec.kind) {
|
|
283
|
+
case "step": {
|
|
284
|
+
if (spec.when !== void 0 && !spec.when(at)) return enterPhase(steps, options, withResult(at, spec.key, null), phase + 1);
|
|
285
|
+
const input = spec.mapInput ? spec.mapInput(at) : defaultInput(steps, at, phase);
|
|
286
|
+
return [at, [cmd.task(spec.activity, input, spec.id !== void 0 ? { id: spec.id } : {})]];
|
|
287
|
+
}
|
|
288
|
+
case "fan_out":
|
|
289
|
+
case "fan_out_runs": {
|
|
290
|
+
const items = spec.select(at);
|
|
291
|
+
if (items.length === 0) return enterPhase(steps, options, withResult(at, spec.key, []), phase + 1);
|
|
292
|
+
const fan = {
|
|
293
|
+
activity: spec.kind === "fan_out" ? spec.activity.name : spec.workflow,
|
|
294
|
+
total: items.length,
|
|
295
|
+
next: 0,
|
|
296
|
+
outstanding: [],
|
|
297
|
+
outputs: new Array(items.length).fill(null)
|
|
298
|
+
};
|
|
299
|
+
const commands = [];
|
|
300
|
+
while (fan.next < fan.total && fan.outstanding.length < spec.concurrency) commands.push(dispatchNext(spec, fan, items));
|
|
301
|
+
return [{
|
|
302
|
+
...at,
|
|
303
|
+
fan
|
|
304
|
+
}, commands];
|
|
305
|
+
}
|
|
306
|
+
case "wait_for": return [at, cmd.awaitHuman(spec.signal, {
|
|
307
|
+
id: waitStepId(phase),
|
|
308
|
+
...spec.timeoutMs !== void 0 ? { timeoutMs: spec.timeoutMs } : {},
|
|
309
|
+
...spec.context !== void 0 ? { context: spec.context } : {}
|
|
310
|
+
})];
|
|
311
|
+
case "sleep": return [at, [cmd.timer({
|
|
312
|
+
ms: spec.ms,
|
|
313
|
+
id: sleepStepId(phase)
|
|
314
|
+
})]];
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
function onTaskDone(steps, options, state, event) {
|
|
318
|
+
const spec = steps[state.phase];
|
|
319
|
+
if (spec === void 0) return [state, []];
|
|
320
|
+
if (spec.kind === "step") {
|
|
321
|
+
if (spec.activity.name !== event.activity) return [state, []];
|
|
322
|
+
if (spec.id !== void 0 && spec.id !== event.step_id) return [state, []];
|
|
323
|
+
if (event.status !== "succeeded" && (spec.onFailure ?? "fail") === "fail") throw taskFailure(event);
|
|
324
|
+
const value = event.status === "succeeded" ? event.output ?? null : null;
|
|
325
|
+
return enterPhase(steps, options, withResult(state, spec.key, value), state.phase + 1);
|
|
326
|
+
}
|
|
327
|
+
if (spec.kind === "fan_out") {
|
|
328
|
+
if (!inFlight(state, event.step_id)) return [state, []];
|
|
329
|
+
if (event.status !== "succeeded" && (spec.onFailure ?? "fail") === "fail") throw taskFailure(event);
|
|
330
|
+
const value = event.status === "succeeded" ? event.output ?? null : null;
|
|
331
|
+
return settleFan(steps, options, spec, state, event.step_id, value);
|
|
332
|
+
}
|
|
333
|
+
return [state, []];
|
|
334
|
+
}
|
|
335
|
+
function onChildDone(steps, options, state, event) {
|
|
336
|
+
const spec = steps[state.phase];
|
|
337
|
+
if (spec === void 0 || spec.kind !== "fan_out_runs") return [state, []];
|
|
338
|
+
if (!inFlight(state, event.step_id)) return [state, []];
|
|
339
|
+
if (event.status !== "succeeded" && (spec.onFailure ?? "fail") === "fail") throw new WorkflowFailure(`child run "${spec.workflow}" ${event.status}`, {
|
|
340
|
+
workflow: spec.workflow,
|
|
341
|
+
step_id: event.step_id,
|
|
342
|
+
child_run_id: event.child_run_id,
|
|
343
|
+
status: event.status
|
|
344
|
+
});
|
|
345
|
+
const value = {
|
|
346
|
+
status: event.status,
|
|
347
|
+
output: event.output ?? null,
|
|
348
|
+
child_run_id: event.child_run_id
|
|
349
|
+
};
|
|
350
|
+
return settleFan(steps, options, spec, state, event.step_id, value);
|
|
351
|
+
}
|
|
352
|
+
/** Records one fan-out item's value, dispatches the next item or advances when none is left. */
|
|
353
|
+
function settleFan(steps, options, spec, state, stepId, value) {
|
|
354
|
+
const fan = state.fan;
|
|
355
|
+
if (fan === void 0) return [state, []];
|
|
356
|
+
const index = fanIndex(stepId);
|
|
357
|
+
const outputs = [...fan.outputs];
|
|
358
|
+
if (index !== void 0 && index < outputs.length) outputs[index] = value;
|
|
359
|
+
const nextFan = {
|
|
360
|
+
...fan,
|
|
361
|
+
outputs,
|
|
362
|
+
outstanding: fan.outstanding.filter((id) => id !== stepId)
|
|
363
|
+
};
|
|
364
|
+
if (nextFan.next < nextFan.total) {
|
|
365
|
+
const command = dispatchNext(spec, nextFan, spec.select(state));
|
|
366
|
+
return [{
|
|
367
|
+
...state,
|
|
368
|
+
fan: nextFan
|
|
369
|
+
}, [command]];
|
|
370
|
+
}
|
|
371
|
+
if (nextFan.outstanding.length > 0) return [{
|
|
372
|
+
...state,
|
|
373
|
+
fan: nextFan
|
|
374
|
+
}, []];
|
|
375
|
+
return enterPhase(steps, options, withResult(state, spec.key, outputs), state.phase + 1);
|
|
376
|
+
}
|
|
377
|
+
function onSignal(steps, options, state, event) {
|
|
378
|
+
const spec = steps[state.phase];
|
|
379
|
+
if (spec === void 0 || spec.kind !== "wait_for" || spec.signal.name !== event.name) return [state, []];
|
|
380
|
+
return enterPhase(steps, options, {
|
|
381
|
+
...state,
|
|
382
|
+
signals: {
|
|
383
|
+
...state.signals,
|
|
384
|
+
[spec.key]: event.payload
|
|
385
|
+
}
|
|
386
|
+
}, state.phase + 1);
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Timers belong to exactly one phase: a sleep's own timer, or a wait's deadline. Anything
|
|
390
|
+
* else — a deadline for a wait the signal already resolved, a timer from a phase left
|
|
391
|
+
* behind — is folded and ignored.
|
|
392
|
+
*/
|
|
393
|
+
function onTimer(steps, options, state, event) {
|
|
394
|
+
const spec = steps[state.phase];
|
|
395
|
+
if (spec === void 0) return [state, []];
|
|
396
|
+
if (spec.kind === "sleep") {
|
|
397
|
+
if (event.step_id !== sleepStepId(state.phase)) return [state, []];
|
|
398
|
+
return enterPhase(steps, options, state, state.phase + 1);
|
|
399
|
+
}
|
|
400
|
+
if (spec.kind === "wait_for") {
|
|
401
|
+
if (event.step_id !== signalTimeoutStepId(waitStepId(state.phase))) return [state, []];
|
|
402
|
+
if ((spec.onTimeout ?? "fail") === "fail") throw new WorkflowFailure(`human timeout: ${spec.signal.name}`, {
|
|
403
|
+
signal: spec.signal.name,
|
|
404
|
+
step_id: event.step_id
|
|
405
|
+
});
|
|
406
|
+
return enterPhase(steps, options, {
|
|
407
|
+
...state,
|
|
408
|
+
signals: {
|
|
409
|
+
...state.signals,
|
|
410
|
+
[spec.key]: null
|
|
411
|
+
}
|
|
412
|
+
}, state.phase + 1);
|
|
413
|
+
}
|
|
414
|
+
return [state, []];
|
|
415
|
+
}
|
|
416
|
+
/** Emits the next pending fan-out task or spawn and advances `fan` in place (always a fresh object). */
|
|
417
|
+
function dispatchNext(spec, fan, items) {
|
|
418
|
+
const index = fan.next;
|
|
419
|
+
if (index >= items.length) throw new WorkflowFailure(`${spec.kind === "fan_out" ? "fanOut" : "fanOutRuns"} "${spec.key}": select() is not pure — it returned ${items.length} items, expected ${fan.total}`);
|
|
420
|
+
const id = `${fan.activity}#${index}`;
|
|
421
|
+
fan.next = index + 1;
|
|
422
|
+
fan.outstanding = [...fan.outstanding, id];
|
|
423
|
+
const item = items[index];
|
|
424
|
+
return spec.kind === "fan_out" ? cmd.task(spec.activity, item, { id }) : cmd.spawn(spec.workflow, item, { id });
|
|
425
|
+
}
|
|
426
|
+
function inFlight(state, stepId) {
|
|
427
|
+
return state.fan !== void 0 && state.fan.outstanding.includes(stepId);
|
|
428
|
+
}
|
|
429
|
+
function taskFailure(event) {
|
|
430
|
+
return new WorkflowFailure(`activity "${event.activity}" ${event.status}${event.error ? `: ${event.error}` : ""}`, {
|
|
431
|
+
activity: event.activity,
|
|
432
|
+
step_id: event.step_id,
|
|
433
|
+
status: event.status,
|
|
434
|
+
...event.cause !== void 0 ? { cause: event.cause } : {}
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
function fanIndex(stepId) {
|
|
438
|
+
const at = stepId.lastIndexOf("#");
|
|
439
|
+
if (at < 0) return void 0;
|
|
440
|
+
const parsed = Number(stepId.slice(at + 1));
|
|
441
|
+
return Number.isInteger(parsed) && parsed >= 0 ? parsed : void 0;
|
|
442
|
+
}
|
|
443
|
+
/** The previous phase's stored value, skipping sleeps, which store nothing. */
|
|
444
|
+
function defaultInput(steps, state, phase) {
|
|
445
|
+
for (let at = phase - 1; at >= 0; at -= 1) {
|
|
446
|
+
const previous = steps[at];
|
|
447
|
+
if (previous === void 0) break;
|
|
448
|
+
if (previous.kind === "sleep") continue;
|
|
449
|
+
return (previous.kind === "wait_for" ? state.signals : state.results)[previous.key] ?? null;
|
|
450
|
+
}
|
|
451
|
+
return state.input;
|
|
452
|
+
}
|
|
453
|
+
function withResult(state, key, value) {
|
|
454
|
+
return {
|
|
455
|
+
...state,
|
|
456
|
+
results: {
|
|
457
|
+
...state.results,
|
|
458
|
+
[key]: value
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
// src/core/helpers/sequence.ts
|
|
463
|
+
/**
|
|
464
|
+
* A {@link sequence} phase that runs `target` once.
|
|
465
|
+
*
|
|
466
|
+
* Without `mapInput` the task input is the run's start input for phase 0 and the previous
|
|
467
|
+
* phase's stored value afterwards (sleeps are skipped). The output is stored in
|
|
468
|
+
* `results[target.name]`. A task that does not succeed fails the run, unless
|
|
469
|
+
* `onFailure: "continue"` stores `null` instead; `when` returning `false` also stores `null`
|
|
470
|
+
* and skips the task. `id` pins the step id for handlers that key on it.
|
|
471
|
+
*
|
|
472
|
+
* @example
|
|
473
|
+
* ```ts
|
|
474
|
+
* import { defineWorkflow, resultOf, sequence, step } from "@oona/vlo";
|
|
475
|
+
* import { finish, notify, plan } from "./activities.ts";
|
|
476
|
+
*
|
|
477
|
+
* export default defineWorkflow("example", sequence([
|
|
478
|
+
* step(plan),
|
|
479
|
+
* step(finish, (state) => ({ uppers: resultOf(state, plan).items, approvedBy: "auto" })),
|
|
480
|
+
* step(notify, undefined, { onFailure: "continue", when: (s) => resultOf(s, plan).items.length > 0 }),
|
|
481
|
+
* ]));
|
|
482
|
+
* ```
|
|
483
|
+
*/
|
|
484
|
+
function step(target, mapInput, options = {}) {
|
|
485
|
+
return {
|
|
486
|
+
kind: "step",
|
|
487
|
+
key: target.name,
|
|
488
|
+
activity: target,
|
|
489
|
+
...mapInput !== void 0 ? { mapInput } : {},
|
|
490
|
+
...options.id !== void 0 ? { id: options.id } : {},
|
|
491
|
+
...options.onFailure !== void 0 ? { onFailure: options.onFailure } : {},
|
|
492
|
+
...options.when !== void 0 ? { when: options.when } : {}
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* A {@link sequence} phase that runs `target` once per item `select` returns, at most
|
|
497
|
+
* `concurrency` at a time, with step ids `${target.name}#${index}`.
|
|
498
|
+
*
|
|
499
|
+
* `select` must be pure and read only state written by earlier phases: it is re-evaluated
|
|
500
|
+
* on every event of the phase and the run fails if it returns a different count. Outputs
|
|
501
|
+
* are stored in `results[target.name]` in item order; an empty selection stores `[]` and
|
|
502
|
+
* moves on. A task that does not succeed fails the run, unless `onFailure: "continue"`
|
|
503
|
+
* stores `null` for that item.
|
|
504
|
+
*
|
|
505
|
+
* Throws a `TypeError` synchronously unless `concurrency` is an integer ≥ 1.
|
|
506
|
+
*
|
|
507
|
+
* @example
|
|
508
|
+
* ```ts
|
|
509
|
+
* import { defineWorkflow, fanOut, resultOf, sequence, step } from "@oona/vlo";
|
|
510
|
+
* import { plan, work } from "./activities.ts";
|
|
511
|
+
*
|
|
512
|
+
* export default defineWorkflow("example", sequence([
|
|
513
|
+
* step(plan),
|
|
514
|
+
* fanOut(work, (state) => resultOf(state, plan).items.map((item) => ({ item })), { concurrency: 2 }),
|
|
515
|
+
* ]));
|
|
516
|
+
* ```
|
|
517
|
+
*/
|
|
518
|
+
function fanOut(target, select, options) {
|
|
519
|
+
assertConcurrency("fanOut", options.concurrency);
|
|
520
|
+
return {
|
|
521
|
+
kind: "fan_out",
|
|
522
|
+
key: target.name,
|
|
523
|
+
activity: target,
|
|
524
|
+
select,
|
|
525
|
+
concurrency: options.concurrency,
|
|
526
|
+
...options.onFailure !== void 0 ? { onFailure: options.onFailure } : {}
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* A {@link sequence} phase that spawns one child run of `target` per item `select` returns,
|
|
531
|
+
* at most `concurrency` at a time, with step ids `${workflow}#${index}`.
|
|
532
|
+
*
|
|
533
|
+
* `select` has the same purity rule as {@link fanOut}. Each item is the child's start input.
|
|
534
|
+
* The phase stores a {@link ChildResult} per item in `results[workflow]`, in item order;
|
|
535
|
+
* read it with {@link fanOutRunsResultsOf}. An empty selection stores `[]` and moves on.
|
|
536
|
+
* A child that did not complete fails the run, unless `onFailure: "continue"` records its
|
|
537
|
+
* status and moves on. The child workflow must be registered on the same host.
|
|
538
|
+
*
|
|
539
|
+
* Throws a `TypeError` synchronously unless `concurrency` is an integer ≥ 1.
|
|
540
|
+
*
|
|
541
|
+
* @example
|
|
542
|
+
* ```ts
|
|
543
|
+
* import { defineWorkflow, fanOutRuns, fanOutRunsResultsOf, resultOf, sequence, step } from "@oona/vlo";
|
|
544
|
+
* import { plan, summarise } from "./activities.ts";
|
|
545
|
+
* import { readSource } from "./read-source.workflow.ts";
|
|
546
|
+
*
|
|
547
|
+
* export default defineWorkflow("research", sequence([
|
|
548
|
+
* step(plan),
|
|
549
|
+
* fanOutRuns(readSource, (s) => resultOf(s, plan).sourceIds.map((sourceId) => ({ sourceId })), {
|
|
550
|
+
* concurrency: 5,
|
|
551
|
+
* onFailure: "continue",
|
|
552
|
+
* }),
|
|
553
|
+
* step(summarise, (s) => ({ read: fanOutRunsResultsOf(s, readSource).filter((r) => r.status === "succeeded").length })),
|
|
554
|
+
* ]));
|
|
555
|
+
* ```
|
|
556
|
+
*/
|
|
557
|
+
function fanOutRuns(target, select, options) {
|
|
558
|
+
assertConcurrency("fanOutRuns", options.concurrency);
|
|
559
|
+
return {
|
|
560
|
+
kind: "fan_out_runs",
|
|
561
|
+
key: nameOf(target),
|
|
562
|
+
workflow: nameOf(target),
|
|
563
|
+
select,
|
|
564
|
+
concurrency: options.concurrency,
|
|
565
|
+
...options.onFailure !== void 0 ? { onFailure: options.onFailure } : {}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* A {@link sequence} phase that parks the run until `definition` is delivered.
|
|
570
|
+
*
|
|
571
|
+
* The payload is stored in `signals[definition.name]`. With `timeoutMs` the wait races the
|
|
572
|
+
* kernel's paired deadline timer (the loser is cancelled): `onTimeout: "fail"` (default)
|
|
573
|
+
* fails the run, `"continue"` stores `null` and advances. `context` is emitted on the
|
|
574
|
+
* `human` channel when the wait opens. A signal or deadline arriving for a phase already
|
|
575
|
+
* left behind is ignored.
|
|
576
|
+
*
|
|
577
|
+
* @example
|
|
578
|
+
* ```ts
|
|
579
|
+
* import { defineWorkflow, sequence, signalOf, step, waitFor } from "@oona/vlo";
|
|
580
|
+
* import { approve, finish, plan } from "./activities.ts";
|
|
581
|
+
*
|
|
582
|
+
* export default defineWorkflow("example", sequence([
|
|
583
|
+
* step(plan),
|
|
584
|
+
* waitFor(approve, { timeoutMs: 86_400_000, onTimeout: "fail", context: { what: "plan" } }),
|
|
585
|
+
* step(finish, (state) => ({ uppers: [], approvedBy: signalOf(state, approve).by })),
|
|
586
|
+
* ]));
|
|
587
|
+
* ```
|
|
588
|
+
*/
|
|
589
|
+
function waitFor(definition, options = {}) {
|
|
590
|
+
return {
|
|
591
|
+
kind: "wait_for",
|
|
592
|
+
key: definition.name,
|
|
593
|
+
signal: definition,
|
|
594
|
+
...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
|
|
595
|
+
...options.onTimeout !== void 0 ? { onTimeout: options.onTimeout } : {},
|
|
596
|
+
...options.context !== void 0 ? { context: options.context } : {}
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* A {@link sequence} phase that parks the run on a timer for `ms` milliseconds. It stores
|
|
601
|
+
* nothing: the phase after it receives the value of the last phase that stored one.
|
|
602
|
+
*
|
|
603
|
+
* @example
|
|
604
|
+
* ```ts
|
|
605
|
+
* import { defineWorkflow, sequence, sleep, step } from "@oona/vlo";
|
|
606
|
+
* import { plan, finish } from "./activities.ts";
|
|
607
|
+
*
|
|
608
|
+
* export default defineWorkflow("example", sequence([
|
|
609
|
+
* step(plan),
|
|
610
|
+
* sleep(60_000),
|
|
611
|
+
* step(finish, (state) => ({ uppers: [], approvedBy: "timer" })),
|
|
612
|
+
* ]));
|
|
613
|
+
* ```
|
|
614
|
+
*/
|
|
615
|
+
function sleep(ms) {
|
|
616
|
+
return {
|
|
617
|
+
kind: "sleep",
|
|
618
|
+
ms
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Compiles an ordered list of phases into a {@link WorkflowDef} for {@link defineWorkflow}.
|
|
623
|
+
*
|
|
624
|
+
* Phases run one after another: {@link step}, {@link fanOut}, {@link fanOutRuns},
|
|
625
|
+
* {@link waitFor} and {@link sleep}. Outputs go to `results` keyed by activity or workflow
|
|
626
|
+
* name and signal payloads to `signals` keyed by signal name, so two phases on the same
|
|
627
|
+
* target share a key. After the last phase the run completes with `results`, or with
|
|
628
|
+
* `options.output(state)`. `state.usage` always holds the run's banked usage as of the
|
|
629
|
+
* last event. Events that do not belong to the current phase are ignored: state
|
|
630
|
+
* unchanged, no commands.
|
|
631
|
+
*
|
|
632
|
+
* @example
|
|
633
|
+
* ```ts
|
|
634
|
+
* import {
|
|
635
|
+
* defineWorkflow, fanOut, fanOutResultsOf, resultOf, sequence, signalOf, step, waitFor,
|
|
636
|
+
* } from "@oona/vlo";
|
|
637
|
+
* import { approve, finish, plan, work } from "./activities.ts";
|
|
638
|
+
*
|
|
639
|
+
* export default defineWorkflow("example", sequence([
|
|
640
|
+
* step(plan),
|
|
641
|
+
* fanOut(work, (s) => resultOf(s, plan).items.map((item) => ({ item })), { concurrency: 2 }),
|
|
642
|
+
* waitFor(approve),
|
|
643
|
+
* step(finish, (s) => ({
|
|
644
|
+
* uppers: fanOutResultsOf(s, work).map((o) => o.upper),
|
|
645
|
+
* approvedBy: signalOf(s, approve).by,
|
|
646
|
+
* })),
|
|
647
|
+
* ], { output: (s) => ({ report: resultOf(s, finish).report, tokens: s.usage?.tokens ?? 0 }) }));
|
|
648
|
+
* ```
|
|
649
|
+
*/
|
|
650
|
+
function sequence(steps, options = {}) {
|
|
651
|
+
return {
|
|
652
|
+
init: (input) => ({
|
|
653
|
+
phase: 0,
|
|
654
|
+
input,
|
|
655
|
+
results: {},
|
|
656
|
+
signals: {}
|
|
657
|
+
}),
|
|
658
|
+
on: {
|
|
659
|
+
started: (state, event) => enterPhase(steps, options, withUsage(state, event), 0),
|
|
660
|
+
task_done: (state, event) => onTaskDone(steps, options, withUsage(state, event), event),
|
|
661
|
+
child_done: (state, event) => onChildDone(steps, options, withUsage(state, event), event),
|
|
662
|
+
signal: (state, event) => onSignal(steps, options, withUsage(state, event), event),
|
|
663
|
+
timer: (state, event) => onTimer(steps, options, withUsage(state, event), event)
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
function assertConcurrency(helper, concurrency) {
|
|
668
|
+
if (!Number.isInteger(concurrency) || concurrency < 1) throw new TypeError(`${helper}: concurrency must be an integer >= 1`);
|
|
669
|
+
}
|
|
670
|
+
function nameOf(target) {
|
|
671
|
+
return typeof target === "string" ? target : target.name;
|
|
672
|
+
}
|
|
673
|
+
// src/core/helpers/sequence-access.ts
|
|
674
|
+
/**
|
|
675
|
+
* The output of an earlier {@link step} on `target`, typed as the activity's output.
|
|
676
|
+
*
|
|
677
|
+
* @example
|
|
678
|
+
* ```ts
|
|
679
|
+
* step(finish, (state) => ({ uppers: resultOf(state, plan).items, approvedBy: "auto" }))
|
|
680
|
+
* ```
|
|
681
|
+
*/
|
|
682
|
+
function resultOf(state, target) {
|
|
683
|
+
return stored(state.results, target.name, "result");
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* The outputs of an earlier {@link fanOut} on `target`, in item order. An empty
|
|
687
|
+
* selection stored `[]`.
|
|
688
|
+
*
|
|
689
|
+
* @example
|
|
690
|
+
* ```ts
|
|
691
|
+
* step(finish, (state) => ({
|
|
692
|
+
* uppers: fanOutResultsOf(state, work).map((output) => output.upper),
|
|
693
|
+
* approvedBy: "auto",
|
|
694
|
+
* }))
|
|
695
|
+
* ```
|
|
696
|
+
*/
|
|
697
|
+
function fanOutResultsOf(state, target) {
|
|
698
|
+
return stored(state.results, target.name, "fan-out result");
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* The outcomes of an earlier {@link fanOutRuns} on `target`, in item order: one
|
|
702
|
+
* {@link ChildResult} per child, whose `output` is `null` unless the child completed. An
|
|
703
|
+
* empty selection stored `[]`. `O` is the child workflow's completion output type.
|
|
704
|
+
*
|
|
705
|
+
* @example
|
|
706
|
+
* ```ts
|
|
707
|
+
* step(summarise, (state) => ({
|
|
708
|
+
* read: fanOutRunsResultsOf<{ ok: boolean }>(state, readSource).filter((r) => r.output?.ok).length,
|
|
709
|
+
* }))
|
|
710
|
+
* ```
|
|
711
|
+
*/
|
|
712
|
+
function fanOutRunsResultsOf(state, target) {
|
|
713
|
+
const name = typeof target === "string" ? target : target.name;
|
|
714
|
+
return stored(state.results, name, "fan-out runs result");
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* The payload an earlier {@link waitFor} on `definition` received, typed as the signal's
|
|
718
|
+
* payload. After an `onTimeout: "continue"` deadline the stored value is `null`, which
|
|
719
|
+
* this returns as-is; narrow it yourself when that option is in play.
|
|
720
|
+
*
|
|
721
|
+
* @example
|
|
722
|
+
* ```ts
|
|
723
|
+
* step(finish, (state) => ({ uppers: [], approvedBy: signalOf(state, approve).by }))
|
|
724
|
+
* ```
|
|
725
|
+
*/
|
|
726
|
+
function signalOf(state, definition) {
|
|
727
|
+
return stored(state.signals, definition.name, "signal");
|
|
728
|
+
}
|
|
729
|
+
function stored(store, key, what) {
|
|
730
|
+
const value = store[key];
|
|
731
|
+
if (value === void 0) throw new TypeError(`no ${what} for "${key}" yet: only phases earlier in the sequence have a value`);
|
|
732
|
+
return value;
|
|
733
|
+
}
|
|
734
|
+
export { fanOut as a, sleep as c, WorkflowFailure as d, defineWorkflow as f, signalTimeoutStepId as g, humanTimeoutStepId as h, signalOf as i, step as l, cmd as m, fanOutRunsResultsOf as n, fanOutRuns as o, ActivityInputError as p, resultOf as r, sequence as s, fanOutResultsOf as t, waitFor as u };
|