@vite-hub/runtime 0.1.0 → 0.3.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 (44) hide show
  1. package/README.md +151 -117
  2. package/dist/durability.d.ts +107 -0
  3. package/dist/durability.js +168 -0
  4. package/dist/error-diagnostics-BKICpwZp.js +85 -0
  5. package/dist/error-diagnostics-BsJr9VdW.d.ts +15 -0
  6. package/dist/{errors-CbqHQTvn.js → errors-BEomN3fX.js} +1 -1
  7. package/dist/{execution-budget-D8SwJE8_.d.ts → execution-budget-BPXbISEt.d.ts} +9 -6
  8. package/dist/index-Bcl-Hr-a.d.ts +678 -0
  9. package/dist/index.d.ts +5 -4
  10. package/dist/index.js +5 -4
  11. package/dist/internal/drain.d.ts +17 -0
  12. package/dist/internal/drain.js +75 -0
  13. package/dist/internal/execution-budget.d.ts +1 -1
  14. package/dist/internal/grant.js +2 -2
  15. package/dist/internal/h3.d.ts +42 -0
  16. package/dist/internal/h3.js +181 -0
  17. package/dist/{node.d.ts → internal/node.d.ts} +2 -2
  18. package/dist/{node.js → internal/node.js} +4 -4
  19. package/dist/internal/public-url.d.ts +2 -0
  20. package/dist/internal/public-url.js +2 -0
  21. package/dist/internal/run-scope.d.ts +11 -0
  22. package/dist/internal/run-scope.js +30 -0
  23. package/dist/internal/runtime-type.d.ts +9 -2
  24. package/dist/internal/runtime-type.js +3 -2
  25. package/dist/{shutdown.d.ts → internal/shutdown.d.ts} +1 -1
  26. package/dist/{shutdown.js → internal/shutdown.js} +1 -1
  27. package/dist/internal/test-mode-setup.d.ts +7 -0
  28. package/dist/internal/test-mode-setup.js +114 -0
  29. package/dist/internal/test-mode.d.ts +32 -0
  30. package/dist/internal/test-mode.js +9 -0
  31. package/dist/operations.d.ts +167 -0
  32. package/dist/operations.js +406 -0
  33. package/dist/public-url-1WeOw54Z.d.ts +34 -0
  34. package/dist/public-url-B6x0HMgY.js +140 -0
  35. package/dist/{src-jy-gyPPu.js → request-context-CP9NhgLL.js} +635 -551
  36. package/dist/runtime-type-BftydMAf.js +88 -0
  37. package/package.json +61 -26
  38. package/dist/drain.d.ts +0 -1
  39. package/dist/drain.js +0 -69
  40. package/dist/error-diagnostics-Bkym4e6y.d.ts +0 -12
  41. package/dist/h3.d.ts +0 -49
  42. package/dist/h3.js +0 -404
  43. package/dist/index-Rl4DbP8B.d.ts +0 -574
  44. package/dist/runtime-type-CgfU6SWl.js +0 -52
package/README.md CHANGED
@@ -16,7 +16,7 @@ ViteHub packages and custom host integrations.
16
16
  | --------------------------------------------- | ------------------------- | --------------------------------------------------- |
17
17
  | A ViteHub application | `vite-hub` | `vite-hub/runtime` |
18
18
  | A reusable package or custom host integration | `@vite-hub/runtime` | `@vite-hub/runtime` |
19
- | Node diagnostics and process lifecycle | The same selected package | `vite-hub/runtime/node` or `@vite-hub/runtime/node` |
19
+ | Operations for the Console, the CLI, and MCP | The same selected package | `vite-hub/operations` or `@vite-hub/runtime/operations` |
20
20
 
21
21
  Use the `vite-hub` facade when it is already your application dependency. Install
22
22
  this owner package directly when the integration should depend only on Runtime's
@@ -29,9 +29,9 @@ or Agent Definitions.
29
29
  pnpm add @vite-hub/runtime
