@vite-hub/runtime 0.0.4 → 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 +278 -41
  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-BEomN3fX.js +190 -0
  7. package/dist/execution-budget-BPXbISEt.d.ts +56 -0
  8. package/dist/index-Bcl-Hr-a.d.ts +678 -0
  9. package/dist/index.d.ts +5 -2
  10. package/dist/index.js +5 -1159
  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 +10 -0
  14. package/dist/internal/execution-budget.js +17 -0
  15. package/dist/internal/grant.d.ts +36 -0
  16. package/dist/internal/grant.js +44 -0
  17. package/dist/internal/h3.d.ts +42 -0
  18. package/dist/internal/h3.js +181 -0
  19. package/dist/internal/node.d.ts +33 -0
  20. package/dist/{node.js → internal/node.js} +12 -9
  21. package/dist/internal/public-url.d.ts +2 -0
  22. package/dist/internal/public-url.js +2 -0
  23. package/dist/internal/run-scope.d.ts +11 -0
  24. package/dist/internal/run-scope.js +30 -0
  25. package/dist/internal/runtime-type.d.ts +26 -0
  26. package/dist/internal/runtime-type.js +3 -0
  27. package/dist/internal/shutdown.d.ts +84 -0
  28. package/dist/internal/shutdown.js +202 -0
  29. package/dist/internal/test-mode-setup.d.ts +7 -0
  30. package/dist/internal/test-mode-setup.js +114 -0
  31. package/dist/internal/test-mode.d.ts +32 -0
  32. package/dist/internal/test-mode.js +9 -0
  33. package/dist/operations.d.ts +167 -0
  34. package/dist/operations.js +406 -0
  35. package/dist/public-url-1WeOw54Z.d.ts +34 -0
  36. package/dist/public-url-B6x0HMgY.js +140 -0
  37. package/dist/request-context-CP9NhgLL.js +2274 -0
  38. package/dist/runtime-type-BftydMAf.js +88 -0
  39. package/package.json +92 -17
  40. package/dist/drain.d.ts +0 -1
  41. package/dist/drain.js +0 -52
  42. package/dist/index-tBKyUP1T.d.ts +0 -314
  43. package/dist/node.d.ts +0 -35
  44. package/dist/runtime-type-ovvOd6m5.js +0 -37
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # @vite-hub/runtime
2
2
 
3
3
  <p>
4
- <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
- <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
- <img alt="Runtime" src="https://img.shields.io/badge/Runtime-context%20%7C%20policy%20%7C%20trace-18181b?style=flat-square">
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://comark-ui.onmax.me/badge.svg?label=ViteHub&amp;value=vitehub.dev"></a>
5
+ <img alt="TypeScript" src="https://comark-ui.onmax.me/badge.svg?label=TypeScript&amp;value=ready">
6
+ <img alt="Runtime" src="https://comark-ui.onmax.me/badge.svg?label=Runtime&amp;value=context+%7C+policy+%7C+trace">
7
7
  </p>
8
8
 
9
9
  `@vite-hub/runtime` provides the shared Runtime Host Context, Runtime Capability,
@@ -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,45 +29,63 @@ 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
- Long-lived Node services can also use `createProcessReconciler()` from the `/node`
37
- entry to coalesce event-driven work, run periodic repair, stop admission, and await
36
+ Trace payload inspection relies on the host's platform intrinsics. Load the
37
+ Runtime before application code replaces platform methods. The Runtime captures
38
+ `WebAssembly.Module.exports` at import time to recognize foreign modules even
39
+ when that method is later replaced. It cannot recover the original intrinsic
40
+ if the host replaces it before import; payload inspection is not an isolation
41
+ boundary for code that can modify the host's JavaScript environment.
42
+
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
38
45
  tracked work during a graceful drain. Set `signal: "SIGUSR2"` when the service
39
- manager should trigger that drain through the `vitehub-drain` command included
40
- 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
41
48
  must return before an external caller starts `drain()`; calling `drain()` from an
