@lovable.dev/workflows-sdk 0.0.0-dev.7 → 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
@@ -347,8 +347,8 @@ That emits `src/routes/api/public/workflows/$workflowId.ts` and serves
347
347
  that makes the route reachable also makes it anonymously reachable.
348
348
 
349
349
  The emitted file is thin — it imports the collection and mounts
350
- `createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk/stacks/tanstack`
351
- as the route's `POST` handler. All runtime logic stays in the package. The file
350
+ `createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk` as the route's
351
+ `POST` handler. All runtime logic stays in the package. The file
352
352
  carries a generated banner, which is the plugin's ownership token: it rewrites
353
353
  and deletes only files that have it, and deletes its own orphans when `path` or
354
354
  `workflowIdParam` changes. Delete the banner line to take the route over — the
@@ -362,41 +362,230 @@ the supported way to add a check of your own in front of the handler.
362
362
  | `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
363
363
  | `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
364
364
 
365
+ ### How the emitted file imports the collection
366
+
367
+ The plugin prefers an alias, so the specifier does not change when `path` moves:
368
+
369
+ ```ts
370
+ import workflows from "@/lib/workflows/index";
371
+ ```
372
+
373
+ It does not assume `@`. It reads the app's Vite `resolve.alias` and its
374
+ tsconfig `compilerOptions.paths`, and picks an alias whose target directory
375
+ contains the collection entry — preferring one both sources declare, then the
376
+ deepest match.
377
+
378
+ An alias is only emitted when the *bundler* can resolve it: a Vite
379
+ `resolve.alias` entry, or a tsconfig `paths` entry when a plugin such as
380
+ `vite-tsconfig-paths` is active. A tsconfig `paths` entry alone instructs the
381
+ typechecker and not the bundler, so emitting it would fail the build.
382
+
383
+ When no alias qualifies, the plugin falls back to a relative specifier
384
+ (`../../../lib/workflows/index`), which always resolves. An app with no alias
385
+ configured still builds; only the specifier is uglier, and its depth tracks
386
+ `path`.
387
+
365
388
  ### Calling it
366
389
 
367
- `POST /api/workflows/{workflow-id}` with a JSON body. The body is decoded by
368
- `parseWorkflowRequest`, so one route takes every traffic shape: `{ "input": ... }`
369
- starts a run, `{ "runId", "approval" }` delivers an approval decision, and
370
- `{ "runId", "signal" }` delivers a signal. A run that parks on `ctx.approve` or
371
- `ctx.waitForEvent` resumes on this same route — there is no separate resume
372
- endpoint. An unknown workflow ID returns 404, an unparseable body 400, and
373
- `{ "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.
392
+
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.
374
513
 
375
- The response is `text/event-stream`. Each engine event becomes one SSE message
376
- whose event name is the event `type` and whose data is the whole event as JSON:
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`:
377
539
 
378
540
  ```text
379
541
  event: RUN_STARTED
380
- data: {"type":"RUN_STARTED","ts":1790505539351,"runId":"run_1790505539350_yin41cp"}
542
+ data: {"type":"RUN_STARTED","ts":1790528863501,"runId":"run_1790528863501_tzqgjl8i"}
381
543
 
382
544
  event: STEP_FINISHED
383
- data: {"type":"STEP_FINISHED","ts":1790505539352,"stepId":"greeting","result":"Hello, YEHYA!"}
545
+ data: {"type":"STEP_FINISHED","ts":1790528863571,"stepId":"greeting","result":"Hello, yehya!"}
384
546
 
385
547
  event: RUN_FINISHED
386
- 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!"}}
387
549
  ```
388
550
 
389
- Run state lives in a process-local `inMemoryRunStore()`: runs are lost on restart
390
- and are invisible to other instances. Pass `runStore` to
391
- `createTanStackWorkflowHandler` to supply another one. The control-plane store is
392
- 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.
393
566
 
394
567
  The path carries no build ID. Version pinning belongs to the signed invocation,
395
- 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
396
569
  manifest. Triggers name a workflow rather than an endpoint, so firing one is a
397
- 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
398
571
  appears in the URL.
399
572
 
573
+ ## Public entry points
574
+
575
+ The package has two, and neither mirrors the source tree:
576
+
577
+ | Import | Provides |
578
+ | --- | --- |
579
+ | `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and the route handlers (`createRunHandler`, `createNextStepsHandler`, `createExecuteStepsHandler`) |
580
+ | `@lovable.dev/workflows-sdk/vite` | `workflowsPlugin`, the build-time Vite plugin |
581
+
582
+ The export map is a contract; the directory layout under `src/` is not. They are
583
+ deliberately decoupled, so the package can be reorganised without a breaking
584
+ change for apps that already have an emitted route.
585
+
586
+ The package sets `"sideEffects": false` and the handler is a plain re-export, so
587
+ a client bundle importing only authoring APIs drops the execution engine.
588
+
400
589
  ## Next PRs
401
590
 
402
591
  Connect the manifest and app code to Lovable deployment and runtime execution.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AnyWorkflowDefinition, AnyWorkflowDefinition as AnyWorkflowDefinition$1, Ctx, StepContext, StepOptions, WorkflowDefinition, WorkflowInput, WorkflowInput as WorkflowInput$1, WorkflowOutput, WorkflowState, createMiddleware, createWorkflow } from "@tanstack/workflow-core";
1
+ import { AnyWorkflowDefinition, AnyWorkflowDefinition as AnyWorkflowDefinition$1, Ctx, RunStore, StepContext, StepOptions, WorkflowDefinition, WorkflowEvent, WorkflowInput, WorkflowInput as WorkflowInput$1, WorkflowOutput, WorkflowState, createMiddleware, createWorkflow } from "@tanstack/workflow-core";
2
2
  //#region src/core/cadence.d.ts
3
3
  type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
4
4
  type Cadence = {
@@ -125,4 +125,114 @@ interface WorkflowManifest {
125
125
  }
126
126
  declare function generateManifests(definition: WorkflowsDefinition): Promise<WorkflowManifest[]>;
127
127
  //#endregion
128
- export { type AnyWorkflowDefinition, type Cadence, type Ctx, type OverlapPolicy, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type StepContext, type StepOptions, type TriggerDefinition, type Weekday, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createMiddleware, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, weekly };
128
+ //#region src/stacks/tanstack/handlers.d.ts
129
+ /** The shape `registerWorkflows()` returns; only the list is needed to dispatch. */
130
+ interface WorkflowCollection {
131
+ readonly workflows: readonly AnyWorkflowDefinition$1[];
132
+ }
133
+ interface TanStackWorkflowHandlerOptions {
134
+ /** @default a process-local `inMemoryRunStore()`, lost on restart */
135
+ runStore?: RunStore;
136
+ /**
137
+ * Route parameter carrying the workflow ID.
138
+ * @default "workflowId"
139
+ */
140
+ workflowIdParam?: string;
141
+ }
142
+ interface TanStackRouteCtx {
143
+ request: Request;
144
+ params?: Record<string, string | undefined>;
145
+ }
146
+ type TanStackWorkflowHandler = (ctx: TanStackRouteCtx) => Promise<Response>;
147
+ /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
148
+ declare function createTanStackWorkflowHandler(collection: WorkflowCollection, options?: TanStackWorkflowHandlerOptions): TanStackWorkflowHandler;
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
170
+ //#region src/stacks/tanstack/sse.d.ts
171
+ /**
172
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
173
+ * engine `type` as the SSE event name and its whole JSON as the data line.
174
+ */
175
+ declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
176
+ //#endregion
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 };