/* auto-generated by NAPI-RS */ /* eslint-disable */ /** * Low-level client for talking to agentd through the sandbox relay socket. * * All bodies are raw CBOR bytes — encode and decode in JS userland with a * library like `cbor-x`. For ergonomic typed access, build a higher layer * on top of this class. */ export declare class AgentClient { /** * Connect to a sandbox by name. Resolves the agent socket from the * SDK's configured runtime directory. Sandbox names are limited to * 128 UTF-8 bytes. */ static connectSandbox(name: string, opts?: AgentConnectOptions | undefined | null): Promise /** Connect to an agentd relay socket by path. */ static connect(path: string, opts?: AgentConnectOptions | undefined | null): Promise /** * Resolve a sandbox's agentd relay socket path without connecting. * * Returns the same path `connectSandbox` would dial, so a caller can talk * to agentd over a raw byte transport instead of this frame client. The * sandbox need not be running. Sandbox names are limited to 128 UTF-8 * bytes. */ static socketPath(name: string): string /** * Send one frame and await a single response frame. * * Use for request/response RPCs that produce exactly one terminal * response (e.g. an `FsRequest` → `FsResponse`). */ request(flags: number, body: Buffer): Promise /** * Open a streaming session. Returns `{id, handle}`: * - `id`: pass to `send()` for follow-up frames within the session. * - `handle`: pass to `streamNext()` / `streamClose()`. */ streamOpen(flags: number, body: Buffer): Promise /** * Pull the next frame from a stream. Resolves with `null` when the * stream has ended (terminal frame delivered, or stream closed). */ streamNext(handle: bigint): Promise /** Close a stream handle. Idempotent. */ streamClose(handle: bigint): Promise /** * Send a follow-up frame on an existing correlation id (e.g. stdin, * signal, resize, or data chunks on an open session). */ send(id: number, flags: number, body: Buffer): Promise /** The cached handshake `core.ready` frame body bytes (CBOR-encoded). */ readyBytes(): Buffer /** Close the connection. Idempotent. */ close(): Promise } /** Fluent builder for interactive attach options. */ export declare class AttachOptionsBuilder { constructor() arg(arg: string): this args(args: Array): this cwd(cwd: string): this user(user: string): this env(key: string, value: string): this envs(vars: Record): this /** * Override the detach key sequence (Docker-style spec, e.g. * `"ctrl-]"` or `"ctrl-p,ctrl-q"`). Default: `Ctrl+]`. */ detachKeys(keys: string): this rlimit(resource: string, limit: number): this rlimitRange(resource: string, soft: number, hard: number): this /** Snapshot the accumulated configuration. */ build(): AttachOptions } export type JsAttachOptionsBuilder = AttachOptionsBuilder /** Fluent builder for DNS interception settings. */ export declare class DnsBuilder { constructor() /** Enable or disable DNS rebinding protection. Default: true. */ rebindProtection(enabled: boolean): this /** * Set the upstream nameservers. Replaces any previous set. * Each entry accepts the same forms as Rust: `"1.1.1.1"`, * `"1.1.1.1:53"`, `"dns.google"`, `"dns.google:53"`. */ nameservers(servers: Array): this /** Set the per-query timeout in milliseconds. Default: 5000. */ queryTimeoutMs(ms: number): this /** Materialize the accumulated state into a `DnsConfig`. */ build(): DnsConfig } export type JsDnsBuilder = DnsBuilder /** * Handle for a streaming command execution. * * Use `recv()` to get events one at a time, or iterate with a loop: * ```js * const handle = await sandbox.execStream("tail", ["-f", "/var/log/app.log"]); * let event; * while ((event = await handle.recv()) !== null) { * if (event.eventType === "stdout") process.stdout.write(event.data); * } * ``` */ export declare class ExecHandle { /** Get the correlation ID for this execution. */ get id(): Promise /** Receive the next event. Returns `null` when the stream ends. */ recv(): Promise /** Take the stdin writer. Can only be called once; returns `null` on subsequent calls. */ takeStdin(): Promise /** Wait for the process to exit and return the exit status. */ wait(): Promise /** Wait for completion and collect all output. */ collect(): Promise /** Send a signal to the running process. */ signal(signal: number): Promise /** Kill the running process (SIGKILL). */ kill(): Promise /** Resize the pseudo-terminal for this exec session. */ resize(rows: number, cols: number): Promise } export type JsExecHandle = ExecHandle /** Fluent builder for per-execution overrides. */ export declare class ExecOptionsBuilder { constructor() /** Append a single command argument. */ arg(arg: string): this /** Append a list of command arguments. */ args(args: Array): this /** Override the working directory. */ cwd(cwd: string): this /** Override the running user. */ user(user: string): this /** Set a single environment variable. */ env(key: string, value: string): this /** Set environment variables from an object. */ envs(vars: Record): this /** Kill the process if it hasn't exited within `ms` milliseconds. */ timeout(ms: number): this stdinNull(): this stdinPipe(): this stdinBytes(data: Buffer): this tty(enabled: boolean): this rlimit(resource: string, limit: number): this rlimitRange(resource: string, soft: number, hard: number): this /** Snapshot the accumulated configuration. */ build(): ExecOptions } export type JsExecOptionsBuilder = ExecOptionsBuilder /** * Output of a completed command execution. * * Provides both string and raw byte access to stdout/stderr: * ```js * const output = await sandbox.shell("echo hello"); * console.log(output.stdout()); // "hello " * console.log(output.stdoutBytes()); // * console.log(output.code); // 0 * console.log(output.success); // true * ``` */ export declare class ExecOutput { /** Exit code of the process. */ get code(): number /** Whether the process exited successfully (code == 0). */ get success(): boolean /** Get stdout as a UTF-8 string. */ stdout(): string /** Get stderr as a UTF-8 string. */ stderr(): string /** Get stdout as raw bytes. */ stdoutBytes(): Buffer /** Get stderr as raw bytes. */ stderrBytes(): Buffer /** Get the exit status. */ status(): ExitStatus } /** Stdin writer for a running process. */ export declare class ExecSink { /** Write data to the process stdin. */ write(data: Buffer): Promise /** Close the sink. Sends EOF in non-TTY pipe mode; PTY mode stays open. */ close(): Promise } export type JsExecSink = ExecSink /** * A streaming reader for file data from the sandbox. * * Supports both manual `recv()` calls and `for await...of` iteration: * ```js * const stream = await sb.fs().readStream("/app/data.bin"); * for await (const chunk of stream) { * processChunk(chunk); * } * ``` * * This type implements JavaScript's async iterable protocol. * It can be used with `for await...of` loops. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols */ export declare class FsReadStream { /** Receive the next chunk of data. Returns `null` when the stream ends. */ recv(): Promise [Symbol.asyncIterator](): AsyncGenerator } export type JsFsReadStream = FsReadStream /** Streaming writer for guest files. */ export declare class FsWriteSink { /** Write a chunk to the underlying file. */ write(data: Buffer): Promise /** Flush and close the sink. Idempotent. */ close(): Promise } export type JsFsWriteSink = FsWriteSink /** Fluent builder for HTTP denial responses. */ export declare class HttpBuilder { /** Create default HTTP settings. */ constructor() /** Enable readable HTTP denial responses. Disabled by default. */ denyResponse(enabled: boolean): this /** Set the body used when denyResponse is enabled, substituting `{host}`. */ denyMessage(message: string): this } export type JsHttpBuilder = HttpBuilder /** * Fluent builder for an explicit rootfs image source. * * Used inside `Sandbox.builder(...).imageWith((i) => i.disk(...).fstype(...))` * or `Sandbox.builder(...).imageWith((i) => i.oci(...).rootDisk(...))`. * Standalone use is rare; `.image("python:3.12")` and `.image("./ubuntu.qcow2")` * resolve the common cases automatically. */ export declare class ImageBuilder { constructor() /** Use an OCI image reference as the root filesystem. */ oci(reference: string): this /** * Configure the writable rootfs layer (root disk) for an OCI rootfs. * * Pass a number of MiB for a managed root disk, or a callback for the * tmpfs and disk-image kinds: * * ```ts * .imageWith((i) => i.oci("python:3.12").rootDisk(8192)) * .imageWith((i) => i.oci("python:3.12").rootDisk((d) => d.tmpfs().size(512))) * .imageWith((i) => i.oci("python:3.12").rootDisk((d) => d.disk("./scratch.img"))) * ``` */ rootDisk(sizeMibOrConfigure: number | ((d: RootDiskBuilder) => RootDiskBuilder)): this /** * Set the writable overlay upper size for an OCI rootfs, in MiB. * * @deprecated Use `rootDisk` instead. */ upperSize(sizeMib: number): this /** * Use a host disk image file as the root filesystem. The format is * derived from the file extension: `.qcow2`, `.raw`, or `.vmdk`. */ disk(path: string): this /** * Use a host directory directly as the root filesystem (bind rootfs). * The directory's contents become the guest rootfs as-is — no OCI pull * and no overlay. */ bind(host: string): this /** * Set the inner filesystem type (e.g. `"ext4"`). Omit to let agentd * auto-detect by probing `/proc/filesystems`. */ fstype(fstype: string): this } export type JsImageBuilder = ImageBuilder /** A lightweight handle to a cached image. */ export declare class ImageHandle { get reference(): string get sizeBytes(): number | null get manifestDigest(): string | null get architecture(): string | null get os(): string | null get layerCount(): number get lastUsedAt(): number | null get createdAt(): number | null } export type JsImageHandle = ImageHandle /** * Fluent builder for the args + env portion of a guest init handoff. * * The cmd is supplied positionally to `SandboxBuilder.initWith`, * mirroring how `ExecOptionsBuilder` omits the command name. */ export declare class InitOptionsBuilder { constructor() /** Append a single argv entry. */ arg(arg: string): this /** Append multiple argv entries. */ args(args: Array): this /** Set a single env var for the init process. */ env(key: string, value: string): this /** Set multiple env vars at once. */ envs(vars: Record): this } export type JsInitOptionsBuilder = InitOptionsBuilder /** * Fluent builder for per-NIC overrides on the guest interface * (`microsandbox_network::config::InterfaceOverrides`). Chainable * setters mutate in place; `.build()` is implicit when passed to * `NetworkBuilder.interface(b => b.mtu(9000))`. */ export declare class InterfaceOverridesBuilder { constructor() /** * Set the guest MAC address from a colon- or dash-delimited 6-byte * string (e.g. `"aa:bb:cc:dd:ee:ff"`). Invalid input is recorded * and surfaced when the parent `NetworkBuilder.build()` runs. */ mac(mac: string): this /** Set the interface MTU. Default: 1500. */ mtu(mtu: number): this /** Set the guest IPv4 address (e.g. `"172.16.0.5"`). */ ipv4(address: string): this /** Set the guest IPv6 address (e.g. `"fd42:6d73:62::5"`). */ ipv6(address: string): this } export type JsInterfaceOverridesBuilder = InterfaceOverridesBuilder /** * A streaming subscription for sandbox log entries. * * Supports both manual `recv()` calls and `for await...of` iteration: * ```js * const stream = await sb.logStream({ follow: true }); * for await (const entry of stream) { * process.stdout.write(entry.data); * } * ``` * * This type implements JavaScript's async iterable protocol. * It can be used with `for await...of` loops. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols */ export declare class LogStream { /** * Receive the next entry. Returns `null` when the stream ends * (snapshot drained, `until` reached, or fatal stream error * already surfaced). */ recv(): Promise [Symbol.asyncIterator](): AsyncGenerator } export type JsLogStream = LogStream /** * A streaming subscription for sandbox metrics at a regular interval. * * Supports both manual `recv()` calls and `for await...of` iteration: * ```js * const stream = await sb.metricsStream(1000); * for await (const m of stream) { * console.log(`CPU: ${m.cpuPercent.toFixed(1)}%`); * } * ``` * * This type implements JavaScript's async iterable protocol. * It can be used with `for await...of` loops. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols */ export declare class MetricsStream { /** Receive the next metrics snapshot. Returns `null` when the stream ends. */ recv(): Promise [Symbol.asyncIterator](): AsyncGenerator } export type JsMetricsStream = MetricsStream /** * Fluent builder for a sandbox volume mount. * * Pick exactly one mount kind via `.bind()`, `.named()`, `.owned()`, `.tmpfs()`, or * `.disk(...)`, then chain modifiers (`.readonly()`, `.noexec()`, `.nosuid()`, `.nodev()`, * `.size(mib)` for tmpfs, `.format(fmt)` / `.fstype(s)` for disk). * Validation is deferred to the terminal `.build()` call. */ export declare class MountBuilder { /** Restore this captured private disk without a host binding. */ captured(): this constructor(guest: string) /** Bind a host directory at the guest path. */ bind(host: string): this /** Mount a named volume created via `Volume.builder(name).create()`. */ named(name: string): this /** Mount a named volume with explicit existence behavior. */ namedWith(name: string, mode?: string | undefined | null, kind?: string | undefined | null, sizeMib?: number | undefined | null, quotaMib?: number | undefined | null): this /** * Allocate storage retained across restarts and removed with this sandbox. * Defaults to a directory; disk storage requires a positive `sizeMib`. */ owned(options?: { kind?: 'dir' | 'disk'; sizeMib?: number; quotaMib?: number }): this /** Mount an in-memory tmpfs at the guest path. */ tmpfs(): this /** Mount a host disk image file as a virtio-blk device. */ disk(host: string): this /** * Override the disk image format (`"qcow2" | "raw" | "vmdk"`). Only * valid when paired with `.disk()`. */ format(format: string): this /** Inner filesystem type for a `.disk()` mount (e.g. `"ext4"`). */ fstype(fstype: string): this /** Mark the mount read-only. */ readonly(): this /** Prevent direct execution from the mount. */ noexec(): this /** Ignore setuid and setgid privilege elevation from files on the mount. */ nosuid(): this /** Ignore device files on the mount. */ nodev(): this /** Tmpfs size cap in MiB (only valid with `.tmpfs()`). */ size(mib: number): this /** * Guest-write quota in MiB (only valid with `.bind()`). * * Bounds how much the guest may add beyond the bind-mounted directory's * existing contents. Without it, a protective default is applied. */ quota(mib: number): this /** * Set the guest stat virtualization policy. * * Accepts `"strict"`, `"relaxed"`, or `"off"`. Valid only for bind and * directory-backed named or owned volume mounts. */ statVirtualization(policy: string): this /** * Set the host permission propagation policy. * * Accepts `"private"` or `"mirror"`. Valid only for bind and * directory-backed named or owned volume mounts. */ hostPermissions(policy: string): this /** * Present host files that carry no per-file stat override as this guest * owner. Valid only for bind and directory-backed named or owned volume mounts. */ owner(uid: number, gid: number): this /** * Materialize the mount spec. Returns a flat `VolumeMount` with a * `kind` discriminator and per-variant fields. */ build(): VolumeMount } export type JsMountBuilder = MountBuilder /** Fluent builder for sandbox network configuration. */ export declare class NetworkBuilder { constructor() /** Enable or disable networking. */ enabled(enabled: boolean): this /** Publish a TCP port. */ port(hostPort: number, guestPort: number): this /** Publish a TCP port on a specific host bind address. */ portBind(bind: string, hostPort: number, guestPort: number): this /** Publish a UDP port. */ portUdp(hostPort: number, guestPort: number): this /** Publish a UDP port on a specific host bind address. */ portUdpBind(bind: string, hostPort: number, guestPort: number): this /** * Set a policy. Construct via the JS-side `NetworkPolicy.fromProfiles()` * / `.allowAll()` / `.none()` factories or build a * custom one and pass it through `JSON.stringify`-friendly JSON. Here * we accept the canonical serialized form (a JSON string) to avoid * re-modeling the rule schema across the FFI; Phase 7 reconciles. */ policyJson(json: string): this /** * Set a policy from a `NetworkPolicyBuilder`. Equivalent to * calling `builder.build()` and passing the result through * `.policy()`, but skips the JSON round-trip. */ policyFromBuilder(builder: JsNetworkPolicyBuilder): this /** * Configure DNS interception via a callback. The callback receives * a fresh `DnsBuilder`; chain setters on it and return. */ dns(configure: (arg: DnsBuilder) => DnsBuilder): this /** Configure TLS interception via a callback. */ tls(configure: (arg: JsTlsBuilder) => JsTlsBuilder): this /** Add a secret via a callback. */ secret(configure: (arg: JsSecretBuilder) => JsSecretBuilder): this /** 4-arg shorthand: add a secret with explicit placeholder. */ secretEnv(envVar: string, value: string, placeholder: string, allowedHost: string): this /** * Add a secret using the same generated placeholder as SandboxBuilder. * Enables TLS interception while preserving existing TLS settings. */ secretEnvSimple(envVar: string, value: string, allowedHost: string): this /** * Set per-NIC overrides (MAC / MTU / IPv4 / IPv6) for the guest * interface. The closure receives a fresh `InterfaceOverridesBuilder`. */ interface(configure: (arg: InterfaceOverridesBuilder) => InterfaceOverridesBuilder): this /** Configure the default blocking action for secret placeholders. */ secretViolationAction(action: string): this /** @deprecated Use maxTcpConnections instead. */ maxConnections(max: number): this /** Set the TCP connection cap; zero selects unlimited. */ maxTcpConnections(max: number): this /** Set the UDP session cap; zero selects unlimited. Defaults to unlimited for single-tenant and 1024 for multi-tenant. */ maxUdpConnections(max: number): this /** * Set the accept-queue depth for published TCP port listeners, 1..=2147483647. Defaults to * 1024; the host kernel clamps it to its own somaxconn. */ tcpAcceptQueueSize(size: number): this /** Require hostname-based policy allows to use inspectable application authority. */ strict(enabled: boolean): this /** Set the IPv4 pool used for per-sandbox /30 guest subnets. */ ipv4Pool(pool: string): this /** Set the IPv6 pool used for per-sandbox /64 guest prefixes. */ ipv6Pool(pool: string): this /** Add a NAT64 /96 prefix for policy classification. */ nat64Prefix(prefix: string): this /** Trust the host's root CAs inside the guest. Default: false. */ trustHostCAs(enabled: boolean): this /** Configure HTTP denial responses via a callback. */ http(configure: (arg: HttpBuilder) => HttpBuilder): this /** * Configure local egress and ingress rate limits. Applies on the next * sandbox start. * * ```js * .rateLimiter((r) => r * .egress((r) => r * .bandwidth(1_048_576, 1_000) * .ops(1_000, 1_000))) * ``` */ rateLimiter(configure: (arg: JsNetworkRateLimiterBuilder) => JsNetworkRateLimiterBuilder): this /** * Snapshot the accumulated configuration as a JSON string. The TS * layer parses + key-remaps to camelCase before returning to the * caller. */ buildJson(): string } export type JsNetworkBuilder = NetworkBuilder /** * Fluent builder for `NetworkPolicy`. * * Mirrors `microsandbox_network::policy::NetworkPolicyBuilder`. All * inputs are recorded eagerly; `.build()` replays them onto the Rust * builder, which lazily parses string IPs/CIDRs/domains and validates * `direction`-set + ICMP-egress-only invariants. The first error is * surfaced from `.build()`. */ export declare class NetworkPolicyBuilder { constructor() /** Set both `default_egress` and `default_ingress` to `Allow`. */ defaultAllow(): this /** Set both `default_egress` and `default_ingress` to `Deny`. */ defaultDeny(): this /** * Per-direction override for the egress default action. * `action` is `"allow"` or `"deny"`. */ defaultEgress(action: string): this /** Per-direction override for the ingress default action. */ defaultIngress(action: string): this /** * Open a multi-rule batch closure. Direction must be set inside via * `.egress()` / `.ingress()` / `.any()` before any rule-adder. */ rule(configure: (arg: RuleBuilder) => RuleBuilder): this /** Sugar for `.rule()` with direction pre-set to `Egress`. */ egress(configure: (arg: RuleBuilder) => RuleBuilder): this /** Sugar for `.rule()` with direction pre-set to `Ingress`. */ ingress(configure: (arg: RuleBuilder) => RuleBuilder): this /** Sugar for `.rule()` with direction pre-set to `Any`. */ any(configure: (arg: RuleBuilder) => RuleBuilder): this /** * Materialize into a `NetworkPolicy` (camelCase JS object). Lazily * parses every recorded `.ip()` / `.cidr()` / `.domain()` / * `.domainSuffix()` input, validates `direction`-set + ICMP-egress- * only invariants, and surfaces the first failure. */ build(): NetworkPolicy } export type JsNetworkPolicyBuilder = NetworkPolicyBuilder /** Fluent builder grouping egress and ingress rate limits. */ export declare class NetworkRateLimiterBuilder { constructor() /** Configure guest-to-runtime traffic limits. */ egress(configure: (arg: RateLimiterBuilder) => RateLimiterBuilder): this /** Configure runtime-to-guest traffic limits. */ ingress(configure: (arg: RateLimiterBuilder) => RateLimiterBuilder): this } export type JsNetworkRateLimiterBuilder = NetworkRateLimiterBuilder /** Selects the protocol for an outbound proxy. */ export declare class OutboundProxyBuilder { constructor() /** Select an HTTP CONNECT proxy at `address`. */ httpConnect(address: string): HttpConnectProxyBuilder /** Select a SOCKS4 proxy at `address`. */ socks4(address: string): Socks4ProxyBuilder /** Select a SOCKS5 proxy at `address`. */ socks5(address: string): Socks5ProxyBuilder } export type JsOutboundProxyBuilder = OutboundProxyBuilder /** Builds an HTTP CONNECT outbound proxy. */ export declare class HttpConnectProxyBuilder {} /** Fluent builder for an ordered list of pre-boot rootfs patches. */ export declare class PatchBuilder { constructor() /** Write a text file (UTF-8) at `path`. */ text(path: string, content: string, opts?: PatchFileOptions | undefined | null): this /** Write raw bytes at `path`. */ file(path: string, content: Buffer, opts?: PatchFileOptions | undefined | null): this /** Copy a host file into the rootfs at `dst`. */ copyFile(src: string, dst: string, opts?: PatchFileOptions | undefined | null): this /** Copy a host directory into the rootfs at `dst`. */ copyDir(src: string, dst: string, opts?: PatchReplaceOnly | undefined | null): this /** Create a symlink at `link` pointing to `target`. */ symlink(target: string, link: string, opts?: PatchReplaceOnly | undefined | null): this /** Create a directory (idempotent). */ mkdir(path: string, opts?: PatchModeOnly | undefined | null): this /** Remove a file or directory (idempotent). */ remove(path: string): this /** Append text to an existing file. */ append(path: string, content: string): this /** Materialize into the ordered list of patches. */ build(): Array } export type JsPatchBuilder = PatchBuilder /** * Pair returned by `createWithPullProgress`: the progress event stream * plus a method to await the final `Sandbox`. */ export declare class PullProgressCreate { /** Cancel creation, independently of whether awaitSandbox is already waiting. */ cancel(): void /** * The progress event stream. Iterate with `for await...of` or * poll with `.recv()`. The stream closes once the pull completes. */ get progress(): PullProgressStream /** * Await the sandbox. Resolves once the pull + boot finishes. * Calling more than once errors. */ awaitSandbox(): Promise } export type JsPullProgressCreate = PullProgressCreate /** * Streaming subscription for image-pull progress events. * * Supports both manual `recv()` and `for await...of` iteration: * ```js * const { sandbox, progress } = await Sandbox.builder("demo") * .image("alpine:latest") * .createWithPullProgress(); * for await (const ev of progress) { * if (ev.kind === "layerDownloadProgress") { … } * } * const sb = await sandbox; // resolves once create finishes * ``` * * This type implements JavaScript's async iterable protocol. * It can be used with `for await...of` loops. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols */ export declare class PullProgressStream { /** * Receive the next progress event. Returns `null` when the pull * completes (channel closed). */ recv(): Promise [Symbol.asyncIterator](): AsyncGenerator } export type JsPullProgressStream = PullProgressStream /** * Fluent builder for one direction's network rate limiter. Chainable * setters accumulate bucket values for `NetworkRateLimiterBuilder`. */ export declare class RateLimiterBuilder { constructor() /** Cap bandwidth at `sizeBytes` bytes per `refillTimeMs` milliseconds. */ bandwidth(sizeBytes: number, refillTimeMs: number): this /** * Grant a one-time startup burst of `sizeBytes` bytes on top of the * bandwidth bucket. Requires `bandwidth()`. */ bandwidthBurst(sizeBytes: number): this /** Cap packet rate at `count` frames per `refillTimeMs` milliseconds. */ ops(count: number, refillTimeMs: number): this /** * Grant a one-time startup burst of `count` frames on top of the ops * bucket. Requires `ops()`. */ opsBurst(count: number): this } export type JsRateLimiterBuilder = RateLimiterBuilder /** Fluent builder for OCI registry connection settings. */ export declare class RegistryConfigBuilder { constructor() /** Set authentication credentials. */ auth(auth: RegistryAuthInput): this /** Use plain HTTP (no TLS). */ insecure(): this /** * Add a PEM-encoded CA root certificate (raw bytes). May be called * repeatedly to add several CAs. */ caCerts(pemData: Buffer): this /** * Read a PEM CA root certificate from `path` and add it. Convenience * shorthand over `caCerts(buffer)`. Panics on read failure deferred * to the next async call site if the path doesn't exist (we surface * it as a typed error there). */ caCertsPath(path: string): this /** Snapshot the accumulated configuration. */ build(): RegistryConfig } export type JsRegistryConfigBuilder = RegistryConfigBuilder /** Snapshot restoration with explicit destination resource bindings. */ export declare class RestoreBuilder { /** Select an installed snapshot or archive; this does not start a VM. */ constructor(snapshot: string, referenceKind?: string | undefined | null) /** Choose the destination sandbox name. */ name(name: string): this /** Set destination CPUs; full execution restore requires the captured count. */ cpus(count: number): this /** Set destination memory in MiB; full execution restore requires captured geometry. */ memory(mib: number): this /** Set only host-side network policy, without DNS, TLS, or guest bootstrap changes. */ networkPolicyJson(json: string): this /** Set host-side policy from the existing policy builder. */ networkPolicyFromBuilder(builder: NetworkPolicyBuilder): this /** @deprecated Use maxTcpConnections instead. */ maxConnections(count: number): this /** Cap destination host-side TCP connections; zero selects unlimited. */ maxTcpConnections(count: number): this /** Cap destination host-side UDP sessions; zero selects unlimited. */ maxUdpConnections(count: number): this /** Disable networking; full restore rejects removal of a captured NIC. */ disableNetwork(): this /** Set guest security for disk boot; explicit changes are rejected by full restore. */ security(profile: 'default' | 'restricted'): this /** Apply the destination host's maximum runtime in seconds; zero expires immediately. */ maxDuration(secs: number): this /** Apply the destination host's idle timeout in seconds; zero expires immediately. */ idleTimeout(secs: number): this /** Accept missing restore resources without inheriting host resources. */ allowMissingResources(): this /** Explicitly reuse locally validated source resource bindings. */ dangerouslyInheritResources(): this /** Supply the base for omitted disk layers and RAM objects in a snapshot archive. */ snapshotBase(base: string): this /** Cold-boot only the disk state carried by a full snapshot. */ diskOnly(): this /** @deprecated Use cowMemory() instead. */ forked(): this /** Restore a full snapshot with private copy-on-write memory. */ cowMemory(): this /** * Validate authorized filesystem mappings strictly (default) or allow supported mismatches. * Neither policy inherits resources; unmapped filesystems remain unavailable. */ externalMountPolicy(policy: 'strict' | 'relaxed'): this /** Override log verbosity: `"trace" | "debug" | "info" | "warn" | "error"`. */ logLevel(level: string): this /** Default running user. */ user(user: string): this /** * Configure a volume mount via a callback. The callback receives a * `MountBuilder` already pre-bound to `guestPath`. */ volume(guestPath: string, configure: (arg: MountBuilder) => MountBuilder): this /** Publish a TCP port from host -> guest. */ port(hostPort: number, guestPort: number): this /** Publish a TCP port from host -> guest on a specific host bind address. */ portBind(bind: string, hostPort: number, guestPort: number): this /** Publish a UDP port from host -> guest. */ portUdp(hostPort: number, guestPort: number): this /** Publish a UDP port from host -> guest on a specific host bind address. */ portUdpBind(bind: string, hostPort: number, guestPort: number): this /** Set the accept-queue depth for the child's published TCP listeners, 1..=2147483647. */ tcpAcceptQueueSize(size: number): this /** Expose a host Unix stream socket or local Windows named pipe on a guest-to-host vsock port. */ vsock(hostPath: string, port: number): this /** Expose a host Unix datagram socket on a guest-to-host vsock port. */ vsockDgram(hostPath: string, port: number): this /** * Restore a detached sandbox and wait until ready. * * # Safety * The builder is consumed before suspension; callers must not reuse it. */ restore(): Promise /** * Restore with image, snapshot preparation and activation progress. * * # Safety * The builder is consumed before suspension; callers must not reuse it. */ restoreWithProgress(): Promise } export type JsRestoreBuilder = RestoreBuilder /** * Fluent builder for the root disk of an OCI image. * * Used inside `ImageBuilder.rootDisk((d) => ...)`: * * ```ts * .imageWith((i) => i.oci("python:3.12").rootDisk(8192)) // managed, sized * .imageWith((i) => i.oci("python:3.12").rootDisk((d) => d.tmpfs().size(512))) // RAM-backed * .imageWith((i) => i.oci("python:3.12").rootDisk((d) => d.disk("./scratch.img").fstype("ext4"))) * .imageWith((i) => i.oci("python:3.12").rootDisk((d) => d.flat().size(8192))) * ``` */ export declare class RootDiskBuilder { constructor() /** * Size in MiB. Valid for the managed (default), tmpfs, and flat kinds; a * user-supplied disk image is sized by the image file itself. */ size(mib: number): this /** * Use a RAM-backed tmpfs upper. Ephemeral: the rootfs is pristine on * every boot, and the size counts against guest memory. */ tmpfs(): this /** Use a complete flat ext4 OCI rootfs without guest OverlayFS. */ flat(): this /** * Use a user-supplied disk image as the upper, attached writable. The * format is derived from the file extension (`.img`/`.raw` → raw, * `.qcow2` → qcow2) unless set explicitly with `.format()`. */ disk(path: string): this /** * Set the disk image format explicitly (`"raw" | "qcow2"`). Only valid * after `.disk()`; vmdk is not supported as a root disk. */ format(format: string): this /** * Inner filesystem type (currently `"ext4"` for flat roots). Valid * after `.disk()` or `.flat()`. */ fstype(fstype: string): this /** Select `"auto"`, `"copy"`, or `"reflink"` private-disk provisioning. */ cloneStrategy(strategy: string): this } export type JsRootDiskBuilder = RootDiskBuilder /** * Per-rule-batch builder. Lives only inside the closure passed to * `.rule()` / `.egress()` / `.ingress()` / `.any()`. State (direction, * protocols, ports) accumulates across rule-adders within the closure * and is **not reset** between them — separate `.rule()` calls are how * you reset state. */ export declare class RuleBuilder { /** Set direction to `Egress` for subsequent rule-adders. Last-write-wins. */ egress(): this /** Set direction to `Ingress` for subsequent rule-adders. */ ingress(): this /** Set direction to `Any` (rules apply in both directions). */ any(): this /** Add `Tcp` to the protocols set. */ tcp(): this /** Add `Udp` to the protocols set. */ udp(): this /** Add `Icmpv4` to the protocols set. Egress-only. */ icmpv4(): this /** Add `Icmpv6` to the protocols set. Egress-only. */ icmpv6(): this /** Add a single port to the ports set. `0..=65535`. */ port(port: number): this /** * Add an inclusive port range. `lo > hi` records an error surfaced * at `.build()` time. */ portRange(lo: number, hi: number): this /** Add multiple single ports. */ ports(ports: Array): this allowPublic(): this denyPublic(): this allowPrivate(): this denyPrivate(): this allowLoopback(): this denyLoopback(): this allowLinkLocal(): this denyLinkLocal(): this allowMeta(): this denyMeta(): this allowMulticast(): this denyMulticast(): this allowHost(): this denyHost(): this /** Allow `Loopback + LinkLocal + Host` (no `Metadata`). */ allowLocal(): this /** Deny `Loopback + LinkLocal + Host`. */ denyLocal(): this /** Allow `Destination::Domain(name)`. One rule per call. */ allowDomain(name: string): this /** Deny `Destination::Domain(name)`. One rule per call. */ denyDomain(name: string): this /** Allow each name as a `Destination::Domain` rule. */ allowDomains(names: Array): this /** Deny each name as a `Destination::Domain` rule. */ denyDomains(names: Array): this /** * Allow `Destination::DomainSuffix(suffix)`. Matches the apex and * any subdomain. */ allowDomainSuffix(suffix: string): this /** * Deny `Destination::DomainSuffix(suffix)`. Matches the apex and * any subdomain. */ denyDomainSuffix(suffix: string): this /** Allow each suffix as a `Destination::DomainSuffix` rule. */ allowDomainSuffixes(suffixes: Array): this /** Deny each suffix as a `Destination::DomainSuffix` rule. */ denyDomainSuffixes(suffixes: Array): this /** * Begin an explicit-destination rule with action `Allow`. The * closure receives a `RuleDestinationBuilder` and must call exactly * one of `.ip()` / `.cidr()` / `.domain()` / `.domainSuffix()` / * `.group()` / `.any()` to commit the rule. */ allow(configure: (arg: RuleDestinationBuilder) => RuleDestinationBuilder): this /** Begin an explicit-destination rule with action `Deny`. */ deny(configure: (arg: RuleDestinationBuilder) => RuleDestinationBuilder): this } export type JsRuleBuilder = RuleBuilder /** * Terminal builder returned by `RuleBuilder.allow(d => ...)` / * `.deny(d => ...)`. Exactly one destination call (`.ip`, `.cidr`, * `.domain`, `.domainSuffix`, `.group`, `.any`) commits the rule; * dropping without a destination call silently does nothing. */ export declare class RuleDestinationBuilder { /** * Commit the rule with destination `Ip()`. Parsed at * `.build()` time; invalid IPs surface as `InvalidIp` then. */ ip(ip: string): this /** Commit the rule with destination `Cidr()`. */ cidr(cidr: string): this /** * Commit the rule with destination `Domain()`. Matches only * when a cached hostname for the remote IP equals this name. */ domain(domain: string): this /** * Commit the rule with destination `DomainSuffix()`. Matches * the apex domain itself and any subdomain. */ domainSuffix(suffix: string): this /** * Commit the rule with destination `Group()`. `group` is * one of the `DestinationGroup` strings (`"public" | "private" | * "loopback" | "link-local" | "metadata" | "multicast" | "host"`). */ group(group: string): this /** Commit the rule with destination `Any` (matches every remote). */ any(): this } export type JsRuleDestinationBuilder = RuleDestinationBuilder /** * A running sandbox instance. * * Created via `Sandbox.create()` or `Sandbox.start()`. Holds a live connection * to the guest VM and can execute commands, access the filesystem, and query metrics. */ export declare class Sandbox { /** * Start an existing stopped sandbox (attached mode). * * Sandbox names are limited to 128 UTF-8 bytes. */ static start(name: string): Promise /** * Start an existing stopped sandbox (detached mode). * * Sandbox names are limited to 128 UTF-8 bytes. */ static startDetached(name: string): Promise /** * Get a lightweight handle to an existing sandbox. * * Sandbox names are limited to 128 UTF-8 bytes. */ static get(name: string): Promise /** List the first page of sandboxes. */ static list(): Promise /** List a configured page of sandboxes. */ static listWith(options: SandboxListOptions): Promise /** * Remove a stopped sandbox from the database. * * Sandbox names are limited to 128 UTF-8 bytes. */ static remove(name: string): Promise /** Backend retained by this sandbox (`"local"` or `"cloud"`). */ get backendKind(): string /** Sandbox name. Names are limited to 128 UTF-8 bytes. */ get name(): Promise /** Stable backend-assigned identity for this persisted sandbox. */ get id(): string /** Whether this handle owns the sandbox lifecycle (attached mode). */ get ownsLifecycle(): boolean /** * Get the full configuration this sandbox was created with * (image, cpus, memory, env, mounts, etc.) as a JSON string. * The TS layer parses + camelCase-remaps this into a plain object. */ configJson(): Promise /** Execute the sandbox's effective OCI entrypoint and CMD. */ execDefault(): Promise /** Execute the sandbox's effective OCI entrypoint and CMD using a populated options builder. */ execDefaultWithBuilder(builder: ExecOptionsBuilder): Promise /** Execute the sandbox's effective OCI entrypoint and CMD with streaming I/O. */ execDefaultStream(): Promise /** Stream the sandbox's effective OCI entrypoint and CMD using a populated options builder. */ execDefaultStreamWithBuilder(builder: ExecOptionsBuilder): Promise /** Execute a command and wait for completion. */ exec(cmd: string, args?: Array | undefined | null): Promise /** * Execute a command using a populated `ExecOptionsBuilder`. The TS * layer wraps this in a closure-callback API (`execWith(cmd, b => …)`). */ execWithBuilder(cmd: string, builder: ExecOptionsBuilder): Promise /** Execute a command with streaming I/O. */ execStream(cmd: string, args?: Array | undefined | null): Promise /** * Execute a command with streaming I/O using a populated * `ExecOptionsBuilder`. The TS layer wraps this in a closure-callback * API (`execStreamWith(cmd, b => …)`). Set `b.stdinPipe()` on the * builder for bidirectional streams. */ execStreamWithBuilder(cmd: string, builder: ExecOptionsBuilder): Promise /** Execute a shell command using the sandbox's configured shell. */ shell(script: string): Promise /** Execute a shell command with streaming I/O. */ shellStream(script: string): Promise /** Get a filesystem handle for operations on the running sandbox. */ fs(): SandboxFsOps /** Connect a native in-process SSH client to this sandbox. */ sshConnect(options?: SshClientOptions | undefined | null): Promise /** Prepare a reusable SSH server endpoint for this sandbox. */ sshServer(options?: SshServerOptions | undefined | null): Promise /** Get point-in-time resource metrics. */ metrics(): Promise /** Check whether agentd is reachable without refreshing idle activity. */ ping(): Promise /** Explicitly refresh this sandbox's idle activity timer. */ touch(): Promise /** * Plan or apply a sandbox modification. Returns the plan as a JSON * string; the TS wrapper parses it into a `SandboxModificationPlan`. */ modify(options?: SandboxModifyOptions | undefined | null): Promise /** Compact root and owned-data disk prefixes; the limit includes the base, not the writable head. */ compact(layers?: number | undefined | null, dryRun?: boolean | undefined | null, disk?: string | undefined | null, rootDiskOnly?: boolean | undefined | null): Promise /** Stream metrics snapshots at the requested interval (in milliseconds). */ metricsStream(intervalMs: number): Promise /** Attach to the sandbox's effective OCI entrypoint and CMD. */ attachDefault(): Promise /** Attach to the sandbox's effective OCI entrypoint and CMD using a populated options builder. */ attachDefaultWithBuilder(builder: AttachOptionsBuilder): Promise /** * Attach to an interactive PTY session inside the sandbox. * * Bridges the host terminal to the guest process. Returns the exit code. */ attach(cmd: string, args?: Array | undefined | null): Promise /** * Attach using a populated `AttachOptionsBuilder`. The TS layer * wraps this in a closure-callback API (`attachWith(cmd, b => …)`). */ attachWithBuilder(cmd: string, builder: AttachOptionsBuilder): Promise /** Attach to the sandbox's default shell. */ attachShell(): Promise /** Stop the sandbox gracefully and wait for it to exit. */ stop(): Promise /** Warnings for unmapped external filesystems and accepted restore mismatches. */ restoreWarnings(): Promise> /** @deprecated Use fork for live execution duplication. */ branch(name: string, recordIntegrity?: boolean | undefined | null, guestFlush?: string | undefined | null): Promise /** @deprecated Use forkMany for live execution duplication. */ branchMany(names: Array, recordIntegrity?: boolean | undefined | null, guestFlush?: string | undefined | null): Promise> /** Create an independent local CoW child without a durable full snapshot. */ fork(name: string, recordIntegrity?: boolean | undefined | null, guestFlush?: string | undefined | null): Promise /** Capture once and return individual child startup outcomes. */ forkMany(names: Array, recordIntegrity?: boolean | undefined | null, guestFlush?: string | undefined | null): Promise> /** Explicit resident pause through host control. */ pause(guestFlush?: string | undefined | null): Promise /** Explicit resident resume through host control. */ resume(): Promise /** Stop and wait for exit, returning the exit status. */ stopAndWait(): Promise /** Request graceful shutdown without waiting for observed exit. */ requestStop(): Promise /** One graceful-completion budget; expiry rejects without killing, including zero. */ stopWithTimeout(timeoutMs: number): Promise /** Kill the sandbox immediately and wait for observed exit. */ kill(): Promise /** Request force termination without waiting for observed exit. */ requestKill(): Promise /** Force-kill the sandbox with an explicit observation timeout. */ killWithTimeout(timeoutMs: number): Promise /** Graceful drain (SIGUSR1 — for load balancing). */ drain(): Promise /** Request graceful drain without waiting for observed exit. */ requestDrain(): Promise /** Wait until this exact sandbox reaches the requested status. */ waitForStatus(status: string): Promise /** Stop and start this exact sandbox. */ restart(options?: SandboxRestartOptions | undefined | null): Promise /** Stop and remove this exact sandbox. */ destroy(options?: SandboxDestroyOptions | undefined | null): Promise /** Wait until the sandbox is observed in a terminal non-running state. */ waitUntilStopped(): Promise /** Wait for the sandbox process to exit. */ wait(): Promise /** * Detach from the sandbox — it will continue running after this handle is dropped. * New operations are rejected; already admitted operations retain their connection. */ detach(): Promise /** * Remove the persisted database record after stopping. * Consumes this wrapper even on failure. Already admitted operations may finish or * fail at the runtime boundary; removal does not wait for guest operations to drain. */ removePersisted(): Promise /** * Read captured output from `exec.log` for this sandbox. * * Reads the on-disk JSON Lines file the runtime writes via the * relay tap. Works on running and stopped sandboxes alike — no * protocol traffic. */ logs(opts?: LogOptions | undefined | null): Promise> /** * Stream captured output as it appears, with optional follow. * * Returns an async iterable of `LogEntry`. Each entry carries * an opaque `cursor` token suitable for passing back via * `fromCursor` on a later call to resume exactly after that * entry. */ logStream(opts?: LogStreamOptions | undefined | null): Promise } /** * Fluent builder for a sandbox. Mirrors `microsandbox::sandbox::SandboxBuilder` * 1:1; setters mutate in place and return `this`. Closure-style * sub-builders (volume / patch / network / secret / registry / imageWith) * receive a fresh napi-wrapped builder, let JS chain on it, and route * the result back through the core SDK's closure callback. Sandbox names are * limited to 128 UTF-8 bytes. */ export declare class SandboxBuilder { /** Start building a sandbox. Names are limited to 128 UTF-8 bytes. */ constructor(name: string) /** * Set the rootfs image source. Accepts an OCI reference or a host * path (paths starting with `/`, `./`, `../` resolve as local; disk * image extensions `.qcow2`/`.raw`/`.vmdk` resolve to virtio-blk). */ image(image: string): this /** Configure a disk-image rootfs explicitly via a callback. */ imageWith(configure: (arg: ImageBuilder) => ImageBuilder): this /** * Configure the writable rootfs layer (root disk) for the OCI image. * * Sugar over `imageWith((i) => i.oci(...).rootDisk(...))` — the root * disk lives on the OCI rootfs source, so an OCI image must be set * first. Pass a number of MiB for a managed root disk, or a callback * for the tmpfs, flat, and disk-image kinds: * * ```ts * .image("python").rootDisk(8192) * .image("python").rootDisk((d) => d.tmpfs().size(512)) * .image("python").rootDisk((d) => d.flat().size(8192).cloneStrategy("auto")) * .image("python").rootDisk((d) => d.disk("./scratch.img")) * ``` */ rootDisk(sizeMibOrConfigure: number | ((d: RootDiskBuilder) => RootDiskBuilder)): this /** Number of virtual CPUs. */ cpus(count: number): this /** Boot-time maximum possible virtual CPUs. */ maxCpus(count: number): this /** Host CPU placement policy. */ cpuPlacement(policy: string): this /** Host-defined placement profile name. */ placementProfile(profile: string): this /** Guest memory in MiB. */ memory(mib: number): this /** Boot-time maximum hotpluggable guest memory in MiB. */ maxMemory(mib: number): this /** Guest transparent huge-page policy selected at boot. */ thp(policy: 'always' | 'madvise' | 'never'): this /** Override log verbosity: `"trace" | "debug" | "info" | "warn" | "error"`. */ logLevel(level: string): this /** Suppress sandbox logs. */ quietLogs(): this /** Create the sandbox in detached/background mode when enabled. */ detached(detached: boolean): this /** * Mark the sandbox as ephemeral (or persistent). * * Ephemeral sandboxes are removed by the host runtime after the VM * reaches a terminal status. Logs and captured output are removed with * the sandbox directory. */ ephemeral(ephemeral: boolean): this /** Override the metrics sampling interval in milliseconds; pass `0` to disable. */ metricsSampleIntervalMs(ms: number): this /** Force-disable metrics sampling regardless of `metricsSampleIntervalMs`. */ disableMetricsSample(): this /** Default working directory for commands. */ workdir(path: string): this /** Shell binary used by `Sandbox.shell(...)`. */ shell(shell: string): this /** In-guest security profile (`"default"` or `"restricted"`). */ security(profile: string): this /** * Host-runtime deployment profile (`"single-tenant"` or `"multi-tenant"`). * Managed backends may enforce their own profile. */ deploymentProfile(profile: string): this /** Configure registry connection settings via a callback. */ registry(configure: (arg: RegistryConfigBuilder) => RegistryConfigBuilder): this /** * Replace any existing sandbox with the same name. * * SIGTERMs the prior instance, waits up to 10 seconds for a * graceful exit, then SIGKILLs. To override the timeout, use * `replaceWithTimeout(ms)`; `replaceWithTimeout(0)` skips SIGTERM * and SIGKILLs immediately. */ replace(): this /** * Replace any existing sandbox, overriding the SIGTERM-to-SIGKILL * timeout. Implies `replace` — calling this alone is enough. * * - `timeoutMs > 0`: SIGTERM, wait up to `timeoutMs`, then SIGKILL. * - `timeoutMs == 0`: SIGKILL immediately (skip SIGTERM). * * The default timeout used by `replace` is 10_000 ms. An expired * timeout force-kills the prior sandbox; `create()` still proceeds. */ replaceWithTimeout(timeoutMs: number): this /** Override the image entrypoint. */ entrypoint(cmd: Array): this /** Override the image CMD used by default-workload execution. */ cmd(cmd: Array): this /** * Hand off PID 1 to a guest init binary after agentd's setup. * * `cmd` is either an absolute path inside the guest rootfs or * the literal `"auto"`. Auto honors known image ENTRYPOINT inits, * preserves attached init-entrypoint commands, then probes common * guest paths. `args` is the supplemental argv; `argv[0]` is * implicitly `cmd`. For env vars, use `initWith`. */ init(cmd: string, args?: Array | undefined | null): this /** * Hand off PID 1 with a closure-builder for argv and env. Mirrors * `imageWith` — the closure is invoked synchronously and returns * the populated `InitOptionsBuilder`. */ initWith(cmd: string, configure: (arg: InitOptionsBuilder) => InitOptionsBuilder): this /** Override the guest hostname. */ hostname(name: string): this /** * Deprecated compatibility setter for older Node SDK callers. * * The libkrunfw path is a process-level concern (one dylib per process * address space), not a per-sandbox builder setting. Keep this chainable * alias so pre-backend-split code still compiles, but route it through the * same process-wide override as `microsandbox.setRuntimeLibkrunfwPath(...)`. */ libkrunfwPath(path: string): this /** Default running user. */ user(user: string): this /** Image pull policy: `"always" | "if-missing" | "never"`. */ pullPolicy(policy: string): this /** Disable networking entirely. */ disableNetwork(): this /** Configure networking via a callback. */ network(configure: (arg: NetworkBuilder) => NetworkBuilder): this /** Configure the single proxy used for outbound sandbox connections. */ proxy(configure: (arg: OutboundProxyBuilder) => HttpConnectProxyBuilder | Socks4ProxyBuilder | Socks5ProxyBuilder): this /** Publish a TCP port from host -> guest. */ port(hostPort: number, guestPort: number): this /** Publish a TCP port from host -> guest on a specific host bind address. */ portBind(bind: string, hostPort: number, guestPort: number): this /** Publish a UDP port from host -> guest. */ portUdp(hostPort: number, guestPort: number): this /** Publish a UDP port from host -> guest on a specific host bind address. */ portUdpBind(bind: string, hostPort: number, guestPort: number): this /** Expose a host Unix stream socket or local Windows named pipe on a guest-to-host vsock port. */ vsock(hostPath: string, port: number): this /** Expose a host Unix datagram socket on a guest-to-host vsock port. */ vsockDgram(hostPath: string, port: number): this /** Add a secret via a callback. */ secret(configure: (arg: JsSecretBuilder) => JsSecretBuilder): this /** * Shorthand: add a secret. Auto-generates the placeholder as * `$MSB_` and allows substitution only on `allowed_host`. */ secretEnv(envVar: string, value: string, allowedHost: string): this /** Set a single environment variable. */ env(key: string, value: string): this /** Set environment variables from an object. */ envs(vars: Record): this /** Attach a single label for metrics attribution. */ label(key: string, value: string): this /** Attach labels from an object for metrics attribution. */ labels(labels: Record): this /** Set a hard rlimit (soft = hard). */ rlimit(resource: string, limit: number): this /** Set a separate soft and hard rlimit. */ rlimitRange(resource: string, soft: number, hard: number): this /** Mount a script under `/.msb/scripts/` inside the guest. */ script(name: string, content: string): this /** Mount many scripts at once. */ scripts(scripts: Record): this /** Auto-stop after `secs` seconds. */ maxDuration(secs: number): this /** Auto-stop after `secs` seconds of inactivity. */ idleTimeout(secs: number): this /** * Configure a volume mount via a callback. The callback receives a * `MountBuilder` already pre-bound to `guestPath`. */ volume(guestPath: string, configure: (arg: MountBuilder) => MountBuilder): this /** Add a single rootfs patch built externally. */ addPatch(patch: Patch): this /** Apply rootfs patches via a callback. */ patch(configure: (arg: PatchBuilder) => PatchBuilder): this /** * Materialize the built configuration without creating a sandbox. * Returns the JSON-serialized `SandboxConfig` for inspection. * * # Safety * See `create` for the `&mut self` async + `unsafe` rationale. */ build(): Promise /** * Create and start the sandbox. * * # Safety * `&mut self` async is required because we drain `inner` * synchronously before awaiting; napi-rs requires the `unsafe` tag * regardless. JS callers see `create(): Promise`. */ create(): Promise /** * Connect to the persisted sandbox with this name, or create it. * * # Safety * Same justification as `create`. */ connectOrCreate(): Promise /** * Create the sandbox with image-pull progress reporting. Returns * a `PullProgressStream` of per-layer download/materialization * events. The actual `Sandbox` is awaited via `.awaitSandbox()` * on the returned object — the TS layer wraps this with a * closure-callback API on the public surface. * * # Safety * Same justification as `create`. */ createWithPullProgress(): Promise /** * Create with image, snapshot preparation and activation progress. * * # Safety * Same consumed-builder ownership requirement as `create`. */ createWithProgress(): Promise } export type JsSandboxBuilder = SandboxBuilder /** Filesystem operations on a running sandbox (via agent protocol). */ export declare class SandboxFsOps { /** Read a file as a Buffer. */ read(path: string): Promise /** Read a file as a UTF-8 string. */ readString(path: string): Promise /** Write data to a file (accepts Buffer or string). */ write(path: string, data: Buffer): Promise /** List directory contents. */ list(path: string): Promise> /** Create a directory. */ mkdir(path: string): Promise /** Remove a directory. */ removeDir(path: string): Promise /** Remove a file. */ remove(path: string): Promise /** Copy a file within the sandbox. */ copy(from: string, to: string): Promise /** Rename a file within the sandbox. */ rename(from: string, to: string): Promise /** Get file or directory metadata. */ stat(path: string): Promise /** Check if a path exists. */ exists(path: string): Promise /** Copy a file from the host into the sandbox. */ copyFromHost(hostPath: string, guestPath: string): Promise /** Copy a file from the sandbox to the host. */ copyToHost(guestPath: string, hostPath: string): Promise /** Read a file with streaming (~3 MiB chunks). */ readStream(path: string): Promise /** Write a file with streaming. Returns a sink the caller writes to. */ writeStream(path: string): Promise } export type JsSandboxFsOps = SandboxFsOps /** * A lightweight handle to a sandbox from the database. * * Does NOT hold a live connection — use `connect()` or `start()` to get a live `Sandbox`. */ export declare class SandboxHandle { /** Observe object storage through its captured backend. */ storageUsage(): Promise /** Sandbox name. Names are limited to 128 UTF-8 bytes. */ get name(): string /** Stable backend-assigned identity for this persisted sandbox. */ get id(): string /** Status at time of query. */ get status(): string /** Backend retained by this handle (`"local"` or `"cloud"`). */ get backendKind(): string /** Raw config JSON string from the database. */ get configJson(): string /** Return a fresh handle for the same sandbox. */ refresh(): Promise /** Creation timestamp as ms since Unix epoch. */ get createdAt(): number | null /** Last update timestamp as ms since Unix epoch. */ get updatedAt(): number | null /** Get point-in-time metrics from the database. */ metrics(): Promise /** * Check whether agentd is reachable without refreshing idle activity. * * Connects to an already-running sandbox; stopped sandboxes are not * started implicitly. */ ping(): Promise /** * Explicitly refresh this sandbox's idle activity timer. * * Connects to an already-running sandbox; stopped sandboxes are not * started implicitly. */ touch(): Promise /** * Plan or apply a sandbox modification. Returns the plan as a JSON * string; the TS wrapper parses it into a `SandboxModificationPlan`. */ modify(options?: SandboxModifyOptions | undefined | null): Promise /** Compact root and owned-data disk prefixes of a running or stopped sandbox. */ compact(layers?: number | undefined | null, dryRun?: boolean | undefined | null, disk?: string | undefined | null, rootDiskOnly?: boolean | undefined | null): Promise /** Start the sandbox (attached mode) — returns a live Sandbox handle. */ start(): Promise /** Start the sandbox (detached mode). */ startDetached(): Promise /** Connect to an already-running sandbox (no lifecycle ownership). */ connect(): Promise /** Connect when running, or start the same persisted sandbox when stopped. */ connectOrStart(detached?: boolean | undefined | null): Promise /** * Connect with an explicit timeout in milliseconds. * * If the sandbox doesn't respond within this window, the call * returns a typed error instead of blocking. `connect()` uses * 10_000 ms by default. */ connectWithTimeout(timeoutMs: number): Promise /** * Stop the sandbox gracefully. * * Wait indefinitely for the targeted runtime to finish gracefully and release * ownership. No implicit kill; use `stopWithTimeout` for a bounded wait. */ stop(): Promise /** @deprecated Use fork for live execution duplication. */ branch(name: string, recordIntegrity?: boolean | undefined | null, guestFlush?: string | undefined | null): Promise /** @deprecated Use forkMany for live execution duplication. */ branchMany(names: Array, recordIntegrity?: boolean | undefined | null, guestFlush?: string | undefined | null): Promise> /** Create an independent local CoW child without a durable full snapshot. */ fork(name: string, recordIntegrity?: boolean | undefined | null, guestFlush?: string | undefined | null): Promise /** Capture once and return individual child startup outcomes. */ forkMany(names: Array, recordIntegrity?: boolean | undefined | null, guestFlush?: string | undefined | null): Promise> /** Explicit resident pause through host control. */ pause(guestFlush?: string | undefined | null): Promise /** Explicit resident resume through host control. */ resume(): Promise /** Request graceful shutdown without waiting. */ requestStop(): Promise /** * One graceful-completion budget in milliseconds. Timeout rejects without killing; * zero expires before dispatch. */ stopWithTimeout(timeoutMs: number): Promise /** Force-kill the sandbox and wait until stopped state is observed. */ kill(): Promise /** Request force termination without waiting. */ requestKill(): Promise /** Force-kill the sandbox with an explicit observation timeout in milliseconds. */ killWithTimeout(timeoutMs: number): Promise /** Request graceful drain without waiting for completion. */ requestDrain(): Promise /** Wait until this exact sandbox reaches the requested status. */ waitForStatus(status: string): Promise /** Stop and start this exact sandbox. */ restart(options?: SandboxRestartOptions | undefined | null): Promise /** Stop and remove this exact sandbox. */ destroy(options?: SandboxDestroyOptions | undefined | null): Promise /** Wait until the sandbox is observed in a terminal non-running state. */ waitUntilStopped(): Promise /** Remove the sandbox from the database. */ remove(): Promise /** * Read captured output from `exec.log` for this sandbox. * * Works without starting the sandbox. */ logs(opts?: LogOptions | undefined | null): Promise> /** * Stream captured output as it appears, with optional follow. * * Works without starting the sandbox; with `follow: true`, the * stream picks up new entries the moment they land in * `exec.log`. */ logStream(opts?: LogStreamOptions | undefined | null): Promise /** * Snapshot this sandbox's disk under a bare name, preserving its running/paused state. * * Resolves under `~/.microsandbox/snapshots//`. Move * artifacts with `Snapshot.save`/`Snapshot.load`. */ snapshot(name: string): Promise } export type JsSandboxHandle = SandboxHandle /** Fluent builder for a single secret entry. */ export declare class SecretBuilder { constructor() /** Environment variable to expose the placeholder under (required). */ env(envVar: string): this /** Secret value (required). */ value(value: string): this /** Custom placeholder. Auto-generated as `$MSB_` when unset. */ placeholder(placeholder: string): this /** Add a host allowed to receive the substituted secret value. */ allow(host: string): this /** * Allow any host. **Dangerous** — secret can be exfiltrated. * Pass `true` to opt in. */ allowAnyHostDangerous(iUnderstand: boolean): this /** Require verified TLS identity before substituting (default: true). */ requireTlsIdentity(enabled: boolean): this /** * Allow a host to receive the unchanged placeholder where substitution does not apply. * Enabled substitution locations still receive the real secret on allowed hosts. */ allowPlaceholderFor(host: string): this /** @deprecated Use allowPlaceholderFor instead. */ allowPassthroughFor(host: string): this /** Configure header substitution (default: true). */ substituteInHeaders(enabled: boolean): this /** Configure URL query parameter substitution (default: false). */ substituteInQuery(enabled: boolean): this /** Configure request body substitution (default: false). */ substituteInBody(enabled: boolean): this /** Configure the blocking action for this secret. */ violationAction(action: string): this /** * Materialize into a `SecretEntry`. Panics if required fields are not * set (matches the underlying Rust builder's contract; surface as a * typed error here). */ build(): SecretEntry } export type JsSecretBuilder = SecretBuilder /** High-level SFTP client session. */ export declare class SftpClient { /** Read a file into memory. */ read(path: string): Promise /** Write a file, creating or truncating it. */ write(path: string, data: Buffer): Promise /** Create a directory. */ mkdir(path: string): Promise /** Remove a file. */ removeFile(path: string): Promise /** Remove an empty directory. */ removeDir(path: string): Promise /** Rename a file or directory. */ rename(oldPath: string, newPath: string): Promise /** Resolve a path to its canonical absolute form. */ realPath(path: string): Promise /** Read a symlink target. */ readLink(path: string): Promise /** Create a symlink. */ symlink(target: string, linkPath: string): Promise /** Close this SFTP session. */ close(): Promise } export type JsSftpClient = SftpClient /** A backend-neutral snapshot artifact. */ export declare class Snapshot { /** Observe object storage through its captured backend. */ storageUsage(): Promise static open(pathOrName: string): Promise static get(nameOrDigest: string): Promise static list(): Promise> static remove(pathOrName: string, opts?: SnapshotRemoveOptions | undefined | null): Promise static load(archive: string, dest?: string | undefined | null, base?: string | undefined | null): Promise static loadWithOptions(archive: string, opts?: LoadOpts | undefined | null): Promise /** Import archives together, resolving dependencies within the batch and destination group. */ static loadMany(archives: Array, opts?: LoadOpts | undefined | null): Promise> /** Read a group's head, or select `group:member` as its head. */ static groupHead(selector: string): Promise /** Deprecated: use `reference`. Throws when no local filesystem path exists. */ get path(): string get reference(): string get referenceKind(): 'id' | 'path' /** Outcome of the group head update performed by this capture. */ get headUpdate(): HeadUpdate | null get id(): string get digest(): string get sizeBytes(): bigint | null get imageRef(): string get imageManifestDigest(): string get stateKind(): string get format(): string | null get fstype(): string | null get upperFile(): string | null get upperIntegrityAlgorithm(): string | null get upperIntegrityDigest(): string | null get upperIntegrityLogicalSize(): bigint | null get upperIntegrityLeafSize(): number | null get checkpointId(): string | null get checkpointManifestDigest(): string | null get parent(): string | null get scope(): 'disk' | 'full' get createdAt(): string get labels(): Record get sourceSandbox(): string | null /** Walk `dir` and parse each snapshot artifact within it. */ static listDir(dir: string): Promise> /** Rebuild the backend snapshot index from artifacts in `dir`. */ static reindex(dir?: string | undefined | null): Promise /** Bundle a snapshot into a `.tar.zst` archive. */ static save(nameOrPath: string, out: string, opts?: SaveOpts | undefined | null): Promise /** Bundle this snapshot into a `.tar.zst` archive. */ saveTo(out: string, opts?: SaveOpts | undefined | null): Promise /** * Configure a new archive containing this snapshot's disk data and * replacement labels and integrity metadata. * Returns an unsupported-operation error when artifact archives are unavailable. */ copyTo(outputArchivePath: string): JsSnapshotCopyBuilder /** Verify this snapshot's recorded payload integrity. */ verify(): Promise } export type JsSnapshot = Snapshot /** Result of direct sandbox-to-archive capture. */ export declare class SnapshotArchive { get id(): string get descriptorDigest(): string get path(): string } export type JsSnapshotArchive = SnapshotArchive /** * Fluent builder for a snapshot. Returned by `Snapshot.builder(name)`. * The source sandbox is set with `fromSandbox()` and is required. */ export declare class SnapshotBuilder { constructor(name: string) /** * Create the artifact under this parent directory instead of the * default snapshots store. The snapshot group is created under this root. */ destDir(destDir: string): this /** Install the snapshot in this group (defaults to the source sandbox's name). */ group(group: string): this /** Set the source sandbox to snapshot. Required. */ fromSandbox(sourceSandbox: string): this /** Attach a key-value label. May be called multiple times. */ label(key: string, value: string): this /** Overwrite an archive destination; installed group members are immutable. */ force(): this /** Compute and record content integrity at create time. */ recordIntegrity(): this /** Capture disk, memory, execution, and device state from a running sandbox. */ full(): this /** Select optional writeback: auto, required, or skip. Required storage barriers remain. */ guestFlush(policy: string): this /** Snapshot the accumulated configuration. */ build(): SnapshotConfig /** * Create the snapshot. * * # Safety * `&mut self` async requires the napi-rs `unsafe` tag. We drain * the inner builder synchronously before awaiting, so it's * effectively safe. JS callers see a normal * `create(): Promise`. */ create(): Promise /** Capture directly to an archive without installing a snapshot artifact. */ createArchive(out: string, plainTar?: boolean | undefined | null): Promise } export type JsSnapshotBuilder = SnapshotBuilder /** Builder for copying a snapshot archive with replacement metadata. */ export declare class SnapshotCopyBuilder { /** Replace the copied snapshot's labels. */ labels(labels: Record): this /** Choose whether to calculate and record disk integrity in the copy. */ recordIntegrity(enabled: boolean): this /** * Write the configured snapshot archive. * Returns an unsupported-operation error when artifact archives are unavailable. */ save(): Promise } export type JsSnapshotCopyBuilder = SnapshotCopyBuilder /** Lightweight snapshot handle returned by the active backend. */ export declare class SnapshotHandle { /** Observe object storage through its captured backend. */ storageUsage(): Promise get group(): string | null get headUpdate(): HeadUpdate | null get id(): string get digest(): string get name(): string | null get parentDigest(): string | null get scope(): 'disk' | 'full' get imageRef(): string get stateKind(): string get format(): string | null get fstype(): string | null get checkpointManifestDigest(): string | null get sizeBytes(): bigint | null get locality(): string get availability(): string get migrationState(): string get migrationErrorCode(): string | null get createdAt(): number /** Deprecated: use `reference`. Throws when no local filesystem path exists. */ get path(): string get reference(): string get referenceKind(): 'id' | 'path' open(): Promise remove(opts?: SnapshotRemoveOptions | undefined | null): Promise /** Bundle this snapshot into a `.tar.zst` archive. */ saveTo(out: string, opts?: SaveOpts | undefined | null): Promise } export type JsSnapshotHandle = SnapshotHandle /** Builds a SOCKS4 outbound proxy. */ export declare class Socks4ProxyBuilder { /** Set the optional user ID sent during the SOCKS4 handshake. */ userId(userId: string): this } export type JsSocks4ProxyBuilder = Socks4ProxyBuilder /** Builds a SOCKS5 outbound proxy. */ export declare class Socks5ProxyBuilder { /** Set username authentication and a host-side password source. */ credentials(username: string, password: SecretSourceInput): this } export type JsSocks5ProxyBuilder = Socks5ProxyBuilder /** Native in-process SSH client session. */ export declare class SshClient { /** Run an SSH exec request and collect stdout, stderr, and exit status. */ exec(command: string, options?: SshExecOptions | undefined | null): Promise /** Attach the local terminal to an interactive SSH shell. */ attach(options?: SshAttachOptions | undefined | null): Promise /** Open an SFTP session over this SSH connection. */ sftp(): Promise /** Close this SSH client session. */ close(): Promise } export type JsSshClient = SshClient /** Reusable SSH server endpoint for a sandbox. */ export declare class SshServer { /** Serve one SSH transport over this process's stdin/stdout. */ serveConnection(): Promise /** Release this prepared server endpoint. */ close(): Promise } export type JsSshServer = SshServer /** Fluent builder for TLS interception settings. */ export declare class TlsBuilder { constructor() /** Add a bypass pattern (no MITM). Supports `*.suffix` wildcards. */ bypass(pattern: string): this /** Verify upstream server certificates (default: true). */ verifyUpstream(verify: boolean): this /** Verify upstream server certificates for matching hosts. */ verifyUpstreamFor(pattern: string, verify: boolean): this /** Set the ports to intercept (default: 443). */ interceptedPorts(ports: Array): this /** Block QUIC on intercepted ports (default: true). */ blockQuic(block: boolean): this /** Add an upstream CA certificate PEM path. May be called repeatedly. */ upstreamCaCert(path: string): this /** Add an upstream CA certificate PEM path for matching hosts. */ upstreamCaCertFor(pattern: string, path: string): this /** Set a custom interception CA certificate PEM path. */ interceptCaCert(path: string): this /** Set a custom interception CA private key PEM path. */ interceptCaKey(path: string): this /** Materialize into a `TlsConfig`. */ build(): TlsConfig } export type JsTlsBuilder = TlsBuilder export declare class Volume { static get(name: string): Promise static getDefault(): Promise static list(): Promise> static remove(name: string): Promise get name(): string get path(): string /** Direct filesystem operations through this volume's bound backend. */ fs(): VolumeFs } export type JsVolume = Volume /** Fluent builder for a named persistent volume. */ export declare class VolumeBuilder { constructor(name: string) /** Create a directory-backed named volume. */ directory(): this /** Create a raw ext4 disk-backed named volume. */ disk(): this /** Limit the volume's storage capacity (MiB). Omit for unlimited. */ quota(mib: number): this /** Set disk volume capacity in MiB. */ size(mib: number): this /** Attach a key-value label. May be called multiple times. */ label(key: string, value: string): this /** Snapshot the accumulated configuration. */ build(): VolumeConfig /** * Create the volume. * * # Safety * `&mut self` async requires the napi-rs `unsafe` tag. We drain the * inner builder synchronously before awaiting, so it's effectively * safe. JS callers see a normal `create(): Promise`. */ create(): Promise } export type JsVolumeBuilder = VolumeBuilder export declare class VolumeFs { read(path: string): Promise readString(path: string): Promise readStream(path: string): Promise write(path: string, data: Buffer): Promise writeStream(path: string): Promise list(path: string): Promise> mkdir(path: string): Promise removeDir(path: string): Promise remove(path: string): Promise copy(from: string, to: string): Promise rename(from: string, to: string): Promise stat(path: string): Promise exists(path: string): Promise } export type JsVolumeFs = VolumeFs /** * This type implements JavaScript's async iterable protocol. * It can be used with `for await...of` loops. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols */ export declare class VolumeFsReadStream { recv(): Promise [Symbol.asyncIterator](): AsyncGenerator } export type JsVolumeFsReadStream = VolumeFsReadStream export declare class VolumeFsWriteSink { write(data: Buffer): Promise close(): Promise } export type JsVolumeFsWriteSink = VolumeFsWriteSink export declare class VolumeHandle { get name(): string get isDefault(): boolean get quotaMib(): number | null get kind(): string get usedBytes(): number get capacityBytes(): number | null get diskFormat(): string | null get diskFstype(): string | null get labels(): Record get createdAt(): number | null remove(): Promise /** Direct filesystem operations through this volume's bound backend. */ fs(): VolumeFs } export type JsVolumeHandle = VolumeHandle /** Options for connecting to an agent relay. */ export interface AgentConnectOptions { /** Handshake timeout in milliseconds. Defaults to 10_000. */ timeoutMs?: number } /** Get metrics for all running sandboxes. */ export declare function allSandboxMetrics(): Promise> /** Built attach options produced by `AttachOptionsBuilder.build()`. */ export interface AttachOptions { args: Array cwd?: string user?: string env: Record detachKeys?: string rlimits: Array } /** Return secret-safe information about the active default backend. */ export declare function defaultBackendInfo(): JsBackendInfo /** Return the active default backend kind (`"local"` or `"cloud"`). */ export declare function defaultBackendKind(): string /** DNS interception configuration produced by `DnsBuilder.build()`. */ export interface DnsConfig { rebindProtection: boolean /** * Nameservers serialized as their parse-roundtrippable string form * (e.g. `"1.1.1.1:53"`, `"dns.google:53"`). */ nameservers: Array /** Per-query timeout in milliseconds. Default: 5000. */ queryTimeoutMs: number } /** Reuse a resolved pair and install only when it is wholly absent. */ export declare function ensureRuntime(configJson: string, optionsJson: string): Promise /** Execution event emitted by `ExecHandle.recv()`. */ export interface ExecEvent { /** "started", "stdout", "stderr", or "exited". */ eventType: string /** Process ID (only for "started" events). */ pid?: number /** Output data (only for "stdout" and "stderr" events). */ data?: Buffer /** Exit code (only for "exited" events). */ code?: number } /** Built exec options produced by `ExecOptionsBuilder.build()`. */ export interface ExecOptions { args: Array cwd?: string user?: string env: Record timeoutMs?: number stdin: StdinMode tty: boolean rlimits: Array } /** Exit status for an executed command. */ export interface ExitStatus { code: number success: boolean } /** An unmapped external filesystem or a mismatch accepted during relaxed restore. */ export interface ExternalMountWarning { guestPath: string reason: string staleInodes: Array } /** Filesystem entry metadata returned by `fs.list()`. */ export interface FsEntry { path: string /** "file", "directory", "symlink", or "other". */ kind: string size: number mode: number modified?: number } /** Filesystem metadata returned by `fs.stat()`. */ export interface FsMetadata { /** "file", "directory", "symlink", or "other". */ kind: string size: number mode: number readonly: boolean modified?: number created?: number } /** Outcome of reading or selecting a snapshot group's head. */ export interface HeadUpdate { group: string previous?: string head: string reason: string changed: boolean } /** OCI config fields extracted from the database. */ export interface ImageConfigDetail { digest: string env: Array cmd?: Array entrypoint?: Array workingDir?: string user?: string labelsJson?: string stopSignal?: string } /** Full image detail (config + layers + handle metadata). */ export interface ImageDetailJs { reference: string manifestDigest?: string architecture?: string os?: string layerCount: number sizeBytes?: number createdAt?: number lastUsedAt?: number config?: ImageConfigDetail layers: Array } /** Look up a cached image by reference. */ export declare function imageGet(reference: string): Promise /** Lightweight image info as returned by `imageList`. */ export interface ImageInfo { reference: string manifestDigest?: string architecture?: string os?: string layerCount: number sizeBytes?: number createdAt?: number lastUsedAt?: number } /** Full inspect (config + layers). */ export declare function imageInspect(reference: string): Promise /** Metadata for a single layer. */ export interface ImageLayerDetail { diffId: string blobDigest: string mediaType?: string compressedSizeBytes?: number erofsSizeBytes?: number position: number } /** List all cached images. */ export declare function imageList(): Promise> /** * Load images from a local archive (`docker save` tarball or OCI Image * Layout) into the image cache. `tag` applies an extra reference to the * first image in the archive. */ export declare function imageLoad(inputPath: string, tag?: string | undefined | null): Promise> /** Remove cached image data that is not used by any sandbox or indexed snapshot. */ export declare function imagePrune(): Promise /** Summary of artifacts removed by `imagePrune`. */ export interface ImagePruneReportJs { skippedInUse: number imageRefsRemoved: number manifestsRemoved: number layersRemoved: number fsmetaRemoved: number vmdkRemoved: number bytesReclaimed?: number } /** * Remove an image reference. Force permits untagging dependencies while retaining * their backing; active storage operations are never bypassed. */ export declare function imageRemove(reference: string, force?: boolean | undefined | null): Promise /** * Save cached images to an archive file. `format` selects the layout: * `"docker"` (default, loadable with `docker load`) or `"oci"`. */ export declare function imageSave(references: Array, outputPath: string, format?: string | undefined | null): Promise /** Explicitly install a runtime pair from the selected source. */ export declare function installRuntime(configJson: string, optionsJson: string): Promise /** Check whether a complete runtime pair resolves. */ export declare function isRuntimeInstalled(configJson: string): boolean /** Secret-safe backend diagnostics returned to JavaScript. */ export interface JsBackendInfo { kind: string apiUrl?: string source: string profile?: string } /** One child result from a capture-once batch, in caller order. */ export interface JsBranchOutcome { name: string sandbox?: Sandbox error?: string } /** One page returned by `Sandbox.list` / `Sandbox.listWith`. */ export interface JsSandboxPage { sandboxes: Array nextCursor?: string } /** Options for importing one or more archives into a snapshot group. */ export interface LoadOpts { /** Parent directory containing snapshot groups. */ dest?: string /** External snapshot or standalone archive for dependencies absent from the batch/group. */ base?: string /** Destination group (generated when omitted). */ group?: string /** Select the unique imported tip even when it is not a fast-forward. */ setHead?: boolean } /** One captured log entry from `exec.log`. */ export interface LogEntry { /** Wall-clock timestamp when the chunk was captured (ms since epoch). */ timestampMs: number /** `"stdout"`, `"stderr"`, `"output"`, or `"system"`. */ source: string /** * Relay-monotonic session id. `null` for `system` entries * (lifecycle markers aren't tied to a specific session). * Exposed as `f64` so it survives JS's number type without * requiring BigInt; session ids stay small in practice * (start at 1, +1 per session opened). */ sessionId?: number /** * Body bytes. UTF-8 lossy decoded by default; raw mode (future) * preserves bytes via base64 round-trip on the host side. */ data: Buffer /** * Opaque resume token. Pass back to `logStream` via * `fromCursor` to pick up immediately after this entry. */ cursor: string } /** * Filters applied by `Sandbox.logs()`. * * All fields optional. Defaults: tail = unset (return everything), * since/until = unset (no time filter), sources = `["stdout", "stderr", "output"]`. */ export interface LogOptions { /** Show only the last N entries. */ tail?: number /** Inclusive lower bound (ms since epoch). */ sinceMs?: number /** Exclusive upper bound (ms since epoch). */ untilMs?: number /** * Sources to include. Each element is `"stdout"`, `"stderr"`, * `"output"`, `"system"`, or `"all"`. Defaults to * `["stdout", "stderr", "output"]` when omitted. */ sources?: Array } /** * Options accepted by `Sandbox.logStream()`. * * All fields optional. Defaults: sources = `["stdout", "stderr", * "output"]`, start from the beginning of available history, no * upper bound, `follow = false`. * * `sinceMs` and `fromCursor` are mutually exclusive — passing both * rejects at the boundary. */ export interface LogStreamOptions { /** Same shape as `LogOptions.sources`. */ sources?: Array /** * Start at the first entry whose timestamp is `>= sinceMs`. * Mutually exclusive with `fromCursor`. */ sinceMs?: number /** * Resume strictly after the entry identified by this cursor * (the value of `LogEntry.cursor` from a prior call). * Mutually exclusive with `sinceMs`. */ fromCursor?: string /** Stop emitting at the first entry whose timestamp is `>= untilMs`. */ untilMs?: number /** * When true, keep the stream open past current EOF and yield * new entries as they are written. */ follow?: boolean } export interface NetworkPolicy { defaultEgress: string defaultIngress: string rules: Array } export interface NetworkPolicyDestination { /** `"any" | "cidr" | "domain" | "domainSuffix" | "group"`. */ kind: string cidr?: string domain?: string suffix?: string group?: string } export interface NetworkPolicyPortRange { start: number end: number } export interface NetworkPolicyRule { direction: string destination: NetworkPolicyDestination protocols: Array ports: Array action: string } /** * Rootfs patch produced by `PatchBuilder.build()`. Flat representation * of the `Patch` enum: `kind` discriminator + per-variant fields. */ export interface Patch { /** `"text" | "file" | "copyFile" | "copyDir" | "symlink" | "mkdir" | "remove" | "append"`. */ kind: string /** Absolute guest path (text/file/mkdir/remove/append). */ path?: string /** Host source path (copyFile/copyDir). */ src?: string /** Guest destination path (copyFile/copyDir). */ dst?: string /** Symlink target. */ target?: string /** Symlink link path. */ link?: string /** Text content (text/append). */ content?: string /** Raw byte content (file). */ contentBytes?: Array /** File / directory permissions. */ mode?: number /** Allow replacing an existing path. */ replace?: boolean } /** Optional knobs accepted by `text`, `file`, `copyFile`. */ export interface PatchFileOptions { mode?: number replace?: boolean } /** Optional knobs accepted by `mkdir`. */ export interface PatchModeOnly { mode?: number } /** Optional knobs accepted by `copyDir`, `symlink`. */ export interface PatchReplaceOnly { replace?: boolean } /** Restore the backend saved by `pushDefaultBackend`. */ export declare function popDefaultBackend(token: number): void /** * One progress event emitted during image pull and EROFS materialization. * * `kind` discriminates the event; the per-variant fields below are * `null` when not applicable to that kind. */ export interface PullProgressEvent { /** * Event kind: one of * `"resolving" | "resolved" | "layerDownloadProgress" | * "layerDownloadComplete" | "layerDownloadVerifying" | * "layerMaterializeStarted" | "layerMaterializeProgress" | * "layerMaterializeWriting" | "layerMaterializeComplete" | * "stitchMergingTrees" | "stitchWritingFsmeta" | * "stitchWritingVmdk" | "stitchComplete" | "complete" | "startup"`. */ kind: string phase?: string completedBytes?: number reference?: string manifestDigest?: string layerCount?: number totalDownloadBytes?: number layerIndex?: number digest?: string diffId?: string downloadedBytes?: number totalBytes?: number bytesRead?: number } /** * Temporarily replace the process-wide default backend and return a scope token. * * The caller must pass the returned token to `popDefaultBackend`; concurrent * JavaScript work in the same process can observe the temporary backend. */ export declare function pushDefaultBackend(kind: string, url?: string | undefined | null, apiKey?: string | undefined | null, profile?: string | undefined | null): number /** * A raw protocol frame: correlation id, flags, and CBOR-encoded body bytes. * * The body is the CBOR-encoded `Message` body (`v`, `t`, `p`) as it * appeared on the wire — decode with any CBOR library (e.g. `cbor-x`). */ export interface RawFrame { /** Correlation ID from the frame header. */ id: number /** Frame flags from the frame header. */ flags: number /** Raw CBOR bytes of the message body. */ body: Buffer } /** Plain-object form of `RegistryAuth`. `kind: "anonymous" | "basic"`. */ export interface RegistryAuthInput { kind: string username?: string password?: string } /** Built registry configuration produced by `RegistryConfigBuilder.build()`. */ export interface RegistryConfig { auth?: RegistryAuthInput insecure: boolean /** * Number of PEM CA certs accumulated via `caCerts(buffer)`. Bytes * themselves are not echoed back. */ caCertsCount: number /** Filesystem path passed to `caCertsPath(path)`, if any. */ caCertsPath?: string } /** Resolve the existing runtime pair without installing host binaries. */ export declare function resolveRuntime(configJson: string): string /** Read an executable's embedded runtime version without starting it. */ export declare function resolveRuntimeVersion(executable: string): Promise /** A single rlimit entry. */ export interface Rlimit { resource: string soft: number hard: number } /** Options for `destroy`. */ export interface SandboxDestroyOptions { force?: boolean timeoutMs?: number } /** Options for one paginated sandbox list request. */ export interface SandboxListOptions { cursor?: string limit?: number labels?: Record } /** Point-in-time resource metrics for a sandbox. */ export interface SandboxMetrics { cpuPercent: number vcpuTimeNs: number memoryBytes: number memoryAvailableBytes?: number memoryHostResidentBytes?: number memoryLimitBytes: number diskReadBytes: number diskWriteBytes: number netRxBytes: number netTxBytes: number upperUsedBytes?: number upperFreeBytes?: number upperHostAllocatedBytes?: number /** Uptime in milliseconds. */ uptimeMs: number /** Timestamp as milliseconds since Unix epoch. */ timestampMs: number } /** * Options accepted by `Sandbox.modify()` / `SandboxHandle.modify()`. * * `memoryMib` / `maxMemoryMib` / `rootDiskSizeMib` are in MiB. `policy` is `"no_restart"` * (default), `"next_start"`, or `"restart"`. With `dryRun: true` the plan * is computed without applying anything. */ export interface SandboxModifyOptions { cpus?: number maxCpus?: number memoryMib?: number maxMemoryMib?: number rootDiskSizeMib?: number env?: Record envRemove?: Array labels?: Record labelsRemove?: Array workdir?: string secrets?: Record secretsRemove?: Array policy?: string dryRun?: boolean } /** Result returned by `Sandbox.ping()` / `SandboxHandle.ping()`. */ export interface SandboxPingResult { name: string latencyMs: number } /** Options for `restart`. */ export interface SandboxRestartOptions { force?: boolean timeoutMs?: number detached?: boolean } /** Result of observing a sandbox in a terminal state. */ export interface SandboxStopResult { name: string status: string exitCode?: number signal?: number observedAt: number source?: string } /** Result returned by `Sandbox.touch()` / `SandboxHandle.touch()`. */ export interface SandboxTouchResult { name: string activitySeq: number } /** Options for `Snapshot.save()` and instance `saveTo()` methods. */ export interface SaveOpts { /** Walk the parent chain and include each ancestor in the archive. */ withParents?: boolean /** Bundle the OCI image cache for offline transport. */ withImage?: boolean /** Skip zstd compression and write a plain `.tar`. */ plainTar?: boolean /** Base snapshot or standalone archive supplying reusable disk layers and RAM objects. */ since?: string /** Newest N immutable disk layers to include. */ lastLayers?: number } /** Host-scoped upstream CA certificate path. */ export interface ScopedUpstreamCaCert { pattern: string path: string } /** Host-scoped upstream certificate verification override. */ export interface ScopedVerifyUpstream { pattern: string verify: boolean } /** A secret entry produced by `SecretBuilder.build()`. */ export interface SecretEntry { /** Environment variable name exposed to the sandbox (holds the placeholder). */ envVar: string /** Secret value (never enters the sandbox). */ value: string /** Placeholder string the sandbox sees instead of the real value. */ placeholder: string /** Exact host names allowed to receive this secret. */ allowedHosts: Array /** Wildcard host patterns (e.g. `*.openai.com`) allowed to receive this secret. */ allowedHostPatterns: Array /** Allow any host. **Dangerous** — secret can be exfiltrated. */ allowAnyHost: boolean /** Hosts allowed to receive the placeholder unchanged. */ passthroughHosts: Array /** Require verified TLS identity before substituting (default: true). */ requireTlsIdentity: boolean /** Per-secret override of the network violation action. */ violationAction?: string /** Where the secret may be injected into requests. */ substitution: SecretSubstitution } /** * Desired state for one secret in `SandboxModifyOptions.secrets`, keyed by * secret name. `env` / `value` / `store` are mutually exclusive ways to * provide the secret material; setting more than one is rejected at the * boundary. Only `value` may carry raw secret material. */ export interface SecretModifySpec { env?: string value?: string store?: string placeholder?: string allowedHosts?: Array } /** Host-side source for secret material. */ export interface SecretSourceInput { /** Source kind. Currently only `env` is supported for proxy credentials. */ kind: string /** Host environment variable name. */ var: string } /** Injection sites for a secret value. */ export interface SecretSubstitution { headers: boolean query: boolean body: boolean } /** * Set the process-wide default backend. * * `kind="local"` selects the local backend. `kind="cloud"` requires either an * API key (with an optional URL override), or a profile. */ export declare function setDefaultBackend(kind: string, url?: string | undefined | null, apiKey?: string | undefined | null, profile?: string | undefined | null): void /** Register the platform package executable as a fallback after the runtime home. */ export declare function setPackagedMsbPath(path: string): void /** * Set the `libkrunfw` shared library path resolved by the JS SDK. * * Process-level setter — one dylib per process address space, so this is the * natural granularity. User env (`MSB_LIBKRUNFW_PATH`) still wins as tier 1. * Mirrors `setRuntimeMsbPath` for libkrunfw. */ export declare function setRuntimeLibkrunfwPath(path: string): void /** * Set the `msb` binary path resolved by the JS SDK. * * This avoids using `process.env` as an internal JS-to-native config channel. */ export declare function setRuntimeMsbPath(path: string): void /** Built snapshot configuration produced by `SnapshotBuilder.build()`. */ export interface SnapshotConfig { guestFlush: string name: string group?: string sourceSandbox?: string destDir?: string labels: Array force: boolean recordIntegrity: boolean full: boolean } /** Snapshot index info from the local DB cache. */ export interface SnapshotInfo { id: string digest: string name?: string group?: string headUpdate?: HeadUpdate parentDigest?: string imageRef: string /** `"disk"` for file state or `"full"` for a complete VM checkpoint. */ scope: string /** `"raw"` or `"qcow2"`. */ stateKind: string format?: string fstype?: string checkpointManifestDigest?: string sizeBytes?: number locality: string availability: string migrationState: string migrationErrorCode?: string createdAt: number /** Local filesystem path, absent for remote snapshots. */ path?: string reference: string referenceKind: 'id' | 'path' } export interface SnapshotLabel { key: string value: string } /** Options for `Snapshot.remove()` (instance and static). */ export interface SnapshotRemoveOptions { force?: boolean } /** * Result of `Snapshot.verify()`. * * `upperKind` is `"notRecorded"` when integrity is absent or `"verified"` * when the recorded value matched. The other fields carry that binding. */ export interface SnapshotVerifyReport { digest: string path: string upperKind: string upperAlgorithm?: string upperDigest?: string /** Verified composite-checkpoint root, when the artifact is full. */ checkpointRoot?: string } /** Options accepted by `SshClient.attach()`. */ export interface SshAttachOptions { term?: string detachKeys?: string } /** Options accepted by `Sandbox.ssh().openClient()`. */ export interface SshClientOptions { user?: string term?: string sftp?: boolean inactivityTimeoutSecs?: number } /** Options accepted by `SshClient.exec()`. */ export interface SshExecOptions { tty?: boolean } /** Output from an SSH exec request. */ export interface SshOutput { status: number stdout: Buffer stderr: Buffer } /** Options accepted by `Sandbox.ssh().prepareServer()`. */ export interface SshServerOptions { hostKeyPath?: string authorizedKeysPath?: string user?: string sftp?: boolean inactivityTimeoutSecs?: number } /** Stdin mode for an exec. */ export interface StdinMode { /** `"null" | "pipe" | "bytes"`. */ kind: string /** Raw bytes piped as stdin (only for kind `"bytes"`). */ data?: Array } /** * Result of opening a stream: the protocol correlation id (for follow-up * sends) and an opaque stream handle (for `streamNext` / `streamClose`). */ export interface StreamOpenResult { /** Protocol correlation ID. Pass to `send()` for follow-up frames. */ id: number /** Opaque stream handle. Pass to `streamNext()` and `streamClose()`. */ handle: bigint } /** TLS interception configuration produced by `TlsBuilder.build()`. */ export interface TlsConfig { enabled: boolean bypass: Array verifyUpstream: boolean interceptedPorts: Array blockQuic: boolean upstreamCaCertPaths: Array scopedUpstreamCaCerts: Array scopedVerifyUpstream: Array interceptCaCertPath?: string interceptCaKeyPath?: string } /** Built volume configuration produced by `VolumeBuilder.build()`. */ export interface VolumeConfig { name: string kind: string quotaMib?: number capacityMib?: number labels: Record } /** Volume handle info from the database. */ export interface VolumeInfo { name: string isDefault: boolean kind: string quotaMib?: number usedBytes: number capacityBytes?: number diskFormat?: string diskFstype?: string labels: Record createdAt?: number } /** * Volume mount specification produced by `MountBuilder.build()`. * Flat representation of the `VolumeMount` enum: `kind` * discriminator + per-variant fields. */ export interface VolumeMount { kind: string guest: string readonly: boolean noexec: boolean nosuid: boolean nodev: boolean host?: string name?: string namedMode?: string namedKind?: string /** Storage kind for sandbox-owned mounts: `"dir"` or `"disk"`. */ ownedKind?: string sizeMib?: number quotaMib?: number format?: string fstype?: string /** * `"strict" | "relaxed" | "off"` for bind/named and owned-directory mounts; * `None` for tmpfs, host disks, or owned disks. */ statVirtualization?: string /** * `"private" | "mirror"` for bind/named and owned-directory mounts; * `None` for tmpfs, host disks, or owned disks. */ hostPermissions?: string /** * Guest owner uid for host-created files under bind/named or owned-directory mounts; * `None` when unset or for tmpfs/disks. Set together with `override_gid`. */ overrideUid?: number /** * Guest owner gid for host-created files under bind/named or owned-directory mounts; * `None` when unset or for tmpfs/disks. Set together with `override_uid`. */ overrideGid?: number } /** Observe storage in the selected local backend without removing files. */ export declare function storageUsage(): Promise /** Inspect or remove unused published runtime RAM; never remove durable state or locks. */ export declare function storagePrune(dryRun?: boolean | undefined | null, olderThanSeconds?: number | undefined | null): Promise /** Aggregate storage usage. Unknown measurements remain nullable. */ export interface StorageUsageJs { images: StorageCategoryUsageJs snapshots: StorageCategoryUsageJs sandboxes: StorageCategoryUsageJs volumes: StorageCategoryUsageJs branchMemory: StorageCategoryUsageJs snapshotMemory: StorageCategoryUsageJs notes: Array } /** Counts and observed bytes in one managed storage category. */ export interface StorageCategoryUsageJs { count?: number inUse?: number logicalBytes?: bigint allocatedBytes?: bigint reclaimableLogicalBytes?: bigint items: Array notes: Array } /** One object's storage usage and retention explanations. */ export interface StorageItemUsageJs { name: string path: string logicalBytes?: bigint allocatedBytes?: bigint inUse?: boolean reclaimable?: boolean reasons: Array } /** Per-file reclamation result, including ownership exclusions and errors. */ export interface MemoryCacheEntryJs { path: string kind: string logicalBytes?: bigint allocatedBytes?: bigint state: string error?: string } /** Runtime RAM pruning report; logical removal does not imply physical reclamation. */ export interface MemoryCacheReportJs { dryRun: boolean entries: Array filesRemoved: number logicalBytesRemoved: bigint physicalBytesReclaimed?: bigint truncated: boolean }