@vite-hub/workflow 0.0.4 → 0.3.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 (65) hide show
  1. package/README.md +168 -47
  2. package/dist/{_app-DgwN4ulW.d.ts → app-BojnC_yf.d.ts} +1 -4
  3. package/dist/{app-BZpq2cwC.js → app-CmMq8l4t.js} +2 -1
  4. package/dist/client-CU5rELC0.js +658 -0
  5. package/dist/{cloudflare-D0Di-QYL.js → cloudflare-BfFnNWB0.js} +20 -4
  6. package/dist/cloudflare-env-CGLx7lUd.js +115 -0
  7. package/dist/cloudflare-env-lookup-CfX6wZKb.d.ts +4 -0
  8. package/dist/{cloudflare-env-CIjdFTv6.d.ts → cloudflare-shared-CTqh_a2s.d.ts} +2 -2
  9. package/dist/config-DCvRDlxA.js +145 -0
  10. package/dist/definition.d.ts +19 -0
  11. package/dist/definition.js +31 -0
  12. package/dist/delay--ESDybVT.js +81 -0
  13. package/dist/dev-recorder-CTN5Fkao.js +10 -0
  14. package/dist/durability.d.ts +23 -0
  15. package/dist/durability.js +62 -0
  16. package/dist/error-diagnostics-8YNJ37rP.js +286 -0
  17. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  18. package/dist/errors-DCqRnZpN.js +35 -0
  19. package/dist/errors-DVwFb6Fd.d.ts +56 -0
  20. package/dist/index.d.ts +23 -71
  21. package/dist/index.js +23 -378
  22. package/dist/inspect-B72iFyj-.js +70 -0
  23. package/dist/object-Da1zyPCR.js +11 -0
  24. package/dist/openworkflow-TEaNk0LV.d.ts +50 -0
  25. package/dist/openworkflow-defaults-DDig2M4s.js +26 -0
  26. package/dist/openworkflow-storage-Dj9zUAsk.js +28 -0
  27. package/dist/openworkflow.d.ts +2 -0
  28. package/dist/openworkflow.js +2 -0
  29. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  30. package/dist/operations-B0L8kV5s.js +329 -0
  31. package/dist/operations.d.ts +71 -0
  32. package/dist/operations.js +314 -0
  33. package/dist/out-fRNaVslw.js +20357 -0
  34. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  35. package/dist/run-error-DBWqiJHH.js +110 -0
  36. package/dist/runtime/cloudflare-runner.d.ts +7 -19
  37. package/dist/runtime/cloudflare-runner.js +27 -10
  38. package/dist/runtime/cloudflare-shared.d.ts +2 -1
  39. package/dist/runtime/cloudflare-shared.js +1 -1
  40. package/dist/runtime/cloudflare-vite.d.ts +10 -11
  41. package/dist/runtime/cloudflare-vite.js +47 -1
  42. package/dist/runtime/dev-runs.d.ts +4 -0
  43. package/dist/runtime/dev-runs.js +73 -0
  44. package/dist/runtime/execute.d.ts +24 -7
  45. package/dist/runtime/execute.js +135 -6
  46. package/dist/runtime/openworkflow-worker.d.ts +34 -9
  47. package/dist/runtime/openworkflow-worker.js +156 -37
  48. package/dist/runtime/openworkflow.d.ts +2 -23
  49. package/dist/runtime/openworkflow.js +289 -46
  50. package/dist/runtime/state.d.ts +22 -21
  51. package/dist/runtime/state.js +99 -25
  52. package/dist/runtime/vercel-vite.d.ts +10 -12
  53. package/dist/runtime/vercel-vite.js +7 -4
  54. package/dist/types-CnKVDnEp.d.ts +241 -0
  55. package/dist/{vercel-B0MuIVgJ.js → vercel-BZU_O6ay.js} +78 -24
  56. package/dist/vite.d.ts +529 -23
  57. package/dist/vite.js +2789 -1609
  58. package/package.json +62 -34
  59. package/dist/cloudflare-env-DjxQNbrx.js +0 -58
  60. package/dist/cloudflare-shared-BVVgDSdq.d.ts +0 -1
  61. package/dist/cloudflare-vite-BkDgB6Sr.js +0 -46
  62. package/dist/config-BHknO_rT.js +0 -136
  63. package/dist/provider-operation-CW2cYfVy.js +0 -65
  64. package/dist/runtime-type-DGUn8Ple.js +0 -37
  65. package/dist/types-B9RdRkKh.d.ts +0 -169
