@lovable.dev/workflows-sdk 0.0.0-dev.1 → 0.0.0-dev.11

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
@@ -15,11 +15,11 @@ from [`@tanstack/workflow-core`](https://github.com/TanStack/workflow).
15
15
  Schema validation libraries implementing Standard Schema, such as Zod, provide
16
16
  input and output inference.
17
17
 
18
- Keep the app's workflow collection in `app/workflows/index.ts`. Each workflow
19
- lives in `app/workflows/{workflow-name}/index.ts`, with its helpers alongside it:
18
+ Keep the app's workflow collection in `src/lib/workflows/index.ts`. Each workflow
19
+ lives in `src/lib/workflows/{workflow-name}/index.ts`, with its helpers alongside it:
20
20
 
21
21
  ```text
22
- app/workflows/
22
+ src/lib/workflows/
23
23
  ├── index.ts
24
24
  └── greet/
25
25
  ├── index.ts
@@ -43,40 +43,202 @@ names. An empty collection is valid. Registration copies the list, retains the
43
43
  definitions, and does not execute handlers or register global state. Treat
44
44
  definitions as immutable after registration.
45
45
 
46
- See [the authoring example](examples/workflows.ts) for schemas, typed middleware,
47
- and a durable step. The package typecheck includes this example.
46
+ See [the authoring example](examples/src/lib/workflows/greet/index.ts) for schemas,
47
+ typed middleware, and a durable step. The package typecheck includes this example.
48
+
49
+ ## Triggers
50
+
51
+ A workflow runs when something triggers it, and a schedule is the first kind of
52
+ trigger: a clock. Triggers go in `registerWorkflows({ workflows, triggers })`,
53
+ and each carries a `type` naming its kind. Webhook and app-event triggers will
54
+ join the same array.
55
+
56
+ A schedule's *cadence* is how often the clock fires. `hourly()`, `daily()`,
57
+ and `weekly()` build one; there is no raw cron.
48
58
 
49
59
  ## Schedules
50
60
 
51
- Declare a schedule with `defineSchedule({ id, workflow, cron, timeZone, input })`
52
- and include it in `registerWorkflows({ workflows, schedules })`. `workflow` refers
53
- to the same definition object included in `workflows`; `input` is required and
54
- inferred from that workflow. Multiple schedules can target one workflow.
61
+ Declare a schedule with `defineSchedule({ id, workflow, cadence, timeZone, input })` and
62
+ include it in `registerWorkflows({ workflows, triggers })`. `workflow` refers to
63
+ the same definition object included in `workflows`; `input` is required and
64
+ inferred from that workflow. Multiple schedules can target one workflow. Schedule
65
+ IDs must be unique within the app's collection. This API declares schedules but
66
+ does not install timers or start runs.
55
67
 
56
- Use a five-field cron expression (minute, hour, day, month, weekday) and an IANA
57
- time zone; the default is UTC. Schedule IDs must be unique within the app's
58
- collection. Registration checks field count and time zone; cron syntax and
59
- calendar semantics remain the engine's responsibility. This API declares
60
- schedules but does not install timers or start runs. Periodic intervals,
61
- catch-up, and overlap policies remain follow-ups.
68
+ ```ts
69
+ import { daily, defineSchedule, hourly, weekly } from "@lovable.dev/workflows-sdk";
70
+
71
+ defineSchedule({ id: "sweep", workflow: sync, cadence: hourly(), timeZone: "UTC", input: {} });
72
+ defineSchedule({ id: "digest", workflow: digest, cadence: daily(), timeZone: "Europe/Stockholm", input: {} });
73
+
74
+ defineSchedule({
75
+ id: "refresh",
76
+ workflow: sync,
77
+ cadence: daily({ at: [0, 6, 12, 18] }),
78
+ timeZone: "UTC",
79
+ input: {},
80
+ });
81
+
82
+ defineSchedule({
83
+ id: "weekday-digest",
84
+ workflow: digest,
85
+ cadence: daily({ at: 9, days: ["mon", "tue", "wed", "thu", "fri"] }),
86
+ timeZone: "America/New_York",
87
+ input: {},
88
+ });
89
+
90
+ defineSchedule({
91
+ id: "monday-report",
92
+ workflow: report,
93
+ cadence: weekly({ on: "monday", at: 7 }),
94
+ timeZone: "Europe/Stockholm",
95
+ input: {},
96
+ });
97
+ ```
62
98
 
63
- The [example](examples/workflows.ts) declares a daily greeting at 09:00 in
64
- Europe/Stockholm with static workflow input.
99
+ | Field | Default | Meaning |
100
+ | --- | --- | --- |
101
+ | `cadence` | — | `hourly()`, `daily()`, or `weekly()` |
102
+ | `timeZone` | — | IANA region name the cadence is interpreted in |
103
+ | `overlapPolicy` | `"skip"` | `skip`, `allow`, or `buffer-one` |
104
+ | `enabled` | `true` | `false` declares a paused schedule without deleting it |
105
+
106
+ There are three cadences and no raw cron:
107
+
108
+ | Cadence | Says | Example |
109
+ | --- | --- | --- |
110
+ | `hourly()` | once an hour | `hourly()` |
111
+ | `daily({ at, days })` | hours of the day, days of the week | `daily({ at: [0, 6, 12, 18] })` |
112
+ | `weekly({ on, at })` | one weekday, hours of the day | `weekly({ on: "monday", at: 7 })` |
113
+
114
+ **The SDK never derives a cron.** The manifest carries the cadence, and the
115
+ `app-workflows-service` backend translates it when it registers the schedule.
116
+ An app declares intent; one service owns the translation, so there is no second
117
+ implementation to drift. Every cadence here is shaped to be exactly
118
+ translatable — that constraint is why the vocabulary is closed and why `at` is
119
+ whole hours.
120
+
121
+ ### Hours, never minutes
122
+
123
+ `at` is a whole hour, `0` through `23`, or a list of them. There is no minute:
124
+ an app says *which hours*, and the platform picks where inside the hour a run
125
+ actually starts (see [Timing](#timing)). `hourly()` takes no options for the
126
+ same reason. An app that could pin a minute would opt itself out of the smear,
127
+ and the herd would come back.
128
+
129
+ This is also what keeps the vocabulary exactly translatable by the backend.
130
+ Cron pairs every value in its minute field with every value in its hour field,
131
+ so a cadence that could say 09:15 and 17:45 has no faithful cron — it would
132
+ become `15,45 9,17 * * *` and fire four times a day instead of twice. With the
133
+ minute fixed, any set of hours translates exactly.
134
+
135
+ `at` accepts a list, so several runs a day need one schedule rather than
136
+ several: `daily({ at: [0, 6, 12, 18] })` is four evenly spaced runs, and
137
+ `daily({ at: [9, 17] })` is two uneven ones — the start and end of a working
138
+ day, which no fixed interval can express. The list is sorted and deduplicated,
139
+ so two orderings are one schedule.
140
+
141
+ ### One schedule, one representation
142
+
143
+ `weekly({ on, at })` is the single-day shorthand for `daily({ at, days: [on] })`
144
+ and resolves into exactly that cadence. There is one internal representation of
145
+ a day-restricted schedule, so the two spellings emit byte-identical manifests
146
+ and hash alike.
147
+
148
+ There is no `"weekdays"` or `"weekends"` shorthand: it would add a third
149
+ spelling of a set `days` already states, and "the weekend" is Friday and
150
+ Saturday in much of the world, so the word would quietly mean the wrong days.
151
+
152
+ There is no interval cadence — no `every("6h")`, no `every("3d")`. Intervals
153
+ are not calendar positions and have no faithful cron: `0 0 */3 * *` restarts its
154
+ count every month, so it means "every 3 days" only until the 28th and then fires
155
+ twice in two days. The sub-daily intervals that *are* faithful are exactly the
156
+ ones `daily({ at })` already covers, and `daily({ at: [0, 6, 12, 18] })` says the
157
+ same thing as "every 6 hours" while staying anchored to the calendar and to the
158
+ app's time zone.
159
+
160
+ ## Timing
161
+
162
+ **A declared hour is approximate, and an app does not control how approximate.**
163
+ Tens of thousands of apps declaring `daily()` must not fire in the same minute,
164
+ so the platform spreads each schedule over a window — a *smear* — and then keeps
165
+ that schedule on the same offset for every later run.
166
+
167
+ Apps do not declare the smear, and there is no field for it. The platform
168
+ derives the window per schedule from the cadence, so what an app leaves
169
+ unspecified is exactly what the platform is free to choose:
170
+
171
+ | Cadence | Smeared across |
172
+ | --- | --- |
173
+ | `daily()` | the whole day |
174
+ | `daily({ at })`, `weekly({ on, at })` | a window around each declared hour |
175
+ | `hourly()` | the hour |
176
+
177
+ Higher plans get tighter windows, so a declared 07:00 lands nearer to 07:00 the
178
+ more an app pays; the exact windows belong to the platform and can change
179
+ without an SDK release.
180
+
181
+ Two consequences worth designing around. A schedule that must run at an exact
182
+ instant is not expressible, by design. And the offset is stable per schedule,
183
+ not random per run, so a report that reads "yesterday's rows" reads the same
184
+ shape every day.
185
+
186
+ Neither the smear nor the schedule itself runs yet; see
187
+ [Next PRs](#next-prs).
188
+
189
+ ### Time zone
190
+
191
+ `timeZone` is required on every schedule. There is no default, because every
192
+ available default is wrong: `daily({ at: 9 })` in UTC is not the 09:00 a reader
193
+ of the digest expects, and the build machine's own zone would make one app
194
+ source fire at different times depending on where it was built.
195
+
196
+ It must be `"UTC"` or a canonical IANA name as `Intl.supportedValuesOf("timeZone")`
197
+ lists it, such as `"Europe/Stockholm"`. That rejects the fixed-offset family
198
+ `Intl` otherwise accepts — `"+05:00"`, `"-0800"`, `"EST"`, `"GMT"`,
199
+ `"Etc/GMT+5"` — none of which observe daylight saving, so `"EST"` is an hour
200
+ off US Eastern for two-thirds of the year, and `"Etc/GMT+5"` is UTC-5 rather
201
+ than UTC+5. It also rejects tzdata's backward-compatibility aliases such as
202
+ `"US/Pacific"`; write the canonical `"America/Los_Angeles"`, so one zone has
203
+ one spelling and one manifest.
204
+
205
+ ### Overlap policy
206
+
207
+ `overlapPolicy` says what happens when an occurrence comes due while the
208
+ previous run is still going: `skip` drops it, `allow` lets runs overlap, and
209
+ `buffer-one` holds the earliest due occurrence and fires it once the in-flight
210
+ run finishes.
211
+
212
+ ### Validation
213
+
214
+ Everything is validated when the schedule is defined, at build time: an hour
215
+ outside `0`-`23`, a fractional hour, a weekday name that is not a weekday, an
216
+ unknown `overlapPolicy`, a missing or non-canonical zone, and a hand-written
217
+ cadence object no constructor produced all fail the build. `registerWorkflows`
218
+ likewise rejects any key other than `workflows` and `triggers`, so a collection
219
+ left on the old `schedules:` name fails the build instead of emitting an empty
220
+ manifest.
221
+
222
+ The [example](examples/src/lib/workflows/index.ts) declares a 09:00 greeting in
223
+ Europe/Stockholm, a weekday greeting in America/New_York, a Monday report, a
224
+ four-times-daily refresh, an hourly sweep, and a paused daily digest.
65
225
 
66
226
  ## Manifest generation
67
227
 
68
- Add `workflowsManifest({ entry: "app/workflows/index.ts" })` from
69
- `@lovable.dev/workflows-sdk/vite` to the app's Vite plugins. The entry must
70
- default-export its `registerWorkflows()` collection. Each production build writes
228
+ Add `workflowsPlugin()` from `@lovable.dev/workflows-sdk/vite` to the app's Vite
229
+ plugins. Its `entry` defaults to `src/lib/workflows/index.ts` and must
230
+ default-export the app's `registerWorkflows()` collection. Each production build writes
71
231
  one manifest per workflow to `.lovable/workflows/{workflow-name}.json` relative
72
232
  to the app root. For example, `greet` produces `.lovable/workflows/greet.json`.
73
233
  Generation errors fail the build. See [the Vite example](examples/vite.config.ts).
74
234
 
75
235
  Each version-1 manifest contains a single `workflow` with its ID, description,
76
236
  version, and input/output/state JSON Schemas, a `graph` for visualization, and a
77
- `schedules` array containing only that workflow's schedules and static inputs. It is an SDK discovery format,
78
- not the engine's deployment or execution contract. Handlers and middleware stay
79
- in app code. Schedule IDs and JSON object keys are sorted for stable output.
237
+ `triggers` array containing only that workflow's triggers and static inputs. Each
238
+ entry names its kind in `type` — `"schedule"` today — and a schedule entry carries
239
+ its `cadence`, `timeZone`, `enabled`, `overlapPolicy`, and `input`. It is an SDK discovery format, not the engine's deployment or execution
240
+ contract. Handlers and middleware stay in app code. Triggers and JSON object keys
241
+ are sorted for stable output.
80
242
 
81
243
  The SDK manages the JSON files in `.lovable/workflows/`. Successful generation
82
244
  removes manifests for deleted or renamed workflows; an empty collection removes
@@ -103,6 +265,12 @@ synchronizing the returned manifests to `.lovable/workflows/` a required build s
103
265
 
104
266
  Each manifest's `graph` contains `nodes` and directed `edges`. The SDK parses the
105
267
  handler's function source without executing it. No additional registration is needed.
268
+
269
+ Graph inference reads the app's own `typescript`, an optional peer. Apps built
270
+ from a Lovable template already have it. Without it — or with a copy exposing no
271
+ stable JS API, as TypeScript 7 does before 7.1 — the build still succeeds and
272
+ every graph carries one `unknown` node and the diagnostic
273
+ `Install typescript to infer step graphs`.
106
274
  Sequential awaited `ctx.step("name", callback)` calls produce order edges;
107
275
  `await Promise.all([ctx.step(...), ctx.step(...)])` produces parallel branches
108
276
  that join at the next step. Returned step promises work too. Keep step IDs literal.
@@ -130,25 +298,336 @@ unsupported code are not expanded. The UI should show these unknown nodes and
130
298
  mark partial graphs. Transforms that rewrite the handler may also produce a
131
299
  partial graph. A handler with no steps can have an empty graph.
132
300
 
301
+ ## Run endpoint (TanStack Start)
302
+
303
+ The same `workflowsPlugin` that writes the manifests also emits one dynamic
304
+ route, `src/routes/api/workflows/$workflowId.ts`, serving every registered
305
+ workflow. There is no opt-in: a declared workflow with no endpoint cannot run.
306
+ One plugin and one `entry` cover both, so a manifest can never describe a
307
+ collection the route does not serve:
308
+
309
+ ```ts
310
+ import { tanstackStart } from "@tanstack/react-start/plugin/vite";
311
+ import { workflowsPlugin } from "@lovable.dev/workflows-sdk/vite";
312
+
313
+ export default defineConfig({
314
+ plugins: [workflowsPlugin(), tanstackStart()],
315
+ });
316
+ ```
317
+
318
+ A missing `entry` file is the only thing that suppresses the route: an app with
319
+ no collection gets no endpoint.
320
+
321
+ ### The route is unauthenticated
322
+
323
+ **Any caller who reaches the route can run any declared workflow.** The SDK
324
+ ships no request authentication today; signed invocation is the next piece of
325
+ work on this endpoint. Until it lands, treat the endpoint as public and keep
326
+ anything a stranger must not trigger — spend, mutation of another user's data,
327
+ outbound mail — out of a declared workflow, or guard it inside the handler.
328
+
329
+ Reachability is the lever an app has in the meantime. Public apps expose the
330
+ route to the internet. Workspace and private apps are gated by the Lovable host,
331
+ which is why `path` matters (below).
332
+
333
+ ### Relocating the route with `path`
334
+
335
+ `path` sets the URL prefix; the workflow ID is appended as a dynamic segment,
336
+ and the emitted file name follows the path. Workspace and private apps reach
337
+ anonymous traffic only under an `/api/public` prefix — everything else is
338
+ blocked by the host before it reaches the app — so those projects must move the
339
+ route there for it to be reachable at all:
340
+
341
+ ```ts
342
+ workflowsPlugin({ path: "/api/public/workflows" });
343
+ ```
344
+
345
+ That emits `src/routes/api/public/workflows/$workflowId.ts` and serves
346
+ `POST /api/public/workflows/{workflow-id}`. The trade is explicit: the prefix
347
+ that makes the route reachable also makes it anonymously reachable.
348
+
349
+ The emitted file is thin — it imports the collection and mounts
350
+ `createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk` as the route's
351
+ `POST` handler. All runtime logic stays in the package. The file
352
+ carries a generated banner, which is the plugin's ownership token: it rewrites
353
+ and deletes only files that have it, and deletes its own orphans when `path` or
354
+ `workflowIdParam` changes. Delete the banner line to take the route over — the
355
+ plugin then leaves that file alone, and the build keeps working. That is also
356
+ the supported way to add a check of your own in front of the handler.
357
+
358
+ | Option | Default | Meaning |
359
+ | --- | --- | --- |
360
+ | `entry` | `src/lib/workflows/index.ts` | Collection entry; a missing file means no route |
361
+ | `routesDir` | `src/routes` | Where the route file is written |
362
+ | `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
363
+ | `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
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
+
388
+ ### Calling it
389
+
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
+ **A repeated operation needs an explicit id — and the build says so.** `ctx.now()`, `ctx.uuid()`,
437
+ `ctx.sleep(ms)` and friends fall back to a default id, and two calls sharing
438
+ one cannot be told apart on replay, so the second is refused. Pass `{ id }` per
439
+ call site: `ctx.now({ id: "started" })`. `ctx.step("id", …)` always has an
440
+ explicit id, so repeating one in a loop is fine.
441
+
442
+ Manifest generation rejects this before a run exists, when the arguments are
443
+ literal:
444
+
445
+ ```text
446
+ workflow "greet" calls ctx.now() 2 times with the default id "now";
447
+ replay cannot tell them apart, so pass an explicit { id } per call site
448
+ ```
449
+
450
+ The same applies to two `ctx.sleep(1000)` calls, two waits on one event name,
451
+ or two approvals with one title — the default id is derived from the argument,
452
+ so only a repeated argument collides. A dynamic argument cannot be read at
453
+ build time and is left to the runtime check.
454
+
455
+ **Handler code outside a step runs on every call.** Keep side effects inside
456
+ `ctx.step`, which is memoized; a bare `fetch` in the handler body repeats each
457
+ pass. A pass also allows only a bounded amount of such work — 5s by default —
458
+ before reporting the run stalled.
459
+
460
+ ### The memo is unauthenticated input
461
+
462
+ **A caller supplies the memo, and the route does not authenticate it.** Anything
463
+ the memo says is already settled is taken as settled, including an approval's
464
+ decision. A caller who can reach the route can therefore hand back
465
+ `{"kind": "approve", "status": "completed", "result": {"approved": true}}` and
466
+ skip the human, or mark an expensive step completed with a fabricated result and
467
+ skip the work. `inputHash` binds a memo to one input, so a forged memo cannot be
468
+ replayed against a different record, but it is computed from the request and so
469
+ is no barrier on its own.
470
+
471
+ Until signed invocation lands, **do not treat `ctx.approve` as a security
472
+ boundary on these routes**, and do not put an operation behind one that a
473
+ stranger must not be able to declare done. Reachability is the only control an
474
+ app has in the meantime; see `path` above.
475
+
476
+ ### Stepping through a run
477
+
478
+ ```bash
479
+ POST /api/workflows/greet/nextSteps
480
+ { "input": { "name": "yehya" } }
481
+ -> { "status": "pending", "memo": [], "steps": [{ "seq": 0, "stepId": "greeting", "kind": "step" }] }
482
+
483
+ POST /api/workflows/greet/executeSteps
484
+ { "input": { "name": "yehya" }, "memo": [], "steps": [{ "stepId": "greeting" }] }
485
+ -> { "status": "pending",
486
+ "results": [{ "seq": 0, "stepId": "greeting", "status": "completed", "result": "Hello, yehya!" }],
487
+ "memo": [{ "seq": 0, "stepId": "greeting", ... }],
488
+ "steps": [{ "seq": 1, "stepId": "shout", "kind": "step" }] }
489
+ ```
490
+
491
+ Send the returned `memo` back each time; the run ends with
492
+ `{"status": "completed", "output": ...}`. Omitting `steps` on `executeSteps`
493
+ runs whatever `nextSteps` would report, so the run advances one wave per call.
494
+
495
+ ### Driving a run from an orchestrator
496
+
497
+ **Loop on `executeSteps` alone, with `steps` omitted.** One response carries the
498
+ results, the updated `memo`, *and* the operations now pending, so a driver never
499
+ needs a separate `nextSteps` call:
500
+
501
+ ```jsonc
502
+ // POST /api/workflows/greet/executeSteps { "input": {...} }
503
+ { "status": "pending",
504
+ "results": [{ "stepId": "greeting", "occurrence": 0, "kind": "step", "status": "completed", "result": "Hello, yehya!" }],
505
+ "steps": [{ "stepId": "shout", "occurrence": 0, "kind": "step" }],
506
+ "memo": [{ "stepId": "greeting", "occurrence": 0, ... }],
507
+ "inputHash": "9f2c…" }
508
+ ```
509
+
510
+ That is one HTTP call and one replay per wave — the cheapest shape, and the one
511
+ to use when a remote orchestrator drives the app. Pairing `nextSteps` with
512
+ `executeSteps` doubles both: use it when something needs to *see* what would run
513
+ before it runs, such as a UI preview or an approval gate.
514
+
515
+ Concurrent steps settle together: `Promise.all([ctx.step("a"), ctx.step("b")])`
516
+ is one wave, and a step after the join is the next.
517
+
518
+ Keep a step's result small: it travels in the memo on every later call, so a
519
+ large payload is resent for the rest of the run. Write bulk data to storage
520
+ inside the step and return the key.
521
+
522
+ **Replay cost.** Each pass re-runs the handler from the top, so code outside
523
+ `ctx.step` executes once per wave — for an 8-step workflow, 8 times through a
524
+ `executeSteps` loop and 16 through a `nextSteps` + `executeSteps` one. Step
525
+ bodies run exactly once each. This is why side effects belong inside a step.
526
+
527
+ `nextSteps` reports a step's `stepId` and `kind` but **not its input**:
528
+ `ctx.step(id, fn)` closes over its arguments rather than declaring them, so the
529
+ input is not knowable without running `fn`. Deterministic values (`ctx.now`,
530
+ `ctx.uuid`) are the exception to the no-side-effects rule — `nextSteps` pins them
531
+ and returns them in `memo`, so a later `executeSteps` replays the same values.
532
+
533
+ ### Waiting on something outside the app
534
+
535
+ `ctx.sleep`, `ctx.waitForEvent` and `ctx.approve` cannot be settled by the app,
536
+ so they are never executed — they come back as pending operations carrying what
537
+ a caller needs to resolve them:
538
+
539
+ ```json
540
+ { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
541
+ "config": { "title": "Approve refund", "description": "refund of $40" } }
542
+ ```
543
+
544
+ The run surface emits `RUN_PAUSED` with that list and the memo, then ends the
545
+ request rather than holding a connection open. Resume by appending the decision
546
+ to the memo and calling again:
547
+
548
+ ```jsonc
549
+ { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
550
+ "status": "completed", "result": { "approved": true, "approvalId": "apr_1" } }
551
+ ```
552
+
553
+ ### The run surface
554
+
555
+ `POST /api/workflows/{workflow-id}` with `{ "input": ... }` starts a run and
556
+ `{ "memo": [...] }` continues one. The response is `text/event-stream`, one SSE
557
+ message per event, the event name being its `type`:
558
+
559
+ ```text
560
+ event: RUN_STARTED
561
+ data: {"type":"RUN_STARTED","ts":1790528863501,"runId":"run_1790528863501_tzqgjl8i"}
562
+
563
+ event: STEP_FINISHED
564
+ data: {"type":"STEP_FINISHED","ts":1790528863571,"stepId":"greeting","result":"Hello, yehya!"}
565
+
566
+ event: RUN_FINISHED
567
+ data: {"type":"RUN_FINISHED","ts":1790528863685,"runId":"...","output":{"message":"Hello, yehya!"}}
568
+ ```
569
+
570
+ It drives the memo loop internally for the length of one request, so it holds no
571
+ state between requests either. `RUN_FINISHED`, `RUN_ERRORED` and `RUN_PAUSED` all carry the
572
+ memo, so a caller that only sent an input still holds what already ran and a
573
+ retry does not repeat it.
574
+
575
+ `createTanStackWorkflowHandler` is still exported for the engine-backed path
576
+ (`runWorkflow` plus a `RunStore`, `inMemoryRunStore()` by default). No emitted
577
+ route uses it: a process-local store loses runs on restart and is invisible to
578
+ other instances, which is what the memo model replaces.
579
+
580
+ ### Not yet carried over
581
+
582
+ `ctx.step`'s `retries` and `timeout` options are accepted and ignored — the
583
+ caller decides whether to re-issue a failed step. Step retry, timeouts, and
584
+ `previousVersions` routing are follow-ups.
585
+
586
+ The path carries no build ID. Version pinning belongs to the signed invocation,
587
+ which leaves these paths stable across deployments and safe to publish in a
588
+ manifest. Triggers name a workflow rather than an endpoint, so firing one is a
589
+ POST to that workflow's run path with the trigger's input; no trigger identifier
590
+ appears in the URL.
591
+
592
+ ## Public entry points
593
+
594
+ The package has two, and neither mirrors the source tree:
595
+
596
+ | Import | Provides |
597
+ | --- | --- |
598
+ | `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and the route handlers (`createRunHandler`, `createNextStepsHandler`, `createExecuteStepsHandler`) |
599
+ | `@lovable.dev/workflows-sdk/vite` | `workflowsPlugin`, the build-time Vite plugin |
600
+
601
+ The export map is a contract; the directory layout under `src/` is not. They are
602
+ deliberately decoupled, so the package can be reorganised without a breaking
603
+ change for apps that already have an emitted route.
604
+
605
+ The package sets `"sideEffects": false` and the handler is a plain re-export, so
606
+ a client bundle importing only authoring APIs drops the execution engine.
607
+
133
608
  ## Next PRs
134
609
 
135
610
  Connect the manifest and app code to Lovable deployment and runtime execution.
136
- Define support for TanStack primitives, version routing, and schedule policies.
611
+ Derive and apply the per-schedule smear on the control plane. Define support for
612
+ TanStack primitives, version routing, and schedule policies.
613
+ Add webhook and app-event triggers to the same `triggers` array.
137
614
 
138
615
  ## Publishing dev builds
139
616
 
140
617
  The [publishing workflow](../../.github/workflows/publish-workflows-sdk.yml)
141
- publishes the version committed in `package.json` to npm's `dev` tag when SDK
618
+ publishes the version committed in `package.json` to npm's `latest` tag when SDK
142
619
  changes land on `main`. Manage versions manually: `0.0.0-dev`, `0.0.0-dev.1`,
143
620
  `0.0.0-dev.2`, and so on. The workflow rejects versions outside this series and
144
621
  skips versions already published. Manual runs default to a dry run.
145
622
  See [the setup guide](PUBLISHING.md) for the
146
623
  one-time bootstrap and npm trusted-publisher configuration.
147
624
 
148
- Install a published build with `npm install @lovable.dev/workflows-sdk@dev`,
149
- or pin the exact version shown in the workflow run's summary.
625
+ Install the newest build with `npm install @lovable.dev/workflows-sdk`, or pin
626
+ the exact version shown in the workflow run's summary. `latest` tracks every dev
627
+ publish while the SDK is pre-1.0; the older `dev` tag is frozen at `0.0.0-dev.2`.
150
628
 
151
- The existing internal [`@lovable/workflow-sdk`](../../packages/workflow-sdk)
629
+ The engine's embedded SDK
630
+ ([`sdk_embed/index.ts`](../../go/workflows/services/workflows/internal/bundler/sdk_embed/index.ts))
152
631
  provides the engine contract. Use [`mcp-js`](../lovable-mcp-js) as the reference
153
632
  for separating authoring, manifest extraction, and framework integration. The
154
633
  workflow prototype's `ts/workflow-sdk` supplies adapter and manifest examples.