@lovable.dev/workflows-sdk 0.0.0-dev.6 → 0.0.0-dev.60

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
@@ -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.
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.
9
-
10
- ## Authoring
11
-
12
- 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
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
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @lovable.dev/workflows-sdk
27
11
  ```
28
12
 
29
- Each workflow's `index.ts` exports its definition. The collection entry imports
30
- all workflow definitions and default-exports `registerWorkflows(...)`:
13
+ ## Define workflows
14
+
15
+ Use `createWorkflow({ id, version, input, output }).handler(...)` to define a workflow
16
+ and `createMiddleware` to extend its typed context. Standard Schema libraries
17
+ such as Zod provide input and output inference.
18
+
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,363 +26,354 @@ 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
+ ## Workflow versions
48
35
 
49
- ## Triggers
36
+ Every workflow requires an explicit `version`, including retained definitions.
37
+ Start with `"v1"`; introduce a new label when changing behavior, schemas, or
38
+ relevant helpers. Keep existing version implementations unchanged while runs drain.
39
+ Registration rejects missing, empty, and invalid labels. Existing unversioned
40
+ runs must drain on their original SDK deployment before upgrading.
50
41
 
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.
42
+ Keep the current definition in `workflows` and attach older definitions with
43
+ `.previousVersions([v1])` before `.handler(...)`. Each definition has the same
44
+ workflow ID and a distinct `version` passed to `createWorkflow`. Versions accept
45
+ 1–128 letters, digits, dots, hyphens, or underscores, starting with a letter or
46
+ digit. The combined manifest filename must fit 255 characters. See the [versioned example](examples/src/lib/workflows/versioned/index.ts).
55
47
 
56
- A schedule's *cadence* is how often the clock fires. `hourly()`, `daily()`,
57
- and `weekly()` build one; there is no raw cron.
48
+ The build emits one manifest per version. The top-level definition has
49
+ `current: true`; retained definitions have `current: false` and no triggers.
50
+ Schedules reference the top-level definition and start its version.
58
51
 
59
- ## Schedules
52
+ Steps responses include `workflowVersion`. Persist it with the run and send it
53
+ on every later request, including an empty memo. A missing version on a
54
+ resume or an unavailable version fails before replay.
60
55
 
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.
56
+ Keep an old definition and its relevant helpers unchanged while the published
57
+ app still uses that version: it is the published version, or it has open runs.
58
+ Remove them after that. Removing a definition makes its version unavailable;
59
+ existing runs never switch to the current version automatically.
67
60
 
68
- ```ts
69
- import { daily, defineSchedule, hourly, weekly } from "@lovable.dev/workflows-sdk";
61
+ ## Durable operations
70
62
 
71
- defineSchedule({ id: "sweep", workflow: sync, cadence: hourly(), timeZone: "UTC", input: {} });
72
- defineSchedule({ id: "digest", workflow: digest, cadence: daily(), timeZone: "Europe/Stockholm", input: {} });
63
+ Every durable operation needs a static, user-facing description:
73
64
 
