@vite-hub/workflow 0.6.1 → 0.8.0

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 (49) hide show
  1. package/README.md +33 -9
  2. package/dist/{app-DXUHElAz.js → app-Cpa9qCXr.js} +1 -1
  3. package/dist/{client-CbBg4HlH.js → client-T41cNf3k.js} +41 -52
  4. package/dist/cloudflare-concurrency-counter-CDHHiMfn.js +136 -0
  5. package/dist/{config-CizNRTMi.js → config-G0z9jHLM.js} +6 -6
  6. package/dist/definition.d.ts +1 -1
  7. package/dist/definition.js +4 -1
  8. package/dist/{delay-CtT3442d.js → delay-B4azP18B.js} +7 -5
  9. package/dist/durability.d.ts +3 -1
  10. package/dist/durability.js +7 -1
  11. package/dist/{error-diagnostics--2cV_ER1.js → error-diagnostics-35AEmfve.js} +25 -5
  12. package/dist/{error-diagnostics-kKXseq8d.js → error-diagnostics-CsiNo_oI.js} +3 -3
  13. package/dist/{errors-CJZuvOcx.d.ts → errors-DwKy5MQ8.d.ts} +1 -1
  14. package/dist/execute-zu08sWGG.js +353 -0
  15. package/dist/index.d.ts +12 -10
  16. package/dist/index.js +3 -3
  17. package/dist/{openworkflow-defaults-DfQWtSRU.js → invariant-Dj2R1eMr.js} +1 -4
  18. package/dist/{openworkflow-CdKbUGGa.d.ts → openworkflow-DHuxMJQB.d.ts} +23 -4
  19. package/dist/openworkflow-defaults-1n0DbLdb.js +4 -0
  20. package/dist/openworkflow-zD8luED5.js +749 -0
  21. package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-Blwi3jQF.d.ts} +1 -0
  22. package/dist/{operations-BBTmDm2H.js → operations-C2XbDDDV.js} +71 -15
  23. package/dist/operations.d.ts +3 -59
  24. package/dist/operations.js +5 -5
  25. package/dist/results-DqbEUMCH.d.ts +60 -0
  26. package/dist/{run-error-8p4BtTMv.js → run-error-zZh1_IBo.js} +5 -21
  27. package/dist/runtime/cloudflare-concurrency.d.ts +21 -0
  28. package/dist/runtime/cloudflare-concurrency.js +21 -0
  29. package/dist/runtime/cloudflare-runner.d.ts +1 -1
  30. package/dist/runtime/cloudflare-runner.js +7 -3
  31. package/dist/runtime/cloudflare-vite.d.ts +1 -1
  32. package/dist/runtime/cloudflare-vite.js +2 -2
  33. package/dist/runtime/execute.d.ts +8 -2
  34. package/dist/runtime/execute.js +1 -278
  35. package/dist/runtime/openworkflow-worker.d.ts +2 -2
  36. package/dist/runtime/openworkflow-worker.js +5 -6
  37. package/dist/runtime/openworkflow.d.ts +2 -2
  38. package/dist/runtime/openworkflow.js +1 -481
  39. package/dist/runtime/state.d.ts +1 -1
  40. package/dist/runtime/state.js +2 -2
  41. package/dist/runtime/vercel-vite.d.ts +1 -1
  42. package/dist/runtime/vercel-vite.js +2 -2
  43. package/dist/{signals-BHQdxoJo.js → signals-CdaxRNjN.js} +1 -1
  44. package/dist/{types-DvYcvbPG.d.ts → types-DrhUXMsE.d.ts} +34 -4
  45. package/dist/{vercel-Cw_Z9-j4.js → vercel-DRezYOUp.js} +8 -6
  46. package/dist/vite.d.ts +19 -4
  47. package/dist/vite.js +970 -212
  48. package/package.json +3 -3
  49. package/dist/cloudflare-Sgywkm1N.js +0 -57
package/README.md CHANGED
@@ -22,7 +22,7 @@ Then install the dependency required by the selected driver:
22
22
  | Provider | Additional dependency | Durable state |
23
23
  | -------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------ |
