@vite-hub/sandbox 0.0.3 → 0.1.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 (60) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +388 -22
  3. package/dist/cloudflare-DO0h3Ncf.js +281 -0
  4. package/dist/cloudflare-env-BBJaBbuQ.js +39 -0
  5. package/dist/crabbox-BFCdf41h.js +1106 -0
  6. package/dist/error-diagnostics-BSysPv-D.js +166 -0
  7. package/dist/error-diagnostics-dGQqfgLt.js +99 -0
  8. package/dist/file-listing-DECFTdSl.js +26 -0
  9. package/dist/file-lock-CxyVl4Cv.js +73 -0
  10. package/dist/index-CXej1Bt0.d.ts +519 -0
  11. package/dist/index.d.ts +2 -65
  12. package/dist/index.js +277 -1172
  13. package/dist/internal/cloudflare.d.ts +4 -0
  14. package/dist/internal/cloudflare.js +16 -0
  15. package/dist/internal/host-toolchain.d.ts +22 -0
  16. package/dist/internal/host-toolchain.js +97 -0
  17. package/dist/internal/vercel.d.ts +4 -0
  18. package/dist/internal/vercel.js +16 -0
  19. package/dist/module-types-BfyRBaiP.js +7 -0
  20. package/dist/module-types-Cis4hrF1.d.ts +95 -0
  21. package/dist/remote-1Jz2oUMK.js +247 -0
  22. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  23. package/dist/runtime-DHp6ImeP.js +32 -0
  24. package/dist/runtime-type-DrmrW5m5.js +42 -0
  25. package/dist/session-DD0S1PDC.js +337 -0
  26. package/dist/shell-quote-Q3u3plif.js +6 -0
  27. package/dist/ssh.d.ts +55 -0
  28. package/dist/ssh.js +219 -0
  29. package/dist/task/index.d.ts +67 -0
  30. package/dist/task/index.js +1523 -0
  31. package/dist/task/runtime/empty-registry.d.ts +6 -0
  32. package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
  33. package/dist/task/runtime/provider-loader.d.ts +20 -0
  34. package/dist/task/runtime/provider-loader.js +19 -0
  35. package/dist/task/runtime/providers/cloudflare.d.ts +28 -0
  36. package/dist/task/runtime/providers/cloudflare.js +26 -0
  37. package/dist/task/runtime/providers/vercel.d.ts +12 -0
  38. package/dist/{runtime → task/runtime}/providers/vercel.js +17 -14
  39. package/dist/task/runtime/state.d.ts +24 -0
  40. package/dist/task/runtime/state.js +73 -0
  41. package/dist/task/vite.d.ts +360 -0
  42. package/dist/task/vite.js +3643 -0
  43. package/dist/toolchain-BUVXtQ2m.js +527 -0
  44. package/dist/trusted-host-DNMJ-Oig.js +872 -0
  45. package/dist/vercel-Jtxa9TJx.js +279 -0
  46. package/package.json +103 -39
  47. package/dist/cloudflare-env-2NctU8i7.js +0 -12
  48. package/dist/module-types-DfXe133f.d.ts +0 -91
  49. package/dist/module-types-Dj1MFmHT.js +0 -7
  50. package/dist/provider-loader-hL7uHVWp.d.ts +0 -21
  51. package/dist/runtime/empty-registry.d.ts +0 -6
  52. package/dist/runtime/provider-loader.d.ts +0 -2
  53. package/dist/runtime/provider-loader.js +0 -15
  54. package/dist/runtime/providers/cloudflare.d.ts +0 -29
  55. package/dist/runtime/providers/cloudflare.js +0 -25
  56. package/dist/runtime/providers/vercel.d.ts +0 -112
  57. package/dist/runtime/state.d.ts +0 -17
  58. package/dist/runtime/state.js +0 -21
  59. package/dist/vite.d.ts +0 -24
  60. package/dist/vite.js +0 -2367
package/README.md CHANGED
@@ -1,56 +1,422 @@
1
1
  # @vite-hub/sandbox
2
2
 
