# ClientVM documentation > A dev machine for every AI agent, inside a browser tab. ClientVM runs Node.js 24, a real bash and the unmodified npm in the browser. Each agent gets isolated instances with their own filesystem, processes and network, runs npm install and npm run dev, and previews the app it built. No containers, no servers to pay for. Source: https://github.com/Reflex-Gravity/client-vm. Each section below is one page of https://clientvm.joeldsouza.me/docs/, also served on its own at the URL given. --- # Overview **A dev machine for every AI agent, inside a browser tab.** ClientVM runs Node.js 24, a real `bash` and the unmodified `npm` entirely in the browser. Each agent gets isolated instances with their own filesystem, processes and network. It runs `npm install` and `npm run dev` and previews the app it built, with no containers and no servers to pay for. [Quickstart](https://clientvm.joeldsouza.me/docs/quickstart.md) · [Hosting](https://clientvm.joeldsouza.me/docs/hosting.md) · [API reference](https://clientvm.joeldsouza.me/docs/interfaces.md) · [Live demo](https://clientvm.joeldsouza.me/) · [GitHub](https://github.com/Reflex-Gravity/client-vm) ```sh npm install @clientvm/clientvm @clientvm/terminal ``` ![Your page holds the ClientVM controller, your UI and the terminal and agent tools. Each instance is a hidden iframe on its own sandbox origin, where a kernel worker owns an in-memory filesystem and runs node, bash and other tools as Web Workers that make synchronous syscalls over SharedArrayBuffer. A service worker routes module loads and preview requests to the kernel, and each open port is previewed on its own origin.](https://clientvm.joeldsouza.me/docs/diagrams/overview.svg) ## Choose your path - **Run code an agent writes.** Boot an instance, give it files, run `exec` and `spawn`, and show the preview. Start with the [quickstart](https://clientvm.joeldsouza.me/docs/quickstart.md). - **Give an LLM a computer.** `@clientvm/agent-api` turns an instance into tool definitions for files, commands, dev servers and driving the preview. See the [agent tool API](https://clientvm.joeldsouza.me/docs/agent-api.md). - **Show users what is running.** `@clientvm/terminal` attaches an interactive `bash`, or a read-only feed of the agent's commands, to any xterm.js-compatible terminal ([terminal README](https://github.com/Reflex-Gravity/client-vm/blob/main/packages/terminal/README.md)). - **Understand the sandbox before you trust it.** Read [how it works](https://clientvm.joeldsouza.me/docs/architecture.md) and the [security model](https://clientvm.joeldsouza.me/docs/security.md). ## Quick start ```ts import { createClientVM } from '@clientvm/clientvm'; const vm = createClientVM({ sandboxOrigin: (id) => `https://${id}.myapp-sandbox.dev` }); const app = await vm.createInstance({ preset: 'vite-react-ts' }); app.onPortOpen((port, url) => (preview.src = url)); await app.spawn('npm', ['run', 'dev'], { cwd: '/home/user/app' }); ``` - `createClientVM` creates the **controller** on your page. `sandboxOrigin` says where the [sandbox you deploy](https://clientvm.joeldsouza.me/docs/hosting.md) answers for each instance. - `createInstance` boots an **instance**. The `vite-react-ts` preset is a ready Vite + React + TypeScript project with `node_modules` installed. It is built once and then boots in about 0.2 s. - `onPortOpen` reports the preview URL when a server inside the instance starts listening. - `spawn` starts a process and streams its output. `exec` runs a command line to completion. The [quickstart](https://clientvm.joeldsouza.me/docs/quickstart.md) walks through each step, including the terminal and the agent tools. ## How ClientVM works 1. **Your page runs the controller.** It is the only trusted part. It boots each instance in a hidden iframe on a sandbox origin of its own and checks every message that comes back. 2. **Each instance is a small operating system.** A kernel worker owns an in-memory filesystem, a process table, terminals, signals and virtual ports. Every process (`node`, `bash`, `npm`, `vite`) is a Web Worker. Blocking calls such as `fs.readFileSync` really block, on a `SharedArrayBuffer`, while the kernel answers. 3. **Servers become private previews.** When a process listens on a port, the instance's service worker routes requests from a preview iframe to it, on an origin of its own. Read [how it works](https://clientvm.joeldsouza.me/docs/architecture.md) for the details, with diagrams. ## What ClientVM supports | | | |---|---| | **Runtime** | Node.js 24 APIs: `fs`, streams, `http`/`net` on virtual ports, `child_process`, `worker_threads`, `crypto`, `zlib`, CommonJS and native ESM. 592 of Node's own tests pass in CI ([compatibility matrix](https://clientvm.joeldsouza.me/docs/compatibility.md)) | | **Package managers** | The unmodified npm 11 and pnpm 10, fetched and verified on first use | | **Tooling** | Stock Vite 6 and Vite 8 with HMR, React, Tailwind CSS 4, Express, `git` (on isomorphic-git) | | **Shell** | `sh`/`bash` with pipes, job control, an interactive mode and about 60 Linux commands | | **Isolation** | One browser origin per instance and per preview port; capabilities between instances | | **Browser** | Chromium. Your app needs no COOP/COEP headers | | **Not supported** | Safari and Firefox, native Node addons (other than the WebAssembly stand-ins), Python and other languages, raw TCP/UDP, outbound requests that CORS blocks | ## Using a coding agent? Every docs page is also served as Markdown: add `.md` to its URL, or start from [`/llms.txt`](https://clientvm.joeldsouza.me/llms.txt). All the docs in one file are at [`/llms-full.txt`](https://clientvm.joeldsouza.me/llms-full.txt). The landing page's **Copy agent prompt** button puts a ready integration prompt on your clipboard. ## Next steps - **Deploy the sandbox:** the [hosting guide](https://clientvm.joeldsouza.me/docs/hosting.md) covers the domain, headers and a deployment check. - **Look up an API:** the [API reference](https://clientvm.joeldsouza.me/docs/interfaces.md). - **Why is it built this way?** The [design decisions](https://clientvm.joeldsouza.me/docs/decisions.md), summarised on one page. --- # Quickstart Add ClientVM to a web app: deploy the sandbox once, boot an instance, run a dev server inside it and show its preview. Then add a terminal and hand the instance to an agent. > [!NOTE] > ClientVM runs in **Chromium-based browsers** (Chrome, Edge, Arc, Brave). To try it without > setting anything up, open the [live demo](https://clientvm.joeldsouza.me/). ## 1. Deploy the sandbox Instances run on a static sandbox: the files of `@clientvm/sandbox-host`, served on a wildcard subdomain of a **separate registrable domain** such as `*.myapp-sandbox.dev`. Each instance and each preview port gets its own subdomain, so the browser keeps agent code away from your app and from other instances. ```sh npm install -D @clientvm/sandbox-host # deploy node_modules/@clientvm/sandbox-host/dist to *.myapp-sandbox.dev ``` Serve these headers on every response, plus `Service-Worker-Allowed: /` on `/__clientvm/sw.js`: ``` Document-Isolation-Policy: isolate-and-require-corp Cross-Origin-Embedder-Policy: require-corp Cross-Origin-Resource-Policy: cross-origin Content-Security-Policy: frame-ancestors https://myapp.example ``` Then check the deployment: ```sh npx clientvm-check-sandbox 'https://{id}.myapp-sandbox.dev' --app https://myapp.example ``` > [!TIP] > The [hosting guide](https://clientvm.joeldsouza.me/docs/hosting.md) explains each requirement and shows a scheme that needs only > one wildcard certificate. ## 2. Install the runtime ```sh npm install @clientvm/clientvm ``` Your own app needs **no** special headers: no COOP, no COEP. ## 3. Create a controller and an instance ```ts import { createClientVM } from '@clientvm/clientvm'; const vm = createClientVM({ sandboxOrigin: (id) => `https://${id}.myapp-sandbox.dev` }); // Start from your own files… const instance = await vm.createInstance({ fs: { from: { home: { user: { app: { 'index.js': "console.log('hi')" } } } } }, limits: { maxProcesses: 64, maxCpuMs: 30_000 }, }); // …or from a ready Vite 8 + React 19 + TypeScript project with node_modules installed. const app = await vm.createInstance({ preset: 'vite-react-ts' }); ``` - **`preset`** builds the project once, in about 10 s, in a hidden instance. The result is kept in your origin's Cache Storage, so every later instance boots from it in about 0.2 s with no downloads ([why](https://clientvm.joeldsouza.me/docs/decisions/0018-presets-cached-on-host-origin.md)). - **`limits`** caps what the instance can use. Agent code is treated as hostile, so set them. - **Persistence:** add `fs: { persist: true }` and a fixed `id` to keep an instance's files across reloads. ## 4. Run commands and show the preview ```ts const { code, stdout } = await instance.exec('node index.js', { cwd: '/home/user/app' }); app.onPortOpen((port, url) => { previewIframe.src = url; // https://-p5173.myapp-sandbox.dev/ }); await app.spawn('npm', ['run', 'dev'], { cwd: '/home/user/app' }); ``` - `exec` runs a shell command line to completion and returns its exit code and output. - `spawn` returns a process with streaming `stdout`/`stderr`, `stdin`, `kill()` and `exit`. - `onPortOpen` fires when a server starts listening. The URL is private to this browser tab. - `instance.fs` reads and writes the instance's files from your page. ## 5. Add a terminal `@clientvm/terminal` attaches a real interactive `bash` to any xterm.js-compatible terminal. You choose the terminal emulator; it is not a dependency. ```ts import { Terminal } from '@xterm/xterm'; import { attachShell, attachActivityView } from '@clientvm/terminal'; const term = new Terminal(); term.open(element); await attachShell(term, app, { cwd: '/home/user/app' }); // history, Tab completion, Ctrl+C, job control // Or a read-only feed of what the agent runs: attachActivityView(agentTerm, app, { filter: (p) => p.tag?.['source'] === 'agent' }); ``` ## 6. Hand it to an agent `@clientvm/agent-api` turns an instance into LLM tool definitions: files, `exec`, background processes, driving the preview, screenshots, the mailbox and child instances. ```ts import { createAgentTools } from '@clientvm/agent-api'; const tools = createAgentTools({ instance: app }); // Send tools.definitions as `tools` to the model; run each tool_use block through // tools.call(block.name, block.input) and return the result as a tool_result. ``` > [!IMPORTANT] > Keep your model API key on your server. Run the model call there and relay tool calls to the > page that owns the `ClientVM`. The [agent tool API](https://clientvm.joeldsouza.me/docs/agent-api.md) has a complete loop. ## Next steps - **How it fits together:** [how ClientVM works](https://clientvm.joeldsouza.me/docs/architecture.md), with diagrams. - **Look up an API:** the [API reference](https://clientvm.joeldsouza.me/docs/interfaces.md). - **Check a Node API before relying on it:** the [compatibility matrix](https://clientvm.joeldsouza.me/docs/compatibility.md). - **Run it from a checkout:** the [README](https://github.com/Reflex-Gravity/client-vm/blob/main/README.md#try-it-locally) starts a local sandbox and an agent playground. --- # Hosting the sandbox ClientVM needs one static deployment of the sandbox: the files in `@clientvm/sandbox-host`'s `dist/`. It must be reachable at every instance origin `https://./`. No server-side code runs, and your own app needs no changes to its headers. ![Your app stays on its own domain and needs no special headers. The sandbox is one static deployment of @clientvm/sandbox-host on a wildcard subdomain of a separate registrable domain, with one subdomain per instance and one per preview port. Every sandbox response carries Document-Isolation-Policy, COEP, CORP and a frame-ancestors CSP. The two domains are cross-site.](https://clientvm.joeldsouza.me/docs/diagrams/hosting.svg) **At a glance:** 1. Pick a **separate registrable domain** for the sandbox, such as `myapp-sandbox.dev`. 2. Point **wildcard DNS and TLS** for `*.myapp-sandbox.dev` at one static deployment. 3. Upload `@clientvm/sandbox-host`'s `dist/` and set the [response headers](#requirements). 4. Run `clientvm-check-sandbox` against it. 5. Pass `sandboxOrigin` to `createClientVM` in your app. ```sh npm install -D @clientvm/sandbox-host # deploy node_modules/@clientvm/sandbox-host/dist, then check it: npx clientvm-check-sandbox 'https://{id}.myapp-sandbox.dev' --app https://myapp.example ``` From a checkout of this repository, `pnpm --filter @clientvm/sandbox-host build` writes the same files to `packages/sandbox-host/dist`. ## Why subdomains The browser's unit of isolation is the origin. ClientVM gives each instance its own, so the browser itself keeps agent code apart: - **One origin per instance** (`k3x9.myapp-sandbox.dev`). Each instance's storage, service worker and windows are its own, out of reach of your app and of every other instance ([ADR 0003](https://clientvm.joeldsouza.me/docs/decisions/0003-kernel-per-instance-origin.md)). - **One origin per preview port** (`k3x9-p5173.myapp-sandbox.dev`). A dev server inside an instance is served on its own origin by that origin's service worker, so its pages are isolated too ([ADR 0008](https://clientvm.joeldsouza.me/docs/decisions/0008-sub-origin-per-port.md)). - **A wildcard, because ids are made at runtime.** Instances and ports come and go; the deployment must answer for any subdomain without a list. - **A separate registrable domain.** Under your app's domain (`sandbox.myapp.com`) instance code would be same-site with your app: it could set cookies on `.myapp.com` and send same-site requests that carry your users' credentials. A domain of its own (`myapp-sandbox.dev`) is cross-site. - **The headers** make each instance page cross-origin isolated through Document-Isolation-Policy. That is what lets `fs.readFileSync` block on `SharedArrayBuffer` and `Atomics.wait`, and why your app needs no COOP/COEP headers ([ADR 0005](https://clientvm.joeldsouza.me/docs/decisions/0005-document-isolation-policy.md)). ## Requirements > [!WARNING] > Never serve the sandbox from a subdomain of your app's domain. Instance code would be > same-site with your app. 1. **A dedicated registrable domain** for the sandbox, separate from your app's (for example `myapp-sandbox.dev`, not `sandbox.myapp.com`). Instances run hostile code, so they must not be same-site with your app. 2. **Wildcard DNS and TLS** for `*.`, serving the same static files for every subdomain. Instance ids are DNS labels (`[a-z0-9-]`, up to 63 chars). 3. **No cookies, ever,** on the sandbox domain, and no authenticated endpoints. Consider adding the domain to the [Public Suffix List](https://publicsuffix.org/) so each instance becomes its own site to the browser. 4. **Response headers on every response** from instance origins: ``` Document-Isolation-Policy: isolate-and-require-corp Cross-Origin-Embedder-Policy: require-corp Cross-Origin-Resource-Policy: cross-origin Content-Security-Policy: frame-ancestors https://your-app.example ``` `frame-ancestors` should list the app origins allowed to embed instances. The handshake is already origin-checked; this is defense in depth. 5. **For the service worker script** (`/__clientvm/sw.js`), also send `Service-Worker-Allowed: /` so it can control the whole instance origin. Serve it with `Cache-Control: no-cache` so updates are picked up. 6. **Keep everything under `/__clientvm/`.** The instance service worker forwards every other path on an instance origin to the instance's own virtual servers, which serve its previews. The development and preview servers (`packages/sandbox-host/vite.config.ts`) apply these headers to `*.localhost`. Set `CLIENTVM_FRAME_ANCESTORS` to add the CSP header. ## Check your deployment ```sh npx clientvm-check-sandbox 'https://{id}.myapp-sandbox.dev' --app https://myapp.example ``` From a checkout, `node scripts/check-sandbox-headers.mjs` runs the same check. It requests an instance page, the service worker and a port origin on random subdomains and fails if a requirement above is not met (it warns when `frame-ancestors` is missing). ## Flat sandbox names `sandboxOrigin` maps a label to an origin. The label is either an instance id or a port label, `-p`. It doesn't have to be the first DNS label of a dedicated domain. A suffix works too: ```ts createClientVM({ sandboxOrigin: (label) => `https://${label}-cvm.example.dev` }); ``` Instances then live at `https://-cvm.example.dev` and previews at `https://-p5173-cvm.example.dev`. Everything stays one level below the zone, so a single wildcard certificate (`*.example.dev`) and one wildcard DNS record cover every origin. The project's own demo uses this scheme on Cloudflare (`deploy/sandbox-worker`). A flat scheme only works under a domain that is itself dedicated to the sandbox, or one with no cookies and no authenticated endpoints anywhere on it. Every origin it creates is same-site with the rest of that domain (see the [security model](https://clientvm.joeldsouza.me/docs/security.md)). ## In your app ```ts import { createClientVM } from '@clientvm/clientvm'; const vm = createClientVM({ sandboxOrigin: (id) => `https://${id}.myapp-sandbox.dev` }); const instance = await vm.createInstance({ fs: { from: { 'index.js': "console.log('hi')" } } }); ``` > [!TIP] > Your app needs **no** special headers. If your app already uses COOP/COEP, instances still work > (fallback mode). ## Previews When a server inside an instance opens a port, `instance.onPortOpen((port, url) => ...)` reports the port's own origin, `https://-p./` (ADR 0008). The same wildcard deployment serves it: the controller embeds `/__clientvm/port.html` there to link that origin's service worker to the instance. Load the URL in an iframe to show the preview. Previews are private: they only resolve inside the browser tab that runs the instance. The service worker adds a module script, `/__clientvm/ws-shim.js`, to HTML pages on port origins: browsers do not let service workers see WebSockets, so the shim carries same-origin (and `localhost`) WebSockets to the server through the service worker. Port origins get the same headers as instance origins; preview responses themselves carry only the app server's headers. --- # How ClientVM works ClientVM behaves like a small operating system that lives in a browser tab. This page follows that system from the outside in: who runs where, how a blocking call works without a server, how a dev server becomes a preview, and how instances stay apart. For a package-by-package tour see [packages](https://clientvm.joeldsouza.me/docs/packages.md); for the reasoning behind each choice see the [design decisions](https://clientvm.joeldsouza.me/docs/decisions.md). ![Your page holds the controller, your UI and the terminal and agent tools. Each instance is a hidden iframe on its own sandbox origin, where a kernel worker owns an in-memory filesystem and runs node, bash and other tools as Web Workers. A service worker routes module loads and preview requests to the kernel. Each open port is previewed on its own origin.](https://clientvm.joeldsouza.me/docs/diagrams/overview.svg) ## The pieces | Piece | Where it runs | What it does | |---|---|---| | **Controller** (`@clientvm/clientvm`) | Your page, on your origin | Boots instances, checks every message they send, and brokers everything between them: capabilities, mailbox, forks, presets. It never runs agent code | | **Instance page** (`@clientvm/sandbox-host`) | A hidden iframe on `https://.` | Cross-origin isolated by Document-Isolation-Policy. Registers the service worker, then starts the kernel | | **Kernel worker** (`@clientvm/kernel`, `@clientvm/vfs`) | A dedicated worker under the instance page | Owns the instance: filesystem, process table, file descriptors, terminals, signals, virtual network, limits | | **Process workers** (`@clientvm/process` + a runtime) | One nested worker per process | Run `node`, `sh`, `npm`, `vite` and your scripts, talking to the kernel through syscalls | | **Service worker** (`@clientvm/sandbox-host`) | The instance origin and each port origin | Serves ES modules to processes and routes preview requests to virtual ports | > [!NOTE] > The **trust boundary** sits between the controller and the instance page. Everything on the > sandbox side treats its input as hostile, and so does the controller towards the sandbox. See > the [security model](https://clientvm.joeldsouza.me/docs/security.md). ## Instances An instance is the unit of isolation: one filesystem, one process table, one network namespace and one budget. The controller creates it as a hidden iframe on its own subdomain, and the browser's origin model does the isolating. Instances cannot see each other's storage, channels or service workers, because they are different origins ([ADR 0003](https://clientvm.joeldsouza.me/docs/decisions/0003-kernel-per-instance-origin.md)). The handshake checks the exact window and origin on both sides. Then the controller and the kernel talk over a single `MessagePort`: the kernel serves `InstanceRpc` (spawn, filesystem, snapshot, grants), and calls back with `ControllerRpc` for things only the controller may do (`mailboxSend`, `netFetch`). Crashed instances are detected by a heartbeat and torn down. ## Processes Every process is a Web Worker, started by the kernel. The runtime it runs is chosen the way Linux chooses a program: **commands are files**. - Built-in runtimes are marker files in `/usr/local/bin` (`#!/clientvm/builtin node`). - The kernel resolves `argv[0]` like `execve`: `PATH` lookup, exec bits, shebang interpreters. So `node_modules/.bin` symlinks and `#!/usr/bin/env node` scripts just work. - Child processes go through the kernel. `spawnSync` is a syscall that blocks the caller until the child exits. Killing a process also kills its descendants, like a signal to a process group. The shell is a runtime too. Its builtins and its ~60 Linux commands (`ls`, `grep`, `sed`, …) run **inside the shell's worker**, so a loop over a thousand files costs microseconds per iteration, not a worker spawn each time. Anything else (`node`, scripts, `.bin` shims) is spawned through the kernel ([ADR 0011](https://clientvm.joeldsouza.me/docs/decisions/0011-in-process-shell-commands.md)). Processes can run on a **pseudo-terminal**: `isatty()` is true, Ctrl+C sends SIGINT to the foreground job, raw mode works for full-screen programs, and resizes send SIGWINCH. Signals are delivered to handlers, with a 1 s grace period before a stuck process is terminated ([ADR 0017](https://clientvm.joeldsouza.me/docs/decisions/0017-pty-and-signals.md)). ## Synchronous syscalls Node's synchronous APIs (`fs.readFileSync`, `execSync`, `require`) must block until the answer arrives. Browsers do allow a worker to block, on a `SharedArrayBuffer` with `Atomics.wait`, but only in a cross-origin isolated context. That is why the instance page needs its headers. ![A process calls fs.readFileSync, writes the request into its shared channel and blocks in Atomics.wait. The kernel, parked with Atomics.waitAsync, wakes, reads the file from the in-memory filesystem, writes the reply and notifies. The process wakes and copies the bytes out. About 10 microseconds per round trip.](https://clientvm.joeldsouza.me/docs/diagrams/syscall.svg) 1. node-compat resolves the path against the process's working directory and encodes the arguments with a compact binary codec. 2. `SyscallClient.call(op, bytes)` writes a header and the payload into the process's channel, sets `STATE = REQUEST`, calls `Atomics.notify`, then blocks in `Atomics.wait`. 3. The kernel's `SyscallServer` wakes from `Atomics.waitAsync` ([ADR 0002](https://clientvm.joeldsouza.me/docs/decisions/0002-syscall-wake-mechanism.md)), decodes the request and calls the filesystem. 4. It writes the response (or an `ERRNO`), sets `STATE = RESPONSE` and notifies. 5. The process copies the response out of shared memory and maps a non-zero errno to a Node-shaped `SystemError`. Payloads larger than the 256 KiB channel are streamed in chunks, so the buffer never grows. Handlers may return a Promise, which leaves room for slower backends; the blocked process doesn't care how long the kernel takes.
The channel layout | Int32 slot | Meaning | |---|---| | 0 `STATE` | 0 idle, 1 request posted, 2 response ready | | 1 `OP` | syscall opcode (≥ 0) or channel opcode (< 0) | | 2 `LEN` | payload bytes in this message | | 3 `ERRNO` | positive errno on failure, else 0 | | 4 `TOTAL` | total bytes of the request or response being streamed | | 5–7 | reserved | Then come `capacity` payload bytes. Large transfers use the channel opcodes `REQUEST_MORE` and `RESPONSE_MORE`.
## The filesystem Each instance has an in-memory filesystem with Linux semantics: inodes, symlinks, hard links, file descriptors, quotas, watchers and copy-on-write snapshots. Syscalls never touch slower storage. Instances created with `fs: { persist: true }` are written behind to the instance origin's OPFS, debounced, crash-safe and content-addressed ([ADR 0004](https://clientvm.joeldsouza.me/docs/decisions/0004-memory-first-vfs-opfs-persistence.md)). ## Loading modules Processes load ES modules with the browser's native `import()` from `/__clientvm/fs/`. The service worker sends each request to the kernel's module server, which resolves specifiers with Node's ESM algorithm (`exports`, `imports`, conditions), rewrites them to such URLs, and serves CommonJS files as ES facades with the same named exports Node would detect. Live bindings, cycles and top-level await therefore behave natively ([ADR 0006](https://clientvm.joeldsouza.me/docs/decisions/0006-native-esm-via-service-worker.md)). The instance page starts the kernel only once the service worker controls it, so every process worker is controlled too. ## Servers and previews Servers listen on **virtual ports** in the kernel's network stack. Inside the instance, `http://localhost:5173/` reaches them. From your page, each port gets its own origin. ![Your page loads the preview URL in an iframe. The port origin's service worker forwards each request over a MessagePort to the kernel's HTTP router, which relays it to the process listening on that port. The response streams back.](https://clientvm.joeldsouza.me/docs/diagrams/preview.svg) 1. A process calls `listen(5173)`. The controller embeds a small bridge page on `https://-p5173./`, which links that origin's service worker to the kernel, then reports the URL through `onPortOpen`. 2. Your page loads the URL in an iframe. The service worker forwards every request (except `/__clientvm/*`) to the kernel. 3. The kernel's HTTP router relays the request to the owning process as messages, and the response streams back as a transferred `ReadableStream`. A port gets its own origin because dev servers emit absolute URLs (`/@vite/client`, `/assets/x.js`) that would break under a path prefix, and because preview code should not share an origin with the kernel ([ADR 0008](https://clientvm.joeldsouza.me/docs/decisions/0008-sub-origin-per-port.md)). Service workers cannot see WebSockets, so the service worker injects a small shim into HTML pages that carries them to the server's `upgrade` handler. ## Many instances Everything that crosses instances goes through the controller, and needs a **capability** granted by the instance it concerns: | Capability | Lets an instance… | |---|---| | `channel` | send mailbox messages to a peer | | `net` | reach a peer's ports at `http://.internal:/` | | `mount` | mount a peer's directory read-only | | `spawn-instance` | create child instances and forks, within limits | `fork()` exports the filesystem as an image, transfers it, and imports it on the new origin. Snapshots inside one instance stay copy-on-write. ## How the packages depend on each other ``` protocol ◄── vfs ◄── kernel ▲ ├──── process ◄── node-compat └──── (all) ◄── sandbox-host (composes kernel + process + node-compat into worker entries) clientvm (controller) ── protocol (types + RpcEndpoint only; never bundles kernel code) ``` The process package does not depend on node-compat. Runtimes are injected as a `RuntimeTable` by the worker entry in sandbox-host, which keeps process tiers (`js`, `builtin`, later `wasi`/`vm`) pluggable. ## For contributors - Sources import siblings with `.ts` extensions. `tsc` rewrites them to `.js` (`rewriteRelativeImportExtensions`), and Node 24 can run the sources directly through type stripping (`erasableSyntaxOnly`). This is how the channel tests run real worker threads. - Each package's `exports` has a `@clientvm/source` condition pointing at `src/index.ts`. Vite and Vitest resolve it, so neither needs a prior build. Published consumers get `dist/`. --- # Security model and threat model ClientVM runs code written by AI agents and code from arbitrary npm packages. **All of it is treated as hostile.** This document must stay current. Every PR that changes a trust boundary updates it. ## Assets 1. **Host app origin.** Its cookies, storage, credentials, and DOM. The most important asset. 2. **Other instances.** Their filesystems, processes, network ports, and mailboxes. 3. **The user's browser tab.** Memory, CPU, and responsiveness. 4. **The user's network position.** Requests sent from the user's browser and IP. ## Adversaries - Agent-generated code running in a process, including code an attacker prompt-injected into the agent. - Malicious or compromised npm packages (install scripts and runtime code). - Content inside a preview iframe, such as a generated app that loads third-party scripts. ## Trust boundaries ``` Host app + controller (trusted, app origin, never runs instance code) ║ handshake via postMessage: exact source window + origin checks; then a MessagePort. ║ The controller validates every value an instance sends. ← boundary 1 Instance iframe on . (one origin per instance) ← boundary 2 (browser origin model) └─ kernel worker (our code, but shares the origin with hostile code) ║ SAB channel + postMessage; kernel validates every request ← boundary 3 └─ process workers (untrusted code) └─ service worker for module loading and in-instance fetch Port origins -p. (one per open port, ADR 0008) └─ bridge page + service worker + preview iframes running the app's own pages. The SW only reaches its own port through a channel the controller handed the kernel. ``` ## Mitigations (planned and status) | Mitigation | Status | |---|---| | Runtime executes on a separate sandbox origin, never the host app's origin | **done** (2b) | | One origin and one kernel per instance, isolating storage, BroadcastChannel and SW between instances ([ADR 0003](https://clientvm.joeldsouza.me/docs/decisions/0003-kernel-per-instance-origin.md)) | **done** (2b), e2e-tested | | Sandbox origin serves static files only, sets no cookies, and has no authenticated endpoints | **documented** ([hosting.md](https://clientvm.joeldsouza.me/docs/hosting.md)) | | Host ↔ instance handshake checks the source window and exact origin on both sides; the controller validates all instance replies and events | **done** (2b) | | `frame-ancestors` CSP restricts who can embed instance pages | **supported** (hosting config) | | Kernel decodes every syscall defensively (type-checked args, `EINVAL` on malformed input, `ENOSYS` on unknown ops) | **done** (spike) | | Process workers get no direct VFS access, only the syscall channel | **done** | | Each process gets its own channel SAB, so processes cannot read each other's syscall traffic | **done** | | Capabilities for every cross-instance interaction, checked in the **controller** (kernels run hostile code and never see the table) | **done** (4a–4c) for mailbox, `.internal` HTTP, mounts and `spawn-instance`, e2e-tested. Revoking a mount capability stops its sync | | The preview agent accepts a connection only from its parent window, and the host validates everything it sends (snapshots, console entries, screenshots). `evaluate` runs in the preview's port origin, which already runs the instance's code. Agent output is untrusted data for an LLM (prompt-injection risk), not instructions | **done** (4d) | | Requests a kernel makes of the controller (`mailboxSend`, `netFetch`) are validated and run with that instance's capabilities only; mailbox messages are re-serialized as JSON so instances never share objects | **done** (4a/4b) | | Resource limits per instance: `maxProcesses`, `quotaBytes`/`maxInodes` (`ENOSPC`), 1024 open files per process, `maxCpuMs` (a process that runs without yielding is killed with `SIGXCPU`), 8 MiB of unread output per stream in the controller, `Instance.exec` `timeoutMs` | **done** (2c, 5c), e2e-tested. **`maxMemoryMB` is not enforced** (open-questions.md) | | The service worker never routes `/__clientvm/*` (ClientVM's own page, workers and SW script) to instance servers, so instance code cannot shadow them | **done** (2d), e2e-tested | | The service worker accepts a kernel link only from the instance page | **done** (2d) | | Preview pages run on a per-port origin, not the kernel's: app code cannot touch the kernel's OPFS store, the instance page, or other ports' storage. A port origin's link serves only its own port, never the module routes | **done** (3d), e2e-tested | | Instance ids cannot end in `-p`, so an instance never shares an origin with another instance's port | **done** (3d) | | Fuzzing of codec, channel, VFS, resolver, shell parser | **done** (5b): seeded tests for the protocol codec, tar reader, path, CommonJS resolver, VFS operations and shell parser. Runs in CI with fixed seeds; `FUZZ_SEED`/`FUZZ_ITERATIONS` for longer runs | | Threads (`worker_threads`, `child_process.fork`) are kernel processes: same syscall checks, process limit and CPU watchdog. Parent and child share only a MessagePort the kernel created | **done** (5a) | | Pseudo-terminals (ADR 0017): terminal output is instance output like any other and goes through the same 8 MiB handle buffer and `onProcess` bounds; `attachShell` sanitizes it as the activity view does. Window sizes are validated (1 to 10000) in the controller and the kernel. Signals are delivered within the instance only, and a process that does not act on one within 1 s is terminated, so a handler cannot make a process unkillable (SIGKILL stays immediate) | **done** (T2), e2e-tested | | Process output shown in the host page (`@clientvm/terminal`, ADR 0016): the controller keeps at most 100 processes and 256 KiB of output each for `onProcess` replay; `attachActivityView` strips string escape sequences (OSC 52 clipboard writes, OSC 8 links, DCS/APC) except titles and draws commands without control characters; feed output is meant to be rendered as text, never HTML | **done** (T1, T3), unit-tested. Views draw at most 64 Ki characters a frame and skip the oldest lines beyond a 1 Mi-character backlog; the only links in a view are ClientVM's own, to the instance's open ports. Persisted scrollback (`sessionStorage`) is the sanitized text | | Agent-supplied regexes (`grep`, `sed`, `find -regex`, `[[ =~ ]]`) run on the JS regex engine and can backtrack catastrophically. They run in the instance's own worker, so a bad pattern only stalls that process; `Instance.exec` `timeoutMs` stops it | **documented** | ## What a compromised instance can do Code in an instance can do anything its own origin can do. It can rewrite its own kernel's memory (the kernel shares the agent cluster), read and write its own filesystem and OPFS, register a service worker for its own origin, and send arbitrary messages to the controller. It cannot reach other instances' storage or channels, or the host app's origin. Everything it sends the controller is validated before use. A hostile instance can lie about its own files and process output, but it cannot affect the controller or other instances. ## Persisted data A persistent instance's store lives in its own origin's OPFS (`clientvm/v1/`). Processes in that instance can read and tamper with it, which only affects that instance. Loading validates the structure and fails closed on corruption. Storage partitioning keys it by the host app's top-level site. Preset images (ADR 0018) are the one thing ClientVM keeps on the **host** origin, in Cache Storage (`clientvm-presets`) or a host-supplied `presetStore`. Only the controller writes them, from a builder instance that runs the pinned template and setup and never agent code, so an instance cannot plant files in another's starting image. Images hold public packages only and are validated at boot like any image; a stored image that fails its framing check is dropped and rebuilt. ## Known risks and open issues - **Spectre / high-resolution timers.** Cross-origin isolation re-enables SAB and precise timers. COEP keeps cross-origin resources that haven't opted in out of the process, but code in a process can still time other code in the same agent cluster. Per-instance origins limit what shares that cluster. Verify how Chromium assigns site isolation and processes for subdomains of one registrable domain: same-site subdomains may share a renderer process. - **Embedding by third parties.** Anyone can embed an instance page. They cannot connect to it unless they are its parent at the claimed origin. Storage partitioning keys an embedded instance's OPFS by the top-level site, so other sites cannot read your users' persisted instances. `frame-ancestors` adds defense in depth. - **Same-site subdomains.** `.` origins are same-site with each other. Cookies with `Domain=` would be shared, so the sandbox domain must never set cookies. Consider listing the sandbox domain on the Public Suffix List so each instance is its own site. - **Service worker hijack.** Preview documents and processes share the instance origin with the SW, so they can register a replacement SW or read the instance's storage. The blast radius is that one instance's previews and data, which that code already controls. A replacement SW cannot affect other instances (different origins) or the host app. Preview documents should not be treated as trustworthy by the host app; only read them through the controller. - **Kernel DoS.** `maxCpuMs` stops a process that spins without yielding, output caps bound what the controller buffers, and `quotaBytes` bounds the filesystem. Still open: a process that yields regularly can run forever (use `timeoutMs` or `kill`), memory is not capped (`maxMemoryMB`), and the defaults are unlimited: integrators must set limits for untrusted use. - **`eval` in process workers.** The node runtime uses indirect `eval` by design. The sandbox boundary is the worker and origin, not the JS realm. - **Outbound network.** Process code can `fetch` any CORS-enabled endpoint from the user's browser. Document this for integrators. A capability gate on outbound fetch is an open question. - **WebAssembly stand-ins (ADR 0013).** esbuild-wasm and @rollup/wasm-node are fetched on first use and checked against the integrity the registry publishes for them. That is the same trust `npm install` places in the registry, not a pin in ClientVM. They run with the instance's authority like any package code. - **pnpm and git.** pnpm 10.34.7 and isomorphic-git 1.44.3 are pinned by SHA-512 like npm (ADRs 0012, 0014), so a compromised registry cannot swap them. `GIT_TOKEN` and `GIT_CORS_PROXY` are visible to everything in the instance; a CORS proxy sees every request and credential sent through it. - **npm supply chain.** npm itself is pinned by SHA-512 (ADR 0012), so a compromised registry or mirror cannot swap the npm CLI. Packages that npm installs are checked against their lockfile integrity, as npm normally does, but their code and lifecycle scripts are untrusted and run with the instance's full authority. Running `npm install --ignore-scripts` reduces what runs during install, not what runs at `require` time. - **The project's own demo sandbox shares a registrable domain.** The live demo on https://clientvm.joeldsouza.me runs instances on `