24
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. |
25
+ | Vercel Workflow | `@vercel/functions`, `workflow@5.2.3`, and `@workflow/builders@5.0.6` ([versions](#make-a-vercel-workflow-durable)) | Workflow DevKit runs every discovered Workflow file. Agent turns and `createWorkflow()` run inline. |
26
26
  | OpenWorkflow | None. `@vite-hub/workflow` depends on `openworkflow` and `postgres` | Postgres Default Database, else a local SQLite file. |
27
27
 
28
28
  Importing the provider-neutral package root does not load OpenWorkflow types. Worker lifecycle helpers live at `@vite-hub/workflow/openworkflow`.
@@ -173,7 +173,7 @@ Keep this process running while it should consume queued runs, and do not start
173
173
  ```ts fragment
174
174
  // server/api/onboard.post.ts
175
175
  import { getWorkflowRun, startWorkflow } from "@vite-hub/workflow";
176
- import { defineEventHandler, readBody } from "h3";
176
+ import { defineEventHandler, readBody } from "nitro/h3";
177
177
  import { installWorkflowRuntime } from "../workflow-runtime.ts";
178
178
 
179
179
  installWorkflowRuntime();
@@ -202,7 +202,7 @@ The other runtime helpers are:
202
202
 
203
203
  Unsupported provider operations fail with `WORKFLOW_OPERATION_UNSUPPORTED`; ViteHub does not pretend that an inline run was cancelled or resumed.
204
204
 
205
- `hubWorkflow()` contributes the `workflow.start`, `get`, `cancel`, `resume`, `runs-list`, 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 get <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. `runs list` and `runs clear` fail there with `WORKFLOW_RUNS_UNAVAILABLE`, and `runs get` reads the run from the provider, without steps.
205
+ `hubWorkflow()` contributes the `workflow.start`, `get`, `cancel`, `resume`, `runs-list`, 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 get <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. With OpenWorkflow, in `vite dev` and in a build, `runs list` also lists the stored runs with their step count, and `runs get <runId>` finds the Workflow of a stored run from its id or idempotency key. `runs clear` removes only the dev history. On other providers outside `vite dev`, `runs list` and `runs clear` fail with `WORKFLOW_RUNS_UNAVAILABLE`, and `runs get` reads the run from the provider, without steps.
206
206
 
207
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
208
 
@@ -222,15 +222,39 @@ const [error, run] = await startWorkflow("send-reminder", { email }, { delay: "3
222
222
  | --- | --- | --- |
223
223
  | OpenWorkflow | The run stays pending in storage until its start time (`availableAt`). | `queued` |
224
224
  | Cloudflare | The run sleeps with `step.sleepUntil()` before the handler. A waiting instance does not count toward the concurrency limit. | `running` |
225
- | Vercel, generated native entry for numbered steps without an index handler | The generated entry calls Workflow DevKit `sleep()` before the first step. | `running` |
225
+ | Vercel, generated native entry for a single file or for numbered steps without an index handler | The generated entry calls Workflow DevKit `sleep()` before the first step. | `running` |
226
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. Outside `vite dev`, the first delayed run of each Workflow logs a warning. | `queued` |
227
+ | Inline runs (`vite dev`, Agent turns and `createWorkflow()` on Vercel) | A timer in the process. It is not durable: a restart loses the run. Outside `vite dev`, the first delayed run of each Workflow logs a warning. | `queued` |
228
228
 
229
229
  For a recurring run, call `startWorkflow()` from a [Schedule](https://vitehub.dev/docs/schedule) handler.
230
230
 
231
+ ## Limit runs at once
232
+
233
+ Set `concurrency` on the Workflow to let at most that number of its runs execute at the same time, on all servers. A Queue `concurrency` only limits starts.
234
+
235
+ ```ts
236
+ import { defineWorkflow } from "@vite-hub/workflow";
237
+
238
+ export default defineWorkflow<{ pullRequest: number }>({
239
+ concurrency: 3,
240
+ handler: async ({ payload }) => ({ reviewed: payload.pullRequest }),
241
+ });
242
+ ```
243
+
244
+ A run that finds no free place sleeps before its handler and tries again, after 1 second and then after up to 60 seconds. A run that ends without freeing its place loses it at the next try.
245
+
246
+ | Driver | Count kept in |
247
+ | --- | --- |
248
+ | Cloudflare | The `ViteHubWorkflowConcurrency` Durable Object, one per Workflow. The build exports it and binds it as `VITEHUB_WORKFLOW_CONCURRENCY`. A missing binding fails the run with `WORKFLOW_CONCURRENCY_BINDING_MISSING`. |
249
+ | OpenWorkflow | The `vitehub_workflow_slots` table of the OpenWorkflow database. |
250
+ | Inline | The process. |
251
+ | Vercel | Not supported. The build fails with `WORKFLOW_CONCURRENCY_VERCEL_UNSUPPORTED`. |
252
+
253
+ The build reads `concurrency` from the default export of the Workflow file, so set it in the object literal. A value that is not a whole number of 1 or more throws `WORKFLOW_CONCURRENCY_INVALID`.
254
+
231
255
  ## Make a Vercel workflow durable
232
256
 
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:
257
+ A Vercel build never runs a discovered Workflow file inline. It generates a Workflow DevKit entry for a single file, which runs the handler as one step, and for a folder of numbered steps without an index file. A folder with an index handler needs a native entry that you write, or the build fails with `WORKFLOW_VERCEL_INDEX_NOT_NATIVE`. Install `@vercel/functions` and the Workflow DevKit packages, keep the same handler, and register the native entry:
234
258
 
235
259
  ```sh
236
260
  pnpm add --save-exact workflow@5.2.3 @workflow/builders@5.0.6
@@ -297,7 +321,7 @@ export const retries = { limit: 5, delay: "30 seconds", backoff: "exponential" }
297
321
  export const timeout = "2 minutes";
298
322
  ```
299
323
 
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).
324
+ Cloudflare gets both in `step.do()`. OpenWorkflow gets `retries` as its `retryPolicy`, with each wait at most 365 days, 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
325
 
302
326
  Throw `NonRetryableError` when another attempt cannot succeed. The run fails at once on every provider. `getWorkflowRun()` reports the error `message` and `name` in `error` on every provider, and inline runs also keep `code`. OpenWorkflow also reports the original message on the failed step in `steps`. Native Vercel can report a generic step error if it cannot read the provider's step error message. Cloudflare also keeps the error in its status record in `metadata`.
303
327
 
@@ -323,7 +347,7 @@ export default defineWorkflow<{ email: string, remindAt: string }>({
323
347
  });
324
348
  ```
325
349
 
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()`.
350
+ The sleep is durable on Cloudflare (`step.sleep` and `step.sleepUntil`, at most 365 days) and OpenWorkflow. Inline runs, in `vite dev` and for Agent turns and `createWorkflow()` on Vercel, wait with a timer. That wait is not durable: a restart loses the run. A Vercel `native` entry uses Workflow DevKit's `sleep()`.
327
351
 
328
352
  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
353
 
@@ -350,7 +374,7 @@ ViteHub makes the token from the Workflow name, the run id, and the call order (
350
374
 
351
375
  ## Production checklist
352
376
 
353
- - Confirm that the selected provider is durable enough for the work; inline Vercel handlers are not durable.
377
+ - Confirm that the selected provider is durable enough for the work; Agent turns and `createWorkflow()` on Vercel run inline and are not durable.
354
378
  - Make side-effecting steps idempotent so retries do not duplicate work.
355
379
  - Keep provider credentials and database URLs in Server Env.
356
380
  - Configure durable OpenWorkflow storage and run its migrations before serving traffic.
@@ -1,4 +1,4 @@
1
- import { t as internalErrorDiagnostics } from "./error-diagnostics-kKXseq8d.js";
1
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-CsiNo_oI.js";
2
2
  // ../internal/src/runtime/app.ts
3
3
  function resolveAppFetch(label, app) {
4
4
  if (!app) return;
@@ -1,18 +1,18 @@
1
1
  import { a as getCloudflareEnv, n as resolveWaitUntil } from "./cloudflare-env-DHhzRZOs.js";
2
- import { t as normalizeWorkflowOptions } from "./config-CizNRTMi.js";
2
+ import { t as normalizeWorkflowOptions } from "./config-G0z9jHLM.js";
3
3
  import { n as createWorkflowError } from "./errors-CZf7oz4k.js";
4
- import { t as workflowErrorDiagnostics } from "./error-diagnostics--2cV_ER1.js";
5
- import { a as encodeNameHex, n as getCloudflareWorkflowBindingName } from "./cloudflare-Sgywkm1N.js";
6
- import { i as toCloudflareStartParams, r as resolveWorkflowStartAt } from "./delay-CtT3442d.js";
4
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-35AEmfve.js";
5
+ import { d as encodeNameHex, s as getCloudflareWorkflowBindingName, u as isCloudflareInstanceNotFound } from "./cloudflare-concurrency-counter-CDHHiMfn.js";
6
+ import { a as toCloudflareStartParams, i as resolveWorkflowStartAt } from "./delay-B4azP18B.js";
7
7
  import { t as getWorkflowDevRecorder } from "./dev-recorder-Dltdmlkv.js";
8
- import { runSerializedWorkflowHandler } from "./runtime/execute.js";
8
+ import { o as runSerializedWorkflowHandler } from "./execute-zu08sWGG.js";
9
9
  import { cloudflareSignalEventType } from "./runtime/cloudflare-runner.js";
10
- import { cancelOpenWorkflowRun, getOpenWorkflowRun, resumeOpenWorkflowSignal, runOpenWorkflow } from "./runtime/openworkflow.js";
11
- import { a as safeWorkflowName, i as runWorkflowProviderOperation, t as toWorkflowRunError } from "./run-error-8p4BtTMv.js";
10
+ import { a as getOpenWorkflowRun, d as runOpenWorkflow, t as cancelOpenWorkflowRun, u as resumeOpenWorkflowSignal } from "./openworkflow-zD8luED5.js";
11
+ import { a as safeWorkflowName, i as runWorkflowProviderOperation, t as toWorkflowRunError } from "./run-error-zZh1_IBo.js";
12
12
  import { t as emitWorkflowFailed } from "./run-failed-BcSjSU2t.js";
13
- import { i as readWorkflowSignalToken, o as resumeInlineWorkflowSignal } from "./signals-BHQdxoJo.js";
13
+ import { i as readWorkflowSignalToken, o as resumeInlineWorkflowSignal } from "./signals-CdaxRNjN.js";
14
14
  import { getInlineWorkflowDefinitions, getWorkflowRunState, getWorkflowRuntimeConfig, getWorkflowRuntimeEvent, getWorkflowRuntimeRegistry, loadWorkflowDefinition, registerInlineWorkflowDefinition, runWithWorkflowRuntimeEvent, setWorkflowRun } from "./runtime/state.js";
15
- import { a as startVercelWorkflow, n as inspectVercelWorkflowRun, r as resumeVercelWorkflowSignal, t as cancelVercelWorkflow } from "./vercel-Cw_Z9-j4.js";
15
+ import { a as startVercelWorkflow, n as inspectVercelWorkflowRun, r as resumeVercelWorkflowSignal, t as cancelVercelWorkflow } from "./vercel-DRezYOUp.js";
16
16
  import { getViteHubErrorShape, isRuntimeDiagnostic, toResultError } from "@vite-hub/runtime";
17
17
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
18
18
  import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime/internal/response";
@@ -79,9 +79,8 @@ function resolveCloudflareBinding(event, binding, name, definition) {
79
79
  function resolveCloudflareInspectionBinding(event, binding, name) {
80
80
  return resolveCloudflareBinding(event, binding, name, getWorkflowRuntimeRegistry()?.[name]);
81
81
  }
82
- function invalidCloudflareWorkflowStart(cause) {
82
+ function invalidCloudflareWorkflowStart() {
83
83
  return createWorkflowError({
84
- ...cause === void 0 ? {} : { cause },
85
84
  code: "WORKFLOW_PROVIDER_OPERATION_FAILED",
86
85
  details: {
87
86
  acknowledgement: "unknown",
@@ -93,12 +92,7 @@ function invalidCloudflareWorkflowStart(cause) {
93
92
  }
94
93
  function normalizeCloudflareWorkflowStart(value, expectedId) {
95
94
  if (typeof value !== "object" || value === null) throw invalidCloudflareWorkflowStart();
96
- let id;
97
- try {
98
- id = Reflect.get(value, "id");
99
- } catch (cause) {
100
- throw invalidCloudflareWorkflowStart(cause);
101
- }
95
+ const id = "id" in value ? value.id : void 0;
102
96
  if (typeof id !== "string" || !id || id !== expectedId) throw invalidCloudflareWorkflowStart();
103
97
  return { id };
104
98
  }
@@ -134,23 +128,9 @@ function ownStatusError(metadata) {
134
128
  if (typeof metadata !== "object" || metadata === null || !Object.hasOwn(metadata, "error")) return void 0;
135
129
  return Reflect.get(metadata, "error");
136
130
  }
137
- function isCloudflareInstanceNotFound(error) {
138
- if (typeof error !== "object" || error === null) return false;
139
- try {
140
- const message = Reflect.get(error, "message");
141
- return typeof message === "string" && message.includes("instance.not_found");
142
- } catch {
143
- return false;
144
- }
145
- }
146
131
  function isCloudflareRejection(error) {
147
132
  if (typeof error !== "object" || error === null) return false;
148
- try {
149
- const message = Reflect.get(error, "message");
150
- return typeof message === "string" && /\((?:instance|workflow)\.[a-z_]+\)|^Workflow instance has invalid id/.test(message);
151
- } catch {
152
- return false;
153
- }
133
+ return "message" in error && typeof error.message === "string" && /\((?:instance|workflow)\.[a-z_]+\)|^Workflow instance has invalid id/.test(error.message);
154
134
  }
155
135
  function hasUnknownWorkflowAcknowledgement(error) {
156
136
  if (!error || typeof error !== "object") return false;
@@ -279,20 +259,25 @@ function createCloudflareAdapter(config) {
279
259
  };
280
260
  return adapter;
281
261
  }
282
- const warnedInlineOpenWorkflowNames = /* @__PURE__ */ new Set();
283
- function isDurableOpenWorkflowDefinition(name) {
262
+ const warnedInlineWorkflowNames = /* @__PURE__ */ new Set();
263
+ function warnInlineWorkflow(name, runner) {
264
+ if (warnedInlineWorkflowNames.has(name)) return;
265
+ warnedInlineWorkflowNames.add(name);
266
+ console.warn(`[vitehub:workflow] The Workflow ${JSON.stringify(name)} is not a discovered file, so ${runner} cannot run it. Its runs execute inline in this process and are not durable. Move it to server/workflows/ to make it durable.`);
267
+ }
268
+ function isDiscoveredWorkflow(name) {
284
269
  const registry = getWorkflowRuntimeRegistry();
285
270
  return Boolean(registry && Object.hasOwn(registry, name));
286
271
  }
287
272
  function createOpenWorkflowAdapter(config) {
288
273
  const inline = inlineAdapter(config);
289
274
  return {
290
- cancel: async ({ event, id, name }) => isDurableOpenWorkflowDefinition(name) ? await cancelOpenWorkflowRun(config, name, id) : await inline.cancel({
275
+ cancel: async ({ event, id, name }) => isDiscoveredWorkflow(name) ? await cancelOpenWorkflowRun(config, name, id) : await inline.cancel({
291
276
  event,
292
277
  id,
293
278
  name
294
279
  }),
295
- get: async ({ event, id, name }) => isDurableOpenWorkflowDefinition(name) ? await getOpenWorkflowRun(config, name, id) : await inline.get({
280
+ get: async ({ event, id, name }) => isDiscoveredWorkflow(name) ? await getOpenWorkflowRun(config, name, id) : await inline.get({
296
281
  event,
297
282
  id,
298
283
  name
@@ -302,12 +287,9 @@ function createOpenWorkflowAdapter(config) {
302
287
  }),
303
288
  run: async (context) => {
304
289
  const { definition, event, name, options, payload, startAt } = context;
305
- if (isDurableOpenWorkflowDefinition(name)) return await runOpenWorkflow(config, name, payload, definition, options, resolveDispatchObserver(event), startAt);
290
+ if (isDiscoveredWorkflow(name)) return await runOpenWorkflow(config, name, payload, definition, options, resolveDispatchObserver(event), startAt);
306
291
  if (definition?.internalAgentWorkflow || definition?.internalAgentInvocationRecovery) throw workflowErrorDiagnostics.WORKFLOW_AGENT_NOT_DISCOVERED({ name });
307
- if (!warnedInlineOpenWorkflowNames.has(name)) {
308
- warnedInlineOpenWorkflowNames.add(name);
309
- console.warn(`[vitehub:workflow] The Workflow ${JSON.stringify(name)} is not a discovered file, so OpenWorkflow workers cannot run it. Its runs execute inline in this process and are not durable. Move it to server/workflows/ to make it durable.`);
310
- }
292
+ warnInlineWorkflow(name, "OpenWorkflow workers");
311
293
  return {
312
294
  ...await inline.run(context),
313
295
  metadata: {
@@ -467,7 +449,16 @@ function createVercelAdapter(config) {
467
449
  },
468
450
  async run(context) {
469
451
  const { definition, event, name, payload, startAt } = context;
470
- if (!runsNatively(definition)) return await fallback.run(context);
452
+ const agentTurn = Boolean(definition?.internalAgentWorkflow || definition?.internalAgentInvocationRecovery);
453
+ const registry = getWorkflowRuntimeRegistry();
454
+ if (!agentTurn && registry && Object.hasOwn(registry, name) && Reflect.get(registry, Symbol.for("vitehub.vercel.nativeWorkflowRegistry")) === true) {
455
+ const native = definition?.native;
456
+ if (typeof native !== "function" || !("workflowId" in native) || typeof native.workflowId !== "string" || !native.workflowId) throw workflowErrorDiagnostics.WORKFLOW_VERCEL_DISCOVERED_NOT_NATIVE({ name });
457
+ }
458
+ if (!runsNatively(definition)) {
459
+ if (!agentTurn && !isDiscoveredWorkflow(name) && !isDevelopmentServer()) warnInlineWorkflow(name, "Workflow DevKit");
460
+ return await fallback.run(context);
461
+ }
471
462
  return await startVercelWorkflow(name, definition, payload, resolveSettlementObserver(event), resolveDispatchObserver(event), startAt);
472
463
  }
473
464
  };
@@ -618,10 +609,10 @@ function createWorkflow(nameOrOptions, handlerOrOptions, options) {
618
609
  ...createOptions?.rootStep === void 0 ? {} : { rootStep: createOptions.rootStep }
619
610
  });
620
611
  return {
621
- cancel: (id) => cancelWorkflow(name, id),
612
+ cancel: async (id) => await cancelWorkflowRun(name, id),
622
613
  name,
623
614
  defer: (payload, options = {}) => deferWorkflowStart(name, async () => await startWorkflowRun(name, payload, await resolveWorkflowStartOptions(name, payload, createOptions, options), true)),
624
- getRun: (id) => getWorkflowRun(name, id),
615
+ getRun: async (id) => await readWorkflowRun(name, id),
625
616
  async start(payload, options = {}) {
626
617
  const startOptions = await resolveWorkflowStartOptions(name, payload, createOptions, options);
627
618
  return await toWorkflowResult(() => startWorkflowRun(name, payload, startOptions));
@@ -660,11 +651,10 @@ async function startWorkflowRun(name, payload, options, deferred = false) {
660
651
  startAt
661
652
  });
662
653
  }
663
- /**
664
- * Reads one run and returns `[error, run]`. A provider failure is `error`. A run that the provider does not know has
665
- * `status: "unknown"`. Config errors throw.
666
- */
667
654
  async function getWorkflowRun(name, id) {
655
+ return await readWorkflowRun(name, id);
656
+ }
657
+ async function readWorkflowRun(name, id) {
668
658
  const config = getActiveWorkflowConfig();
669
659
  const test = getViteHubTestMode();
670
660
  if (test) return [void 0, getWorkflowTestRun(test, config.driver, name, id)];
@@ -674,11 +664,10 @@ async function getWorkflowRun(name, id) {
674
664
  name
675
665
  }));
676
666
  }
677
- /**
678
- * Cancels one run and returns `[error, run]`. A provider failure, or a provider that cannot cancel the run, is
679
- * `error`. Config errors, for example an unknown Workflow name, throw.
680
- */
681
667
  async function cancelWorkflow(name, id) {
668
+ return await cancelWorkflowRun(name, id);
669
+ }
670
+ async function cancelWorkflowRun(name, id) {
682
671
  const config = getActiveWorkflowConfig();
683
672
  const definition = await loadRequiredWorkflowDefinition(name);
684
673
  const test = getViteHubTestMode();
@@ -0,0 +1,136 @@
1
+ import { n as invariantError } from "./invariant-Dj2R1eMr.js";
2
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-35AEmfve.js";
3
+ // ../internal/src/integrations/hex.ts
4
+ const textEncoder = new TextEncoder();
5
+ new TextDecoder();
6
+ function encodeNameHex(name) {
7
+ return [...textEncoder.encode(name)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
8
+ }
9
+ // src/integrations/cloudflare.ts
10
+ const cloudflareWorkflowNameMaxLength = 64;
11
+ function isCloudflareInstanceNotFound(error) {
12
+ if (typeof error !== "object" || error === null) return false;
13
+ try {
14
+ const message = Reflect.get(error, "message");
15
+ return typeof message === "string" && message.includes("instance.not_found");
16
+ } catch {
17
+ return false;
18
+ }
19
+ }
20
+ function shortHash(value) {
21
+ let hash = 14695981039346656037n;
22
+ for (const char of value) {
23
+ hash ^= BigInt(char.codePointAt(0) || 0);
24
+ hash = BigInt.asUintN(64, hash * 1099511628211n);
25
+ }
26
+ return hash.toString(16).padStart(16, "0");
27
+ }
28
+ function legacyShortHash(value) {
29
+ let hash = 2166136261;
30
+ for (const char of value) {
31
+ hash ^= char.codePointAt(0) || 0;
32
+ hash = Math.imul(hash, 16777619);
33
+ }
34
+ return (hash >>> 0).toString(16).padStart(8, "0");
35
+ }
36
+ function workflowClassPrefix(name) {
37
+ return name.split(/[^a-z0-9]+/i).filter(Boolean).map((segment) => `${segment.charAt(0).toUpperCase()}${segment.slice(1)}`).join("") || "Default";
38
+ }
39
+ function getCloudflareWorkflowBindingName(name) {
40
+ return `WORKFLOW_${encodeNameHex(name).toUpperCase()}`;
41
+ }
42
+ function getCloudflareWorkflowName(name) {
43
+ const encoded = encodeNameHex(name);
44
+ const fullName = `workflow--${encoded}`;
45
+ if (fullName.length <= cloudflareWorkflowNameMaxLength) return fullName;
46
+ const hash = shortHash(name);
47
+ const prefixLength = 53 - hash.length;
48
+ return `workflow--${encoded.slice(0, prefixLength)}-${hash}`;
49
+ }
50
+ function getCloudflareWorkflowClassName(name) {
51
+ return `ViteHub${workflowClassPrefix(name)}${shortHash(name)}Workflow`;
52
+ }
53
+ /** The pre-64-bit class export kept for existing Cloudflare Workflow instances. */
54
+ function getLegacyCloudflareWorkflowClassName(name) {
55
+ return `ViteHub${workflowClassPrefix(name)}${legacyShortHash(name)}Workflow`;
56
+ }
57
+ function createCloudflareWorkflowBindings(definitions, options) {
58
+ if (!definitions.length) return;
59
+ const configurable = definitions.filter((definition) => definition.source !== "agent-workflow-recovery");
60
+ if (configurable.length > 1 && options && (options.binding || options.name)) throw workflowErrorDiagnostics.WORKFLOW_R0001({ message: "Cloudflare workflow binding and name overrides are only supported when one workflow is discovered." });
61
+ return definitions.map((definition) => ({
62
+ binding: configurable.length === 1 && configurable[0] === definition && options ? options.binding || getCloudflareWorkflowBindingName(definition.name) : getCloudflareWorkflowBindingName(definition.name),
63
+ class_name: getCloudflareWorkflowClassName(definition.name),
64
+ name: configurable.length === 1 && configurable[0] === definition && options ? options.name || getCloudflareWorkflowName(definition.name) : getCloudflareWorkflowName(definition.name)
65
+ }));
66
+ }
67
+ // src/runtime/cloudflare-concurrency-counter.ts
68
+ /** The Durable Object binding that counts the runs of the Workflows that set `concurrency`. */
69
+ const cloudflareConcurrencyBinding = "VITEHUB_WORKFLOW_CONCURRENCY";
70
+ const cloudflareConcurrencyClassName = "ViteHubWorkflowConcurrency";
71
+ const cloudflareConcurrencyMigrationTag = "vitehub-workflow-concurrency-v1";
72
+ const endedStatuses = /* @__PURE__ */ new Set([
73
+ "complete",
74
+ "errored",
75
+ "terminated"
76
+ ]);
77
+ const holdersKey = "holders";
78
+ function isCounterNamespace(value) {
79
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "get") === "function" && typeof Reflect.get(value, "idFromName") === "function";
80
+ }
81
+ function isWorkflowInstanceBinding(value) {
82
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "get") === "function";
83
+ }
84
+ async function readHolders(storage) {
85
+ const value = await storage.get(holdersKey);
86
+ return Array.isArray(value) ? value.filter((holder) => typeof holder === "string") : [];
87
+ }
88
+ async function hasEnded(binding, run) {
89
+ try {
90
+ const { status } = await (await binding.get(run)).status();
91
+ return status !== void 0 && endedStatuses.has(status);
92
+ } catch (error) {
93
+ return isCloudflareInstanceNotFound(error);
94
+ }
95
+ }
96
+ /**
97
+ * The count of one Workflow, kept by one Durable Object. `blockConcurrencyWhile` keeps a second request out while a
98
+ * request reads the instance status of the runs that hold a place, so two runs cannot take the last place. A holder whose
99
+ * instance ended, or that Cloudflare no longer knows (it throws after retention), loses its place.
100
+ */
101
+ function createCloudflareConcurrencyCounter(state, env) {
102
+ return {
103
+ acquire: async (run, limit, binding) => await state.blockConcurrencyWhile(async () => {
104
+ let holders = await readHolders(state.storage);
105
+ if (holders.includes(run)) return true;
106
+ if (holders.length >= limit) {
107
+ const instances = env[binding];
108
+ if (!isWorkflowInstanceBinding(instances)) throw invariantError(`The Workflow binding ${binding} is missing in the Durable Object that counts its runs.`);
109
+ const ended = await Promise.all(holders.map(async (holder) => await hasEnded(instances, holder)));
110
+ holders = holders.filter((_holder, index) => !ended[index]);
111
+ if (holders.length >= limit) {
112
+ await state.storage.put(holdersKey, holders);
113
+ return false;
114
+ }
115
+ }
116
+ await state.storage.put(holdersKey, [...holders, run]);
117
+ return true;
118
+ }),
119
+ release: async (run) => await state.blockConcurrencyWhile(async () => {
120
+ const holders = await readHolders(state.storage);
121
+ if (holders.includes(run)) await state.storage.put(holdersKey, holders.filter((holder) => holder !== run));
122
+ })
123
+ };
124
+ }
125
+ /** The place of the Cloudflare instance `run` in the count of the Workflow `name`. */
126
+ function createCloudflareConcurrencySlots(env, name, run, binding) {
127
+ const namespace = env[cloudflareConcurrencyBinding];
128
+ if (!isCounterNamespace(namespace)) throw workflowErrorDiagnostics.WORKFLOW_CONCURRENCY_BINDING_MISSING({ name });
129
+ if (!run) throw invariantError(`Cloudflare started the Workflow ${JSON.stringify(name)} without an instance id.`);
130
+ const counter = () => namespace.get(namespace.idFromName(name));
131
+ return {
132
+ acquire: async (limit) => await counter().acquire(run, limit, binding),
133
+ release: async () => await counter().release(run)
134
+ };
135
+ }
136
+ export { createCloudflareConcurrencySlots as a, getCloudflareWorkflowClassName as c, encodeNameHex as d, createCloudflareConcurrencyCounter as i, getLegacyCloudflareWorkflowClassName as l, cloudflareConcurrencyClassName as n, createCloudflareWorkflowBindings as o, cloudflareConcurrencyMigrationTag as r, getCloudflareWorkflowBindingName as s, cloudflareConcurrencyBinding as t, isCloudflareInstanceNotFound as u };
@@ -1,5 +1,5 @@
1
1
  import { t as isRecord } from "./object-CAK6UYR5.js";
2
- import { t as workflowErrorDiagnostics } from "./error-diagnostics--2cV_ER1.js";
2
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-35AEmfve.js";
3
3
  import { defu } from "defu";
4
4
  /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
5
5
  function hostFromNitroPreset(value) {
@@ -28,7 +28,7 @@ const knownDrivers = /* @__PURE__ */ new Set([
28
28
  "openworkflow",
29
29
  "vercel"
30
30
  ]);
31
- function readString(value, label) {
31
+ function readOptionalNonEmptyString(value, label) {
32
32
  if (typeof value === "undefined") return;
33
33
  if (typeof value !== "string" || !value.trim()) throw workflowErrorDiagnostics.WORKFLOW_C0001({ message: `\`${label}\` must be a non-empty string when provided.` });
