@voyant-travel/workflows 0.107.10

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 (120) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +52 -0
  3. package/README.md +79 -0
  4. package/dist/auth/index.d.ts +125 -0
  5. package/dist/auth/index.d.ts.map +1 -0
  6. package/dist/auth/index.js +352 -0
  7. package/dist/bindings.d.ts +119 -0
  8. package/dist/bindings.d.ts.map +1 -0
  9. package/dist/bindings.js +19 -0
  10. package/dist/client.d.ts +135 -0
  11. package/dist/client.d.ts.map +1 -0
  12. package/dist/client.js +305 -0
  13. package/dist/conditions.d.ts +29 -0
  14. package/dist/conditions.d.ts.map +1 -0
  15. package/dist/conditions.js +5 -0
  16. package/dist/config.d.ts +93 -0
  17. package/dist/config.d.ts.map +1 -0
  18. package/dist/config.js +7 -0
  19. package/dist/driver.d.ts +237 -0
  20. package/dist/driver.d.ts.map +1 -0
  21. package/dist/driver.js +53 -0
  22. package/dist/errors.d.ts +58 -0
  23. package/dist/errors.d.ts.map +1 -0
  24. package/dist/errors.js +76 -0
  25. package/dist/events/compile.d.ts +34 -0
  26. package/dist/events/compile.d.ts.map +1 -0
  27. package/dist/events/compile.js +204 -0
  28. package/dist/events/index.d.ts +8 -0
  29. package/dist/events/index.d.ts.map +1 -0
  30. package/dist/events/index.js +11 -0
  31. package/dist/events/input-mapper.d.ts +24 -0
  32. package/dist/events/input-mapper.d.ts.map +1 -0
  33. package/dist/events/input-mapper.js +169 -0
  34. package/dist/events/manifest-builder.d.ts +42 -0
  35. package/dist/events/manifest-builder.d.ts.map +1 -0
  36. package/dist/events/manifest-builder.js +313 -0
  37. package/dist/events/payload-hash.d.ts +46 -0
  38. package/dist/events/payload-hash.d.ts.map +1 -0
  39. package/dist/events/payload-hash.js +98 -0
  40. package/dist/events/predicate.d.ts +77 -0
  41. package/dist/events/predicate.d.ts.map +1 -0
  42. package/dist/events/predicate.js +347 -0
  43. package/dist/events/registry.d.ts +37 -0
  44. package/dist/events/registry.d.ts.map +1 -0
  45. package/dist/events/registry.js +47 -0
  46. package/dist/handler/index.d.ts +114 -0
  47. package/dist/handler/index.d.ts.map +1 -0
  48. package/dist/handler/index.js +267 -0
  49. package/dist/handler/resume.d.ts +41 -0
  50. package/dist/handler/resume.d.ts.map +1 -0
  51. package/dist/handler/resume.js +44 -0
  52. package/dist/http-ingest.d.ts +54 -0
  53. package/dist/http-ingest.d.ts.map +1 -0
  54. package/dist/http-ingest.js +214 -0
  55. package/dist/index.d.ts +6 -0
  56. package/dist/index.d.ts.map +1 -0
  57. package/dist/index.js +10 -0
  58. package/dist/protocol/index.d.ts +345 -0
  59. package/dist/protocol/index.d.ts.map +1 -0
  60. package/dist/protocol/index.js +110 -0
  61. package/dist/rate-limit/index.d.ts +40 -0
  62. package/dist/rate-limit/index.d.ts.map +1 -0
  63. package/dist/rate-limit/index.js +139 -0
  64. package/dist/runtime/ctx.d.ts +111 -0
  65. package/dist/runtime/ctx.d.ts.map +1 -0
  66. package/dist/runtime/ctx.js +624 -0
  67. package/dist/runtime/determinism.d.ts +19 -0
  68. package/dist/runtime/determinism.d.ts.map +1 -0
  69. package/dist/runtime/determinism.js +61 -0
  70. package/dist/runtime/errors.d.ts +21 -0
  71. package/dist/runtime/errors.d.ts.map +1 -0
  72. package/dist/runtime/errors.js +45 -0
  73. package/dist/runtime/executor.d.ts +166 -0
  74. package/dist/runtime/executor.d.ts.map +1 -0
  75. package/dist/runtime/executor.js +226 -0
  76. package/dist/runtime/journal.d.ts +56 -0
  77. package/dist/runtime/journal.d.ts.map +1 -0
  78. package/dist/runtime/journal.js +28 -0
  79. package/dist/testing/index.d.ts +117 -0
  80. package/dist/testing/index.d.ts.map +1 -0
  81. package/dist/testing/index.js +599 -0
  82. package/dist/trigger.d.ts +37 -0
  83. package/dist/trigger.d.ts.map +1 -0
  84. package/dist/trigger.js +11 -0
  85. package/dist/types.d.ts +63 -0
  86. package/dist/types.d.ts.map +1 -0
  87. package/dist/types.js +3 -0
  88. package/dist/workflow.d.ts +222 -0
  89. package/dist/workflow.d.ts.map +1 -0
  90. package/dist/workflow.js +55 -0
  91. package/package.json +120 -0
  92. package/src/auth/index.ts +398 -0
  93. package/src/bindings.ts +135 -0
  94. package/src/client.ts +498 -0
  95. package/src/conditions.ts +43 -0
  96. package/src/config.ts +114 -0
  97. package/src/driver.ts +277 -0
  98. package/src/errors.ts +109 -0
  99. package/src/events/compile.ts +268 -0
  100. package/src/events/index.ts +42 -0
  101. package/src/events/input-mapper.ts +201 -0
  102. package/src/events/manifest-builder.ts +372 -0
  103. package/src/events/payload-hash.ts +110 -0
  104. package/src/events/predicate.ts +390 -0
  105. package/src/events/registry.ts +86 -0
  106. package/src/handler/index.ts +413 -0
  107. package/src/handler/resume.ts +100 -0
  108. package/src/http-ingest.ts +299 -0
  109. package/src/index.ts +18 -0
  110. package/src/protocol/index.ts +483 -0
  111. package/src/rate-limit/index.ts +181 -0
  112. package/src/runtime/ctx.ts +876 -0
  113. package/src/runtime/determinism.ts +75 -0
  114. package/src/runtime/errors.ts +58 -0
  115. package/src/runtime/executor.ts +442 -0
  116. package/src/runtime/journal.ts +80 -0
  117. package/src/testing/index.ts +796 -0
  118. package/src/trigger.ts +63 -0
  119. package/src/types.ts +80 -0
  120. package/src/workflow.ts +328 -0
