@lovable.dev/workflows-sdk 0.0.0-dev.8 → 0.0.0-dev.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -387,37 +387,187 @@ configured still builds; only the specifier is uglier, and its depth tracks
387
387
 
388
388
  ### Calling it
389
389
 
390
- `POST /api/workflows/{workflow-id}` with a JSON body. The body is decoded by
391
- `parseWorkflowRequest`, so one route takes every traffic shape: `{ "input": ... }`
392
- starts a run, `{ "runId", "approval" }` delivers an approval decision, and
393
- `{ "runId", "signal" }` delivers a signal. A run that parks on `ctx.approve` or
394
- `ctx.waitForEvent` resumes on this same route — there is no separate resume
395
- endpoint. An unknown workflow ID returns 404, an unparseable body 400, and
396
- `{ "abort": true }` returns 501 until a shared run registry exists.
390
+ Each workflow gets three routes. The run surface drives a workflow to
391
+ completion; the two step surfaces advance it one wave at a time.
397
392
 
398
- The response is `text/event-stream`. Each engine event becomes one SSE message
399
- whose event name is the event `type` and whose data is the whole event as JSON:
393
+ | Route | Does |
394
+ | --- | --- |
395
+ | `POST /api/workflows/{id}` | Runs to completion, streaming SSE |
396
+ | `POST /api/workflows/{id}/nextSteps` | Reports what would run next, running nothing |
397
+ | `POST /api/workflows/{id}/executeSteps` | Runs the requested steps and returns their results |
398
+
399
+ An unknown workflow ID returns 404 and an unparseable body 400.
400
+
401
+ ### The memo is the run
402
+
403
+ There is no run store. A run's entire state is its **memo** — the list of
404
+ settled operations — and the caller carries it between calls:
405
+
406
+ ```jsonc
407
+ [{ "seq": 0, "stepId": "greeting", "occurrence": 0, "kind": "step", "status": "completed", "result": "Hello, yehya!" }]
408
+ ```
409
+
410
+ An entry is keyed by `stepId` and `occurrence` (which call of that id in the
411
+ run, from 0) — never by position or `seq`. Two parallel branches can reach the
412
+ same pair of operations in either order from one pass to the next, so call order
413
+ is reported but is not the identity.
414
+
415
+ Every response returns the memo the next call should send back, along with an
416
+ `inputHash`. Send both, plus the **same `input`** — replay re-runs the handler
417
+ from the top, and the memo does not carry the input. `inputHash` binds the memo
418
+ to the input it came from: resuming with a different one is a 400 rather than a
419
+ run whose settled steps and remaining steps saw different records. Key order in
420
+ the input does not affect it. Because state travels in the request, a run
421
+ survives a restart and can continue on a different instance; there is nothing to
422
+ lose and no process affinity.
423
+
424
+ Replay is what makes this work: the handler re-runs from the top on every call,
425
+ settled operations answer from the memo instead of executing again, and
426
+ `ctx.state` plus ordinary control flow rebuild themselves. A settled operation
427
+ can sit beside an earlier pending one — `ctx.now()` pinned next to a step still
428
+ waiting in the same `Promise.all`. An entry must match the kind of operation
429
+ replay finds at its id, so a tampered or stale memo fails the call rather than
430
+ answering the wrong one:
431
+
432
+ ```json
433
+ { "status": "failed", "error": "non-deterministic replay: memo has approve \"thing\" (#0), replay produced step" }
434
+ ```
435
+
436
+ **Handler code outside a step runs on every call.** Keep side effects inside
437
+ `ctx.step`, which is memoized; a bare `fetch` in the handler body repeats each
438
+ pass. A pass also allows only a bounded amount of such work — 5s by default —
439
+ before reporting the run stalled.
440
+
441
+ ### The memo is unauthenticated input
442
+
443
+ **A caller supplies the memo, and the route does not authenticate it.** Anything
444
+ the memo says is already settled is taken as settled, including an approval's
445
+ decision. A caller who can reach the route can therefore hand back
446
+ `{"kind": "approve", "status": "completed", "result": {"approved": true}}` and
447
+ skip the human, or mark an expensive step completed with a fabricated result and
448
+ skip the work. `inputHash` binds a memo to one input, so a forged memo cannot be
449
+ replayed against a different record, but it is computed from the request and so
450
+ is no barrier on its own.
451
+
452
+ Until signed invocation lands, **do not treat `ctx.approve` as a security
453
+ boundary on these routes**, and do not put an operation behind one that a
454
+ stranger must not be able to declare done. Reachability is the only control an
455
+ app has in the meantime; see `path` above.
456
+
457
+ ### Stepping through a run
458
+
459
+ ```bash
460
+ POST /api/workflows/greet/nextSteps
461
+ { "input": { "name": "yehya" } }
462
+ -> { "status": "pending", "memo": [], "steps": [{ "seq": 0, "stepId": "greeting", "kind": "step" }] }
463
+
464
+ POST /api/workflows/greet/executeSteps
465
+ { "input": { "name": "yehya" }, "memo": [], "steps": [{ "stepId": "greeting" }] }
466
+ -> { "status": "pending",
467
+ "results": [{ "seq": 0, "stepId": "greeting", "status": "completed", "result": "Hello, yehya!" }],
468
+ "memo": [{ "seq": 0, "stepId": "greeting", ... }],
469
+ "steps": [{ "seq": 1, "stepId": "shout", "kind": "step" }] }
470
+ ```
471
+
472
+ Send the returned `memo` back each time; the run ends with
473
+ `{"status": "completed", "output": ...}`. Omitting `steps` on `executeSteps`
474
+ runs whatever `nextSteps` would report, so the run advances one wave per call.
475
+
476
+ ### Driving a run from an orchestrator
477
+
478
+ **Loop on `executeSteps` alone, with `steps` omitted.** One response carries the
479
+ results, the updated `memo`, *and* the operations now pending, so a driver never
480
+ needs a separate `nextSteps` call:
481
+
482
+ ```jsonc
483
+ // POST /api/workflows/greet/executeSteps { "input": {...} }
484
+ { "status": "pending",
485
+ "results": [{ "stepId": "greeting", "occurrence": 0, "kind": "step", "status": "completed", "result": "Hello, yehya!" }],
486
+ "steps": [{ "stepId": "shout", "occurrence": 0, "kind": "step" }],
487
+ "memo": [{ "stepId": "greeting", "occurrence": 0, ... }],
488
+ "inputHash": "9f2c…" }
489
+ ```
490
+
491
+ That is one HTTP call and one replay per wave — the cheapest shape, and the one
492
+ to use when a remote orchestrator drives the app. Pairing `nextSteps` with
493
+ `executeSteps` doubles both: use it when something needs to *see* what would run
494
+ before it runs, such as a UI preview or an approval gate.
495
+
496
+ Concurrent steps settle together: `Promise.all([ctx.step("a"), ctx.step("b")])`
497
+ is one wave, and a step after the join is the next.
498
+
499
+ Keep a step's result small: it travels in the memo on every later call, so a
500
+ large payload is resent for the rest of the run. Write bulk data to storage
501
+ inside the step and return the key.
502
+
503
+ **Replay cost.** Each pass re-runs the handler from the top, so code outside
504
+ `ctx.step` executes once per wave — for an 8-step workflow, 8 times through a
505
+ `executeSteps` loop and 16 through a `nextSteps` + `executeSteps` one. Step
506
+ bodies run exactly once each. This is why side effects belong inside a step.
507
+
508
+ `nextSteps` reports a step's `stepId` and `kind` but **not its input**:
509
+ `ctx.step(id, fn)` closes over its arguments rather than declaring them, so the
510
+ input is not knowable without running `fn`. Deterministic values (`ctx.now`,
511
+ `ctx.uuid`) are the exception to the no-side-effects rule — `nextSteps` pins them
512
+ and returns them in `memo`, so a later `executeSteps` replays the same values.
513
+
514
+ ### Waiting on something outside the app
515
+
516
+ `ctx.sleep`, `ctx.waitForEvent` and `ctx.approve` cannot be settled by the app,
517
+ so they are never executed — they come back as pending operations carrying what
518
+ a caller needs to resolve them:
519
+
520
+ ```json
521
+ { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
522
+ "config": { "title": "Approve refund", "description": "refund of $40" } }
523
+ ```
524
+
525
+ The run surface emits `RUN_PAUSED` with that list and the memo, then ends the
526
+ request rather than holding a connection open. Resume by appending the decision
527
+ to the memo and calling again:
528
+
529
+ ```jsonc
530
+ { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
531
+ "status": "completed", "result": { "approved": true, "approvalId": "apr_1" } }
532
+ ```
533
+
534
+ ### The run surface
535
+
536
+ `POST /api/workflows/{workflow-id}` with `{ "input": ... }` starts a run and
537
+ `{ "memo": [...] }` continues one. The response is `text/event-stream`, one SSE
538
+ message per event, the event name being its `type`:
400
539
 