74
- defineSchedule({
75
- id: "refresh",
76
- workflow: sync,
77
- cadence: daily({ at: [0, 6, 12, 18] }),
78
- timeZone: "UTC",
79
- input: {},
65
+ | Operation | Description field |
66
+ | --- | --- |
67
+ | `ctx.step` | Third argument: `meta.description` |
68
+ | `ctx.llm` | Second argument: `meta.description` |
69
+ | `ctx.connector` | Third argument: `meta.description` |
70
+ | `ctx.sleep`, `ctx.sleepUntil` | Second argument: `meta.description` |
71
+ | `ctx.waitForEvent` | Second argument: `meta.description` |
72
+ | `ctx.now`, `ctx.uuid` | First argument: `meta.description` |
73
+ | `ctx.approve` | First argument: `description` |
74
+
75
+ `ctx.llm(request, options): Promise<string>` calls AI Gateway inside the app
76
+ and returns assistant text. Pass a provider-prefixed `model` and either `prompt`
77
+ or nonempty text-only user/assistant `messages`. Optional `system` supplies system
78
+ instructions; `maxTokens` defaults to 4096. Use a unique `options.id` and a literal
79
+ `options.meta.description`, with item-based template IDs for repeated calls.
80
+ Compatible OpenAI and Gemini Chat Completions models and Claude Messages models
81
+ are supported for text generation. Claude uses the separate `system` field and
82
+ returns joined text blocks; thinking blocks are excluded. Its token budget includes
83
+ thinking. Token-limit or context-window truncation fails the step with a truncation
84
+ error. Refusals, tool requests, paused turns, and responses without text also fail.
85
+ Streaming, tools, images, and structured output are outside this API.
86
+
87
+ The Gateway SDK reads the app's server-side `LOVABLE_API_KEY`; the generated
88
+ workflow route authenticates the Temporal activity with `LOVABLE_WORKFLOWS_KEY`.
89
+ LLM steps use the same execution, forks, replay, and activity-controlled retries
90
+ as code steps. Discovery and unselected branches make no model calls. Saved text
91
+ replays; saved final errors throw into the workflow's `try/catch`. Gateway SDK
92
+ retries are disabled. A result lost before persistence can be generated again
93
+ on an activity retry, just as code-step side effects can repeat.
94
+
95
+ Before choosing a model, install `@lovable.dev/ai-gateway` in the app and run:
96
+
97
+ ```sh
98
+ bun -e 'import { listModels } from "@lovable.dev/ai-gateway"; console.log(JSON.stringify(await listModels()));'
99
+ ```
100
+
101
+ Require `workspace_models: "included"`; missing markers, public catalogs, and
102
+ invalid credentials do not establish project access. Choose an exact eligible
103
+ model ID whose `modalities.output` includes `text`. Its `supported_surfaces` must
104
+ include `chat-completions` for `openai/...` and `google/gemini-...`, or `messages`
105
+ for `anthropic/claude-...`. Use the project's resolved default when compatible,
106
+ then run `bunx ai-gateway generate --model <model-id>` and inspect the matching
107
+ surface's text contract. Discovery happens while authoring, not on every workflow run.
108
+
109
+ Run LLM workflows through the generated `/steps` route. The standalone
110
+ `createTanStackWorkflowHandler` uses TanStack's runtime and does not support LLM steps.
111
+ Real app-side calls require SDK `0.0.0-dev.49` or newer.
112
+ Claude support requires SDK `0.0.0-dev.54` or newer.
113
+
114
+ Both `ctx.approve` and `ctx.waitForEvent` require `timeoutMs`: a duration in
115
+ milliseconds, written as a finite numeric literal of at least 60000 (one minute) (for example,
116
+ `3600000` for one hour or `86400000` for one day). The Vite build fails if it
117
+ is omitted, computed, or invalid. Do not pass an absolute timestamp or the
118
+ upstream `deadline` option. Execution computes expiry when the wait first
119
+ parks, then preserves that expiry across replays.
120
+
121
+ ```ts
122
+ await ctx.step("load-customer", () => loadCustomer(ctx.input.customerId), {
123
+ meta: { description: "Load the customer record" },
80
124
  });
125
+ ```
126
+
127
+ Every durable operation takes an explicit `id` — `ctx.approve({ id, title, timeoutMs: 86400000 })`,
128
+ `ctx.waitForEvent(name, { id, timeoutMs: 3600000 })`, `ctx.sleep(ms, { id })`, `ctx.now({ id })` —
129
+ and none is derived from a title, name or duration. IDs share one namespace per
130
+ workflow, so the build fails on a missing or repeated one, including two calls
131
+ on mutually exclusive branches. Keep side effects inside step bodies;
132
+ handler code outside a step may run more than once. A step body is one atomic
133
+ execution unit and cannot contain another durable operation.
134
+
135
+ Keep durable control flow in the workflow handler. Do not pass, alias,
136
+ destructure, or return `ctx`, and do not detach methods such as `ctx.step`.
137
+ Pass extracted data such as `ctx.input.customerId` to helpers instead.
81
138
 
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: {},
139
+ ### Connector callbacks
140
+
141
+ SDK `0.0.0-dev.52` is the first version that executes
142
+ `ctx.connector(stepId, callback, options)` through the generated `/steps` route.
143
+ Use it for gateway-backed App connectors: a connection linked to the app,
144
+ shared across workflow runs. App User Connectors, which act for individual app
145
+ users, are outside this authoring flow.
146
+
147
+ ```ts
148
+ const messages = await ctx.connector("read-messages", ({ signal }) => readMessages(signal), {
149
+ connectorId: "slack", connectionId: "std_REPLACE_WITH_LINKED_CONNECTION_ID",
150
+ meta: { description: "Read recent channel messages" },
88
151
  });
152
+ ```
153
+
154
+ Keep `connectorId` and `connectionId` as nonempty string literals in the inline
155
+ options object. They identify the declared step in the manifest and run history;
156
+ credentials enforce access. They cannot vary by workflow input or loop item.
157
+ Use a new workflow version when changing the connection; replay rejects saved
158
+ results or failures whose connector identity differs.
159
+
160
+ The callback receives the normal step context, including `signal`. It owns
161
+ server-side credential access, URL, method, headers, encoding, `fetch`, and
162
+ provider errors. Check both HTTP success and the provider's success fields
163
+ before returning. Forward `signal` to I/O. Return compact JSON-serializable
164
+ data, including plain strings; there is no response envelope. A callback that
165
+ returns `undefined` records and returns `null`. Return parsed data or text,
166
+ never a `Response` or credentials.
167
+
168
+ Select and link an App connection with Lovable's existing connector tools.
169
+ `standard_connectors--get_connection_secrets` takes the connection's `std_...`
170
+ ID and returns exact secret names and generated-app routing, never secret
171
+ values. Follow that routing and run its read-only App credential check before
172
+ using the workflow. Secret names depend on the connection; do not derive them
173
+ from `connectorId`. Keep gateway credentials separate from
174
+ `LOVABLE_WORKFLOWS_KEY`, which authenticates the workflow endpoint.
175
+
176
+ Connector retries inherit `defaultStepRetry`. An inline `retry` replaces that
177
+ default and requires `maxAttempts`; use literal `backoff: "fixed"` or
178
+ `"exponential"` and optional `baseMs`. The engine records custom-policy flags
179
+ but does not invoke `shouldRetry` or backoff callbacks; custom backoff uses
180
+ exponential delays. `timeout` is a positive number of
181
+ milliseconds per attempt. Let the workflow engine retry: disable additional
182
+ client retries and avoid retry loops inside the callback. An external write
183
+ can repeat if its result is lost before persistence; use a provider idempotency
184
+ key derived from stable run input when the provider supports one.
185
+
186
+ Discovery, unselected branches, and completed-step replay never invoke the
187
+ callback. Saved final failures throw into the handler's `try/catch`. The
188
+ standalone `createTanStackWorkflowHandler` does not support connector callbacks.
189
+ See the [Slack digest example](examples/src/lib/workflows/slack-digest/index.ts)
190
+ for a connector read followed by an LLM summary and a saved code-step result.
191
+ The example uses hosted-app gateway authentication. Replace its marked
192
+ connection ID and secret name with the tool output, adapt routing/authentication
193
+ to that output, and select a model through the discovery procedure above before
194
+ running it.
195
+
196
+ ### Repeated steps
197
+
198
+ A step inside a loop or callback needs `meta.group` with a stable ID and
199
+ user-facing label. Each repeated step still needs its own dynamic ID:
89
200
 
90
- defineSchedule({
91
- id: "monday-report",
92
- workflow: report,
93
- cadence: weekly({ on: "monday", at: 7 }),
94
- timeZone: "Europe/Stockholm",
95
- input: {},
201
+ ```ts
202
+ ctx.step(`process-${item.id}`, () => processItem(item), {
203
+ meta: { description: "Process an item", group: { id: "process-items", label: "Process items" } },
96
204
  });
97
205
  ```
98
206
 
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 |
207
+ For dynamic sequential work, await one step directly as the only statement in
208
+ a `for...of` loop. For dynamic parallel work, use a mapped `Promise.all()`.
209
+ Both forms support `ctx.step`, `ctx.llm`, and `ctx.connector`; see [order summaries](examples/src/lib/workflows/order-summaries/index.ts).
210
+ Repeated connector steps keep the same literal connector and connection IDs
211
+ while each item gets a unique step ID.
212
+ Use a different group ID for each repeated callsite, and derive item IDs from
213
+ workflow input or saved step results so replay reaches the same operations.
214
+ Fixed `Promise.all([stepA, stepB])` branches and ordinary sequential steps do
215
+ not need a group.
105
216
 
106
- There are three cadences and no raw cron:
217
+ ### Conditional steps
107
218
 
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.
225
-
226
- ## Manifest generation
227
-
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
231
- one manifest per workflow to `.lovable/workflows/{workflow-name}.json` relative
232
- to the app root. For example, `greet` produces `.lovable/workflows/greet.json`.
233
- Generation errors fail the build. See [the Vite example](examples/vite.config.ts).
234
-
235
- Each version-1 manifest contains a single `workflow` with its ID, description,
236
- version, and input/output/state JSON Schemas, a `graph` for visualization, and a
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.
242
-
243
- The SDK manages the JSON files in `.lovable/workflows/`. Successful generation
244
- removes manifests for deleted or renamed workflows; an empty collection removes
245
- all JSON manifests. Other files and subdirectories are preserved. All definitions
246
- are validated before writing, and each file is replaced by rename so readers
247
- never see a partially written JSON document.
248
-
249
- Schemas must implement [Standard JSON Schema](https://standardschema.dev/json-schema)
250
- conversion to draft 2020-12, as Zod 4 does. Missing conversion support and
251
- conversion errors fail generation. Schedule inputs must be plain JSON and pass
252
- the workflow's input schema; the manifest retains the raw input for validation
253
- when a run starts. Functions, undefined values, non-finite numbers, class
254
- instances, and cycles are rejected. `previousVersions` is rejected until version
255
- routing has a manifest contract.
256
-
257
- The plugin evaluates the entry using a separate Vite SSR loader with the app's
258
- aliases, mode, defines, and SSR dependency rules. Module-level code and schema
259
- validators run during extraction; workflow handlers and middleware do not.
260
- Custom app transform plugins and virtual modules are not loaded by this loader.
261
- For another build system, call `await generateManifests(collection)` and make
262
- synchronizing the returned manifests to `.lovable/workflows/` a required build step.
263
-
264
- ### Step graph
265
-
266
- Each manifest's `graph` contains `nodes` and directed `edges`. The SDK parses the
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`.
274
- Sequential awaited `ctx.step("name", callback)` calls produce order edges;
275
- `await Promise.all([ctx.step(...), ctx.step(...)])` produces parallel branches
276
- that join at the next step. Returned step promises work too. Keep step IDs literal.
277
-
278
- | Field | Meaning |
279
- | --- | --- |
280
- | `nodes[].id` | Unique occurrence ID within this graph; use as the UI node key |
281
- | `nodes[].kind` | `step` or `unknown` |
282
- | `nodes[].stepId` | Literal step name, present for known steps |
283
- | `nodes[].label` | Step name or explanation of unsupported code |
284
- | `edges[]` | `{ source, target, kind: "order" }`, referencing node IDs |
285
- | `complete` | Whether the handler uses only supported syntax |
286
- | `diagnostics` | Reasons the graph is partial |
287
-
288
- For example, `read` followed by parallel `transform-a` and `transform-b`, then
289
- `save`, produces `read → transform-a → save` and `read → transform-b → save`.
290
- Repeated step names remain separate nodes. Node IDs are deterministic for the
291
- same source, but may change when the handler is edited.
292
-
293
- Graphs have `source: "inferred"` and `scope: "handler"`. They describe source
294
- structure, not run history or data dependencies, and exclude middleware and
295
- initialization. Branches, loops, helper calls, dynamic step IDs, nested steps,
296
- and unawaited steps produce `unknown` nodes and `complete: false`; steps inside
297
- unsupported code are not expanded. The UI should show these unknown nodes and
298
- mark partial graphs. Transforms that rewrite the handler may also produce a
299
- partial graph. A handler with no steps can have an empty graph.
300
-
301
- ## Run endpoint (TanStack Start)
302
-
303
- Pass `runRoute: true` to the same `workflowsPlugin` that writes the manifests. It
304
- then also emits one dynamic route, `src/routes/api/workflows/$workflowId.ts`,
305
- serving every registered workflow. One plugin and one `entry` cover both, so a
306
- manifest can never describe a collection the route does not serve:
219
+ Durable operations inside `if` and `else` branches include an outer-to-inner
220
+ `meta.branches` path. Both sides of one condition use the same static ID and
221
+ description:
307
222
 
308
223
  ```ts
309
- import { tanstackStart } from "@tanstack/react-start/plugin/vite";
310
- import { workflowsPlugin } from "@lovable.dev/workflows-sdk/vite";
224
+ meta: {
225
+ description: "Publish the approved draft",
226
+ branches: [{ id: "editor-approved", description: "The editor approved the draft" }],
227
+ }
228
+ ```
311
229
 
312
- export default defineConfig({
313
- plugins: [workflowsPlugin({ runRoute: true }), tanstackStart()],
230
+ ## Schedules
231
+
232
+ Declare schedules with `defineSchedule({ id, workflow, cadence, timeZone,
233
+ input })` and include them in the collection's `triggers`. The workflow must be
234
+ part of the same collection, and schedule IDs must be unique. Schedules run on
235
+ the published app only: publishing registers them, and the preview never runs
236
+ them. Each publish replaces the app's schedules with the ones its workflows
237
+ declare.
238
+
239
+ ```ts
240
+ const morning = defineSchedule({
241
+ id: "morning-digest", workflow: digest, cadence: daily({ at: [9] }), timeZone: "Europe/Stockholm", input: {},
314
242
  });
315
243
  ```
316
244
 
317
- `runRoute` defaults to `false`. The route is unauthenticated: any caller who
318
- reaches it runs any declared workflow. Turn it on only where that is acceptable,
319
- until signed invocation lands.
245
+ | Field | Default | Meaning |
246
+ | --- | --- | --- |
247
+ | `cadence` | — | `every({ minutes })`, `hourly()`, `daily({ at })`, or `weekly({ on, at })` |
248
+ | `timeZone` | — | Canonical IANA region name |
249
+ | `overlapPolicy` | `"skip"` | `skip`, `allow`, or `buffer-one` |
250
+ | `enabled` | `true` | `false` declares a paused schedule |
251
+
252
+ | Cadence | Example |
253
+ | --- | --- |
254
+ | Every few minutes | `every({ minutes: 10 })` |
255
+ | Hourly | `hourly()` |
256
+ | Selected hours | `daily({ at: [0, 6, 12, 18] })` |
257
+ | Weekly | `weekly({ on: ["mon", "fri"], at: [0, 12] })` |
258
+
259
+ `daily` requires a non-empty `at` list. `weekly` requires non-empty `on` and
260
+ `at` lists and runs at every selected hour on every selected weekday. Hours are
261
+ whole numbers from 0 through 23; schedules do not accept minute or raw-cron
262
+ fields. `timeZone` is required and accepts `"UTC"` or a canonical IANA region
263
+ such as `"America/New_York"`. A run of an hour-based cadence starts at a
264
+ fixed offset of 0 to 3599 seconds after its scheduled hour. Lovable picks the offset for each schedule
265
+ and keeps it, so `daily({ at: [9] })` starts at the same time between 09:00 and
266
+ 09:59 every day.
267
+
268
+ `every({ minutes })` takes 5, 10, 15, 20 or 30 and runs on UTC minutes,
269
+ whatever `timeZone` says. Its offset falls within one interval, so
270
+ `every({ minutes: 10 })` might start at :03:07, :13:07 and so on, every hour.
271
+ A 5-minute schedule makes 288 runs a day.
272
+
273
+ `overlapPolicy` controls what happens when a schedule becomes due while its
274
+ previous run is active. `skip` drops it, `allow` starts another run, and
275
+ `buffer-one` starts the earliest missed run after the active run finishes.
276
+ Lovable supports only `skip` today. If any schedule of a workflow declares
277
+ `allow` or `buffer-one`, publishing registers none of that workflow's
278
+ schedules.
279
+
280
+ ## Start runs from app code
281
+
282
+ `startRun`, `getRun` and `deliverEvent` start, read and resume runs of the
283
+ app's published workflows. They require SDK `0.0.0-dev.57` or newer. Call them
284
+ from server code only, such as a server route or a `*.server.ts` helper: they
285
+ send the app's `LOVABLE_API_KEY`, and they throw in a browser. The
286
+ `LOVABLE_WORKFLOWS_KEY` that authenticates the `/steps` route is a different
287
+ key and plays no part here.
320
288
 
321
- The emitted file is thin — it imports the collection and mounts
322
- `createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk/stacks/tanstack`
323
- as the route's `POST` handler. All runtime logic stays in the package. The file
324
- carries a generated banner, which is the plugin's ownership token: it rewrites
325
- and deletes only files that have it, and deletes its own orphans when `path`,
326
- `workflowIdParam`, or `runRoute` changes. Delete the banner line to take the
327
- route over — the plugin then leaves that file alone, and the build keeps
328
- working.
289
+ ```ts
290
+ const run = await startRun(orderShipped, { orderId: shipment.orderId }, { idempotencyKey: `shipment:${shipment.id}` });
291
+ const latest = await getRun(run.runId);
292
+ await deliverEvent(run.runId, { eventId: `approval:${approval.id}`, name: "approved", payload: { by: approval.by } });
293
+ ```
329
294
 
330
- | Option | Default | Meaning |
295
+ | Call | Returns |
296
+ | --- | --- |
297
+ | `startRun(workflow, input?, options?)` | `{ runId, workflowId, status, trigger, createdAt }`; `trigger` is `api` |
298
+ | `getRun(runId, options?)` | The summary plus `updatedAt`, `closedAt`, `error`, `input` and `output` |
299
+ | `deliverEvent(runId, { eventId, name, payload? }, options?)` | `{ recorded }`, false when the `eventId` was already recorded |
300
+
301
+ A start runs the published version of the workflow. Preview and sandbox starts
302
+ run the published build too, and a start before the first publish throws
303
+ `WorkflowNotPublishedError`. Pass the workflow's definition to type the input
304
+ and check it against the workflow's input schema before anything is sent. An
305
+ input that fails the check throws `RunInputInvalidError`, creates no run and
306
+ leaves the idempotency key unused. In preview, between a schema change and the
307
+ next publish, the check uses the changed schema while the run uses the
308
+ published one. A workflow id string also works, without the check.
309
+
310
+ Derive `idempotencyKey` (1–64 printable ASCII characters) from the event that
311
+ starts the run. A repeat with the same key and input returns the run the key
312
+ started, in its current state. The same key with another input throws
313
+ `IdempotencyKeyReusedError`; an input object rebuilt with another key order
314
+ counts as another input. The SDK never retries a call and never makes up a key.
315
+
316
+ The input is any JSON value, at most 2 MiB serialized. Pass larger data by
317
+ reference: store it and pass its id. Integers above 2^53 lose precision, so
318
+ pass them as strings. A project can start 100 runs, read 1,000 runs and deliver
319
+ 100 events a second.
320
+
321
+ `getRun` reads every run of the app's project, scheduled and editor test runs
322
+ included. `completed`, `failed`, `cancelled` and `skipped` are final; treat
323
+ `unknown` and any status added later as open. `output` is set once the run is
324
+ `completed`.
325
+
326
+ `deliverEvent` resumes the `ctx.waitForEvent(name)` call that waits on `name`.
327
+ Events are not queued: an open run that doesn't wait on the name yet throws
328
+ `RunNotWaitingError`, and a finished run throws `RunClosedError`. A retry with
329
+ the same `eventId` is always safe. An omitted `payload` resolves the wait with
330
+ no value, and `null` resolves it with `null`.
331
+
332
+ Every call takes an optional `signal`. Aborting stops the wait for the answer;
333
+ it does not undo a start or a delivery the gateway already received, so retry
334
+ with the same idempotency key or `eventId`.
335
+
336
+ Every error extends `WorkflowsApiError`, with `type`, `status`, `requestId`,
337
+ `retryable` and `retryAfterMs`. Its `toJSON()` never contains the API key.
338
+
339
+ | Error | Cause | Retryable |
331
340
  | --- | --- | --- |
332
- | `entry` | `src/lib/workflows/index.ts` | Collection entry; a missing file means no route |
333
- | `routesDir` | `src/routes` | Where the route file is written |
334
- | `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
335
- | `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
336
- | `runRoute` | `false` | Emit the route at all |
337
-
338
- ### Calling it
339
-
340
- `POST /api/workflows/{workflow-id}` with a JSON body. The body is decoded by
341
- `parseWorkflowRequest`, so one route takes every traffic shape: `{ "input": ... }`
342
- starts a run, `{ "runId", "approval" }` delivers an approval decision, and
343
- `{ "runId", "signal" }` delivers a signal. A run that parks on `ctx.approve` or
344
- `ctx.waitForEvent` resumes on this same route — there is no separate resume
345
- endpoint. An unknown workflow ID returns 404, an unparseable body 400, and
346
- `{ "abort": true }` returns 501 until a shared run registry exists.
347
-
348
- The response is `text/event-stream`. Each engine event becomes one SSE message
349
- whose event name is the event `type` and whose data is the whole event as JSON:
350
-
351
- ```text
352
- event: RUN_STARTED
353
- data: {"type":"RUN_STARTED","ts":1790505539351,"runId":"run_1790505539350_yin41cp"}
354
-
355
- event: STEP_FINISHED
356
- data: {"type":"STEP_FINISHED","ts":1790505539352,"stepId":"greeting","result":"Hello, YEHYA!"}
357
-
358
- event: RUN_FINISHED
359
- data: {"type":"RUN_FINISHED","ts":1790505539352,"runId":"run_1790505539350_yin41cp","output":{"message":"Hello, YEHYA!"}}
341
+ | `WorkflowNotPublishedError` | The workflow has no published version: ask the user to publish | No |
342
+ | `IdempotencyKeyReusedError` | The key already started a run from another request | No |
343
+ | `RunInputInvalidError` | The input fails the workflow's input schema | No |
344
+ | `RunNotWaitingError` | No step of the open run waits on the event name now | Yes, while the run is open |
345
+ | `RunClosedError` | The run has finished | No |
346
+ | `RunNotFoundError` | No such run in this project | No |
347
+ | `EventAlreadyDeliveredError` | The `eventId` already answered a wait with another name | No |
348
+ | `WorkflowsPayloadTooLargeError` | The input or payload is over its limit | No |
349
+ | `WorkflowsRateLimitedError`, `WorkflowsUnavailableError` | Over the project's limit, or the service is busy | Yes, after `retryAfterMs` |
350
+ | `WorkflowsNetworkError` | No answer arrived; the start may have happened | Yes, with the same key |
351
+ | `WorkflowsAuthenticationError` | The key is invalid or no longer registered: rotate `LOVABLE_API_KEY`, then republish or restart the backend | No |
352
+ | `WorkflowsKeyLookupError` | The gateway could not check the key | Yes |
353
+ | `WorkflowsDevelopmentKeyError` | A development key reached production | No |
354
+ | `WorkflowsDisabledError` | App workflows are off for the project | No |
355
+ | `WorkflowsRequestInvalidError` | An argument or the request is invalid | No |
356
+ | `WorkflowsConfigurationError` | A browser, a missing `LOVABLE_API_KEY` or a bad `LOVABLE_WORKFLOWS_API_URL` | No |
357
+
358
+ `LOVABLE_WORKFLOWS_API_URL` overrides the gateway URL, which defaults to
359
+ `https://connector-gateway.lovable.dev`. Lovable sets it for local development.
360
+
361
+ ## Build integration
362
+
363
+ Add `workflowsPlugin()` before the TanStack Start plugin. Its `entry` defaults
364
+ to `src/lib/workflows/index.ts` and must default-export the registered
365
+ collection. See [the Vite example](examples/vite.config.ts).
366
+
367
+ ```ts
368
+ plugins: [
369
+ workflowsPlugin(),
370
+ tanstackStart(),
371
+ ];
360
372
  ```
361
373
 
362
- Run state lives in a process-local `inMemoryRunStore()`: runs are lost on restart
363
- and are invisible to other instances. Pass `runStore` to
364
- `createTanStackWorkflowHandler` to supply another one. The control-plane store is
365
- a follow-up.
366
-
367
- The path carries no build ID. Version pinning belongs to the signed invocation,
368
- which leaves this path stable across deployments and safe to publish in a
369
- manifest. Triggers name a workflow rather than an endpoint, so firing one is a
370
- POST to that workflow's path with the trigger's input; no trigger identifier
371
- appears in the URL.
372
-
373
- ## Next PRs
374
-
375
- Connect the manifest and app code to Lovable deployment and runtime execution.
376
- Derive and apply the per-schedule smear on the control plane. Define support for
377
- TanStack primitives, version routing, and schedule policies.
378
- Add webhook and app-event triggers to the same `triggers` array.
379
-
380
- ## Publishing dev builds
381
-
382
- The [publishing workflow](../../.github/workflows/publish-workflows-sdk.yml)
383
- publishes the version committed in `package.json` to npm's `latest` tag when SDK
384
- changes land on `main`. Manage versions manually: `0.0.0-dev`, `0.0.0-dev.1`,
385
- `0.0.0-dev.2`, and so on. The workflow rejects versions outside this series and
386
- skips versions already published. Manual runs default to a dry run.
387
- See [the setup guide](PUBLISHING.md) for the
388
- one-time bootstrap and npm trusted-publisher configuration.
389
-
390
- Install the newest build with `npm install @lovable.dev/workflows-sdk`, or pin
391
- the exact version shown in the workflow run's summary. `latest` tracks every dev
392
- publish while the SDK is pre-1.0; the older `dev` tag is frozen at `0.0.0-dev.2`.
393
-
394
- The engine's embedded SDK
395
- ([`sdk_embed/index.ts`](../../go/workflows/services/workflows/internal/bundler/sdk_embed/index.ts))
396
- provides the engine contract. Use [`mcp-js`](../lovable-mcp-js) as the reference
397
- for separating authoring, manifest extraction, and framework integration. The
398
- workflow prototype's `ts/workflow-sdk` supplies adapter and manifest examples.
374
+ ## Imports
375
+
376
+ | Import | Provides |
377
+ | --- | --- |
378
+ | `@lovable.dev/workflows-sdk` | Workflow authoring, registration, cadences, schedules, and `startRun`, `getRun` and `deliverEvent` |
379
+ | `@lovable.dev/workflows-sdk/vite` | Lovable build integration |