@lovable.dev/workflows-sdk 0.0.0-dev.5 → 0.0.0-dev.52

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,317 +26,194 @@ 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. `every()`, `hourly()`,
57
- `daily()`, 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 old definitions and their relevant helpers unchanged until their runs and
57
+ pending execution attempts drain. Removing a definition makes its version
58
+ unavailable; existing runs never switch to the current version automatically.
59
+
60
+ ## Durable operations
61
+
62
+ Every durable operation needs a static, user-facing description:
63
+
64
+ | Operation | Description field |
65
+ | --- | --- |
66
+ | `ctx.step` | Third argument: `meta.description` |
67
+ | `ctx.llm` | Second argument: `meta.description` |
68
+ | `ctx.sleep`, `ctx.sleepUntil` | Second argument: `meta.description` |
69
+ | `ctx.waitForEvent` | Second argument: `meta.description` |
70
+ | `ctx.now`, `ctx.uuid` | First argument: `meta.description` |
71
+ | `ctx.approve` | First argument: `description` |
72
+
73
+ `ctx.llm(request, options): Promise<string>` calls AI Gateway inside the app
74
+ and returns assistant text. Pass a provider-prefixed `model` and either `prompt`
75
+ or nonempty text-only user/assistant `messages`. Optional `system` supplies system
76
+ instructions; `maxTokens` defaults to 4096. Use a unique `options.id` and a literal
77
+ `options.meta.description`, with item-based template IDs for repeated calls.
78
+ Compatible OpenAI and Gemini Chat Completions text models are supported.
79
+ Streaming, tools, images, and structured output are outside this API.
80
+
81
+ The Gateway SDK reads the app's server-side `LOVABLE_API_KEY`; the generated
82
+ workflow route authenticates the Temporal activity with `LOVABLE_WORKFLOWS_KEY`.
83
+ LLM steps use the same execution, forks, replay, and activity-controlled retries
84
+ as code steps. Discovery and unselected branches make no model calls. Saved text
85
+ replays; saved final errors throw into the workflow's `try/catch`. Gateway SDK
86
+ retries are disabled. A result lost before persistence can be generated again
87
+ on an activity retry, just as code-step side effects can repeat.
88
+
89
+ Before choosing a model, install `@lovable.dev/ai-gateway` in the app and run:
90
+
91
+ ```sh
92
+ bun -e 'import { listModels } from "@lovable.dev/ai-gateway"; console.log(JSON.stringify(await listModels()));'
93
+ ```
94
+
95
+ Require `workspace_models: "included"`; missing markers, public catalogs, and
96
+ invalid credentials do not establish project access. Choose an exact eligible
97
+ OpenAI or Gemini model ID whose `supported_surfaces` includes `chat-completions`
98
+ and `modalities.output` includes `text`. Use the project's resolved default when
99
+ compatible, then run `bunx ai-gateway generate --model <model-id>` and inspect its
100
+ Chat Completions contract for text support. Discovery happens while authoring,
101
+ not on every workflow run.
102
+
103
+ Run LLM workflows through the generated `/steps` route. The standalone
104
+ `createTanStackWorkflowHandler` uses TanStack's runtime and does not support LLM steps.
105
+ Real app-side calls require SDK `0.0.0-dev.49` or newer.
106
+
107
+ Both `ctx.approve` and `ctx.waitForEvent` require `timeoutMs`: a duration in
108
+ milliseconds, written as a finite numeric literal of at least 60000 (one minute) (for example,
109
+ `3600000` for one hour or `86400000` for one day). The Vite build fails if it
110
+ is omitted, computed, or invalid. Do not pass an absolute timestamp or the
111
+ upstream `deadline` option. Execution computes expiry when the wait first
112
+ parks, then preserves that expiry across replays.
67
113
 