401
540
  ```text
402
541
  event: RUN_STARTED
403
- data: {"type":"RUN_STARTED","ts":1790505539351,"runId":"run_1790505539350_yin41cp"}
542
+ data: {"type":"RUN_STARTED","ts":1790528863501,"runId":"run_1790528863501_tzqgjl8i"}
404
543
 
405
544
  event: STEP_FINISHED
406
- data: {"type":"STEP_FINISHED","ts":1790505539352,"stepId":"greeting","result":"Hello, YEHYA!"}
545
+ data: {"type":"STEP_FINISHED","ts":1790528863571,"stepId":"greeting","result":"Hello, yehya!"}
407
546
 
408
547
  event: RUN_FINISHED
409
- data: {"type":"RUN_FINISHED","ts":1790505539352,"runId":"run_1790505539350_yin41cp","output":{"message":"Hello, YEHYA!"}}
548
+ data: {"type":"RUN_FINISHED","ts":1790528863685,"runId":"...","output":{"message":"Hello, yehya!"}}
410
549
  ```
411
550
 
412
- Run state lives in a process-local `inMemoryRunStore()`: runs are lost on restart
413
- and are invisible to other instances. Pass `runStore` to
414
- `createTanStackWorkflowHandler` to supply another one. The control-plane store is
415
- a follow-up.
551
+ It drives the memo loop internally for the length of one request, so it holds no
552
+ state between requests either. `RUN_FINISHED`, `RUN_ERRORED` and `RUN_PAUSED` all carry the
553
+ memo, so a caller that only sent an input still holds what already ran and a
554
+ retry does not repeat it.
555
+
556
+ `createTanStackWorkflowHandler` is still exported for the engine-backed path
557
+ (`runWorkflow` plus a `RunStore`, `inMemoryRunStore()` by default). No emitted
558
+ route uses it: a process-local store loses runs on restart and is invisible to
559
+ other instances, which is what the memo model replaces.
560
+
561
+ ### Not yet carried over
562
+
563
+ `ctx.step`'s `retries` and `timeout` options are accepted and ignored — the
564
+ caller decides whether to re-issue a failed step. Step retry, timeouts, and
565
+ `previousVersions` routing are follow-ups.
416
566
 
417
567
  The path carries no build ID. Version pinning belongs to the signed invocation,
418
- which leaves this path stable across deployments and safe to publish in a
568
+ which leaves these paths stable across deployments and safe to publish in a
419
569
  manifest. Triggers name a workflow rather than an endpoint, so firing one is a
420
- POST to that workflow's path with the trigger's input; no trigger identifier
570
+ POST to that workflow's run path with the trigger's input; no trigger identifier
421
571
  appears in the URL.