package/README.md CHANGED
@@ -1,15 +1,15 @@
1
1
  # @vite-hub/workflow
2
2
 
3
3
  <p>
4
- <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
- <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
- <img alt="Vite" src="https://img.shields.io/badge/Vite-discovery-646cff?style=flat-square">
7
- <img alt="Workflow" src="https://img.shields.io/badge/Workflow-durable%20steps-7c3aed?style=flat-square">
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">
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.
11
11
 
12
- Use a Workflow when the application needs a run id, durable state, retries, cancellation, or resumable work. Use [Queue](https://vitehub.dev/docs/server-primitives/queue) when background delivery is enough and the application does not need to inspect a run.
12
+ Use a Workflow when the application needs a run id, durable state, retries, cancellation, or resumable work. Use [Queue](https://vitehub.dev/docs/queue) when background delivery is enough and the application does not need to inspect a run.
13
13
 
14
14
  ## Install
15
15
 
@@ -17,23 +17,27 @@ 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 | Requires explicit SQLite or Postgres storage. |
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
+
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
+
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`.
29
33
 
30
34
  ## Define a workflow
31
35
 
32
- ```ts
36
+ ```ts fragment
33
37
  // server/workflows/onboard-user.ts
34
38
  import { defineWorkflow } from "@vite-hub/workflow";
35
39
 
36
- export default defineWorkflow<{ email: string }>(async ({ id, payload, provider }) => {
40
+ export default defineWorkflow("onboard-user", async (payload: { email: string }, { id, provider }) => {
37
41
  const idempotencyKey = `onboard-user:${payload.email}`;
38
42
  const user = await upsertUser(payload.email, { idempotencyKey });
39
43
  await sendWelcomeEmail(user.email, { idempotencyKey: `${idempotencyKey}:welcome-email` });
@@ -44,15 +48,46 @@ export default defineWorkflow<{ email: string }>(async ({ id, payload, provider
44
48
 
45
49
  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.
46
50
 
47
- 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.
51
+ 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 name is the Workflow name. Pass the same name to `defineWorkflow(name, handler)` and to the runtime helpers. A definition that passes another name fails with `WORKFLOW_C0019` when the Workflow loads.
52
+
53
+ The handler gets `(payload, context)`. Annotate `payload` to type it. `context` has `id`, `name`, `provider`, and `steps`.
54
+
55
+ ## Call typed steps
56
+
57
+ A folder Workflow runs its numbered files as steps. `01.create-user.ts` becomes `steps.createUser`:
58
+
59
+ ```ts [server/workflows/onboard-user/index.ts]
60
+ // server/workflows/onboard-user/index.ts
61
+ import { defineWorkflow } from "@vite-hub/workflow";
62
+
63
+ export default defineWorkflow("onboard-user", async (payload: { email: string }, { steps }) => {
64
+ const user = await steps.createUser(payload);
65
+ return await steps.sendWelcome(user);
66
+ });
67
+ ```
68
+
69
+ ```ts [server/workflows/onboard-user/01.create-user.ts]
70
+ // server/workflows/onboard-user/01.create-user.ts
71
+ export default async function createUser(input: { email: string }) {
72
+ return { id: `user:${input.email}`, email: input.email };
73
+ }
74
+ ```
75
+
76
+ ```ts [server/workflows/onboard-user/02.send-welcome.ts]
77
+ // server/workflows/onboard-user/02.send-welcome.ts
78
+ export default async function sendWelcome(user: { id: string, email: string }) {
79
+ return { userId: user.id, welcomeSent: true };
80
+ }
81
+ ```
48
82
 
49
- ## Configure the provider
83
+ The Vite Integration writes `.vitehub/workflow.d.ts`. It declares the step files of each folder Workflow, so each step takes the input type of its file and returns its result type. A call to a step that has no file is a type error. Include `.vitehub/workflow.d.ts` in your TypeScript project; `vite-hub` includes it through `.vitehub/types.d.ts`.
50
84
 
51
- ```ts
85
+ ## Configure the driver
86
+
87
+ ```ts fragment
52
88
  // server/workflow-runtime.ts
53
89
  import type {
54
90
  ResolvedWorkflowOptions,
55
- WorkflowDefinition,
56
91
  WorkflowDefinitionRegistry,
57
92
  } from "@vite-hub/workflow";
58
93
  import {
@@ -65,14 +100,12 @@ const postgresUrl = {
65
100
  } as const;
66
101
 
67
102
  export const workflowConfig = {
68
- provider: "openworkflow",
103
+ driver: "openworkflow",
69
104
  postgres: { url: postgresUrl },
70
105
  } satisfies ResolvedWorkflowOptions;
71
106
 
72
107
  const workflowRegistry = {
73
- "onboard-user": async () => ({
74
- default: (await import("./workflows/onboard-user.ts")).default as WorkflowDefinition,
75
- }),
108
+ "onboard-user": () => import("./workflows/onboard-user.ts"),
76
109
  } satisfies WorkflowDefinitionRegistry;
77
110
 
78
111
  export function installWorkflowRuntime() {
@@ -87,42 +120,55 @@ export function installWorkflowRuntime() {
87
120
  }
88
121
  ```
89
122
 
90
- ```ts
123
+ For a standalone Vite app, install Nitro 3 before adding its server plugin:
124
+
125
+ ```sh
126
+ pnpm add -D nitro@^3.0.261103-rc
127
+ ```
128
+
129
+ ```ts fragment
91
130
  // vite.config.ts
92
131
  import { hubWorkflow } from "@vite-hub/workflow/vite";
132
+ import { nitro } from "nitro/vite";
93
133
  import { defineConfig } from "vite";
94
134
  import { workflowConfig } from "./server/workflow-runtime.ts";
95
135
 
96
136
  export default defineConfig({
97
- plugins: [hubWorkflow()],
98
- workflow: workflowConfig,
137
+ nitro: { serverDir: "./server" },
138
+ plugins: [hubWorkflow(workflowConfig), nitro()],
99
139
  });
100
140
  ```
101
141
 
102
- 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.
142
+ `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()`.
143
+
144
+ 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.
103
145
 
104
146
  OpenWorkflow accepts one storage choice: `postgres.url` or `sqlite.path`. Hosted credentials belong in Server Env, not source code.
105
147
 
106
148
  ### Run an OpenWorkflow worker
107
149
 
108
- `runWorkflow()` only enqueues an OpenWorkflow run. Start one worker in a long-lived Node or Docker process:
150
+ `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.
151
+
152
+ 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.
109
153
 
110
- ```ts
154
+ Set `workflow: { worker: false }` to keep the servers from starting a worker. Then start one worker in a separate long-lived process:
155
+
156
+ ```ts fragment
111
157
  // worker.ts
112
- import { startOpenWorkflowWorker } from "@vite-hub/workflow/runtime/openworkflow-worker";
158
+ import { startOpenWorkflowWorker } from "@vite-hub/workflow/openworkflow";
113
159
  import { installWorkflowRuntime } from "./server/workflow-runtime.ts";
114
160
 
115
161
  installWorkflowRuntime();
116
162
  const worker = await startOpenWorkflowWorker();
117
163
  ```
118
164
 
119
- 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.
165
+ 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.
120
166
 
121
167
  ## Start and inspect a run
122
168
 
123
- ```ts
169
+ ```ts fragment
124
170
  // server/api/onboard.post.ts
125
- import { getWorkflowRun, runWorkflow } from "@vite-hub/workflow";
171
+ import { getWorkflowRun, startWorkflow } from "@vite-hub/workflow";
126
172
  import { defineEventHandler, readBody } from "h3";
127
173
  import { installWorkflowRuntime } from "../workflow-runtime.ts";
128
174
 
@@ -130,33 +176,63 @@ installWorkflowRuntime();
130
176
 
131
177
  export default defineEventHandler(async (event) => {
132
178
  const payload = await readBody<{ email: string }>(event);
133
- const started = await runWorkflow("onboard-user", payload);
179
+ const started = await startWorkflow("onboard-user", payload);
134
180
 
135
181
  return await getWorkflowRun("onboard-user", started.id);
136
182
  });
137
183
  ```
138
184
 
139
- `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.
185
+ `startWorkflow()` returns a normalized acknowledgement with an id, provider, and status. 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`.
186
+
187
+ 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. Invalid start ids fail with `WORKFLOW_CLOUDFLARE_RUN_ID_INVALID`. Inspection queries the binding because existing instance ids can follow different rules.
140
188
 
141
189
  The other runtime helpers are:
142
190
 
143
- - `deferWorkflow()` starts through the deferred provider path when available.
144
- - `cancelWorkflow()` cancels a native Vercel run.
145
- - `resumeWorkflowSignal()` resumes a registered Vercel Workflow DevKit hook token.
146
- - `createWorkflow()` creates a named handle with `run`, `defer`, `getRun`, and `cancel` methods.
191
+ - `deferWorkflow()` starts a run after the response, through `waitUntil`. It returns nothing and logs a failure. Call `startWorkflow()` when you need the run id.
192
+ - `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`.
193
+ - `resumeWorkflow()` resumes a registered Vercel Workflow DevKit hook token.
194
+ - `createWorkflow()` creates a named handle with `start`, `defer`, `getRun`, and `cancel` methods.
147
195
 
148
196
  Unsupported provider operations fail with `WORKFLOW_OPERATION_UNSUPPORTED`; ViteHub does not pretend that an inline run was cancelled or resumed.
149
197
 
198
+ `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`.
199
+
200
+ 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`.
201
+
202
+ 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.
203
+
204
+ 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.
205
+
206
+ ## Start a run later
207
+
208
+ Pass `delay` to start the run later. It accepts milliseconds, a duration such as `"30 minutes"` or `"3 days"`, or a `Date` that the run must not start before. A `Date` in the past starts the run now. A negative or unknown value fails with `WORKFLOW_START_DELAY_INVALID`. Use a `Date` for a month or a calendar time. `delay` works with `{ id }`.
209
+
210
+ ```ts fragment
211
+ await startWorkflow("send-reminder", { email }, { delay: "3 days", id: `reminder-${userId}` });
212
+ ```
213
+
214
+ | Provider | How the delay works | Status during the delay |
215
+ | --- | --- | --- |
216
+ | OpenWorkflow | The run stays pending in storage until its start time (`availableAt`). | `queued` |
217
+ | Cloudflare | The run sleeps with `step.sleepUntil()` before the handler. A waiting instance does not count toward the concurrency limit. | `running` |
218
+ | Vercel `native` entry of a folder Workflow | The generated entry calls Workflow DevKit `sleep()` before the first step. | `running` |
219
+ | Vercel `native` entry that you wrote | Not supported. `startWorkflow()` fails with `WORKFLOW_OPERATION_UNSUPPORTED`. | |
220
+ | Inline runs (`vite dev`, normal Vercel handlers) | A timer in the process. It is not durable: a restart loses the run. | `queued` |
221
+
222
+ For a recurring run, call `startWorkflow()` from a [Schedule](https://vitehub.dev/docs/schedule) handler.
223
+
150
224
  ## Make a Vercel workflow durable
151
225
 
152
- 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:
226
+ 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:
153
227
 
154
228
  ```sh
155
- pnpm add workflow @workflow/builders
229
+ pnpm add --save-exact workflow@5.2.3 @workflow/builders@5.0.6
156
230
  ```
157
231
 
158
- ```ts
159
- import { defineWorkflow, type WorkflowExecutionContext } from "@vite-hub/workflow";
232
+ 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).
233
+
234
+ ```ts fragment
235
+ import { defineWorkflow, type WorkflowProviderContext } from "@vite-hub/workflow";
160
236
 
161
237
  interface OnboardPayload {
162
238
  email: string;
@@ -168,28 +244,28 @@ async function upsertUserStep(email: string) {
168
244
  return await upsertUser(email, { idempotencyKey: `onboard-user:${email}` });
169
245
  }
170
246
 
171
- async function durableOnboard({ payload }: WorkflowExecutionContext<OnboardPayload>) {
247
+ async function durableOnboard({ payload }: WorkflowProviderContext<OnboardPayload>) {
172
248
  "use workflow";
173
249
 
174
250
  const user = await upsertUserStep(payload.email);
175
251
  return { userId: user.id };
176
252
  }
177
253
 
178
- async function inlineOnboard({ payload }: WorkflowExecutionContext<OnboardPayload>) {
254
+ async function inlineOnboard(payload: OnboardPayload) {
179
255
  const user = await upsertUser(payload.email, { idempotencyKey: `onboard-user:${payload.email}` });
180
256
  return { userId: user.id };
181
257
  }
182
258
 
183
- export default defineWorkflow(inlineOnboard, { native: durableOnboard });
259
+ export default defineWorkflow("onboard-user", inlineOnboard, { native: durableOnboard });
184
260
  ```
185
261
 
186
- ViteHub transforms `native` when it generates Vercel output. Other providers keep using the normal handler. Put external side effects in idempotent `use step` functions because a durable step may be retried.
262
+ 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.
187
263
 
188
264
  ## Handle stable failures
189
265
 
190
266
  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.
191
267
 
192
- ```ts
268
+ ```ts fragment
193
269
  import { ViteHubError } from "@vite-hub/runtime";
194
270
 
195
271
  async function transcribe(recordingId: string) {
@@ -204,7 +280,37 @@ async function transcribe(recordingId: string) {
204
280
  }
205
281
  ```
206
282
 
207
- `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.
283
+ `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.
284
+
285
+ A step file has no retry option. On Cloudflare and OpenWorkflow, every step file uses `limit: 3`, `delay: "10 seconds"`, and `backoff: "exponential"`. A Vercel `native` entry follows the Workflow DevKit rules, and an inline run does not retry.
286
+
287
+ 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`.
288
+
289
+ ```ts fragment
290
+ import { NonRetryableError } from "@vite-hub/workflow";
291
+
292
+ throw new NonRetryableError("The card was declined.", { cause });
293
+ ```
294
+
295
+ 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.
296
+
297
+ 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.
298
+
299
+ ```ts fragment
300
+ // server/workflows/remind-user/index.ts, next to 01.send-welcome.ts and 02.send-reminder.ts
301
+ export default defineWorkflow("remind-user", async (payload: { email: string, remindAt: string }, { sleep, steps }) => {
302
+ await steps.sendWelcome(payload);
303
+ await sleep("1 day");
304
+ await sleep(new Date(payload.remindAt));
305
+ await steps.sendReminder(payload);
306
+ });
307
+ ```
308
+
309
+ 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()`.
310
+
311
+ 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"`.
312
+
313
+ 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`.
208
314
 
209
315
  ## Production checklist
210
316
 
@@ -216,8 +322,23 @@ async function transcribe(recordingId: string) {
216
322
 
217
323
  ## Documentation
218
324
 
219
- - [Workflow guide](https://vitehub.dev/docs/server-primitives/workflows)
325
+ - [Workflow guide](https://vitehub.dev/docs/workflows)
220
326
  - [Runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix)
221
327
  - [OpenWorkflow](https://openworkflow.dev/docs/overview)
222
328
  - [Cloudflare Workflows](https://developers.cloudflare.com/workflows/)
223
329
  - [Vercel Workflow](https://vercel.com/docs/workflow)
330
+
331
+
332
+ ## Required handle input
333
+
334
+ 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.
335
+
336
+ ```ts fragment
337
+ const welcome = createWorkflow("welcome", async (payload: { email: string }) => {
338
+ await sendWelcomeEmail(payload.email)
339
+ })
340
+ await welcome.start({ email: "ada@example.com" })
341
+ // welcome.start() is a type error.
342
+ ```
343
+
344
+ 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.
@@ -5,7 +5,4 @@ type VitehubApp = AppHandler | {
5
5
  request?: (request: Request, options?: RequestInit, context?: Record<string, unknown>) => Response | Promise<Response>;
6
6
  };
7
7
  //#endregion
8
- //#region src/runtime/_app.d.ts
9
- type WorkflowApp = VitehubApp;
10
- //#endregion
11
- export { WorkflowApp as t };
8
+ export { VitehubApp as t };
@@ -1,10 +1,11 @@
1
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-DSkCJC_L.js";
1
2
  //#region ../internal/src/runtime/app.ts
2
3
  function resolveAppFetch(label, app) {
3
4
  if (!app) return;
4
5
  if (typeof app === "function") return app;
5
6
  if (typeof app.request === "function") return (request, context) => app.request(request, void 0, context);
6
7
  if (typeof app.fetch === "function") return app.fetch.bind(app);
7
- throw new TypeError(`Invalid ${label} app. Expected an h3 app or a fetch-compatible handler.`);
8
+ throw internalErrorDiagnostics.INTERNAL_R0011({ message: `Invalid ${label} app. Expected an h3 app or a fetch-compatible handler.` });
8
9
  }
9
10
  //#endregion
10
11
  export { resolveAppFetch as t };