@vite-hub/workflow 0.1.0 → 0.4.1

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 (66) hide show
  1. package/README.md +173 -55
  2. package/dist/{app-CzPoP84f.js → app-He0GTrYZ.js} +1 -1
  3. package/dist/client-DkwOxEiT.js +707 -0
  4. package/dist/{cloudflare-nF4abPd4.js → cloudflare-BHfClPvT.js} +2 -2
  5. package/dist/{cloudflare-env-BNrYo29x.js → cloudflare-env-CGLx7lUd.js} +44 -42
  6. package/dist/cloudflare-env-lookup-CfX6wZKb.d.ts +4 -0
  7. package/dist/{cloudflare-env-CIjdFTv6.d.ts → cloudflare-shared-CTqh_a2s.d.ts} +2 -2
  8. package/dist/{config-IJMb0eeZ.js → config-C3DvtjfJ.js} +41 -40
  9. package/dist/definition.d.ts +18 -0
  10. package/dist/definition.js +33 -0
  11. package/dist/delay-D1-nq_VE.js +46 -0
  12. package/dist/dev-recorder-CTN5Fkao.js +10 -0
  13. package/dist/durability.d.ts +23 -0
  14. package/dist/durability.js +62 -0
  15. package/dist/error-diagnostics-0V2T3JFw.js +317 -0
  16. package/dist/error-diagnostics-CQ4BUqRe.js +270 -0
  17. package/dist/errors-DCqRnZpN.js +35 -0
  18. package/dist/errors-uhP8DZTi.d.ts +67 -0
  19. package/dist/index.d.ts +35 -63
  20. package/dist/index.js +15 -19
  21. package/dist/object-Da1zyPCR.js +11 -0
  22. package/dist/openworkflow-BhzxV_Y3.d.ts +52 -0
  23. package/dist/openworkflow-defaults-DDig2M4s.js +26 -0
  24. package/dist/openworkflow-storage-Dj9zUAsk.js +28 -0
  25. package/dist/openworkflow.d.ts +2 -0
  26. package/dist/openworkflow.js +2 -0
  27. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-nmRu_O3V.d.ts} +42 -15
  28. package/dist/operations-D_WJwjrS.js +333 -0
  29. package/dist/operations.d.ts +40 -6
  30. package/dist/operations.js +163 -736
  31. package/dist/{out-CsaJxg8m.js → out-DxLKolA0.js} +32 -1430
  32. package/dist/{rolldown-runtime-CMFfr-1z.js → rolldown-runtime-B4iAMlE-.js} +10 -1
  33. package/dist/run-error-DBWqiJHH.js +110 -0
  34. package/dist/run-failed-gVGo1BaF.js +18 -0
  35. package/dist/runtime/cloudflare-runner.d.ts +3 -5
  36. package/dist/runtime/cloudflare-runner.js +39 -45
  37. package/dist/runtime/cloudflare-shared.d.ts +2 -2
  38. package/dist/runtime/cloudflare-shared.js +1 -1
  39. package/dist/runtime/cloudflare-vite.d.ts +3 -2
  40. package/dist/runtime/cloudflare-vite.js +47 -1
  41. package/dist/runtime/dev-runs.d.ts +4 -0
  42. package/dist/runtime/dev-runs.js +73 -0
  43. package/dist/runtime/execute.d.ts +42 -5
  44. package/dist/runtime/execute.js +216 -17
  45. package/dist/runtime/openworkflow-worker.d.ts +29 -2
  46. package/dist/runtime/openworkflow-worker.js +156 -38
  47. package/dist/runtime/openworkflow.d.ts +2 -21
  48. package/dist/runtime/openworkflow.js +307 -44
  49. package/dist/runtime/state.d.ts +3 -1
  50. package/dist/runtime/state.js +6 -6
  51. package/dist/runtime/vercel-vite.d.ts +1 -1
  52. package/dist/runtime/vercel-vite.js +7 -4
  53. package/dist/types-Dsmwsdlv.d.ts +282 -0
  54. package/dist/{vercel-D-ZNtB_u.js → vercel-DTvm61iY.js} +53 -24
  55. package/dist/vite.d.ts +228 -30
  56. package/dist/vite.js +2640 -1449
  57. package/package.json +28 -50
  58. package/dist/client-DsGM3M4U.js +0 -389
  59. package/dist/cloudflare-shared-CaxrMD1A.d.ts +0 -1
  60. package/dist/cloudflare-vite-B3IabBsv.js +0 -47
  61. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  62. package/dist/error-diagnostics-pwNFvAHP.js +0 -67
  63. package/dist/operations-B_rYG71W.js +0 -230
  64. package/dist/provider-operation-CW2cYfVy.js +0 -65
  65. package/dist/runtime-type-DBCvIh5x.js +0 -7
  66. package/dist/types-D82WmfZa.d.ts +0 -180
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # @vite-hub/workflow
2
2
 