30
30
  ```
31
31
 
32
- The package declares Node.js 24 or newer. Import the root entry for portable
33
- Runtime contracts. When inspected, the `/node` entry reads Node process
34
- information and, on Linux, `/proc` and cgroup v2 files.
32
+ The package declares Node.js 22.18 or newer. Import the root entry for portable
33
+ Runtime contracts. The `/operations` entry exports `defineOperation()`, its types,
34
+ and the `vitehub: { operations }` contribution types of a Vite plugin.
35
35
 
36
36
  Trace payload inspection relies on the host's platform intrinsics. Load the
37
37
  Runtime before application code replaces platform methods. The Runtime captures
@@ -40,20 +40,20 @@ when that method is later replaced. It cannot recover the original intrinsic
40
40
  if the host replaces it before import; payload inspection is not an isolation
41
41
  boundary for code that can modify the host's JavaScript environment.
42
42
 
43
- Long-lived Node services can also use `createProcessReconciler()` from the `/node`
44
- entry to coalesce event-driven work, run periodic repair, stop admission, and await
43
+ ViteHub packages use the private `/internal/node` entry. `createProcessReconciler()`
44
+ lets a long-lived Node service coalesce event-driven work, run periodic repair, stop admission, and await
45
45
  tracked work during a graceful drain. Set `signal: "SIGUSR2"` when the service
46
- manager should trigger that drain through the `vitehub-drain` command included
47
- with the owner-package installation, `@vite-hub/runtime`. Lifecycle callbacks
46
+ manager should trigger that drain through `vitehub drain MAINPID [STATUS_URL]`
47
+ from the `vite-hub` package, for example in systemd `ExecStop`. Lifecycle callbacks
48
48
  must return before an external caller starts `drain()`; calling `drain()` from an
49
49
  active callback rejects to prevent that callback from waiting on itself. `close()`
50
50
  removes the configured signal listener after the drain settles, including a failed
51
51
  drain. Keep the
52
- status endpoint available until `vitehub-drain` observes the terminal `drained`
52
+ status endpoint available until `vitehub drain` observes the terminal `drained`
53
53
  status; process exit or endpoint loss before that acknowledgement is a failed drain.
54
54
 
55
55
  ViteHub packages register their stop work with `onShutdown(nitroApp, name, drain)`
56
- from the `/shutdown` entry, in a Nitro plugin. Applications do not call it. When a server
56
+ from the private `/internal/shutdown` entry, in a Nitro plugin. Applications do not call it. When a server
57
57
  that owns stop signals gets `SIGTERM` or `SIGINT`, ViteHub runs every registered drain
58
58
  in parallel and keeps HTTP open. Each drain gets the shared budget from
59
59
  `VITEHUB_SHUTDOWN_DRAIN_MS` (default 0) and an `AbortSignal` that aborts when the
@@ -94,94 +94,6 @@ Running the file prints:
94
94
  node:health
95
95
  ```
96
96
 
97
- ## Bounded runtime preflight
98
-
99
- Hosts that start an Agent can check commands, files, browsers, MCP servers, or
100
- tools before model execution without making those checks part of the critical
101
- path. `startRuntimePreflight()` runs a bounded set of checks in parallel and
102
- returns a promise for a compact, serializable manifest. A failed or missing
103
- optional capability becomes data and a Nostics diagnostic; it never rejects the
104
- manifest or the invocation. The diagnostic callback is best effort and does not
105
- delay the checks.
106
-
107
- ```ts
108
- import { startRuntimePreflight } from "@vite-hub/runtime"
109
-
110
- const preflight = startRuntimePreflight({
111
- checks: [
112
- { id: "command:git", kind: "command", required: true, check: ({ signal }) => runWhich("git", signal) },
113
- { id: "file:AGENTS.md", kind: "file", check: ({ signal }) => readFile("AGENTS.md", signal) },
114
- ],
115
- onDiagnostic: issue => reportDiagnostic(issue.diagnostic),
116
- })
117
-
118
- // The host may expose this to inspection or model instructions when ready.
119
- const manifest = await preflight.manifest
120
- ```
121
-
122
- Keep `details` on a check result small and redacted. The framework limits each
123
- reason and details object, caps the check count, and bounds asynchronous waiting
124
- time. Check IDs are limited to 128 characters and kinds to 64 characters.
125
- Results must be plain data records without proxies or accessors; only the first
126
- 12 detail properties are inspected, with 64-character keys and 256-character
127
- string values. More checks than `maxChecks` rejects the configuration before
128
- any run.
129
-
130
- Checks run on the host event loop. Use non-blocking asynchronous APIs for
131
- external processes, filesystem work, and network requests, and honor the
132
- provided `AbortSignal`. ViteHub cannot interrupt a synchronous callback; when
133
- one runs past its budget, the result is reported as `unknown` after that
134
- callback returns. A timed-out asynchronous operation may still need to cancel
135
- its own underlying work when it observes the signal.
136
-
137
- `createRuntimeContext()` gives each operation a fresh memo cache and tracks work
138
- registered with `waitUntil()`. Pass the host's `waitUntil` method to forward that
139
- work to a real provider lifetime. Without one, await `flushWaitUntil()` before
140
- returning. A flush drains nested work and then reports the first observed failure.
141
- Concurrent flush calls wait for the same work and report the same result.
142
- The constructor does not extend serverless lifetime or cancel background tasks.
143
-
144
- Call `flushWaitUntil()` from the code that owns the operation. A task registered
145
- with `waitUntil()` must not await that context's flush. The flush waits for the
146
- task, so both would wait indefinitely. Await child promises directly inside a
147
- task. If the task needs its own background-work controller, create a separate
148
- Runtime Context and flush that context instead.
149
-
150
- For H3 1, H3 2, and Nuxt routes, use `getRuntimeContext(event, options?)` from
151
- `@vite-hub/runtime/h3` or `vite-hub/runtime/h3`. This framework entry normalizes
152
- event bindings and lifetime methods. It reads the event by shape, so the Runtime
153
- owner package has no H3 dependency.
154
-
155
- `createExecutionContext()` always returns a complete Execution Context. It creates
156
- fresh empty `capabilities` and `runtimeConfig` objects when the host omits them,
157
- and preserves the supplied objects when the host provides them.
158
-
159
- ### Invocation execution budgets
160
-
161
- `createExecutionBudget()` gives one Invocation a shared deadline, cancellation
162
- signal, and counters for tool calls, input bytes, output bytes, and retries.
163
- `child()` adds stricter limits while sharing usage with its parent. The budget
164
- returns a serializable `snapshot()` for inspection and throws
165
- `ExecutionBudgetExceededError` before a counter can exceed its limit.
166
- Call `dispose()` when code owns a budget outside an Agent Invocation. It is
167
- idempotent and releases deadline timers and cancellation listeners for the
168
- budget and all children. The Agent runtime disposes its Invocation budget after
169
- the result finishes, including streamed results, and on setup or finish errors.
170
- Children created after disposal are inert and do not acquire new timers or
171
- listeners.
172
-
173
- Agent input accepts `executionBudget` limits. The Agent runtime creates one
174
- Invocation-owned budget and Workspace Shell tools spend it, so separate tool
175
- calls cannot bypass the same limit. AI SDK model requests spend serialized prompt
176
- bytes on each attempt, and responses spend serialized content bytes (or content
177
- deltas while streaming). Provider retries and repair generations share the retry
178
- counter. `cancel(reason)` aborts the budget signal and clears its deadline timer.
179
- The AI SDK adapter also charges model usage when the provider reports token
180
- counts. It estimates four UTF-8 bytes per input or output token because model
181
- providers do not expose a portable byte count. Missing token counts remain
182
- unknown and do not spend a byte budget. Each reported model call is charged
183
- once, including calls made while streaming or repairing output.
184
-
185
97
  ## Understand the boundaries
