@vite-hub/schedule 0.1.0 → 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 (54) hide show
  1. package/README.md +114 -96
  2. package/dist/console-wEhr0LWn.d.ts +330 -0
  3. package/dist/definition.d.ts +6 -2
  4. package/dist/definition.js +47 -1
  5. package/dist/due-BVMRQ93v.js +144 -0
  6. package/dist/durability.d.ts +14 -0
  7. package/dist/durability.js +23 -0
  8. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  9. package/dist/error-diagnostics-Mpeks7J0.js +166 -0
  10. package/dist/index.d.ts +59 -5
  11. package/dist/index.js +27 -2
  12. package/dist/invariant-DolT9EEx.js +22 -0
  13. package/dist/{kv-storage-Bv9ocZT-.d.ts → kv-storage-C0KZZB6v.d.ts} +2 -2
  14. package/dist/{kv-storage-DWinmLLy.js → kv-storage-iJChCS5A.js} +2 -2
  15. package/dist/object-Da1zyPCR.js +11 -0
  16. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  17. package/dist/{operations-gk2qzhYV.js → operations-DwZWFIUX.js} +75 -22
  18. package/dist/operations.d.ts +27 -4
  19. package/dist/operations.js +127 -730
  20. package/dist/os.d.ts +167 -0
  21. package/dist/os.js +1659 -0
  22. package/dist/runtime/console.d.ts +12 -0
  23. package/dist/runtime/console.js +85 -0
  24. package/dist/runtime/kv.d.ts +1 -1
  25. package/dist/runtime/kv.js +1 -1
  26. package/dist/runtime/process.d.ts +32 -5
  27. package/dist/runtime/process.js +401 -413
  28. package/dist/runtime/state.d.ts +2 -9
  29. package/dist/runtime/state.js +2 -2
  30. package/dist/runtime/static.d.ts +28 -2
  31. package/dist/runtime/static.js +2 -2
  32. package/dist/runtime.d.ts +34 -32
  33. package/dist/runtime.js +6 -5
  34. package/dist/started-BuGmnus4.js +201 -0
  35. package/dist/started-Bx7MDbrl.js +146 -0
  36. package/dist/{execute-BJrgNgQ0.js → started-errors-p7cu_rI7.js} +69 -20
  37. package/dist/{state-DSxmHPn3.js → state-B-Fuyfb4.js} +42 -22
  38. package/dist/state-Do2wV4Tx.d.ts +49 -0
  39. package/dist/{static-6g82xguw.js → static-DQwzzvPg.js} +63 -42
  40. package/dist/store-Df0-fzCl.d.ts +53 -0
  41. package/dist/time-zone-SBldrUgt.js +59 -0
  42. package/dist/{types-CHdV9FQU.d.ts → types-Cw5LjPuc.d.ts} +62 -8
  43. package/dist/vite.d.ts +255 -2
  44. package/dist/vite.js +5876 -2
  45. package/dist/{wait-until-BmIqRo4x.js → wait-until-Dy4Bn3ZN.js} +26 -1
  46. package/package.json +19 -24
  47. package/dist/definition-CMiOg1lg.js +0 -111
  48. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  49. package/dist/error-diagnostics-in7mif5s.js +0 -45
  50. package/dist/nuxt.d.ts +0 -17
  51. package/dist/nuxt.js +0 -27
  52. package/dist/store-QAOd8bxm.d.ts +0 -11
  53. package/dist/vite-BAVyZ8hZ.d.ts +0 -474
  54. package/dist/vite-BJwZkMrn.js +0 -5193