3
3
  <p>
4
- <a href="https://vitehub.dev"><img alt="ViteHub" src="https://comark-ui.onmax.me/badge.svg?label=ViteHub&amp;value=vitehub.dev"></a>
5
- <img alt="TypeScript" src="https://comark-ui.onmax.me/badge.svg?label=TypeScript&amp;value=ready">
6
- <img alt="Vite" src="https://comark-ui.onmax.me/badge.svg?label=Vite&amp;value=discovery">
7
- <img alt="Workflow" src="https://comark-ui.onmax.me/badge.svg?label=Workflow&amp;value=durable+steps">
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/static/v1?label=ViteHub&amp;message=vitehub.dev&amp;color=blue"></a>
5
+ <img alt="TypeScript" src="https://img.shields.io/static/v1?label=TypeScript&amp;message=ready&amp;color=blue">
6
+ <img alt="Vite" src="https://img.shields.io/static/v1?label=Vite&amp;message=discovery&amp;color=blue">
7
+ <img alt="Workflow" src="https://img.shields.io/static/v1?label=Workflow&amp;message=durable+steps&amp;color=blue">
8
8
  </p>
9
9
 
10
10
  `@vite-hub/workflow` discovers named long-running work and exposes one provider-neutral API for starting and inspecting runs.
@@ -17,42 +17,78 @@ Use a Workflow when the application needs a run id, durable state, retries, canc
17
17
  pnpm add @vite-hub/workflow
18
18
  ```
19
19
 
20
- Then install the dependency required by the selected provider:
20
+ Then install the dependency required by the selected driver:
21
21
 
22
22
  | Provider | Additional dependency | Durable state |
23
23
  | -------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------ |
24
- | Cloudflare Workflows | None in application code | Cloudflare owns run state. |
25
- | Vercel Workflow | `workflow` and `@workflow/builders` for native durable definitions | Native definitions survive function restarts; plain handlers run inline. |
26
- | OpenWorkflow | `openworkflow`; add `postgres` when using Postgres | Uses local SQLite by default. Configure durable storage for deployment. |
24
+ | Cloudflare Workflows | None in application code | Cloudflare owns run state. Without the binding, only `vite dev` runs inline; a Worker fails with `WORKFLOW_R0036`. |
25
+ | Vercel Workflow | `@vercel/functions`; add `workflow@5.2.3` and `@workflow/builders@5.0.6` for native durable definitions ([versions](#make-a-vercel-workflow-durable)) | Native definitions survive function restarts; plain handlers run inline. |
26
+ | OpenWorkflow | None. `@vite-hub/workflow` depends on `openworkflow` and `postgres` | Postgres Default Database, else a local SQLite file. |
27
27
 
28
- Importing the provider-neutral package root does not load OpenWorkflow types. Worker lifecycle helpers live at `@vite-hub/workflow/runtime/openworkflow-worker`.
28
+ Importing the provider-neutral package root does not load OpenWorkflow types. Worker lifecycle helpers live at `@vite-hub/workflow/openworkflow`.
29
29
 
30
- Set `workflow.sqlite.path` or `workflow.postgres.url` to select OpenWorkflow storage. An explicit value takes precedence over ambient storage environment variables. A configured environment declaration must resolve to a value; missing configuration rejects before opening a backend. With no storage configuration or storage environment variables, OpenWorkflow uses `.vitehub/data/openworkflow.sqlite.db`.
30
+ On Node and Docker, ViteHub selects OpenWorkflow when `driver` is not set, also in `vite dev` with the `node` host. OpenWorkflow reads its storage at runtime. Set `workflow.sqlite.path` or `workflow.postgres.url` to select the storage yourself. An explicit value takes precedence over ambient storage environment variables. Without it, `OPENWORKFLOW_SQLITE_PATH` selects SQLite, then `OPENWORKFLOW_POSTGRES_URL` selects Postgres. Then, when the app has a Postgres Default Database, OpenWorkflow uses its connection URL (`getPostgresConnectionUrl()` from `@vite-hub/database`). A `DATABASE_URL` alone is not used, the same as for Queue and Realtime. If it contains a `postgres://` or `postgresql://` URL and storage would otherwise fall back to SQLite, resolution fails with `WORKFLOW_OPENWORKFLOW_DATABASE_URL_IGNORED`. Before upgrading, set `OPENWORKFLOW_POSTGRES_URL` or `workflow.postgres.url` to that same URL, or add a Postgres Default Database pointing to the existing database. Keep the same schema and namespace to retain queued and sleeping runs. Select `workflow.sqlite.path` or `OPENWORKFLOW_SQLITE_PATH` to choose local storage intentionally. Other `DATABASE_URL` schemes do not trigger the error. `vite dev` keeps runs in the local SQLite file unless `workflow.remote` is `true`, so a dev server never runs the runs of a shared database. A configured environment declaration must resolve to a value; missing configuration rejects before opening a backend. With no storage configuration or storage environment variables, OpenWorkflow uses `.vitehub/data/openworkflow.sqlite.db`, and the server logs at boot that other instances do not see those runs.
31
31
 