68
114
  ```ts
69
- import { daily, defineSchedule, every, hourly, weekly } from "@lovable.dev/workflows-sdk";
70
-
71
- defineSchedule({ id: "heartbeat", workflow: sync, cadence: every("5m"), timeZone: "UTC", input: {} });
72
- defineSchedule({ id: "sweep", workflow: sync, cadence: hourly({ at: ":30" }), timeZone: "UTC", input: {} });
73
- defineSchedule({ id: "digest", workflow: digest, cadence: daily(), timeZone: "Europe/Stockholm", input: {} });
74
-
75
- defineSchedule({
76
- id: "weekday-digest",
77
- workflow: digest,
78
- cadence: daily({ at: "09:00", days: ["mon", "tue", "wed", "thu", "fri"] }),
79
- timeZone: "America/New_York",
80
- smear: { window: "15m" },
81
- input: {},
115
+ await ctx.step("load-customer", () => loadCustomer(ctx.input.customerId), {
116
+ meta: { description: "Load the customer record" },
82
117
  });
118
+ ```
119
+
120
+ Every durable operation takes an explicit `id` — `ctx.approve({ id, title, timeoutMs: 86400000 })`,
121
+ `ctx.waitForEvent(name, { id, timeoutMs: 3600000 })`, `ctx.sleep(ms, { id })`, `ctx.now({ id })` —
122
+ and none is derived from a title, name or duration. IDs share one namespace per
123
+ workflow, so the build fails on a missing or repeated one, including two calls
124
+ on mutually exclusive branches. Keep side effects inside step bodies;
125
+ handler code outside a step may run more than once. A step body is one atomic
126
+ execution unit and cannot contain another durable operation.
127
+
128
+ Keep durable control flow in the workflow handler. Do not pass, alias,
129
+ destructure, or return `ctx`, and do not detach methods such as `ctx.step`.
130
+ Pass extracted data such as `ctx.input.customerId` to helpers instead.
131
+
132
+ ### Repeated steps
83
133
 
