@operad-io/engine 0.0.0-stage → 0.0.1

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.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/config.schema.json +188 -0
  3. package/keys.schema.json +12 -0
  4. package/package.json +22 -4
  5. package/src/config/config.ts +627 -0
  6. package/src/config/index.ts +1 -0
  7. package/src/flow/define-flow.ts +57 -0
  8. package/src/flow/index.ts +5 -0
  9. package/src/flow/load.ts +41 -0
  10. package/src/flow/types.ts +107 -0
  11. package/src/flow/validate.ts +296 -0
  12. package/src/http/address.ts +142 -0
  13. package/src/http/index.ts +25 -0
  14. package/src/http/link.ts +20 -0
  15. package/src/http/server.ts +920 -0
  16. package/src/http/token.ts +85 -0
  17. package/src/index.ts +16 -0
  18. package/src/kernel/decide.ts +689 -0
  19. package/src/kernel/index.ts +3 -0
  20. package/src/kernel/state.ts +275 -0
  21. package/src/kernel/types.ts +366 -0
  22. package/src/log/errors.ts +77 -0
  23. package/src/log/facts.ts +50 -0
  24. package/src/log/index.ts +6 -0
  25. package/src/log/json-value.ts +67 -0
  26. package/src/log/open-log.ts +17 -0
  27. package/src/log/schema.ts +5 -0
  28. package/src/log/secret.ts +30 -0
  29. package/src/log/sqlite.ts +1011 -0
  30. package/src/log/types.ts +230 -0
  31. package/src/loop/code-watch.ts +486 -0
  32. package/src/loop/index.ts +3 -0
  33. package/src/loop/older-code.ts +58 -0
  34. package/src/loop/serve.ts +483 -0
  35. package/src/markdown.ts +451 -0
  36. package/src/notify/index.ts +10 -0
  37. package/src/notify/notify.ts +256 -0
  38. package/src/platform/file-lock.ts +385 -0
  39. package/src/platform/index.ts +13 -0
  40. package/src/platform/load.ts +18 -0
  41. package/src/platform/process-group.ts +635 -0
  42. package/src/platform/process-watch.ts +152 -0
  43. package/src/platform/sqlite-open.ts +104 -0
  44. package/src/platform/step-reap.ts +668 -0
  45. package/src/platform/watch.ts +158 -0
  46. package/src/platform/worker-reports.ts +34 -0
  47. package/src/plugin/action-schema.ts +550 -0
  48. package/src/plugin/declared-flows.ts +74 -0
  49. package/src/plugin/define-plugin.ts +12 -0
  50. package/src/plugin/errors.ts +73 -0
  51. package/src/plugin/filters.ts +46 -0
  52. package/src/plugin/harness.ts +50 -0
  53. package/src/plugin/home.ts +13 -0
  54. package/src/plugin/index.ts +65 -0
  55. package/src/plugin/install.ts +268 -0
  56. package/src/plugin/keys.ts +63 -0
  57. package/src/plugin/load.ts +256 -0
  58. package/src/plugin/logger.ts +30 -0
  59. package/src/plugin/object-facts.ts +132 -0
  60. package/src/plugin/open-store.ts +32 -0
  61. package/src/plugin/paging.ts +133 -0
  62. package/src/plugin/registry.ts +1783 -0
  63. package/src/plugin/secrets.ts +141 -0
  64. package/src/plugin/semver.ts +110 -0
  65. package/src/plugin/settings.ts +64 -0
  66. package/src/plugin/sqlite-store.ts +756 -0
  67. package/src/plugin/store.ts +318 -0
  68. package/src/plugin/types.ts +1236 -0
  69. package/src/plugin/usage.ts +157 -0
  70. package/src/plugin/validate.ts +1028 -0
  71. package/src/runner/answer.ts +156 -0
  72. package/src/runner/ask.ts +483 -0
  73. package/src/runner/cancel.ts +51 -0
  74. package/src/runner/errors.ts +20 -0
  75. package/src/runner/grants.ts +92 -0
  76. package/src/runner/index.ts +33 -0
  77. package/src/runner/limits.ts +403 -0
  78. package/src/runner/lock.ts +140 -0
  79. package/src/runner/runner.ts +1175 -0
  80. package/src/runner/service.ts +184 -0
  81. package/src/runner/step-worker.ts +303 -0
  82. package/src/testing/clock.ts +67 -0
  83. package/src/testing/index.ts +90 -0
  84. package/src/testing/types.ts +116 -0
  85. package/src/testing/world.ts +369 -0
  86. package/src/trigger/cron.ts +193 -0
  87. package/src/trigger/index.ts +32 -0
  88. package/src/trigger/kernel.ts +1212 -0
  89. package/src/trigger/rules.ts +300 -0
  90. package/src/trigger/store.ts +233 -0
  91. package/src/trigger/types.ts +156 -0
  92. package/src/util.ts +50 -0
  93. package/src/views/history.ts +634 -0
  94. package/src/views/index.ts +7 -0
  95. package/src/views/pending.ts +209 -0
  96. package/src/views/presentation.ts +2551 -0
  97. package/src/views/running.ts +255 -0
  98. package/src/views/settings.ts +452 -0
  99. package/src/views/types.ts +72 -0
  100. package/src/views/uploads.ts +228 -0
  101. package/triggers.schema.json +48 -0
  102. package/README.md +0 -3
