@vite-hub/sandbox 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.
- package/README.md +118 -53
- package/dist/abortable-CR01hzfi.js +57 -0
- package/dist/cloudflare-Cog_r2Me.js +910 -0
- package/dist/cloudflare-env-lookup-DzI6Xv1Y.js +16 -0
- package/dist/cloudflare-failure-CFQhalfh.js +50 -0
- package/dist/container-CqfD8yuE.js +868 -0
- package/dist/{crabbox-BFCdf41h.js → crabbox-sbV3Zjuo.js} +10 -6
- package/dist/error-diagnostics-5QT_BjbQ.js +354 -0
- package/dist/error-diagnostics-BJtLRL9w.js +536 -0
- package/dist/{file-listing-DECFTdSl.js → file-listing-CHtRrfo1.js} +1 -1
- package/dist/{file-lock-CxyVl4Cv.js → file-lock-D0-XPogS.js} +3 -2
- package/dist/{index-CXej1Bt0.d.ts → index-DsoQAUb7.d.ts} +94 -19
- package/dist/index.d.ts +2 -2
- package/dist/index.js +15 -10
- package/dist/internal/cloudflare.d.ts +173 -1
- package/dist/internal/cloudflare.js +4 -12
- package/dist/internal/host-toolchain.d.ts +1 -1
- package/dist/internal/host-toolchain.js +6 -7
- package/dist/internal/vercel.d.ts +1 -1
- package/dist/internal/vercel.js +3 -11
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/module-types-B0LQ5H2S.js +7 -0
- package/dist/module-types-DCeJbS9Z.d.ts +110 -0
- package/dist/process-sweep-CMaujWE5.js +33 -0
- package/dist/provider-resolution-C6AQzuFG.js +133 -0
- package/dist/{remote-1Jz2oUMK.js → remote-70ZVZZlq.js} +32 -14
- package/dist/runtime-type-Deo4qzxN.js +9 -0
- package/dist/{session-DD0S1PDC.js → session-e0lyzjJ3.js} +2 -1
- package/dist/size-7AkVwGZb.js +118 -0
- package/dist/ssh.d.ts +8 -0
- package/dist/ssh.js +107 -40
- package/dist/task/index.d.ts +19 -17
- package/dist/task/index.js +92 -201
- package/dist/task/runtime/provider-loader.d.ts +7 -9
- package/dist/task/runtime/provider-loader.js +2 -5
- package/dist/task/runtime/providers/cloudflare.d.ts +5 -19
- package/dist/task/runtime/providers/cloudflare.js +7 -6
- package/dist/task/runtime/providers/vercel.d.ts +3 -3
- package/dist/task/runtime/providers/vercel.js +35 -4
- package/dist/task/runtime/state.d.ts +4 -1
- package/dist/task/runtime/state.js +11 -2
- package/dist/task/vite.d.ts +143 -17
- package/dist/task/vite.js +723 -400
- package/dist/{toolchain-BUVXtQ2m.js → toolchain-BIVGMRty.js} +12 -11
- package/dist/{trusted-host-DNMJ-Oig.js → trusted-host-kxkpaQcs.js} +21 -179
- package/dist/{vercel-Jtxa9TJx.js → vercel-BGGrNpza.js} +107 -34
- package/package.json +15 -12
- package/dist/cloudflare-DO0h3Ncf.js +0 -281
- package/dist/cloudflare-env-BBJaBbuQ.js +0 -39
- package/dist/error-diagnostics-BSysPv-D.js +0 -166
- package/dist/error-diagnostics-dGQqfgLt.js +0 -99
- package/dist/module-types-BfyRBaiP.js +0 -7
- package/dist/module-types-Cis4hrF1.d.ts +0 -95
- package/dist/runtime-type-DrmrW5m5.js +0 -42
package/README.md
CHANGED
|
@@ -15,9 +15,26 @@ pnpm add @vite-hub/sandbox
|
|
|
15
15
|
|
|
16
16
|
## Prepare a trusted-host Sandbox
|
|
17
17
|
|
|
18
|
+
The Sandbox below reads two secrets of the app's Server Env:
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
// vite.config.ts
|
|
22
|
+
import { env, hubEnv } from "@vite-hub/env/vite";
|
|
23
|
+
import { defineConfig } from "vite";
|
|
24
|
+
|
|
25
|
+
export default defineConfig({
|
|
26
|
+
plugins: [hubEnv({
|
|
27
|
+
server: {
|
|
28
|
+
githubToken: env({ secret: true, source: env.source("GITHUB_TOKEN") }),
|
|
29
|
+
codexAuthJson: env({ secret: true, source: env.source("CODEX_AUTH_JSON") }),
|
|
30
|
+
},
|
|
31
|
+
})],
|
|
32
|
+
});
|
|
33
|
+
```
|
|
34
|
+
|
|
18
35
|
```ts
|
|
19
36
|
import { resolveSandbox } from "@vite-hub/sandbox";
|
|
20
|
-
import { useServerEnv } from "
|
|
37
|
+
import { useServerEnv } from "@vite-hub/env";
|
|
21
38
|
|
|
22
39
|
const sandbox = await resolveSandbox({
|
|
23
40
|
runtime: { kind: "trusted-host", stateRoot: "/var/lib/vitehub/sandboxes" },
|
|
@@ -82,12 +99,20 @@ try {
|
|
|
82
99
|
|
|
83
100
|
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
101
|
|
|
85
|
-
|
|
102
|
+
Spawned `vercel` processes stream `stdout` and `stderr` while they run. Consume both streams concurrently, or cancel unused output. Each channel buffers up to 1 MiB; if a log entry would exceed that limit, that stream errors with `SANDBOX_R0159` and discards its queued and subsequent output. The other channel continues streaming. Cancelling both channels stops log streaming without killing the process.
|
|
86
103
|
|
|
87
|
-
|
|
104
|
+
Spawned `cloudflare` processes stream `stdout` and `stderr` through `streamProcessLogs()` with the same 1 MiB per-channel limit and `SANDBOX_R0159` error. A custom `getSandbox` stub without `streamProcessLogs()` returns each channel's full output after the process exits. The built-in Durable Object starts each spawned command in its own process group with bash job control, and `child.kill()`, a `timeout`, or an aborted `signal` signals that whole group, so child processes stop too.
|
|
88
105
|
|
|
89
|
-
|
|
90
|
-
|
|
106
|
+
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. Every trusted-host command starts with the `VITEHUB_SANDBOX_SESSION` environment variable. On Linux, closing the session also stops the processes that have it and left their process group, for example with `setsid`.
|
|
107
|
+
|
|
108
|
+
A `timeout` or an aborted `signal` stops only that command, on every runtime. The Sandbox and its other processes keep running. `exec()` rejects with the abort reason. For `spawn()`, the runtime kills the process and `wait()` rejects with the abort reason.
|
|
109
|
+
|
|
110
|
+
`child.kill(signal)` sends the signal that you name, or rejects. The `vercel` runtime sends `SIGHUP`, `SIGINT`, `SIGQUIT`, `SIGKILL`, `SIGTERM`, `SIGCONT`, `SIGSTOP`, or a signal number. The `cloudflare` runtime sends `SIGALRM`, `SIGHUP`, `SIGINT`, `SIGKILL`, `SIGQUIT`, `SIGTERM`, `SIGUSR1`, `SIGUSR2`, or a signal number. The `crabbox` runtime sends only `SIGTERM`. Other signals reject with `SANDBOX_R0165`.
|
|
111
|
+
|
|
112
|
+
A spawned `SandboxProcess` can also expose `stdin` as a `WritableStream<Uint8Array>`. The `trusted-host` and `crabbox` runtimes always forward it to the process. The `vercel` runtime forwards it only when you pass `stdin: true`, because a command that reads its input then waits until you close the writer. Close the writer to end the process input. Runtimes that cannot forward input leave `stdin` undefined:
|
|
113
|
+
|
|
114
|
+
```ts fragment
|
|
115
|
+
const child = await session.spawn!("node", ["workspace/filter.mjs"], { stdin: true });
|
|
91
116
|
const writer = child.stdin?.getWriter();
|
|
92
117
|
if (!writer) throw new Error("This Sandbox runtime does not forward process input.");
|
|
93
118
|
await writer.write(new TextEncoder().encode("input\n"));
|
|
@@ -98,18 +123,50 @@ console.log(await new Response(child.stdout).text(), await child.wait());
|
|
|
98
123
|
Hosted runtimes use tagged values from the same root API:
|
|
99
124
|
|
|
100
125
|
```ts
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
126
|
+
import { resolveSandbox } from "@vite-hub/sandbox";
|
|
127
|
+
import type { CloudflareDurableObjectNamespace } from "@vite-hub/sandbox";
|
|
128
|
+
|
|
129
|
+
// `namespace` is the Durable Object binding of the Worker, such as `env.SANDBOX`.
|
|
130
|
+
export async function openHostedSandboxes(namespace: CloudflareDurableObjectNamespace) {
|
|
131
|
+
const cloudflare = await resolveSandbox({
|
|
132
|
+
runtime: { kind: "cloudflare", namespace },
|
|
133
|
+
}, {});
|
|
134
|
+
|
|
135
|
+
const vercel = await resolveSandbox({
|
|
136
|
+
runtime: { kind: "vercel", ports: [3000] },
|
|
137
|
+
}, {});
|
|
138
|
+
return { cloudflare, vercel };
|
|
139
|
+
}
|
|
140
|
+
```
|
|
104
141
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
142
|
+
Use `runtime: "vercel"` for the default Vercel Sandbox configuration. Cloudflare remains tag-only because its Durable Objects namespace is required. The Vercel runtime imports `@vercel/sandbox`. Install it in the app, and the server build includes it.
|
|
143
|
+
|
|
144
|
+
The Cloudflare runtime talks to the Sandbox Durable Object that the ViteHub Cloudflare host integration generates. That class starts the Container with the Workers Container API, uses `Files` from `@cloudflare/sandbox` 1.x, preserves Durable Object idle reuse, and the runtime bounds each transport operation with a deadline. It retries only operations that are safe to repeat, such as file reads and full file writes, when Cloudflare marks the error `retryable`. It retries a command or a new process only when the Container was not ready to receive it; other errors keep the Cloudflare flag in `error.data.retryable`. Sessions with the same Sandbox ID share one Container and its files. `open()` does not delete the Home or workspace files of an earlier or concurrent session; only a `checkout` empties the workspace first. A new Container starts with no files. Pass `getSandbox` to use another Durable Object that implements `CloudflareSandboxStub`. Its `cancelExec(id)` must stop the `exec` command that was started with that `id`, and nothing else. 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.
|
|
145
|
+
|
|
146
|
+
Both hosted runtimes take the same `networkPolicy` option for outbound traffic:
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
import { resolveSandbox } from "@vite-hub/sandbox";
|
|
150
|
+
import type { CloudflareDurableObjectNamespace } from "@vite-hub/sandbox";
|
|
151
|
+
|
|
152
|
+
export async function openRestrictedSandbox(namespace: CloudflareDurableObjectNamespace) {
|
|
153
|
+
const sandbox = await resolveSandbox({
|
|
154
|
+
runtime: { kind: "cloudflare", namespace, networkPolicy: { allow: ["registry.npmjs.org", "*.github.com"] } },
|
|
155
|
+
}, {});
|
|
156
|
+
console.log(sandbox.plan.executionAuthority.network); // "restricted"
|
|
157
|
+
return sandbox;
|
|
158
|
+
}
|
|
108
159
|
```
|
|
109
160
|
|
|
110
|
-
|
|
161
|
+
| Value | Outbound traffic | `executionAuthority.network` |
|
|
162
|
+
| --- | --- | --- |
|
|
163
|
+
| `"allow-all"` (default) | All traffic. | `"unrestricted"` |
|
|
164
|
+
| `"deny-all"` | No traffic. | `"none"` |
|
|
165
|
+
| `{ allow: [...] }` | HTTP and HTTPS to the listed hostnames only. Other hosts and protocols fail. | `"restricted"` |
|
|
166
|
+
|
|
167
|
+
`"*.example.com"` matches subdomains of `example.com`, not `example.com` itself. Vercel matches HTTPS hosts by TLS SNI and does not decrypt the traffic. Vercel also takes `subnets` and its other policy forms. On Cloudflare, the generated Worker exports a `SandboxOutbound` entrypoint, and Cloudflare sends HTTP on port 80 and HTTPS on port 443 to an allowed host through it. The entrypoint checks the request host against the list again, because a command can send a `Host` header that differs from the TLS server name. It answers 403 for other hosts. Cloudflare decrypts that HTTPS traffic and signs it again with its own CA. ViteHub sets `NODE_EXTRA_CA_CERTS`, `SSL_CERT_FILE`, `CURL_CA_BUNDLE`, `REQUESTS_CA_BUNDLE`, and `GIT_SSL_CAINFO` on every command, so Node.js, curl, Python requests, and Git trust that CA. Names of other hosts do not resolve. The Cloudflare list takes at most 64 hostnames and no IP addresses. The Worker needs a `compatibility_date` of `2025-11-17` or later.
|
|
111
168
|
|
|
112
|
-
|
|
169
|
+
Cloudflare applies the policy when the Container starts, so each Sandbox ID has one policy at a time, not each container class. When a Sandbox ID that runs opens with another policy, ViteHub stops its Container and the next command starts a new one with the new policy. Files and processes in the old Container are lost. A custom `getSandbox` starts its own Container, so it cannot take `networkPolicy`. An invalid policy throws `SANDBOX_NETWORK_POLICY_INVALID`.
|
|
113
170
|
|
|
114
171
|
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
172
|
|
|
@@ -155,7 +212,7 @@ Requirement names, commands, and argv are inspectable declaration metadata. They
|
|
|
155
212
|
|
|
156
213
|
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
214
|
|
|
158
|
-
```ts
|
|
215
|
+
```ts fragment
|
|
159
216
|
const sandbox = await resolveSandbox({
|
|
160
217
|
runtime: { kind: "trusted-host", stateRoot: "/var/lib/vitehub/sandboxes" },
|
|
161
218
|
checkout: { ref, remote, sha },
|
|
@@ -196,7 +253,7 @@ Cache entries are content-addressed and read-only once published. Global install
|
|
|
196
253
|
|
|
197
254
|
## Run through Crabbox
|
|
198
255
|
|
|
199
|
-
```ts
|
|
256
|
+
```ts fragment
|
|
200
257
|
sandbox: {
|
|
201
258
|
runtime: {
|
|
202
259
|
kind: "crabbox",
|
|
@@ -227,13 +284,40 @@ Commands must remain owned by their Sandbox session. ViteHub adds the reserved `
|
|
|
227
284
|
|
|
228
285
|
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
286
|
|
|
287
|
+
## Run in a caged container
|
|
288
|
+
|
|
289
|
+
```ts fragment
|
|
290
|
+
sandbox: {
|
|
291
|
+
runtime: {
|
|
292
|
+
kind: "container",
|
|
293
|
+
image: "node:24-bookworm",
|
|
294
|
+
egress: { allow: ["registry.npmjs.org"] },
|
|
295
|
+
credentials: {
|
|
296
|
+
GH_TOKEN: { hosts: ["api.github.com", "github.com"], value: () => useServerEnv().githubToken.unseal() },
|
|
297
|
+
},
|
|
298
|
+
memoryBytes: 4 * 1024 ** 3,
|
|
299
|
+
},
|
|
300
|
+
checkout: { ref, remote, sha },
|
|
301
|
+
}
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
Each session starts a new container on an internal Docker network, through the Docker CLI of the ViteHub process. Without `egress`, the container has no network exit. With `egress: { allow }` or `egress: "open"`, a broker container (`mitmproxy/mitmproxy`, pinned) is the only exit. It refuses hosts outside the allowlist at `CONNECT` time and for each request. Credential hosts are always allowed.
|
|
305
|
+
|
|
306
|
+
The Docker daemon must be rootful Docker Engine 28 or newer on native Linux. The isolated bridge has no host address, and the Sandbox has no `NET_RAW` capability. This blocks direct access to host services with or without egress. Docker Desktop, OrbStack, WSL, and rootless Docker have additional host routes outside this boundary and are rejected before resources are created, as are older daemons. The CLI may use a remote native Linux daemon. Host patterns without a port allow only port 443; use `host:port` for another HTTP or HTTPS port. The broker rejects raw TCP tunnels.
|
|
307
|
+
|
|
308
|
+
Credential values resolve on the ViteHub host for each session and reach only the broker, through the Docker CLI environment. They are never on a command line. The Sandbox gets `vitehub-<NAME>-<random>` in each credential variable. The broker replaces it only in HTTPS request headers, including Basic authentication, to a host that the credential lists. A placeholder in a URL, over HTTP, to another host, or from an earlier session gets a `403` with a `SANDBOX_BROKER_B00x` code. The broker logs each request as a JSON line, without query strings. Read them with `docker logs`.
|
|
309
|
+
|
|
310
|
+
The Sandbox trusts the broker certificate through `SSL_CERT_FILE`, `NODE_EXTRA_CA_CERTS`, `GIT_SSL_CAINFO`, `CURL_CA_BUNDLE`, and `REQUESTS_CA_BUNDLE`, and uses `HTTPS_PROXY`, `HTTP_PROXY`, and `NODE_USE_ENV_PROXY=1`. The CA private key stays in the broker. Home is `/vitehub/home` and the workspace is `/vitehub/workspace`. Relative file paths are relative to the workspace. `spawn` forwards input only with `stdin: true`. `kill()` signals the process group in the container. Closing the session removes both containers and the network. Each Docker object has the `dev.vitehub.sandbox` label, so `docker ps -a --filter label=dev.vitehub.sandbox` finds anything that a crashed process left.
|
|
311
|
+
|
|
312
|
+
The image needs `sh`, coreutils, GNU `find`, and `git` for a checkout. The runtime has no ports, no `cwd` mount, and no durable Home state. `cpus`, `memoryBytes`, and `pidsLimit` (default 4096) map to the `docker run` limits, and `user` runs commands as another image user. `docker` selects another Docker CLI.
|
|
313
|
+
|
|
230
314
|
## Bring a custom runtime
|
|
231
315
|
|
|
232
316
|
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
317
|
|
|
234
318
|
## Security boundary
|
|
235
319
|
|
|
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 `
|
|
320
|
+
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`. The built-in `cloudflare` and `vercel` runtimes report `network` from `networkPolicy`: `"unrestricted"` by default, `"none"` for `"deny-all"`, and `"restricted"` for an allowlist. With a custom Cloudflare `getSandbox`, `network` stays `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`, `cloudflare`, or `container` for untrusted code.
|
|
237
321
|
|
|
238
322
|
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
323
|
|
|
@@ -257,37 +341,15 @@ const launch = sshLaunch({
|
|
|
257
341
|
// Pass launch to driver.launch in an Agent Definition.
|
|
258
342
|
```
|
|
259
343
|
|
|
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.
|
|
344
|
+
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. It runs each command with `/bin/sh -c`, not a login shell, so a profile cannot replace the forwarded `PATH`.
|
|
265
345
|
|
|
266
|
-
|
|
346
|
+
A sidecar that is still starting refuses connections. `sshLaunch` connects again for up to `connectRetryMs` (30 seconds by default) while the SSH port refuses connections, so a provider probe or launch right after a pod restart waits for the sidecar. Authentication, host key, and command failures are not retried. Set `connectRetryMs: 0` to fail on the first refused connection.
|
|
267
347
|
|
|
268
|
-
|
|
348
|
+
The launch command includes a cancellable `prepare` callback. Agent Drivers await it before starting provider probe deadlines, for both Codex and Claude. It runs a separate `/bin/true` connection check; direct process consumers can await it before starting their own deadline. OpenSSH local diagnostics are kept separate from remote stderr so a command that starts another failing SSH client is never repeated.
|
|
269
349
|
|
|
270
|
-
|
|
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
|
-
},
|
|
279
|
-
}
|
|
280
|
-
```
|
|
281
|
-
|
|
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.
|
|
350
|
+
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).
|
|
289
351
|
|
|
290
|
-
|
|
352
|
+
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. When a command ends, the server stops its process group. On Linux it also stops the processes that the command started outside that group, for example with `setsid`. It finds them by the `VITEHUB_SSH_COMMAND` environment variable. `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.
|
|
291
353
|
|
|
292
354
|
## Sandbox Tasks
|
|
293
355
|
|
|
@@ -303,13 +365,13 @@ Install Sandbox, TypeScript, Vite, and the Sandbox provider used by your deploym
|
|
|
303
365
|
pnpm add @vite-hub/sandbox typescript @vercel/sandbox vite
|
|
304
366
|
```
|
|
305
367
|
|
|
306
|
-
Sandbox Task requires Node.js
|
|
368
|
+
Sandbox Task requires Node.js 22.18 or newer. The Vercel provider accepts `@vercel/sandbox` 3.9 and 4. Version 4 requires Node.js 22.19 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
369
|
|
|
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.
|
|
370
|
+
For Cloudflare, install `@cloudflare/sandbox` 1.x 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
371
|
|
|
310
372
|
### Run one Sandbox Task
|
|
311
373
|
|
|
312
|
-
Register discovery and select the
|
|
374
|
+
Register discovery and select the driver in Vite:
|
|
313
375
|
|
|
314
376
|
```ts
|
|
315
377
|
// vite.config.ts
|
|
@@ -317,7 +379,7 @@ import { hubSandboxTask } from "@vite-hub/sandbox/task/vite";
|
|
|
317
379
|
import { defineConfig } from "vite";
|
|
318
380
|
|
|
319
381
|
export default defineConfig({
|
|
320
|
-
plugins: [hubSandboxTask({
|
|
382
|
+
plugins: [hubSandboxTask({ driver: "vercel" })],
|
|
321
383
|
build: {
|
|
322
384
|
ssr: "src/server.ts",
|
|
323
385
|
},
|
|
@@ -349,7 +411,7 @@ export default async function releaseNotes(payload: ReleaseNotesPayload = {}) {
|
|
|
349
411
|
}
|
|
350
412
|
```
|
|
351
413
|
|
|
352
|
-
Invoke the discovered name from server code. `runSandboxTask()` returns a native Web `Response` and infers its payload from the Definition:
|
|
414
|
+
Invoke the discovered name from server code. `runSandboxTask()` returns a native Web `Response` and infers its payload from the Definition. A registered handler with a required payload requires that argument at invocation; optional and zero-argument handlers can be invoked without it. The handler's context defaults to `{}` when omitted:
|
|
353
415
|
|
|
354
416
|
```ts
|
|
355
417
|
// src/server.ts
|
|
@@ -381,11 +443,14 @@ The Definition entrypoint does not import `@vite-hub/sandbox/task`. ViteHub call
|
|
|
381
443
|
|
|
382
444
|
### Provider and lifecycle limits
|
|
383
445
|
|
|
384
|
-
-
|
|
385
|
-
-
|
|
446
|
+
- Set `cpu` (vCPUs) and `memory` (MiB) next to `driver`, such as `hubSandboxTask({ driver: "cloudflare", cpu: 1, memory: 4096 })`. They are minimums, and ViteHub picks the smallest driver size that fits both. Vercel gets `resources.vcpus`: 1 or an even number up to 32, with 2048 MiB for each vCPU. Cloudflare gets the smallest instance type from `lite` to `standard-4`, and the default is `standard-1` (1/2 vCPU, 4096 MiB). On Cloudflare the size belongs to the Container class, so it applies to every task of the app. ViteHub keeps the `instance_type` of your own `containers` entry and fails the build when it is smaller than `cpu` or `memory`. `maxInstances` sets the Cloudflare Container limit (default 12).
|
|
447
|
+
- Driver selection belongs to application or host configuration, not to a Definition. `hubSandboxTask({ driver: "vercel" })` and `hubSandboxTask({ driver: "cloudflare" })` are the direct-package forms. The `vite-hub` distribution infers the driver from its Vercel and Cloudflare hosts, and takes the same options in `vitehub({ sandboxTask: { ... } })`.
|
|
448
|
+
- `vitehub.sandboxTask.timeout` must be a positive integer no greater than `2_147_483_647`. Without it, a run stops after 5 minutes on every driver. It bounds one execution attempt after driver 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 driver operations and returns a `SANDBOX_TASK_TIMEOUT` error in a non-2xx JSON response. On Vercel, the Sandbox session gets the task timeout plus 30 seconds, because its clock starts before Sandbox setup. ViteHub then ends the run at the task timeout, not the VM.
|
|
386
449
|
- 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
|
-
-
|
|
388
|
-
-
|
|
450
|
+
- A failed run's JSON response keeps `error.code`, `error.message`, and `error.details`. Outside `vite dev`, the details do not include `stack`, `stdout`, `stderr`, their previews, `output`, `cause`, `cwd`, or `args`. `resolveSandboxTaskRunner(name).run()` throws the error with all details for server logs.
|
|
451
|
+
- 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 return a non-2xx JSON response, even after a successful handler. So do Cloudflare invocation-file cleanup failures in a Sandbox that stays open after the run. A Sandbox that ViteHub closes after the run loses its files when it closes, so ViteHub does not delete them separately.
|
|
452
|
+
- Cloudflare can retry the whole Task before its first command starts. After that, only the transport retries an individual command when a cold start proves it did not run. Handler errors do not replay the Task.
|
|
453
|
+
- 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. ViteHub leaves an explicitly named Sandbox for idle shutdown after every run, also after a timeout or an abort. A timeout or an abort stops only that run's command, so runs from other isolates keep their Container. `sleepAfter` sets the idle time (default `"5m"`), and `keepAlive: true` raises it to the 6 hour Cloudflare maximum. A Sandbox without an ID still closes after each run, also with `keepAlive: true`.
|
|
389
454
|
|
|
390
455
|
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
456
|
|
|
@@ -402,7 +467,7 @@ const runner = await resolveSandboxTaskRunner("release-notes");
|
|
|
402
467
|
console.log(runner.executionAuthority);
|
|
403
468
|
```
|
|
404
469
|
|
|
405
|
-
The descriptor reports the provider's complete `ExecutionAuthority`, including dimensions it cannot establish as `unknown`.
|
|
470
|
+
The descriptor reports the provider's complete `ExecutionAuthority`, including dimensions it cannot establish as `unknown`. Set `networkPolicy` in the `vercel` or `cloudflare` provider options to limit outbound traffic, keep secrets in server environment or provider configuration, and do not treat container execution alone as authorization for untrusted code.
|
|
406
471
|
|
|
407
472
|
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
473
|
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
//#region src/internal/abortable.ts
|
|
2
|
+
/**
|
|
3
|
+
* Wait for a promise until the caller's signal aborts.
|
|
4
|
+
*
|
|
5
|
+
* The underlying operation is intentionally not cancelled. This helper only
|
|
6
|
+
* stops waiting for it and rejects with the signal reason.
|
|
7
|
+
*/
|
|
8
|
+
function abortable(promise, signal) {
|
|
9
|
+
if (!signal) return promise;
|
|
10
|
+
signal.throwIfAborted();
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
const onAbort = () => {
|
|
13
|
+
signal.removeEventListener("abort", onAbort);
|
|
14
|
+
reject(signal.reason);
|
|
15
|
+
};
|
|
16
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
17
|
+
promise.then((value) => {
|
|
18
|
+
signal.removeEventListener("abort", onAbort);
|
|
19
|
+
resolve(value);
|
|
20
|
+
}, (error) => {
|
|
21
|
+
signal.removeEventListener("abort", onAbort);
|
|
22
|
+
reject(error);
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Kills a started process when the signal aborts, so a timeout or cancellation stops only that command.
|
|
28
|
+
* After an abort, `wait()` rejects with the signal reason.
|
|
29
|
+
*/
|
|
30
|
+
function killOnAbort(process, signal) {
|
|
31
|
+
if (!signal) return process;
|
|
32
|
+
let killed;
|
|
33
|
+
const abort = () => {
|
|
34
|
+
killed = process.kill("KILL").catch(() => void 0);
|
|
35
|
+
};
|
|
36
|
+
if (signal.aborted) abort();
|
|
37
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
38
|
+
const exit = process.wait().finally(() => signal.removeEventListener("abort", abort));
|
|
39
|
+
exit.catch(() => void 0);
|
|
40
|
+
return {
|
|
41
|
+
pid: process.pid,
|
|
42
|
+
stderr: process.stderr,
|
|
43
|
+
get stdin() {
|
|
44
|
+
return process.stdin;
|
|
45
|
+
},
|
|
46
|
+
stdout: process.stdout,
|
|
47
|
+
kill: async (signal) => await process.kill(signal),
|
|
48
|
+
async wait() {
|
|
49
|
+
const result = await exit;
|
|
50
|
+
if (!killed) return result;
|
|
51
|
+
await killed;
|
|
52
|
+
throw signal.reason;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
export { killOnAbort as n, abortable as t };
|