422
572
 
423
573
  ## Public entry points
@@ -426,7 +576,7 @@ The package has two, and neither mirrors the source tree:
426
576
 
427
577
  | Import | Provides |
428
578
  | --- | --- |
429
- | `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and `createTanStackWorkflowHandler` |
579
+ | `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and the route handlers (`createRunHandler`, `createNextStepsHandler`, `createExecuteStepsHandler`) |
430
580
  | `@lovable.dev/workflows-sdk/vite` | `workflowsPlugin`, the build-time Vite plugin |
431
581
 
432
582
  The export map is a contract; the directory layout under `src/` is not. They are
package/dist/index.d.ts CHANGED
@@ -147,6 +147,26 @@ type TanStackWorkflowHandler = (ctx: TanStackRouteCtx) => Promise<Response>;
147
147
  /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
148
148
  declare function createTanStackWorkflowHandler(collection: WorkflowCollection, options?: TanStackWorkflowHandlerOptions): TanStackWorkflowHandler;
149
149
  //#endregion
150
+ //#region src/stacks/tanstack/steps.d.ts
151
+ interface StepsHandlerOptions {
152
+ /** Route parameter carrying the workflow ID. @default "workflowId" */
153
+ workflowIdParam?: string;
154
+ }
155
+ interface RouteCtx {
156
+ request: Request;
157
+ params?: Record<string, string | undefined>;
158
+ }
159
+ type StepsHandler = (ctx: RouteCtx) => Promise<Response>;
160
+ /** Report what a run is waiting on, running nothing. Pins ctx.now/ctx.uuid into
161
+ * `memo` so a later executeSteps replays the same values. */
162
+ declare function createNextStepsHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
163
+ /** Run the requested steps; omitting `steps` runs whatever `nextSteps` would
164
+ * report, advancing the run one wave per call. */
165
+ declare function createExecuteStepsHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
166
+ //#endregion
167
+ //#region src/stacks/tanstack/run.d.ts
168
+ declare function createRunHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
169
+ //#endregion
150
170
  //#region src/stacks/tanstack/sse.d.ts
151
171
  /**
152
172
  * Encode a workflow event stream as `text/event-stream`. Each event keeps its
@@ -154,4 +174,65 @@ declare function createTanStackWorkflowHandler(collection: WorkflowCollection, o
154
174
  */
155
175
  declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
156
176
  //#endregion
157
- export { type AnyWorkflowDefinition, type Cadence, type Ctx, type OverlapPolicy, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type StepContext, type StepOptions, type TanStackWorkflowHandler, type TanStackWorkflowHandlerOptions, type TriggerDefinition, type Weekday, type WorkflowCollection, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createMiddleware, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
177
+ //#region src/runtime/types.d.ts
178
+ /** Durable operations a replay can answer from the memo. */
179
+ type StepKind = "step" | "sleep" | "waitForEvent" | "approve" | "now" | "uuid";
180
+ /**
181
+ * One settled durable operation. The memo is the whole run state: the caller
182
+ * carries it between calls, so no run store is involved.
183
+ */
184
+ interface MemoEntry {
185
+ /** Call order within the pass that recorded it. Reporting only: racing
186
+ * branches can order differently on a later pass, so it is not the key. */
187
+ seq: number;
188
+ stepId: string;
189
+ /** Which call of this `stepId` in the run, from 0. */
190
+ occurrence: number;
191
+ kind: StepKind;
192
+ status: "completed" | "failed";
193
+ result?: unknown;
194
+ error?: string;
195
+ }
196
+ /** A durable operation the replay reached but could not answer. */
197
+ interface StepIntent {
198
+ seq: number;
199
+ stepId: string;
200
+ occurrence: number;
201
+ kind: StepKind;
202
+ /** Kind-specific detail: sleep `ms`, `waitForEvent` name, approval title. */
203
+ config?: Record<string, unknown>;
204
+ }
205
+ interface StepResult {
206
+ seq: number;
207
+ stepId: string;
208
+ occurrence: number;
209
+ kind: StepKind;
210
+ status: "completed" | "failed";
211
+ result?: unknown;
212
+ error?: string;
213
+ }
214
+ type ReplayStatus = "completed" | "failed" | "pending";
215
+ interface ReplayOutcome {
216
+ status: ReplayStatus;
217
+ /** The memo the next call should send back, including entries this pass settled. */
218
+ memo: MemoEntry[];
219
+ /** Operations that still need an answer; empty unless `status` is `pending`. */
220
+ steps: StepIntent[];
221
+ /** Operations this pass executed, in execution order. */
222
+ results: StepResult[];
223
+ /** `ctx.emit` payloads; diagnostic only, never part of replay. */
224
+ emitted: {
225
+ name: string;
226
+ value: Record<string, unknown>;
227
+ }[];
228
+ output?: unknown;
229
+ error?: string;
230
+ }
231
+ /** Identifies one durable operation for `executeSteps`. */
232
+ interface StepSelector {
233
+ stepId: string;
234
+ /** Defaults to 0; needed only when a run calls the same `stepId` more than once. */
235
+ occurrence?: number;
236
+ }
237
+ //#endregion
238
+ export { type AnyWorkflowDefinition, type Cadence, type Ctx, type MemoEntry, type OverlapPolicy, type ReplayOutcome, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type StepContext, type StepIntent, type StepKind, type StepOptions, type StepResult, type StepSelector, type StepsHandler, type StepsHandlerOptions, type TanStackWorkflowHandler, type TanStackWorkflowHandlerOptions, type TriggerDefinition, type Weekday, type WorkflowCollection, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createExecuteStepsHandler, createMiddleware, createNextStepsHandler, createRunHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ const HEADERS = {
7
7
  connection: "keep-alive",
8
8
  "x-accel-buffering": "no"
9
9
  };
10
- function describe(error) {
10
+ function describe$1(error) {
11
11
  return error instanceof Error ? error.message : String(error);
12
12
  }
13
13
  function frame(name, data) {
@@ -33,13 +33,13 @@ function toServerSentEventsResponse(events) {
33
33
  try {
34
34
  write(frame(name, data));
35
35
  } catch (error) {
36
- write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe(error)}` }));
36
+ write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe$1(error)}` }));
37
37
  }
38
38
  };