@@ -0,0 +1,1175 @@
1
+ /** Drives one run: inputs to `decide`, facts to the log, effects to plugins. */
2
+
3
+ import type { FlowDefinition } from "../flow/types.ts";
4
+ import type { Input, KernelState, StartInput } from "../kernel/types.ts";
5
+ import { RunEndedError, SeqConflictError } from "../log/errors.ts";
6
+ import type { JsonValue, LogBackend } from "../log/types.ts";
7
+ import type {
8
+ AskRequest,
9
+ PluginStepResult,
10
+ RunObject,
11
+ StepAsker,
12
+ StepLimiter,
13
+ } from "../plugin/types.ts";
14
+ import { PluginRegistry } from "../plugin/registry.ts";
15
+ import type { ObjectRef } from "../plugin/types.ts";
16
+ import { messageOf } from "../plugin/errors.ts";
17
+ import type { StepEvent, TriggerView } from "../trigger/types.ts";
18
+ import { Worker } from "node:worker_threads";
19
+ import { KILL_GRACE_MS, REAP_ROUNDS, systemClock, type Clock } from "../platform/index.ts";
20
+ import {
21
+ acquireLock,
22
+ runLockPath,
23
+ type LockHandle,
24
+ } from "./lock.ts";
25
+ import { AskHost, type AskTimer } from "./ask.ts";
26
+ import { StepLimits } from "./limits.ts";
27
+ import { accessWith, usedGrants } from "./grants.ts";
28
+ import { appendInput, applyInput, parseObjectKey, readState } from "./service.ts";
29
+
30
+ /** The wall time a plugin step may take before the run records a failure. */
31
+ export const DEFAULT_STEP_TIMEOUT_MS = 5 * 60 * 1000;
32
+
33
+ /**
34
+ * How long a worker gets to stop what it started before it is terminated. A
35
+ * process-group stop may wait one grace for the sentinel's `ready` and one more
36
+ * after SIGTERM before it sends SIGKILL, so this exceeds both plus latency;
37
+ * terminating sooner would leave the sentinel and its line running. The sweep
38
+ * of what the step left behind runs after the stop, in the same worker, and
39
+ * gets its own budget.
40
+ */
41
+ export const REAP_BUDGET_MS = REAP_ROUNDS * (KILL_GRACE_MS + 2000);
42
+ export const WORKER_ABORT_GRACE_MS = 2 * KILL_GRACE_MS + 1000 + REAP_BUDGET_MS;
43
+
44
+ const STEP_WORKER = new URL("./step-worker.ts", import.meta.url);
45
+
46
+ interface StepWorkerReply {
47
+ readonly kind: "result";
48
+ readonly ok: boolean;
49
+ readonly result?: PluginStepResult | undefined;
50
+ readonly error?: string | undefined;
51
+ }
52
+
53
+ interface StepWorkerEmit {
54
+ readonly kind: "emit";
55
+ readonly id: number;
56
+ readonly plugin: string;
57
+ readonly event: StepEvent;
58
+ }
59
+
60
+ /** A nested step in the worker asks for, cancels or gives back a place. */
61
+ type StepWorkerLimit =
62
+ | {
63
+ readonly kind: "limit";
64
+ readonly id: number;
65
+ readonly use: string;
66
+ readonly key: string;
67
+ readonly concurrent: number;
68
+ /** A wait the step reports for a place it manages itself. */
69
+ readonly report?: boolean;
70
+ /** How many waiters its plugin says are ahead of a reported wait. */
71
+ readonly ahead?: number;
72
+ }
73
+ | { readonly kind: "limit-cancel"; readonly id: number }
74
+ | { readonly kind: "limit-release"; readonly id: number };
75
+
76
+ /** A step in the worker asks a person, or stops asking. */
77
+ type StepWorkerAsk =
78
+ | { readonly kind: "ask"; readonly id: number; readonly request: AskRequest }
79
+ | { readonly kind: "ask-cancel"; readonly id: number }
80
+ | { readonly kind: "grant"; readonly id: number; readonly waitId: string };
81
+
82
+ function isStepWorkerAsk(value: unknown): value is StepWorkerAsk {
83
+ if (typeof value !== "object" || value === null) return false;
84
+ if (typeof (value as { id?: unknown }).id !== "number") return false;
85
+ const kind = (value as { kind?: unknown }).kind;
86
+ if (kind === "ask-cancel") return true;
87
+ if (kind === "grant") {
88
+ return typeof (value as { waitId?: unknown }).waitId === "string";
89
+ }
90
+ if (kind !== "ask") return false;
91
+ const request = (value as { request?: unknown }).request;
92
+ return (
93
+ typeof request === "object" &&
94
+ request !== null &&
95
+ typeof (request as { prompt?: unknown }).prompt === "string"
96
+ );
97
+ }
98
+
99
+ /** What `StepTimeout` uses to tell time; tests give it their own. */
100
+ export interface TimeoutClock {
101
+ readonly now: () => number;
102
+ readonly set: (fire: () => void, ms: number) => unknown;
103
+ readonly clear: (handle: unknown) => void;
104
+ }
105
+
106
+ const REAL_CLOCK: TimeoutClock = {
107
+ now: () => Date.now(),
108
+ set: (fire, ms) => setTimeout(fire, ms),
109
+ clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
110
+ };
111
+
112
+ /**
113
+ * A step's wall time. It stops while a question to a person is open: the
114
+ * person's time is not the step's.
115
+ */
116
+ export class StepTimeout {
117
+ private handle: unknown;
118
+ private remaining: number;
119
+ private startedAt = 0;
120
+ private paused = 0;
121
+ private done = false;
122
+
123
+ constructor(
124
+ ms: number,
125
+ private readonly fire: () => void,
126
+ private readonly time: TimeoutClock = REAL_CLOCK,
127
+ ) {
128
+ this.remaining = ms;
129
+ this.start();
130
+ }
131
+
132
+ private start(): void {
133
+ this.startedAt = this.time.now();
134
+ this.handle = this.time.set(() => {
135
+ this.handle = undefined;
136
+ if (!this.done) this.fire();
137
+ }, this.remaining);
138
+ }
139
+
140
+ pause(): void {
141
+ this.paused += 1;
142
+ if (this.paused !== 1 || this.done || this.handle === undefined) return;
143
+ this.time.clear(this.handle);
144
+ this.handle = undefined;
145
+ this.remaining = Math.max(0, this.remaining - (this.time.now() - this.startedAt));
146
+ }
147
+
148
+ resume(): void {
149
+ if (this.paused === 0) return;
150
+ this.paused -= 1;
151
+ if (this.paused === 0 && !this.done) this.start();
152
+ }
153
+
154
+ clear(): void {
155
+ this.done = true;
156
+ if (this.handle !== undefined) this.time.clear(this.handle);
157
+ this.handle = undefined;
158
+ }
159
+ }
160
+
161
+ function isStepWorkerLimit(value: unknown): value is StepWorkerLimit {
162
+ if (typeof value !== "object" || value === null) return false;
163
+ const kind = (value as { kind?: unknown }).kind;
164
+ if (typeof (value as { id?: unknown }).id !== "number") return false;
165
+ if (kind === "limit-cancel" || kind === "limit-release") return true;
166
+ return (
167
+ kind === "limit" &&
168
+ typeof (value as { use?: unknown }).use === "string" &&
169
+ typeof (value as { key?: unknown }).key === "string" &&
170
+ typeof (value as { concurrent?: unknown }).concurrent === "number"
171
+ );
172
+ }
173
+
174
+ function isStepWorkerReply(value: unknown): value is StepWorkerReply {
175
+ return (
176
+ typeof value === "object" &&
177
+ value !== null &&
178
+ "kind" in value &&
179
+ (value as { kind?: unknown }).kind === "result" &&
180
+ "ok" in value &&
181
+ typeof (value as { ok: unknown }).ok === "boolean"
182
+ );
183
+ }
184
+
185
+ function isStepWorkerEmit(value: unknown): value is StepWorkerEmit {
186
+ return (
187
+ typeof value === "object" &&
188
+ value !== null &&
189
+ (value as { kind?: unknown }).kind === "emit" &&
190
+ typeof (value as { id?: unknown }).id === "number" &&
191
+ typeof (value as { plugin?: unknown }).plugin === "string" &&
192
+ typeof (value as { event?: unknown }).event === "object"
193
+ );
194
+ }
195
+
196
+ export type RunnerOutcome =
197
+ | "progress"
198
+ | "waiting"
199
+ | "blocked"
200
+ | "ended"
201
+ /** The process stopped between steps so a fresh one continues the run. */
202
+ | "handover";
203
+
204
+ export interface RunnerOptions {
205
+ readonly log: LogBackend;
206
+ readonly flow: FlowDefinition;
207
+ readonly runId: string;
208
+ readonly registry: PluginRegistry;
209
+ readonly clock?: (() => number) | undefined;
210
+ /**
211
+ * The timers that time a step's run. A test passes a fake one to decide when
212
+ * a step times out; the grace a worker gets to stop after an abort stays real.
213
+ * @internal Used by `@operad-io/engine/testing`.
214
+ */
215
+ readonly timers?: Clock | undefined;
216
+ readonly stepTimeoutMs?: number | undefined;
217
+ /** `ask.graceSecs` from config.json: how long `ctx.ask` waits by default. */
218
+ readonly askGraceSecs?: number | undefined;
219
+ /** Starts the grace timer of a question; tests inject theirs. */
220
+ readonly askTimer?: AskTimer | undefined;
221
+ /** How the step's wall time is told; tests move it by hand. */
222
+ readonly timeoutClock?: TimeoutClock | undefined;
223
+ readonly cwd?: string | undefined;
224
+ readonly signal?: AbortSignal | undefined;
225
+ /** The store root; the run lock lives under `<root>/locks/runs`. */
226
+ readonly lockRoot?: string | undefined;
227
+ readonly object?: ObjectRef | undefined;
228
+ /** Fixed JSON the flow starts with; the runner writes it in the start fact. */
229
+ readonly params?: JsonValue | undefined;
230
+ /** The access profile the run starts with; recovery reads it from the log. */
231
+ readonly access?: JsonValue | undefined;
232
+ /** Treat an outstanding step as a crash and recover it first. */
233
+ readonly recover?: boolean | undefined;
234
+ /**
235
+ * Asked between steps, never during one. A reason means this process should
236
+ * stop and let a fresh one continue the run from the next step; the runner
237
+ * records the reason in the run's history and returns "handover".
238
+ */
239
+ readonly handover?: (() => Promise<string | undefined>) | undefined;
240
+ /** The event that started the run, read-only for its steps. */
241
+ readonly trigger?: TriggerView | undefined;
242
+ /** The start fact to use for an idle run, written by the start entry. */
243
+ readonly startInput?: StartInput | undefined;
244
+ /** Sends an event a step emitted, from the plugin that registered it. */
245
+ readonly emit?:
246
+ | ((plugin: string, event: StepEvent) => Promise<void>)
247
+ | undefined;
248
+ /** Called once when the run ends, before the log marks it ended. */
249
+ readonly onEnded?:
250
+ | ((runId: string, state: KernelState) => Promise<void>)
251
+ | undefined;
252
+ }
253
+
254
+ function resultsOf(registry: PluginRegistry, use: string): readonly string[] {
255
+ return registry.stepResults(use) ?? [];
256
+ }
257
+
258
+ function chooseFailure(
259
+ use: string,
260
+ registry: PluginRegistry,
261
+ preferInterrupted: boolean,
262
+ ): string {
263
+ // A check reports through the wait step, which accepts only "interrupted"
264
+ // as a failure; a plugin step uses the failure result it declares.
265
+ if (preferInterrupted) return "interrupted";
266
+ const results = resultsOf(registry, use);
267
+ if (results.includes("failed")) return "failed";
268
+ if (results.includes("interrupted")) return "interrupted";
269
+ // No declared failure result: name the failure anyway, so the kernel turns
270
+ // it into an interrupted step instead of advancing on a success result.
271
+ return "failed";
272
+ }
273
+
274
+ /**
275
+ * The plugin specifiers when every plugin has one, or undefined when a plugin
276
+ * was registered in memory and cannot be reloaded in a worker.
277
+ */
278
+ function allSources(
279
+ sources: readonly (string | undefined)[],
280
+ ): readonly string[] | undefined {
281
+ const resolved: string[] = [];
282
+ for (const source of sources) {
283
+ if (source === undefined) return undefined;
284
+ resolved.push(source);
285
+ }
286
+ return resolved;
287
+ }
288
+
289
+ export class Runner {
290
+ private readonly log: LogBackend;
291
+ private readonly flow: FlowDefinition;
292
+ private readonly registry: PluginRegistry;
293
+ private readonly clock: () => number;
294
+ private readonly timers: Clock;
295
+ private readonly stepTimeoutMs: number;
296
+ private readonly askGraceSecs: number | undefined;
297
+ private readonly askTimer: AskTimer | undefined;
298
+ private readonly timeoutClock: TimeoutClock;
299
+ /** The wall time of the step that is running now. */
300
+ private activeTimeout: StepTimeout | undefined;
301
+ private readonly cwd: string | undefined;
302
+ /** The caller's signal; while `run` drives the run it also fires when the run is ended elsewhere. */
303
+ private signal: AbortSignal | undefined;
304
+ private readonly lockRoot: string | undefined;
305
+ private readonly object: ObjectRef | undefined;
306
+ private readonly trigger: TriggerView | undefined;
307
+ private readonly startInput: StartInput | undefined;
308
+ private readonly params: JsonValue | undefined;
309
+ private readonly access: JsonValue | undefined;
310
+ private readonly emitEvent:
311
+ | ((plugin: string, event: StepEvent) => Promise<void>)
312
+ | undefined;
313
+ private readonly onEnded:
314
+ | ((runId: string, state: KernelState) => Promise<void>)
315
+ | undefined;
316
+ private readonly recover: boolean;
317
+ private readonly handover: (() => Promise<string | undefined>) | undefined;
318
+ readonly runId: string;
319
+
320
+ constructor(options: RunnerOptions) {
321
+ this.log = options.log;
322
+ this.flow = options.flow;
323
+ this.runId = options.runId;
324
+ this.registry = options.registry;
325
+ this.clock = options.clock ?? (() => Date.now());
326
+ this.timers = options.timers ?? systemClock;
327
+ this.stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS;
328
+ this.askGraceSecs = options.askGraceSecs;
329
+ this.askTimer = options.askTimer;
330
+ this.timeoutClock = options.timeoutClock ?? {
331
+ now: () => Date.now(),
332
+ set: (fire, ms) => this.timers.setTimeout(fire, ms),
333
+ clear: (handle) => this.timers.clearTimeout(handle),
334
+ };
335
+ this.cwd = options.cwd;
336
+ this.signal = options.signal;
337
+ this.lockRoot = options.lockRoot;
338
+ this.object = options.object;
339
+ this.trigger = options.trigger;
340
+ this.startInput = options.startInput;
341
+ this.emitEvent = options.emit;
342
+ this.onEnded = options.onEnded;
343
+ this.params = options.params;
344
+ this.access = options.access;
345
+ this.recover = options.recover === true;
346
+ this.handover = options.handover;
347
+ }
348
+
349
+ /**
350
+ * Takes the run's lock and drives it until it waits for a person, waits for
351
+ * a time or check, or ends. On a recovery start an outstanding step is fed
352
+ * to `recover` before anything else.
353
+ */
354
+ async run(): Promise<RunnerOutcome> {
355
+ let lock: LockHandle | undefined;
356
+ if (this.lockRoot !== undefined) {
357
+ lock = acquireLock(runLockPath(this.lockRoot, this.runId), {
358
+ clock: this.clock,
359
+ });
360
+ }
361
+ const given = this.signal;
362
+ const watch = this.watchForEnd();
363
+ this.signal = given === undefined ? watch.signal : AbortSignal.any([given, watch.signal]);
364
+ try {
365
+ let state = await readState(this.log, this.runId);
366
+ if (state.status === "ended") {
367
+ // Record the end event before ending the run: a crash in between leaves
368
+ // the run active, and the next pass records the same event again.
369
+ await this.onEnded?.(this.runId, state);
370
+ await this.log.endRun(this.runId);
371
+ return "ended";
372
+ }
373
+ let pendingRecovery = this.recover;
374
+
375
+ if (pendingRecovery) {
376
+ pendingRecovery = false;
377
+ if (
378
+ state.status === "running" &&
379
+ state.effect !== null &&
380
+ state.effects[state.effect.id] === "outstanding"
381
+ ) {
382
+ const result = await applyInput(
383
+ this.log,
384
+ this.flow,
385
+ this.runId,
386
+ state,
387
+ { kind: "recover" },
388
+ this.clock(),
389
+ "runner",
390
+ `recover:${state.lastSeq}`,
391
+ this.hooks(),
392
+ );
393
+ state = result.state;
394
+ }
395
+ }
396
+
397
+ if (state.status === "idle") {
398
+ const result = await this.startIdle(state);
399
+ state = result.state;
400
+ }
401
+
402
+ let outcome: RunnerOutcome = "progress";
403
+ while (outcome === "progress") {
404
+ outcome = await this.step(state);
405
+ if (outcome === "progress") {
406
+ state = await readState(this.log, this.runId);
407
+ if (state.status === "running" && (await this.handedOver(state))) {
408
+ return "handover";
409
+ }
410
+ }
411
+ }
412
+ return outcome;
413
+ } finally {
414
+ watch.stop();
415
+ this.signal = given;
416
+ lock?.release();
417
+ }
418
+ }
419
+
420
+ /**
421
+ * Fires the returned signal when another process ends the run (a cancel)
422
+ * while this one is inside a step, so the step stops what it started. The
423
+ * run's own end does the same, after the loop has nothing left to do.
424
+ */
425
+ private watchForEnd(): { readonly signal: AbortSignal; readonly stop: () => void } {
426
+ const controller = new AbortController();
427
+ const unsubscribe = this.log.subscribe?.((change) => {
428
+ if (change.runId !== this.runId || controller.signal.aborted) return;
429
+ void readState(this.log, this.runId).then(
430
+ (state) => {
431
+ if (state.status === "ended") controller.abort();
432
+ },
433
+ () => {
434
+ // The next change reads again.
435
+ },
436
+ );
437
+ });
438
+ return {
439
+ signal: controller.signal,
440
+ stop: () => {
441
+ unsubscribe?.();
442
+ },
443
+ };
444
+ }
445
+
446
+ /**
447
+ * True when the process should give the run to a fresh one: the caller named
448
+ * a reason, and the line saying so is in the run's history.
449
+ */
450
+ private async handedOver(state: KernelState): Promise<boolean> {
451
+ const reason = await this.handover?.();
452
+ if (reason === undefined) return false;
453
+ try {
454
+ await this.log.append(this.runId, state.lastSeq, [
455
+ { kind: "process_replaced", payload: { reason }, cause: state.lastSeq },
456
+ ]);
457
+ } catch (error) {
458
+ // Another writer moved the run on; the next step asks again.
459
+ if (error instanceof SeqConflictError) return false;
460
+ throw error;
461
+ }
462
+ return true;
463
+ }
464
+
465
+ /** Performs one unit of work for the run, or reports why it cannot. */
466
+ async step(stateInput?: KernelState): Promise<RunnerOutcome> {
467
+ let state = stateInput ?? (await readState(this.log, this.runId));
468
+ if (state.status === "ended") return "ended";
469
+ if (state.status === "waiting_person") return "waiting";
470
+ if (state.status === "idle") {
471
+ const result = await this.startIdle(state);
472
+ return result.duplicate ? "blocked" : "progress";
473
+ }
474
+
475
+ const effect = state.effect;
476
+ if (effect === null) return "blocked";
477
+
478
+ if (effect.kind === "schedule_wake") {
479
+ if (effect.due === null || this.clock() < effect.due) return "blocked";
480
+ const result = await applyInput(
481
+ this.log,
482
+ this.flow,
483
+ this.runId,
484
+ state,
485
+ { kind: "tick" },
486
+ this.clock(),
487
+ "runner",
488
+ `tick:${state.lastSeq}`,
489
+ this.hooks(),
490
+ );
491
+ return result.duplicate ? "blocked" : "progress";
492
+ }
493
+
494
+ if (effect.kind === "poll_check") {
495
+ if (effect.check === null) return "blocked";
496
+ const outcome = await this.execute(effect.check, effect.params, true, state.params, state.access);
497
+ if (outcome.result === "ready" || outcome.result === "interrupted") {
498
+ await this.recordResult(state, effect.id, outcome.result, outcome.data);
499
+ return "progress";
500
+ }
501
+ return "blocked";
502
+ }
503
+
504
+ if (effect.use === null) return "blocked";
505
+
506
+ // A step under a limit key takes its place before it is marked started: a
507
+ // crash while it waits is a step that never began, not a crashed step.
508
+ let limited = false;
509
+ let refusal: PluginStepResult | undefined;
510
+ try {
511
+ const limit = this.registry.stepLimit(effect.use, effect.params);
512
+ if (limit !== undefined) {
513
+ limited = true;
514
+ await this.limits().acquire(
515
+ {
516
+ runId: this.runId,
517
+ effectId: effect.id,
518
+ step: effect.step,
519
+ key: limit.key,
520
+ concurrent: limit.concurrent,
521
+ },
522
+ this.signal,
523
+ );
524
+ state = await readState(this.log, this.runId);
525
+ }
526
+ } catch (error) {
527
+ refusal = this.failure(effect.use, false, {
528
+ reason: this.signal?.aborted === true ? "aborted" : "error",
529
+ message:
530
+ this.signal?.aborted === true
531
+ ? "the step was cancelled"
532
+ : messageOf(error),
533
+ });
534
+ }
535
+
536
+ let outcome: PluginStepResult;
537
+ if (refusal !== undefined) {
538
+ outcome = refusal;
539
+ } else {
540
+ const recovering = state.effectStarted === effect.id;
541
+ if (!recovering) state = await this.markStarted(state, effect);
542
+ const nestedBase = recovering
543
+ ? await this.limits().resetNested(this.runId, effect.id)
544
+ : 0;
545
+ state = await readState(this.log, this.runId);
546
+ outcome = await this.execute(
547
+ effect.use,
548
+ effect.params,
549
+ false,
550
+ state.params,
551
+ accessWith(
552
+ state.access,
553
+ effect.grants,
554
+ await usedGrants(this.log, this.runId),
555
+ ),
556
+ this.limits().limiterFor(this.runId, effect.id, effect.step, nestedBase),
557
+ this.asks().asker(this.runId, effect.id, effect.step, effect.grants ?? []),
558
+ );
559
+ }
560
+ // The limit's own facts moved the run's last sequence on.
561
+ state = await readState(this.log, this.runId);
562
+ await this.recordResult(state, effect.id, outcome.result, outcome.data);
563
+ // The result frees the place; the next in line gets it now, or from the
564
+ // next pass of `serve` if this process dies first.
565
+ if (limited) await this.limits().grant();
566
+ return "progress";
567
+ }
568
+
569
+ private askHost: AskHost | undefined;
570
+
571
+ private asks(): AskHost {
572
+ this.askHost ??= new AskHost({
573
+ log: this.log,
574
+ graceSecs: this.askGraceSecs,
575
+ timer: this.askTimer,
576
+ pause: () => {
577
+ const timeout = this.activeTimeout;
578
+ timeout?.pause();
579
+ return () => timeout?.resume();
580
+ },
581
+ });
582
+ return this.askHost;
583
+ }
584
+
585
+ private stepLimits: StepLimits | undefined;
586
+
587
+ private limits(): StepLimits {
588
+ this.stepLimits ??= new StepLimits({
589
+ log: this.log,
590
+ lockRoot: this.lockRoot,
591
+ });
592
+ return this.stepLimits;
593
+ }
594
+
595
+ private hooks(): {
596
+ readonly beforeEnd: (runId: string, state: KernelState) => Promise<void>;
597
+ } {
598
+ return {
599
+ beforeEnd: async (runId, state) => {
600
+ await this.onEnded?.(runId, state);
601
+ },
602
+ };
603
+ }
604
+
605
+ /** Applies the run's start fact, using the start entry's metadata when present. */
606
+ private async startIdle(
607
+ state: KernelState,
608
+ ): Promise<{ readonly state: KernelState; readonly duplicate: boolean }> {
609
+ const meta = this.startInput;
610
+ const provided = meta?.access ?? this.access;
611
+ const access =
612
+ provided ?? (meta === undefined ? await this.initialAccess() : undefined);
613
+ this.registry.checkAccess(this.flow.name, access);
614
+ if (meta !== undefined && meta.inputId !== undefined) {
615
+ const start: Input =
616
+ access === undefined || meta.access !== undefined
617
+ ? meta
618
+ : { ...meta, access };
619
+ const result = await appendInput(
620
+ this.log,
621
+ this.flow,
622
+ this.runId,
623
+ state,
624
+ start,
625
+ this.clock(),
626
+ );
627
+ if (result.state.status === "ended") {
628
+ await this.onEnded?.(this.runId, result.state);
629
+ await this.log.endRun(this.runId);
630
+ }
631
+ return { state: result.state, duplicate: false };
632
+ }
633
+ const input: Input =
634
+ meta === undefined
635
+ ? {
636
+ kind: "start",
637
+ ...(this.params === undefined ? {} : { params: this.params }),
638
+ ...(access === undefined ? {} : { access }),
639
+ }
640
+ : {
641
+ kind: "start",
642
+ ...(meta.params === undefined ? {} : { params: meta.params }),
643
+ ...(meta.hops === undefined ? {} : { hops: meta.hops }),
644
+ ...(meta.trigger === undefined ? {} : { trigger: meta.trigger }),
645
+ ...(access === undefined ? {} : { access }),
646
+ };
647
+ const result = await applyInput(
648
+ this.log,
649
+ this.flow,
650
+ this.runId,
651
+ state,
652
+ input,
653
+ this.clock(),
654
+ "runner",
655
+ "start",
656
+ this.hooks(),
657
+ );
658
+ return { state: result.state, duplicate: result.duplicate };
659
+ }
660
+
661
+ /**
662
+ * Records that this process began the step. `serve` reads it to tell a
663
+ * crashed step from a fresh one, and the fact names the process that ran it.
664
+ */
665
+ private async markStarted(
666
+ state: KernelState,
667
+ effect: NonNullable<KernelState["effect"]>,
668
+ ): Promise<KernelState> {
669
+ await this.log.append(this.runId, state.lastSeq, [
670
+ {
671
+ kind: "step_started",
672
+ payload: { step: effect.step, effectId: effect.id, pid: process.pid },
673
+ cause: state.lastSeq,
674
+ },
675
+ ]);
676
+ return readState(this.log, this.runId);
677
+ }
678
+
679
+ private async recordResult(
680
+ state: KernelState,
681
+ effectId: string,
682
+ result: string,
683
+ data: object | undefined,
684
+ ): Promise<void> {
685
+ const input: Input =
686
+ data === undefined
687
+ ? { kind: "step_result", effectId, result }
688
+ : {
689
+ kind: "step_result",
690
+ effectId,
691
+ result,
692
+ data: data as unknown as JsonValue,
693
+ };
694
+ try {
695
+ await applyInput(
696
+ this.log,
697
+ this.flow,
698
+ this.runId,
699
+ state,
700
+ input,
701
+ this.clock(),
702
+ "runner",
703
+ `result:${effectId}`,
704
+ this.hooks(),
705
+ );
706
+ } catch (error) {
707
+ // The run was cancelled while the step ran; its result has nowhere to go.
708
+ if (error instanceof RunEndedError) return;
709
+ throw error;
710
+ }
711
+ }
712
+
713
+ /** Read afresh: the signal may fire during an await. */
714
+ private signalAborted(): boolean {
715
+ return this.signal?.aborted === true;
716
+ }
717
+
718
+ /**
719
+ * Runs a plugin step with a wall-time limit and the cancel signal. A step
720
+ * that throws or overruns becomes a declared failure result; the data says
721
+ * which in words the history view can print.
722
+ *
723
+ * A step whose plugin came from a file runs in a worker thread, so the wall
724
+ * time also bounds a step that never yields to the event loop. A registry
725
+ * built in memory has no file to reload, so its steps stay in this process.
726
+ */
727
+ private async execute(
728
+ use: string,
729
+ params: unknown,
730
+ preferInterrupted: boolean,
731
+ flowParams: JsonValue,
732
+ access: JsonValue,
733
+ limiter?: StepLimiter | undefined,
734
+ asker?: StepAsker | undefined,
735
+ ): Promise<PluginStepResult> {
736
+ if (this.signal?.aborted === true) {
737
+ return this.failure(use, preferInterrupted, {
738
+ reason: "aborted",
739
+ message: "the step was cancelled",
740
+ });
741
+ }
742
+
743
+ const object = await this.runObject();
744
+ // A cancel that came while the object was read must not start the step.
745
+ if (this.signalAborted()) {
746
+ return this.failure(use, preferInterrupted, {
747
+ reason: "aborted",
748
+ message: "the step was cancelled",
749
+ });
750
+ }
751
+ const sources =
752
+ this.registry.store.kind === "file"
753
+ ? allSources(this.registry.pluginSources())
754
+ : undefined;
755
+ if (sources !== undefined) {
756
+ return this.executeInWorker(
757
+ use,
758
+ params,
759
+ object,
760
+ sources,
761
+ preferInterrupted,
762
+ flowParams,
763
+ access,
764
+ limiter,
765
+ asker,
766
+ );
767
+ }
768
+ return this.executeHere(
769
+ use,
770
+ params,
771
+ object,
772
+ preferInterrupted,
773
+ flowParams,
774
+ access,
775
+ limiter,
776
+ asker,
777
+ );
778
+ }
779
+
780
+ private startInputFor(access: JsonValue | undefined): Input {
781
+ return {
782
+ kind: "start",
783
+ ...(this.params === undefined ? {} : { params: this.params }),
784
+ ...(access === undefined ? {} : { access }),
785
+ };
786
+ }
787
+
788
+ /** The profile given to the runner, or the one the log recorded at start. */
789
+ private async initialAccess(): Promise<JsonValue | undefined> {
790
+ if (this.access !== undefined) return this.access;
791
+ const runs = await this.log.runs();
792
+ return runs.find((run) => run.runId === this.runId)?.access;
793
+ }
794
+
795
+ /** The step type's own `timeoutSecs`, or the runner's step timeout. */
796
+ private timeoutMsFor(use: string): number {
797
+ const declared = this.registry
798
+ .stepTypes()
799
+ .find((type) => type.name === use)?.timeoutSecs;
800
+ return declared === undefined ? this.stepTimeoutMs : declared * 1000;
801
+ }
802
+
803
+ private async runObject(): Promise<RunObject | undefined> {
804
+ if (this.object === undefined) return undefined;
805
+ const stored = await this.registry.store.get(
806
+ this.object.type,
807
+ this.object.id,
808
+ );
809
+ return {
810
+ type: this.object.type,
811
+ id: this.object.id,
812
+ data: stored?.data ?? {},
813
+ };
814
+ }
815
+
816
+ private executeInWorker(
817
+ use: string,
818
+ params: unknown,
819
+ object: RunObject | undefined,
820
+ sources: readonly string[],
821
+ preferInterrupted: boolean,
822
+ flowParams: JsonValue,
823
+ access: JsonValue,
824
+ limiter: StepLimiter | undefined,
825
+ asker: StepAsker | undefined,
826
+ ): Promise<PluginStepResult> {
827
+ return new Promise((resolve) => {
828
+ const questions = new Map<number, AbortController>();
829
+ // Waits for a place that the worker's nested steps asked for, by the id
830
+ // the worker gave the request; a finished worker stops them all.
831
+ const waits = new Map<number, AbortController>();
832
+ const held = new Map<number, () => Promise<void>>();
833
+ const worker = new Worker(STEP_WORKER, {
834
+ workerData: {
835
+ sources,
836
+ home: this.registry.home,
837
+ cwd: this.cwd ?? this.registry.workdir,
838
+ storeRoot: this.registry.store.root,
839
+ ...(this.registry.store.location === undefined
840
+ ? {}
841
+ : { store: this.registry.store.location }),
842
+ use,
843
+ params,
844
+ flowParams,
845
+ access,
846
+ settings: this.registry.pluginSettings(),
847
+ ...(this.trigger === undefined ? {} : { trigger: this.trigger }),
848
+ runId: this.runId,
849
+ ...(object === undefined ? {} : { object }),
850
+ },
851
+ });
852
+
853
+ let settled = false;
854
+ let timer: StepTimeout | undefined;
855
+ let stopTimer: ReturnType<typeof setTimeout> | undefined;
856
+ const finish = (result: PluginStepResult, terminate = true): void => {
857
+ if (settled) return;
858
+ settled = true;
859
+ for (const wait of waits.values()) wait.abort();
860
+ for (const question of questions.values()) question.abort();
861
+ timer?.clear();
862
+ if (this.activeTimeout === timer) this.activeTimeout = undefined;
863
+ this.signal?.removeEventListener("abort", onAbort);
864
+ if (terminate) {
865
+ void worker.terminate();
866
+ resolve(result);
867
+ } else {
868
+ // Give the step a moment to stop the processes it started; the
869
+ // worker is killed anyway when it does not answer in time. The run
870
+ // waits for that cleanup so it never leaves a process behind.
871
+ stopTimer = setTimeout(() => {
872
+ void worker.terminate();
873
+ }, WORKER_ABORT_GRACE_MS);
874
+ worker.once("exit", () => {
875
+ if (stopTimer !== undefined) clearTimeout(stopTimer);
876
+ resolve(result);
877
+ });
878
+ }
879
+ };
880
+ const abortWorker = (): void => {
881
+ try {
882
+ worker.postMessage("abort");
883
+ } catch {
884
+ // The worker ended between the abort and this message.
885
+ }
886
+ };
887
+ const onAbort = (): void => {
888
+ abortWorker();
889
+ finish(
890
+ this.failure(use, preferInterrupted, {
891
+ reason: "aborted",
892
+ message: "the step was cancelled",
893
+ }),
894
+ false,
895
+ );
896
+ };
897
+
898
+ timer = new StepTimeout(
899
+ this.timeoutMsFor(use),
900
+ () => {
901
+ abortWorker();
902
+ finish(
903
+ this.failure(use, preferInterrupted, {
904
+ reason: "timeout",
905
+ message: `the step took longer than ${this.timeoutMsFor(use)} ms`,
906
+ }),
907
+ false,
908
+ );
909
+ },
910
+ this.timeoutClock,
911
+ );
912
+ this.activeTimeout = timer;
913
+ this.signal?.addEventListener("abort", onAbort, { once: true });
914
+
915
+ worker.on("message", (message: unknown) => {
916
+ if (settled) {
917
+ // The step answered after an abort: it has stopped what it started.
918
+ void worker.terminate();
919
+ return;
920
+ }
921
+ if (isStepWorkerLimit(message)) {
922
+ void this.serveLimit(message, limiter, worker, waits, held);
923
+ return;
924
+ }
925
+ if (isStepWorkerAsk(message)) {
926
+ void this.serveAsk(message, asker, worker, questions);
927
+ return;
928
+ }
929
+ if (isStepWorkerEmit(message)) {
930
+ void (async () => {
931
+ try {
932
+ if (this.emitEvent === undefined) {
933
+ throw new Error("no event destination is configured");
934
+ }
935
+ await this.emitEvent(message.plugin, message.event);
936
+ worker.postMessage({ kind: "emit-result", id: message.id, ok: true });
937
+ } catch (error) {
938
+ worker.postMessage({
939
+ kind: "emit-result",
940
+ id: message.id,
941
+ ok: false,
942
+ error: messageOf(error),
943
+ });
944
+ }
945
+ })();
946
+ return;
947
+ }
948
+ if (isStepWorkerReply(message) && message.ok && message.result) {
949
+ finish(message.result);
950
+ return;
951
+ }
952
+ finish(
953
+ this.failure(use, preferInterrupted, {
954
+ reason: "error",
955
+ message:
956
+ isStepWorkerReply(message) && message.error !== undefined
957
+ ? message.error
958
+ : "the step failed",
959
+ }),
960
+ );
961
+ });
962
+ worker.once("error", (error) => {
963
+ finish(
964
+ this.failure(use, preferInterrupted, {
965
+ reason: "error",
966
+ message: messageOf(error),
967
+ }),
968
+ );
969
+ });
970
+ worker.once("exit", () => {
971
+ if (stopTimer !== undefined) clearTimeout(stopTimer);
972
+ finish(
973
+ this.failure(use, preferInterrupted, {
974
+ reason: "error",
975
+ message: "the step ended without a result",
976
+ }),
977
+ );
978
+ });
979
+ });
980
+ }
981
+
982
+ private async serveAsk(
983
+ message: StepWorkerAsk,
984
+ asker: StepAsker | undefined,
985
+ worker: Worker,
986
+ questions: Map<number, AbortController>,
987
+ ): Promise<void> {
988
+ if (message.kind === "ask-cancel") {
989
+ questions.get(message.id)?.abort();
990
+ return;
991
+ }
992
+ if (message.kind === "grant") {
993
+ try {
994
+ if (asker === undefined) throw new Error("no one takes grants here");
995
+ const used = await asker.useGrant(message.waitId);
996
+ worker.postMessage({ kind: "grant-result", id: message.id, ok: true, used });
997
+ } catch (error) {
998
+ try {
999
+ worker.postMessage({
1000
+ kind: "grant-result",
1001
+ id: message.id,
1002
+ ok: false,
1003
+ error: messageOf(error),
1004
+ });
1005
+ } catch {
1006
+ // The worker is gone.
1007
+ }
1008
+ }
1009
+ return;
1010
+ }
1011
+ const reply = (body: Record<string, unknown>): void => {
1012
+ try {
1013
+ worker.postMessage({ kind: "ask-result", id: message.id, ...body });
1014
+ } catch {
1015
+ // The worker is gone; nobody waits for the answer.
1016
+ }
1017
+ };
1018
+ if (asker === undefined) {
1019
+ reply({ ok: false, error: "no one takes questions here" });
1020
+ return;
1021
+ }
1022
+ const wait = new AbortController();
1023
+ questions.set(message.id, wait);
1024
+ try {
1025
+ const outcome = await asker.ask(message.request, wait.signal);
1026
+ reply({ ok: true, outcome });
1027
+ } catch (error) {
1028
+ reply({ ok: false, error: messageOf(error) });
1029
+ } finally {
1030
+ questions.delete(message.id);
1031
+ }
1032
+ }
1033
+
1034
+ private async serveLimit(
1035
+ message: StepWorkerLimit,
1036
+ limiter: StepLimiter | undefined,
1037
+ worker: Worker,
1038
+ waits: Map<number, AbortController>,
1039
+ held: Map<number, () => Promise<void>>,
1040
+ ): Promise<void> {
1041
+ const reply = (ok: boolean, error?: string): void => {
1042
+ try {
1043
+ worker.postMessage({
1044
+ kind: "limit-result",
1045
+ id: message.id,
1046
+ ok,
1047
+ ...(error === undefined ? {} : { error }),
1048
+ });
1049
+ } catch {
1050
+ // The worker is gone; nobody waits for the answer.
1051
+ }
1052
+ };
1053
+ if (message.kind === "limit-cancel") {
1054
+ waits.get(message.id)?.abort();
1055
+ return;
1056
+ }
1057
+ if (message.kind === "limit-release") {
1058
+ const release = held.get(message.id);
1059
+ held.delete(message.id);
1060
+ try {
1061
+ await release?.();
1062
+ reply(true);
1063
+ } catch (error) {
1064
+ reply(false, messageOf(error));
1065
+ }
1066
+ return;
1067
+ }
1068
+ if (limiter === undefined) {
1069
+ reply(false, "no limiter is configured");
1070
+ return;
1071
+ }
1072
+ const wait = new AbortController();
1073
+ waits.set(message.id, wait);
1074
+ try {
1075
+ if (message.report === true) {
1076
+ held.set(message.id, await limiter.report({
1077
+ key: message.key,
1078
+ ...(message.ahead === undefined ? {} : { ahead: message.ahead }),
1079
+ }));
1080
+ reply(true);
1081
+ return;
1082
+ }
1083
+ const release = await limiter.acquire({
1084
+ use: message.use,
1085
+ key: message.key,
1086
+ concurrent: message.concurrent,
1087
+ signal: wait.signal,
1088
+ });
1089
+ held.set(message.id, release);
1090
+ reply(true);
1091
+ } catch (error) {
1092
+ reply(false, messageOf(error));
1093
+ } finally {
1094
+ waits.delete(message.id);
1095
+ }
1096
+ }
1097
+
1098
+ private async executeHere(
1099
+ use: string,
1100
+ params: unknown,
1101
+ object: RunObject | undefined,
1102
+ preferInterrupted: boolean,
1103
+ flowParams: JsonValue,
1104
+ access: JsonValue,
1105
+ limiter: StepLimiter | undefined,
1106
+ asker: StepAsker | undefined,
1107
+ ): Promise<PluginStepResult> {
1108
+ const controller = new AbortController();
1109
+ const forward = (): void => controller.abort();
1110
+ this.signal?.addEventListener("abort", forward, { once: true });
1111
+
1112
+ let timer: StepTimeout | undefined;
1113
+ const timeout = new Promise<"timeout">((resolve) => {
1114
+ timer = new StepTimeout(
1115
+ this.timeoutMsFor(use),
1116
+ () => {
1117
+ controller.abort();
1118
+ resolve("timeout");
1119
+ },
1120
+ this.timeoutClock,
1121
+ );
1122
+ });
1123
+ this.activeTimeout = timer;
1124
+
1125
+ const step = this.registry.runStep(use, params, {
1126
+ runId: this.runId,
1127
+ ...(this.cwd === undefined ? {} : { cwd: this.cwd }),
1128
+ ...(object === undefined ? {} : { object }),
1129
+ params: flowParams,
1130
+ access,
1131
+ ...(this.trigger === undefined ? {} : { trigger: this.trigger }),
1132
+ ...(this.emitEvent === undefined ? {} : { emit: this.emitEvent }),
1133
+ signal: controller.signal,
1134
+ ...(limiter === undefined ? {} : { limits: limiter }),
1135
+ ...(asker === undefined ? {} : { asker }),
1136
+ });
1137
+ // After a timeout the plugin may still reject; that rejection is no
1138
+ // longer interesting, and must not crash the process.
1139
+ step.catch(() => undefined);
1140
+
1141
+ try {
1142
+ const raced = await Promise.race([
1143
+ step.then((value) => ({ kind: "result" as const, value })),
1144
+ timeout.then(() => ({ kind: "timeout" as const })),
1145
+ ]);
1146
+ if (raced.kind === "timeout") {
1147
+ return this.failure(use, preferInterrupted, {
1148
+ reason: "timeout",
1149
+ message: `the step took longer than ${this.timeoutMsFor(use)} ms`,
1150
+ });
1151
+ }
1152
+ return raced.value;
1153
+ } catch (error) {
1154
+ return this.failure(use, preferInterrupted, {
1155
+ reason: "error",
1156
+ message: messageOf(error),
1157
+ });
1158
+ } finally {
1159
+ timer?.clear();
1160
+ if (this.activeTimeout === timer) this.activeTimeout = undefined;
1161
+ this.signal?.removeEventListener("abort", forward);
1162
+ }
1163
+ }
1164
+
1165
+ private failure(
1166
+ use: string,
1167
+ preferInterrupted: boolean,
1168
+ data: { readonly reason: string; readonly message: string },
1169
+ ): PluginStepResult {
1170
+ return {
1171
+ result: chooseFailure(use, this.registry, preferInterrupted),
1172
+ data,
1173
+ };
1174
+ }
1175
+ }