@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,689 @@
1
+ import { END, type FlowDefinition, type Step } from "../flow/types.ts";
2
+ import type { FactCause, JsonValue } from "../log/types.ts";
3
+ import { MAX_TRIGGER_HOPS } from "../trigger/types.ts";
4
+ import type {
5
+ Decision,
6
+ Effect,
7
+ EffectRequestedPayload,
8
+ FactKind,
9
+ Grant,
10
+ Input,
11
+ KernelFact,
12
+ KernelState,
13
+ PendingEffect,
14
+ RunStartedPayload,
15
+ StepInterruptedPayload,
16
+ } from "./types.ts";
17
+ import { inputCause } from "./types.ts";
18
+
19
+ /** The default number of times a run may enter the same step. */
20
+ export const DEFAULT_MAX_VISITS = 10;
21
+
22
+ /** How many recoveries without a result stop the run and ask a person. */
23
+ export const CRASH_LOOP_LIMIT = 3;
24
+
25
+ const CRASH_PROMPT = "This step keeps crashing. Retry it or cancel the run?";
26
+ const CRASH_CHOICES = ["retry", "cancel"];
27
+
28
+ function findStep(flow: FlowDefinition, id: string): Step | undefined {
29
+ const found = flow.steps.find((step) => step.id === id);
30
+ return found === undefined ? undefined : (found as Step);
31
+ }
32
+
33
+ function edgesOf(step: Step): Readonly<Record<string, string>> {
34
+ return step.kind === "end" ? {} : step.next;
35
+ }
36
+
37
+ /** The result names the step may produce. */
38
+ /** The `message` a step's data carries, as a field to spread into a payload. */
39
+ function messageField(data: JsonValue | undefined): { readonly message?: string } {
40
+ if (typeof data !== "object" || data === null || Array.isArray(data)) return {};
41
+ const message = (data as { readonly message?: unknown }).message;
42
+ return typeof message === "string" && message.length > 0 ? { message } : {};
43
+ }
44
+
45
+ function declaredResults(step: Step): readonly string[] {
46
+ switch (step.kind) {
47
+ case "end":
48
+ return [];
49
+ case "wait":
50
+ return ["ready", "interrupted"];
51
+ case "wait_person":
52
+ return [...step.params.choices, "interrupted"];
53
+ case "plugin":
54
+ return Object.keys(step.next);
55
+ }
56
+ }
57
+
58
+ /** A question a step asked and could not wait for; the flow wait carries it on. */
59
+ interface AskedVia {
60
+ readonly waitId: string;
61
+ readonly prompt: string;
62
+ readonly choices: readonly string[];
63
+ readonly resume: JsonValue;
64
+ }
65
+
66
+ /** A question the person answered, on the way back to the step that asked. */
67
+ interface AnsweredAsk {
68
+ readonly waitId: string;
69
+ readonly step: string;
70
+ readonly prompt: string;
71
+ readonly resume: JsonValue;
72
+ readonly choice: string;
73
+ readonly note: string | null;
74
+ }
75
+
76
+ type EnterVia = {
77
+ readonly step: string;
78
+ readonly result: string;
79
+ readonly named?: string;
80
+ readonly ask?: AskedVia;
81
+ readonly answered?: AnsweredAsk;
82
+ };
83
+
84
+ function isPlainRecord(value: unknown): value is Record<string, JsonValue> {
85
+ return typeof value === "object" && value !== null && !Array.isArray(value);
86
+ }
87
+
88
+ /**
89
+ * The params the step runs again with after its question was answered: the
90
+ * params it had, the session it left, and the answer. Anything the step did
91
+ * not leave is simply absent.
92
+ */
93
+ function resumedParams(base: JsonValue, answered: AnsweredAsk): JsonValue {
94
+ const resume = answered.resume;
95
+ const session =
96
+ typeof resume === "string"
97
+ ? resume
98
+ : isPlainRecord(resume) && typeof resume.session === "string"
99
+ ? resume.session
100
+ : undefined;
101
+ return {
102
+ ...(isPlainRecord(base) ? base : {}),
103
+ ...(session === undefined ? {} : { resumeSession: session }),
104
+ askAnswer: {
105
+ prompt: answered.prompt,
106
+ choice: answered.choice,
107
+ ...(answered.note === null ? {} : { note: answered.note }),
108
+ },
109
+ };
110
+ }
111
+
112
+ /** The one-time permission the call the step asked about gets, if it named one. */
113
+ function grantsFrom(answered: AnsweredAsk): readonly Grant[] | undefined {
114
+ const resume = answered.resume;
115
+ if (!isPlainRecord(resume)) return undefined;
116
+ const grant = resume.grant;
117
+ if (
118
+ !isPlainRecord(grant) ||
119
+ (grant.kind !== "command" && grant.kind !== "path") ||
120
+ typeof grant.value !== "string" ||
121
+ grant.value.length === 0
122
+ ) {
123
+ return undefined;
124
+ }
125
+ // Only a choice that approves gives the permission: the one the step named,
126
+ // every choice in its `choices` list, or "approve" when it named none
127
+ // (`ctx.ask` refuses a question with choices that names none).
128
+ const approves = new Set<string>();
129
+ if (typeof grant.choice === "string") approves.add(grant.choice);
130
+ if (Array.isArray(grant.choices)) {
131
+ for (const choice of grant.choices) {
132
+ if (typeof choice === "string") approves.add(choice);
133
+ }
134
+ }
135
+ if (approves.size === 0) approves.add("approve");
136
+ if (!approves.has(answered.choice)) return undefined;
137
+ return [
138
+ {
139
+ waitId: answered.waitId,
140
+ kind: grant.kind,
141
+ value: grant.value,
142
+ ...(typeof grant.tool === "string" ? { tool: grant.tool } : {}),
143
+ },
144
+ ];
145
+ }
146
+
147
+ /** The question in the data of a `waiting` result, when it is well formed. */
148
+ function askedIn(result: string, data: unknown): AskedVia | undefined {
149
+ if (result !== "waiting") return undefined;
150
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
151
+ return undefined;
152
+ }
153
+ const record = data as Record<string, unknown>;
154
+ if (typeof record.waitId !== "string" || record.waitId.length === 0) {
155
+ return undefined;
156
+ }
157
+ if (typeof record.prompt !== "string") return undefined;
158
+ const choices = Array.isArray(record.choices)
159
+ ? record.choices.filter((item): item is string => typeof item === "string")
160
+ : [];
161
+ return {
162
+ waitId: record.waitId,
163
+ prompt: record.prompt,
164
+ choices,
165
+ resume: (record.resume ?? null) as JsonValue,
166
+ };
167
+ }
168
+
169
+ /** The step a result names, when its data came from a step that stopped. */
170
+ function stepNameOf(data: unknown): string | undefined {
171
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
172
+ return undefined;
173
+ }
174
+ const step = (data as Record<string, unknown>).step;
175
+ return typeof step === "string" && step.length > 0 ? step : undefined;
176
+ }
177
+
178
+ /**
179
+ * The prompt a person sees. A wait reached by an interrupted result appends
180
+ * the wait's note, with `{step}` naming the step that stopped.
181
+ */
182
+ function waitPrompt(
183
+ params: { readonly prompt: string; readonly note?: string | undefined },
184
+ via: EnterVia | undefined,
185
+ ): string {
186
+ if (via?.result !== "interrupted" || params.note === undefined) {
187
+ return params.prompt;
188
+ }
189
+ const named = via.named ?? via.step;
190
+ return `${params.prompt}\n\n${params.note.replaceAll("{step}", named)}`;
191
+ }
192
+
193
+ function effectRequestedPayload(effect: PendingEffect, recovery: boolean): EffectRequestedPayload {
194
+ return {
195
+ ...(effect.grants === undefined ? {} : { grants: effect.grants }),
196
+ effectId: effect.id,
197
+ effect: effect.kind,
198
+ step: effect.step,
199
+ replay: effect.replay,
200
+ recovery,
201
+ use: effect.use,
202
+ params: effect.params,
203
+ check: effect.check,
204
+ due: effect.due,
205
+ };
206
+ }
207
+
208
+ function describeEffect(effect: PendingEffect): Effect {
209
+ switch (effect.kind) {
210
+ case "run_plugin_step":
211
+ return {
212
+ kind: "run_plugin_step",
213
+ effectId: effect.id,
214
+ step: effect.step,
215
+ use: effect.use ?? "",
216
+ params: effect.params,
217
+ replay: effect.replay,
218
+ };
219
+ case "schedule_wake":
220
+ return {
221
+ kind: "schedule_wake",
222
+ effectId: effect.id,
223
+ step: effect.step,
224
+ due: effect.due ?? 0,
225
+ };
226
+ case "poll_check":
227
+ return {
228
+ kind: "poll_check",
229
+ effectId: effect.id,
230
+ step: effect.step,
231
+ check: effect.check ?? "",
232
+ params: effect.params,
233
+ };
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Turn one input into facts and effect descriptions. No I/O, no clock: `now`
239
+ * is the caller's time, and the log's sequence numbers start at
240
+ * `state.lastSeq + 1`.
241
+ */
242
+ export function decide(
243
+ flow: FlowDefinition,
244
+ state: KernelState,
245
+ input: Input,
246
+ now: number,
247
+ ): Decision {
248
+ const facts: KernelFact[] = [];
249
+ const effects: Effect[] = [];
250
+ const base = state.lastSeq;
251
+ const maxVisits = flow.maxVisits ?? DEFAULT_MAX_VISITS;
252
+ const cause = inputCause(input);
253
+
254
+ function push(kind: FactKind, payload: object, causedBy: FactCause): number {
255
+ facts.push({ kind, payload: payload as unknown as JsonValue, cause: causedBy });
256
+ return base + facts.length;
257
+ }
258
+
259
+ function endRun(status: "done" | "failed" | "cancelled", reason: string | null, causedBy: FactCause): void {
260
+ if (state.hops + 1 > MAX_TRIGGER_HOPS) {
261
+ push(
262
+ "trigger_skipped",
263
+ {
264
+ source: "operad",
265
+ type: `run.${status}`,
266
+ key: "",
267
+ hops: state.hops + 1,
268
+ reason: `the chain is ${state.hops + 1} hops deep; at most ${MAX_TRIGGER_HOPS} are followed`,
269
+ },
270
+ causedBy,
271
+ );
272
+ }
273
+ push("run_ended", { status, reason }, causedBy);
274
+ }
275
+
276
+ function enter(
277
+ stepId: string,
278
+ causedBy: FactCause,
279
+ via?: EnterVia,
280
+ ): void {
281
+ const step = findStep(flow, stepId);
282
+ if (step === undefined) {
283
+ endRun("failed", `unknown step ${stepId}`, causedBy);
284
+ return;
285
+ }
286
+
287
+ const visit = (state.visits[stepId] ?? 0) + 1;
288
+ if (visit > maxVisits) {
289
+ const limitSeq = push(
290
+ "visit_limit_reached",
291
+ { step: stepId, visits: visit, limit: maxVisits },
292
+ causedBy,
293
+ );
294
+ endRun("failed", "visit_limit", limitSeq);
295
+ return;
296
+ }
297
+
298
+ const enteredSeq = push(
299
+ "step_entered",
300
+ { step: stepId, visit, kind: step.kind },
301
+ causedBy,
302
+ );
303
+
304
+ switch (step.kind) {
305
+ case "end": {
306
+ endRun(step.params.status, null, enteredSeq);
307
+ return;
308
+ }
309
+ case "plugin": {
310
+ const effectId = `${step.id}:${visit}`;
311
+ // The step that asked, back after the answer: it continues the same
312
+ // session with the answer and, for the call it asked about, a grant.
313
+ // The answer waits in the state, so it reaches the step whatever path
314
+ // the flow took from the wait back to it.
315
+ const answered =
316
+ via?.answered?.step === step.id
317
+ ? via.answered
318
+ : state.answeredAsk?.step === step.id
319
+ ? state.answeredAsk
320
+ : undefined;
321
+ const grants = answered === undefined ? undefined : grantsFrom(answered);
322
+ const effect: PendingEffect = {
323
+ id: effectId,
324
+ kind: "run_plugin_step",
325
+ step: step.id,
326
+ use: step.params.use,
327
+ params:
328
+ answered === undefined
329
+ ? (step.params.params as unknown as JsonValue)
330
+ : resumedParams(step.params.params as unknown as JsonValue, answered),
331
+ check: null,
332
+ due: null,
333
+ replay: step.replay,
334
+ ...(grants === undefined ? {} : { grants }),
335
+ };
336
+ push("effect_requested", effectRequestedPayload(effect, false), enteredSeq);
337
+ effects.push(describeEffect(effect));
338
+ return;
339
+ }
340
+ case "wait_person": {
341
+ // A step that asked and ran out of grace hands its question over: the
342
+ // wait keeps the question's id, so nobody sees it twice.
343
+ const asked = via?.ask;
344
+ const waitId = asked?.waitId ?? `${step.id}:${visit}`;
345
+ const own = [...step.params.choices];
346
+ const allowed = new Set([...own, ...(step.params.lateChoices ?? [])]);
347
+ const choices =
348
+ asked !== undefined &&
349
+ asked.choices.length > 0 &&
350
+ asked.choices.every((choice) => allowed.has(choice))
351
+ ? [...asked.choices]
352
+ : own;
353
+ const prompt = asked?.prompt ?? waitPrompt(step.params, via);
354
+ push(
355
+ "waiting_for_person",
356
+ {
357
+ waitId,
358
+ step: step.id,
359
+ prompt,
360
+ choices,
361
+ waitKind: "step",
362
+ effectId: null,
363
+ ...(asked === undefined || via === undefined
364
+ ? {}
365
+ : { ask: { step: via.step, resume: asked.resume } }),
366
+ },
367
+ enteredSeq,
368
+ );
369
+ effects.push({
370
+ kind: "notify_pending",
371
+ waitId,
372
+ step: step.id,
373
+ prompt,
374
+ choices,
375
+ waitKind: "step",
376
+ });
377
+ return;
378
+ }
379
+ case "wait": {
380
+ const effectId = `${step.id}:${visit}`;
381
+ if ("afterSecs" in step.params) {
382
+ const due = now + step.params.afterSecs * 1000;
383
+ const effect: PendingEffect = {
384
+ id: effectId,
385
+ kind: "schedule_wake",
386
+ step: step.id,
387
+ use: null,
388
+ params: null,
389
+ check: null,
390
+ due,
391
+ replay: step.replay,
392
+ };
393
+ push("effect_requested", effectRequestedPayload(effect, false), enteredSeq);
394
+ effects.push(describeEffect(effect));
395
+ } else {
396
+ const checkParams = step.params.params;
397
+ const effect: PendingEffect = {
398
+ id: effectId,
399
+ kind: "poll_check",
400
+ step: step.id,
401
+ use: null,
402
+ params:
403
+ checkParams === undefined
404
+ ? null
405
+ : (checkParams as unknown as JsonValue),
406
+ check: step.params.check,
407
+ due: null,
408
+ replay: step.replay,
409
+ };
410
+ push("effect_requested", effectRequestedPayload(effect, false), enteredSeq);
411
+ effects.push(describeEffect(effect));
412
+ }
413
+ return;
414
+ }
415
+ }
416
+ }
417
+
418
+ function takeEdge(
419
+ step: Step,
420
+ result: string,
421
+ causedBy: FactCause,
422
+ named?: string,
423
+ ask?: AskedVia,
424
+ answered?: AnsweredAsk,
425
+ ): void {
426
+ const target = edgesOf(step)[result];
427
+ if (target === undefined) {
428
+ endRun("failed", `no edge for result ${result}`, causedBy);
429
+ return;
430
+ }
431
+ const edgeSeq = push("edge_taken", { step: step.id, result, target }, causedBy);
432
+ if (target === END) {
433
+ endRun("done", null, edgeSeq);
434
+ return;
435
+ }
436
+ enter(target, edgeSeq, {
437
+ step: step.id,
438
+ result,
439
+ ...(named === undefined ? {} : { named }),
440
+ ...(ask === undefined ? {} : { ask }),
441
+ ...(answered === undefined ? {} : { answered }),
442
+ });
443
+ }
444
+
445
+ function requestAgain(effect: PendingEffect, causedBy: FactCause, recovery: boolean): void {
446
+ push("effect_requested", effectRequestedPayload(effect, recovery), causedBy);
447
+ effects.push(describeEffect(effect));
448
+ }
449
+
450
+ function stopForCrashLoop(effect: PendingEffect, recoveries: number, causedBy: FactCause): void {
451
+ const stoppedSeq = push(
452
+ "crash_loop_stopped",
453
+ { step: effect.step, effectId: effect.id, recoveries },
454
+ causedBy,
455
+ );
456
+ const waitId = `crash:${effect.id}`;
457
+ const choices = [...CRASH_CHOICES];
458
+ push(
459
+ "waiting_for_person",
460
+ {
461
+ waitId,
462
+ step: effect.step,
463
+ prompt: CRASH_PROMPT,
464
+ choices,
465
+ waitKind: "crash_loop",
466
+ effectId: effect.id,
467
+ },
468
+ stoppedSeq,
469
+ );
470
+ effects.push({
471
+ kind: "notify_pending",
472
+ waitId,
473
+ step: effect.step,
474
+ prompt: CRASH_PROMPT,
475
+ choices,
476
+ waitKind: "crash_loop",
477
+ });
478
+ }
479
+
480
+ switch (input.kind) {
481
+ case "start": {
482
+ if (state.started || state.status !== "idle") return { facts, effects };
483
+ const payload: RunStartedPayload = {
484
+ flow: flow.name,
485
+ ...(input.params === undefined ? {} : { params: input.params }),
486
+ ...(input.access === undefined ? {} : { access: input.access }),
487
+ ...(input.hops === undefined ? {} : { hops: input.hops }),
488
+ ...(input.trigger === undefined ? {} : { trigger: input.trigger }),
489
+ };
490
+ const startedSeq = push("run_started", payload, cause);
491
+ enter(flow.entry, startedSeq);
492
+ return { facts, effects };
493
+ }
494
+
495
+ case "step_result": {
496
+ if (!state.started || state.status === "ended" || state.status === "idle") {
497
+ return { facts, effects };
498
+ }
499
+ const effect = state.effect;
500
+ if (
501
+ effect === null ||
502
+ effect.id !== input.effectId ||
503
+ state.effects[input.effectId] !== "outstanding" ||
504
+ state.step !== effect.step
505
+ ) {
506
+ return { facts, effects };
507
+ }
508
+ const step = findStep(flow, effect.step);
509
+ if (step === undefined) return { facts, effects };
510
+
511
+ if (!declaredResults(step).includes(input.result)) {
512
+ const payload: StepInterruptedPayload = {
513
+ step: effect.step,
514
+ effectId: effect.id,
515
+ reason: "undeclared_result",
516
+ result: input.result,
517
+ ...messageField(input.data),
518
+ };
519
+ const interruptedSeq = push("step_interrupted", { ...payload }, cause);
520
+ takeEdge(step, "interrupted", interruptedSeq);
521
+ return { facts, effects };
522
+ }
523
+
524
+ const resultSeq = push(
525
+ "step_result",
526
+ {
527
+ effectId: effect.id,
528
+ step: effect.step,
529
+ result: input.result,
530
+ data: input.data ?? null,
531
+ },
532
+ cause,
533
+ );
534
+ takeEdge(
535
+ step,
536
+ input.result,
537
+ resultSeq,
538
+ stepNameOf(input.data),
539
+ askedIn(input.result, input.data),
540
+ );
541
+ return { facts, effects };
542
+ }
543
+
544
+ case "person_answer": {
545
+ const wait = state.wait;
546
+ if (
547
+ state.status !== "waiting_person" ||
548
+ wait === null ||
549
+ wait.id !== input.waitId ||
550
+ !wait.choices.includes(input.choice)
551
+ ) {
552
+ return { facts, effects };
553
+ }
554
+ const answerSeq = push(
555
+ "person_answered",
556
+ {
557
+ waitId: wait.id,
558
+ step: wait.step,
559
+ choice: input.choice,
560
+ note: input.note ?? null,
561
+ waitKind: wait.kind,
562
+ actor: { via: input.actor.via, id: input.actor.id },
563
+ ...(wait.ask === undefined
564
+ ? {}
565
+ : {
566
+ ask: {
567
+ step: wait.ask.step,
568
+ prompt: wait.prompt,
569
+ resume: wait.ask.resume,
570
+ },
571
+ }),
572
+ },
573
+ cause,
574
+ );
575
+
576
+ if (wait.kind === "crash_loop") {
577
+ if (input.choice === "cancel") {
578
+ endRun("cancelled", null, answerSeq);
579
+ return { facts, effects };
580
+ }
581
+ if (state.effect !== null) requestAgain(state.effect, answerSeq, false);
582
+ return { facts, effects };
583
+ }
584
+
585
+ const step = findStep(flow, wait.step);
586
+ if (step === undefined) {
587
+ endRun("failed", `unknown step ${wait.step}`, answerSeq);
588
+ return { facts, effects };
589
+ }
590
+ takeEdge(
591
+ step,
592
+ input.choice,
593
+ answerSeq,
594
+ undefined,
595
+ undefined,
596
+ wait.ask === undefined
597
+ ? undefined
598
+ : {
599
+ waitId: wait.id,
600
+ step: wait.ask.step,
601
+ prompt: wait.prompt,
602
+ resume: wait.ask.resume,
603
+ choice: input.choice,
604
+ note: input.note ?? null,
605
+ },
606
+ );
607
+ return { facts, effects };
608
+ }
609
+
610
+ case "tick": {
611
+ if (!state.started || state.status === "ended" || state.status === "waiting_person") {
612
+ return { facts, effects };
613
+ }
614
+ const effect = state.effect;
615
+ if (effect === null || effect.kind !== "schedule_wake" || effect.due === null) {
616
+ return { facts, effects };
617
+ }
618
+ if (now < effect.due) return { facts, effects };
619
+
620
+ const step = findStep(flow, effect.step);
621
+ if (step === undefined) return { facts, effects };
622
+ const readySeq = push(
623
+ "step_result",
624
+ {
625
+ effectId: effect.id,
626
+ step: effect.step,
627
+ result: "ready",
628
+ data: { at: now },
629
+ },
630
+ cause,
631
+ );
632
+ takeEdge(step, "ready", readySeq);
633
+ return { facts, effects };
634
+ }
635
+
636
+ case "recover": {
637
+ if (
638
+ !state.started ||
639
+ state.status === "idle" ||
640
+ state.status === "ended" ||
641
+ state.status === "waiting_person"
642
+ ) {
643
+ return { facts, effects };
644
+ }
645
+ const effect = state.effect;
646
+ if (
647
+ effect === null ||
648
+ state.effects[effect.id] !== "outstanding" ||
649
+ state.step !== effect.step
650
+ ) {
651
+ return { facts, effects };
652
+ }
653
+ const step = findStep(flow, effect.step);
654
+ if (step === undefined) return { facts, effects };
655
+
656
+ const recoveries = (state.recoveries[effect.id] ?? 0) + 1;
657
+ if (recoveries >= CRASH_LOOP_LIMIT) {
658
+ stopForCrashLoop(effect, recoveries, cause);
659
+ return { facts, effects };
660
+ }
661
+
662
+ if (step.replay === "safe") {
663
+ requestAgain(effect, cause, true);
664
+ return { facts, effects };
665
+ }
666
+
667
+ const interruptedSeq = push(
668
+ "step_interrupted",
669
+ {
670
+ step: effect.step,
671
+ effectId: effect.id,
672
+ reason: "recover_unsafe",
673
+ result: null,
674
+ },
675
+ cause,
676
+ );
677
+ takeEdge(step, "interrupted", interruptedSeq);
678
+ return { facts, effects };
679
+ }
680
+
681
+ case "cancel": {
682
+ if (!state.started || state.status === "idle" || state.status === "ended") {
683
+ return { facts, effects };
684
+ }
685
+ endRun("cancelled", "cancel", cause);
686
+ return { facts, effects };
687
+ }
688
+ }
689
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./types.ts";
2
+ export { DEFAULT_MAX_VISITS, CRASH_LOOP_LIMIT, decide } from "./decide.ts";
3
+ export { evolve, initialState, replay } from "./state.ts";