@lovable.dev/workflows-sdk 0.0.0-dev.23 → 0.0.0-dev.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +75 -641
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,33 +1,23 @@
1
1
  # @lovable.dev/workflows-sdk
2
2
 
3
- Author workflows with TanStack workflow-core and register them in an explicit
4
- collection for Lovable. This development SDK generates build manifests; execution
5
- and schedule installation on Lovable are not implemented yet.
3
+ Experimental SDK for authoring workflows in Lovable apps with
4
+ [`@tanstack/workflow-core`](https://github.com/TanStack/workflow). Releases stay
5
+ in the `0.0.0-dev` series and may change without compatibility guarantees.
6
6
 
7
- Experimental: every release stays in the `0.0.0-dev` series. The API may
8
- change without compatibility guarantees; this SDK is not production-ready.
7
+ ## Install
9
8
 
10
- ## Authoring
9
+ ```sh
10
+ npm install @lovable.dev/workflows-sdk
11
+ ```
12
+
13
+ ## Define workflows
11
14
 
12
15
  Use `createWorkflow({ id, input, output }).handler(...)` to define a workflow
13
- and `createMiddleware` to extend its typed context. Both builders come directly
14
- from [`@tanstack/workflow-core`](https://github.com/TanStack/workflow).
15
- Schema validation libraries implementing Standard Schema, such as Zod, provide
16
- input and output inference.
17
-
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
-
21
- ```text
22
- src/lib/workflows/
23
- ├── index.ts
24
- └── greet/
25
- ├── index.ts
26
- └── helpers.ts
27
- ```
16
+ and `createMiddleware` to extend its typed context. Standard Schema libraries
17
+ such as Zod provide input and output inference.
28
18
 
29
- Each workflow's `index.ts` exports its definition. The collection entry imports
30
- all workflow definitions and default-exports `registerWorkflows(...)`:
19
+ Keep definitions under `src/lib/workflows/{workflow-name}/` and default-export
20
+ one collection from `src/lib/workflows/index.ts`:
31
21
 
32
22
  ```ts
33
23
  import { registerWorkflows } from "@lovable.dev/workflows-sdk";
@@ -36,19 +26,14 @@ import { greet } from "./greet";
36
26
  export default registerWorkflows({ workflows: [greet] });
37
27
  ```
38
28
 
39
- The `id` passed to `createWorkflow` is its app-wide unique name and should match
40
- its folder name. Names contain 1–128 lowercase letters, digits, hyphens, or
41
- underscores, starting with a letter or digit. The app collection rejects duplicate
42
- names. An empty collection is valid. Registration copies the list, retains the
43
- definitions, and does not execute handlers or register global state. Treat
44
- definitions as immutable after registration.
29
+ Workflow IDs contain 1–128 lowercase letters, digits, hyphens, or underscores,
30
+ starting with a letter or digit. They must be unique within the collection.
31
+ See the [authoring example](examples/src/lib/workflows/greet/index.ts) for
32
+ schemas, typed middleware, and a durable step.
45
33
 
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.
34
+ ## Durable operations
48
35
 
49
- Every durable operation needs a static, user-facing description. Lovable's
50
- agent supplies this text so the workflow UI can explain each operation before
51
- and during a run. Put it in the operation's options:
36
+ Every durable operation needs a static, user-facing description:
52
37
 
53
38
  | Operation | Description field |
54
39
  | --- | --- |
@@ -64,273 +49,35 @@ await ctx.step("load-customer", () => loadCustomer(ctx.input.customerId), {
64
49
  });
65
50
  ```
66
51
 
67
- Manifest generation rejects a missing or computed description. A step declared
68
- inside a loop or callback also needs a group with a stable ID and user-facing
69
- label. The group identifies the repeated callsite while each runtime step keeps
70
- its own concrete ID:
71
-
72
- ```ts
73
- await Promise.all(
74
- ctx.input.items.map((item) =>
75
- ctx.step(`process-${item.id}`, () => processItem(item), {
76
- meta: {
77
- description: "Process an item",
78
- group: { id: "process-items", label: "Process items" },
79
- },
80
- }),
81
- ),
82
- );
83
- ```
84
-
85
- Group IDs are unique per workflow callsite. Ordinary sequential steps and
86
- fixed `Promise.all([stepA, stepB])` branches do not need a group. For dynamic
87
- sequential work, await one step directly as the only statement in a `for...of`
88
- loop. For dynamic parallel work, use the mapped `Promise.all()` form above;
89
- manifest generation rejects loops that collect step promises for a later
90
- `Promise.all()`.
91
-
92
- ## Triggers
52
+ Step IDs must be unique within a workflow. Keep side effects inside step bodies;
53
+ handler code outside a step may run more than once. A step body is one atomic
54
+ execution unit and cannot contain another durable operation.
93
55
 
94
- A workflow runs when something triggers it, and a schedule is the first kind of
95
- trigger: a clock. Triggers go in `registerWorkflows({ workflows, triggers })`,
96
- and each carries a `type` naming its kind. Webhook and app-event triggers will
97
- join the same array.
56
+ Keep durable control flow in the workflow handler. Do not pass, alias,
57
+ destructure, or return `ctx`, and do not detach methods such as `ctx.step`.
58
+ Pass extracted data such as `ctx.input.customerId` to helpers instead.
98
59
 
99
- A schedule's *cadence* is how often the clock fires. `hourly()`, `daily()`,
100
- and `weekly()` build one; there is no raw cron.
101
-
102
- ## Schedules
60
+ ### Repeated steps
103
61
 
104
- Declare a schedule with `defineSchedule({ id, workflow, cadence, timeZone, input })` and
105
- include it in `registerWorkflows({ workflows, triggers })`. `workflow` refers to
106
- the same definition object included in `workflows`; `input` is required and
107
- inferred from that workflow. Multiple schedules can target one workflow. Schedule
108
- IDs must be unique within the app's collection. This API declares schedules but
109
- does not install timers or start runs.
62
+ A step inside a loop or callback needs `meta.group` with a stable ID and
63
+ user-facing label. Each repeated step still needs its own dynamic ID:
110
64
 
111
65
  ```ts
112
- import { daily, defineSchedule, hourly, weekly } from "@lovable.dev/workflows-sdk";
113
-
114
- defineSchedule({ id: "sweep", workflow: sync, cadence: hourly(), timeZone: "UTC", input: {} });
115
- defineSchedule({ id: "digest", workflow: digest, cadence: daily(), timeZone: "Europe/Stockholm", input: {} });
116
-
117
- defineSchedule({
118
- id: "refresh",
119
- workflow: sync,
120
- cadence: daily({ at: [0, 6, 12, 18] }),
121
- timeZone: "UTC",
122
- input: {},
123
- });
124
-
125
- defineSchedule({
126
- id: "weekday-digest",
127
- workflow: digest,
128
- cadence: daily({ at: 9, days: ["mon", "tue", "wed", "thu", "fri"] }),
129
- timeZone: "America/New_York",
130
- input: {},
131
- });
132
-
133
- defineSchedule({
134
- id: "monday-report",
135
- workflow: report,
136
- cadence: weekly({ on: "monday", at: 7 }),
137
- timeZone: "Europe/Stockholm",
138
- input: {},
66
+ ctx.step(`process-${item.id}`, () => processItem(item), {
67
+ meta: { description: "Process an item", group: { id: "process-items", label: "Process items" } },
139
68
  });
140
69
  ```
141
70
 
142
- | Field | Default | Meaning |
143
- | --- | --- | --- |
144
- | `cadence` | — | `hourly()`, `daily()`, or `weekly()` |
145
- | `timeZone` | — | IANA region name the cadence is interpreted in |
146
- | `overlapPolicy` | `"skip"` | `skip`, `allow`, or `buffer-one` |
147
- | `enabled` | `true` | `false` declares a paused schedule without deleting it |
71
+ For dynamic sequential work, await one step directly as the only statement in
72
+ a `for...of` loop. For dynamic parallel work, use a mapped `Promise.all()`.
73
+ Fixed `Promise.all([stepA, stepB])` branches and ordinary sequential steps do
74
+ not need a group.
148
75
 
149
- There are three cadences and no raw cron:
76
+ ### Conditional steps
150
77
 
151
- | Cadence | Says | Example |
152
- | --- | --- | --- |
153
- | `hourly()` | once an hour | `hourly()` |
154
- | `daily({ at, days })` | hours of the day, days of the week | `daily({ at: [0, 6, 12, 18] })` |
155
- | `weekly({ on, at })` | one weekday, hours of the day | `weekly({ on: "monday", at: 7 })` |
156
-
157
- **The SDK never derives a cron.** The manifest carries the cadence, and the
158
- `app-workflows-service` backend translates it when it registers the schedule.
159
- An app declares intent; one service owns the translation, so there is no second
160
- implementation to drift. Every cadence here is shaped to be exactly
161
- translatable — that constraint is why the vocabulary is closed and why `at` is
162
- whole hours.
163
-
164
- ### Hours, never minutes
165
-
166
- `at` is a whole hour, `0` through `23`, or a list of them. There is no minute:
167
- an app says *which hours*, and the platform picks where inside the hour a run
168
- actually starts (see [Timing](#timing)). `hourly()` takes no options for the
169
- same reason. An app that could pin a minute would opt itself out of the smear,
170
- and the herd would come back.
171
-
172
- This is also what keeps the vocabulary exactly translatable by the backend.
173
- Cron pairs every value in its minute field with every value in its hour field,
174
- so a cadence that could say 09:15 and 17:45 has no faithful cron — it would
175
- become `15,45 9,17 * * *` and fire four times a day instead of twice. With the
176
- minute fixed, any set of hours translates exactly.
177
-
178
- `at` accepts a list, so several runs a day need one schedule rather than
179
- several: `daily({ at: [0, 6, 12, 18] })` is four evenly spaced runs, and
180
- `daily({ at: [9, 17] })` is two uneven ones — the start and end of a working
181
- day, which no fixed interval can express. The list is sorted and deduplicated,
182
- so two orderings are one schedule.
183
-
184
- ### One schedule, one representation
185
-
186
- `weekly({ on, at })` is the single-day shorthand for `daily({ at, days: [on] })`
187
- and resolves into exactly that cadence. There is one internal representation of
188
- a day-restricted schedule, so the two spellings emit byte-identical manifests
189
- and hash alike.
190
-
191
- There is no `"weekdays"` or `"weekends"` shorthand: it would add a third
192
- spelling of a set `days` already states, and "the weekend" is Friday and
193
- Saturday in much of the world, so the word would quietly mean the wrong days.
194
-
195
- There is no interval cadence — no `every("6h")`, no `every("3d")`. Intervals
196
- are not calendar positions and have no faithful cron: `0 0 */3 * *` restarts its
197
- count every month, so it means "every 3 days" only until the 28th and then fires
198
- twice in two days. The sub-daily intervals that *are* faithful are exactly the
199
- ones `daily({ at })` already covers, and `daily({ at: [0, 6, 12, 18] })` says the
200
- same thing as "every 6 hours" while staying anchored to the calendar and to the
201
- app's time zone.
202
-
203
- ## Timing
204
-
205
- **A declared hour is approximate, and an app does not control how approximate.**
206
- Tens of thousands of apps declaring `daily()` must not fire in the same minute,
207
- so the platform spreads each schedule over a window — a *smear* — and then keeps
208
- that schedule on the same offset for every later run.
209
-
210
- Apps do not declare the smear, and there is no field for it. The platform
211
- derives the window per schedule from the cadence, so what an app leaves
212
- unspecified is exactly what the platform is free to choose:
213
-
214
- | Cadence | Smeared across |
215
- | --- | --- |
216
- | `daily()` | the whole day |
217
- | `daily({ at })`, `weekly({ on, at })` | a window around each declared hour |
218
- | `hourly()` | the hour |
219
-
220
- Higher plans get tighter windows, so a declared 07:00 lands nearer to 07:00 the
221
- more an app pays; the exact windows belong to the platform and can change
222
- without an SDK release.
223
-
224
- Two consequences worth designing around. A schedule that must run at an exact
225
- instant is not expressible, by design. And the offset is stable per schedule,
226
- not random per run, so a report that reads "yesterday's rows" reads the same
227
- shape every day.
228
-
229
- Neither the smear nor the schedule itself runs yet; see
230
- [Next PRs](#next-prs).
231
-
232
- ### Time zone
233
-
234
- `timeZone` is required on every schedule. There is no default, because every
235
- available default is wrong: `daily({ at: 9 })` in UTC is not the 09:00 a reader
236
- of the digest expects, and the build machine's own zone would make one app
237
- source fire at different times depending on where it was built.
238
-
239
- It must be `"UTC"` or a canonical IANA name as `Intl.supportedValuesOf("timeZone")`
240
- lists it, such as `"Europe/Stockholm"`. That rejects the fixed-offset family
241
- `Intl` otherwise accepts — `"+05:00"`, `"-0800"`, `"EST"`, `"GMT"`,
242
- `"Etc/GMT+5"` — none of which observe daylight saving, so `"EST"` is an hour
243
- off US Eastern for two-thirds of the year, and `"Etc/GMT+5"` is UTC-5 rather
244
- than UTC+5. It also rejects tzdata's backward-compatibility aliases such as
245
- `"US/Pacific"`; write the canonical `"America/Los_Angeles"`, so one zone has
246
- one spelling and one manifest.
247
-
248
- ### Overlap policy
249
-
250
- `overlapPolicy` says what happens when an occurrence comes due while the
251
- previous run is still going: `skip` drops it, `allow` lets runs overlap, and
252
- `buffer-one` holds the earliest due occurrence and fires it once the in-flight
253
- run finishes.
254
-
255
- ### Validation
256
-
257
- Everything is validated when the schedule is defined, at build time: an hour
258
- outside `0`-`23`, a fractional hour, a weekday name that is not a weekday, an
259
- unknown `overlapPolicy`, a missing or non-canonical zone, and a hand-written
260
- cadence object no constructor produced all fail the build. `registerWorkflows`
261
- likewise rejects any key other than `workflows` and `triggers`, so a collection
262
- left on the old `schedules:` name fails the build instead of emitting an empty
263
- manifest.
264
-
265
- The [example](examples/src/lib/workflows/index.ts) declares a 09:00 greeting in
266
- Europe/Stockholm, a weekday greeting in America/New_York, a Monday report, a
267
- four-times-daily refresh, an hourly sweep, and a paused daily digest.
268
-
269
- ## Manifest generation
270
-
271
- Add `workflowsPlugin()` from `@lovable.dev/workflows-sdk/vite` to the app's Vite
272
- plugins. Its `entry` defaults to `src/lib/workflows/index.ts` and must
273
- default-export the app's `registerWorkflows()` collection. Each production build writes
274
- one manifest per workflow to `.lovable/workflows/{workflow-name}.json` relative
275
- to the app root. For example, `greet` produces `.lovable/workflows/greet.json`.
276
- Generation errors fail the build. See [the Vite example](examples/vite.config.ts).
277
-
278
- Each version-1 manifest contains a single `workflow` with its ID, description,
279
- version, and input/output/state JSON Schemas, a `graph` for visualization, and a
280
- `triggers` array containing only that workflow's triggers and static inputs. Each
281
- entry names its kind in `type` — `"schedule"` today — and a schedule entry carries
282
- its `cadence`, `timeZone`, `enabled`, `overlapPolicy`, and `input`. It is an SDK discovery format, not the engine's deployment or execution
283
- contract. Handlers and middleware stay in app code. Triggers and JSON object keys
284
- are sorted for stable output.
285
-
286
- The SDK manages the JSON files in `.lovable/workflows/`. Successful generation
287
- removes manifests for deleted or renamed workflows; an empty collection removes
288
- all JSON manifests. Other files and subdirectories are preserved. All definitions
289
- are validated before writing, and each file is replaced by rename so readers
290
- never see a partially written JSON document.
291
-
292
- Schemas must implement [Standard JSON Schema](https://standardschema.dev/json-schema)
293
- conversion to draft 2020-12, as Zod 4 does. Missing conversion support and
294
- conversion errors fail generation. Schedule inputs must be plain JSON and pass
295
- the workflow's input schema; the manifest retains the raw input for validation
296
- when a run starts. Functions, undefined values, non-finite numbers, class
297
- instances, and cycles are rejected. `previousVersions` is rejected until version
298
- routing has a manifest contract.
299
-
300
- The plugin evaluates the entry using a separate Vite SSR loader with the app's
301
- aliases, mode, defines, and SSR dependency rules. Module-level code and schema
302
- validators run during extraction; workflow handlers and middleware do not.
303
- Custom app transform plugins and virtual modules are not loaded by this loader.
304
- For another build system, call `await generateManifests(collection)` and make
305
- synchronizing the returned manifests to `.lovable/workflows/` a required build step.
306
-
307
- ### Step graph
308
-
309
- Each manifest's `graph` contains `nodes` and directed `edges`. The SDK parses the
310
- handler's function source without executing it. No additional registration is needed.
311
-
312
- Graph inference reads the app's own `typescript`, an optional peer. Apps built
313
- from a Lovable template already have it. Without it — or with a copy exposing no
314
- stable JS API, as TypeScript 7 does before 7.1 — the build still succeeds and
315
- every graph carries one `unknown` node and the diagnostic
316
- `Install typescript to infer step graphs`.
317
- Sequential awaited `ctx.step("name", callback, options)` calls produce order edges;
318
- `await Promise.all([ctx.step(...), ctx.step(...)])` produces parallel branches
319
- that join at the next step. A `Promise.all()` mapped over a collection with the
320
- step ID template `step-${item.id}` produces one dynamic parallel node labeled
321
- from `meta.group.label`. A `for...of` loop whose only statement directly awaits
322
- a step with such an ID template produces one dynamic sequential `loop` node.
323
- Returned step promises work too. Keep step IDs literal outside these dynamic
324
- forms. A `try` block retains its durable operations when the `catch` only handles
325
- the error in ordinary code. Durable operations in a `catch` remain visible in a
326
- partial graph because edges do not encode error outcomes.
327
-
328
- An `if` whose body contains durable operations produces a `branch` node. Every
329
- durable operation inside it includes an outer-to-inner `meta.branches` path;
330
- each entry has a static `id` and agent-written `description`. Both sides of one
331
- condition use the same entry. The AST determines nesting and whether an edge is
332
- the `true` or `false` outcome, so metadata never declares topology. Branch IDs
333
- identify one `if` statement within the workflow.
78
+ Durable operations inside `if` and `else` branches include an outer-to-inner
79
+ `meta.branches` path. Both sides of one condition use the same static ID and
80
+ description:
334
81
 
335
82
  ```ts
336
83
  meta: {
@@ -339,371 +86,58 @@ meta: {
339
86
  }
340
87
  ```
341
88
 
342
- | Field | Meaning |
343
- | --- | --- |
344
- | `nodes[].id` | Unique occurrence ID within this graph; use as the UI node key |
345
- | `nodes[].kind` | Durable operation, `branch`, `parallel`, `loop`, or `unknown` |
346
- | `nodes[].stepId` | Runtime durable ID for every statically known operation |
347
- | `nodes[].description` | User-facing description for every known durable operation and branch |
348
- | `nodes[].branchId` | Stable ID for an inferred `if` node |
349
- | `nodes[].condition` | Source expression from the corresponding `if` statement |
350
- | `nodes[].groupId` | Stable callsite ID for a dynamic parallel or loop node |
351
- | `nodes[].cardinality` | `dynamic` for a runtime-sized repeated operation |
352
- | `nodes[].execution` | `sequential` for a dynamic loop node |
353
- | `nodes[].operation.kind` | Durable operation repeated by a dynamic node |
354
- | `nodes[].operation.stepIdTemplate` | Display template for steps in a dynamic node |
355
- | `nodes[].operation.description` | User-facing description shared by the repeated steps |
356
- | `nodes[].label` | Step ID, branch description, group label, or explanation of unsupported code |
357
- | `edges[]` | Order edges or branch edges with an AST-derived boolean `outcome`, referencing node IDs |
358
- | `complete` | Whether the handler uses only supported syntax |
359
- | `diagnostics` | Reasons the graph is partial |
360
-
361
- For example, `read` followed by parallel `transform-a` and `transform-b`, then
362
- `save`, produces `read → transform-a → save` and `read → transform-b → save`.
363
- Node IDs are deterministic for the same source, but may change when the handler
364
- is edited.
365
-
366
- Known durable nodes use the same `stepId` as runtime progress records. An
367
- explicit `{ id }` wins; otherwise the graph and runtime share the operation's
368
- derived default. `label` remains the display name.
369
-
370
- Graphs have `source: "inferred"` and `scope: "handler"`. They describe source
371
- structure, not run history or data dependencies, and exclude middleware and
372
- initialization. A mapped `Promise.all` is complete when its callback directly
373
- returns `ctx.step()` with a template-literal ID derived from a callback parameter.
374
- A `for...of` loop is complete when its only statement directly awaits the same
375
- shape of step using the loop variable. Other loops, switch statements,
376
- conditional expressions, helper calls, dynamic step IDs, and unawaited steps
377
- produce `unknown` nodes and `complete: false`; steps inside unsupported code are
378
- not expanded. The UI should show these unknown nodes and mark partial graphs.
379
- Transforms that rewrite the handler may also produce a partial graph. A handler
380
- with no steps can have an empty graph.
381
-
382
- A step body is one atomic execution unit. Manifest generation rejects statically
383
- visible durable calls inside it, including `ctx.step`, `ctx.sleep`, `ctx.now`,
384
- and the other `ctx.*` operations. Move each durable operation into the workflow
385
- handler and pass its result into the step instead.
386
-
387
- Keep the workflow context in the handler. Manifest generation rejects passing,
388
- aliasing, destructuring, or returning `ctx`, and rejects detached durable methods
389
- such as `helper(ctx.step)`. Pass only extracted data such as `ctx.input` to
390
- helpers instead. This keeps durable control flow visible in the handler source
391
- used to build the graph.
392
-
393
- ## Steps endpoint (TanStack Start)
394
-
395
- The same `workflowsPlugin` that writes the manifests also emits
396
- `src/routes/api/workflows/$workflowId/steps.ts`, serving every registered
397
- workflow. There is no opt-in: a declared workflow with no endpoint cannot run.
398
- One plugin and one `entry` feed the manifest and route, so they cannot describe
399
- different workflow collections:
400
-
401
- ```ts
402
- import { tanstackStart } from "@tanstack/react-start/plugin/vite";
403
- import { workflowsPlugin } from "@lovable.dev/workflows-sdk/vite";
404
-
405
- export default defineConfig({
406
- plugins: [workflowsPlugin(), tanstackStart()],
407
- });
408
- ```
409
-
410
- A missing `entry` file is the only thing that suppresses the route: an app with
411
- no collection gets no endpoint.
412
-
413
- ### The route is unauthenticated
414
-
415
- **Any caller who reaches the route can run any declared workflow.** The SDK
416
- ships no request authentication today; signed invocation is the next piece of
417
- work on this endpoint. Until it lands, treat the endpoint as public and keep
418
- anything a stranger must not trigger — spend, mutation of another user's data,
419
- outbound mail — out of a declared workflow, or guard it inside the handler.
420
-
421
- Reachability is the lever an app has in the meantime. Public apps expose the
422
- route to the internet. Workspace and private apps are gated by the Lovable host,
423
- which is why `path` matters (below).
424
-
425
- ### Relocating the route with `path`
89
+ ## Schedules
426
90
 
427
- `path` sets the URL prefix; the workflow ID is appended as a dynamic segment,
428
- and the emitted file name follows the path. Workspace and private apps reach
429
- anonymous traffic only under an `/api/public` prefix — everything else is
430
- blocked by the host before it reaches the app — so those projects must move the
431
- route there for it to be reachable at all:
91
+ Declare schedules with `defineSchedule({ id, workflow, cadence, timeZone,
92
+ input })` and include them in the collection's `triggers`. The workflow must be
93
+ part of the same collection, and schedule IDs must be unique. This API declares
94
+ schedules; Lovable execution is not available yet.
432
95
 
433
96
  ```ts
434
- workflowsPlugin({ path: "/api/public/workflows" });
97
+ const morning = defineSchedule({
98
+ id: "morning-digest", workflow: digest, cadence: daily({ at: 9 }), timeZone: "Europe/Stockholm", input: {},
99
+ });
435
100
  ```
436
101
 
437
- That emits `src/routes/api/public/workflows/$workflowId/steps.ts` and serves
438
- `POST /api/public/workflows/{workflow-id}/steps`. The trade is explicit: the
439
- prefix that makes the route reachable also makes it anonymously reachable.
440
-
441
- The emitted file imports the collection and mounts its package handler. All
442
- runtime logic stays in the package. A generated banner is the plugin's
443
- ownership token: it rewrites and deletes only files that have it, and deletes
444
- its own orphans when `path` or `workflowIdParam` changes. Delete the banner line
445
- to take the route over. That is also the supported way to add a check of your
446
- own in front of the handler.
447
-
448
- | Option | Default | Meaning |
102
+ | Field | Default | Meaning |
449
103
  | --- | --- | --- |
450
- | `entry` | `src/lib/workflows/index.ts` | Collection entry; a missing file means no route |
451
- | `routesDir` | `src/routes` | Where the route file is written |
452
- | `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
453
- | `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
454
-
455
- ### How the emitted file imports the collection
456
-
457
- The plugin prefers an alias, so the specifier does not change when `path` moves:
458
-
459
- ```ts
460
- import workflows from "@/lib/workflows/index";
461
- ```
462
-
463
- It does not assume `@`. It reads the app's Vite `resolve.alias` and its
464
- tsconfig `compilerOptions.paths`, and picks an alias whose target directory
465
- contains the collection entry — preferring one both sources declare, then the
466
- deepest match.
467
-
468
- An alias is only emitted when the *bundler* can resolve it: a Vite
469
- `resolve.alias` entry, or a tsconfig `paths` entry when a plugin such as
470
- `vite-tsconfig-paths` is active. A tsconfig `paths` entry alone instructs the
471
- typechecker and not the bundler, so emitting it would fail the build.
472
-
473
- When no alias qualifies, the plugin falls back to a relative specifier
474
- (`../../../lib/workflows/index`), which always resolves. An app with no alias
475
- configured still builds; only the specifier is uglier, and its depth tracks
476
- `path`.
477
-
478
- ### Calling it
479
-
480
- Each workflow gets one route for an external engine to drive one atomic step per
481
- request.
104
+ | `cadence` | — | `hourly()`, `daily()`, or `weekly()` |
105
+ | `timeZone` | — | Canonical IANA region name |
106
+ | `overlapPolicy` | `"skip"` | `skip`, `allow`, or `buffer-one` |
107
+ | `enabled` | `true` | `false` declares a paused schedule |
482
108
 
483
- | Route | Does |
109
+ | Cadence | Example |
484
110
  | --- | --- |
485
- | `POST /api/workflows/{id}/steps` | Advances a singleton frontier or executes one selected step |
486
-
487
- An unknown workflow ID returns 404 and an unparseable body 400.
488
-
489
- ### The memo is the run
490
-
491
- There is no run store. A run's entire state is its **memo** — the list of
492
- settled operations — and the caller carries it between calls:
493
-
494
- ```jsonc
495
- [{
496
- "seq": 0,
497
- "stepId": "greeting",
498
- "occurrence": 0,
499
- "kind": "step",
500
- "meta": { "description": "Create a personalized greeting" },
501
- "status": "completed",
502
- "result": "Hello, yehya!"
503
- }]
504
- ```
111
+ | Hourly | `hourly()` |
112
+ | Selected hours | `daily({ at: [0, 6, 12, 18] })` |
113
+ | Selected weekdays | `daily({ at: 9, days: ["mon", "tue", "wed", "thu", "fri"] })` |
114
+ | Weekly | `weekly({ on: "monday", at: 7 })` |
505
115
 
506
- An entry is keyed by `stepId` and `occurrence` (which call of that id in the
507
- run, from 0) — never by position or `seq`. Two parallel branches can reach the
508
- same pair of operations in either order from one pass to the next, so call order
509
- is reported but is not the identity.
510
-
511
- Every response returns a `memoDelta` and an `inputHash`. Merge the delta into the
512
- memo by `(stepId, occurrence)`, then send the full memo, `inputHash`, `runId`, and
513
- the same `input` on the next call. Replay re-runs the handler from the top, and
514
- the memo does not carry the input. `inputHash` binds the memo to the input it came
515
- from: resuming with a different one is a 400. Key order in the input does not
516
- affect it. Because state travels in the request, a run survives a restart and can
517
- continue on a different instance.
518
-
519
- Replay is what makes this work: the handler re-runs from the top on every call,
520
- settled operations answer from the memo instead of executing again, and
521
- `ctx.state` plus ordinary control flow rebuild themselves. A settled operation
522
- can sit beside an earlier pending one — `ctx.now()` pinned next to a step still
523
- waiting in the same `Promise.all`. An entry must match the kind of operation
524
- replay finds at its id, so a tampered or stale memo fails the call rather than
525
- answering the wrong one:
526
-
527
- ```json
528
- { "disposition": "failed", "error": "non-deterministic replay: memo has approve \"thing\" (#0), replay produced step" }
529
- ```
530
-
531
- **Every step ID must be unique within a workflow.** Manifest generation rejects
532
- a repeated literal ID in sequential calls, parallel branches, mutually exclusive
533
- branches, loops, and callbacks. Dynamic IDs cannot be proven at build time, so
534
- the runtime refuses the second step that resolves to an ID already reached.
535
-
536
- `ctx.now()`, `ctx.uuid()`, `ctx.sleep(ms)` and the other durable operations fall
537
- back to a default ID. Two calls sharing one cannot be told apart on replay, so
538
- the second is refused. Pass `{ id }` per call site: `ctx.now({ id: "started" })`.
539
-
540
- Manifest generation rejects this before a run exists, when the arguments are
541
- literal:
542
-
543
- ```text
544
- workflow "greet" calls ctx.now() 2 times with the default id "now";
545
- replay cannot tell them apart, so pass an explicit { id } per call site
546
- ```
547
-
548
- The same applies to two `ctx.sleep(1000)` calls, two waits on one event name, or
549
- two approvals with one title. Their default ID is derived from the argument, so
550
- only a repeated argument collides. A dynamic argument is left to the runtime
551
- check.
552
-
553
- **Handler code outside a step runs on every call.** Keep side effects inside
554
- `ctx.step`, which is memoized; a bare `fetch` in the handler body repeats each
555
- pass. A pass also allows only a bounded amount of such work — 5s by default —
556
- before reporting the run stalled.
557
-
558
- ### The memo is unauthenticated input
559
-
560
- **A caller supplies the memo, and the route does not authenticate it.** Anything
561
- the memo says is already settled is taken as settled, including an approval's
562
- decision. A caller who can reach the route can therefore hand back
563
- `{"kind": "approve", "status": "completed", "result": {"approved": true}}` and
564
- skip the human, or mark an expensive step completed with a fabricated result and
565
- skip the work. `inputHash` binds a memo to one input, so a forged memo cannot be
566
- replayed against a different record, but it is computed from the request and so
567
- is no barrier on its own.
568
-
569
- Until signed invocation lands, **do not treat `ctx.approve` as a security
570
- boundary on these routes**, and do not put an operation behind one that a
571
- stranger must not be able to declare done. Reachability is the only control an
572
- app has in the meantime; see `path` above.
573
-
574
- ### Stepping through a run
575
-
576
- ```bash
577
- POST /api/workflows/greet/steps
578
- { "input": { "name": "yehya" } }
579
- -> { "disposition": "advanced",
580
- "executed": { "stepId": "greeting", "occurrence": 0, "kind": "step", "status": "completed" },
581
- "memoDelta": [{ "stepId": "greeting", "occurrence": 0, ... }],
582
- "next": [{ "seq": 1, "stepId": "shout", "occurrence": 0, "kind": "step" }] }
583
-
584
- POST /api/workflows/greet/steps
585
- { "action": "execute", "step": { "stepId": "shout", "occurrence": 0, "kind": "step" },
586
- "input": { "name": "yehya" }, "memo": [...], "inputHash": "9f2c...", "runId": "run_..." }
587
- -> { "disposition": "completed", "memoDelta": [...], "next": [], "output": "HELLO, YEHYA!" }
588
- ```
589
-
590
- Omitting `action` means `"advance"`. When the current frontier contains exactly
591
- one app-executable step, `advance` executes it and returns the next frontier. A
592
- sequential workflow therefore needs one HTTP call per step, including the first.
116
+ Hours are whole numbers from 0 through 23; schedules do not accept minute or
117
+ raw-cron fields. `timeZone` is required and accepts `"UTC"` or a canonical IANA
118
+ region such as `"America/New_York"`. A scheduled hour is approximate: Lovable
119
+ chooses a stable offset within the corresponding scheduling window.
593
120
 
594
- ### Driving a run from an orchestrator
121
+ `overlapPolicy` controls what happens when a schedule becomes due while its
122
+ previous run is active. `skip` drops it, `allow` starts another run, and
123
+ `buffer-one` starts the earliest missed run after the active run finishes.
595
124
 
596
- Use the response disposition to choose the next call:
125
+ ## Build integration
597
126
 
598
- | Disposition | Engine action |
599
- | --- | --- |
600
- | `advanced` | Merge `memoDelta`, then execute the single entry in `next`. |
601
- | `fork` | Merge `memoDelta`, then execute each app-executable entry in `next` in a separate concurrent request using that same memo. |
602
- | `waiting` | Settle the external operations in `next`, then call `advance`. |
603
- | `completed` | Persist `output`; the run is done. |
604
- | `failed` | Apply the engine's retry or failure policy. |
605
-
606
- At a fork, every `execute` request receives the same base memo and selects one
607
- `{ kind: "step", stepId, occurrence }`. Merge all returned deltas, then call
608
- `advance` once. That replay crosses the join and immediately executes a
609
- singleton tail when one exists. Do not schedule from one branch's `next`: a
610
- partial branch response cannot see results still running in its siblings.
611
-
612
- An `execute` call runs only its selected step. The endpoint returns 409
613
- `stale_step` if that reference is not executable from the supplied memo.
614
-
615
- Keep a step's result small: it travels in the memo on every later call, so a
616
- large payload is resent for the rest of the run. Write bulk data to storage
617
- inside the step and return the key.
618
-
619
- Each call re-runs the handler from the top. Step bodies run only in their
620
- selected request, so side effects belong inside a step.
621
-
622
- `next` reports an operation's `stepId`, `kind`, and author-supplied `meta`,
623
- including its description and group. An approval's top-level authoring
624
- description is copied into runtime metadata for the same response shape. `next`
625
- does not report a step's input:
626
- `ctx.step(id, fn, options)` closes over its arguments rather than declaring
627
- them, so the input is not knowable without running `fn`. Deterministic values
628
- (`ctx.now`, `ctx.uuid`) are pinned into `memoDelta`, so concurrent calls replay
629
- the same values after the engine merges the delta.
630
-
631
- ### Waiting on something outside the app
632
-
633
- `ctx.sleep`, `ctx.waitForEvent` and `ctx.approve` cannot be settled by the app,
634
- so they are never executed — they come back as pending operations carrying what
635
- a caller needs to resolve them:
636
-
637
- ```json
638
- { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
639
- "meta": { "description": "Ask a reviewer to approve the refund" },
640
- "config": { "title": "Approve refund", "description": "Ask a reviewer to approve the refund" } }
641
- ```
642
-
643
- The endpoint returns `waiting` with that list in `next`. Resume by appending the
644
- decision to the memo, preserving its `meta`, and calling `advance`:
127
+ Add `workflowsPlugin()` before the TanStack Start plugin. Its `entry` defaults
128
+ to `src/lib/workflows/index.ts` and must default-export the registered
129
+ collection. See [the Vite example](examples/vite.config.ts).
645
130
 
646
- ```jsonc
647
- { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
648
- "meta": { "description": "Ask a reviewer to approve the refund" },
649
- "status": "completed", "result": { "approved": true, "approvalId": "apr_1" } }
131
+ ```ts
132
+ plugins: [
133
+ workflowsPlugin(),
134
+ tanstackStart(),
135
+ ];
650
136
  ```
651
137
 
652
- `createTanStackWorkflowHandler` is still exported for the engine-backed path
653
- (`runWorkflow` plus a `RunStore`, `inMemoryRunStore()` by default). No emitted
654
- route uses it: a process-local store loses runs on restart and is invisible to
655
- other instances, which is what the memo model replaces.
656
-
657
- ### Not yet carried over
658
-
659
- `ctx.step`'s `retries` and `timeout` options are accepted and ignored — the
660
- caller decides whether to re-issue a failed step. Step retry, timeouts, and
661
- `previousVersions` routing are follow-ups.
662
-
663
- The path carries no build ID. Version pinning belongs to the signed invocation,
664
- which leaves it stable across deployments and safe to publish in a manifest.
665
- Triggers name a workflow rather than an endpoint, so no trigger identifier
666
- appears in the URL.
667
-
668
- ## Public entry points
669
-
670
- The package has two, and neither mirrors the source tree:
138
+ ## Imports
671
139
 
672
140
  | Import | Provides |
673
141
  | --- | --- |
674
- | `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and the `createStepsHandler` route handler |
675
- | `@lovable.dev/workflows-sdk/vite` | `workflowsPlugin`, the build-time Vite plugin |
676
-
677
- The export map is a contract; the directory layout under `src/` is not. They are
678
- deliberately decoupled, so the package can be reorganised without a breaking
679
- change for apps that already have an emitted route.
680
-
681
- The package sets `"sideEffects": false` and the handler is a plain re-export, so
682
- a client bundle importing only authoring APIs drops the execution engine.
683
-
684
- ## Next PRs
685
-
686
- Connect the manifest and app code to Lovable deployment and runtime execution.
687
- Derive and apply the per-schedule smear on the control plane. Define support for
688
- TanStack primitives, version routing, and schedule policies.
689
- Add webhook and app-event triggers to the same `triggers` array.
690
-
691
- ## Publishing dev builds
692
-
693
- The [publishing workflow](../../.github/workflows/publish-workflows-sdk.yml)
694
- publishes the version committed in `package.json` to npm's `latest` tag when SDK
695
- changes land on `main`. Manage versions manually: `0.0.0-dev`, `0.0.0-dev.1`,
696
- `0.0.0-dev.2`, and so on. The workflow rejects versions outside this series and
697
- skips versions already published. Manual runs default to a dry run.
698
- See [the setup guide](PUBLISHING.md) for the
699
- one-time bootstrap and npm trusted-publisher configuration.
700
-
701
- Install the newest build with `npm install @lovable.dev/workflows-sdk`, or pin
702
- the exact version shown in the workflow run's summary. `latest` tracks every dev
703
- publish while the SDK is pre-1.0; the older `dev` tag is frozen at `0.0.0-dev.2`.
704
-
705
- The engine's embedded SDK
706
- ([`sdk_embed/index.ts`](../../go/workflows/services/workflows/internal/bundler/sdk_embed/index.ts))
707
- provides the engine contract. Use [`mcp-js`](../lovable-mcp-js) as the reference
708
- for separating authoring, manifest extraction, and framework integration. The
709
- workflow prototype's `ts/workflow-sdk` supplies adapter and manifest examples.
142
+ | `@lovable.dev/workflows-sdk` | Workflow authoring, registration, cadences, and schedules |
143
+ | `@lovable.dev/workflows-sdk/vite` | Lovable build integration |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/workflows-sdk",
3
- "version": "0.0.0-dev.23",
3
+ "version": "0.0.0-dev.24",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "dev",