186
98
 
187
99
  ### Runtime Host Context
@@ -197,6 +109,33 @@ does not clone, redact, encrypt, or restrict `request`, `event`, `cloudflare.env
197
109
  `runtimeConfig`, or Runtime Capability values. Pass only the bindings and secrets
198
110
  needed by that operation, and do not copy secrets into traces or approval input.
199
111
 
112
+ ### Host bindings
113
+
114
+ `getHostBinding(name, event?)` reads one raw binding of a Cloudflare Worker, such
115
+ as an R2 bucket or a `send_email` binding, for host features that no ViteHub
116
+ primitive covers. It reads the bindings of the request event, else the bindings
117
+ that Nitro or ViteHub installed for the current request, Schedule, Queue
118
+ message, or Workflow step. It returns `[error, binding]`:
119
+
120
+ - `RUNTIME_HOST_BINDINGS_UNAVAILABLE` when the code runs without host bindings,
121
+ for example on Node.
122
+ - `RUNTIME_HOST_BINDING_NOT_FOUND` when the Worker has no binding with that name.
123
+
124
+ Run `wrangler types` to type the binding from `Cloudflare.Env`. Without it, the
125
+ binding is `unknown`.
126
+
127
+ ```ts fragment
128
+ import { getHostBinding } from "vite-hub/runtime"
129
+
130
+ const [error, email] = getHostBinding("REVIEW_EMAIL", event)
131
+ if (error) throw new HTTPError({ status: 503, message: error.why })
132
+ await email.send(message)
133
+ ```
134
+
135
+ `detectHost()` returns the host that `vitehub()` builds for when `host` is
136
+ omitted, or `"cloudflare"` inside a Worker. It returns `undefined` when nothing
137
+ names a host.
138
+
200
139
  ### Runtime Capabilities
201
140
 
202
141
  `defineCapability()` and `getCapability()` pass a named implementation between
@@ -252,6 +191,8 @@ that inspect the Error instance.
252
191
  ViteHub packages use `defineGrant()` from the internal `@vite-hub/runtime/internal/grant` entry. It is not a public API. A grant connects a check to the sensitive action that it guards: the check issues a frozen grant, and the action requires the grant and verifies it at runtime.
253
192
 
254
193
  ```ts
194
+ import { defineGrant } from "@vite-hub/runtime/internal/grant"
195
+
255
196
  const sourceWrite = defineGrant("vitehub.workspace.source-write", (path: string) => path)
256
197
 