42
- active callback rejects to prevent that callback from waiting on itself. Keep the
43
- status endpoint available until `vitehub-drain` observes the terminal `drained`
49
+ active callback rejects to prevent that callback from waiting on itself. `close()`
50
+ removes the configured signal listener after the drain settles, including a failed
51
+ drain. Keep the
52
+ status endpoint available until `vitehub drain` observes the terminal `drained`
44
53
  status; process exit or endpoint loss before that acknowledgement is a failed drain.
45
54
 
55
+ ViteHub packages register their stop work with `onShutdown(nitroApp, name, drain)`
56
+ from the private `/internal/shutdown` entry, in a Nitro plugin. Applications do not call it. When a server
57
+ that owns stop signals gets `SIGTERM` or `SIGINT`, ViteHub runs every registered drain
58
+ in parallel and keeps HTTP open. Each drain gets the shared budget from
59
+ `VITEHUB_SHUTDOWN_DRAIN_MS` (default 0) and an `AbortSignal` that aborts when the
60
+ budget ends. A drain that does not settle 15 seconds after the budget ends is
61
+ reported as `timeout`. Then the server closes HTTP, Nitro runs its `close` hooks
62
+ for up to 10 seconds, and the process exits once with code 0. Give the host a
63
+ termination grace period longer than the budget plus 25 seconds. The Node, Bun, and
64
+ Deno server presets own stop signals. In development, during prerender, on
65
+ serverless and Cloudflare hosts, and when the server's graceful shutdown is off,
66
+ ViteHub does not handle signals; the drains run when the Nitro app calls its
67
+ `close` hooks. `shutdownState()` (also `process.__vitehubShutdown`) shows the
68
+ registered drains, the signal, and each drain result. The logs have the events
69
+ `shutdown.draining`, `shutdown.drained`, and `shutdown.exited`.
70
+
46
71
  ## Get a first result
47
72
 
48
73
  Create the host context explicitly, register one Runtime Capability, and look it
49
74
  up through the public package entry:
50
75
 
51
76
  ```ts
52
- import { createExecutionContext, defineCapability, getCapability } from "@vite-hub/runtime";
77
+ import { createRuntimeContext, defineCapability, getCapability } from "@vite-hub/runtime";
53
78
 
54
- const values = new Map<string, unknown>();
55
- const context = createExecutionContext({
79
+ const context = createRuntimeContext({
56
80
  capabilities: {
57
81
  health: defineCapability("health", { status: "ready" }),
58
82
  },
59
- memo<T>(key: string, create: () => T): T {
60
- if (!values.has(key)) values.set(key, create());
61
- return values.get(key) as T;
62
- },
63
83
  runtime: "node",
64
- waitUntil(task) {
65
- void task.catch(console.error);
66
- },
67
84
  });
68
85
 
69
86
  const health = getCapability(context, "health");
70
87
  console.log(`${context.runtime}:${health.kind}`);
88
+ await context.flushWaitUntil();
71
89
  ```
72
90
 
73
91
  Running the file prints:
@@ -76,22 +94,14 @@ Running the file prints:
76
94
  node:health
77
95
  ```
78
96
 
79
- This proves context construction and capability lookup. The `waitUntil` fallback
80
- only observes rejected promises in a long-lived process. It does not keep a
81
- serverless request alive. A production host must delegate background work to its
82
- provider lifetime API.
83
-
84
- `createExecutionContext()` always returns a complete Execution Context. It creates
85
- fresh empty `capabilities` and `runtimeConfig` objects when the host omits them,
86
- and preserves the supplied objects when the host provides them.
87
-
88
97
  ## Understand the boundaries
89
98
 
90
99
  ### Runtime Host Context
91
100
 
92
- `createExecutionContext()` normalizes an object supplied by the host. The host
93
- still owns `runtime`, `memo`, `waitUntil`, request or event data, provider
94
- bindings, and cleanup. Runtime does not discover framework globals, propagate an
101
+ `createExecutionContext()` normalizes a complete object supplied by the host.
102
+ `createRuntimeContext()` also supplies memo storage and background-work tracking.
103
+ The host still owns the runtime name, request or event data, provider bindings,
104
+ background-work lifetime, and cleanup. Runtime does not discover framework globals, propagate an
95
105
  ambient context, or isolate concurrent requests.
96
106
 
97
107
  Treat every value on the context as available to code that receives it. Runtime
@@ -99,10 +109,38 @@ does not clone, redact, encrypt, or restrict `request`, `event`, `cloudflare.env
99
109
  `runtimeConfig`, or Runtime Capability values. Pass only the bindings and secrets
