/* tslint:disable */ /* eslint-disable */ /* auto-generated by scripts/gen-dts.js from napi-derive's TYPE_DEF_TMP_PATH output */ /* DO NOT EDIT — regenerate via `npm run build`. */ /** * VM-shaped handle passed to a `warmup` callback. Only valid * during the callback's lifetime — `exec` errors after return. */ export interface WarmupVm { exec(options: ExecOptions): Promise } /** * One staged host file → guest path mapping for `extraFiles`. See * [`BuildOptions::extra_files`]. */ export interface ExtraFileSpec { /** * Host filesystem path. File contents are read at bake time * and folded into the snapshot's input-hash, so changes * re-bake. */ hostPath: string /** Where the file appears inside the guest's root filesystem. */ guestPath: string } /** * One virtio-fs DAX mount: a host directory exposed to the guest * at a given `guestTag` (max 35 UTF-8 bytes). Reads go through * DAX (zero-copy, host-page-cache-shared across VMs that mount the * same path) — validated by spike 22. * * init-oci auto-mounts the share at `guestPath` (absolute path * inside the guest) before the workload starts — same convention * as Docker and Apple `container`. Volumes whose `guestPath` nests * under a mount's `guestPath` layer on top in declared order, so * layering (e.g. mount `/workspace` + volume * `/workspace/node_modules`) "just works" with no warmup mount * logic required. */ export interface MountSpec { /** Host directory to expose. Must exist + be a directory. */ hostPath: string /** virtiofs tag the guest mounts by. Max 35 bytes. */ guestTag: string /** * Absolute guest mount point. init-oci auto-mounts the share * here before the workload starts and BEFORE any volume * auto-mounts, so volumes whose `guestPath` nests under this * path layer on top correctly. Required. */ guestPath: string /** * Symlink policy: `"deny"` | `"opaque"` | `"follow"`. Default * `"opaque"` — guest may create symlinks (npm/pnpm/yarn rely on * them) but host-side symlinks pointing outside the mount root * are rejected. Use `"deny"` for paranoid mounts (no symlinks or * hard links at all) or `"follow"` for trusted single-tenant * workloads (pre-0.5.5 `allowExternalSymlinks: true` behaviour). */ symlinks?: string } /** * A writable virtio-blk volume backed by a host file. Use for * dependency caches (`node_modules`, `target/`, `__pycache__`, * `.next/`) and other write-heavy paths — block I/O is ~native * disk speed, no FUSE round-trip per file. Contrast with * [`MountSpec`] which exposes a host directory via virtio-fs * (right for source trees you want live-editable from the host, * wrong for thousands-of-small-files write workloads). * * The host file is created sparse at `hostPath` if missing * (actual disk usage tracks what the guest writes). Snapshots * capture the mapping, not the volume contents — same backing * file is reused across all restores of this snapshot. * * init-oci auto-mounts every declared volume at its `guestPath` * before the workload starts. When `guestPath` nests under a * [`MountSpec`] target (e.g. mount at `/workspace`, volume at * `/workspace/node_modules`), layering "just works" as long as * the mount also declares its `guestPath` (0.7.28+) — init-oci * auto-mounts virtio-fs binds first, volumes second, so child * volumes overlay parent binds correctly. */ export interface VolumeSpec { /** * Host file backing this volume. Created sparse at `sizeMib` * MiB if missing. Persists across restores; delete it to * reset state. */ hostPath: string /** * Mount point inside the guest, e.g. `"/var/lib/postgres"` * or `"/workspace/node_modules"`. init-oci auto-mounts the * volume here at boot. */ guestPath: string /** * Size cap in MiB. Default 1024 (1 GiB). Sparse — actual * disk usage matches what the guest writes. */ sizeMib?: number } /** * Options for [`Image.build`]. Mirrors `OciImageBuilder` in the * Rust crate. All fields optional except `ref` (the OCI image * reference). */ export interface BuildOptions { /** * OCI image reference, e.g. `"rust:1-slim"`, * `"ghcr.io/owner/image@sha256:..."`. */ ref: string /** * Stable snapshot name. Defaults to a sha-derived name based * on the image reference. */ name?: string /** * Guest memory in MiB. Default 256. Note: allocation is lazy * (CoW page-fault); this is the guest-visible ceiling, not * host commit. */ memoryMib?: number /** vCPUs per VM. Default 1. */ vcpus?: number /** `"always"` | `"missing"` | `"never"`. Default `"missing"`. */ pullPolicy?: string /** * Workload listener port. Default 80. Used by service-image * bakes (see `listenerRequired`). */ guestPort?: number /** * Replace the image's CMD (not ENTRYPOINT). Mirrors * `docker run ` and Apple `container run` * semantics: the image's `ENTRYPOINT` (if any) is preserved * and prepended; this array becomes `$@` to that entrypoint. * * Examples for an image with * `ENTRYPOINT ["/entrypoint.sh"]` + `CMD ["sleep", "infinity"]`: * * * `cmd: undefined` → runs `[/entrypoint.sh, sleep, infinity]` * (image defaults). * * `cmd: ["node", "server.js"]` → runs * `[/entrypoint.sh, node, server.js]` — entrypoint script * still gets to bootstrap (Xvfb, dbus, etc.) before exec'ing * your command. * * To bypass the image's ENTRYPOINT entirely, the bake-time * `--entrypoint` CLI flag remains available (not exposed on * the napi surface — file a request if needed). */ cmd?: Array /** Extra environment variables for the workload. */ env?: Record /** * When `true`, wait for the workload's listener to bind before * capturing the snapshot — v0.4.22 behavior. Default `false` * uses the pre-exec trigger (v0.4.23+): fast bake, workload * starts fresh on each restore. Set `true` for service-image * bakes (nginx, redis) where you want the listener pre-bound. */ listenerRequired?: boolean /** * Directory for the snapshot artifact. Default * `~/.local/supermachine-snapshots`. */ snapshotsDir?: string /** * Files to bake into the delta layer at fixed guest paths. * Bytes read from `hostPath` at bake time; the host file's * contents are folded into the snapshot's input-hash so any * change re-bakes. Common pattern: ship per-snapshot * kernel modules, certs, configuration files. Maps to * `OciImageBuilder::with_extra_file`. */ extraFiles?: Array /** * virtio-fs DAX mounts. Each entry attaches a host directory * to the guest, served zero-copy via FUSE-over-virtio with DAX. * Folded into the bake's input hash so changing `hostPath` * re-bakes. */ mounts?: Array /** * Writable virtio-blk volumes. Each entry maps a sparse host * file to a guest mount point. Use for dependency caches * (`node_modules`, `target/`) — block I/O is ~native disk * speed and bypasses the FUSE round-trip cost that makes * `mounts` slow for thousands-of-small-files workloads. * Volume bytes persist across restores; only the mapping is * captured in the snapshot. */ volumes?: Array /** * Extra kernel cmdline tokens, appended after supermachine's * own defaults (earlycon, console, tsi_hijack, etc.). Power- * user / testing escape hatch — e.g. `["panic=1"]` to force * an immediate panic on warning, or `["init=/nope"]` to * deliberately trigger an early-init kernel panic in a test. * Folded into the bake's input hash so changing this re-bakes. */ extraKernelArgs?: Array /** * Override where to fetch the image bytes. Default behavior * (when omitted) treats `ref` as a registry reference and pulls * from Docker Hub / the registry encoded in `ref`. Set this * when the image lives locally and a registry round-trip * would be wasteful or impossible (offline CI, locally-built * images via Apple `container`, etc.). * * Accepted values: * * `"oci-archive"` — `sourcePath` is a tarball (the output of * `docker save` or `skopeo copy --format=oci-archive`). * * `"oci-layout"` — `sourcePath` is a directory containing * `index.json` + `oci-layout` + `blobs/sha256/...`. * * `"registry"` — default. `sourcePath` is ignored. * * `"dockerfile"` — build an image FROM a Dockerfile, entirely * inside supermachine (no Docker, no Apple `container`): each * instruction runs in a microVM and is snapshotted per layer. * Provide the Dockerfile via `dockerfilePath` or * `dockerfileContents`, the build context via `contextDir`, and * optional `buildArgs`. The base `FROM` image is pulled via the * native registry path. `sourcePath` is ignored; run-tuning * options (`memoryMib`/`vcpus`/`cmd`/`env`/`mounts`/`volumes`/ * `warmup`/…) do not apply to the build itself — the produced * image carries the Dockerfile's own ENV/CMD/ENTRYPOINT, and you * set run config when you `pool()`/`fromSnapshot()` it. * * Build-step VMs boot with a generous RAM ceiling (default * 8192 MiB) so a heavy `RUN` (e.g. a multi-GB `apt-get install`) * doesn't exhaust the writable overlay's in-RAM tmpfs upper. The * ceiling is a CoW page-fault limit (host pages commit only when * the guest writes them) and snapshots stay sparse, so it's nearly * free. Override via the `SUPERMACHINE_BUILD_MEMORY_MIB` env var if * a build writes more than ~half the default ceiling in one layer. * * When set, `ref` is preserved as the logical image identifier * (used to derive the snapshot directory name); the actual * image bytes come from `sourcePath`. The folded input hash * includes the source path's stat so changes to the local * image re-bake automatically. */ source?: string /** File or directory path for non-registry sources. See `source`. */ sourcePath?: string /** * Path to a Dockerfile, for `source: "dockerfile"`. Mutually * exclusive with `dockerfileContents`. */ dockerfilePath?: string /** * Inline Dockerfile text, for `source: "dockerfile"` (alternative * to `dockerfilePath`). Mutually exclusive with `dockerfilePath`. */ dockerfileContents?: string /** * Build-context directory for `source: "dockerfile"` — the root * that `COPY`/`ADD` resolve their relative source paths against. * Defaults to the directory containing `dockerfilePath`, or the * process cwd when building from inline `dockerfileContents`. */ contextDir?: string /** * `--build-arg` overrides for `ARG` substitution in a * `source: "dockerfile"` build (name → value). The Dockerfile's * `ARG` defaults apply for any name left unset. */ buildArgs?: Record /** * Target platform, in Docker `--platform` form. Supported: * * `"linux/arm64"` (default) — native arm64 path. * * `"linux/amd64"` — pull the amd64 variant of multi-arch * images, auto-mount Apple's Rosetta runtime share at * `/run/rosetta`, register binfmt for amd64 ELFs. Requires * `softwareupdate --install-rosetta` on the host. * See `docs/design/chrome-amd64-gap-2026-05-17.md` for the * Chrome / Playwright headful demo this enables. */ platform?: string /** * Stable tag for the warmup callback (see the `warmup` * parameter on [`Image.build`]). Folded into the snapshot's * cached fingerprint so changing the warmup body invalidates * the previous warm snapshot. Default `"default"` — set a * versioned tag (`"v1"`, `"v2"`) when you mutate the warmup. * Ignored when no warmup function is provided. */ warmupTag?: string /** * kboxlike backend only: guest path of a readiness marker the * workload writes once it is actually serving (e.g. after its * listener is bound). When set, the live capture waits for * this file before snapshotting, and a pool over the image * captures the workload ONCE and restores every slot/cycle * from that shared warm snapshot. Folded into the bake cache * key. No effect on other backends. */ readyFile?: string /** * kboxlike backend only: substring that must appear in * `readyFile` before the capture proceeds (omit to treat the * marker's existence as ready). */ readyPattern?: string /** * kboxlike backend only: capture deadline in milliseconds * while waiting for `readyFile` (the capture proceeds at the * deadline even if the marker never appeared). */ readyTimeoutMs?: number /** * kboxlike backend only: the warm-pool workload argv. Pool VMs * boot + capture THIS command (gated on `readyFile`) while `cmd` * stays inert for the bake itself (the daemon usually cannot * boot before the warmup installed its dependencies). */ warmCmd?: Array /** * How `extraFiles` and other host-side inputs contribute to * the bake key. Two modes: * * * `"fast"` (default) — hash mtime + size. Cheap (single * stat per file); a same-size, same-mtime edit avoids a * re-bake. Safe for the typical workflow where editors * touch mtime on save. * * `"content"` — hash file bytes. Slower (full read); * detects byte-identical-but-different-mtime cases (touch * without edit doesn't re-bake; cp -p preserves mtime). * Use when your build system fingerprints inputs by * content rather than by mtime. * * Promoted from the 0.7.37 `SUPERMACHINE_SNAPSHOT_HASH_MODE` * env var (deleted in 0.7.38). */ cacheKeyMode?: string /** * virtio-fs FUSE_FSYNC handler mode. Two modes: * * * `"strong"` (default) — use macOS `F_FULLFSYNC`. Genuine * crash-safety guarantee: data is on stable storage when * the syscall returns. ~10-100× slower than plain fsync. * * `"weak"` — use plain `fsync(2)`. Faster; the host kernel * may still have data in flight. Acceptable when your * workload tolerates a small loss window (tests, * ephemeral builds, scratch dirs). * * Promoted from the 0.7.37 `SUPERMACHINE_FSYNC_WEAK=1` env * var (deleted in 0.7.38; the env still propagates to the * worker for one release as a deprecation runway). */ fsyncMode?: string } export interface PoolOptions { /** * Minimum idle VMs to keep warm. Spawned eagerly at pool * build time. Default 1. */ min?: number /** * Maximum total VMs (active + idle). Pool grows up to this * under load. Default 1. */ max?: number /** * Max wait for `acquire()` when the pool is saturated. * Default 60_000 (60 s). * * Special value: pass `0` for "no timeout — block forever". * Useful for batch workloads that prefer waiting over * failing. Mirrors `PoolBuilder::no_acquire_timeout()` on the * Rust side. */ acquireTimeoutMs?: number /** * Idle VM lifetime before janitor evicts above `min`. Defaults * to no eviction. */ idleTimeoutMs?: number /** If `true` (default), cycle-restore the VM on release. */ restoreOnRelease?: boolean /** * Runtime memory ceiling override for this pool's workers * (in MiB). Defaults to the value baked into the snapshot. * Pure runtime — doesn't re-bake. Pages are lazy-committed, * so raising the ceiling above the baked value doesn't * increase host commit unless the guest actually writes to * the new pages. */ memoryMib?: number /** * Runtime vCPU count override for this pool's workers. * Defaults to the value baked into the snapshot. */ vcpus?: number /** * Per-worker snapshot-restore timeout (ms). Default 30_000. * Bump for slow disks or large RAM snapshots — restore time * scales roughly linearly with snapshot size. Forwards to * `VmConfig::with_restore_timeout` via PoolBuilder. */ restoreTimeoutMs?: number } /** * Returned by [`Pool.stats`]. Pool observability for monitoring, * autoscaling decisions, and capacity tuning. */ export interface PoolStats { /** Total workers the pool has spawned (idle + checked-out). */ alive: number /** Workers currently checked out via `acquire()`. */ inUse: number /** Workers sitting in the idle queue. */ idle: number /** * Number of callers currently blocked in `acquire()` waiting * for an idle worker to free up. */ waiting: number /** Configured `min` from PoolOptions. */ min: number /** Configured `max` from PoolOptions. */ max: number /** * Cumulative workers the pool watchdog reaped after they died while * idle. A steadily rising value indicates workers crashing * post-restore (inspect worker logs via SUPERMACHINE_WORKER_LOG_FILE). */ reaped: number /** * High-water-mark resident footprint (MiB) observed across this * pool's workers vs the configured memory cap. Memory admission * charges this (+25% margin) instead of the cap once measured, so * the gap is density reclaimed for free. `0` until the first * worker is measured. */ observedFootprintMib: number } /** * One file → bytes mapping for `stageFilesMode` (variant of * `stageFiles` that also lets you set the guest-side file mode, * e.g. 0o755 for shipping executable scripts inline with an exec). */ export interface StagedFileMode { guestPath: string bytes: Buffer /** * Unix file mode (e.g. `0o755`, written as `493` if you can't * use octal literals in your JS engine). When `null`, the * agent uses 0o644 (same as the plain `stageFiles` entry). */ mode?: number } export interface ExecOptions { argv: Array /** * Files to stage at fixed paths inside the guest before the * command runs. Mode defaults to 0o644. Use `stageFilesMode` * instead when you need to set the executable bit (or any * other mode). */ stageFiles?: Record /** * Like `stageFiles` but with explicit per-file Unix modes. * Useful for shipping executable scripts (`0o755`) or * read-only secrets (`0o400`). Entries here are unioned with * `stageFiles` — same `guestPath` in both is undefined order; * pick one. */ stageFilesMode?: Array timeoutMs?: number env?: Record cwd?: string chain?: Array /** * Allocate a pseudo-terminal for the guest process. With * `tty: true`, stdout/stdin pass through the pty master and * stderr is empty (the pty merges fd 1 + fd 2). Use this for * interactive REPLs, shells, or any process that expects a * real terminal (e.g. progress bars that detect isatty). */ tty?: boolean /** * Initial window size for tty mode. Ignored when `tty` is * false. Call `ExecChild.resize(cols, rows)` to change it * later from the streaming `spawn()` path. */ winsize?: Winsize } /** * Terminal window size for `ExecOptions.winsize`. Both fields are * in character cells (not pixels). Use 0/0 to let the agent pick * a default (80x24 in practice). */ export interface Winsize { cols: number rows: number } export interface ExecOutput { stdout: Buffer stderr: Buffer exitCode: number } /** * Result of [`ExecChild.wait`]. Mirrors `ExecOutcome` minus the * stdout/stderr buffers (those were already streamed via * `readStdout`/`readStderr`). */ export interface ExecWaitResult { /** `-1` if killed by signal / timeout / agent disconnect. */ exitCode: number /** * `true` if the process exited because the spawn-time * `timeoutMs` watchdog killed it. */ timedOut: boolean /** * Peak resident-set size in KiB during the process's life, * as reported by the in-guest agent's wait4(rusage). `null` * when not reported. */ peakRssKib?: number } /** * A baked OCI image. Returned by [`Image.build`] (bakes or * cache-hits) and by [`Image.fromSnapshot`]. */ export declare class Image { /** * Build an image from an OCI reference, or return the cached * snapshot if one already exists. Async: runs the bake * pipeline on a libuv worker thread. * * **Cold first-time bake of `alpine:latest` on Apple Silicon * takes ~400 ms**. Cache-hit is ~15 ms. * * `warmup` is an optional async callback that receives a [`Vm`] * after the guest is booted. Use it to pre-populate guest * state (compile a seed program, warm a page cache) — the * bake captures the post-warmup snapshot, so restores land in * the warm state. Pair with `warmupTag` in `options` to * version-tag the warmup for cache invalidation. * * The Vm passed to the warmup is invalidated after the * callback returns; holding a reference past return is safe * (won't crash) but `vm.exec()` will error. * * We take `warmup` as a separate positional argument rather * than as a field on `options` because napi-rs's async-fn * support requires all parameters to be `Send`. Plain * `JsFunction` isn't `Send`; here we use `AsyncTask` (which * splits sync-setup from sync-compute) to keep the JsFunction * → TSFn conversion on the JS thread while the bake runs on * a worker. The JS shim in index.js wraps this back into a * natural `Image.build({...})` API. */ static build(options: BuildOptions): Promise /** * Load an image from a previously-baked snapshot directory or * `restore.snap` file path. No bake — just reads metadata.json * and validates the snapshot file exists. */ static fromSnapshot(path: string): Promise /** * Create a VM pool for this image. `min`/`max` are the most * important — `min=max=N` pre-spawns N VMs eagerly and caps * total at N. * * Memory: each idle VM costs ~3 MiB host phys_footprint * (measured). The `memoryMib` build option is a guest-visible * ceiling, not host commit. */ pool(options?: PoolOptions | undefined | null): Promise /** * On-disk snapshot directory backing this Image. Same as * `supermachine::Image::snapshot_path` in Rust. Useful for * diagnostics, log lines, or chaining a second image off the * same snapshot via `Image.fromSnapshot`. */ get snapshotPath(): string /** Guest memory (MiB) as baked into the snapshot's metadata. */ get memoryMib(): number /** vCPU count as baked into the snapshot's metadata. */ get vcpus(): number } export declare class Pool { /** * Acquire a VM from the pool. Blocks (async) up to * `acquireTimeoutMs`. ~0 ms warm-handoff / ~5 ms cycle-restore * / ~22 ms spawn-from-disk. */ acquire(): Promise /** * Explicit pool shutdown. Wakes any caller blocked on * `acquire()` (they receive a "pool is shutting down" error * instead of hanging), drains idle + dirty workers, and * stops housekeeping threads. Idempotent. * * The pool ALSO shuts down on GC, but JS GC is unpredictable * and an integrator wiring this into a process-shutdown hook * wants a synchronous "pool is gone now" guarantee. Call * this in your shutdown path; the await resolves when the * idle workers have been QUITed (or SIGKILLed on timeout). */ shutdown(): Promise /** * Snapshot of the pool's current state. Cheap (~1 µs, just a * mutex lock) — safe to poll frequently for monitoring / * autoscaling decisions. */ stats(): PoolStats } /** * Streaming exec handle returned by [`Vm.spawn`]. Pull-style API: * caller polls `readStdout()` / `readStderr()` for chunks, writes * to stdin via `writeStdin()`, sends signals via `signal()`, and * awaits exit via `wait()`. Mirrors the Rust `ExecChild`. * * Pull-style was chosen over Node `ReadableStream`/`WritableStream` * for two reasons: (1) the underlying Rust types are sync * `Read`/`Write`, so wrapping in stream adapters would require * per-chunk napi roundtrips anyway, and (2) pull-style is the * minimum-surface-area API that covers all use cases (LLM-style * streaming output, interactive REPLs, anything you can build * with `for await (const chunk of pull()) ...`). */ export declare class ExecChild { /** * Write a chunk to the process's stdin. Returns when the * bytes have been queued on the host-side socket; the guest * agent forwards them to the process asynchronously. Multiple * calls append. */ writeStdin(bytes: Buffer): Promise /** Close stdin (send EOF to the process). Idempotent. */ closeStdin(): Promise /** * Read up to `maxBytes` (default 64 KiB) from stdout. Returns * an empty Buffer when stdout has closed (process exited and * drained); the caller's `for await` loop should terminate on * `buf.length === 0`. * * Blocks the libuv worker thread; the JS event loop stays * free for other work. */ readStdout(maxBytes?: number | undefined | null): Promise /** Same as [`readStdout`] for stderr. */ readStderr(maxBytes?: number | undefined | null): Promise /** * Nonblocking stdout poll. Returns `null` when no bytes are currently * queued, an empty Buffer on EOF, or a non-empty Buffer with available data. */ tryReadStdout(maxBytes?: number | undefined | null): Promise /** Nonblocking stderr poll. See [`tryReadStdout`]. */ tryReadStderr(maxBytes?: number | undefined | null): Promise /** * Resize the pty (tty mode only). No-op when the process was * spawned without `tty: true` — the guest agent ignores RESIZE * frames if no pty is attached. Use this from the JS side to * react to host terminal resize events (e.g. SIGWINCH on * process.stdout). */ resize(cols: number, rows: number): Promise /** * Send a signal to the guest-side process. Common values: * 1=SIGHUP, 2=SIGINT, 9=SIGKILL, 15=SIGTERM. Routes through * the cached signaler so it works even if a concurrent * `wait()` has already consumed the child handle (the * signaler outlives the child; calls become no-ops on the * closed socket). */ signal(signum: number): Promise /** * Return a thread-safe [`ExecSignaler`] handle that can signal * or abort this child from ANY caller (including a different * async task) without holding the ExecChild itself. The handle * can outlive the child — after exit, calls become no-ops on * the closed socket. * * Use this when you want to interrupt a `wait()` from a Ctrl-C * handler, a cancel registry, or a pool-shutdown hook. The * returned object is the JS-side analogue of Rust's * `ExecSignaler` — Send + Sync + Clone, one atomic refcount * inc per clone. * * Idiomatic shape: * * ```js * const child = await vm.spawn({ argv: ["./run.sh"] }); * const sig = child.signaler(); * process.on("SIGINT", () => sig.kill()); * const exit = await child.wait(); * ``` */ signaler(): ExecSignaler /** * Close the host-side socket WITHOUT waiting for a clean exit. * The demux thread observes EOF, a concurrent `wait()` returns * an error within milliseconds. Use this when the agent / * worker is unresponsive — e.g. you've already decided the * process must stop right now and don't care about reaping a * clean exit code. * * Works even AFTER a concurrent `wait()` has consumed the * child handle — routes through the cached signaler so the * host-side shutdown still fires. */ abort(): void /** * Non-consuming poll for child exit. Returns `null` if the * child is still running, or an `ExecWaitResult` if it has * exited. Mirrors `std::process::Child::try_wait`. Useful for * loops that want to check status without blocking, and that * pair with a signaler stashed in a registry. * * Returns null also if `wait()` has already consumed the * child (subsequent polls don't error). */ tryWait(): ExecWaitResult | null /** * Wait for the guest-side process to exit and return its * status. Consumes the underlying ExecChild — subsequent * calls error with "already waited". Drains any unread * stdout/stderr (caller should pull them out FIRST if they * care about full output). */ wait(): Promise } /** * Thread-safe control handle for an [`ExecChild`]. Returned by * [`ExecChild::signaler`]. Send a signal (SIGINT / SIGTERM / * SIGKILL / ...) to the in-guest process from any caller — a * cancel registry, a Ctrl-C handler, a pool-shutdown hook — * without holding the ExecChild itself. * * The handle keeps the underlying socket alive via Arc refcount * (one atomic inc per JS-side wrapper). Calls after the child * has exited or been waited are no-ops on the closed socket; * they don't panic or deadlock. */ export declare class ExecSignaler { /** * Send a signal (numeric) to the in-guest process. Common * values: 2 = SIGINT, 9 = SIGKILL, 15 = SIGTERM. */ signal(signum: number): void /** * Shortcut for `signal(9)` — SIGKILL. Mirrors * `child_process.ChildProcess.kill('SIGKILL')` semantics on * the JS side. */ kill(): void /** * Close the host-side socket immediately. Wakes a concurrent * `wait()` on the corresponding ExecChild, regardless of * whether the in-guest agent is still alive. Use this when * the SIGNAL path won't work — e.g. you've already * SIGKILL'd the guest agent, or the worker process is dead * and you want the host-side `await child.wait()` to * return now. * * Idempotent. */ abort(): void } /** * VM handle. Drop or `release()` to return to the pool. With Node * 20+, use the `using` keyword + `Symbol.asyncDispose`. */ export declare class Vm { /** * Run a process inside the guest via the in-guest exec agent. * * Collects stdout + stderr into Buffers; returns when the * process exits OR when `timeoutMs` fires (whichever first). * For very large outputs (>100 MiB) the buffer cost matters * — collecting locks memory until the call returns. * * **Need to stream output as it arrives, or pipe stdin * incrementally?** Use [`Vm.spawn`] instead — it returns an * [`ExecChild`] handle with `stdout` / `stderr` as async * iterables and a writable `stdin`. Common shape: * * ```ts * const child = await vm.spawn({ argv: ["my-app"] }); * for await (const chunk of child.stdout) { * process.stdout.write(chunk); * } * const exit = await child.wait(); * ``` * * See `examples/05-spawn-streaming.mjs` for the full pattern. */ exec(options: ExecOptions): Promise /** Return the VM to the pool. Idempotent. */ release(): Promise /** * Alias for `release()`. Wired up to `Symbol.asyncDispose` in * the JS shim for the TC39 explicit-resource-management * `using` keyword (Node 20+). */ dispose(): Promise /** * Write `bytes` to `path` inside the guest. Native vsock RPC, * ~100 µs round-trip. Complement to `exec({stageFiles})` — * use this when you want to drop a file without running a * command (or between commands on the same vm). * * 4 MiB default cap on file size; stream larger files via * `exec` with `stageFiles` instead. */ writeFile(path: string, bytes: Buffer): Promise /** * Read `path` from inside the guest, return bytes. Native * vsock RPC, ~100 µs round-trip. Default cap is 32 MiB (raised * from 4 MiB in 0.5.0); pass `maxBytes` for larger files, or * stream via `exec('cat ...')` for unbounded reads. */ readFile(path: string, maxBytes?: bigint | undefined | null): Promise /** * Spawn a process inside the guest and return a streaming * [`ExecChild`] handle. Unlike `exec()` which collects * stdout/stderr into Buffers, `spawn()` lets you write to * stdin / read from stdout/stderr incrementally — useful for * LLM-style streaming, long-running daemons, interactive REPLs. * * Important: ExecOptions.timeoutMs is IGNORED in spawn mode — * the caller controls cancellation via `child.signal(9)`. The * timeout watchdog only applies to the collect-mode `exec()`. */ spawn(options: ExecOptions): Promise /** * Capture a snapshot of this VM's current state and return a * new `Image` pointing at it. Equivalent to `Vm::snapshot` in * the Rust crate. The guest is paused for the capture * (typically 10s of ms; bounded by disk write time for large * RAM). The Vm remains usable after — handy for the * "warm up + snapshot + keep working" pattern. * * Returns a fresh Image; build a pool from it via `image.pool()` * to spawn workers that restore from the captured state. */ snapshot(destDir: string): Promise /** * Send `signum` to the guest's workload PID-1 (the process * the image's CMD/ENTRYPOINT launched at boot). Mirrors * `supermachine::Vm::workload_signal`. * * Distinct from `ExecChild.signal`, which targets a process * spawned via `vm.spawn()`. Use this for graceful service * shutdown of baked service images (e.g. SIGTERM to nginx * before tearing down the VM). */ workloadSignal(signum: number): Promise /** * On-disk path of this Vm's per-acquire vsock mux socket. * Stable for the lifetime of the Vm; goes away on `release()`. * Use this as an escape hatch when you want to bring your own * client (e.g. open a raw UnixStream from `node:net` and speak * a custom protocol to a workload listening inside the guest). * * Throws if called on the warmup vm — the bake driver owns * the warmup vm's sockets. */ get vsockPath(): string /** * On-disk path of this Vm's per-acquire exec control socket. * Same lifetime as `vsockPath`. Mostly an escape hatch for * users wiring up a non-libuv RPC client; the napi binding's * own `exec`/`spawn`/`writeFile`/`readFile` go through this * internally. */ get execPath(): string /** * Bind `127.0.0.1:hostPort` and proxy connections into the * guest's vsock mux. Returns a [`TcpForwarder`] handle; drop * it (or call `forwarder.stop()`) to stop accepting new * connections. In-flight connections survive `stop()` and * close naturally. * * Pass `hostPort = 0` to let the OS pick a free port; read * the actual bound port back via `forwarder.localAddr`. * * `guestPort` pins the host-port → guest-port mapping. The * forwarder writes a small per-connection routing header * (`SMUX-PORT-V1\0\0\0\0` + u32 BE port) over the unix mux, * and the worker routes to the matching AF_INET TSI listener * instead of falling back to "first listener" — important * when the guest binds multiple AF_INET ports (e.g. Chrome * DevTools + helper sockets). Pass `guestPort = 0` to opt out * of the header and keep the legacy first-listener behavior. */ exposeTcp(hostPort: number, guestPort: number): Promise } /** * Active TCP→vsock forwarder. Returned by [`Vm.exposeTcp`]; owns * the host-side TcpListener accept-loop thread. Drop it (or call * `stop()`) to stop accepting new connections. In-flight * connections continue independently until they close naturally. */ export declare class TcpForwarder { /** * The address the forwarder is bound to, e.g. `"127.0.0.1:54321"`. * Useful when you asked for `hostPort = 0` and want the * OS-assigned port back. */ get localAddr(): string /** * Stop accepting new connections. Idempotent. Equivalent to * dropping the forwarder, but returns when the accept thread * has actually exited (vs Drop, which detaches the join). */ stop(): Promise }