eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
1,058 lines (1,057 loc) • 34.6 kB
TypeScript
import { Paginator } from "./utils/paginator.js";
import { SandboxMetaData, SandboxRouteData, SessionMetaData, SnapshotMetadata } from "./api-client/validators.js";
import { NetworkPolicy, NetworkPolicyKeyValueMatcher, NetworkPolicyMatch, NetworkPolicyMatcher } from "./network-policy.js";
import { WithPrivate } from "./utils/types.js";
import { RUNTIMES } from "./constants.js";
import { APIClient, WithFetchOptions } from "./api-client/api-client.js";
import "./api-client/index.js";
import { Credentials } from "./utils/get-credentials.js";
import { Command, CommandFinished } from "./command.js";
import { Snapshot } from "./snapshot.js";
import { SandboxSnapshot } from "./utils/sandbox-snapshot.js";
import { RunCommandParams, Session } from "./session.js";
import { FileSystem } from "./filesystem.js";
import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from "./_workflow-serde.js";
//#region src/sandbox.d.ts
/** @inline */
interface BaseCreateSandboxParams {
/**
* The name of the sandbox. If omitted, a random name will be generated.
*/
name?: string;
/**
* The source of the sandbox.
*
* Omit this parameter start a sandbox without a source.
*
* For git sources:
* - `depth`: Creates shallow clones with limited commit history (minimum: 1)
* - `revision`: Clones and checks out a specific commit, branch, or tag
*/
source?: {
type: "git";
url: string;
depth?: number;
revision?: string;
} | {
type: "git";
url: string;
username: string;
password: string;
depth?: number;
revision?: string;
} | {
type: "tarball";
url: string;
};
/**
* Array of port numbers to expose from the sandbox. Sandboxes can
* expose up to 4 ports.
*/
ports?: number[];
/**
* Timeout in milliseconds before the sandbox auto-terminates.
*/
timeout?: number;
/**
* Resources to allocate to the sandbox.
*
* Your sandbox will get the amount of vCPUs you specify here and
* 2048 MB of memory per vCPU.
*/
resources?: {
vcpus: number;
};
/**
* The runtime of the sandbox, currently only `node24`, `node22`, `node26` and `python3.13` are supported.
* If not specified, the default runtime `node24` will be used.
*/
runtime?: RUNTIMES | (string & {});
/**
* Network policy to define network restrictions for the sandbox.
* Defaults to full internet access if not specified.
*/
networkPolicy?: NetworkPolicy;
/**
* Default environment variables for the sandbox.
* These are inherited by all commands unless overridden with
* the `env` option in `runCommand`.
*
* @example
* const sandbox = await Sandbox.create({
* env: { NODE_ENV: "production", API_KEY: "secret" },
* });
* // All commands will have NODE_ENV and API_KEY set
* await sandbox.runCommand("node", ["app.js"]);
*/
env?: Record<string, string>;
/**
* Key-value tags to associate with the sandbox. Maximum 5 tags.
* @example { env: "staging", team: "infra" }
*/
tags?: Record<string, string>;
/**
* An AbortSignal to cancel sandbox creation.
*/
signal?: AbortSignal;
/**
* Enable or disable automatic restore of the filesystem between sessions.
*/
persistent?: boolean;
/**
* Default snapshot expiration in milliseconds.
* When set, snapshots created for this sandbox will expire after this duration.
* Use `0` for no expiration.
*/
snapshotExpiration?: number;
/**
* Retention policy that keeps only the N most recent snapshots of this
* sandbox. Older snapshots are evicted when a new one is created.
*/
keepLastSnapshots?: {
/**
* Number of snapshots to keep (1-10).
*/
count: number;
/**
* Expiration in milliseconds applied to kept snapshots.
* Use `0` for no expiration. Falls back to `snapshotExpiration` when omitted.
*/
expiration?: number;
/**
* When `true` (the default), evicted snapshots are deleted immediately;
* when `false`, they keep the default expiration.
*/
deleteEvicted?: boolean;
};
/**
* Called when the sandbox session is resumed (e.g., after a snapshot restore).
* Use this to re-warm caches, restore transient state, or run other setup logic.
*/
onResume?: (sandbox: Sandbox) => Promise<void>;
}
type CreateSandboxParams = BaseCreateSandboxParams | (Omit<BaseCreateSandboxParams, "runtime" | "source"> & {
source: {
type: "snapshot";
snapshotId: string;
};
});
/**
* Parameters for {@link Sandbox.fork}.
*
* The fork inherits the source sandbox's current filesystem snapshot and copies
* as many config fields from the source as the server exposes. Any field set
* here acts as an override of the copied value.
*
* `env` is not copied (encrypted server-side); pass it explicitly to set
* environment variables on the fork. `runtime` is not exposed: when the
* source has a snapshot, it is inherited; otherwise it is copied from the
* source sandbox.
* @inline
*/
type ForkSandboxParams = Omit<BaseCreateSandboxParams, "source" | "runtime"> & {
/**
* Name of the source sandbox to fork from.
*/
sourceSandbox: string;
};
/** @inline */
interface GetSandboxParams {
/**
* The name of the sandbox.
*/
name: string;
/**
* Whether to resume an existing session. Defaults to true.
*/
resume?: boolean;
/**
* An AbortSignal to cancel the operation.
*/
signal?: AbortSignal;
/**
* Called when the sandbox session is resumed (e.g., after a snapshot restore).
* Use this to re-warm caches, restore transient state, or run other setup logic.
*/
onResume?: (sandbox: Sandbox) => Promise<void>;
}
/**
* Extends both {@link BaseCreateSandboxParams} and {@link GetSandboxParams}
* (minus `name`, which is required on get but optional here) so that any
* new parameter added to either flow is picked up automatically. The
* structural overlap on `signal` / `onResume` is intentional — both
* interfaces declare them with identical optional types.
* @inline
*/
interface GetOrCreateSandboxParams extends BaseCreateSandboxParams, Omit<GetSandboxParams, "name"> {
/**
* Called once after a sandbox is freshly created (not when an existing
* sandbox is retrieved). Use this for one-time setup such as seeding
* files or warming caches. The returned promise is awaited before
* {@link Sandbox.getOrCreate} resolves.
*/
onCreate?: (sandbox: Sandbox) => Promise<void>;
}
/**
* Serialized representation of a Sandbox for @workflow/serde.
* Fields `metadata` and `routes` are the original wire format from main.
* Fields `sandboxMetadata` and `projectId` are added for named-sandboxes.
*/
interface SerializedSandbox {
metadata: SandboxSnapshot;
routes: SandboxRouteData[];
sandboxMetadata?: SandboxMetaData;
projectId?: string;
}
/**
* A Sandbox is a persistent, isolated Linux MicroVMs to run commands in.
* Use {@link Sandbox.create} or {@link Sandbox.get} to construct.
* @hideconstructor
*/
declare class Sandbox {
private _client;
private readonly projectId;
/**
* In-flight resume promise, used to deduplicate concurrent resume calls.
*/
private resumePromise;
/**
* Internal Session instance for the current VM.
*/
private session;
/**
* Internal metadata about the sandbox.
*/
private sandbox;
/**
* Hook that will be executed when a new session is created during resume.
*/
private readonly onResume?;
/**
* A `node:fs/promises`-compatible API for interacting with the sandbox filesystem.
*
* @example
* const content = await sandbox.fs.readFile('/etc/hostname', 'utf8');
* await sandbox.fs.writeFile('/tmp/hello.txt', 'Hello, world!');
* const files = await sandbox.fs.readdir('/tmp');
* const stats = await sandbox.fs.stat('/tmp/hello.txt');
*/
readonly fs: FileSystem;
/**
* Lazily resolve credentials and construct an API client.
* @internal
*/
private ensureClient;
/**
* The name of this sandbox.
*/
get name(): string;
/**
* Routes from ports to subdomains.
* @hidden
*/
get routes(): SandboxRouteData[];
/**
* Whether the sandbox persists the state.
*/
get persistent(): boolean;
/**
* The region this sandbox runs in.
*/
get region(): string | undefined;
/**
* Number of virtual CPUs allocated.
*/
get vcpus(): number | undefined;
/**
* Memory allocated in MB.
*/
get memory(): number | undefined;
/** Runtime identifier (e.g. "node24", "python3.13"). */
get runtime(): string | undefined;
/**
* Cumulative egress bytes across all sessions.
*/
get totalEgressBytes(): number | undefined;
/**
* Cumulative ingress bytes across all sessions.
*/
get totalIngressBytes(): number | undefined;
/**
* Cumulative active CPU duration in milliseconds across all sessions.
*/
get totalActiveCpuDurationMs(): number | undefined;
/**
* Cumulative wall-clock duration in milliseconds across all sessions.
*/
get totalDurationMs(): number | undefined;
/**
* When this sandbox was last updated.
*/
get updatedAt(): Date;
/**
* When the sandbox status was last updated.
*/
get statusUpdatedAt(): Date | undefined;
/**
* When this sandbox was created.
*/
get createdAt(): Date;
/**
* Interactive port.
*/
get interactivePort(): number | undefined;
/**
* The default working directory of the current session (e.g.
* `/vercel/sandbox`).
*/
get cwd(): string;
/**
* The status of the current session.
*/
get status(): SessionMetaData["status"];
/**
* The default timeout of this sandbox in milliseconds.
*/
get timeout(): number | undefined;
/**
* Key-value tags attached to the sandbox.
*/
get tags(): Record<string, string> | undefined;
/**
* The default network policy of this sandbox.
*/
get networkPolicy(): NetworkPolicy | undefined;
/**
* If the session was created from a snapshot, the ID of that snapshot.
*/
get sourceSnapshotId(): string | undefined;
/**
* The current snapshot ID of this sandbox, if any.
*/
get currentSnapshotId(): string | undefined;
/**
* The default snapshot expiration in milliseconds, if set.
*/
get snapshotExpiration(): number | undefined;
/**
* The snapshot retention policy (`keep-last-snapshots`) currently configured
* on this sandbox, if any.
*/
get keepLastSnapshots(): {
count: number;
expiration?: number;
deleteEvicted?: boolean;
} | undefined;
/**
* The amount of CPU used by the session. Only reported once the VM is stopped.
*/
get activeCpuUsageMs(): number | undefined;
/**
* The amount of network data used by the session. Only reported once the VM is stopped.
*/
get networkTransfer(): {
ingress: number;
egress: number;
} | undefined;
/**
* Allow to get a list of sandboxes for a team narrowed to the given params.
* It returns both the sandboxes and the pagination metadata to allow getting
* the next page of results.
*
* The returned object is async-iterable to auto-paginate through all pages:
*
* ```ts
* const result = await Sandbox.list({ namePrefix: "ci-" });
* for await (const sandbox of result) { ... }
* // or: await result.toArray();
* // or: for await (const page of result.pages()) { ... }
* ```
*/
static list(params?: Partial<Parameters<APIClient["listSandboxes"]>[0]> & Partial<Credentials> & WithFetchOptions): Promise<Paginator<{
sandboxes: {
name: string;
persistent: boolean;
createdAt: number;
updatedAt: number;
currentSessionId: string;
status: "failed" | "aborted" | "pending" | "running" | "stopping" | "stopped" | "snapshotting";
region?: string | undefined;
vcpus?: number | undefined;
memory?: number | undefined;
runtime?: string | undefined;
timeout?: number | undefined;
networkPolicy?: {
[x: string]: unknown;
mode: "allow-all";
} | {
[x: string]: unknown;
mode: "deny-all";
} | {
[x: string]: unknown;
mode: "custom";
allowedDomains?: string[] | undefined;
allowedCIDRs?: string[] | undefined;
deniedCIDRs?: string[] | undefined;
injectionRules?: {
domain: string;
headers?: Record<string, string> | undefined;
headerNames?: string[] | undefined;
match?: {
path?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
method?: string[] | undefined;
queryString?: {
key?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
value?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
}[] | undefined;
headers?: {
key?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
value?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
}[] | undefined;
} | undefined;
}[] | undefined;
forwardRules?: {
domain: string;
forwardURL: string;
match?: {
path?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
method?: string[] | undefined;
queryString?: {
key?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
value?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
}[] | undefined;
headers?: {
key?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
value?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
}[] | undefined;
} | undefined;
}[] | undefined;
} | undefined;
totalEgressBytes?: number | undefined;
totalIngressBytes?: number | undefined;
totalActiveCpuDurationMs?: number | undefined;
totalDurationMs?: number | undefined;
currentSnapshotId?: string | undefined;
statusUpdatedAt?: number | undefined;
cwd?: string | undefined;
tags?: Record<string, string> | undefined;
snapshotExpiration?: number | undefined;
keepLastSnapshots?: {
count: number;
expiration?: number | undefined;
deleteEvicted?: boolean | undefined;
} | undefined;
}[];
pagination: {
count: number;
next: string | null;
};
}, "sandboxes">>;
/**
* Serialize a Sandbox instance to plain data for @workflow/serde.
*
* @param instance - The Sandbox instance to serialize
* @returns A plain object containing sandbox metadata and routes
*/
static [WORKFLOW_SERIALIZE](instance: Sandbox): SerializedSandbox;
/**
* Deserialize a Sandbox from serialized snapshot data.
*
* The deserialized instance uses the serialized metadata synchronously and
* lazily creates an API client only when methods perform API requests.
*
* @param data - The serialized sandbox data
* @returns The reconstructed Sandbox instance
*/
static [WORKFLOW_DESERIALIZE](data: SerializedSandbox): Sandbox;
/**
* Create a new sandbox.
*
* @param params - Creation parameters and optional credentials.
* @returns A promise resolving to the created {@link Sandbox}.
* @example
* <caption>Create a sandbox with default options</caption>
* const sandbox = await Sandbox.create();
*
* @example
* <caption>Create a sandbox and drop it in the end of the block</caption>
* async function fn() {
* await using const sandbox = await Sandbox.create();
* // Sandbox automatically stopped at the end of the lexical scope
* }
*/
static create(params?: WithPrivate<CreateSandboxParams | (CreateSandboxParams & Credentials)> & WithFetchOptions): Promise<Sandbox & AsyncDisposable>;
/**
* Fork an existing sandbox into a new one. Any field passed in `params`
* overrides the source value.
*
* If the source sandbox has no current snapshot, falls back to creating a
* fresh sandbox with the same copied config plus the source's `runtime`.
*
* `env` is not copied (encrypted server-side); pass it explicitly to set
* environment variables on the fork.
*
* @param params - Fork parameters and optional credentials.
* `sourceSandbox` is the name of the source sandbox; everything else
* acts as an override.
* @returns A promise resolving to the new {@link Sandbox}.
*
* @example
* <caption>Fork with all config copied from the source</caption>
* const fork = await Sandbox.fork({ sourceSandbox: "prod-agent" });
*
* @example
* <caption>Fork with an explicit new name and overridden vcpus</caption>
* const fork = await Sandbox.fork({
* sourceSandbox: "prod-agent",
* name: "forked-prod-agent",
* resources: { vcpus: 4 },
* });
*/
static fork(params: WithPrivate<ForkSandboxParams | (ForkSandboxParams & Credentials)> & WithFetchOptions): Promise<Sandbox & AsyncDisposable>;
/**
* Retrieve an existing sandbox and resume its session.
*
* @param params - Get parameters and optional credentials.
* @returns A promise resolving to the {@link Sandbox}.
*/
static get(params: WithPrivate<GetSandboxParams | (GetSandboxParams & Credentials)> & WithFetchOptions): Promise<Sandbox>;
/**
* Retrieve an existing named sandbox, or create a new one if none exists.
*
* If `name` is omitted, this always creates a new sandbox and fires
* `onCreate`. If `name` is provided, it first tries {@link Sandbox.get};
* on `not_found` it creates a new sandbox with that name; on
* `snapshot_not_found` it deletes the stale named sandbox and creates
* a fresh one with the same name.
*
* @param params - Get/create parameters plus an optional `onCreate` hook.
* @returns A promise resolving to the {@link Sandbox}.
*
* @example
* <caption>Idempotent named sandbox with one-time setup</caption>
* const sandbox = await Sandbox.getOrCreate({
* name: "my-workspace",
* onCreate: async (sbx) => {
* await sbx.writeFiles([
* { path: "README.md", content: Buffer.from("# Hello") },
* ]);
* },
* });
*
* @example
* <caption>Unnamed — always creates</caption>
* const sandbox = await Sandbox.getOrCreate({
* onCreate: async (sbx) => {
* await sbx.runCommand("npm", ["install"]);
* },
* });
*/
static getOrCreate(params?: WithPrivate<GetOrCreateSandboxParams | (GetOrCreateSandboxParams & Credentials)> & WithFetchOptions): Promise<Sandbox>;
/**
* Create a new Sandbox instance.
*
* @param params.client - Optional API client. If not provided, will be lazily created using global credentials.
* @param params.routes - Port-to-subdomain mappings for exposed ports
* @param params.sandbox - Sandbox snapshot metadata
*/
constructor({
client,
routes,
session,
sandbox,
projectId,
onResume
}: {
client?: APIClient;
routes: SandboxRouteData[];
session?: SessionMetaData;
sandbox: SandboxMetaData;
projectId?: string;
onResume?: (sandbox: Sandbox) => Promise<void>;
});
/**
* Get the current session (the running VM) for this sandbox.
*
* @returns The {@link Session} instance.
*/
currentSession(): Session;
/**
* Resume this sandbox by creating a new session via `getSandbox`.
*/
private resume;
private doResume;
/**
* Poll until the current session reaches a terminal state, then resume.
*/
private waitForStopAndResume;
/**
* Execute `fn`, and if the session is stopped/stopping/snapshotting, resume and retry.
*/
private withResume;
/**
* Start executing a command in this sandbox.
*
* @param command - The command to execute.
* @param args - Arguments to pass to the command.
* @param opts - Optional parameters.
* @param opts.signal - An AbortSignal to cancel the command execution.
* @param opts.timeoutMs - Maximum time in milliseconds to wait for the
* command to complete. On expiry the process is killed with SIGKILL.
* @returns A {@link CommandFinished} result once execution is done.
*/
runCommand(command: string, args?: string[], opts?: {
signal?: AbortSignal;
timeoutMs?: number;
}): Promise<CommandFinished>;
/**
* Start executing a command in detached mode.
*
* @param params - The command parameters.
* @returns A {@link Command} instance for the running command.
*/
runCommand(params: RunCommandParams & {
detached: true;
}): Promise<Command>;
/**
* Start executing a command in this sandbox.
*
* @param params - The command parameters.
* @returns A {@link CommandFinished} result once execution is done.
*/
runCommand(params: RunCommandParams): Promise<CommandFinished>;
/**
* Internal helper to start a command in the sandbox.
*
* @param params - Command execution parameters.
* @returns A {@link Command} or {@link CommandFinished}, depending on `detached`.
* @internal
*/
getCommand(cmdId: string, opts?: {
signal?: AbortSignal;
}): Promise<Command>;
/**
* Create a directory in the filesystem of this sandbox.
*
* @param path - Path of the directory to create
* @param opts - Optional parameters.
* @param opts.signal - An AbortSignal to cancel the operation.
*/
mkDir(path: string, opts?: {
signal?: AbortSignal;
}): Promise<void>;
/**
* Open an interactive shell session, resuming the sandbox if needed.
*
* @param opts - Optional parameters.
* @param opts.signal - An AbortSignal to cancel the operation.
* @returns The WebSocket URL and token used to connect to the PTY.
*/
openInteractive(opts?: {
signal?: AbortSignal;
}): Promise<{
url: string;
token: string;
}>;
/**
* Read a file from the filesystem of this sandbox as a stream.
*
* @param file - File to read, with path and optional cwd
* @param opts - Optional parameters.
* @param opts.signal - An AbortSignal to cancel the operation.
* @returns A promise that resolves to a ReadableStream containing the file contents, or null if file not found
*/
readFile(file: {
path: string;
cwd?: string;
}, opts?: {
signal?: AbortSignal;
}): Promise<NodeJS.ReadableStream | null>;
/**
* Read a file from the filesystem of this sandbox as a Buffer.
*
* @param file - File to read, with path and optional cwd
* @param opts - Optional parameters.
* @param opts.signal - An AbortSignal to cancel the operation.
* @returns A promise that resolves to the file contents as a Buffer, or null if file not found
*/
readFileToBuffer(file: {
path: string;
cwd?: string;
}, opts?: {
signal?: AbortSignal;
}): Promise<Buffer | null>;
/**
* Download a file from the sandbox to the local filesystem.
*
* @param src - Source file on the sandbox, with path and optional cwd
* @param dst - Destination file on the local machine, with path and optional cwd
* @param opts - Optional parameters.
* @param opts.mkdirRecursive - If true, create parent directories for the destination if they don't exist.
* @param opts.signal - An AbortSignal to cancel the operation.
* @returns The absolute path to the written file, or null if the source file was not found
*/
downloadFile(src: {
path: string;
cwd?: string;
}, dst: {
path: string;
cwd?: string;
}, opts?: {
mkdirRecursive?: boolean;
signal?: AbortSignal;
}): Promise<string | null>;
/**
* Write files to the filesystem of this sandbox.
* Defaults to writing to /vercel/sandbox unless an absolute path is specified.
* Writes files using the `vercel-sandbox` user.
*
* @param files - Array of files with path, content, and optional mode (permissions)
* @param opts - Optional parameters.
* @param opts.signal - An AbortSignal to cancel the operation.
* @returns A promise that resolves when the files are written
*
* @example
* // Write an executable script
* await sandbox.writeFiles([
* { path: "/usr/local/bin/myscript", content: "#!/bin/bash\necho hello", mode: 0o755 }
* ]);
*/
writeFiles(files: {
path: string;
content: string | Uint8Array;
mode?: number;
}[], opts?: {
signal?: AbortSignal;
}): Promise<void>;
/**
* Get the public domain of a port of this sandbox.
*
* @param p - Port number to resolve
* @returns A full domain (e.g. `https://subdomain.vercel.run`)
* @throws If the port has no associated route
*/
domain(p: number): string;
/**
* Stop the sandbox.
*
* @param opts - Optional parameters.
* @param opts.signal - An AbortSignal to cancel the operation.
* @returns The final session state after stopping, with optional snapshot metadata.
*/
stop(opts?: {
signal?: AbortSignal;
}): Promise<SandboxSnapshot & {
snapshot?: SnapshotMetadata;
}>;
/**
* Update the network policy for this sandbox.
*
* @deprecated Use {@link Sandbox.update} instead.
*
* @param networkPolicy - The new network policy to apply.
* @param opts - Optional parameters.
* @param opts.signal - An AbortSignal to cancel the operation.
* @returns A promise that resolves when the network policy is updated.
*
* @example
* // Restrict to specific domains
* await sandbox.updateNetworkPolicy({
* allow: ["*.npmjs.org", "github.com"],
* });
*
* @example
* // Inject credentials with per-domain transformers
* await sandbox.updateNetworkPolicy({
* allow: {
* "ai-gateway.vercel.sh": [{
* transform: [{
* headers: { authorization: "Bearer ..." }
* }]
* }],
* "*": []
* }
* });
*
* @example
* // Deny all network access
* await sandbox.updateNetworkPolicy("deny-all");
*/
updateNetworkPolicy(networkPolicy: NetworkPolicy, opts?: {
signal?: AbortSignal;
}): Promise<NetworkPolicy>;
/**
* Extend the timeout of the sandbox by the specified duration.
*
* This allows you to extend the lifetime of a sandbox up until the maximum
* execution timeout for your plan.
*
* @param duration - The duration in milliseconds to extend the timeout by
* @param opts - Optional parameters.
* @param opts.signal - An AbortSignal to cancel the operation.
* @returns A promise that resolves when the timeout is extended
*
* @example
* const sandbox = await Sandbox.create({ timeout: ms('10m') });
* // Extends timeout by 5 minutes, to a total of 15 minutes.
* await sandbox.extendTimeout(ms('5m'));
*/
extendTimeout(duration: number, opts?: {
signal?: AbortSignal;
}): Promise<void>;
/**
* Create a snapshot from this currently running sandbox. New sandboxes can
* then be created from this snapshot using {@link Sandbox.createFromSnapshot}.
*
* Note: this sandbox will be stopped as part of the snapshot creation process.
*
* @param opts - Optional parameters.
* @param opts.expiration - Optional expiration time in milliseconds. Use 0 for no expiration at all.
* @param opts.signal - An AbortSignal to cancel the operation.
* @returns A promise that resolves to the Snapshot instance
*/
snapshot(opts?: {
expiration?: number;
signal?: AbortSignal;
}): Promise<Snapshot>;
/**
* Update the sandbox configuration.
*
* When `ports` is provided, it is treated as the full desired port list:
* any currently exposed port omitted from the array will be deregistered.
*
* @param params - Fields to update.
* @param opts - Optional abort signal.
*/
update(params: {
persistent?: boolean;
resources?: {
vcpus?: number;
};
timeout?: number;
networkPolicy?: NetworkPolicy;
tags?: Record<string, string>;
ports?: number[];
snapshotExpiration?: number;
keepLastSnapshots?: {
count: number;
expiration?: number;
deleteEvicted?: boolean;
} | null;
currentSnapshotId?: string;
}, opts?: {
signal?: AbortSignal;
}): Promise<void>;
/**
* Delete this sandbox.
*
* After deletion the instance becomes inert — all further API calls will
* throw immediately.
*/
delete(opts?: {
signal?: AbortSignal;
}): Promise<void>;
/**
* List sessions (VMs) that have been created for this sandbox.
*
* @param params - Optional pagination parameters.
* @returns The list of sessions and pagination metadata.
*/
listSessions(params?: {
limit?: number;
cursor?: string;
sortOrder?: "asc" | "desc";
signal?: AbortSignal;
}): Promise<Paginator<{
sessions: {
[x: string]: unknown;
id: string;
memory: number;
vcpus: number;
region: string;
runtime: string;
timeout: number;
status: "failed" | "aborted" | "pending" | "running" | "stopping" | "stopped" | "snapshotting";
requestedAt: number;
createdAt: number;
cwd: string;
updatedAt: number;
startedAt?: number | undefined;
requestedStopAt?: number | undefined;
stoppedAt?: number | undefined;
abortedAt?: number | undefined;
duration?: number | undefined;
sourceSnapshotId?: string | undefined;
snapshottedAt?: number | undefined;
interactivePort?: number | undefined;
networkPolicy?: {
[x: string]: unknown;
mode: "allow-all";
} | {
[x: string]: unknown;
mode: "deny-all";
} | {
[x: string]: unknown;
mode: "custom";
allowedDomains?: string[] | undefined;
allowedCIDRs?: string[] | undefined;
deniedCIDRs?: string[] | undefined;
injectionRules?: {
domain: string;
headers?: Record<string, string> | undefined;
headerNames?: string[] | undefined;
match?: {
path?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
method?: string[] | undefined;
queryString?: {
key?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
value?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
}[] | undefined;
headers?: {
key?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
value?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
}[] | undefined;
} | undefined;
}[] | undefined;
forwardRules?: {
domain: string;
forwardURL: string;
match?: {
path?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
method?: string[] | undefined;
queryString?: {
key?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
value?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
}[] | undefined;
headers?: {
key?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
value?: {
exact?: string | undefined;
startsWith?: string | undefined;
regex?: string | undefined;
} | undefined;
}[] | undefined;
} | undefined;
}[] | undefined;
} | undefined;
activeCpuDurationMs?: number | undefined;
networkTransfer?: {
ingress: number;
egress: number;
} | undefined;
}[];
pagination: {
count: number;
next: string | null;
};
}, "sessions">>;
/**
* List snapshots that belong to this sandbox.
*
* @param params - Optional pagination parameters.
* @returns The list of snapshots and pagination metadata.
*/
listSnapshots(params?: {
limit?: number;
cursor?: string;
sortOrder?: "asc" | "desc";
signal?: AbortSignal;
}): Promise<Paginator<{
snapshots: {
id: string;
sourceSessionId: string;
region: string;
status: "created" | "deleted" | "failed";
sizeBytes: number;
createdAt: number;
updatedAt: number;
expiresAt?: number | undefined;
lastUsedAt?: number | undefined;
creationMethod?: string | undefined;
parentId?: string | undefined;
}[];
pagination: {
count: number;
next: string | null;
};
}, "snapshots">>;
}
//#endregion
export { Sandbox, SerializedSandbox };
//# sourceMappingURL=sandbox.d.ts.map