32
32
  The former `workflow.database` option was never connected to Named Databases. It now rejects instead of silently selecting fallback storage. Replace it with `workflow.sqlite.path` or `workflow.postgres.url`.
33
33
 
34
34
  ## Define a workflow
35
35
 
36
- ```ts
36
+ ```ts fragment
37
37
  // server/workflows/onboard-user.ts
38
38
  import { defineWorkflow } from "@vite-hub/workflow";
39
39
 
40
- export default defineWorkflow<{ email: string }>(async ({ id, payload, provider }) => {
41
- const idempotencyKey = `onboard-user:${payload.email}`;
42
- const user = await upsertUser(payload.email, { idempotencyKey });
43
- await sendWelcomeEmail(user.email, { idempotencyKey: `${idempotencyKey}:welcome-email` });
40
+ export default defineWorkflow<{ email: string }>({
41
+ handler: async ({ payload, id, provider }) => {
42
+ const idempotencyKey = `onboard-user:${payload.email}`;
43
+ const user = await upsertUser(payload.email, { idempotencyKey });
44
+ await sendWelcomeEmail(user.email, { idempotencyKey: `${idempotencyKey}:welcome-email` });
44
45
 
45
- return { id, provider };
46
+ return { id, provider };
47
+ },
46
48
  });
47
49
  ```
48
50
 
49
51
  Both external operations receive keys derived from stable input. Preserve that idempotency when adding side effects so retrying a completed operation does not duplicate it.
50
52
 
51
- ViteHub discovers `server/workflows/<name>.ts`, folder workflows such as `server/workflows/onboard-user/index.ts`, and `src/<name>.workflow.ts`. The file name becomes the name passed to runtime helpers.
53
+ ViteHub discovers `server/workflows/<name>.ts`, folder workflows such as `server/workflows/onboard-user/index.ts`, and `src/<name>.workflow.ts`. The file or folder path is the Workflow name. `defineWorkflow()` takes one object and no name. Pass the name to the runtime helpers.
52
54
 
53
- ## Configure the provider
55
+ The handler gets one object with `payload`, `id`, `name`, `provider`, `sleep`, and `steps`. Pass the payload type as the type argument of `defineWorkflow()`. ViteHub writes the names and payload types to `.vitehub/workflow.d.ts`, so `startWorkflow("onboard-user", payload)` checks both.
54
56
 
55
- ```ts
57
+ ## Call typed steps
58
+
59
+ A folder Workflow runs its numbered files as steps. `01.create-user.ts` becomes `steps.createUser`:
60
+
61
+ ```ts [server/workflows/onboard-user/index.ts]
62
+ // server/workflows/onboard-user/index.ts
63
+ import { defineWorkflow } from "@vite-hub/workflow";
64
+
65
+ export default defineWorkflow<{ email: string }>({
66
+ handler: async ({ payload, steps }) => {
67
+ const user = await steps.createUser(payload);
68
+ return await steps.sendWelcome(user);
69
+ },
70
+ });
71
+ ```
72
+
73
+ ```ts [server/workflows/onboard-user/01.create-user.ts]
74
+ // server/workflows/onboard-user/01.create-user.ts
75
+ export default async function createUser(input: { email: string }) {
76
+ return { id: `user:${input.email}`, email: input.email };
77
+ }
78
+ ```
79
+
80
+ ```ts [server/workflows/onboard-user/02.send-welcome.ts]
81
+ // server/workflows/onboard-user/02.send-welcome.ts
82
+ export default async function sendWelcome(user: { id: string, email: string }) {
83
+ return { userId: user.id, welcomeSent: true };
84
+ }
85
+ ```
86
+
87
+ The Vite Integration writes `.vitehub/workflow.d.ts`. A step name shared by multiple folders accepts only inputs that all those steps accept and can return any of their result types. A call to a step that has no file is a type error. At runtime, only the current folder's steps are available. Include `.vitehub/workflow.d.ts` in your TypeScript project; `vite-hub` includes it through `.vitehub/types.d.ts`.
88
+
89
+ ## Configure the driver
90
+
91
+ ```ts fragment
56
92
  // server/workflow-runtime.ts
57
93
  import type {
58
94
  ResolvedWorkflowOptions,
@@ -68,7 +104,7 @@ const postgresUrl = {
68
104
  } as const;
69
105
 
70
106
  export const workflowConfig = {
71
- provider: "openworkflow",
107
+ driver: "openworkflow",
72
108
  postgres: { url: postgresUrl },
73
109
  } satisfies ResolvedWorkflowOptions;
74
110
 
@@ -88,42 +124,55 @@ export function installWorkflowRuntime() {
88
124
  }
89
125
  ```
90
126
 
91
- ```ts
127
+ For a standalone Vite app, install Nitro 3 before adding its server plugin:
128
+
129
+ ```sh
130
+ pnpm add -D nitro@^3.0.261103-rc
131
+ ```
132
+
133
+ ```ts fragment
92
134
  // vite.config.ts
93
135
  import { hubWorkflow } from "@vite-hub/workflow/vite";
136
+ import { nitro } from "nitro/vite";
94
137
  import { defineConfig } from "vite";
95
138
  import { workflowConfig } from "./server/workflow-runtime.ts";
96
139
 
97
140
  export default defineConfig({
98
- plugins: [hubWorkflow()],
99
- workflow: workflowConfig,
141
+ nitro: { serverDir: "./server" },
142
+ plugins: [hubWorkflow(workflowConfig), nitro()],
100
143
  });
101
144
  ```
102
145
 
103
- The Vite config, application process, and worker below share one provider config. The runtime installer also registers the same definitions in both processes. Set `provider` explicitly when the deployment target should not decide it. Otherwise ViteHub selects Cloudflare on Cloudflare hosting and Vercel on other supported hosts. Node and Docker select OpenWorkflow when its storage is configured. Netlify cannot infer a provider.
146
+ `hubWorkflow()` adds Workflow discovery and host output, but no server. Nitro gives the app its server and reads the routes in `server/`. Without `nitro()`, a plain Vite build fails with `Cannot resolve entry module index.html`. `vitehub({ workflow: workflowConfig })` includes Nitro and installs the driver config and registry in the server, so an app that uses it does not need `installWorkflowRuntime()`.
147
+
148
+ The Vite config, application process, and worker below share one driver config. The runtime installer also registers the same definitions in both processes. Set `driver` explicitly when the deployment target should not decide it. Otherwise ViteHub selects Cloudflare on Cloudflare hosting, OpenWorkflow on Node and Docker, and Vercel on Vercel. Deno requires an explicit driver or OpenWorkflow storage for builds; development and Agent-only Workflows can run inline. Netlify cannot infer a driver.
104
149
 
105
150
  OpenWorkflow accepts one storage choice: `postgres.url` or `sqlite.path`. Hosted credentials belong in Server Env, not source code.
106
151
 
107
152
  ### Run an OpenWorkflow worker
108
153
 
109
- `runWorkflow()` only enqueues an OpenWorkflow run. Start one worker in a long-lived Node or Docker process:
154
+ `startWorkflow()` only enqueues an OpenWorkflow run, and a worker executes it. With `hubWorkflow()` or `vitehub()`, the generated Nitro startup plugin of a Node or Docker server calls `installOpenWorkflow(nitroApp)`. When the registry has discovered Workflow or Agent files, it loads OpenWorkflow from the server bundle and starts one worker. With only inline Workflows, it does not resolve or open OpenWorkflow storage or start a worker. The worker executes 10 runs at once; set `workflow.worker.concurrency` to change it. Each Agent turn uses two runs: the turn and its recovery run. The worker stops when Nitro closes or the process gets `SIGTERM`. Several servers can run a worker on the same Postgres database. Servers that start together set up the OpenWorkflow schema one at a time, so they do not fail with `duplicate key value violates unique constraint`. A server tries a Postgres advisory lock (`pg_try_advisory_xact_lock`) in a short transaction, and waits without a connection when another server holds it. OpenWorkflow does not export its migrations, so they run on their own connection while the lock transaction holds another. The server that gets the lock first checks for that second connection and stops with `WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE` when it gets none in 10 seconds, then holds the lock until the setup ends. OpenWorkflow claims each run with `FOR UPDATE SKIP LOCKED`, so one worker executes it. When setup or the worker start fails, the server reports the error and tries again, with a delay that grows to 30 seconds, until it works or the server closes. `WORKFLOW_OPENWORKFLOW_DATABASE_URL_MISSING` and `WORKFLOW_OPENWORKFLOW_DATABASE_URL_IGNORED` stop the retries, because only a configuration change fixes it. `WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE` (no second connection in 10 seconds) is retried, because a full pool frees connections later. `installOpenWorkflow()` resolves to `true` when the worker runs.
110
155
 
111
- ```ts
156
+ Every worker registers the discovered Workflow Definitions of the build registry when it starts, and any worker can claim a run. So OpenWorkflow runs only those definitions. The registry has each discovered Agent Workflow and its invocation recovery Workflow, so Agent turns are durable OpenWorkflow runs. The startup registry also installs the generated Agent State resolver and Capability loaders, so a fresh worker can restore persisted Channel deliveries without loading an Agent route first. A turn of an Agent that is not discovered fails with `WORKFLOW_AGENT_NOT_DISCOVERED`. A definition that code registers later, such as an inline `createWorkflow(name, handler)`, runs inline in the request process, with `metadata.mode` set to `"inline"` and a warning. In `vite dev`, a changed Workflow file replaces the worker; the old backend stays open until the old worker finishes its runs.
157
+
158
+ Set `workflow: { worker: false }` to keep the servers from starting a worker. Then start one worker in a separate long-lived process:
159
+
160
+ ```ts fragment
112
161
  // worker.ts
113
- import { startOpenWorkflowWorker } from "@vite-hub/workflow/runtime/openworkflow-worker";
162
+ import { startOpenWorkflowWorker } from "@vite-hub/workflow/openworkflow";
114
163
  import { installWorkflowRuntime } from "./server/workflow-runtime.ts";
115
164
 
116
165
  installWorkflowRuntime();
117
166
  const worker = await startOpenWorkflowWorker();
118
167
  ```
119
168
 
120
- Keep this process running while it should consume queued runs, and do not start a worker per request. `startOpenWorkflowWorker()` installs `SIGINT` and `SIGTERM` handlers. If the host owns shutdown, await `worker.stop()` from its shutdown hook.
169
+ Keep this process running while it should consume queued runs, and do not start a worker per request. A separate worker executes the discovered definitions that it loads from the same registry. `startOpenWorkflowWorker()` installs `SIGINT` and `SIGTERM` handlers. If the host owns shutdown, await `worker.stop()` from its shutdown hook.
121
170
 
122
171
  ## Start and inspect a run
123
172
 
124
- ```ts
173
+ ```ts fragment
125
174
  // server/api/onboard.post.ts
126
- import { getWorkflowRun, runWorkflow } from "@vite-hub/workflow";
175
+ import { getWorkflowRun, startWorkflow } from "@vite-hub/workflow";
127
176
  import { defineEventHandler, readBody } from "h3";
128
177
  import { installWorkflowRuntime } from "../workflow-runtime.ts";
129
178
 
@@ -131,37 +180,66 @@ installWorkflowRuntime();
131
180
 
132
181
  export default defineEventHandler(async (event) => {
133
182
  const payload = await readBody<{ email: string }>(event);
134
- const started = await runWorkflow("onboard-user", payload);
183
+ const [startError, started] = await startWorkflow("onboard-user", payload);
184
+ if (startError) throw startError;
135
185
 
136
- return await getWorkflowRun("onboard-user", started.id);
186
+ const [error, run] = await getWorkflowRun("onboard-user", started.id);
187
+ if (error) throw error;
188
+ return run;
137
189
  });
138
190
  ```
139
191
 
140
- `runWorkflow()` returns a normalized acknowledgement with an id, provider, and status. `getWorkflowRun()` returns normalized run and step state, including timestamps, attempts, results, and failures when the provider supplies them.
192
+ `startWorkflow()` returns `[error, run]`: a normalized acknowledgement with an id, provider, and status. `getWorkflowRun()`, `cancelWorkflow()`, `resumeWorkflow()`, and the `start`, `getRun`, and `cancel` methods of a handle also return `[error, data]`. A provider failure, an unsupported option, or an invalid `delay` is `error`; its `code` is a `WorkflowResultErrorCode`. A config error, such as an unknown Workflow name, throws. When you pass `{ id }`, that id is the run id on Cloudflare, OpenWorkflow, and inline runs, and a second start with the same id returns the first run. `getWorkflowRun()` returns normalized run and step state, including timestamps, attempts, and results when the provider supplies them. A failed run has `error`: `{ message, name?, code? }`, safe to send as JSON, on every provider. `metadata` keeps provider data and no longer holds the error. Every provider reports the same statuses: a sleeping or waiting run reports `running`, a Cloudflare `terminated` run reports `cancelled`, and a run id that does not exist reports `unknown`.
193
+
194
+ To set your own id, pass `{ id }`. On Cloudflare, start with a letter, a digit, or `_`, then use only letters, digits, `-`, and `_`, up to 100 characters. `startWorkflow()` returns the error `WORKFLOW_CLOUDFLARE_RUN_ID_INVALID` for another id. Inspection queries the binding because existing instance ids can follow different rules.
141
195
 
142
196
  The other runtime helpers are:
143
197
 
144
- - `deferWorkflow()` starts through the deferred provider path when available.
145
- - `cancelWorkflow()` cancels a native Vercel run.
146
- - `resumeWorkflowSignal()` resumes a registered Vercel Workflow DevKit hook token.
147
- - `createWorkflow()` creates a named handle with `run`, `defer`, `getRun`, and `cancel` methods.
198
+ - `deferWorkflow()` starts a run after the response, through `waitUntil`. It returns nothing and logs a failure. Call `startWorkflow()` when you need the run id.
199
+ - `cancelWorkflow()` cancels a Cloudflare run with `instance.terminate()`, a native Vercel run, or a pending or running OpenWorkflow run. A finished run keeps its status, and a missing run reports `unknown`.
200
+ - `resumeWorkflow()` resumes a registered Vercel Workflow DevKit hook token.
201
+ - `createWorkflow()` creates a named handle with `start`, `defer`, `getRun`, and `cancel` methods.
148
202
 
149
203
  Unsupported provider operations fail with `WORKFLOW_OPERATION_UNSUPPORTED`; ViteHub does not pretend that an inline run was cancelled or resumed.
150
204
 
151
- Inline runs buffer the response body before completion. Each inspection and duplicate start returns a fresh response, so reading or cancelling one result does not consume later results. A body read failure marks the run as failed.
205
+ `hubWorkflow()` contributes the `workflow.start`, `get`, `cancel`, `resume`, `runs-list`, `runs-show`, and `runs-clear` operations. In `vite dev`, the dev Nitro plugin records every inline run in the memory of the dev server: its status, times, result, error, and each step of a folder Workflow. `vitehub workflow runs list` lists the newest runs first, `vitehub workflow runs show <runId>` shows one with its steps, and `vitehub workflow runs clear --yes` removes them all. The history keeps the newest 200 runs until the dev server restarts. It does not include runs that a Cloudflare binding, OpenWorkflow, or a native Vercel Workflow executes. Only the dev Nitro plugin imports the `runtime/dev-runs` module, by file path. It holds the history. The production runtime has only an empty recorder slot, so a build does not include the history code and never records runs. The three commands fail there with `WORKFLOW_RUNS_UNAVAILABLE`.
206
+
207
+ The `result` of a completed run is the value that the handler returned, stored as JSON. Every provider returns the same plain value, so a `Date` comes back as a string and `undefined` fields are dropped. Return a JSON-safe value, or return a `Response` for binary data or for status and headers. When the handler returns a `Response`, `result` is a `Response`.
208
+
209
+ Inline runs buffer a returned `Response` body before completion. Each inspection and duplicate start returns a fresh `Response`, so reading or cancelling one result does not consume later results. A body read failure marks the run as failed.
152
210
 
153
211
  Inline run inspection uses weak references while execution is active. A reachable execution remains inspectable; an abandoned execution with no remaining owner can be garbage-collected and then reports `unknown`. Completed inline runs are retained for five minutes, up to 1,024 entries per runtime. Completed history does not evict active executions. If either `WeakRef` or `FinalizationRegistry` is unavailable, active inspection uses strong references capped at 1,024 entries. Starting another run evicts the oldest active inspection entry, even if execution is still reachable; it reports `unknown` and completion does not restore it. Use a durable provider when inspection must survive abandonment or a process restart.
154
212
 
213
+ ## Start a run later
214
+
215
+ Pass `delay` to start the run later. It accepts a duration such as `"30m"` or `"3 days"`, or a `Date` that the run must not start before. A `Date` in the past starts the run now. `startWorkflow()` returns `RUNTIME_DURATION_INVALID` for an invalid duration, including a bare number, and `WORKFLOW_START_DELAY_INVALID` for an invalid or out-of-range start time. Use a `Date` for a month or a calendar time. `delay` works with `{ id }`.
216
+
217
+ ```ts fragment
218
+ const [error, run] = await startWorkflow("send-reminder", { email }, { delay: "3 days", id: `reminder-${userId}` });
219
+ ```
220
+
221
+ | Provider | How the delay works | Status during the delay |
222
+ | --- | --- | --- |
223
+ | OpenWorkflow | The run stays pending in storage until its start time (`availableAt`). | `queued` |
224
+ | Cloudflare | The run sleeps with `step.sleepUntil()` before the handler. A waiting instance does not count toward the concurrency limit. | `running` |
225
+ | Vercel `native` entry of a folder Workflow | The generated entry calls Workflow DevKit `sleep()` before the first step. | `running` |
226
+ | Vercel `native` entry that you wrote | Not supported. `startWorkflow()` returns the error `WORKFLOW_OPERATION_UNSUPPORTED`. | |
227
+ | Inline runs (`vite dev`, normal Vercel handlers) | A timer in the process. It is not durable: a restart loses the run. | `queued` |
228
+
229
+ For a recurring run, call `startWorkflow()` from a [Schedule](https://vitehub.dev/docs/schedule) handler.
230
+
155
231
  ## Make a Vercel workflow durable
156
232
 
157
- A plain Vercel definition executes inline and does not survive a function restart. For durable execution, keep the same context-shaped handler and register a native Workflow DevKit entry:
233
+ A plain Vercel definition executes inline and does not survive a function restart. Install `@vercel/functions` as shown in the provider table above for all Vercel definitions. For durable execution, also install the Workflow DevKit packages, keep the same handler, and register a native entry:
158
234
 
159
235
  ```sh
160
- pnpm add workflow @workflow/builders
236
+ pnpm add --save-exact workflow@5.2.3 @workflow/builders@5.0.6
161
237
  ```
162
238
 
163
- ```ts
164
- import { defineWorkflow, type WorkflowExecutionContext, type WorkflowProviderContext } from "@vite-hub/workflow";
239
+ The peer ranges accept any 5.x from these versions. ViteHub tests with 5.2.3 and 5.0.6. Workflow 5.3.0 and later end a run as soon as the workflow function returns, even while a losing `Promise.race` step still runs; see [Upgrade the Vercel Workflow SDK](https://vitehub.dev/docs/workflows/hosts#upgrade-the-vercel-workflow-sdk).
240
+
241
+ ```ts fragment
242
+ import { defineWorkflow, type WorkflowProviderContext } from "@vite-hub/workflow";
165
243
 
166
244
  interface OnboardPayload {
167
245
  email: string;
@@ -180,21 +258,22 @@ async function durableOnboard({ payload }: WorkflowProviderContext<OnboardPayloa
180
258
  return { userId: user.id };
181
259
  }
182
260
 
183
- async function inlineOnboard({ payload }: WorkflowExecutionContext<OnboardPayload>) {
184
- const user = await upsertUser(payload.email, { idempotencyKey: `onboard-user:${payload.email}` });
185
- return { userId: user.id };
186
- }
187
-
188
- export default defineWorkflow(inlineOnboard, { native: durableOnboard });
261
+ export default defineWorkflow<OnboardPayload>({
262
+ handler: async ({ payload }) => {
263
+ const user = await upsertUser(payload.email, { idempotencyKey: `onboard-user:${payload.email}` });
264
+ return { userId: user.id };
265
+ },
266
+ native: durableOnboard,
267
+ });
189
268
  ```
190
269
 
191
- ViteHub transforms `native` when it generates Vercel output. Other providers keep using the normal handler. Vercel calls `native` with a `WorkflowProviderContext`, which has no `steps` runner. Put external side effects in idempotent `use step` functions because a durable step may be retried.
270
+ ViteHub transforms `native` when it generates Vercel output. Other providers keep using the normal handler. `vite dev` does not transform `native`, so the dev server runs the normal handler inline, also with the Vercel provider. Test the durable entry on a Vercel preview deployment. Vercel calls `native` with a `WorkflowProviderContext`, which has no `steps` runner. Put external side effects in idempotent `use step` functions because a durable step may be retried.
192
271
 
193
272
  ## Handle stable failures
194
273
 
195
274
  Throw `ViteHubError` when app callers need a stable, inspectable Workflow failure instead of parsing log output or provider-specific messages. ViteHub-owned failures use the package's fixed `WorkflowErrorCode` vocabulary.
196
275
 
197
- ```ts
276
+ ```ts fragment
198
277
  import { ViteHubError } from "@vite-hub/runtime";
199
278
 
200
279
  async function transcribe(recordingId: string) {
@@ -209,7 +288,46 @@ async function transcribe(recordingId: string) {
209
288
  }
210
289
  ```
211
290
 
212
- `code` and `message` remain available through `error.toJSON()`. Keep `details` JSON-safe and free of secrets; `toJSON()` omits `cause`, which remains available only on the in-memory error. ViteHub's built-in codes are typed as `WorkflowErrorCode` and use code-derived messages and code-specific details. Workflow Step retry behavior belongs in the Step's retry options rather than the error.
291
+ `code` and `message` remain available through `error.toJSON()`. Keep `details` JSON-safe and free of secrets; `toJSON()` omits `cause`, which remains available only on the in-memory error. ViteHub's built-in codes are typed as `WorkflowErrorCode` and use code-derived messages and code-specific details. A `ViteHubError` does not change the retry policy.
292
+
293
+ A step gets 3 retries after the first attempt, 10 seconds apart and then twice as long each time. A step file can export its own policy and a time limit for each attempt:
294
+
295
+ ```ts
296
+ export const retries = { limit: 5, delay: "30 seconds", backoff: "exponential" };
297
+ export const timeout = "2 minutes";
298
+ ```
299
+
300
+ Cloudflare gets both in `step.do()`. OpenWorkflow gets `retries` as its `retryPolicy`, and a generated Vercel step gets `limit` as `maxRetries`. Vercel steps cannot set `delay` or `backoff`, so the build fails with `WORKFLOW_STEP_RETRY_DELAY_UNSUPPORTED`. Outside Cloudflare, ViteHub enforces `timeout` itself: it aborts the `signal` that the step function gets as its second argument and fails the attempt. Code that ignores the signal keeps running. An inline run does not retry. See [Retries and sleeps](https://vitehub.dev/docs/workflows/limits-and-errors#retries-and-sleeps).
301
+
302
+ Throw `NonRetryableError` when another attempt cannot succeed. The run fails at once on every provider. `getWorkflowRun()` reports the error `message` and `name` in `metadata` for inline and OpenWorkflow runs, Cloudflare keeps the error in its status record in `metadata`, and a Vercel `native` run reports the message on the failed step in `steps`.
303
+
304
+ ```ts fragment
305
+ import { NonRetryableError } from "@vite-hub/workflow";
306
+
307
+ throw new NonRetryableError("The card was declined.", { cause });
308
+ ```
309
+
310
+ Cloudflare gets its own `NonRetryableError` from ViteHub. Workflow DevKit reads `fatal: true`, as for its `FatalError`. OpenWorkflow has no such error, so ViteHub ends the step with the error as its result and fails the run outside the step. A replay reads that result and throws the same error. ViteHub finds the error by `isRetryable === false` or by its name, so an error from another bundle also works.
311
+
312
+ Only a folder Workflow can sleep. Its `index.ts` calls `context.sleep()` between steps, with a duration or a `Date`. A duration is a number of milliseconds or a string such as `"30 seconds"` or `"1 day"`: a number, one space, and a unit (second, minute, hour, day, week, month, or year, with or without a final `s`). A month is 30 days and a year is 365.25 days.
313
+
314
+ ```ts fragment
315
+ // server/workflows/remind-user/index.ts, next to 01.send-welcome.ts and 02.send-reminder.ts
316
+ export default defineWorkflow<{ email: string, remindAt: string }>({
317
+ handler: async ({ payload, sleep, steps }) => {
318
+ await steps.sendWelcome(payload);
319
+ await sleep("1 day");
320
+ await sleep(new Date(payload.remindAt));
321
+ await steps.sendReminder(payload);
322
+ },
323
+ });
324
+ ```
325
+
326
+ The sleep is durable on Cloudflare (`step.sleep` and `step.sleepUntil`, at most 365 days) and OpenWorkflow. Inline runs, in `vite dev` and in normal Vercel handlers, wait with a timer. That wait is not durable: a restart loses the run. A Vercel `native` entry uses Workflow DevKit's `sleep()`.
327
+
328
+ After a sleep, the provider runs `index.ts` again from the start, and completed step files return their stored results. ViteHub names each sleep by call order (`sleep-1`, `sleep-2`), so `index.ts` must call `sleep()` in the same order on each replay. Put each side effect and each value that changes, such as `Date.now()`, in a step file. `getWorkflowRun()` lists a sleep as a step with the name `sleep-1` and the wake time in `sleepUntil` on OpenWorkflow. A sleeping Cloudflare run reports `running` with `metadata.status: "waiting"`.
329
+
330
+ A single-file Workflow runs as one root step, and a replay after a sleep would run the code before the sleep again. So `context.sleep()` in a single-file Workflow throws `WORKFLOW_ROOT_STEP_SLEEP` on every provider, and the run fails without a retry. A duration that is not in the form above throws `WORKFLOW_SLEEP_DURATION_INVALID`.
213
331
 
214
332
  ## Production checklist
215
333
 
@@ -230,14 +348,14 @@ async function transcribe(recordingId: string) {
230
348
 
231
349
  ## Required handle input
232
350
 
233
- A typed Workflow handle requires a payload when its handler requires one. Both `run()` and `defer()` use this rule. A handle with an optional payload or `void` input can still run with no argument. To set start options for a no-input Workflow, pass `undefined` first.
351
+ A typed Workflow handle requires a payload when its handler requires one. Both `start()` and `defer()` use this rule. A handle with an optional payload or `void` input can still start with no argument. To set start options for a no-input Workflow, pass `undefined` first.
234
352
 
235
- ```ts
353
+ ```ts fragment
236
354
  const welcome = createWorkflow<{ email: string }>("welcome", async ({ payload }) => {
237
355
  await sendWelcomeEmail(payload.email)
238
356
  })
239
- await welcome.run({ email: "ada@example.com" })
240
- // welcome.run() is a type error.
357
+ await welcome.start({ email: "ada@example.com" })
358
+ // welcome.start() is a type error.
241
359
  ```
242
360
 
243
361
  This is a breaking type correction. Supply the required payload at each handle call. Named operational functions do not infer a handler from a string, and persisted run results remain unknown.
@@ -1,4 +1,4 @@
1
- import { t as internalErrorDiagnostics } from "./error-diagnostics-A_8Kp-48.js";
1
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-CQ4BUqRe.js";
2
2
  //#region ../internal/src/runtime/app.ts
3
3
  function resolveAppFetch(label, app) {
4
4
  if (!app) return;