84
- defineSchedule({
85
- id: "monday-report",
86
- workflow: report,
87
- cadence: weekly({ on: "monday", at: "07:00" }),
88
- timeZone: "Europe/Stockholm",
89
- input: {},
134
+ A step inside a loop or callback needs `meta.group` with a stable ID and
135
+ user-facing label. Each repeated step still needs its own dynamic ID:
136
+
137
+ ```ts
138
+ ctx.step(`process-${item.id}`, () => processItem(item), {
139
+ meta: { description: "Process an item", group: { id: "process-items", label: "Process items" } },
90
140
  });
91
141
  ```
92
142
 
93
- | Field | Default | Meaning |
94
- | --- | --- | --- |
95
- | `cadence` | — | `every()`, `hourly()`, `daily()`, or `weekly()` |
96
- | `timeZone` | — | IANA region name the cadence is interpreted in |
97
- | `overlapPolicy` | `"skip"` | `skip`, `cancel-previous`, or `terminate-previous` |
98
- | `enabled` | `true` | `false` declares a paused schedule without deleting it |
99
- | `smear` | see below | `false`, or `{ window: "15m" }` to spread firings over a window |
100
-
101
- There are four cadences and no raw cron, so every schedule has a firing period
102
- the SDK can compute and a calendar the SDK can check. `at` pins the position
103
- inside the period on all three calendar cadences, and omitting it hands that
104
- position to the smear:
105
-
106
- | Cadence | Pins | Example | Derived `cron` |
107
- | --- | --- | --- | --- |
108
- | `every(interval)` | — | `every("5m")` | `*/5 * * * *` |
109
- | `hourly({ at })` | minute past the hour | `hourly({ at: ":30" })` | `30 * * * *` |
110
- | `daily({ at, days })` | time of day, days of week | `daily({ at: "09:00", days: ["mon", "tue", "wed", "thu", "fri"] })` | `0 9 * * 1-5` |
111
- | `weekly({ on, at })` | one day, time of day | `weekly({ on: "monday", at: "07:00" })` | `0 7 * * 1` |
112
-
113
- `every` takes a whole number of minutes, hours, or days that divides its unit
114
- evenly — `1m` through `30m`, `1h` through `12h`, or `1d`. `hourly({ at: ":30" })`
115
- carries the leading colon so a minute past the hour can never be misread as an
116
- hour of the day. `days` accepts `"mon"` or `"monday"` in any case and is stored
117
- sorted and deduplicated, so two orderings of one weekday set are one schedule.
118
-
119
- `weekly({ on, at })` is the single-day shorthand for `daily({ at, days: [on] })`
120
- and resolves into exactly that cadence. There is one internal representation of
121
- a day-restricted schedule, so the two spellings emit byte-identical manifests
122
- and hash alike. There is no `"weekdays"` or `"weekends"` shorthand: it would add
123
- a third spelling of a set `days` already states, and "the weekend" is Friday and
124
- Saturday in much of the world, so the word would quietly mean the wrong days.
125
-
126
- The manifest still carries a five-field `cron` string derived from the cadence,
127
- because the engine registers native schedules that take cron. Apps no longer
128
- write it.
129
-
130
- ### Time zone
131
-
132
- `timeZone` is required on every schedule. There is no default, because every
133
- available default is wrong: `daily({ at: "09:00" })` in UTC is not the 09:00 a
134
- reader of the digest expects, and the build machine's own zone would make one
135
- app source fire at different times depending on where it was built.
136
-
137
- It must be an IANA region name such as `"Europe/Stockholm"`, or `"UTC"`.
138
- Fixed offsets and abbreviations — `"+05:00"`, `"-0800"`, `"EST"` — are
139
- rejected even though the platform accepts them: they do not observe daylight
140
- saving, so `"EST"` is an hour off US Eastern for two-thirds of the year.
141
- `every()` needs one too, since its derived cron anchors to hour and day
142
- boundaries that a DST change moves.
143
-
144
- Everything is validated when the schedule is defined, at build time: a malformed
145
- interval, time of day, or weekday name, an unknown `overlapPolicy`, a missing or
146
- non-IANA zone, and a smear window wider than the cadence's own firing period all
147
- fail the build.
148
-
149
- ### Smear
150
-
151
- Tens of thousands of apps declaring `daily()` must not fire in the same minute.
152
- A schedule therefore carries a smear *policy*, not a concrete offset. A cadence
153
- that leaves its position in the period unpinned defaults to spreading over that
154
- whole period: bare `daily()` to `{ strategy: "hash", windowSeconds: 86400 }` and
155
- bare `hourly()` to `{ strategy: "hash", windowSeconds: 3600 }`. Every pinned
156
- cadence — `every`, `hourly({ at })`, `daily({ at })`, `weekly({ on, at })` —
157
- defaults to `{ strategy: "none" }`, because the app author chose the time.
158
- `smear: false` on an unpinned cadence is rejected: pass `{ at }` instead.
159
-
160
- The concrete offset is derived once, when the control plane registers the
161
- manifest, as `fnv1a64(projectId + "\0" + scheduleId) % windowSeconds` seconds
162
- after the manifest's `cron`. That keeps the manifest project-independent and
163
- therefore content-addressable, while giving two projects that both name a
164
- schedule `digest` different fire minutes, and giving one project the same fire
165
- minute across every rebuild. `smearOffsetSeconds(projectId, scheduleId,
166
- windowSeconds)` is the reference implementation the engine and the run UI agree
167
- with.
168
-
169
- Any cadence can opt in with `smear: { window }`. The window may never exceed the
170
- cadence's own firing period, or two firings would overrun each other; the bound
171
- applies to every cadence, since every cadence's period is computable. For a day
172
- set the period is the shortest gap between two firings, not the repeat length:
173
- `daily({ days: ["mon", "fri"] })` fires again in three days and then in four, so
174
- its bound is three days — capped, as every window is, at `1d`.
175
-
176
- The [example](examples/src/lib/workflows/index.ts) declares a 09:00 greeting in
177
- Europe/Stockholm, a smeared weekday greeting in America/New_York, a Monday
178
- report, a five-minute heartbeat, an hourly sweep, and a paused daily digest.
179
-
180
- ## Manifest generation
181
-
182
- Add `workflowsPlugin()` from `@lovable.dev/workflows-sdk/vite` to the app's Vite
183
- plugins. Its `entry` defaults to `src/lib/workflows/index.ts` and must
184
- default-export the app's `registerWorkflows()` collection. Each production build writes
185
- one manifest per workflow to `.lovable/workflows/{workflow-name}.json` relative
186
- to the app root. For example, `greet` produces `.lovable/workflows/greet.json`.
187
- Generation errors fail the build. See [the Vite example](examples/vite.config.ts).
188
-
189
- Each version-1 manifest contains a single `workflow` with its ID, description,
190
- version, and input/output/state JSON Schemas, a `graph` for visualization, and a
191
- `triggers` array containing only that workflow's triggers and static inputs. Each
192
- entry names its kind in `type` — `"schedule"` today — and a schedule entry carries
193
- its `cadence`, derived `cron`, `timeZone`, `enabled`, `overlapPolicy`, `smear`, and
194
- `input`. It is an SDK discovery format, not the engine's deployment or execution
195
- contract. Handlers and middleware stay in app code. Triggers and JSON object keys
196
- are sorted for stable output.
197
-
198
- The SDK manages the JSON files in `.lovable/workflows/`. Successful generation
199
- removes manifests for deleted or renamed workflows; an empty collection removes
200
- all JSON manifests. Other files and subdirectories are preserved. All definitions
201
- are validated before writing, and each file is replaced by rename so readers
202
- never see a partially written JSON document.
203
-
204
- Schemas must implement [Standard JSON Schema](https://standardschema.dev/json-schema)
205
- conversion to draft 2020-12, as Zod 4 does. Missing conversion support and
206
- conversion errors fail generation. Schedule inputs must be plain JSON and pass
207
- the workflow's input schema; the manifest retains the raw input for validation
208
- when a run starts. Functions, undefined values, non-finite numbers, class
209
- instances, and cycles are rejected. `previousVersions` is rejected until version
210
- routing has a manifest contract.
211
-
212
- The plugin evaluates the entry using a separate Vite SSR loader with the app's
213
- aliases, mode, defines, and SSR dependency rules. Module-level code and schema
214
- validators run during extraction; workflow handlers and middleware do not.
215
- Custom app transform plugins and virtual modules are not loaded by this loader.
216
- For another build system, call `await generateManifests(collection)` and make
217
- synchronizing the returned manifests to `.lovable/workflows/` a required build step.
218
-
219
- ### Step graph
220
-
221
- Each manifest's `graph` contains `nodes` and directed `edges`. The SDK parses the
222
- handler's function source without executing it. No additional registration is needed.
223
-
224
- Graph inference reads the app's own `typescript`, an optional peer. Apps built
225
- from a Lovable template already have it. Without it — or with a copy exposing no
226
- stable JS API, as TypeScript 7 does before 7.1 — the build still succeeds and
227
- every graph carries one `unknown` node and the diagnostic
228
- `Install typescript to infer step graphs`.
229
- Sequential awaited `ctx.step("name", callback)` calls produce order edges;
230
- `await Promise.all([ctx.step(...), ctx.step(...)])` produces parallel branches
231
- that join at the next step. Returned step promises work too. Keep step IDs literal.
232
-
233
- | Field | Meaning |
234
- | --- | --- |
235
- | `nodes[].id` | Unique occurrence ID within this graph; use as the UI node key |
236
- | `nodes[].kind` | `step` or `unknown` |
237
- | `nodes[].stepId` | Literal step name, present for known steps |
238
- | `nodes[].label` | Step name or explanation of unsupported code |
239
- | `edges[]` | `{ source, target, kind: "order" }`, referencing node IDs |
240
- | `complete` | Whether the handler uses only supported syntax |
241
- | `diagnostics` | Reasons the graph is partial |
242
-
243
- For example, `read` followed by parallel `transform-a` and `transform-b`, then
244
- `save`, produces `read → transform-a → save` and `read → transform-b → save`.
245
- Repeated step names remain separate nodes. Node IDs are deterministic for the
246
- same source, but may change when the handler is edited.
247
-
248
- Graphs have `source: "inferred"` and `scope: "handler"`. They describe source
249
- structure, not run history or data dependencies, and exclude middleware and
250
- initialization. Branches, loops, helper calls, dynamic step IDs, nested steps,
251
- and unawaited steps produce `unknown` nodes and `complete: false`; steps inside
252
- unsupported code are not expanded. The UI should show these unknown nodes and
253
- mark partial graphs. Transforms that rewrite the handler may also produce a
254
- partial graph. A handler with no steps can have an empty graph.
255
-
256
- ## Run endpoint (TanStack Start)
257
-
258
- Pass `runRoute: true` to the same `workflowsPlugin` that writes the manifests. It
259
- then also emits one dynamic route, `src/routes/api/workflows/$workflowId.ts`,
260
- serving every registered workflow. One plugin and one `entry` cover both, so a
261
- manifest can never describe a collection the route does not serve:
143
+ For dynamic sequential work, await one step directly as the only statement in
144
+ a `for...of` loop. For dynamic parallel work, use a mapped `Promise.all()`.
145
+ Both forms support `ctx.step` and `ctx.llm`; see [order summaries](examples/src/lib/workflows/order-summaries/index.ts).
146
+ Use a different group ID for each repeated callsite, and derive item IDs from
147
+ workflow input or saved step results so replay reaches the same operations.
148
+ Fixed `Promise.all([stepA, stepB])` branches and ordinary sequential steps do
149
+ not need a group.
150
+
151
+ ### Conditional steps
152
+
153
+ Durable operations inside `if` and `else` branches include an outer-to-inner
154
+ `meta.branches` path. Both sides of one condition use the same static ID and
155
+ description:
262
156
 
263
157
  ```ts
264
- import { tanstackStart } from "@tanstack/react-start/plugin/vite";
265
- import { workflowsPlugin } from "@lovable.dev/workflows-sdk/vite";
158
+ meta: {
159
+ description: "Publish the approved draft",
160
+ branches: [{ id: "editor-approved", description: "The editor approved the draft" }],
161
+ }
162
+ ```
163
+
164
+ ## Schedules
165
+
166
+ Declare schedules with `defineSchedule({ id, workflow, cadence, timeZone,
167
+ input })` and include them in the collection's `triggers`. The workflow must be
168
+ part of the same collection, and schedule IDs must be unique. This API declares
169
+ schedules; Lovable execution is not available yet.
266
170
 
267
- export default defineConfig({
268
- plugins: [workflowsPlugin({ runRoute: true }), tanstackStart()],
171
+ ```ts
172
+ const morning = defineSchedule({
173
+ id: "morning-digest", workflow: digest, cadence: daily({ at: [9] }), timeZone: "Europe/Stockholm", input: {},
269
174
  });
270
175
  ```
271
176
 
272
- `runRoute` defaults to `false`. The route is unauthenticated: any caller who
273
- reaches it runs any declared workflow. Turn it on only where that is acceptable,
274
- until signed invocation lands.
177
+ | Field | Default | Meaning |
178
+ | --- | --- | --- |
179
+ | `cadence` | — | `hourly()`, `daily({ at })`, or `weekly({ on, at })` |
180
+ | `timeZone` | — | Canonical IANA region name |
181
+ | `overlapPolicy` | `"skip"` | `skip`, `allow`, or `buffer-one` |
182
+ | `enabled` | `true` | `false` declares a paused schedule |
275
183
 
276
- The emitted file is thin — it imports the collection and mounts
277
- `createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk/stacks/tanstack`
278
- as the route's `POST` handler. All runtime logic stays in the package. The file
279
- carries a generated banner, which is the plugin's ownership token: it rewrites
280
- and deletes only files that have it, and deletes its own orphans when `path`,
281
- `workflowIdParam`, or `runRoute` changes. Delete the banner line to take the
282
- route over — the plugin then leaves that file alone, and the build keeps
283
- working.
184
+ | Cadence | Example |
185
+ | --- | --- |
186
+ | Hourly | `hourly()` |
187
+ | Selected hours | `daily({ at: [0, 6, 12, 18] })` |
188
+ | Weekly | `weekly({ on: ["mon", "fri"], at: [0, 12] })` |
284
189
 
285
- | Option | Default | Meaning |
286
- | --- | --- | --- |
287
- | `entry` | `src/lib/workflows/index.ts` | Collection entry; a missing file means no route |
288
- | `routesDir` | `src/routes` | Where the route file is written |
289
- | `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
290
- | `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
291
- | `runRoute` | `false` | Emit the route at all |
292
-
293
- ### Calling it
294
-
295
- `POST /api/workflows/{workflow-id}` with a JSON body. The body is decoded by
296
- `parseWorkflowRequest`, so one route takes every traffic shape: `{ "input": ... }`
297
- starts a run, `{ "runId", "approval" }` delivers an approval decision, and
298
- `{ "runId", "signal" }` delivers a signal. A run that parks on `ctx.approve` or
299
- `ctx.waitForEvent` resumes on this same route — there is no separate resume
300
- endpoint. An unknown workflow ID returns 404, an unparseable body 400, and
301
- `{ "abort": true }` returns 501 until a shared run registry exists.
302
-
303
- The response is `text/event-stream`. Each engine event becomes one SSE message
304
- whose event name is the event `type` and whose data is the whole event as JSON:
305
-
306
- ```text
307
- event: RUN_STARTED
308
- data: {"type":"RUN_STARTED","ts":1790505539351,"runId":"run_1790505539350_yin41cp"}
309
-
310
- event: STEP_FINISHED
311
- data: {"type":"STEP_FINISHED","ts":1790505539352,"stepId":"greeting","result":"Hello, YEHYA!"}
312
-
313
- event: RUN_FINISHED
314
- data: {"type":"RUN_FINISHED","ts":1790505539352,"runId":"run_1790505539350_yin41cp","output":{"message":"Hello, YEHYA!"}}
190
+ `daily` requires a non-empty `at` list. `weekly` requires non-empty `on` and
191
+ `at` lists and runs at every selected hour on every selected weekday. Hours are
192
+ whole numbers from 0 through 23; schedules do not accept minute or raw-cron
193
+ fields. `timeZone` is required and accepts `"UTC"` or a canonical IANA region
194
+ such as `"America/New_York"`. A scheduled hour is approximate: Lovable chooses
195
+ a stable offset within the corresponding scheduling window.
196
+
197
+ `overlapPolicy` controls what happens when a schedule becomes due while its
198
+ previous run is active. `skip` drops it, `allow` starts another run, and
199
+ `buffer-one` starts the earliest missed run after the active run finishes.
200
+
201
+ ## Build integration
202
+
203
+ Add `workflowsPlugin()` before the TanStack Start plugin. Its `entry` defaults
204
+ to `src/lib/workflows/index.ts` and must default-export the registered
205
+ collection. See [the Vite example](examples/vite.config.ts).
206
+
207
+ ```ts
208
+ plugins: [
209
+ workflowsPlugin(),
210
+ tanstackStart(),
211
+ ];
315
212
  ```
316
213
 
317
- Run state lives in a process-local `inMemoryRunStore()`: runs are lost on restart
318
- and are invisible to other instances. Pass `runStore` to
319
- `createTanStackWorkflowHandler` to supply another one. The control-plane store is
320
- a follow-up.
321
-
322
- The path carries no build ID. Version pinning belongs to the signed invocation,
323
- which leaves this path stable across deployments and safe to publish in a
324
- manifest. Triggers name a workflow rather than an endpoint, so firing one is a
325
- POST to that workflow's path with the trigger's input; no trigger identifier
326
- appears in the URL.
327
-
328
- ## Next PRs
329
-
330
- Connect the manifest and app code to Lovable deployment and runtime execution.
331
- Define support for TanStack primitives, version routing, and schedule policies.
332
- Add webhook and app-event triggers to the same `triggers` array.
333
-
334
- ## Publishing dev builds
335
-
336
- The [publishing workflow](../../.github/workflows/publish-workflows-sdk.yml)
337
- publishes the version committed in `package.json` to npm's `latest` tag when SDK
338
- changes land on `main`. Manage versions manually: `0.0.0-dev`, `0.0.0-dev.1`,
339
- `0.0.0-dev.2`, and so on. The workflow rejects versions outside this series and
340
- skips versions already published. Manual runs default to a dry run.
341
- See [the setup guide](PUBLISHING.md) for the
342
- one-time bootstrap and npm trusted-publisher configuration.
343
-
344
- Install the newest build with `npm install @lovable.dev/workflows-sdk`, or pin
345
- the exact version shown in the workflow run's summary. `latest` tracks every dev
346
- publish while the SDK is pre-1.0; the older `dev` tag is frozen at `0.0.0-dev.2`.
347
-
348
- The engine's embedded SDK
349
- ([`sdk_embed/index.ts`](../../go/workflows/services/workflows/internal/bundler/sdk_embed/index.ts))
350
- provides the engine contract. Use [`mcp-js`](../lovable-mcp-js) as the reference
351
- for separating authoring, manifest extraction, and framework integration. The
352
- workflow prototype's `ts/workflow-sdk` supplies adapter and manifest examples.
214
+ ## Imports
215
+
216
+ | Import | Provides |
217
+ | --- | --- |
218
+ | `@lovable.dev/workflows-sdk` | Workflow authoring, registration, cadences, and schedules |
219
+ | `@lovable.dev/workflows-sdk/vite` | Lovable build integration |
@@ -0,0 +1,113 @@
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-RIBcr2Xd.js";
2
+ //#region src/manifests/branch-metadata.ts
3
+ const optionsArgument = {
4
+ step: 2,
5
+ connector: 2,
6
+ llm: 1,
7
+ approve: 0,
8
+ sleep: 1,
9
+ sleepUntil: 1,
10
+ waitForEvent: 1,
11
+ now: 0,
12
+ uuid: 0
13
+ };
14
+ async function findBranchMetadataIssues(handler) {
15
+ const api = await loadTypeScript();
16
+ if (!api) return [];
17
+ const ts = api;
18
+ const handlerSource = workflowHandlerSource(handler);
19
+ if (!handlerSource) return [];
20
+ const declaration = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS).statements[0];
21
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
22
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return [];
23
+ const parameter = fn.parameters[0]?.name;
24
+ if (!parameter || !ts.isIdentifier(parameter)) return [];
25
+ const context = parameter.text;
26
+ function property(node, name) {
27
+ if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
28
+ for (const entry of node.properties) {
29
+ if (!ts.isPropertyAssignment(entry)) continue;
30
+ if ((ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name) ? entry.name.text : void 0) === name) return entry.initializer;
31
+ }
32
+ }
33
+ function literalString(node) {
34
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
35
+ }
36
+ function durableCall(node) {
37
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression) || !ts.isIdentifier(node.expression.expression) || node.expression.expression.text !== context || !(node.expression.name.text in optionsArgument)) return;
38
+ return {
39
+ call: node,
40
+ method: node.expression.name.text
41
+ };
42
+ }
43
+ function branchPath(call, method) {
44
+ const options = call.arguments[optionsArgument[method]];
45
+ const branches = property(property(options, "meta"), "branches");
46
+ if (!branches || !ts.isArrayLiteralExpression(branches)) return void 0;
47
+ const path = [];
48
+ for (const element of branches.elements) {
49
+ if (!ts.isObjectLiteralExpression(element)) return void 0;
50
+ const id = literalString(property(element, "id"));
51
+ const description = literalString(property(element, "description"));
52
+ if (id === void 0 || description === void 0) return void 0;
53
+ path.push({
54
+ id,
55
+ description
56
+ });
57
+ }
58
+ return path;
59
+ }
60
+ const issues = [];
61
+ const metadataByBranch = /* @__PURE__ */ new Map();
62
+ const branchById = /* @__PURE__ */ new Map();
63
+ function visit(node, branches) {
64
+ if (issues.length > 0) return;
65
+ if (ts.isIfStatement(node)) {
66
+ visit(node.expression, branches);
67
+ visit(node.thenStatement, [...branches, node]);
68
+ if (node.elseStatement) visit(node.elseStatement, [...branches, node]);
69
+ return;
70
+ }
71
+ const durable = durableCall(node);
72
+ if (durable) {
73
+ const path = branchPath(durable.call, durable.method);
74
+ const stepId = durable.method === "step" || durable.method === "connector" ? literalString(durable.call.arguments[0]) : void 0;
75
+ if (branches.length === 0 && path !== void 0 || branches.length > 0 && (path === void 0 || path.length !== branches.length)) {
76
+ issues.push({
77
+ kind: "path",
78
+ method: durable.method,
79
+ ...stepId === void 0 ? {} : { stepId }
80
+ });
81
+ return;
82
+ }
83
+ for (let index = 0; index < branches.length; index++) {
84
+ const branch = branches[index];
85
+ const entry = path?.[index];
86
+ if (!branch || !entry) continue;
87
+ const existing = metadataByBranch.get(branch);
88
+ if (existing && (existing.id !== entry.id || existing.description !== entry.description)) {
89
+ issues.push({
90
+ kind: "inconsistent",
91
+ branchId: existing.id
92
+ });
93
+ return;
94
+ }
95
+ const existingNode = branchById.get(entry.id);
96
+ if (existingNode && existingNode !== branch) {
97
+ issues.push({
98
+ kind: "duplicate-id",
99
+ branchId: entry.id
100
+ });
101
+ return;
102
+ }
103
+ metadataByBranch.set(branch, entry);
104
+ branchById.set(entry.id, branch);
105
+ }
106
+ }
107
+ ts.forEachChild(node, (child) => visit(child, branches));
108
+ }
109
+ visit(fn, []);
110
+ return issues;
111
+ }
112
+ //#endregion
113
+ export { findBranchMetadataIssues };