/* 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 } 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 stdin (sends EOF to the process). */ 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 an explicit rootfs image source. * * Used inside `Sandbox.builder(...).imageWith((i) => i.disk(...).fstype(...))` * or `Sandbox.builder(...).imageWith((i) => i.oci(...).upperSize(...))`. * 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 /** Set the writable overlay upper size for an OCI rootfs, in MiB. */ 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 /** * 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()`, `.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 { 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 /** 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 /** * Set the guest stat virtualization policy. * * Accepts `"strict"`, `"relaxed"`, or `"off"`. Valid only for bind and * named volume mounts. */ statVirtualization(policy: string): this /** * Set the host permission propagation policy. * * Accepts `"private"` or `"mirror"`. Valid only for bind and named volume * mounts. */ hostPermissions(policy: string): 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.publicOnly()` * / `.allowAll()` / `.none()` / `.nonLocal()` 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 /** * 3-arg shorthand matching the Rust core's `secret_env(env_var, * value, allowed_host)`. The placeholder defaults to the original * value (env-var injection only — header injection is disabled * without an explicit placeholder). */ 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 violation action for secrets. */ onSecretViolation(configure: (arg: JsViolationActionBuilder) => JsViolationActionBuilder): this /** Set the maximum number of concurrent connections. */ maxConnections(max: number): 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 /** Trust the host's root CAs inside the guest. Default: false. */ trustHostCAs(enabled: boolean): 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 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 { /** * 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 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 /** * 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 all sandboxes. */ static list(): Promise> /** List sandboxes matching a filter. */ static listWith(filter: SandboxListFilter): Promise> /** * Remove a stopped sandbox from the database. * * Sandbox names are limited to 128 UTF-8 bytes. */ static remove(name: string): Promise /** Sandbox name. Names are limited to 128 UTF-8 bytes. */ get name(): Promise /** Whether this handle owns the sandbox lifecycle (attached mode). */ get ownsLifecycle(): Promise /** * 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 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(): JsSandboxFs /** 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 /** Stream metrics snapshots at the requested interval (in milliseconds). */ metricsStream(intervalMs: number): 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 (SIGTERM). */ stop(): Promise /** Stop and wait for exit, returning the exit status. */ stopAndWait(): Promise /** Kill the sandbox immediately (SIGKILL). */ kill(): Promise /** Graceful drain (SIGUSR1 — for load balancing). */ drain(): Promise /** Wait for the sandbox process to exit. */ wait(): Promise /** Detach from the sandbox — it will continue running after this handle is dropped. */ detach(): Promise /** Remove the persisted database record after stopping. */ 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 /** * Boot a fresh sandbox from a snapshot artifact (path or name). * Mutually exclusive with `image()` / `imageWith()` — the * snapshot already pins the image reference and digest. */ fromSnapshot(pathOrName: string): this /** Number of virtual CPUs. */ cpus(count: number): this /** Guest memory in MiB. */ memory(mib: number): 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 /** 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 /** * 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 /** 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 /** 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 /** 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 /** * 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 } 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 { /** Sandbox name. Names are limited to 128 UTF-8 bytes. */ get name(): string /** Status at time of query: "running", "stopped", "crashed", or "draining". */ get status(): 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 /** 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 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. * * Lets the sandbox finish writing any pending data to disk before * it exits, so files written inside the sandbox aren't lost across * a later restart. Waits 10_000 ms by default before force-kill; * override with `stopWithTimeout(timeoutMs)`. */ stop(): Promise /** Request graceful shutdown without waiting. */ requestStop(): Promise /** * Stop the sandbox gracefully with an explicit timeout in * milliseconds before escalation. */ 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 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 (stopped) sandbox under a bare name. * * Resolves under `~/.microsandbox/snapshots//`. Use * [`snapshotTo`](Self::snapshot_to) for an explicit filesystem * destination. */ snapshot(name: string): Promise /** Snapshot this (stopped) sandbox to an explicit filesystem path. */ snapshotTo(path: 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(var: string): this /** Secret value (required). */ value(value: string): this /** Custom placeholder. Auto-generated as `$MSB_` when unset. */ placeholder(placeholder: string): this /** Add an allowed exact-match host. */ allowHost(host: string): this /** Add an allowed wildcard host pattern (e.g. `*.openai.com`). */ allowHostPattern(pattern: 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 /** Configure header injection (default: true). */ injectHeaders(enabled: boolean): this /** Configure Basic Auth injection (default: true). */ injectBasicAuth(enabled: boolean): this /** Configure URL query parameter injection (default: false). */ injectQuery(enabled: boolean): this /** Configure request body injection (default: false). */ injectBody(enabled: boolean): this /** Configure violation behavior for this secret. */ onViolation(configure: (arg: JsViolationActionBuilder) => JsViolationActionBuilder): 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 /** Builder for installing the runtime binaries. */ export declare class Setup { constructor() baseDir(path: string): this version(version: string): this skipVerify(enabled: boolean): this force(enabled: boolean): this install(): Promise } export type JsSetup = Setup /** 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 snapshot artifact on disk. */ export declare class Snapshot { static open(pathOrName: string): Promise static get(nameOrDigest: string): Promise static list(): Promise> /** * Walk `dir` and parse each subdirectory's `manifest.json`. Does * not touch the local index — useful for inspecting external * snapshot collections (e.g. a mounted volume of artifacts that * were never imported). */ static listDir(dir: string): Promise> static remove(pathOrName: string, opts?: SnapshotRemoveOptions | undefined | null): Promise static reindex(dir?: string | undefined | null): Promise static export(nameOrPath: string, out: string, opts?: ExportOpts | undefined | null): Promise static import(archive: string, dest?: string | undefined | null): Promise get path(): string get digest(): string get sizeBytes(): bigint get imageRef(): string get imageManifestDigest(): string get format(): string get fstype(): string get parent(): string | null get createdAt(): string get labels(): Record get sourceSandbox(): string | null verify(): Promise } export type JsSnapshot = Snapshot /** Fluent builder for a snapshot. Returned by `Snapshot.builder(name)`. */ export declare class SnapshotBuilder { constructor(sourceSandbox: string) /** Set a bare name (resolved under the default snapshots dir). */ name(name: string): this /** Set an explicit destination path. */ path(path: string): this /** Attach a key-value label. May be called multiple times. */ label(key: string, value: string): this /** Overwrite an existing artifact at the destination. */ force(): this /** Compute and record content integrity at create time. */ recordIntegrity(): 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 } export type JsSnapshotBuilder = SnapshotBuilder /** Lightweight snapshot handle from the local index. */ export declare class SnapshotHandle { get digest(): string get name(): string | null get parentDigest(): string | null get imageRef(): string get format(): string get sizeBytes(): bigint | null get createdAt(): number get path(): string open(): Promise remove(opts?: SnapshotRemoveOptions | undefined | null): Promise } export type JsSnapshotHandle = SnapshotHandle /** 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 /** 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 /** 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 /** Fluent builder for secret violation behavior. */ export declare class ViolationActionBuilder { constructor() /** Block the request silently. */ block(): this /** Block the request and log a warning. */ blockAndLog(): this /** Block the request and terminate the sandbox. */ blockAndTerminate(): this /** Allow an exact host to receive placeholders unchanged. */ passthroughHost(host: string): this /** Allow hosts matching a wildcard pattern to receive placeholders unchanged. */ passthroughHostPattern(pattern: string): this /** Allow any host to receive placeholders unchanged. */ passthroughAllHosts(iUnderstand: boolean): this } export type JsViolationActionBuilder = ViolationActionBuilder export declare class Volume { static get(name: string): Promise static list(): Promise> static remove(name: string): Promise get name(): string get path(): string /** Host-side filesystem operations on this volume's directory. */ 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 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 /** Host-side filesystem operations on this volume's directory. */ 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 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 } /** 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 } /** Options for `Snapshot.export()`. */ export interface ExportOpts { /** Walk the parent chain and include each ancestor (no-op today). */ withParents?: boolean /** Bundle the OCI image cache for offline transport. */ withImage?: boolean /** Skip zstd compression and write a plain `.tar`. */ plainTar?: boolean } /** 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 } /** 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 } /** Garbage-collect everything reclaimable. Returns the number reclaimed. */ export declare function imageGc(): Promise /** Garbage-collect orphaned layers. Returns the number reclaimed. */ export declare function imageGcLayers(): Promise /** 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> /** * Remove a cached image. Pass `force = true` to delete even when a * sandbox references it. */ export declare function imageRemove(reference: string, force?: boolean | undefined | null): Promise /** Download and install msb + libkrunfw to ~/.microsandbox/. */ export declare function install(): Promise /** Check if msb and libkrunfw are installed and available. */ export declare function isInstalled(): 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"`. */ kind: string 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 } /** A single rlimit entry. */ export interface Rlimit { resource: string soft: number hard: number } /** Lightweight sandbox info returned by `Sandbox.list`. */ export interface SandboxInfo { name: string status: string configJson: string createdAt?: number updatedAt?: number } /** * Filter for `Sandbox.list`. Matched sandboxes must carry all of `labels` * (AND-matched). Omit or leave empty to match every sandbox. */ export interface SandboxListFilter { 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 } /** Result of observing a sandbox in a terminal state. */ export interface SandboxStopResult { name: string status: string exitCode?: number signal?: number observedAt: number source?: string } /** 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 /** Require verified TLS identity before substituting (default: true). */ requireTlsIdentity: boolean /** Where the secret may be injected into requests. */ injection: JsSecretInjection } /** Injection sites for a secret value. */ export interface SecretInjection { headers: boolean basicAuth: boolean queryParams: boolean body: boolean } /** * Set the process-wide default backend. * * `kind="local"` selects the local backend. `kind="cloud"` requires either * `url` + `api_key`, or `profile`. */ export declare function setDefaultBackend(kind: string, url?: string | undefined | null, apiKey?: string | undefined | null, profile?: string | undefined | null): 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 { sourceSandbox: string destinationKind: string destinationValue?: string labels: Array force: boolean recordIntegrity: boolean } /** Snapshot index info from the local DB cache. */ export interface SnapshotInfo { digest: string name?: string parentDigest?: string imageRef: string /** `"raw"` or `"qcow2"`. */ format: string sizeBytes?: number createdAt: number path: string } 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 no integrity hash was stored, * or `"verified"` when the recorded hash matched the recomputed one. * `upperAlgorithm` and `upperDigest` are populated only when * `upperKind === "verified"`. */ export interface SnapshotVerifyReport { digest: string path: string upperKind: string upperAlgorithm?: string upperDigest?: 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 } /** 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 } /** 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 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 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 sizeMib?: number format?: string fstype?: string /** `"strict" | "relaxed" | "off"` for bind/named mounts; `None` for tmpfs/disk. */ statVirtualization?: string /** `"private" | "mirror"` for bind/named mounts; `None` for tmpfs/disk. */ hostPermissions?: string }