39
39
  try {
40
40
  for await (const event of events) send(event.type, event);
41
41
  } catch (error) {
42
- send("STREAM_ERRORED", { message: describe(error) });
42
+ send("STREAM_ERRORED", { message: describe$1(error) });
43
43
  } finally {
44
44
  try {
45
45
  controller.close();
@@ -52,13 +52,13 @@ function toServerSentEventsResponse(events) {
52
52
  }
53
53
  //#endregion
54
54
  //#region src/stacks/tanstack/handlers.ts
55
- function json(status, body) {
55
+ function json$1(status, body) {
56
56
  return new Response(JSON.stringify(body), {
57
57
  status,
58
58
  headers: { "content-type": "application/json; charset=utf-8" }
59
59
  });
60
60
  }
61
- function resolveWorkflowId(ctx, param) {
61
+ function resolveWorkflowId$1(ctx, param) {
62
62
  const fromParams = ctx.params?.[param];
63
63
  if (fromParams) return fromParams;
64
64
  return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
@@ -69,9 +69,9 @@ function createTanStackWorkflowHandler(collection, options = {}) {
69
69
  const param = options.workflowIdParam ?? "workflowId";
70
70
  const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
71
71
  return async (ctx) => {
72
- const workflowId = resolveWorkflowId(ctx, param);
72
+ const workflowId = resolveWorkflowId$1(ctx, param);
73
73
  const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
74
- if (!workflow) return json(404, {
74
+ if (!workflow) return json$1(404, {
75
75
  error: "unknown_workflow",
76
76
  workflowId: workflowId ?? ""
77
77
  });
@@ -79,13 +79,13 @@ function createTanStackWorkflowHandler(collection, options = {}) {
79
79
  try {
80
80
  params = await parseWorkflowRequest(ctx.request);
81
81
  } catch (error) {
82
- if (error instanceof WorkflowRequestParseError) return json(400, {
82
+ if (error instanceof WorkflowRequestParseError) return json$1(400, {
83
83
  error: "invalid_request",
84
84
  message: error.message
85
85
  });
86
86
  throw error;
87
87
  }
88
- if (params.abort) return json(501, {
88
+ if (params.abort) return json$1(501, {
89
89
  error: "abort_unsupported",
90
90
  message: "Cancelling an in-flight run needs a shared run registry (WOR-53)."
91
91
  });
@@ -97,4 +97,535 @@ function createTanStackWorkflowHandler(collection, options = {}) {
97
97
  };
98
98
  }
99
99
  //#endregion
100
- export { createMiddleware, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
100
+ //#region src/runtime/input-hash.ts
101
+ /** Key order must not change the hash, so objects are serialized sorted. */
102
+ function canonical(value) {
103
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
104
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
105
+ return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
106
+ }
107
+ /**
108
+ * Identifies the input a run started with. A resume carries it back so replay
109
+ * cannot be pointed at a different record than the one its memo came from.
110
+ */
111
+ async function hashInput(input) {
112
+ const bytes = new TextEncoder().encode(canonical(input));
113
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
114
+ return [...new Uint8Array(digest)].slice(0, 16).map((byte) => byte.toString(16).padStart(2, "0")).join("");
115
+ }
116
+ //#endregion
117
+ //#region src/runtime/replay.ts
118
+ /** How long a pass waits for handler work that is not a durable operation. */
119
+ const DEFAULT_SETTLE_MS = 5e3;
120
+ function memoKey(stepId, occurrence) {
121
+ return `${stepId}#${occurrence}`;
122
+ }
123
+ const EXECUTABLE = /* @__PURE__ */ new Set([
124
+ "step",
125
+ "now",
126
+ "uuid"
127
+ ]);
128
+ function describe(error) {
129
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
130
+ }
131
+ function runtimeContext() {
132
+ return {
133
+ timeRemaining: () => Number.POSITIVE_INFINITY,
134
+ shouldYield: () => false,
135
+ yield: async () => {}
136
+ };
137
+ }
138
+ /** Thread the handler through `.middleware([...])`, merging each extension into ctx. */
139
+ async function throughMiddleware(middlewares, ctx, handler) {
140
+ let index = 0;
141
+ const dispatch = async () => {
142
+ const middleware = middlewares[index++];
143
+ if (!middleware) return handler(ctx);
144
+ return middleware.server({
145
+ ctx,
146
+ next: async ({ context }) => {
147
+ Object.assign(ctx, context);
148
+ return dispatch();
149
+ }
150
+ });
151
+ };
152
+ return dispatch();
153
+ }
154
+ async function replay(options) {
155
+ const { workflow, input, runId } = options;
156
+ const byKey = new Map(options.memo.map((entry) => [memoKey(entry.stepId, entry.occurrence ?? 0), entry]));
157
+ const allow = options.shouldExecute ?? (() => true);
158
+ const never = new Promise(() => {});
159
+ const pending = [];
160
+ const settled = /* @__PURE__ */ new Map();
161
+ const pass = { stepsSettled: 0 };
162
+ const occurrences = /* @__PURE__ */ new Map();
163
+ const consumed = /* @__PURE__ */ new Set();
164
+ let lastProgress = Date.now();
165
+ const results = [];
166
+ const emitted = [];
167
+ const inflight = [];
168
+ let seq = 0;
169
+ let nonDeterminism;
170
+ function record(entry) {
171
+ settled.set(memoKey(entry.stepId, entry.occurrence), entry);
172
+ lastProgress = Date.now();
173
+ if (entry.kind === "step") pass.stepsSettled += 1;
174
+ const result = {
175
+ seq: entry.seq,
176
+ stepId: entry.stepId,
177
+ occurrence: entry.occurrence,
178
+ kind: entry.kind,
179
+ status: entry.status,
180
+ result: entry.result,
181
+ error: entry.error
182
+ };
183
+ results.push(result);
184
+ options.onStepSettle?.(result);
185
+ }
186
+ function durable(kind, stepId, run, config, defaulted = false) {
187
+ const index = seq++;
188
+ const occurrence = occurrences.get(stepId) ?? 0;
189
+ occurrences.set(stepId, occurrence + 1);
190
+ if (defaulted && occurrence > 0) {
191
+ nonDeterminism = `ctx.${kind}() was reached more than once with the default id "${stepId}"; pass an explicit { id } per call site`;
192
+ return never;
193
+ }
194
+ const key = memoKey(stepId, occurrence);
195
+ consumed.add(key);
196
+ const answered = byKey.get(key) ?? settled.get(key);
197
+ if (answered) {
198
+ if (answered.kind !== kind) {
199
+ nonDeterminism = `memo has ${answered.kind} "${stepId}" (#${occurrence}), replay produced ${kind}`;
200
+ return never;
201
+ }
202
+ if (answered.status === "completed") return Promise.resolve(answered.result);
203
+ return Promise.reject(new Error(answered.error ?? `step "${stepId}" failed`));
204
+ }
205
+ const intent = {
206
+ seq: index,
207
+ stepId,
208
+ occurrence,
209
+ kind,
210
+ ...config ? { config } : {}
211
+ };
212
+ if (!run || !EXECUTABLE.has(kind) || !allow(intent, pass)) {
213
+ pending.push(intent);
214
+ return never;
215
+ }
216
+ options.onStepStart?.(intent);
217
+ const running = run().then((result) => {
218
+ record({
219
+ seq: index,
220
+ stepId,
221
+ occurrence,
222
+ kind,
223
+ status: "completed",
224
+ result
225
+ });
226
+ return result;
227
+ }, (error) => {
228
+ record({
229
+ seq: index,
230
+ stepId,
231
+ occurrence,
232
+ kind,
233
+ status: "failed",
234
+ error: describe(error)
235
+ });
236
+ throw error;
237
+ });
238
+ inflight.push(running.then(noop, noop));
239
+ return running;
240
+ }
241
+ const state = { ...workflow.initialize?.({ input }) };
242
+ const runtime = runtimeContext();
243
+ const controller = new AbortController();
244
+ const ctx = {
245
+ runId,
246
+ input,
247
+ state,
248
+ signal: controller.signal,
249
+ runtime,
250
+ step: (id, fn, _options) => durable("step", id, async () => fn({
251
+ id,
252
+ attempt: 1,
253
+ runtime,
254
+ signal: controller.signal
255
+ })),
256
+ sleep: (ms, opts) => durable("sleep", opts?.id ?? `sleep:${ms}`, void 0, { ms }, opts?.id === void 0),
257
+ sleepUntil: (timestamp, opts) => durable("sleep", opts?.id ?? `sleepUntil:${timestamp}`, void 0, { timestamp }, opts?.id === void 0),
258
+ waitForEvent: (name, opts) => durable("waitForEvent", opts?.id ?? `event:${name}`, void 0, { name }, opts?.id === void 0),
259
+ approve: (opts) => durable("approve", opts.id ?? `approve:${opts.title}`, void 0, {
260
+ title: opts.title,
261
+ ...opts.description === void 0 ? {} : { description: opts.description }
262
+ }, opts.id === void 0),
263
+ now: (opts) => durable("now", opts?.id ?? "now", async () => Date.now(), void 0, opts?.id === void 0),
264
+ uuid: (opts) => durable("uuid", opts?.id ?? "uuid", async () => crypto.randomUUID(), void 0, opts?.id === void 0),
265
+ emit: (name, value) => {
266
+ emitted.push({
267
+ name,
268
+ value
269
+ });
270
+ }
271
+ };
272
+ let outcome;
273
+ throughMiddleware(workflow.middlewares ?? [], ctx, workflow.handler).then((output) => {
274
+ outcome = {
275
+ status: "completed",
276
+ output: output ?? null
277
+ };
278
+ }, (error) => {
279
+ outcome = {
280
+ status: "failed",
281
+ error: describe(error)
282
+ };
283
+ });
284
+ const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
285
+ for (;;) {
286
+ for (let tick = 0; tick < 20; tick++) await new Promise((resolve) => setTimeout(resolve, 0));
287
+ if (outcome || nonDeterminism) break;
288
+ if (inflight.length > 0) {
289
+ await Promise.all(inflight.splice(0));
290
+ lastProgress = Date.now();
291
+ continue;
292
+ }
293
+ if (pending.length > 0 || Date.now() - lastProgress >= settleMs) break;
294
+ await new Promise((resolve) => setTimeout(resolve, 5));
295
+ }
296
+ while (inflight.length > 0) await Promise.all(inflight.splice(0));
297
+ const memo = [...byKey.values(), ...settled.values()];
298
+ const orphan = [...byKey.keys()].find((key) => !consumed.has(key));
299
+ pending.sort((a, b) => a.seq - b.seq);
300
+ results.sort((a, b) => a.seq - b.seq);
301
+ const base = {
302
+ memo,
303
+ results,
304
+ emitted
305
+ };
306
+ if (nonDeterminism) return {
307
+ ...base,
308
+ status: "failed",
309
+ steps: [],
310
+ error: `non-deterministic replay: ${nonDeterminism}`
311
+ };
312
+ if (orphan !== void 0) return {
313
+ ...base,
314
+ status: "failed",
315
+ steps: [],
316
+ error: `stale memo: no operation matched "${orphan}"`
317
+ };
318
+ if (outcome?.status === "completed") return {
319
+ ...base,
320
+ status: "completed",
321
+ steps: [],
322
+ output: outcome.output
323
+ };
324
+ if (outcome?.status === "failed") return {
325
+ ...base,
326
+ status: "failed",
327
+ steps: [],
328
+ error: outcome.error
329
+ };
330
+ if (pending.length > 0) return {
331
+ ...base,
332
+ status: "pending",
333
+ steps: pending
334
+ };
335
+ return {
336
+ ...base,
337
+ status: "failed",
338
+ steps: [],
339
+ error: `workflow stalled: no durable operation and nothing settled for ${settleMs}ms`
340
+ };
341
+ }
342
+ function noop() {}
343
+ //#endregion
344
+ //#region src/stacks/tanstack/steps.ts
345
+ function json(status, body) {
346
+ return new Response(JSON.stringify(body), {
347
+ status,
348
+ headers: { "content-type": "application/json; charset=utf-8" }
349
+ });
350
+ }
351
+ function resolveWorkflowId(ctx, param) {
352
+ const fromParams = ctx.params?.[param];
353
+ if (fromParams) return fromParams;
354
+ return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-2);
355
+ }
356
+ function isMemoEntry(value) {
357
+ const entry = value;
358
+ return typeof entry === "object" && entry !== null && Number.isInteger(entry.seq) && entry.seq >= 0 && typeof entry.stepId === "string" && Number.isInteger(entry.occurrence) && entry.occurrence >= 0 && (entry.status === "completed" || entry.status === "failed");
359
+ }
360
+ function parseBody(value) {
361
+ if (value === null || typeof value !== "object") return "body must be a JSON object";
362
+ const body = value;
363
+ if (body.memo !== void 0) {
364
+ if (!Array.isArray(body.memo) || !body.memo.every(isMemoEntry)) return "memo must be an array of settled step entries";
365
+ if (new Set(body.memo.map((entry) => memoKey(entry.stepId, entry.occurrence))).size !== body.memo.length) return "memo entries must be unique per stepId and occurrence";
366
+ }
367
+ if (body.steps !== void 0 && (!Array.isArray(body.steps) || !body.steps.every(isSelector))) return "steps must be an array of { stepId, occurrence? } selectors";
368
+ if (body.memo !== void 0 && body.memo.length > 0 && !("input" in value)) return "input must be sent with every call, including a resume";
369
+ return body;
370
+ }
371
+ async function readBody(request) {
372
+ const text = await request.text();
373
+ if (!text.trim()) return {};
374
+ return JSON.parse(text);
375
+ }
376
+ function selectorKey(selector) {
377
+ return memoKey(selector.stepId, selector.occurrence ?? 0);
378
+ }
379
+ function isSelector(value) {
380
+ const selector = value;
381
+ return typeof selector === "object" && selector !== null && typeof selector.stepId === "string" && (selector.occurrence === void 0 || Number.isInteger(selector.occurrence) && selector.occurrence >= 0);
382
+ }
383
+ function respond(runId, inputHash, outcome) {
384
+ const { status, memo, steps, results, emitted, output, error } = outcome;
385
+ return json(200, {
386
+ runId,
387
+ inputHash,
388
+ status,
389
+ memo,
390
+ steps,
391
+ results,
392
+ ...emitted.length > 0 ? { emitted } : {},
393
+ ...output === void 0 ? {} : { output },
394
+ ...error === void 0 ? {} : { error }
395
+ });
396
+ }
397
+ function prepare(collection, options) {
398
+ return {
399
+ param: options.workflowIdParam ?? "workflowId",
400
+ byId: new Map(collection.workflows.map((workflow) => [workflow.id, workflow]))
401
+ };
402
+ }
403
+ async function resolve(ctx, param, byId) {
404
+ const workflowId = resolveWorkflowId(ctx, param);
405
+ const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
406
+ if (!workflow) return json(404, {
407
+ error: "unknown_workflow",
408
+ workflowId: workflowId ?? ""
409
+ });
410
+ let raw;
411
+ try {
412
+ raw = await readBody(ctx.request);
413
+ } catch (error) {
414
+ return json(400, {
415
+ error: "invalid_request",
416
+ message: `body is not valid JSON: ${String(error)}`
417
+ });
418
+ }
419
+ const body = parseBody(raw);
420
+ if (typeof body === "string") return json(400, {
421
+ error: "invalid_request",
422
+ message: body
423
+ });
424
+ const inputHash = await hashInput(body.input ?? null);
425
+ if (body.memo !== void 0 && body.memo.length > 0 && body.inputHash !== inputHash) return json(400, {
426
+ error: "invalid_request",
427
+ message: body.inputHash === void 0 ? "inputHash must be sent with a memo; echo the value from the previous response" : "input does not match the run this memo came from"
428
+ });
429
+ return {
430
+ workflow,
431
+ body,
432
+ runId: body.runId ?? `run_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,
433
+ inputHash
434
+ };
435
+ }
436
+ /** Report what a run is waiting on, running nothing. Pins ctx.now/ctx.uuid into
437
+ * `memo` so a later executeSteps replays the same values. */
438
+ function createNextStepsHandler(collection, options = {}) {
439
+ const { param, byId } = prepare(collection, options);
440
+ return async (ctx) => {
441
+ const resolved = await resolve(ctx, param, byId);
442
+ if (resolved instanceof Response) return resolved;
443
+ const { workflow, body, runId, inputHash } = resolved;
444
+ return respond(runId, inputHash, await replay({
445
+ workflow,
446
+ input: body.input ?? null,
447
+ memo: body.memo ?? [],
448
+ runId,
449
+ shouldExecute: (intent) => intent.kind !== "step"
450
+ }));
451
+ };
452
+ }
453
+ /** Run the requested steps; omitting `steps` runs whatever `nextSteps` would
454
+ * report, advancing the run one wave per call. */
455
+ function createExecuteStepsHandler(collection, options = {}) {
456
+ const { param, byId } = prepare(collection, options);
457
+ return async (ctx) => {
458
+ const resolved = await resolve(ctx, param, byId);
459
+ if (resolved instanceof Response) return resolved;
460
+ const { workflow, body, runId, inputHash } = resolved;
461
+ const input = body.input ?? null;
462
+ const memo = body.memo ?? [];
463
+ const wanted = body.steps && new Set(body.steps.map(selectorKey));
464
+ return respond(runId, inputHash, await replay({
465
+ workflow,
466
+ input,
467
+ memo,
468
+ runId,
469
+ shouldExecute: (intent, pass) => intent.kind !== "step" || (wanted ? wanted.has(selectorKey(intent)) : pass.stepsSettled === 0)
470
+ }));
471
+ };
472
+ }
473
+ //#endregion
474
+ //#region src/stacks/tanstack/run.ts
475
+ function event(type, fields) {
476
+ return {
477
+ type,
478
+ ts: Date.now(),
479
+ ...fields
480
+ };
481
+ }
482
+ async function* drive(workflow, input, runId, initialMemo, inputHash) {
483
+ let memo = [...initialMemo];
484
+ yield event("RUN_STARTED", {
485
+ runId,
486
+ inputHash
487
+ });
488
+ for (;;) {
489
+ const queue = [];
490
+ let wake;
491
+ const emit = (next) => {
492
+ queue.push(next);
493
+ wake?.();
494
+ wake = void 0;
495
+ };
496
+ let settledPass;
497
+ let passError;
498
+ let finished = false;
499
+ const running = replay({
500
+ workflow,
501
+ input,
502
+ memo,
503
+ runId,
504
+ shouldExecute: (intent, state) => intent.kind !== "step" || state.stepsSettled === 0,
505
+ onStepStart: (intent) => {
506
+ if (intent.kind === "step") emit(event("STEP_STARTED", { stepId: intent.stepId }));
507
+ },
508
+ onStepSettle: (result) => {
509
+ if (result.kind !== "step") return;
510
+ emit(result.status === "completed" ? event("STEP_FINISHED", {
511
+ stepId: result.stepId,
512
+ result: result.result
513
+ }) : event("STEP_FAILED", {
514
+ stepId: result.stepId,
515
+ error: result.error
516
+ }));
517
+ }
518
+ }).then((value) => {
519
+ settledPass = value;
520
+ finished = true;
521
+ wake?.();
522
+ wake = void 0;
523
+ }, (error) => {
524
+ passError = error;
525
+ finished = true;
526
+ wake?.();
527
+ wake = void 0;
528
+ });
529
+ for (;;) {
530
+ if (queue.length > 0) {
531
+ yield queue.shift();
532
+ continue;
533
+ }
534
+ if (finished) break;
535
+ await new Promise((resolve) => {
536
+ wake = resolve;
537
+ });
538
+ }
539
+ await running;
540
+ if (!settledPass) {
541
+ yield event("RUN_ERRORED", {
542
+ runId,
543
+ inputHash,
544
+ error: `replay threw: ${passError instanceof Error ? passError.message : String(passError)}`,
545
+ memo
546
+ });
547
+ return;
548
+ }
549
+ const pass = settledPass;
550
+ memo = pass.memo;
551
+ if (pass.status === "completed") {
552
+ yield event("RUN_FINISHED", {
553
+ runId,
554
+ inputHash,
555
+ output: pass.output,
556
+ memo
557
+ });
558
+ return;
559
+ }
560
+ if (pass.status === "failed") {
561
+ yield event("RUN_ERRORED", {
562
+ runId,
563
+ inputHash,
564
+ error: pass.error,
565
+ memo
566
+ });
567
+ return;
568
+ }
569
+ if (pass.steps.every((intent) => intent.kind !== "step")) {
570
+ yield event("RUN_PAUSED", {
571
+ runId,
572
+ inputHash,
573
+ waitingOn: pass.steps,
574
+ memo
575
+ });
576
+ return;
577
+ }
578
+ if (pass.results.length === 0) {
579
+ yield event("RUN_ERRORED", {
580
+ runId,
581
+ inputHash,
582
+ error: "run made no progress",
583
+ memo
584
+ });
585
+ return;
586
+ }
587
+ }
588
+ }
589
+ function createRunHandler(collection, options = {}) {
590
+ const param = options.workflowIdParam ?? "workflowId";
591
+ const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
592
+ return async (ctx) => {
593
+ const workflowId = ctx.params?.[param] ?? new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
594
+ const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
595
+ if (!workflow) return new Response(JSON.stringify({
596
+ error: "unknown_workflow",
597
+ workflowId: workflowId ?? ""
598
+ }), {
599
+ status: 404,
600
+ headers: { "content-type": "application/json; charset=utf-8" }
601
+ });
602
+ let body = {};
603
+ try {
604
+ const text = await ctx.request.text();
605
+ if (text.trim()) body = JSON.parse(text);
606
+ } catch (error) {
607
+ return new Response(JSON.stringify({
608
+ error: "invalid_request",
609
+ message: String(error)
610
+ }), {
611
+ status: 400,
612
+ headers: { "content-type": "application/json; charset=utf-8" }
613
+ });
614
+ }
615
+ const inputHash = await hashInput(body.input ?? null);
616
+ if (body.memo !== void 0 && body.memo.length > 0 && body.inputHash !== inputHash) {
617
+ const message = body.inputHash === void 0 ? "inputHash must be sent with a memo; echo the value from the previous response" : "input does not match the run this memo came from";
618
+ return new Response(JSON.stringify({
619
+ error: "invalid_request",
620
+ message
621
+ }), {
622
+ status: 400,
623
+ headers: { "content-type": "application/json; charset=utf-8" }
624
+ });
625
+ }
626
+ const runId = body.runId ?? `run_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
627
+ return toServerSentEventsResponse(drive(workflow, body.input ?? null, runId, body.memo ?? [], inputHash));
628
+ };
629
+ }
630
+ //#endregion
631
+ export { createExecuteStepsHandler, createMiddleware, createNextStepsHandler, createRunHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
package/dist/vite.js CHANGED
@@ -159,7 +159,21 @@ function relativeImportSpecifier(routeFile, target) {
159
159
  function collectionSpecifier(routeFile, entry, aliases, tsconfigPathsPlugin) {
160
160
  return aliasedSpecifier(entry, aliases, tsconfigPathsPlugin) ?? relativeImportSpecifier(routeFile, entry);
161
161
  }
162
- function buildRouteSource(routeFile, routeLiteral, param, specifier, root) {
162
+ const SURFACES = [
163
+ {
164
+ segment: "",
165
+ factory: "createRunHandler"
166
+ },
167
+ {
168
+ segment: "nextSteps",
169
+ factory: "createNextStepsHandler"
170
+ },
171
+ {
172
+ segment: "executeSteps",
173
+ factory: "createExecuteStepsHandler"
174
+ }
175
+ ];
176
+ function buildRouteSource(routeFile, routeLiteral, param, specifier, root, factory) {
163
177
  return `${GENERATED_BANNER}
164
178
  // route: ${routeLiteral}
165
179
  // emitted to: ${normalizePath(relative(root, routeFile))}
@@ -168,14 +182,14 @@ function buildRouteSource(routeFile, routeLiteral, param, specifier, root) {
168
182
 
169
183
  import { createFileRoute } from "@tanstack/react-router";
170
184
 
171
- import { createTanStackWorkflowHandler } from "@lovable.dev/workflows-sdk";
185
+ import { ${factory} } from "@lovable.dev/workflows-sdk";
172
186
 
173
187
  import workflows from "${specifier}";
174
188
 
175
189
  export const Route = createFileRoute("${routeLiteral}")({
176
190
  server: {
177
191
  handlers: {
178
- POST: createTanStackWorkflowHandler(workflows, { workflowIdParam: "${param}" }),
192
+ POST: ${factory}(workflows, { workflowIdParam: "${param}" }),
179
193
  },
180
194
  },
181
195
  });
@@ -228,12 +242,16 @@ function findAdoptedFiles(routesDir) {
228
242
  function createRouteEmitter(options) {
229
243
  const param = assertParamShape(options.workflowIdParam);
230
244
  const pathSegments = assertUrlPathShape(options.path);
231
- const routeLiteral = `/${pathSegments}/$${param}`;
232
- const routeFileName = join(...pathSegments.split("/"), `$${param}.ts`);
245
+ const base = `/${pathSegments}/$${param}`;
246
+ const surfaces = SURFACES.map((surface) => ({
247
+ ...surface,
248
+ literal: surface.segment ? `${base}/${surface.segment}` : base,
249
+ fileName: surface.segment ? join(...pathSegments.split("/"), `$${param}`, `${surface.segment}.ts`) : join(...pathSegments.split("/"), `$${param}.ts`)
250
+ }));
233
251
  let root = process.cwd();
234
252
  let entry = resolve(root, options.entry);
235
253
  let routesDir = resolve(root, options.routesDir);
236
- let routeFile = resolve(routesDir, routeFileName);
254
+ let routeFiles = surfaces.map((surface) => resolve(routesDir, surface.fileName));
237
255
  let aliases = [];
238
256
  let tsconfigPathsPlugin = false;
239
257
  return {
@@ -246,8 +264,8 @@ function createRouteEmitter(options) {
246
264
  assertContains(root, entry, `entry "${options.entry}"`);
247
265
  routesDir = resolve(root, options.routesDir);
248
266
  assertContains(root, routesDir, `routesDir "${options.routesDir}"`);
249
- routeFile = resolve(routesDir, routeFileName);
250
- assertContains(routesDir, routeFile, `path "${routeLiteral}"`);
267
+ routeFiles = surfaces.map((surface) => resolve(routesDir, surface.fileName));
268
+ routeFiles.forEach((file, index) => assertContains(routesDir, file, `path "${surfaces[index].literal}"`));
251
269
  },
252
270
  regenerate() {
253
271
  let entryExists = true;
@@ -258,11 +276,12 @@ function createRouteEmitter(options) {
258
276
  entryExists = false;
259
277
  }
260
278
  const expected = /* @__PURE__ */ new Set();
261
- if (entryExists) {
262
- expected.add(routeFile);
263
- const specifier = collectionSpecifier(routeFile, entry, aliases, tsconfigPathsPlugin);
264
- writeIfChanged(routeFile, buildRouteSource(routeFile, routeLiteral, param, specifier, root));
265
- }
279
+ if (entryExists) surfaces.forEach((surface, index) => {
280
+ const file = routeFiles[index];
281
+ expected.add(file);
282
+ const specifier = collectionSpecifier(file, entry, aliases, tsconfigPathsPlugin);
283
+ writeIfChanged(file, buildRouteSource(file, surface.literal, param, specifier, root, surface.factory));
284
+ });
266
285
  for (const file of findAdoptedFiles(routesDir)) {
267
286
  if (expected.has(file)) continue;
268
287
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/workflows-sdk",
3
- "version": "0.0.0-dev.8",
3
+ "version": "0.0.0-dev.9",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "dev",