257
198
  export function checkSourceWrite(path: string) {
@@ -298,8 +239,11 @@ async function list(limit: number): Promise<Result<string[], "KV_INVALID_LIMIT">
298
239
 
299
240
  const [error, keys] = await list(0)
300
241
  if (error) error.code // "KV_INVALID_LIMIT"
242
+ if (errors.KV_INVALID_LIMIT.is(error)) error.data // data of KV_INVALID_LIMIT
301
243
  ```
302
244
 
245
+ Check an error with the catalog. `errors.is(error)` accepts any code of the catalog, and `errors.KV_INVALID_LIMIT.is(error)` accepts one code. Both narrow `code` and `data`. They read `code` from a live Nostics error, so they also accept an error from another bundled copy or realm. `is` is not enumerable, so `Object.keys(errors)` gives only the codes, and no code can be named `is`. `InferDiagnosticCodes<typeof errors>` from `nostics` is the union of the codes.
246
+
303
247
  A `ResultError` is a Nostics diagnostic with `code`, `why`, `fix`, `docs`, and `cause`. Catalog definitions can also provide static or computed `data`. `defineErrors()` infers that data for each code; `ResultError<Code, Data>` can name its type explicitly. A bare `ResultError` or `ResultError<Code>` keeps data as `unknown` so it can accept any catalog error. Codes without data infer `undefined`.
304
248
 
305
249
  Its `toJSON()` returns only `name`, `code`, `why`, `fix`, and `docs`. The code and name keep their literal types. For compatibility with Nostics consumers such as `formatDiagnostic()`, its return type retains Nostics serializer fields, including required `data`; those metadata fields are not present at runtime. Read metadata from the error itself. Cause, stack, sources, and diagnostic data stay in memory and are absent from public JSON.
@@ -309,6 +253,36 @@ same object when its `name` and `toJSON` properties can be replaced. Otherwise i
309
253
  creates a new diagnostic with the same code, text, cause, data, sources, and stack,
310
254
  and leaves the original unchanged. The caller owns code allowlisting and public text.
311
255
 
256
+ ### Durability
257
+
258
+ Each primitive reports where it keeps its state for the driver that it uses:
259
+
260
+ ```ts fragment
261
+ interface Durability {
262
+ primitive: string
263
+ name?: string
264
+ store: string
265
+ scope: 'shared' | 'host' | 'process'
266
+ reason: string
267
+ fix?: string
268
+ }
269
+ ```
270
+
271
+ A primitive's Vite plugin contributes a reporter through `vitehub.durability`:
272
+ the primitive id, a module, an export, and the resolved configuration as JSON.
273
+ A Node server built with ViteHub calls each reporter at boot as
274
+ `reporter(input, context)`. `context.env` is `process.env`, so a driver that an
275
+ environment variable selects at boot, such as `REDIS_URL`, reports correctly.
276
+ `context.find(primitive, name)` returns the report of another primitive, such
277
+ as the Database that a KV store or the Queue keeps its rows in.
278
+ `classifySqliteUrl()` tells a local SQLite file from a remote libSQL server.
279
+
280
+ The server then calls `checkDurability()`. It prints one line per primitive,
281
+ records the report for `getDurabilityReport()` and `vitehub durability list`,
282
+ and throws `RUNTIME_R0017` when `VITEHUB_INSTANCES` (or `node.instances`) is
283
+ greater than 1 and a primitive is `host` or `process` scoped. A new driver
284
+ reports itself in its owner package's `durability.ts`.
285
+
312
286
  ### Developer diagnostics
313
287
 
314
288
  Runtime-owned API and contract defects use Nostics diagnostics with stable `RUNTIME_R####` codes. Packages that do not follow the error contract yet keep the `ViteHubError` public contract for expected portable failures. See [Errors and diagnostics](https://vitehub.dev/docs/reference/errors-diagnostics).
@@ -329,13 +303,89 @@ Use `isRuntimeDiagnostic(error)` to recognize a live Nostics error from another
329
303
  These helpers produce developer diagnostics. They do not make arbitrary errors
330
304
  safe for public responses. Use the `ViteHubError` public contract at that boundary.
331
305
 
306
+ ### Leases
307
+
308
+ A lease gives one caller at a time a key, such as one Schedule occurrence or one leader. It ends at `release()` or when its TTL passes, so a holder that crashes blocks the key only until then.
309
+
310
+ | Store | Use it for | Atomic across |
311
+ | --- | --- | --- |
312
+ | `createMemoryLeaseStore()` | One process and tests | One process |
313
+ | `createSqlLeaseStore(client)` | Several instances on one Database | Every process on the Database |
314
+
315
+ In a ViteHub app, `useLeases()` from `@vite-hub/database` returns a SQL store on the app's Database, on every driver including D1. Use `createSqlLeaseStore()` for a SQL client outside ViteHub Database.
316
+
317
+ ```ts fragment
318
+ import { createSqlLeaseStore } from '@vite-hub/runtime'
319
+ import postgres from 'postgres'
320
+
321
+ const sql = postgres(process.env.DATABASE_URL!)
322
+ const leases = createSqlLeaseStore({
323
+ dialect: 'postgresql',
324
+ query: async (text, params) => await sql.unsafe(text, params),
325
+ })
326
+
327
+ const [error, lease] = await leases.acquire('report:2026-11-09', { ttl: 60, owner: 'instance-a' })
328
+ if (error) throw error
329
+ // `lease` is null when another instance holds the key.
330
+ if (lease) {
331
+ try {
332
+ await sendReport()
333
+ }
334
+ finally {
335
+ await lease.release()
336
+ }
337
+ }
338
+ ```
339
+
340
+ On libSQL, pass `{ dialect: 'sqlite', query: async (sql, args) => (await client.execute({ sql, args })).rows }`. On `node:sqlite`, pass `{ dialect: 'sqlite', query: async (sql, params) => db.prepare(sql).all(...params) }`. A local libSQL `file:` client is for one process only. See the note on SQLite below.
341
+
342
+ - `acquire(key, { ttl, owner? })` returns `[error, lease]`. `lease` is `null` when another caller holds the key. `ttl` is in seconds, like KV. Fractions are allowed. Leases are not reentrant: the same `owner` also gets `null`.
343
+ - Each acquire gets a new random `id`. `lease.release()` and `lease.renew({ ttl? })` act only when the stored `id` is still this one. They return `false` when the lease expired and another caller took it. `renew()` updates `lease.expiresAt`.
344
+ - `get(key)` returns the live lease with its `owner` and `expiresAt`, or `null`. Use it to inspect who holds a key.
345
+ - `owner` is a label for inspection. Acquire does not compare it.
346
+ - Errors: `RUNTIME_LEASE_INVALID_TTL` when `ttl` is not a positive number, and `RUNTIME_LEASE_FAILED` when the store fails. Read `error.cause` for the Database error.
347
+
348
+ The SQL store keeps leases in the `vitehub_leases` table and creates it when it is missing. Each operation is one statement. Acquire is one `INSERT ... ON CONFLICT ("key") DO UPDATE ... WHERE expires_at <= now RETURNING`, so of many processes that acquire one key at the same time, exactly one gets it. Expiry uses the clock of the Database, not the clocks of the hosts. Postgres and SQLite 3.35 or later work. The store deletes expired rows at most once a minute.
349
+
350
+ There is no KV lease store yet. A KV lease store needs atomic compare-and-delete for `release()` and atomic compare-and-set with a TTL for `renew()` on every KV driver it supports, so it can check the holder in the same step. These are follow-ups. The `fs-lite` driver also ignores the TTL, so a lease on it would never expire.
351
+
352
+ On SQLite, a statement that fails with `SQLITE_BUSY` because another process holds the lock runs again for up to 5 seconds, without blocking the event loop. Contention gives a `null` lease, not `RUNTIME_LEASE_FAILED`.
353
+
354
+ When several processes share leases, use Postgres, remote libSQL, or `node:sqlite` on one file. Do not use a local libSQL `file:` client in more than one process. After `SQLITE_BUSY`, `@libsql/client` 0.18 keeps the transaction of the failed statement open, and it can lose writes that it reported as done. A busy `timeout` makes this less frequent but does not stop it under load.
355
+
356
+ #### Provision the SQL table
357
+
358
+ On PostgreSQL, automatic table creation needs `CREATE` privilege on the schema. If migrations use a separate role, create the table and index before the application uses the store. An accessible existing table skips DDL, so the application role does not need `CREATE`.
359
+
360
+ These statements work on both PostgreSQL and SQLite 3.35 or later:
361
+
362
+ ```sql
363
+ CREATE TABLE IF NOT EXISTS vitehub_leases (
364
+ "key" text PRIMARY KEY,
365
+ id text NOT NULL,
366
+ owner text,
367
+ expires_at bigint NOT NULL
368
+ );
369
+ CREATE INDEX IF NOT EXISTS vitehub_leases_expires_at
370
+ ON vitehub_leases (expires_at);
371
+ ```
372
+
373
+ `expires_at` stores milliseconds since the Unix epoch. Create the table in the schema that the application connection resolves. On PostgreSQL, the application role needs `USAGE` on that schema and `SELECT`, `INSERT`, `UPDATE`, and `DELETE` on the table. For example, for the `public` schema and an application role named `lease_app`, run this as the migration role:
374
+
375
+ ```sql
376
+ GRANT USAGE ON SCHEMA public TO lease_app;
377
+ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE public.vitehub_leases TO lease_app;
378
+ ```
379
+
332
380
  ## Public entry points
333
381
 
334
382
  | Import | Provides |
335
383
  | ------------------------ | ---------------------------------------------------------------------------------------------------- |
336
- | `@vite-hub/runtime` | Context, capability, policy, approval, trace, lease, diagnostic, error, execution-authority, and public URL APIs |
337
- | `@vite-hub/runtime/node` | Node process observations, reconciliation, and graceful-drain lifecycle primitives |
338
- | `@vite-hub/runtime/shutdown` | Shared host shutdown: drain registration, stop signal handling, and shutdown state |
384
+ | `@vite-hub/runtime` | Context, capability, policy, approval, trace, lease, diagnostic, error, execution-authority, public URL, and host binding APIs |
385
+ | `@vite-hub/runtime/operations` | `defineOperation()`, operation and plugin contribution types |
386
+ | `@vite-hub/runtime/durability` | The `Durability` contract that each primitive reports, the boot table, and the instance check |
387
+ | `@vite-hub/runtime/internal/node` | Node process observations, reconciliation, and graceful-drain lifecycle primitives |
388
+ | `@vite-hub/runtime/internal/shutdown` | Shared host shutdown: drain registration, stop signal handling, and shutdown state |
339
389
 
340
390
  Do not import from `src`, `dist`, or ViteHub's `_internal` paths.
341
391
 
@@ -347,19 +397,3 @@ Do not import from `src`, `dist`, or ViteHub's `_internal` paths.
347
397
  - [Stable import paths](https://vitehub.dev/docs/reference/import-paths)
348
398
  - [Node Runtime diagnostics](https://vitehub.dev/docs/agents/capabilities/diagnostics)
349
399
  - [Report a Runtime issue](https://github.com/vite-hub/vitehub/issues/new)
350
-
351
- ### Work checkpoints
352
-
353
- `createWorkTracker({ store })` owns single-process work deduplication and durable park/retry checkpoints. The store exposes asynchronous `get(key)` and `set(key, checkpoint)` operations. The application supplies a meaningful state fingerprint and decides whether a completed run should park or retry.
354
-
355
- ```ts
356
- import { createWorkTracker } from '@vite-hub/runtime'
357
-
358
- const work = createWorkTracker({ store, retryMs: 60_000, maxRetryMs: 3_600_000 })
359
- await work.run(key, observedFingerprint, async () => {
360
- await repair()
361
- return { disposition: 'park', fingerprint: repairedFingerprint }
362
- })
363
- ```
364
-
365
- Unchanged parked work is skipped. Retries use bounded exponential backoff, including thrown errors. A changed fingerprint bypasses cooldown. Failed checkpoint writes retain a local cooldown and propagate the persistence failure; they do not claim durability. Active keys are exclusive within one tracker. Use an external lease for multiple hosts sharing work. `eligible(key, fingerprint)` supports discovery filtering, while `run` rechecks eligibility after acquiring local ownership.
@@ -0,0 +1,107 @@
1
+ //#region src/durability.d.ts
2
+ /**
3
+ * Where the state of a primitive lives.
4
+ *
5
+ * - `shared`: every server instance reads and writes the same store, such as Postgres, Redis, or S3.
6
+ * - `host`: the state is in files on this host. It survives a restart, but another host or container does not see it.
7
+ * - `process`: the state is in the memory of this process. A restart loses it and other processes do not see it.
8
+ */
9
+ export type DurabilityScope = "host" | "process" | "shared";
10
+ /** What one primitive reports about the store that it uses in this server. */
11
+ export interface Durability {
12
+ /** The primitive, such as `kv`, `queue`, or `database`. */
13
+ primitive: string;
14
+ /** The named store or Database, when the primitive has more than one. Omitted for the default. */
15
+ name?: string;
16
+ /** The driver or engine that holds the state, such as `fs-lite`, `memory`, or `postgres`. */
17
+ store: string;
18
+ scope: DurabilityScope;
19
+ /** One sentence that tells where the state is. */
20
+ reason: string;
21
+ /** How to make the state shared. Set it when `scope` is not `shared`. */
22
+ fix?: string;
23
+ }
24
+ /** What a reporter reads at boot besides the configuration of its own primitive. */
25
+ export interface DurabilityContext {
26
+ /** The server environment. A driver that an environment variable selects at boot reads it here. */
27
+ env: Record<string, string | undefined>;
28
+ /**
29
+ * The report of another primitive in this server, such as the Database that a KV store keeps its rows in. `name`
30
+ * defaults to the default store. `undefined` when that primitive is off.
31
+ */
32
+ find: (primitive: string, name?: string) => Durability | undefined;
33
+ }
34
+ /**
35
+ * A primitive's durability reporter. The build passes the resolved configuration of the primitive as `input`. The
36
+ * server passes a context with its environment and the other reports, so a driver that the environment or the Default
37
+ * Database selects at boot reports correctly.
38
+ */
39
+ export type DurabilityReporter<Input> = (input: Input, context: DurabilityContext) => readonly Durability[];
40
+ /** One primitive's reporter, with its configuration already applied. */
41
+ export interface DurabilityEntry {
42
+ primitive: string;
43
+ report: (context: DurabilityContext) => readonly Durability[];
44
+ }
45
+ /**
46
+ * Runs every reporter once, in order. A reporter that calls `context.find()` runs the reporter of that primitive first,
47
+ * so the order of the entries does not matter.
48
+ */
49
+ export declare function collectDurability(entries: readonly DurabilityEntry[], env: Record<string, string | undefined>): Durability[];
50
+ /**
51
+ * Where a SQLite or libSQL URL keeps its data: `:memory:` in this process, `libsql:`, `http(s):`, or `ws(s):` on a
52
+ * remote server, and anything else, such as `file:`, on this host.
53
+ */
54
+ export declare function classifySqliteUrl(url: string): Pick<Durability, "reason" | "scope" | "store">;
55
+ /**
56
+ * Hides a remote URL before the build writes it into the server: a `file:` or `:memory:` URL stays, and any other URL
57
+ * becomes `remote`, which `classifySqliteUrl()` reads as a remote server.
58
+ */
59
+ export declare function sqliteUrlInput(url: string): string;
60
+ /** A configuration value that can name runtime environment variables, as the Database and Workflow options do. */
61
+ export type DurabilityConfigValue = string | {
62
+ default?: unknown;
63
+ source?: {
64
+ name?: string;
65
+ names?: readonly string[];
66
+ };
67
+ };
68
+ /** Reads a configuration value the same way the runtime does: the first set environment variable, then the default. */
69
+ export declare function resolveDurabilityValue(value: DurabilityConfigValue | undefined, env: Record<string, string | undefined>): string | undefined;
70
+ /** The durability of the running server, as `vitehub durability list` shows it. */
71
+ export interface DurabilityReport {
72
+ instances: number;
73
+ /** Where the instance count comes from. */
74
+ instancesSource: "default" | "env" | "option";
75
+ primitives: readonly Durability[];
76
+ /** The primitives that split their state when `instances` is greater than 1. */
77
+ problems: readonly Durability[];
78
+ }
79
+ export interface DurabilityCheckOptions {
80
+ /** `node.instances` from the ViteHub config. `VITEHUB_INSTANCES` in `env` overrides it. */
81
+ instances?: number;
82
+ env?: Record<string, string | undefined>;
83
+ /** Fail when several instances would split state. The dev server only records the report. */
84
+ enforce?: boolean;
85
+ /** Write the boot table. Defaults to `console.info`. Pass `false` to skip it. */
86
+ log?: ((message: string) => void) | false;
87
+ }
88
+ export declare const instancesEnvName = "VITEHUB_INSTANCES";
89
+ /**
90
+ * The number of server instances that run this build. `VITEHUB_INSTANCES` wins over `node.instances`, because a
91
+ * deployment often decides the count after the build. The default is 1.
92
+ */
93
+ export declare function readInstanceCount(env?: Record<string, string | undefined>, configured?: number): Pick<DurabilityReport, "instances" | "instancesSource">;
94
+ /** One line per primitive: name, store, scope, and reason, in aligned columns. */
95
+ export declare function formatDurabilityTable(primitives: readonly Durability[]): string;
96
+ /** The primitives that would split their state across `instances` server instances. */
97
+ export declare function durabilityProblems(primitives: readonly Durability[], instances: number): Durability[];
98
+ /** Builds the error that a server with several instances and a `host` or `process` store fails with. */
99
+ export declare function durabilityError(report: Pick<DurabilityReport, "instances" | "problems">): Error;
100
+ /** The report that the server recorded at boot, or `undefined` before the boot check runs or outside a Node server. */
101
+ export declare function getDurabilityReport(): DurabilityReport | undefined;
102
+ /**
103
+ * Records the durability of each primitive, prints one line per primitive, and fails when several instances would
104
+ * split state. A Node server runs it once at boot, from a Nitro plugin that ViteHub generates.
105
+ */
106
+ export declare function checkDurability(primitives: readonly Durability[], options?: DurabilityCheckOptions): DurabilityReport;
107
+ //#endregion
@@ -0,0 +1,168 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region src/durability.ts
3
+ /**
4
+ * Runs every reporter once, in order. A reporter that calls `context.find()` runs the reporter of that primitive first,
5
+ * so the order of the entries does not matter.
6
+ */
7
+ function collectDurability(entries, env) {
8
+ const results = /* @__PURE__ */ new Map();
9
+ const running = /* @__PURE__ */ new Set();
10
+ const run = (entry) => {
11
+ const done = results.get(entry);
12
+ if (done) return done;
13
+ if (running.has(entry)) return [];
14
+ running.add(entry);
15
+ const reports = entry.report(context);
16
+ running.delete(entry);
17
+ results.set(entry, reports);
18
+ return reports;
19
+ };
20
+ const context = {
21
+ env,
22
+ find: (primitive, name = "default") => entries.filter((entry) => entry.primitive === primitive).flatMap(run).find((report) => (report.name ?? "default") === name)
23
+ };
24
+ return entries.flatMap((entry) => [...run(entry)]);
25
+ }
26
+ /**
27
+ * Where a SQLite or libSQL URL keeps its data: `:memory:` in this process, `libsql:`, `http(s):`, or `ws(s):` on a
28
+ * remote server, and anything else, such as `file:`, on this host.
29
+ */
30
+ function classifySqliteUrl(url) {
31
+ if (url === ":memory:" || url === "file::memory:") return {
32
+ store: "sqlite",
33
+ scope: "process",
34
+ reason: "SQLite in the memory of this process."
35
+ };
36
+ if (url === "remote" || /^(?:libsql|https?|wss?):/i.test(url)) return {
37
+ store: "libsql",
38
+ scope: "shared",
39
+ reason: "A remote libSQL server."
40
+ };
41
+ return {
42
+ store: "sqlite",
43
+ scope: "host",
44
+ reason: `The SQLite file ${url.replace(/^file:(?:\/\/)?/i, "")} on this host.`
45
+ };
46
+ }
47
+ /**
48
+ * Hides a remote URL before the build writes it into the server: a `file:` or `:memory:` URL stays, and any other URL
49
+ * becomes `remote`, which `classifySqliteUrl()` reads as a remote server.
50
+ */
51
+ function sqliteUrlInput(url) {
52
+ return /^file:/i.test(url) || url === ":memory:" ? url : "remote";
53
+ }
54
+ /** Reads a configuration value the same way the runtime does: the first set environment variable, then the default. */
55
+ function resolveDurabilityValue(value, env) {
56
+ if (typeof value !== "object") return value?.trim() || void 0;
57
+ for (const name of value.source?.names ?? (value.source?.name ? [value.source.name] : [])) {
58
+ const resolved = env[name]?.trim();
59
+ if (resolved) return resolved;
60
+ }
61
+ return typeof value.default === "string" ? value.default.trim() || void 0 : void 0;
62
+ }
63
+ const instancesEnvName = "VITEHUB_INSTANCES";
64
+ const durabilityDiagnostics = defineDiagnostics({
65
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
66
+ codes: {
67
+ RUNTIME_R0017: {
68
+ why: ({ instances, lines }) => [`[vitehub] ${instancesEnvName} is ${instances}, but these primitives keep their state in one process or on one host. Each instance would see different data:`, ...lines].join("\n"),
69
+ fix: `Move each listed primitive to a shared store, or set ${instancesEnvName}=1 and run one instance.`,
70
+ data: (params) => params
71
+ },
72
+ RUNTIME_R0018: {
73
+ why: ({ source, value }) => `${source} must be a positive integer. It is ${JSON.stringify(value)}.`,
74
+ fix: `Set ${instancesEnvName} or \`node.instances\` to the number of server instances that share this deployment, such as 1 or 3.`,
75
+ data: (params) => params
76
+ }
77
+ }
78
+ });
79
+ /**
80
+ * The number of server instances that run this build. `VITEHUB_INSTANCES` wins over `node.instances`, because a
81
+ * deployment often decides the count after the build. The default is 1.
82
+ */
83
+ function readInstanceCount(env = process.env, configured) {
84
+ const value = env[instancesEnvName]?.trim();
85
+ if (value) {
86
+ if (!/^\d+$/.test(value) || Number(value) < 1) throw durabilityDiagnostics.RUNTIME_R0018({
87
+ source: instancesEnvName,
88
+ value
89
+ });
90
+ return {
91
+ instances: Number(value),
92
+ instancesSource: "env"
93
+ };
94
+ }
95
+ if (configured === void 0) return {
96
+ instances: 1,
97
+ instancesSource: "default"
98
+ };
99
+ if (!Number.isInteger(configured) || configured < 1) throw durabilityDiagnostics.RUNTIME_R0018({
100
+ source: "node.instances",
101
+ value: String(configured)
102
+ });
103
+ return {
104
+ instances: configured,
105
+ instancesSource: "option"
106
+ };
107
+ }
108
+ function label(durability) {
109
+ return durability.name ? `${durability.primitive} (${durability.name})` : durability.primitive;
110
+ }
111
+ /** One line per primitive: name, store, scope, and reason, in aligned columns. */
112
+ function formatDurabilityTable(primitives) {
113
+ const rows = primitives.map((durability) => [
114
+ label(durability),
115
+ durability.store,
116
+ durability.scope,
117
+ durability.reason
118
+ ]);
119
+ const widths = [
120
+ 0,
121
+ 1,
122
+ 2
123
+ ].map((column) => Math.max(...rows.map((row) => row[column].length)));
124
+ return rows.map((row) => ` ${row.map((cell, column) => column < 3 ? cell.padEnd(widths[column]) : cell).join(" ")}`).join("\n");
125
+ }
126
+ function instancesLabel(report) {
127
+ const count = `${report.instances} instance${report.instances === 1 ? "" : "s"}`;
128
+ if (report.instancesSource === "env") return `${count}, from ${instancesEnvName}`;
129
+ if (report.instancesSource === "option") return `${count}, from node.instances`;
130
+ return `${count}. Set ${instancesEnvName} when you run more`;
131
+ }
132
+ /** The primitives that would split their state across `instances` server instances. */
133
+ function durabilityProblems(primitives, instances) {
134
+ return instances > 1 ? primitives.filter((durability) => durability.scope !== "shared") : [];
135
+ }
136
+ /** Builds the error that a server with several instances and a `host` or `process` store fails with. */
137
+ function durabilityError(report) {
138
+ return durabilityDiagnostics.RUNTIME_R0017({
139
+ instances: report.instances,
140
+ lines: report.problems.map((durability) => ` - ${label(durability)}: ${durability.store} (${durability.scope}). ${durability.reason}${durability.fix ? ` Fix: ${durability.fix}` : ""}`),
141
+ primitives: report.problems.map(label)
142
+ });
143
+ }
144
+ const reportKey = Symbol.for("vitehub.durability.report");
145
+ const scope = globalThis;
146
+ /** The report that the server recorded at boot, or `undefined` before the boot check runs or outside a Node server. */
147
+ function getDurabilityReport() {
148
+ return scope[reportKey];
149
+ }
150
+ /**
151
+ * Records the durability of each primitive, prints one line per primitive, and fails when several instances would
152
+ * split state. A Node server runs it once at boot, from a Nitro plugin that ViteHub generates.
153
+ */
154
+ function checkDurability(primitives, options = {}) {
155
+ const count = readInstanceCount(options.env ?? process.env, options.instances);
156
+ const report = {
157
+ ...count,
158
+ primitives: [...primitives],
159
+ problems: durabilityProblems(primitives, count.instances)
160
+ };
161
+ scope[reportKey] = report;
162
+ const log = options.log === void 0 ? (message) => console.info(message) : options.log;
163
+ if (log && primitives.length) log(`[vitehub] Durability (${instancesLabel(report)}):\n${formatDurabilityTable(primitives)}`);
164
+ if (options.enforce !== false && report.problems.length) throw durabilityError(report);
165
+ return report;
166
+ }
167
+ //#endregion
168
+ export { checkDurability, classifySqliteUrl, collectDurability, durabilityError, durabilityProblems, formatDurabilityTable, getDurabilityReport, instancesEnvName, readInstanceCount, resolveDurabilityValue, sqliteUrlInput };