34
34
  return value.trim();
@@ -36,7 +36,7 @@ function readString(value, label) {
36
36
  function readRuntimeConfigValue(value, label, preserveWhitespace = false) {
37
37
  if (typeof value === "undefined") return;
38
38
  if (typeof value === "string") {
39
- const normalized = readString(value, label);
39
+ const normalized = readOptionalNonEmptyString(value, label);
40
40
  return preserveWhitespace ? value : normalized;
41
41
  }
42
42
  if (!isRuntimeEnvDeclaration(value)) throw workflowErrorDiagnostics.WORKFLOW_C0002({ message: `\`${label}\` must be a string or runtime env declaration.` });
@@ -61,9 +61,9 @@ function readPositiveInteger(value, label) {
61
61
  function normalizeOpenWorkflowPostgresOptions(value) {
62
62
  if (typeof value === "undefined") return;
63
63
  if (!isRecord(value)) throw workflowErrorDiagnostics.WORKFLOW_C0005({ message: "`workflow.postgres` must be a plain object." });
64
- const namespaceId = readString(value.namespaceId, "workflow.postgres.namespaceId");
64
+ const namespaceId = readOptionalNonEmptyString(value.namespaceId, "workflow.postgres.namespaceId");
65
65
  const runMigrations = readBoolean(value.runMigrations, "workflow.postgres.runMigrations");
66
- const schema = readString(value.schema, "workflow.postgres.schema");
66
+ const schema = readOptionalNonEmptyString(value.schema, "workflow.postgres.schema");
67
67
  const url = readRuntimeConfigValue(value.url, "workflow.postgres.url");
68
68
  return {
69
69
  ...namespaceId ? { namespaceId } : {},
@@ -75,7 +75,7 @@ function normalizeOpenWorkflowPostgresOptions(value) {
75
75
  function normalizeOpenWorkflowSqliteOptions(value) {
76
76
  if (typeof value === "undefined") return;
77
77
  if (!isRecord(value)) throw workflowErrorDiagnostics.WORKFLOW_C0006({ message: "`workflow.sqlite` must be a plain object." });
78
- const namespaceId = readString(value.namespaceId, "workflow.sqlite.namespaceId");
78
+ const namespaceId = readOptionalNonEmptyString(value.namespaceId, "workflow.sqlite.namespaceId");
79
79
  const path = readRuntimeConfigValue(value.path, "workflow.sqlite.path", true);
80
80
  const runMigrations = readBoolean(value.runMigrations, "workflow.sqlite.runMigrations");
81
81
  return {
@@ -1,4 +1,4 @@
1
- import { f as WorkflowDefinition } from "./types-DvYcvbPG.js";
1
+ import { h as WorkflowDefinition } from "./types-DrhUXMsE.js";
2
2
  /**
3
3
  * Defines a Workflow from one object: `defineWorkflow({ handler, ...options })`. The file path is the Workflow name.
4
4
  * The handler receives one object, `{ payload, steps, sleep, ...context }`. Pass the payload type as the type argument.
@@ -1,7 +1,8 @@
1
1
  import { t as isRecord } from "./object-CAK6UYR5.js";
2
- import { t as workflowErrorDiagnostics } from "./error-diagnostics--2cV_ER1.js";
2
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-35AEmfve.js";
3
3
  // src/definition.ts
4
4
  const workflowDefinitionKeys = /* @__PURE__ */ new Set([
5
+ "concurrency",
5
6
  "handler",
6
7
  "native",
7
8
  "rootStep"
@@ -27,6 +28,8 @@ function defineWorkflow(definition, ...removed) {
27
28
  if (unknownKey) throw workflowErrorDiagnostics.WORKFLOW_C0015({ message: `\`defineWorkflow()\` does not support the ${JSON.stringify(unknownKey)} option.` });
28
29
  if (typeof definition.handler !== "function") throw workflowErrorDiagnostics.WORKFLOW_C0014({ message: "`defineWorkflow()` requires a workflow handler." });
29
30
  if (definition.native !== void 0 && typeof definition.native !== "function") throw workflowErrorDiagnostics.WORKFLOW_C0016({ message: "`defineWorkflow()` native entry must be a workflow handler." });
31
+ const concurrency = definition.concurrency;
32
+ if (concurrency !== void 0 && (typeof concurrency !== "number" || !Number.isSafeInteger(concurrency) || concurrency < 1)) throw workflowErrorDiagnostics.WORKFLOW_CONCURRENCY_INVALID({ value: typeof concurrency === "string" ? JSON.stringify(concurrency) : String(concurrency) });
30
33
  return definition;
31
34
  }
32
35
  export { defineWorkflow };
@@ -1,4 +1,4 @@
1
- import { t as workflowErrorDiagnostics } from "./error-diagnostics--2cV_ER1.js";
1
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-35AEmfve.js";
2
2
  import { parseDuration } from "@vite-hub/runtime";
3
3
  // src/runtime/delay.ts
4
4
  const maximumTime = 864e13;
@@ -23,6 +23,8 @@ function resolveWorkflowStartAt(delay, now = Date.now()) {
23
23
  const workflowStartAtKey = "~vitehubStartAt";
24
24
  /** Marks the Vercel native entry that ViteHub generates for a folder Workflow. Only that entry reads the start time. */
25
25
  const generatedNativeEntryKey = "~vitehubGenerated";
26
+ const generatedNativeRootStepKey = "~vitehubGeneratedRootStep";
27
+ const vercelNativeRegistryKey = "vitehub.vercel.nativeWorkflowRegistry";
26
28
  /** Cloudflare `create()` has no delay, so a delayed run sends its start time next to the payload. */
27
29
  function toCloudflareStartParams(payload, startAt) {
28
30
  return startAt === void 0 ? payload : {
@@ -32,13 +34,13 @@ function toCloudflareStartParams(payload, startAt) {
32
34
  }
33
35
  /** Reads the params of a Cloudflare run. The handler gets only the payload. */
34
36
  function fromCloudflareStartParams(params) {
35
- if (typeof params !== "object" || params === null || !Object.hasOwn(params, "~vitehubStartAt")) return { payload: params };
36
- const startAt = Reflect.get(params, workflowStartAtKey);
37
+ if (typeof params !== "object" || params === null || !("~vitehubStartAt" in params)) return { payload: params };
38
+ const startAt = params[workflowStartAtKey];
37
39
  const keys = Object.keys(params);
38
40
  if (typeof startAt !== "number" || !keys.every((key) => key === "~vitehubStartAt" || key === "payload")) return { payload: params };
39
41
  return {
40
- payload: Reflect.get(params, "payload"),
42
+ payload: "payload" in params ? params.payload : void 0,
41
43
  startAt
42
44
  };
43
45
  }
44
- export { workflowStartAtKey as a, toCloudflareStartParams as i, generatedNativeEntryKey as n, resolveWorkflowStartAt as r, fromCloudflareStartParams as t };
46
+ export { toCloudflareStartParams as a, resolveWorkflowStartAt as i, generatedNativeEntryKey as n, vercelNativeRegistryKey as o, generatedNativeRootStepKey as r, workflowStartAtKey as s, fromCloudflareStartParams as t };
@@ -1,4 +1,4 @@
1
- import { P as WorkflowRuntimeConfigValue } from "./types-DvYcvbPG.js";
1
+ import { z as WorkflowRuntimeConfigValue } from "./types-DrhUXMsE.js";
2
2
  import { Durability, DurabilityContext } from "@vite-hub/runtime/durability";
3
3
  /** What the build passes to `workflowDurability()`. The storage values may name runtime environment variables. */
4
4
  export interface WorkflowDurabilityInput {
@@ -6,6 +6,8 @@ export interface WorkflowDurabilityInput {
6
6
  defaultDatabase?: boolean;
7
7
  postgresUrl?: WorkflowRuntimeConfigValue;
8
8
  driver: string;
9
+ /** The build makes a Workflow DevKit entry for each discovered Workflow file. Only a Vercel build does. */
10
+ native?: boolean;
9
11
  sqlitePath?: WorkflowRuntimeConfigValue;
10
12
  }
11
13
  /**
@@ -32,12 +32,18 @@ function workflowDurability(input, context) {
32
32
  scope: "shared",
33
33
  reason: "Cloudflare Workflows store each run."
34
34
  }];
35
+ if (input.driver === "vercel" && input.native) return [{
36
+ primitive: "workflow",
37
+ store: "vercel",
38
+ scope: "shared",
39
+ reason: "Vercel Workflow DevKit stores each run of a discovered Workflow file."
40
+ }];
35
41
  if (input.driver !== "openworkflow") return [{
36
42
  primitive: "workflow",
37
43
  store: "inline",
38
44
  scope: "process",
39
45
  reason: "Runs execute in the request process. A restart loses them.",
40
- fix: "Set `workflow: { driver: \"openworkflow\" }` with a Postgres URL."
46
+ fix: "The Vercel driver runs Workflows durably only in a Vercel build. Deploy to Vercel, or set `workflow: { driver: \"openworkflow\" }` with a Postgres URL to run them on this server."
41
47
  }];
42
48
  const storage = resolveOpenWorkflowStorage({
43
49
  postgresUrl: resolveDurabilityValue(input.postgresUrl, env),