package/README.md CHANGED
@@ -5,14 +5,14 @@
5
5
  [![license](https://comark-ui.onmax.me/badge.svg?label=license&value=Apache-2.0)](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
6
6
  [![docs](https://comark-ui.onmax.me/badge.svg?label=docs&value=vitehub.dev)](https://vitehub.dev/docs)
7
7
 
8
- `@vite-hub/schedule` discovers recurring work, generates cron output for supported hosts, and manages recurring schedules that an application creates while it runs.
8
+ `@vite-hub/schedule` discovers recurring work, generates cron output for supported hosts, and can run Static Schedule Definitions in one long-lived process.
9
9
 
10
10
  ## Choose the package
11
11
 
12
- Install `vite-hub` for an application. It includes Schedule and exposes application imports under `vite-hub/schedule`.
12
+ Install `vite-hub` and `@vite-hub/schedule` for an application. `vite-hub` exposes application imports under `vite-hub/schedule` and loads Schedule from the app.
13
13
 
14
14
  ```sh
15
- pnpm add vite-hub
15
+ pnpm add vite-hub @vite-hub/schedule
16
16
  ```
17
17
 
18
18
  Enable Schedule with the framework integration and import application helpers from its feature path:
@@ -23,7 +23,7 @@ import { vitehub } from "vite-hub";
23
23
  import { defineConfig } from "vite";
24
24
 
25
25
  export default defineConfig({
26
- plugins: [vitehub({ preset: "cloudflare", schedule: true })],
26
+ plugins: [vitehub({ host: "cloudflare", schedule: true })],
27
27
  });
28
28
  ```
29
29
 
@@ -37,19 +37,9 @@ Install the owner package directly when a library or custom integration needs Sc
37
37
  pnpm add @vite-hub/schedule
38
38
  ```
39
39
 
40
- Direct integrations use `@vite-hub/schedule`, `@vite-hub/schedule/runtime`, and `@vite-hub/schedule/vite`. Add Vite when the project uses `hubSchedule()`. Add `@vite-hub/kv` when using the default KV-backed stores or the generated Process Runtime. Static Schedule Definitions, memory stores, and custom `ScheduleKVStorage` implementations do not require KV.
40
+ Direct integrations use `@vite-hub/schedule`, `@vite-hub/schedule/runtime`, and `@vite-hub/schedule/vite`. Add Vite when the project uses `hubSchedule()`. Add `@vite-hub/kv` when using the KV Schedule Run store through `@vite-hub/schedule/runtime/kv` or the generated Process Runtime. Static Schedule Definitions, memory stores, and custom `ScheduleKVStorage` implementations do not require KV.
41
41
 
42
- Both packages require Node.js 24.15 or newer.
43
-
44
- ## Choose the schedule kind
45
-
46
- | Kind | Create it with | Use it when |
47
- | -------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
48
- | Static Schedule Definition | `defineSchedule()` in a discovered source file | The cron is part of the deployment and can produce host Provider Output. |
49
- | Schedule Target | `defineScheduleTarget()` in a discovered source file | Runtime Schedules need a named handler with no build-time cron. A target never produces static cron output. |
50
- | Runtime Schedule | `schedules.create()` in server code | The application must create, update, pause, or delete a recurring schedule while it runs. |
51
-
52
- A Runtime Schedule must name a Schedule Target. A Static Schedule Definition can also become a target when it sets `allowRuntimeSchedules: true`.
42
+ Both packages require Node.js 22.18 or newer.
53
43
 
54
44
  ## Run one occurrence
55
45
 
@@ -99,7 +89,7 @@ export default defineConfig({
99
89
 
100
90
  Then export a definition from `server/schedules/<name>.ts` or `src/<name>.schedule.ts`.
101
91
 
102
- ```ts
92
+ ```ts fragment
103
93
  // server/schedules/daily-report.ts
104
94
  import { defineSchedule } from "@vite-hub/schedule";
105
95
 
@@ -112,81 +102,81 @@ export default defineSchedule({
112
102
  });
113
103
  ```
114
104
 
115
- Static Schedule Definitions use five-field UTC cron expressions. They cannot set `timeZone`. The integration can generate host-specific output for Cloudflare Cron Triggers, Vercel Cron Jobs, Netlify Scheduled Functions, standalone `Deno.cron`, and Nitro's Cloudflare schedule hook. Host selection, local execution, deployment proof, limits, and billing still come from the selected host. Check the [runtime and host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix) before deploying.
105
+ Static Schedule Definitions use five-field cron expressions. The cron uses UTC unless the definition sets `timeZone` to an IANA name, such as `Europe/Madrid`. `timeZone` works with the Process Runtime and with every host's cron output.
116
106
 
117
- Applications that use the framework distribution register Schedule through `vitehub({ preset, schedule: true })` and import the definition helper from `vite-hub/schedule`. The Deno framework preset currently rejects Schedule because standalone Deno cron output sits outside its generated Nitro entrypoint. Use the direct Schedule integration for that output.
107
+ The integration can generate host-specific output for Cloudflare Cron Triggers, Vercel Cron Jobs, Netlify Scheduled Functions, standalone `Deno.cron`, Nitro's Cloudflare schedule hook, and Netlify Scheduled Functions that run in Nitro's server bundle. A build writes only the output of its host: Nitro's resolved preset, or else `nitro.preset`, `NITRO_PRESET`, `SERVER_PRESET`, or `VITEHUB_HOST`. It writes the output of every host only when no host is known. Host selection, local execution, deployment proof, limits, and billing still come from the selected host. Check the [runtime and host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix) before deploying.
118
108
 
119
- Direct Nuxt projects can register `@vite-hub/schedule/nuxt` instead of `hubSchedule()`. The module installs the Vite integration and merges Schedule output into Nitro config.
109
+ Applications that use the framework distribution register Schedule through `vitehub({ host, schedule: true })` and import the definition helper from `vite-hub/schedule`. On Deno, the build writes standalone cron output and a `.output/main.ts` entrypoint that loads it before the Nitro server.
120
110
 
121
- ## Create a Runtime Schedule
111
+ Nuxt projects enable Schedule with `vite-hub/nuxt` and `vitehub: { schedule: true }`. The module installs the Vite integration and merges Schedule output into Nitro config.
122
112
 
123
- Define a cronless target for work that runs only through Runtime Schedules.
113
+ ## Start a Schedule from code
114
+
115
+ Leave out `cron` when your users pick the time, such as a reminder. Code then starts the Definition with `startSchedule()`, once at `at` or on a `cron` in a `timeZone`, and the handler gets `payload`.
124
116
 
125
117
  ```ts
126
- // server/schedules/report.ts
127
- import { defineScheduleTarget } from "@vite-hub/schedule";
118
+ // server/schedules/reminder.ts
119
+ import { defineSchedule } from "@vite-hub/schedule";
128
120
 
129
- export default defineScheduleTarget<{ prompt: string }>({
130
- async handler({ input }) {
131
- if (input) await generateReport(input.prompt);
121
+ export default defineSchedule({
122
+ handler({ payload }) {
123
+ console.log("Reminder", payload);
132
124
  },
133
125
  });
134
126
  ```
135
127
 
136
- Before creating the recurring record, install the Schedule runtime so it can load the discovered target registry and reconcile stored schedules. A custom host calls `installScheduleRuntime()` from `@vite-hub/schedule/runtime/driver` with its wake driver. A generated Process Runtime does this during application startup.
137
-
138
- After runtime installation completes, create the recurring record from server code.
139
-
140
128
  ```ts
141
- import { schedules } from "@vite-hub/schedule/runtime";
142
-
143
- const report = await schedules.create({
144
- cron: "30 8 * * 1-5",
145
- id: "weekday-report",
146
- input: { prompt: "Summarize yesterday" },
147
- target: "report",
148
- timeZone: "Europe/Copenhagen",
149
- });
129
+ import { cancelSchedule, listSchedules, startSchedule } from "@vite-hub/schedule";
150
130
 
151
- console.log(report.id);
131
+ const [error, reminder] = await startSchedule("reminder", { at: "2026-11-08T09:00:00Z", payload: { text: "Call Ana" } });
132
+ const [, standUp] = await startSchedule("reminder", { cron: "0 9 * * 1-5", timeZone: "Europe/Madrid", payload: { text: "Stand-up" } });
133
+ const [, started] = await listSchedules({ name: "reminder" });
134
+ await cancelSchedule(standUp!.id);
152
135
  ```
153
136
 
154
- The installed runtime can supply a native wake driver, or one long-lived process can install `createProcessScheduleWakeDriver()` from `@vite-hub/schedule/runtime/process`.
155
-
156
- Static provider cron output does not automatically wake Runtime Schedules. Provider-backed Runtime Schedules need a host-owned wake driver. Request-scoped and serverless hosts must not use the Process Runtime because the process may stop between requests.
137
+ The functions return `[error, data]`. The Schedules are stored in KV, so they survive restarts and deploys. When a Definition has no `cron`, the build adds the Schedule `vitehub/started-schedules` with the cron `* * * * *`: Cloudflare wakes it with a Cron Trigger, and the Process Runtime wakes it on Node. Each wake runs the started Schedules that are due. Started Schedules need KV, and on Node the Process Runtime. `vitehub schedule list`, `start`, and `cancel` and the Console Schedules page show and change them. Read the [server API](https://vitehub.dev/docs/schedule/server-api#start-a-schedule-from-code) for the delivery rules.
157
138
 
158
139
  ## Understand time zones
159
140
 
160
- Static Schedule Definitions and their Provider Output always use UTC. Runtime Schedules use UTC when `timeZone` is absent and accept IANA time-zone names when the cron must follow local clock time.
141
+ The value of `timeZone` must be an IANA name. Abbreviations such as `PST` and numeric offsets such as `+01:00` are rejected. The Process Runtime accepts any expression, such as a shared constant. Host cron output reads `timeZone` from the source file at build time, so write it as a string literal there. A dynamic value fails the build with `SCHEDULE_R0003`.
161
142
 
162
- Omitting `timeZone` during an update preserves the stored zone. Set it to `UTC` to return to UTC evaluation. Numeric offsets such as `+01:00` are rejected. During a daylight-saving gap, ViteHub skips a local time that does not exist. During an overlap, both distinct instants that share the repeated local time are due.
143
+ Cloudflare, Vercel, Netlify, and Deno read cron in UTC only. For a Schedule with a `timeZone`, the build writes a UTC cron that covers every offset of the time zone in the next two years, and the runtime checks the local time on each wake. `0 8 * * *` in `Europe/Madrid` becomes `0 6,7 * * *`: the host wakes the Schedule twice a day, and the Schedule runs at the wake that is 08:00 in Madrid. When a local time moves to another UTC day, the UTC cron wakes every day, or on the shifted weekdays, and the runtime checks the local date. A `cron` override in the build config replaces both the cron and the time zone: the host runs the override in UTC. Rebuild when a time zone changes its rules.
163
144
 
164
- ## Choose storage and wake ownership
145
+ On daylight saving time changes, every host and the Process Runtime behave the same:
165
146
 
166
- Memory stores are the default for direct calls. They are process-local and lose Runtime Schedules and Schedule Run history on restart. Use `createKVRuntimeScheduleStore({ kvStore })` and `createKVScheduleRunStore({ kvStore })` when those records must survive a restart. Both factories require an explicit `ScheduleKVStorage`. Static schedules, memory stores, and custom storage do not require `@vite-hub/kv`.
147
+ - A local time that the clock skips runs once, shifted by the length of the gap, as RFC 5545 and `Temporal` read it. `30 2 * * *` in `Europe/Madrid` runs at 03:30 on the spring-forward day.
148
+ - A local time that occurs twice runs once, at its first occurrence, when the cron sets a fixed minute and hour. A cron with `*` in the minute or hour field runs on elapsed time, so it also runs in the repeated hour.
167
149
 
168
- To use ViteHub KV, install `@vite-hub/kv` and import the adapter explicitly:
150
+ ## Run a Schedule once per occurrence
169
151
 
170
- ```ts
171
- import { createKVRuntimeScheduleStore, createKVScheduleRunStore } from "@vite-hub/schedule/runtime"
172
- import { scheduleKVStorage } from "@vite-hub/schedule/runtime/kv"
152
+ Each run gets `idempotencyKey`, `schedule:<name>:<scheduledAt ISO>`. Cloudflare supplies the scheduled timestamp, and the Process Runtime records each occurrence. Repeated deliveries of those occurrences keep the same key. Pass the key to Email, a Channel `send()`, or a Queue on Vercel or the local driver to dedupe work with the same key:
173
153
 
174
- const runtimeScheduleStore = createKVRuntimeScheduleStore({ kvStore: scheduleKVStorage })
175
- const scheduleRunStore = createKVScheduleRunStore({ kvStore: scheduleKVStorage })
154
+ ```ts fragment
155
+ export default defineSchedule({
156
+ cron: "0 7 * * *",
157
+ timeZone: "Europe/Stockholm",
158
+ async handler({ idempotencyKey }) {
159
+ await email.send({ from, to, subject: "Today's lesson", text, idempotencyKey });
160
+ },
161
+ });
176
162
  ```
177
163
 
178
- Migration: replace factory calls without `kvStore` with the explicit adapter shown above. Generated Process Runtime wiring selects this adapter automatically. Applications using the framework can import it from `vite-hub/schedule/runtime/kv`.
164
+ The Process Runtime also stores one run per occurrence, so it does not run a repeated wake again. Host cron output does not store runs.
165
+
166
+ Vercel, Netlify, and Deno do not supply a scheduled timestamp to these entries. They estimate `scheduledAt` as the latest host UTC cron match within the previous day, or the current minute when none matches. A late delivery or retry after another host cron match can get a different key. Time-zone filtering uses that estimate too: a summer Madrid 06:00 wake delivered after the extra 07:00 wake can be skipped. These hosts cannot guarantee occurrence identity or dedupe across that boundary. Use an application business key for side effects that must dedupe across delays and retries.
179
167
 
180
- The generated Process Runtime creates both stores through the default KV store configured by `hubKv()`. It scans inside the Node.js process and runs discovered Static Schedule Definitions with stored Runtime Schedules. Configure it only for one long-lived replica:
168
+ ## Run schedules in the server process
169
+
170
+ The generated Process Runtime runs each Static Schedule Definition on its cron inside the Node.js process. It records Schedule Runs in the default KV store configured by `hubKV()`. Use it on long-lived servers, one or more:
181
171
 
182
172
  ```ts
183
- import { hubKv } from "@vite-hub/kv/vite";
173
+ import { hubKV } from "@vite-hub/kv/vite";
184
174
  import { hubSchedule } from "@vite-hub/schedule/vite";
185
175
  import { defineConfig } from "vite";
186
176
 
187
177
  export default defineConfig({
188
178
  plugins: [
189
- hubKv(),
179
+ hubKV(),
190
180
  hubSchedule({
191
181
  runtime: {
192
182
  driver: "process",
@@ -197,64 +187,92 @@ export default defineConfig({
197
187
  });
198
188
  ```
199
189
 
200
- Its defaults are prefix `vitehub:schedule`, scan interval `60_000` milliseconds, and concurrency `1`. The interval cannot exceed one minute. `concurrency` limits wake delivery only inside that process. The KV run store records occurrences but does not provide distributed leader election or locking, so multiple replicas can execute the same work. A stopped process does not backfill minutes that it missed.
190
+ Its defaults are prefix `vitehub:schedule`, scan interval `60_000` milliseconds, concurrency `1`, catch-up `catchUpMs` of one hour, and `leaseTtlMs` of one minute. The interval cannot exceed one minute. `concurrency` limits runs only inside that process. A queued occurrence can start while its scheduled minute is within `catchUpMs` of the current minute; older queued work is dropped. With `catchUpMs: 0`, it can start only in its scheduled minute. After a restart, the runtime runs the due minutes that no process checked, within `catchUpMs`, for each Schedule that already has a run. Run ids are deterministic, so a minute that already ran does not run again. Request-scoped and serverless hosts must not use the Process Runtime because the process may stop between requests.
201
191
 
202
- With the Process Runtime, the default `providerOutput: "auto"` emits no host Provider Output, so the process owns Static Schedule wakes. Set `providerOutput: "standalone"` or `"nitro"` to move Static Schedule wakes to that Provider Output while the process continues to run Runtime Schedules. `providerOutput: false` explicitly records the same wake ownership as `"auto"` in this configuration.
192
+ ### Run on more than one server
203
193
 
204
- `installScheduleRuntime()` returns only after its driver reconciles the complete stored snapshot, including disabled Runtime Schedules. Later creates, updates, and deletes persist first and reconcile one at a time. If host reconciliation fails, ViteHub restores the previous stored record and rejects the change.
194
+ Every server checks every Schedule. Before a server runs an occurrence, it takes a lease on the key `<prefix>/schedule/<run id>`, such as `vitehub:schedule/schedule/srun_static_daily_2026-11-09T08:00:00.000Z`. The prefix is `runtime.prefix`, which defaults to `vitehub:schedule`. Use a different prefix for each app that shares a Database, and the same prefix on every server of one app. One server gets the lease and runs the occurrence while it holds that lease. The others skip it and try again at their next scan. Started Schedules use the same lease for each occurrence. Manual runs have their own run id, so the server that gets the request runs them once.
205
195
 
206
- When a custom host installs a wake driver, call and await `controller.close()` during shutdown. Closing stops new wakes, drains active wakes and `waitUntil()` work, and releases driver resources. It does not delete Schedule Definitions, Runtime Schedules, or run history. The generated Nitro Process Runtime registers the same close operation with ViteHub shutdown, so it runs on a stop signal before the server closes HTTP, or when Nitro closes. See [graceful shutdown](../runtime/README.md).
196
+ - The server that holds the lease renews it every third of `leaseTtlMs` while the run works. When the run ends, it writes a done marker (`<prefix>/schedule/<run id>/done`) and frees the lease. The marker lasts for `catchUpMs` plus `leaseTtlMs` plus two minutes, so a server that starts later does not run the occurrence again. If the marker write fails, the server reports the error and tries to extend its claim for the same time, without releasing it. If that also fails, another server can run the occurrence after the claim expires.
197
+ - If the server loses the Database, or its event loop pauses, for longer than `leaseTtlMs`, its lease can expire while its handler still runs. Another server can run the same occurrence at the same time. The runtime reports renewal failures, but cannot stop the handler or undo its effects. Choose a TTL longer than expected pauses and make external effects idempotent.
198
+ - If the lease store fails before a run starts, the server reports the error and retries at its next scan while the occurrence is inside `catchUpMs`.
199
+ - A failed run is final, as on one server. It is not retried.
200
+ - When a server stops during a run, for example after a crash, its lease ends after `leaseTtlMs`. Then another server runs the occurrence, unless it has a done marker. With shared run history, the run gets a new attempt, and the stopped attempt is marked as failed. This also works when every server restarts: at start, a server reads the runs inside `catchUpMs` that are still pending or running, and tries them again.
207
201
 
208
- ## Inspect Runtime Schedules
202
+ The generated runtime keeps the leases in the `vitehub_leases` table of the Default Database, through `useLeases()` from `@vite-hub/database`. That works on Postgres, remote libSQL, and D1. A local libSQL file is safe for one server process only, because `@libsql/client` can lose writes when several processes write to one file. The server prints a warning at the first lease in that case. Without a Database, the leases stay in memory and the build prints a warning: each server then runs every occurrence, so run one server only. The run history stays in KV. Use a KV store that all servers share, such as Upstash, so catch-up and the Console see the runs of every server.
209
203
 
210
- `hubSchedule()` contributes the `schedule.runs`, `schedule.attempts`, and `schedule.run` operations. They are the `vitehub schedule runs <id> [--limit <n>]`, `attempts <runId>`, and `run <name>` commands, and the Console runs them too. Each command accepts `--json` and `--url`. Without `--url` the command calls the dev server of the project, whose Nitro runtime owns the same stores and registry as the running app. The operations import from `@vite-hub/schedule/operations`.
204
+ With the Process Runtime, the default `providerOutput: "auto"` emits no host Provider Output, so the process owns Static Schedule wakes. Set `providerOutput: "standalone"` or `"nitro"` to move Static Schedule wakes to that Provider Output. `providerOutput: false` records the same wake ownership as `"auto"` in this configuration.
211
205
 
212
- Set `manual: true` on a Static Schedule Definition to allow an on-demand run, then invoke it with `vitehub schedule run <name>`. The name is the discovered schedule file name. Add `--url <app-url>` with the Console credentials to run it on a deployment that enables `console.invoke`. A CI job can post a signed dispatch (`vitehub secret derive vitehub:dispatch`) to `/_vitehub/schedules/run` instead.
206
+ A custom long-running host can call `installProcessScheduleRuntime({ registry, scheduleRunStore, leases, prefix })` from `@vite-hub/schedule/runtime/process`. Pass the same shared `LeaseStore` and prefix to every process of one app. `prefix` defaults to `vitehub:schedule`; use the same prefix for the app's Schedule stores. Without `leases`, it uses `createMemoryLeaseStore()`, which is for one process only. Call and await `controller.close()` during shutdown. It waits for active runs and their `waitUntil()` work, then stops the timer. It does not delete Schedule Definitions or run history. The generated Nitro Process Runtime registers the same close operation with ViteHub shutdown. See [graceful shutdown](../runtime/README.md).
213
207
 
214
- Discovery reads `manual` and `allowRuntimeSchedules` as literal booleans from directly exported Definitions. Use identifier keys or quoted keys without escape sequences. Spreads, computed keys, escaped keys, and metadata getters or methods fail with the source file and line.
208
+ ## Install an OS timer
215
209
 
216
- The Console Schedules section is a record table. Build-time records list Schedule Definitions. `readScheduleConsoleRecords()` from `@vite-hub/schedule/runtime/console` adds Runtime Schedules with enabled state, next run, last run, and run history on each request. The Console is read-only. A Runtime Schedule with `console: { enabled: false }` is hidden there. The CLI and the Console redact credentials in Schedule input and error messages.
210
+ A CLI or a desktop tool has no server that stays on. `@vite-hub/schedule/os` installs the cron of a Schedule as a systemd timer on Linux, a launchd job on macOS, or a Task Scheduler task on Windows. The operating system then starts your command at each time.
217
211
 
218
- ## Import runtime helpers
212
+ ```ts
213
+ // src/cli.ts
214
+ import { defineSchedule } from "@vite-hub/schedule";
215
+ import { installOsSchedule } from "@vite-hub/schedule/os";
219
216
 
220
- The main `@vite-hub/schedule` entry exports `defineSchedule`, `defineScheduleTarget`, `schedules`, `validateRuntimeScheduleCron`, and public types. Import execution, storage, and runtime state helpers from `@vite-hub/schedule/runtime`. Import `discoverScheduleDefinitions` from `@vite-hub/schedule/vite` when writing a build integration. Applications use `vite-hub/schedule` and `vite-hub/schedule/runtime`.
217
+ const photoSync = defineSchedule({
218
+ cron: "0 * * * *",
219
+ timeZone: "Europe/Madrid",
220
+ handler() {
221
+ console.log("Syncing photos");
222
+ },
223
+ });
221
224
 
222
- Static Schedule execution logs each failed handler as `[vitehub:schedule] Schedule "<name>" failed` with the message, stack, status, and cause chain. The other schedules on the same cron still finish. The run rejects with the error, or with an `AggregateError` when several failed.
225
+ const [error, unit] = await installOsSchedule("photo-sync", photoSync, {
226
+ command: [process.execPath, process.argv[1], "sync"],
227
+ });
228
+ if (error) throw error;
229
+ console.log(unit.changed ? unit.files : "The timer is up to date.");
230
+ ```
223
231
 
224
- Runtime execution helpers accept `captureHandlerFailure: true` to return the persisted failed run after a handler error. Pre-execution guards, including disabled schedules, still throw.
225
- Manual calls reject an existing disabled Runtime Schedule even when the same occurrence has a saved run. Provider wakes acknowledge saved occurrences after disablement without another handler attempt. A new provider occurrence still requires an enabled schedule.
232
+ `command[0]` must be an absolute path. An install with the same input changes nothing. `unit.status()` and `unit.uninstall()` read and remove the timer. A cron or time zone that the OS cannot run exactly returns a typed error, such as `SCHEDULE_OS_TIME_ZONE_UNSUPPORTED`. Read [OS timers](https://vitehub.dev/docs/schedule/os-timers) for scopes, logs, catch-up, and time zones.
226
233
 
227
- This is a breaking import change. Move existing execution, store, and state helper imports to `/runtime`, and discovery imports to `/vite`. Helper behavior is unchanged. The main entry no longer loads file discovery or its build dependencies.
234
+ ## Choose storage
228
235
 
229
- ## Documentation and support
236
+ Schedule Runs record manual runs and Process Runtime runs. Provider cron output runs the handler without a run record.
230
237
 
231
- - Read the [Schedule guide](https://vitehub.dev/docs/schedule) for every public import, Runtime Helper, store, wake driver, and Vite option.
232
- - Check [Provider Output](https://vitehub.dev/docs/reference/provider-output) for generated files and deployment inspection.
233
- - Check [runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix) for current proof and host qualifications.
234
- - Report package problems in the [ViteHub issue tracker](https://github.com/vite-hub/vitehub/issues).
238
+ The memory store is the default for direct calls. It is process-local and loses Schedule Run history on restart. Use `createKVScheduleRunStore({ kvStore })` when runs must survive a restart. The factory requires an explicit `ScheduleKVStorage`. To use ViteHub KV, install `@vite-hub/kv` and import the adapter explicitly:
235
239
 
236
- Cron parsing uses [`cron-schedule`](https://github.com/P4sca1/cron-schedule).
240
+ ```ts
241
+ import { createKVScheduleRunStore } from "@vite-hub/schedule/runtime"
242
+ import { scheduleKVStorage } from "@vite-hub/schedule/runtime/kv"
237
243
 
244
+ const scheduleRunStore = createKVScheduleRunStore({ kvStore: scheduleKVStorage })
245
+ ```
238
246
 
239
- ## Definition-owned target inputs
247
+ Generated Process Runtime wiring selects this adapter automatically. Applications using the framework can import it from `vite-hub/schedule/runtime/kv`. Use `setScheduleRunStore(store)` to install a custom `ScheduleRunStore`.
240
248
 
241
- The Vite Integration writes `.vitehub/schedule.d.ts`. Include it in your TypeScript project. The Nuxt Integration includes it automatically. The generated `ScheduleTargetRegistry` maps eligible names to their definitions. `schedules.create()` checks input against the selected target:
249
+ Custom stores must apply the `listRuns({ scheduleId, idPrefix, limit })` filters before the limit. The Process Runtime requests `idPrefix: "srun_static_"` with `limit: 1` to read its newest cron run without loading manual run history.
242
250
 
243
- ```ts
244
- const record = await schedules.create({
245
- target: "daily-report",
246
- cron: "0 9 * * *",
247
- input: { prompt: "Summarize yesterday" },
248
- })
249
- await schedules.update(record.id, {
250
- target: "daily-report",
251
- input: { prompt: "Summarize this week" },
252
- })
253
- await schedules.update(record.id, { enabled: false })
254
- ```
251
+ ## Run and inspect schedules
252
+
253
+ `hubSchedule()` contributes the `schedule.runs`, `schedule.attempts`, `schedule.run`, `schedule.list`, `schedule.start`, and `schedule.cancel` operations. They are the `vitehub schedule runs <id> [--limit <n>]`, `attempts <runId>`, `run <name>`, `list [name]`, `start <name>`, and `cancel <id>` commands, and the Console runs them too. Each command accepts `--json` and `--url`. Without `--url` the command calls the dev server of the project, whose Nitro runtime owns the same stores and registry as the running app.
254
+
255
+ Set `manual: true` on a Static Schedule Definition to allow an on-demand run, then invoke it with `vitehub schedule run <name>`. The name is the discovered schedule file name. Add `--url <app-url>` to run it on a deployment that enables `console.invoke`. The command signs the call with `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`, so a CI job needs only that secret. `vitehub secret console-key ci` prints a new key pair. Server code can call `runSchedule(name)` from `@vite-hub/schedule`. It reads the generated registry. Each manual run gets a new `srun_manual_` id.
256
+
257
+ Add `--at <ISO date-time>` to run it as if the cron fired at that time, for example `vitehub schedule run close-month --at 2026-01-31T23:59:00Z`. The handler gets the time as `scheduledAt`, and the run records it, so `vitehub schedule runs` lists it under that time. `runSchedule()` takes the same value as `scheduledAt`. The value needs `Z` or an offset. A value without a time zone, a date only, or a day that does not exist fails with `SCHEDULE_INVALID_SCHEDULED_AT` before the handler runs. The time is not checked against the cron. Manual runs do not advance the Process Runtime's catch-up cursor, even when their scheduled time is in the future.
255
258
 
256
- When an update changes `input`, also supply `target`. When an update changes `target`, supply the new input or `input: undefined` to clear it. An ID alone does not identify a definition type. Stored records can outlive a deployment, so `get()`, `list()`, and `update()` return unknown input. Handler input remains optional; targets must handle records with no input.
259
+ Discovery reads `manual` as a literal boolean from directly exported Definitions. Use identifier keys or quoted keys without escape sequences. Spreads, computed keys, escaped keys, and metadata getters or methods fail with the source file and line.
257
260
 
258
- Use `schedules.dynamic.create()` and `schedules.dynamic.update()` when names or stored input come from external data. The dynamic methods validate target eligibility and Schedule fields. They do not validate a target's business input. Validate that data in the application and again in a target that reads durable records.
261
+ The Console Schedules section lists Schedule Definitions with their cron, time zone, and manual state. It reads them at build time. When the server runs the Process Runtime, the cron and time zone come from the loaded Definitions on each request, so they are the values that the runtime uses. `vitehub inspect definitions` reads them from the source file and shows `Not a static string` for a value that it cannot read there. Use `vitehub schedule runs <name>` to list the runs that the runtime recorded. The CLI and the Console redact credentials in error messages.
259
262
 
260
- This is a breaking change: include the generated declarations for typed application calls, and move operational calls with unknown names to `schedules.dynamic`. There is no permissive string overload on typed creation.
263
+ ## Import runtime helpers
264
+
265
+ The main `@vite-hub/schedule` entry exports `defineSchedule`, `runSchedule`, `startSchedule`, `getSchedule`, `listSchedules`, `cancelSchedule`, and public types. Import execution, storage, and runtime state helpers from `@vite-hub/schedule/runtime`. Import `installProcessScheduleRuntime` from `@vite-hub/schedule/runtime/process`. Import `installOsSchedule`, `osScheduleStatus`, and `uninstallOsSchedule` from `@vite-hub/schedule/os`. Import `discoverScheduleDefinitions` from `@vite-hub/schedule/vite` when writing a build integration. Applications use `vite-hub/schedule` and `vite-hub/schedule/runtime`.
266
+
267
+ Static Schedule execution logs each failed handler as `[vitehub:schedule] Schedule "<name>" failed` with the message, stack, status, and cause chain. The other schedules on the same cron still finish. The run rejects with the error, or with an `AggregateError` when several failed.
268
+
269
+ `executeSchedule()` accepts `captureHandlerFailure: true` to return the persisted failed run after a handler error. Pre-execution guards still throw.
270
+
271
+ ## Documentation and support
272
+
273
+ - Read the [Schedule guide](https://vitehub.dev/docs/schedule) for every public import, Runtime Helper, store, and Vite option.
274
+ - Check [Provider Output](https://vitehub.dev/docs/reference/provider-output) for generated files and deployment inspection.
275
+ - Check [runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix) for current proof and host qualifications.
276
+ - Report package problems in the [ViteHub issue tracker](https://github.com/vite-hub/vitehub/issues).
277
+
278
+ Cron parsing uses [`cron-schedule`](https://github.com/P4sca1/cron-schedule).