3
- `@vite-hub/sandbox` discovers and runs named work by composing a package project and a Box. Sandbox owns discovery, orchestration, and project staging; Box owns provider-specific execution.
3
+ [![npm version](https://comark-ui.onmax.me/badge.svg?source=npm-version&package=%40vite-hub%2Fsandbox&icon=npm)](https://npmx.dev/package/@vite-hub/sandbox)
4
+ [![npm downloads](https://comark-ui.onmax.me/badge.svg?source=npm-downloads&package=%40vite-hub%2Fsandbox&period=month&icon=npm)](https://npmx.dev/package/@vite-hub/sandbox)
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
+ [![docs](https://comark-ui.onmax.me/badge.svg?label=docs&value=vitehub.dev)](https://vitehub.dev/docs)
7
+
8
+ `@vite-hub/sandbox` owns portable execution for ViteHub. A project declares environment inputs, immutable Home files, writable Home state, and boot checks; a runtime Adapter turns that declaration into an inspectable preparation plan and opens active Sandbox sessions without exposing a provider SDK.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ pnpm add @vite-hub/sandbox
14
+ ```
15
+
16
+ ## Prepare a trusted-host Sandbox
4
17
 
5
18
  ```ts
6
- // server/sandboxes/release-notes/index.ts
7
- interface SandboxPayload {
8
- notes?: string
19
+ import { resolveSandbox } from "@vite-hub/sandbox";
20
+ import { useServerEnv } from "#vitehub/env/server";
21
+
22
+ const sandbox = await resolveSandbox({
23
+ runtime: { kind: "trusted-host", stateRoot: "/var/lib/vitehub/sandboxes" },
24
+ checkout: {
25
+ ref: "refs/pull/985/head",
26
+ remote: "https://github.com/vite-hub/vitehub.git",
27
+ sha: "0123456789abcdef0123456789abcdef01234567",
28
+ },
29
+ env: {
30
+ GH_TOKEN: () => useServerEnv().githubToken.unseal(),
31
+ GIT_CONFIG_NOSYSTEM: "1",
32
+ GIT_TERMINAL_PROMPT: "0",
33
+ },
34
+ home: {
35
+ files: {
36
+ ".gitconfig": { from: ".vitehub/sandbox/gitconfig" },
37
+ ".codex/config.toml": { from: ".vitehub/sandbox/codex.toml" },
38
+ },
39
+ state: {
40
+ ".codex": {
41
+ key: "babysitter/codex",
42
+ seed: {
43
+ "auth.json": {
44
+ contents: () => useServerEnv().codexAuthJson.unseal(),
45
+ },
46
+ },
47
+ },
48
+ },
49
+ },
50
+ requires: [{ name: "GitHub CLI", command: "gh", args: ["auth", "status"] }, "pnpm"],
51
+ }, {});
52
+ ```
53
+
54
+ Direct callers can inspect preparation without resolving secrets, then open a session:
55
+
56
+ ```ts
57
+ import { resolveSandbox } from "@vite-hub/sandbox";
58
+
59
+ const sandbox = await resolveSandbox(
60
+ {
61
+ env: { PROJECT_ENV: "test" },
62
+ requires: ["node", "pnpm"],
63
+ runtime: "trusted-host",
64
+ },
65
+ {},
66
+ );
67
+
68
+ console.log(sandbox.plan.runtime, sandbox.plan.requirements, sandbox.plan.executionAuthority);
69
+
70
+ const session = await sandbox.open();
71
+ try {
72
+ await session.files.write("workspace/input.bin", new Uint8Array([0, 1, 255]));
73
+ const result = await session.exec("node", ["workspace/run.mjs"], {
74
+ cwd: session.cwd,
75
+ timeout: 30_000,
76
+ });
77
+ if (!result.ok) throw new Error(result.stderr);
78
+ } finally {
79
+ await session.close();
9
80
  }
81
+ ```
82
+
83
+ Binary file reads and writes, directory operations, recursive listing, removal, and command execution are required across runtimes. Long-running processes and exposed ports are explicit optional capabilities through `session.spawn` and `session.ports`. `close()` is idempotent, and every operation rejects after closure.
84
+
85
+ For trusted-host processes, `child.kill()` sends `SIGTERM`, then sends `SIGKILL` after a 250 ms grace period if needed. On POSIX hosts it terminates the process group, including descendants. `child.kill(signal)` forwards the explicit signal and waits for the process to finish without automatic escalation.
86
+
87
+ A spawned `SandboxProcess` can also expose `stdin` as a `WritableStream<Uint8Array>`. The `trusted-host` and `crabbox` runtimes forward it to the process. Close the writer to end the process input. Runtimes that cannot forward input leave `stdin` undefined:
88
+
89
+ ```ts
90
+ const child = await session.spawn!("node", ["workspace/filter.mjs"]);
91
+ const writer = child.stdin?.getWriter();
92
+ if (!writer) throw new Error("This Sandbox runtime does not forward process input.");
93
+ await writer.write(new TextEncoder().encode("input\n"));
94
+ await writer.close();
95
+ console.log(await new Response(child.stdout).text(), await child.wait());
96
+ ```
97
+
98
+ Hosted runtimes use tagged values from the same root API:
99
+
100
+ ```ts
101
+ const cloudflare = await resolveSandbox({
102
+ runtime: { kind: "cloudflare", namespace: env.SANDBOX },
103
+ }, {});
104
+
105
+ const vercel = await resolveSandbox({
106
+ runtime: { kind: "vercel", ports: [3000] },
107
+ }, {});
108
+ ```
109
+
110
+ Use `runtime: "vercel"` for the default Vercel Sandbox configuration. Cloudflare remains tag-only because its Durable Objects namespace is required.
111
+
112
+ The Cloudflare runtime uses `@cloudflare/sandbox`, preserves Durable Object idle reuse, and bounds transient transport operations with retries and deadlines. The Vercel runtime exposes only the ports declared when the microVM is created. Both reject host `cwd`; materialize a Workspace into their working tree instead.
113
+
114
+ If Cloudflare Sandbox or Vercel cleanup fails, retry `session.close()`. The session rejects new operations after the first close attempt. Concurrent close calls wait for the same cleanup.
115
+
116
+ `sandbox.open({ initialize })` runs initialization inside runtime preparation. If initialization fails, a runtime must tear down the session and roll back state created for that failed boot.
117
+
118
+ `checkout` gives each invocation a disposable real Git repository at the exact requested commit. The runtime fetches `ref` from `remote`, verifies the resulting commit against the full `sha`, and starts the process in a detached checkout. Normal Git commits work, and callers can push explicitly with `git push origin HEAD:<branch>`. Use the source repository as `remote` for fork pull requests, and keep credentials in Sandbox `env` or Home rather than embedding them in the remote URL.
119
+
120
+ `checkout` and `cwd` are mutually exclusive. Use `cwd` for a caller-owned authoritative directory; use `checkout` when the Sandbox should create, isolate, and delete the working tree. Git is an implicit checkout requirement and is included in resolved Sandbox metadata.
121
+
122
+ Every Sandbox session receives a new private `HOME` plus `XDG_CONFIG_HOME`, `XDG_CACHE_HOME`, and `XDG_STATE_HOME`. The runtime starts from a small operational environment allowlist, applies the declared `env`, attaches writable state, materializes files, and runs requirements before the process starts. Missing declarations fail boot; the host Home and undeclared credential variables cannot satisfy them.
123
+
124
+ `home.files` targets and state paths are relative POSIX paths below the materialized Home. A `from` source is relative to `cwd`, or the ViteHub process directory when `cwd` is omitted. Files with `contents` accept text, bytes, or a `SandboxValue` callback. Every declared value is required.
125
+
126
+ The project may commit declarations, non-secret files, and ciphertext. Resolve plaintext through Server Env or another runtime capability. Do not commit plaintext credentials or the capability that decrypts committed ciphertext.
127
+
128
+ ## Separate files from state
129
+
130
+ `home.files` is rebuilt at every boot and never becomes authoritative runtime state. Use it for `.gitconfig`, Codex configuration, arbitrary CLI settings, and immutable credential files.
131
+
132
+ `home.state` attaches an opaque writable directory from the runtime's protected `stateRoot`. Its `key` is a stable project-owned identity. The runtime resolves `seed` only when that state directory does not exist, so a refreshed OAuth file is never replaced by stale bootstrap data. Sessions sharing a state key are serialized until the owning session stops its processes and releases the lease.
133
+
134
+ A file may live beneath a state target. The runtime attaches state first and projects the file afterward, so committed configuration wins on every boot while adjacent CLI-owned files remain writable.
135
+
136
+ `{ kind: "trusted-host", stateRoot }` requires a durable local path whenever state is declared. Keep it outside the checkout, workspace, build context, cache, and artifact directories. The runtime creates private children but does not change permissions on an existing caller-owned root.
137
+
138
+ ## Use generic requirement checks
139
+
140
+ A string requirement checks that an executable exists on `PATH`. An object supplies a fixed command and argv after the Sandbox is prepared, without parsing a project-supplied shell command:
141
+
142
+ ```ts
143
+ requires: [
144
+ "git",
145
+ { name: "GitHub CLI", command: "gh", args: ["auth", "status"] },
146
+ { name: "Acme CLI", command: "acme", args: ["auth", "status"] },
147
+ ];
148
+ ```
149
+
150
+ Core does not contain provider names or auth-file formats. Declare every executable and authentication check required by the process that will run in the Sandbox.
151
+
152
+ Requirement names, commands, and argv are inspectable declaration metadata. They verify or select executables, but they do not restrict filesystem access, network egress, inherited credentials, or child processes. Inspect `sandbox.plan.executionAuthority` for those boundaries, and keep credentials in `env` or Home files rather than arguments.
153
+
154
+ ## Provision the project toolchain
155
+
156
+ A Sandbox does not assume that Node.js, npm, pnpm, Yarn, or Corepack exist on the host or image. Declare `toolchain` and the Sandbox installs the versions that the project pins:
157
+
158
+ ```ts
159
+ const sandbox = await resolveSandbox({
160
+ runtime: { kind: "trusted-host", stateRoot: "/var/lib/vitehub/sandboxes" },
161
+ checkout: { ref, remote, sha },
162
+ toolchain: "project",
163
+ }, {});
164
+ ```
165
+
166
+ `"project"` is short for `{ node: "project", packageManager: "project" }`. The object form accepts:
167
+
168
+ | Option | Values |
169
+ | --- | --- |
170
+ | `node` | `"project"` (default), or a version, range, or alias such as `"22.11.0"`, `"22"`, `"^22.11.0"`, or `"lts/*"` |
171
+ | `packageManager` | `"project"` (default), `false` for the npm bundled with Node.js, or `name@version` such as `"pnpm@10.2.0"` |
172
+ | `fallbackNode` | A Node.js version, range, or alias used when the project pins none |
173
+
174
+ The first match selects Node.js:
175
+
176
+ 1. `package.json` `devEngines.runtime`, the entry named `node` (object or array)
177
+ 2. `.node-version`
178
+ 3. `.nvmrc`
179
+ 4. `package.json` `volta.node`
180
+ 5. `package.json` `engines.node`
181
+ 6. `toolchain.fallbackNode`
182
+
183
+ If none matches, boot fails with `SANDBOX_R0147`. The Sandbox never falls back to a Node.js that happens to be on `PATH`. A range or alias such as `lts/*`, `lts/iron`, or `node` resolves to the highest matching release in the distribution `index.json`. The package manager comes from `package.json` `packageManager` (`pnpm@x.y.z`, `yarn@x.y.z`, or `npm@x.y.z`, with an optional `+sha512.<hex>` hash) or `devEngines.packageManager`. Without either, the project uses the npm bundled with Node.js. Bun fails with `SANDBOX_R0149`.
184
+
185
+ The ViteHub process downloads official archives with `fetch`. Node.js archives must match `SHASUMS256.txt` from the same distribution. Package managers come from the npm registry and must match its `dist.integrity` (sha512) and, when present, the `packageManager` hash. Yarn 2 and later use `@yarnpkg/cli-dist`; their `packageManager` hash is checked against its `bin/yarn.js`, as Corepack does. A project `yarnPath` still takes effect. ViteHub does not use Corepack, nvm, or mise. On musl Linux, Node.js comes from `https://unofficial-builds.nodejs.org/download/release`. Set `VITEHUB_NODE_DIST_URL`, `VITEHUB_NODE_MUSL_DIST_URL`, or `VITEHUB_NPM_REGISTRY_URL` in the ViteHub process to use a mirror.
186
+
187
+ The runtime provisions after it materializes the checkout and before requirement checks. It puts the package manager and Node.js `bin` directories first on the Sandbox `PATH`, adds `node` and the package manager to the requirements, and then checks `node -v` and `<package manager> --version` with the Sandbox environment. Without `checkout`, pins come from `cwd`, or the ViteHub process directory when `cwd` is omitted, and `sandbox.plan.toolchain` lists them. A `checkout` Sandbox reads them from the checkout at each boot, so its plan reports `source: "checkout"`. An open session reports the exact versions in `session.toolchain`.
188
+
189
+ | Runtime | Toolchain location |
190
+ | --- | --- |
191
+ | `trusted-host` | `<stateRoot>/toolchains`, or `$XDG_CACHE_HOME/vitehub/toolchains` without `stateRoot`. Shared by sessions and processes; a lock makes concurrent sessions download each version once. |
192
+ | `crabbox` | The same layout on the target, under the target user's cache when `stateRoot` is not set. Archives travel through the Crabbox copy transport. |
193
+ | `cloudflare`, `vercel` | `$HOME/.cache/vitehub/toolchains` in the Sandbox, for one session. An image `node` with the exact resolved version is used as is. |
194
+
195
+ Cache entries are content-addressed and read-only once published. Global installs such as `npm install -g` cannot write into them. To clear a cache, run `chmod -R u+w <cache> && rm -rf <cache>`. Installation uses `sh`, `tar` with gzip, `mktemp`, and `base64` on the target. The first boot of a version needs network access from the ViteHub process; an exact pin that is already cached boots without it. Custom runtimes do not provision toolchains, and boot fails with `SANDBOX_R0156` when one declares `toolchain`. Windows hosts are not supported.
196
+
197
+ ## Run through Crabbox
198
+
199
+ ```ts
200
+ sandbox: {
201
+ runtime: {
202
+ kind: "crabbox",
203
+ profile: "babysitter",
204
+ stateRoot: "/var/lib/vitehub/sandboxes",
205
+ },
206
+ checkout: {
207
+ ref: ({ input }) => input.options?.ref,
208
+ remote: ({ input }) => input.options?.remote,
209
+ sha: ({ input }) => input.options?.sha,
210
+ },
211
+ env: {
212
+ GH_TOKEN: () => useServerEnv().githubToken.unseal(),
213
+ },
214
+ home: {
215
+ files: {
216
+ ".gitconfig": { from: ".vitehub/sandbox/gitconfig" },
217
+ },
218
+ },
219
+ }
220
+ ```
221
+
222
+ Crabbox materializes the same declaration on the target before requirement checks. Resolved material travels through Crabbox's protected stdin channel rather than command arguments. The private Home and writable state stay outside Workspace synchronization. An authoritative `cwd` is synchronized back; a disposable `checkout` remains target-local and is deleted with the Sandbox session.
223
+
224
+ Crabbox requires either `cwd` or `checkout` and targets Linux/POSIX Static SSH hosts. `stateRoot` is an absolute path on the target. File reads and writes use Crabbox's resolved SSH copy transport. Port URLs wait for and reuse one loopback-only Crabbox tunnel per port by default, and session teardown stops those tunnels. Use `network: "direct"` only when the target shares the ViteHub process loopback namespace.
10
225
 
11
- export default async function releaseNotes(payload: SandboxPayload = {}) {
12
- return { summary: payload.notes?.split("\n")[0] ?? "" }
226
+ Commands must remain owned by their Sandbox session. ViteHub adds the reserved `VITEHUB_SANDBOX_SESSION` environment marker to commands and reclaims marked processes on the SSH target when the session closes, including children adopted by supervisors. Commands cannot override this marker through the `env` option. Supervisors that launch replacement processes must preserve it.
227
+
228
+ The marker is read from each process's environment at launch. A process that starts with the marker remains owned by that Sandbox, even if it later changes its environment. A process started without the marker is not owned by that Sandbox, even if it references the Sandbox directory. This cleanup does not add process isolation.
229
+
230
+ ## Bring a custom runtime
231
+
232
+ A `runtime` can also be an object with `name`, `prepare(input)` and `open(input, options)`. Set `network: "direct"` only when its sessions reach the ViteHub process loopback services, for example through SSH reverse tunnels. Agents then pass host Capability tools into the Sandbox. A session may implement `importWorkspace(checkout, signal)` and `refreshDependencies(checkout, signal)` to replace the generic working-tree copy and the publishing of host-installed dependencies. Use them when the runtime can transfer or install faster on its own host.
233
+
234
+ ## Security boundary
235
+
236
+ A Sandbox isolates Home, configuration, and declared process environment from ambient machine state. It does not necessarily isolate the filesystem, network, installed executables, or trusted project code; the complete normalized provider declaration is `sandbox.plan.executionAuthority` and is copied unchanged onto every opened session. Dimensions the provider cannot establish remain `unknown`. Use `"trusted-host"` only when the Agent may act with the host user's authority, and use an isolated Sandbox runtime such as `vercel` or `cloudflare` for untrusted code.
237
+
238
+ Resolved environment values, file contents, state keys, and physical Home paths are excluded from `sandbox.plan`; `sandbox.plan.home.state` lists declared target paths with opaque stable identities. Requirement failures discard command output, while every process inside the Sandbox remains trusted and can still read or log its credentials. Stable preparation identity uses declaration targets and state keys, never secret values or temporary paths.
239
+
240
+ Sandbox does not own Workspace snapshots, diffs, or commits. Workspace materializes those files through `SandboxSession.files`, while Sandbox remains responsible for execution and lifecycle.
241
+
242
+
243
+ ## Trusted SSH command transport
244
+
245
+ `@vite-hub/sandbox/ssh` exports `sshLaunch` for Agent provider launch callbacks and `serveSsh` for a trusted sidecar. The client requires Node and OpenSSH. The server requires the optional `ssh2` peer.
246
+
247
+ ```ts
248
+ import { sshLaunch } from "@vite-hub/sandbox/ssh"
249
+
250
+ const launch = sshLaunch({
251
+ host: "127.0.0.1",
252
+ port: 2222,
253
+ user: "agent",
254
+ identityFile: "/ssh/id_ed25519",
255
+ hostKeyFile: "/ssh/ssh_host_ed25519_key.pub",
256
+ })
257
+ // Pass launch to driver.launch in an Agent Definition.
258
+ ```
259
+
260
+ The target must expose the same working-directory and credential paths, for example through a shared sidecar volume. Host keys are verified. Environment names come from the resolved provider launch context; values travel through SSH environment requests. An explicit `forwardEnvironment` narrows the list while retaining framework-required names. `serveSsh` accepts valid environment names from authenticated clients unless `acceptEnvironment` restricts them.
261
+
262
+ The `vite-hub` distribution also exposes this module as `vite-hub/sandbox/ssh`, and `vitehub sandbox serve` and `vitehub sandbox check` run the server and a Driver readiness check without a project config. See the [CLI reference](https://vitehub.dev/docs/development/cli#commands).
263
+
264
+ This transport grants arbitrary command execution as the configured user. It is not a sandbox and does not synchronize Workspace files. Server shutdown closes connections and stops supervised process groups. `close({ drainTimeoutMs })` stops new connections at once and waits up to `drainTimeoutMs` for open connections to close before it ends them, so a stopping container can let running commands finish. `connections` counts the open connections. `vitehub sandbox serve --drain-timeout <ms>` uses this on SIGTERM and SIGINT.
265
+
266
+ ## Limit trusted-host command memory
267
+
268
+ On Linux, set `runtime.resources` to cap the combined memory of one session's commands and their descendants:
269
+
270
+ ```ts
271
+ runtime: {
272
+ kind: "trusted-host",
273
+ resources: {
274
+ cgroupParent: "/sys/fs/cgroup/system.slice/agent.service",
275
+ memoryHighBytes: 3 * 1024 ** 3,
276
+ memoryMaxBytes: 4 * 1024 ** 3,
277
+ memorySwapMaxBytes: 128 * 1024 ** 2,
278
+ },
13
279
  }
14
280
  ```
15
281
 
16
- The folder supplies the Definition name, and the adjacent manifest owns portable lifecycle metadata:
282
+ Use a writable delegated cgroup v2 parent with the memory controller. For systemd 254 or later, `Delegate=memory` and `DelegateSubgroup=controller` place the controller in a separate child. `ProtectControlGroups` must allow the delegated subtree to be written. The parent must contain no processes before Sandbox enables the controller. Sandbox fails closed when configured limits cannot be enforced. Swap defaults to zero.
283
+
284
+ All `exec` and `spawn` commands in the session share one budget, including native provider tools. A local OOM kills the whole command group and rejects pending waits with `SANDBOX_R0158`, the memory limit, peak bytes and OOM kill count. Further commands fail until a new session opens. Closing the session kills remaining descendants, including processes that left their process group, and removes its cgroup. `sandbox.plan.resources` exposes the configured limits.
285
+
286
+ Checkout materialization, toolchain provisioning and requirement checks run before session commands and remain under the controller's service limits. The trusted launcher also prepares its environment under that budget, then joins the session cgroup before executing the command or any caller-controlled loader hooks. Keep those limits in place. This resource policy does not add filesystem or network isolation. Trusted commands can use the host user's authority to change cgroup membership; use an isolated Sandbox runtime such as `vercel` or `cloudflare` for untrusted code.
287
+
288
+ On kernels without `memory.peak`, the OOM diagnostic reports `peak=unavailable`. Sandbox invalidates the session on a local allocation OOM, including allocation failures without a kill. This signal identifies exhaustion of the session budget and works with `memory_localevents` mounts. Ancestor or host kills alone do not invalidate it. The diagnostic reports the observed `memory.events` kill count as context, not proof of the kill cause; that count can exclude descendant victims on `memory_localevents` mounts. Sandbox removes nested cgroups during close. The launcher restores the command environment only after joining the session group.
289
+
290
+ If descendants remain alive after a kill, close waits up to 10 seconds for the cgroup to become empty. A timeout rejects close and retains the cgroup and state lease. Retry close after the descendants exit; cleanup must succeed before that state can be reused.
291
+
292
+ ## Sandbox Tasks
293
+
294
+ A Sandbox Task is one job that runs inside one Sandbox. `@vite-hub/sandbox/task` runs a discovered Sandbox Task Definition inside a provider-backed Sandbox. It owns discovery, package staging, typed invocation, timeouts, and result transport. The rest of this package owns the Sandbox: the execution environment and its isolation.
295
+
296
+ Most applications should install [`vite-hub`](https://vitehub.dev/docs/getting-started/installation) and import APIs such as `runSandboxTask` from `vite-hub/sandbox/task`. Import `@vite-hub/sandbox/task` directly when you are building a library, a custom Vite composition, or package-level tooling.
297
+
298
+ ### Install
299
+
300
+ Install Sandbox, TypeScript, Vite, and the Sandbox provider used by your deployment. Sandbox Tasks read their Definitions with TypeScript at build time. This first run uses Vercel Sandbox:
301
+
302
+ ```sh
303
+ pnpm add @vite-hub/sandbox typescript @vercel/sandbox vite
304
+ ```
305
+
306
+ Sandbox Task requires Node.js 24 or newer. Vercel execution also requires a Vercel project with Sandbox access. At runtime, use the project's environment or set `VERCEL_TOKEN`, `VERCEL_TEAM_ID`, and `VERCEL_PROJECT_ID`.
307
+
308
+ For Cloudflare, install `@cloudflare/sandbox` instead and use the ViteHub Cloudflare host integration so it can emit the required Container, Durable Object binding, migration, and Worker exports. Both providers run remote, potentially billed infrastructure; Sandbox does not include a local in-process provider.
309
+
310
+ ### Run one Sandbox Task
311
+
312
+ Register discovery and select the provider in Vite:
313
+
314
+ ```ts
315
+ // vite.config.ts
316
+ import { hubSandboxTask } from "@vite-hub/sandbox/task/vite";
317
+ import { defineConfig } from "vite";
318
+
319
+ export default defineConfig({
320
+ plugins: [hubSandboxTask({ provider: "vercel" })],
321
+ build: {
322
+ ssr: "src/server.ts",
323
+ },
324
+ });
325
+ ```
326
+
327
+ Create a package-backed Definition at `server/sandbox-tasks/release-notes/package.json`. The folder path supplies the name `release-notes`, and its manifest owns the timeout for each execution attempt:
17
328
 
18
329
  ```json
19
330
  {
20
331
  "private": true,
21
332
  "type": "module",
22
333
  "vitehub": {
23
- "sandbox": {
334
+ "sandboxTask": {
24
335
  "timeout": 30000
25
336
  }
26
337
  }
27
338
  }
28
339
  ```
29
340
 
30
- ViteHub calls the default function with `(payload, context)` and infers the `runSandbox()` payload and result types from it. Nested `Blob` and `Uint8Array` values cross the Box boundary through binary sidecars rather than application JSON; Node.js `Buffer` values retain their `Buffer` type. Existing non-function default exports remain supported; their optional exported `SandboxPayload` type is the payload fallback. The entrypoint needs no `@vite-hub/sandbox` runtime dependency.
31
-
32
- ViteHub uses the manifest's `packageManager`, then a lockfile at that package root, then npm. A matching `pnpm-workspace.yaml` selects pnpm, moves preparation to the pnpm workspace root, and carries the transitive `workspace:*` dependency closure into the Box while the entrypoint still runs from its package directory.
341
+ ```ts
342
+ // server/sandbox-tasks/release-notes/index.ts
343
+ interface ReleaseNotesPayload {
344
+ notes?: string;
345
+ }
33
346
 
34
- Package entrypoints are ESM projects. Keep `"type": "module"`, use explicit relative ESM imports for local `.ts` and `.mts` source, and depend on packages that expose runtime-ready JavaScript. ViteHub compiles the reachable local TypeScript graph without bundling package dependencies or moving relative assets. It rejects CommonJS/CTS, package import aliases and self-references for local source, imports that escape the selected package, and workspace dependencies that expose TypeScript runtime entries.
347
+ export default async function releaseNotes(payload: ReleaseNotesPayload = {}) {
348
+ return { summary: payload.notes?.split("\n")[0] ?? "" };
349
+ }
350
+ ```
35
351
 
36
- Use `<path>.sandbox.ts` with `defineSandbox()` for free-form Definitions outside `server/sandboxes`.
352
+ Invoke the discovered name from server code. `runSandboxTask()` returns a native Web `Response` and infers its payload from the Definition:
37
353
 
38
354
  ```ts
39
- import { runSandbox } from "@vite-hub/sandbox"
355
+ // src/server.ts
356
+ import { runSandboxTask } from "@vite-hub/sandbox/task";
357
+
358
+ const response = await runSandboxTask("release-notes", {
359
+ notes: "ship it\nadd tests",
360
+ });
361
+
362
+ if (!response.ok) throw new Error(await response.text());
363
+
364
+ console.log(JSON.stringify(await response.json()));
365
+ ```
366
+
367
+ Build through Vite so discovery and the runtime registry are generated, then run the server entry:
40
368
 
41
- const [error, result] = await runSandbox("release-notes", { notes: "ship it" })
42
- if (error) throw error
369
+ ```sh
370
+ pnpm vite build
371
+ node dist/server.js
43
372
  ```
44
373
 
45
- Resolve a runner when orchestration needs to inspect the provider boundary before execution:
374
+ The process prints:
375
+
376
+ ```json
377
+ { "summary": "ship it" }
378
+ ```
379
+
380
+ The Definition entrypoint does not import `@vite-hub/sandbox/task`. ViteHub calls its default function with `(payload, context)` and returns its awaited result.
381
+
382
+ ### Provider and lifecycle limits
383
+
384
+ - Provider selection belongs to application or host configuration, not to a Definition. `hubSandboxTask({ provider: "vercel" })` and `hubSandboxTask({ provider: "cloudflare" })` are the direct-package forms. The `vite-hub` distribution can infer these from its Vercel and Cloudflare presets.
385
+ - `vitehub.sandboxTask.timeout` must be a positive integer no greater than `2_147_483_647`. It bounds one execution attempt after provider startup, including package preparation, staging, and execution. Queueing, Sandbox startup, and retry delays can make the complete `runSandboxTask()` call take longer. An elapsed attempt timeout sends an internal abort signal to cancellable provider operations and returns a `SANDBOX_TASK_TIMEOUT` error in a non-2xx JSON response.
386
+ - Pass `signal` to `runSandboxTask()` when it belongs to a request or Agent Invocation. ViteHub forwards it to Sandbox startup and execution, cancels queued Cloudflare runs and retry backoff, and preserves the caller's abort reason. A Definition timeout remains the independent bound for each execution attempt.
387
+ - Vercel Sandbox sessions are closed in a `finally` block after success or failure. Cloudflare also creates and closes a unique Sandbox for each run unless you configure `sandboxId` or pass one to `runSandboxTask()`. Session cleanup failures and Cloudflare invocation-file cleanup failures return a non-2xx JSON response, even after a successful handler.
388
+ - An explicit Cloudflare `sandboxId` opts into a shared Sandbox identity. ViteHub deletes invocation-local files after each attempt, caches prepared projects by digest inside that Sandbox, and serializes runs with the same ID within one runtime isolate. Separate Worker isolates can still enter the Sandbox concurrently, so use external coordination when deployment-wide serialization is required. The provider normally leaves an explicitly named Sandbox for idle shutdown; setting `keepAlive: true` makes ViteHub close its session after the run.
389
+
390
+ When `resolveSandboxTaskRunner().run()` throws, its error cause retains the original provider diagnostic. If execution and cleanup both fail, the cause chain contains an `AggregateError` with both failures. The primary error code and message stay unchanged. JSON error responses omit causes.
391
+
392
+ ### Security and isolation
393
+
394
+ A Sandbox Task Definition name and its typed arguments select work; they are not a permission boundary. Code inside the Sandbox can use whatever filesystem, environment, network, credentials, executables, and child-process authority the selected provider exposes.
395
+
396
+ Inspect that authority before execution when application policy depends on it:
46
397
 
47
398
  ```ts
48
- import { resolveSandboxRunner } from "@vite-hub/sandbox"
399
+ import { resolveSandboxTaskRunner } from "@vite-hub/sandbox/task";
49
400
 
50
- const runner = await resolveSandboxRunner("release-notes")
51
- console.log(runner.executionAuthority)
401
+ const runner = await resolveSandboxTaskRunner("release-notes");
402
+ console.log(runner.executionAuthority);
52
403
  ```
53
404
 
54
- The runner exposes the selected Box provider's complete `ExecutionAuthority` descriptor. A Sandbox Definition name and its structural command arguments choose work to run; they do not limit what that process can read, reach, inherit, or spawn.
405
+ The descriptor reports the provider's complete `ExecutionAuthority`, including dimensions it cannot establish as `unknown`. Apply provider controls such as Vercel `networkPolicy`, keep secrets in server environment or provider configuration, and do not treat container execution alone as authorization for untrusted code.
406
+
407
+ Payloads, context, and results must be JSON-serializable. Nested `Blob` and `Uint8Array` values cross the Sandbox boundary through invocation-local binary files, and Node.js `Buffer` values retain their type.
408
+
409
+ ### Package projects
410
+
411
+ ViteHub uses the package manifest's `packageManager`, then a lockfile at that package root, then npm. A matching `pnpm-workspace.yaml` moves preparation to the pnpm Workspace root and carries the transitive `workspace:*` dependency closure into the Sandbox while the entrypoint still runs from its package directory.
412
+
413
+ Package entrypoints are ESM projects. Keep `"type": "module"`, use explicit relative ESM imports for local `.ts` and `.mts` source, and depend on packages that expose runtime-ready JavaScript. ViteHub compiles reachable local TypeScript without bundling package dependencies or moving relative assets. It rejects CommonJS/CTS, local package aliases and self-references, imports that escape the selected package, and Workspace dependencies that expose TypeScript runtime entries.
414
+
415
+ Use `<path>.sandbox-task.ts` with `defineSandboxTask()` for a free-form Definition outside `server/sandbox-tasks`. Free-form Definitions use their nearest package project.
416
+
417
+ ### Read more about Sandbox Tasks
55
418
 
56
- Add `hubSandbox()` to Vite for discovery, typed registry generation, package preparation plans, and host output. Provider images and full Dockerfile overrides belong to the selected Box adapter or host configuration; Sandbox Definitions stay portable.
419
+ - [Sandbox Task guide](https://vitehub.dev/docs/sandbox)
420
+ - [Sandbox execution and security model](https://vitehub.dev/docs/agents/sandboxes)
421
+ - [Runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix)
422
+ - [ViteHub security policy](https://github.com/vite-hub/vitehub/blob/main/SECURITY.md)