100
110
  needed by that operation, and do not copy secrets into traces or approval input.
101
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
+
102
139
  ### Runtime Capabilities
103
140
 
104
141
  `defineCapability()` and `getCapability()` pass a named implementation between
105
- packages. A handle is not a permission boundary: code that receives its `value`
142
+ packages. Lookup accepts only own properties of `context.capabilities`; inherited
143
+ properties do not register capabilities. A handle is not a permission boundary: code that receives its `value`
106
144
  can call that implementation. Keep authentication, tenant checks, input
107
145
  validation, rate limits, and provider credentials at the application or provider
108
146
  boundary that owns the operation.
@@ -125,6 +163,11 @@ secret detection. Arbitrary names such as `token` or `authorization` are not
125
163
  automatically redacted, and `error.message` is retained. `{ content: "content" }`
126
164
  retains all supplied attributes.
127
165
 
166
+ Attribute projection reads own data properties. It does not invoke attribute
167
+ getters. In `metadata` mode this also applies to nested objects and array entries;
168
+ accessor-backed content keys are recorded as omitted, and other accessors are
169
+ skipped. In `content` mode nested attribute values remain unchanged.
170
+
128
171
  Own trace access, retention, size limits, redaction, and durable export in the
129
172
  host. `entries()` returns the current in-memory entries; it does not persist or
130
173
  stream them by itself.