@@ -0,0 +1,61 @@
1
+ // Deterministic clock and RNG used by the workflow body.
2
+ //
3
+ // `ctx.now()` must return the timestamp of the event currently being
4
+ // consumed from the journal during replay (§4.5 of docs/design.md).
5
+ // `ctx.random()` / `ctx.randomUUID()` are seeded from the run id so
6
+ // replays produce the same values.
7
+ export function createClock(runStartedAt) {
8
+ return { baseWallClock: runStartedAt, offset: 0 };
9
+ }
10
+ export function now(clock) {
11
+ return clock.baseWallClock + clock.offset;
12
+ }
13
+ /** Advance the clock to the event currently being replayed. */
14
+ export function advanceClockTo(clock, eventAt) {
15
+ clock.offset = eventAt - clock.baseWallClock;
16
+ }
17
+ /**
18
+ * Mulberry32 PRNG — fast, fine for workflow-determinism use. Seeded
19
+ * from a 32-bit hash of the run id. Not cryptographic.
20
+ */
21
+ export function seededRandom(seed) {
22
+ let state = seed >>> 0;
23
+ return () => {
24
+ state = (state + 0x6d2b79f5) >>> 0;
25
+ let t = state;
26
+ t = Math.imul(t ^ (t >>> 15), t | 1);
27
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
28
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
29
+ };
30
+ }
31
+ export function hashSeed(runId) {
32
+ // FNV-1a 32-bit
33
+ let hash = 0x811c9dc5;
34
+ for (let i = 0; i < runId.length; i++) {
35
+ hash ^= runId.charCodeAt(i);
36
+ hash = Math.imul(hash, 0x01000193);
37
+ }
38
+ return hash >>> 0;
39
+ }
40
+ export function createRandom(runId) {
41
+ return seededRandom(hashSeed(runId));
42
+ }
43
+ const HEX = "0123456789abcdef";
44
+ export function createRandomUUID(rng) {
45
+ // v4-shaped deterministic UUID. Not cryptographically random; matches
46
+ // the style of crypto.randomUUID but is reproducible across replays.
47
+ return () => {
48
+ const bytes = new Uint8Array(16);
49
+ for (let i = 0; i < 16; i++)
50
+ bytes[i] = Math.floor(rng() * 256);
51
+ bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4 (high nibble of byte 6)
52
+ bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant RFC 4122 (high bits of byte 8)
53
+ let s = "";
54
+ for (let i = 0; i < 16; i++) {
55
+ const b = bytes[i];
56
+ s += HEX[b >>> 4] + HEX[b & 0x0f];
57
+ }
58
+ // s is 32 hex chars; slice into 8-4-4-4-12 groups.
59
+ return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20, 32)}`;
60
+ };
61
+ }
@@ -0,0 +1,21 @@
1
+ declare const WAITPOINT_PENDING: unique symbol;
2
+ declare const RUN_CANCELLED: unique symbol;
3
+ declare const COMPENSATE_REQUESTED: unique symbol;
4
+ export declare class WaitpointPendingSignal extends Error {
5
+ readonly [WAITPOINT_PENDING]: true;
6
+ readonly waitpointId: string;
7
+ constructor(waitpointId: string);
8
+ }
9
+ export declare class RunCancelledSignal extends Error {
10
+ readonly [RUN_CANCELLED]: true;
11
+ constructor(reason?: string);
12
+ }
13
+ export declare function isWaitpointPending(err: unknown): err is WaitpointPendingSignal;
14
+ export declare function isRunCancelled(err: unknown): err is RunCancelledSignal;
15
+ export declare class CompensateRequestedSignal extends Error {
16
+ readonly [COMPENSATE_REQUESTED]: true;
17
+ constructor();
18
+ }
19
+ export declare function isCompensateRequested(err: unknown): err is CompensateRequestedSignal;
20
+ export {};
21
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/runtime/errors.ts"],"names":[],"mappings":"AAKA,QAAA,MAAM,iBAAiB,eAAkD,CAAA;AACzE,QAAA,MAAM,aAAa,eAA8C,CAAA;AACjE,QAAA,MAAM,oBAAoB,eAAqD,CAAA;AAE/E,qBAAa,sBAAuB,SAAQ,KAAK;IAC/C,QAAQ,CAAC,CAAC,iBAAiB,CAAC,EAAG,IAAI,CAAS;IAC5C,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;gBAChB,WAAW,EAAE,MAAM;CAKhC;AAED,qBAAa,kBAAmB,SAAQ,KAAK;IAC3C,QAAQ,CAAC,CAAC,aAAa,CAAC,EAAG,IAAI,CAAS;gBAC5B,MAAM,CAAC,EAAE,MAAM;CAI5B;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,sBAAsB,CAM9E;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,kBAAkB,CAMtE;AAED,qBAAa,yBAA0B,SAAQ,KAAK;IAClD,QAAQ,CAAC,CAAC,oBAAoB,CAAC,EAAG,IAAI,CAAS;;CAKhD;AAED,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,yBAAyB,CAMpF"}
@@ -0,0 +1,45 @@
1
+ // Internal runtime signal errors. Distinct from user-facing `@voyant-travel/workflows/errors`:
2
+ // these are thrown inside the executor to unwind the workflow body on
3
+ // waitpoint yield or run cancellation. They must not be caught by user
4
+ // code (the executor re-throws if it observes one being swallowed).
5
+ const WAITPOINT_PENDING = Symbol.for("voyant.workflows.waitpointPending");
6
+ const RUN_CANCELLED = Symbol.for("voyant.workflows.runCancelled");
7
+ const COMPENSATE_REQUESTED = Symbol.for("voyant.workflows.compensateRequested");
8
+ export class WaitpointPendingSignal extends Error {
9
+ [WAITPOINT_PENDING] = true;
10
+ waitpointId;
11
+ constructor(waitpointId) {
12
+ super(`waitpoint pending: ${waitpointId}`);
13
+ this.name = "WaitpointPendingSignal";
14
+ this.waitpointId = waitpointId;
15
+ }
16
+ }
17
+ export class RunCancelledSignal extends Error {
18
+ [RUN_CANCELLED] = true;
19
+ constructor(reason) {
20
+ super(reason ?? "run cancelled");
21
+ this.name = "RunCancelledSignal";
22
+ }
23
+ }
24
+ export function isWaitpointPending(err) {
25
+ return (typeof err === "object" &&
26
+ err !== null &&
27
+ err[WAITPOINT_PENDING] === true);
28
+ }
29
+ export function isRunCancelled(err) {
30
+ return (typeof err === "object" &&
31
+ err !== null &&
32
+ err[RUN_CANCELLED] === true);
33
+ }
34
+ export class CompensateRequestedSignal extends Error {
35
+ [COMPENSATE_REQUESTED] = true;
36
+ constructor() {
37
+ super("compensate requested");
38
+ this.name = "CompensateRequestedSignal";
39
+ }
40
+ }
41
+ export function isCompensateRequested(err) {
42
+ return (typeof err === "object" &&
43
+ err !== null &&
44
+ err[COMPENSATE_REQUESTED] === true);
45
+ }
@@ -0,0 +1,166 @@
1
+ import type { SerializedError } from "../protocol/index.js";
2
+ import { type RateLimiter } from "../rate-limit/index.js";
3
+ import type { RunStatus, RunTrigger, WaitpointKind } from "../types.js";
4
+ import type { WorkflowDefinition } from "../workflow.js";
5
+ import { type RuntimeEnvironment } from "./ctx.js";
6
+ import { RunCancelledSignal, WaitpointPendingSignal } from "./errors.js";
7
+ import type { JournalSlice, StepJournalEntry } from "./journal.js";
8
+ export type StepRunner = (
9
+ /**
10
+ * Executes a step body and returns the journal entry to record.
11
+ *
12
+ * In-process runners (the default edge runner, local-dev passthrough)
13
+ * call `fn(stepCtx)` directly. Dispatching runners (e.g. the CF
14
+ * Container runner) ignore `fn` — they can't serialize a closure —
15
+ * and use the run/workflow identity + step options to address the
16
+ * remote container and POST the required context.
17
+ */
18
+ args: {
19
+ stepId: string;
20
+ attempt: number;
21
+ input: unknown;
22
+ fn: (stepCtx: import("../workflow.js").StepContext) => Promise<unknown>;
23
+ stepCtx: import("../workflow.js").StepContext;
24
+ /** Identity of the run — used by dispatching runners. */
25
+ runId: string;
26
+ workflowId: string;
27
+ workflowVersion: string;
28
+ /** Project / organization id from the runtime environment — used by
29
+ * dispatching runners to resolve per-tenant bundle storage keys. */
30
+ projectId: string;
31
+ organizationId: string;
32
+ /** Merged step options (runtime, machine, timeout, …). */
33
+ options: import("../workflow.js").StepOptions<unknown>;
34
+ /**
35
+ * Current journal slice at dispatch time — steps already completed,
36
+ * waitpoints already resolved, etc. Dispatching runners pass this
37
+ * to the remote executor so body replay there short-circuits on
38
+ * cached steps, and the container can stop cleanly after the
39
+ * target step runs.
40
+ */
41
+ journal: JournalSlice;
42
+ }) => Promise<StepJournalEntry>;
43
+ export interface WaitpointRegistration {
44
+ clientWaitpointId: string;
45
+ kind: WaitpointKind;
46
+ meta: Record<string, unknown>;
47
+ timeoutMs?: number;
48
+ }
49
+ export interface MetadataMutation {
50
+ op: "set" | "increment" | "append" | "remove";
51
+ key: string;
52
+ value?: unknown;
53
+ target?: "self" | "parent" | "root";
54
+ }
55
+ export interface CompensationReport {
56
+ stepId: string;
57
+ status: "ok" | "err";
58
+ error?: SerializedError;
59
+ durationMs: number;
60
+ }
61
+ export interface StreamChunk {
62
+ streamId: string;
63
+ seq: number;
64
+ encoding: "text" | "json" | "base64";
65
+ chunk: unknown;
66
+ final: boolean;
67
+ at: number;
68
+ }
69
+ export interface ExecuteWorkflowStepRequest {
70
+ runId: string;
71
+ workflowId: string;
72
+ workflowVersion: string;
73
+ input: unknown;
74
+ journal: JournalSlice;
75
+ invocationCount: number;
76
+ environment: RuntimeEnvironment;
77
+ triggeredBy: RunTrigger;
78
+ runStartedAt: number;
79
+ tags: string[];
80
+ abortSignal?: AbortSignal;
81
+ /**
82
+ * Default step executor (the "edge" runtime) — runs step bodies
83
+ * in-process. Used for any step whose `options.runtime` is unset or
84
+ * explicitly `"edge"`.
85
+ */
86
+ stepRunner: StepRunner;
87
+ /**
88
+ * Optional runner for steps declared with `options.runtime === "node"`.
89
+ * Typical impl dispatches to a Cloudflare Container sized for the
90
+ * step (or, in local dev, an in-process passthrough).
91
+ *
92
+ * If a step requests `"node"` and this is unset, the step fails with
93
+ * `NODE_RUNTIME_UNAVAILABLE` — declaring a runtime and then silently
94
+ * falling back to edge would hide deployment bugs.
95
+ */
96
+ nodeStepRunner?: StepRunner;
97
+ /**
98
+ * Optional rate limiter. When a step declares `options.rateLimit`,
99
+ * the executor calls `rateLimiter.acquire(...)` before invoking the
100
+ * step runner. Without a limiter, a step that declares `rateLimit`
101
+ * fails with `RATE_LIMITER_MISSING` — declaring a limit and not
102
+ * enforcing it would be silently dangerous.
103
+ */
104
+ rateLimiter?: RateLimiter;
105
+ /** `() => number` used for compensation durations. Defaults to Date.now. */
106
+ now?: () => number;
107
+ /**
108
+ * Optional per-chunk callback fired synchronously from
109
+ * `ctx.stream.*` as each chunk is produced. Enables live streaming
110
+ * (dashboards, queues) in-process before the invocation completes.
111
+ * Chunks are still accumulated in the response's `streamChunks`
112
+ * array so the at-end delivery keeps working.
113
+ */
114
+ onStreamChunk?: (chunk: StreamChunk) => void;
115
+ /**
116
+ * Optional read-only service resolver, surfaced to the workflow body as
117
+ * `ctx.services`. Wired by the framework through
118
+ * `StepHandlerDeps.services` → here. When unset, `ctx.services.resolve(...)`
119
+ * throws with a clear message — see `runtime/ctx.ts`.
120
+ */
121
+ services?: import("../driver.js").ServiceResolver;
122
+ }
123
+ export type ExecuteWorkflowStepResponse = {
124
+ status: "completed";
125
+ output: unknown;
126
+ metadataUpdates: MetadataMutation[];
127
+ journal: JournalSlice;
128
+ streamChunks: StreamChunk[];
129
+ } | {
130
+ status: "failed";
131
+ error: SerializedError;
132
+ metadataUpdates: MetadataMutation[];
133
+ journal: JournalSlice;
134
+ streamChunks: StreamChunk[];
135
+ } | {
136
+ status: "cancelled";
137
+ metadataUpdates: MetadataMutation[];
138
+ journal: JournalSlice;
139
+ compensations: CompensationReport[];
140
+ streamChunks: StreamChunk[];
141
+ } | {
142
+ status: "waiting";
143
+ waitpoints: WaitpointRegistration[];
144
+ metadataUpdates: MetadataMutation[];
145
+ journal: JournalSlice;
146
+ streamChunks: StreamChunk[];
147
+ } | {
148
+ status: "compensated";
149
+ /** Only set when compensation was triggered by an uncaught body error. */
150
+ error?: SerializedError;
151
+ compensations: CompensationReport[];
152
+ metadataUpdates: MetadataMutation[];
153
+ journal: JournalSlice;
154
+ streamChunks: StreamChunk[];
155
+ } | {
156
+ status: "compensation_failed";
157
+ error?: SerializedError;
158
+ compensations: CompensationReport[];
159
+ metadataUpdates: MetadataMutation[];
160
+ journal: JournalSlice;
161
+ streamChunks: StreamChunk[];
162
+ };
163
+ export declare function executeWorkflowStep(def: WorkflowDefinition, req: ExecuteWorkflowStepRequest): Promise<ExecuteWorkflowStepResponse>;
164
+ export type { RunStatus };
165
+ export { RunCancelledSignal, WaitpointPendingSignal };
166
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../src/runtime/executor.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA;AAC3D,OAAO,EAAgB,KAAK,WAAW,EAAE,MAAM,wBAA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,OAAO,EAAE,YAAY,CAAA;IACrB,YAAY,EAAE,WAAW,EAAE,CAAA;CAC5B,CAAA;AAQL,wBAAsB,mBAAmB,CACvC,GAAG,EAAE,kBAAkB,EACvB,GAAG,EAAE,0BAA0B,GAC9B,OAAO,CAAC,2BAA2B,CAAC,CAqKtC;AA4ED,YAAY,EAAE,SAAS,EAAE,CAAA;AACzB,OAAO,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,CAAA"}
@@ -0,0 +1,226 @@
1
+ // The workflow-step executor. Takes a registered workflow + journal and
2
+ // runs the body exactly once, yielding a response envelope.
3
+ //
4
+ // Corresponds to the tenant-side handler of POST /__voyant/workflow-step
5
+ // described in docs/runtime-protocol.md §2.1.
6
+ import { durationToMs } from "../rate-limit/index.js";
7
+ import { buildCtx } from "./ctx.js";
8
+ import { createClock, createRandom } from "./determinism.js";
9
+ import { isCompensateRequested, isRunCancelled, isWaitpointPending, RunCancelledSignal, WaitpointPendingSignal, } from "./errors.js";
10
+ export async function executeWorkflowStep(def, req) {
11
+ const abortSignal = req.abortSignal ?? new AbortController().signal;
12
+ const now = req.now ?? (() => Date.now());
13
+ const clock = createClock(req.runStartedAt);
14
+ const random = createRandom(req.runId);
15
+ const waitpoints = [];
16
+ const metadataUpdates = [];
17
+ const compensable = [];
18
+ const streamChunks = [];
19
+ const retryOverride = {
20
+ current: def.config.retry,
21
+ };
22
+ const callbacks = {
23
+ invocationCount: req.invocationCount,
24
+ abortSignal,
25
+ async runStep(args) {
26
+ if (args.options.rateLimit) {
27
+ await acquireRateLimit({
28
+ spec: args.options.rateLimit,
29
+ stepId: args.stepId,
30
+ input: req.input,
31
+ runId: req.runId,
32
+ projectId: req.environment.project.id,
33
+ limiter: req.rateLimiter,
34
+ signal: abortSignal,
35
+ });
36
+ }
37
+ const runtime = args.options.runtime ?? "edge";
38
+ const runner = runtime === "node" ? req.nodeStepRunner : req.stepRunner;
39
+ if (!runner) {
40
+ const e = new Error(`step "${args.stepId}" declared runtime="node" but the handler has no nodeStepRunner wired; ` +
41
+ `pass { nodeStepRunner } to createStepHandler() or remove options.runtime`);
42
+ e.code = "NODE_RUNTIME_UNAVAILABLE";
43
+ throw e;
44
+ }
45
+ const entry = await runner({
46
+ stepId: args.stepId,
47
+ attempt: args.attempt,
48
+ input: args.input,
49
+ fn: args.fn,
50
+ stepCtx: args.stepCtx,
51
+ runId: req.runId,
52
+ workflowId: req.workflowId,
53
+ workflowVersion: req.workflowVersion,
54
+ projectId: req.environment.project.id,
55
+ organizationId: req.environment.organization.id,
56
+ options: args.options,
57
+ journal: req.journal,
58
+ });
59
+ // Stamp the runtime on the journal entry so downstream consumers
60
+ // (journal persistence, dashboard events) can report where each
61
+ // step actually ran.
62
+ entry.runtime = runtime;
63
+ return entry;
64
+ },
65
+ registerWaitpoint(args) {
66
+ waitpoints.push(args);
67
+ },
68
+ pushMetadata(op) {
69
+ metadataUpdates.push(op);
70
+ },
71
+ recordCompensable(args) {
72
+ compensable.push(args);
73
+ },
74
+ compensableLength() {
75
+ return compensable.length;
76
+ },
77
+ spliceCompensable(fromIndex) {
78
+ return compensable.splice(fromIndex);
79
+ },
80
+ pushStreamChunk(args) {
81
+ const chunk = { ...args, at: now() };
82
+ streamChunks.push(chunk);
83
+ // Fire the live hook synchronously. Errors are swallowed — a
84
+ // misbehaving subscriber must not break the workflow body.
85
+ if (req.onStreamChunk) {
86
+ try {
87
+ req.onStreamChunk(chunk);
88
+ }
89
+ catch {
90
+ /* ignore */
91
+ }
92
+ }
93
+ },
94
+ };
95
+ const ctx = buildCtx({
96
+ env: req.environment,
97
+ journal: req.journal,
98
+ callbacks,
99
+ clock,
100
+ random,
101
+ retryOverride,
102
+ services: req.services,
103
+ });
104
+ try {
105
+ const output = await def.config.run(req.input, ctx);
106
+ // If the body registered a waitpoint but a user try/catch swallowed
107
+ // the internal yield signal, honour the waitpoint — the body can't
108
+ // both register a waitpoint and complete in the same invocation.
109
+ if (waitpoints.length > 0) {
110
+ return { status: "waiting", waitpoints, metadataUpdates, journal: req.journal, streamChunks };
111
+ }
112
+ return { status: "completed", output, metadataUpdates, journal: req.journal, streamChunks };
113
+ }
114
+ catch (err) {
115
+ if (isWaitpointPending(err)) {
116
+ return { status: "waiting", waitpoints, metadataUpdates, journal: req.journal, streamChunks };
117
+ }
118
+ // Same guard for the error path: a swallowed signal shouldn't let
119
+ // the body claim failure while waitpoints are pending.
120
+ if (waitpoints.length > 0 && !isRunCancelled(err) && !isCompensateRequested(err)) {
121
+ return { status: "waiting", waitpoints, metadataUpdates, journal: req.journal, streamChunks };
122
+ }
123
+ if (isRunCancelled(err)) {
124
+ // Default: compensate on cancel. Terminal status stays `cancelled`
125
+ // to reflect why the run ended.
126
+ const compensations = await runCompensations(compensable, now);
127
+ return {
128
+ status: "cancelled",
129
+ metadataUpdates,
130
+ journal: req.journal,
131
+ compensations,
132
+ streamChunks,
133
+ };
134
+ }
135
+ if (isCompensateRequested(err)) {
136
+ const compensations = await runCompensations(compensable, now);
137
+ const anyErr = compensations.some((c) => c.status === "err");
138
+ return {
139
+ status: anyErr ? "compensation_failed" : "compensated",
140
+ compensations,
141
+ metadataUpdates,
142
+ journal: req.journal,
143
+ streamChunks,
144
+ };
145
+ }
146
+ // Uncaught user error. Run compensations LIFO; adjust terminal status
147
+ // based on whether compensations were registered and all succeeded.
148
+ const compensations = await runCompensations(compensable, now);
149
+ const serialized = serializeError(err);
150
+ if (compensations.length === 0) {
151
+ return {
152
+ status: "failed",
153
+ error: serialized,
154
+ metadataUpdates,
155
+ journal: req.journal,
156
+ streamChunks,
157
+ };
158
+ }
159
+ const anyErr = compensations.some((c) => c.status === "err");
160
+ return {
161
+ status: anyErr ? "compensation_failed" : "compensated",
162
+ error: serialized,
163
+ compensations,
164
+ metadataUpdates,
165
+ journal: req.journal,
166
+ streamChunks,
167
+ };
168
+ }
169
+ }
170
+ async function runCompensations(compensable, now) {
171
+ const reports = [];
172
+ // Reverse order: last-completed compensates first.
173
+ for (let i = compensable.length - 1; i >= 0; i--) {
174
+ const c = compensable[i];
175
+ const startedAt = now();
176
+ try {
177
+ await c.compensate(c.output);
178
+ reports.push({ stepId: c.stepId, status: "ok", durationMs: now() - startedAt });
179
+ }
180
+ catch (err) {
181
+ reports.push({
182
+ stepId: c.stepId,
183
+ status: "err",
184
+ error: serializeError(err),
185
+ durationMs: now() - startedAt,
186
+ });
187
+ // Continue with remaining compensations; don't abort on one failure.
188
+ }
189
+ }
190
+ return reports;
191
+ }
192
+ function serializeError(err) {
193
+ if (err instanceof Error) {
194
+ const code = err.code;
195
+ const cause = err.cause;
196
+ return {
197
+ category: "USER_ERROR",
198
+ code: typeof code === "string" ? code : "UNKNOWN",
199
+ message: err.message,
200
+ name: err.name,
201
+ stack: err.stack,
202
+ cause: cause !== undefined ? serializeError(cause) : undefined,
203
+ };
204
+ }
205
+ return { category: "USER_ERROR", code: "UNKNOWN", message: String(err) };
206
+ }
207
+ async function acquireRateLimit(args) {
208
+ const ctx = { run: { id: args.runId }, project: { id: args.projectId } };
209
+ const key = typeof args.spec.key === "function" ? args.spec.key(args.input, ctx) : args.spec.key;
210
+ const limit = typeof args.spec.limit === "function" ? args.spec.limit(args.input) : args.spec.limit;
211
+ const units = args.spec.units === undefined
212
+ ? 1
213
+ : typeof args.spec.units === "function"
214
+ ? args.spec.units(args.input)
215
+ : args.spec.units;
216
+ const windowMs = durationToMs(args.spec.window);
217
+ const onLimit = args.spec.onLimit ?? "queue";
218
+ if (!args.limiter) {
219
+ const e = new Error(`step "${args.stepId}" declared options.rateLimit but the handler has no rateLimiter wired; ` +
220
+ `pass { rateLimiter } to createStepHandler()`);
221
+ e.code = "RATE_LIMITER_MISSING";
222
+ throw e;
223
+ }
224
+ await args.limiter.acquire({ key, limit, units, windowMs, onLimit, signal: args.signal });
225
+ }
226
+ export { RunCancelledSignal, WaitpointPendingSignal };
@@ -0,0 +1,56 @@
1
+ import type { SerializedError, WorkflowPayloadReference } from "../protocol/index.js";
2
+ import type { WaitpointKind } from "../types.js";
3
+ export interface StepJournalEntry {
4
+ attempt: number;
5
+ status: "ok" | "err";
6
+ output?: unknown;
7
+ error?: SerializedError;
8
+ startedAt: number;
9
+ finishedAt: number;
10
+ /**
11
+ * Which runtime actually executed the step. Set by the executor when
12
+ * routing between `stepRunner` (edge) and `nodeStepRunner`.
13
+ * Informational only — doesn't affect replay.
14
+ */
15
+ runtime?: "edge" | "node";
16
+ }
17
+ export interface WaitpointResolutionEntry {
18
+ kind: WaitpointKind;
19
+ resolvedAt: number;
20
+ matchedEventId?: string;
21
+ payload?: unknown;
22
+ payloadRef?: WorkflowPayloadReference;
23
+ source: "live" | "inbox" | "replay";
24
+ /** Populated for RUN waitpoints when the child run ended in a failure state. */
25
+ error?: SerializedError;
26
+ }
27
+ export interface CompensationJournalEntry {
28
+ status: "ok" | "err";
29
+ finishedAt: number;
30
+ error?: SerializedError;
31
+ }
32
+ export interface JournalSlice {
33
+ stepResults: Record<string, StepJournalEntry>;
34
+ waitpointsResolved: Record<string, WaitpointResolutionEntry>;
35
+ compensationsRun: Record<string, CompensationJournalEntry>;
36
+ metadataState: Record<string, unknown>;
37
+ /**
38
+ * Stream ids whose generator has already been consumed in a prior
39
+ * invocation. The orchestrator already has the chunks on the run
40
+ * record; replaying the body must skip re-iterating the source
41
+ * (generators often have side effects — LLM calls, file reads,
42
+ * billable API usage).
43
+ */
44
+ streamsCompleted: Record<string, {
45
+ chunkCount: number;
46
+ }>;
47
+ }
48
+ export declare function emptyJournal(): JournalSlice;
49
+ /**
50
+ * Clone the journal into a slice that the body sees. Each step /
51
+ * waitpoint the body replays is *consumed* from the slice so we can
52
+ * detect leftover journal entries that the code no longer produces
53
+ * (which is a versioning hazard — see §6.7 of design.md).
54
+ */
55
+ export declare function forkJournal(j: JournalSlice): JournalSlice;
56
+ //# sourceMappingURL=journal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"journal.d.ts","sourceRoot":"","sources":["../../src/runtime/journal.ts"],"names":[],"mappings":"AAKA,OAAO,KAA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AAE,CAAC,CAAA;CACzD;AAED,wBAAgB,YAAY,IAAI,YAAY,CAQ3C;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,YAAY,GAAG,YAAY,CAQzD"}
@@ -0,0 +1,28 @@
1
+ // Tenant-side view of the journal sent by the orchestrator on every
2
+ // `/__voyant/workflow-step` invocation.
3
+ //
4
+ // Wire shape defined in docs/runtime-protocol.md §2.1 (JournalSlice).
5
+ export function emptyJournal() {
6
+ return {
7
+ stepResults: {},
8
+ waitpointsResolved: {},
9
+ compensationsRun: {},
10
+ metadataState: {},
11
+ streamsCompleted: {},
12
+ };
13
+ }
14
+ /**
15
+ * Clone the journal into a slice that the body sees. Each step /
16
+ * waitpoint the body replays is *consumed* from the slice so we can
17
+ * detect leftover journal entries that the code no longer produces
18
+ * (which is a versioning hazard — see §6.7 of design.md).
19
+ */
20
+ export function forkJournal(j) {
21
+ return {
22
+ stepResults: { ...j.stepResults },
23
+ waitpointsResolved: { ...j.waitpointsResolved },
24
+ compensationsRun: { ...j.compensationsRun },
25
+ metadataState: { ...j.metadataState },
26
+ streamsCompleted: { ...j.streamsCompleted },
27
+ };
28
+ }