# Architecture

How ClientVM is put together today: which threads and origins run what, how a syscall travels, and
how the packages depend on each other. For a gentler tour of the packages see
[packages.md](https://clientvm.joeldsouza.me/docs/packages.md); for the reasoning behind each choice see the
[design decisions](https://clientvm.joeldsouza.me/docs/#decisions).

## Thread layout

```
Host app page (any origin, not cross-origin isolated)
  └─ controller (@clientvm/clientvm): trusted broker, validates everything it receives
       │ hidden iframe + handshake (exact window and origin checks), then a MessagePort
       ▼
Instance page  https://<id>.<sandbox-domain>/__clientvm/instance.html
  (Document-Isolation-Policy → cross-origin isolated)       (@clientvm/sandbox-host)
  └─ kernel worker: one instance                              (@clientvm/kernel)
       ├─ MemoryVfs (CoW snapshots, quotas, watchers)         (@clientvm/vfs)
       ├─ process table: pid → { channel SAB, SyscallServer, FdTable, Worker }
       │  serves InstanceRpc to the controller over the port  (@clientvm/protocol)
       ▼
     process workers (nested dedicated workers, one per process)
       ├─ runtime chosen by argv[0]: node → @clientvm/node-compat, clientvm-bench → builtin
       ├─ sync syscalls: SyscallClient over the channel SAB (Atomics.wait)
       └─ async: postMessage to the kernel for stdout / stderr / ready / exit
```

Each instance origin also has a **service worker** (`/__clientvm/sw.js`, scope `/`). It forwards
every request outside `/__clientvm/` (preview iframes, `fetch` from processes) over a MessagePort
to the kernel's `HttpRouter`, which dispatches by virtual port. If the SW restarts and loses its
port, it asks the instance page to reconnect.

Processes load ES modules with the browser's native `import()` from `/__clientvm/fs/<path>`; the SW
sends those to the kernel's `ModuleServer`, which resolves specifiers with Node's ESM algorithm,
rewrites them to such URLs, and serves CommonJS files as ES facades. The instance page creates the
kernel worker only once the SW controls the page, so every process worker is controlled too.

Commands are files. Built-in runtimes are marker files in `/usr/local/bin`
(`#!/clientvm/builtin node`), and 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 started by a process are routed through the kernel. `spawnSync` is a
syscall that blocks the caller until the child exits. Killing a process also kills its children,
like a signal to a process group.

The shell (`@clientvm/shell`) is the `sh`/`bash` runtime. Its builtins and Linux commands run
inside the shell's worker when `PATH` resolves to their marker file. Everything else (`node`,
scripts, `.bin` shims) is spawned through the kernel, and output the shell does not redirect is
inherited ([ADR 0011](https://clientvm.joeldsouza.me/docs/decisions/0011-in-process-shell-commands.md)). Each command is also its own
runtime, so programs can spawn `ls` or `grep` directly.

Servers listen on virtual ports in the kernel's net stack (`packages/kernel/src/net.ts`). An
HTTP request is relayed to the owning process as messages, and the response streams back to the
service worker as a transferred `ReadableStream`. Upgrades and `net` connections are byte
sockets linked end to end (process ↔ process, or process ↔ MessagePort for a preview's
WebSocket). Each port is previewed on its own origin (ADR 0008).

Each instance has its own origin, so the browser isolates instances' storage, channels and
service workers from each other ([ADR 0003](https://clientvm.joeldsouza.me/docs/decisions/0003-kernel-per-instance-origin.md)).
Forking into a new instance exports a filesystem image (`exportImage`), transfers it, and imports
it on the other side.

## Sync syscall path

1. node-compat (`fs.readFileSync('x')`) resolves the path against the process cwd and encodes the
   arguments with the binary codec.
2. `SyscallClient.call(op, bytes)` writes the header (`OP`, `LEN`, `TOTAL`) and payload into the
   SAB, stores `STATE = REQUEST`, then calls `Atomics.notify`, or posts a doorbell in
   `postMessage` mode. It then blocks in `Atomics.wait` while `STATE == REQUEST`.
3. The kernel's `SyscallServer` wakes from `Atomics.waitAsync` (or the doorbell), decodes the
   request, calls the VFS, and writes the response. It sets `ERRNO` on failure, stores
   `STATE = RESPONSE`, and calls `Atomics.notify`.
4. The client copies the response out of the SAB (the result never aliases shared memory) and maps
   a non-zero errno to a Node-shaped `SystemError`.

Payloads larger than the 256 KiB region are streamed with the channel-level opcodes
`REQUEST_MORE` and `RESPONSE_MORE`, so the buffer never grows. Handlers may return a Promise, which
leaves room for async backends like OPFS. The blocked process doesn't care how long the kernel
takes.

### 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.

## Package dependency graph

```
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.

## Workspace conventions

- 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/`.