@@ -143,20 +186,214 @@ details. Never put secrets in those fields; keep raw provider failures in `cause
143
186
  A `cause` is excluded from `toJSON()`, but remains available to code and loggers
144
187
  that inspect the Error instance.
145
188
 
189
+ ### Grants
190
+
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.
192
+
193
+ ```ts
194
+ import { defineGrant } from "@vite-hub/runtime/internal/grant"
195
+
196
+ const sourceWrite = defineGrant("vitehub.workspace.source-write", (path: string) => path)
197
+
198
+ export function checkSourceWrite(path: string) {
199
+ // ...the owner check...
200
+ return sourceWrite.issue(path)
201
+ }
202
+
203
+ export function writeSource(grant: ReturnType<typeof checkSourceWrite>, data: string) {
204
+ const path = sourceWrite.verify(grant)
205
+ // ...write `data` to `path`...
206
+ }
207
+ ```
208
+
209
+ - Keep the definition module-private. Only the module that owns the check issues grants.
210
+ - Bind the grant to what it authorizes, for example a path, a tool call, or a request. The second argument of `defineGrant()` copies or freezes that value.
211
+ - `verify()` returns the bound value or throws a `ViteHubError` with code `GRANT_REQUIRED`. `check()` returns `undefined` instead; use `isValid()` when a bound value may itself be `undefined`. `consume()` makes a grant single-use. `attach(owner, grant)` and `attached(owner)` keep a grant with a request or context object.
212
+ - Each definition has its own registry. A grant from another definition, another bundled copy of the package, or a forged object fails closed. The kind string brands the grant type, so use a unique `vitehub.<package>.<name>` kind.
213
+ - Grants are request-scoped. Never persist one. Durable or resumed work must run the check again.
214
+
215
+ ### Errors
216
+
217
+ Every primitive follows one error contract:
218
+
219
+ 1. A runtime operation returns `[error, data]`. Errors before a stream starts are in the tuple; errors after it starts go into the stream.
220
+ 2. Definition and config errors throw, at build time, at define time, or when an operation starts.
221
+ 3. A package defines a small catalog with `defineErrors()`. Each code has a guessable name, a `why`, and a `fix`.
222
+ 4. Each method type lists the union of the codes that it can return.
223
+ 5. Each code has a heading on the `limits-and-errors` docs page of the package, so `error.docs` opens it.
224
+
225
+ ```ts
226
+ import { defineErrors, type Result } from "@vite-hub/runtime"
227
+
228
+ const errors = defineErrors({
229
+ docs: "https://vitehub.dev/docs/kv/limits-and-errors",
230
+ codes: {
231
+ KV_INVALID_LIMIT: { why: "`limit` must be a positive integer.", fix: "Pass a positive integer." },
232
+ },
233
+ })
234
+
235
+ async function list(limit: number): Promise<Result<string[], "KV_INVALID_LIMIT">> {
236
+ if (!Number.isInteger(limit) || limit <= 0) return [errors.KV_INVALID_LIMIT(), undefined]
237
+ return [undefined, []]
238
+ }
239
+
240
+ const [error, keys] = await list(0)
241
+ if (error) error.code // "KV_INVALID_LIMIT"
242
+ if (errors.KV_INVALID_LIMIT.is(error)) error.data // data of KV_INVALID_LIMIT
243
+ ```
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
+
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`.
248
+
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.
250
+
251
+ `toResultError()` gives an allowed diagnostic this public serializer. It keeps the
252
+ same object when its `name` and `toJSON` properties can be replaced. Otherwise it
253
+ creates a new diagnostic with the same code, text, cause, data, sources, and stack,
254
+ and leaves the original unchanged. The caller owns code allowlisting and public text.
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
+
286
+ ### Developer diagnostics
287
+
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).
289
+
290
+ `normalizeRuntimeDiagnosticError(error)` creates a bounded diagnostic record. It
291
+ preserves Nostics codes, fixes, documentation links, and source locations from
292
+ Error instances and JSON records. Causes, aggregate errors, details, and source
293
+ locations share a node budget. All strings share a size budget. Stacks require
294
+ `{ includeStack: true }`.
295
+
296
+ Use `formatRuntimeDiagnosticError(error)` for terminal output or Agent tool error
297
+ text. It prints the code, message, fix, source locations, and documentation link
298
+ with Nostics formatting. It omits causes and stacks. Plain errors return their
299
+ message. Both helpers accept `unknown` and handle failed property reads.
300
+
301
+ Use `isRuntimeDiagnostic(error)` to recognize a live Nostics error from another bundled copy. It checks the native Error and diagnostic fields without requiring the same `Diagnostic` constructor. It rejects serialized records; use `normalizeRuntimeDiagnosticError()` to inspect those. Recognition does not make diagnostic text safe for a public response. Keep the owning package's code allowlist and public error mapping.
302
+
303
+ These helpers produce developer diagnostics. They do not make arbitrary errors
304
+ safe for public responses. Use the `ViteHubError` public contract at that boundary.
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
+
146
380
  ## Public entry points
147
381
 
148
382
  | Import | Provides |
149
383
  | ------------------------ | ---------------------------------------------------------------------------------------------------- |
150
- | `@vite-hub/runtime` | Context, capability, policy, approval, trace, lease, diagnostic, error, and execution-authority APIs |
151
- | `@vite-hub/runtime/node` | Node process observations, reconciliation, and graceful-drain lifecycle primitives |
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 |
152
389
 
153
390
  Do not import from `src`, `dist`, or ViteHub's `_internal` paths.
154
391
 
155
392
  ## Go deeper
156
393
 
157
- - [Runtime Context](https://vitehub.dev/docs/concepts/runtime-context)
158
- - [Runtime policy, approvals, and traces](https://vitehub.dev/docs/concepts/runtime-policy-approvals-and-traces)
394
+ - [Runtime Context](https://vitehub.dev/docs/reference/runtime-context)
395
+ - [Runtime policy, approvals, and traces](https://vitehub.dev/docs/agents/runtime-policy)
159
396
  - [Runtime events](https://vitehub.dev/docs/reference/runtime-events)
160
397
  - [Stable import paths](https://vitehub.dev/docs/reference/import-paths)
161
- - [Node Runtime diagnostics](https://vitehub.dev/docs/capabilities/diagnostics)
398
+ - [Node Runtime diagnostics](https://vitehub.dev/docs/agents/capabilities/diagnostics)
162
399
  - [Report a Runtime issue](https://github.com/vite-hub/vitehub/issues/new)
@@ -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