Sandbox
Section titled “Sandbox”Represents a Daytona Sandbox.
Properties:
autoArchiveInterval?number - Auto-archive interval in minutesautoDeleteInterval?number - Auto-delete interval in minutesautoPauseInterval?number - Auto-pause interval in minutesautoStopInterval?number - Auto-stop interval in minutesbackupCreatedAt?string - When the backup was created (not returned by list results; callrefreshData()on each item to populate)backupState?SandboxBackupStateEnum - Current state of Sandbox backupbuildInfo?BuildInfo - Build information for the Sandbox if it was created from dynamic build (not returned by list results; callrefreshData()on each item to populate)codeInterpreterCodeInterpreter - Stateful interpreter interface for executing code. Currently supports only Python. For other languages, use theprocess.codeRunmethod.computerUseComputerUse - Computer use operations interface for desktop automationcpunumber - Number of CPUs allocated to the SandboxcreatedAt?string - When the Sandbox was createddisknumber - Amount of disk space allocated to the Sandbox in GiBdomainAllowList?string - Comma-separated list of allowed domains for the Sandbox (not returned by list results; callrefreshData()on each item to populate)env?Record<string, string> - Environment variables set in the Sandbox (not returned by list results; callrefreshData()on each item to populate)errorReason?string - Error message if Sandbox is in error statefsFileSystem - File system operations interfacegitGit - Git operations interfacegpunumber - Number of GPUs allocated to the Sandboxidstring - Unique identifier for the SandboxlabelsRecord<string, string> - Custom labels attached to the SandboxlastActivityAt?string - When the Sandbox last had activitylinkedSandboxId?string - ID of the Sandbox this Sandbox is linked to. When set, the Sandbox is co-located on the same runner as the linked Sandbox. (not returned by list results; callrefreshData()on each item to populate)memorynumber - Amount of memory allocated to the Sandbox in GiBnamestringnetworkAllowList?string - Comma-separated list of allowed CIDR network addresses for the Sandbox (not returned by list results; callrefreshData()on each item to populate)networkBlockAll?boolean - Whether to block all network access for the Sandbox (not returned by list results; callrefreshData()on each item to populate)organizationIdstring - Organization ID of the SandboxprocessProcess - Process execution interfacepublicboolean - Whether the Sandbox is publicly accessiblerecoverable?boolean - Whether the Sandbox error is recoverable.snapshot?string - Daytona snapshot used to create the Sandboxstate?SandboxState - Current state of the Sandbox (e.g., “started”, “stopped”)targetstring - Target location of the runner where the Sandbox runstoolboxProxyUrlstringupdatedAt?string - When the Sandbox was last updateduserstring - OS user running in the Sandboxvolumes?SandboxVolume[] - Volumes attached to the Sandbox (not returned by list results; callrefreshData()on each item to populate)
Constructors
Section titled “Constructors”new Sandbox()
Section titled “new Sandbox()”new Sandbox( sandboxDto: SandboxListItem | Sandbox, clientConfig: Configuration, axiosInstance: AxiosInstance, sandboxApi: SandboxApi, getAnalyticsApiUrl: () => Promise<string>): SandboxCreates a new Sandbox instance
Parameters:
sandboxDtoThe API Sandbox instance -SandboxListItem|SandboxclientConfigConfigurationaxiosInstanceAxiosInstancesandboxApiSandboxApigetAnalyticsApiUrl() => Promise<string>
Returns:
Sandbox
Methods
Section titled “Methods”_experimental_createSnapshot()
Section titled “_experimental_createSnapshot()”_experimental_createSnapshot(name: string, timeout?: number): Promise<void>Creates a snapshot from the current state of the Sandbox.
This captures the Sandbox’s filesystem into a reusable snapshot that can be used to create new Sandboxes. The Sandbox will temporarily enter a ‘snapshotting’ state and return to its previous state when complete.
Parameters:
namestring - Name for the new snapshottimeout?number = 60 - Maximum time to wait in seconds. 0 means no timeout. Defaults to 60-second timeout.
Returns:
Promise<void>
Throws:
-
If timeout is a negative number
-
If the snapshot operation fails or times out
Example:
const sandbox = await daytona.get('my-sandbox');await sandbox._experimental_createSnapshot('my-snapshot');console.log('Snapshot created successfully');_experimental_fork()
Section titled “_experimental_fork()”_experimental_fork(params?: { name: string;}, timeout?: number): Promise<Sandbox>Forks the Sandbox, creating a new Sandbox with an identical filesystem.
The forked Sandbox is a copy-on-write clone of the original. It starts with the same disk contents but operates independently from that point on.
Parameters:
params?Fork parametersname?string - Optional name for the forked Sandbox. If not provided, a unique name will be generated.timeout?number = 60 - Maximum time to wait in seconds. 0 means no timeout. Defaults to 60-second timeout.
Returns:
Promise<Sandbox>- The forked Sandbox.
Throws:
-
If timeout is a negative number
-
If the fork operation fails or times out
Example:
const sandbox = await daytona.get('my-sandbox');const forked = await sandbox._experimental_fork({ name: 'my-fork' });console.log(`Forked sandbox: ${forked.id}`);archive()
Section titled “archive()”archive(): Promise<void>Archives the sandbox, making it inactive and preserving its state. When sandboxes are archived, the entire filesystem state is moved to cost-effective object storage, making it possible to keep sandboxes available for an extended period. The tradeoff between archived and stopped states is that starting an archived sandbox takes more time, depending on its size. Sandbox must be stopped before archiving.
Returns:
Promise<void>
createLspServer()
Section titled “createLspServer()”createLspServer(languageId: string, pathToProject: string): Promise<LspServer>Creates a new Language Server Protocol (LSP) server instance.
The LSP server provides language-specific features like code completion, diagnostics, and more.
Parameters:
languageIdstring - The language server type (e.g., “typescript”)pathToProjectstring - Path to the project root directory. Relative paths are resolved based on the sandbox working directory.
Returns:
Promise<LspServer>- A new LSP server instance configured for the specified language
Example:
const lsp = await sandbox.createLspServer('typescript', 'workspace/project');createSshAccess()
Section titled “createSshAccess()”createSshAccess(expiresInMinutes?: number): Promise<SshAccessDto>Creates an SSH access token for the sandbox.
Parameters:
expiresInMinutes?number - The number of minutes the SSH access token will be valid for.
Returns:
Promise<SshAccessDto>- The SSH access token.
delete()
Section titled “delete()”delete(timeout: number): Promise<void>Deletes the Sandbox.
Parameters:
timeoutnumber = 60
Returns:
Promise<void>
expireSignedPreviewUrl()
Section titled “expireSignedPreviewUrl()”expireSignedPreviewUrl(port: number, token: string): Promise<void>Expires a signed preview url for the sandbox at the specified port.
Parameters:
portnumber - The port to expire the signed preview url on.tokenstring - The token to expire the signed preview url on.
Returns:
Promise<void>
getMetrics()
Section titled “getMetrics()”getMetrics(start?: Date, end?: Date): Promise<SandboxMetrics[]>Gets historical time-series resource usage metrics for the Sandbox.
Parameters:
start?Date - Start of the time range. Defaults to the Sandbox creation time.end?Date - End of the time range. Defaults to the current time.
Returns:
Promise<SandboxMetrics[]>- Time-ordered usage samples over the requested range.
Example:
const samples = await sandbox.getMetrics()for (const s of samples) { console.log(`${s.timestamp.toISOString()} CPU: ${s.cpuUsedPct}% mem: ${s.memUsed}/${s.memTotal}`)}getMetricsLatest()
Section titled “getMetricsLatest()”getMetricsLatest(): Promise<SandboxMetrics>Gets the most recent resource usage sample directly from the sandbox daemon.
Unlike getMetrics, which returns aggregated historical samples, this returns the single current reading without going through the telemetry backend.
Returns:
Promise<SandboxMetrics>- The current resource usage sample for the sandbox.
Example:
const m = await sandbox.getMetricsLatest()console.log(`CPU: ${m.cpuUsedPct}%, mem: ${m.memUsed}/${m.memTotal}`)getPreviewLink()
Section titled “getPreviewLink()”getPreviewLink(port: number): Promise<PortPreviewUrl>Retrieves the preview link for the sandbox at the specified port. If the port is closed, it will be opened automatically. For private sandboxes, a token is included to grant access to the URL.
Parameters:
portnumber - The port to open the preview link on.
Returns:
Promise<PortPreviewUrl>- The response object for the preview link, which includes theurland thetoken(to access private sandboxes).
Example:
const previewLink = await sandbox.getPreviewLink(3000);console.log(`Preview URL: ${previewLink.url}`);console.log(`Token: ${previewLink.token}`);getSignedPreviewUrl()
Section titled “getSignedPreviewUrl()”getSignedPreviewUrl(port: number, expiresInSeconds?: number): Promise<SignedPortPreviewUrl>Retrieves a signed preview url for the sandbox at the specified port.
Parameters:
portnumber - The port to open the preview link on.expiresInSeconds?number - The number of seconds the signed preview url will be valid for. Defaults to 60 seconds.
Returns:
Promise<SignedPortPreviewUrl>- The response object for the signed preview url.
getUserHomeDir()
Section titled “getUserHomeDir()”getUserHomeDir(): Promise<string>Gets the user’s home directory path for the logged in user inside the Sandbox.
Returns:
Promise<string>- The absolute path to the Sandbox user’s home directory for the logged in user
Example:
const userHomeDir = await sandbox.getUserHomeDir();console.log(`Sandbox user home: ${userHomeDir}`);getUserRootDir()
Section titled “getUserRootDir()”getUserRootDir(): Promise<string>Returns:
Promise<string>
Deprecated
Section titled “Deprecated”Use getUserHomeDir instead. This method will be removed in a future version.
getWorkDir()
Section titled “getWorkDir()”getWorkDir(): Promise<string>Gets the working directory path inside the Sandbox.
Returns:
Promise<string>- The absolute path to the Sandbox working directory. Uses the WORKDIR specified in the Dockerfile if present, or falling back to the user’s home directory if not.
Example:
const workDir = await sandbox.getWorkDir();console.log(`Sandbox working directory: ${workDir}`);pause()
Section titled “pause()”pause(timeout?: number): Promise<void>Pauses the Sandbox, freezing all running processes.
The Sandbox will enter a ‘pausing’ state and transition to ‘paused’ when complete. While paused, the Sandbox retains its state in memory but does not consume CPU cycles.
Parameters:
timeout?number = 60 - Maximum time to wait in seconds. 0 means no timeout. Defaults to 60-second timeout.
Returns:
Promise<void>
Throws:
-
If timeout is a negative number
-
If the pause operation fails or times out
Example:
const sandbox = await daytona.get('my-sandbox');await sandbox.pause();console.log('Sandbox paused successfully');recover()
Section titled “recover()”recover(timeout?: number): Promise<void>Recover the Sandbox from a recoverable error and wait for it to be ready.
Parameters:
timeout?number = 60 - Maximum time to wait in seconds. 0 means no timeout. Defaults to 60-second timeout.
Returns:
Promise<void>
Throws:
DaytonaError- If Sandbox fails to recover or times out
Example:
const sandbox = await daytona.get('my-sandbox-id');await sandbox.recover();console.log('Sandbox recovered successfully');refreshActivity()
Section titled “refreshActivity()”refreshActivity(): Promise<void>Refreshes the sandbox activity to reset the timer for automated lifecycle management actions.
This method updates the sandbox’s last activity timestamp without changing its state. It is useful for keeping long-running sessions alive while there is still user activity.
Returns:
Promise<void>
Example:
// Keep sandbox activity aliveawait sandbox.refreshActivity();refreshData()
Section titled “refreshData()”refreshData(): Promise<void>Refreshes the Sandbox data from the API.
Returns:
Promise<void>
Example:
await sandbox.refreshData();console.log(`Sandbox ${sandbox.id}:`);console.log(`State: ${sandbox.state}`);console.log(`Resources: ${sandbox.cpu} CPU, ${sandbox.memory} GiB RAM`);resize()
Section titled “resize()”resize(resources: Pick<Resources, "cpu" | "memory" | "disk">, timeout?: number): Promise<void>Resizes the Sandbox resources.
Changes the CPU, memory, or disk allocation. Hot resize (on a running Sandbox) accepts only CPU and memory increases. Disk resize requires a stopped Sandbox; disk can only grow. GPU is not resizable — to change GPU, create a new Sandbox.
Parameters:
resourcesPick<Resources, “cpu” | “memory” | “disk”> - New resource configuration (cpu, memory, disk only). Only specified fields are updated.timeout?number = 60 - Timeout in seconds for the resize operation. 0 means no timeout.
Returns:
Promise<void>
Throws:
If hot-resize constraints are violated, disk resize is attempted on a running Sandbox, disk decrease is attempted, no fields are provided, or the operation times out.
Examples:
await sandbox.resize({ cpu: 4, memory: 8 })await sandbox.stop()await sandbox.resize({ cpu: 2, memory: 4, disk: 30 })revokeSshAccess()
Section titled “revokeSshAccess()”revokeSshAccess(token: string): Promise<void>Revokes an SSH access token for the sandbox.
Parameters:
tokenstring - The token to revoke.
Returns:
Promise<void>
setAutoArchiveInterval()
Section titled “setAutoArchiveInterval()”setAutoArchiveInterval(interval: number): Promise<void>Set the auto-archive interval for the Sandbox.
The Sandbox will automatically archive after being continuously stopped for the specified interval.
Parameters:
intervalnumber - Number of minutes after which a continuously stopped Sandbox will be auto-archived. Set to 0 for the maximum interval. Default is 7 days.
Returns:
Promise<void>
Throws:
DaytonaError- If interval is not a non-negative integer
Example:
// Auto-archive after 1 hourawait sandbox.setAutoArchiveInterval(60);// Or use the maximum intervalawait sandbox.setAutoArchiveInterval(0);setAutoDeleteInterval()
Section titled “setAutoDeleteInterval()”setAutoDeleteInterval(interval: number): Promise<void>Set the auto-delete interval for the Sandbox.
The Sandbox will automatically delete after being continuously stopped for the specified interval.
Parameters:
intervalnumber - Number of minutes after which a continuously stopped Sandbox will be auto-deleted. Set to negative value to disable auto-delete. Set to 0 to delete immediately upon stopping. By default, auto-delete is disabled.
Returns:
Promise<void>
Example:
// Auto-delete after 1 hourawait sandbox.setAutoDeleteInterval(60);// Or delete immediately upon stoppingawait sandbox.setAutoDeleteInterval(0);// Or disable auto-deleteawait sandbox.setAutoDeleteInterval(-1);setAutoPauseInterval()
Section titled “setAutoPauseInterval()”setAutoPauseInterval(interval: number): Promise<void>Set the auto-pause interval for the Sandbox.
The Sandbox will automatically pause after being idle (no new events) for the specified interval. Events include any state changes or interactions with the Sandbox through the sdk. Interactions using Sandbox Previews are not included.
Only supported for sandbox classes that support pausing. At most one of the auto-stop and auto-pause intervals may be non-zero, so disable auto-stop first by setting its interval to 0.
Parameters:
intervalnumber - Number of minutes of inactivity before auto-pausing. Set to 0 to disable auto-pause. For pause-supporting sandbox classes, creation defaults to 60 minutes when neither interval is provided.
Returns:
Promise<void>
Throws:
DaytonaError- If interval is not a non-negative integer
Example:
// Auto-pause after 1 hourawait sandbox.setAutoPauseInterval(60);// Or disable auto-pauseawait sandbox.setAutoPauseInterval(0);setAutostopInterval()
Section titled “setAutostopInterval()”setAutostopInterval(interval: number): Promise<void>Set the auto-stop interval for the Sandbox.
The Sandbox will automatically stop after being idle (no new events) for the specified interval. Events include any state changes or interactions with the Sandbox through the sdk. Interactions using Sandbox Previews are not included.
Parameters:
intervalnumber - Number of minutes of inactivity before auto-stopping. Set to 0 to disable auto-stop. Default is 15 minutes.
Returns:
Promise<void>
Throws:
DaytonaError- If interval is not a non-negative integer
Example:
// Auto-stop after 1 hourawait sandbox.setAutostopInterval(60);// Or disable auto-stopawait sandbox.setAutostopInterval(0);setLabels()
Section titled “setLabels()”setLabels(labels: Record<string, string>): Promise<Record<string, string>>Sets labels for the Sandbox.
Labels are key-value pairs that can be used to organize and identify Sandboxes.
Parameters:
labelsRecord<string, string> - Dictionary of key-value pairs representing Sandbox labels
Returns:
Promise<Record<string, string>>
Example:
// Set sandbox labelsawait sandbox.setLabels({ project: 'my-project', environment: 'development', team: 'backend'});start()
Section titled “start()”start(timeout?: number): Promise<void>Start the Sandbox.
This method starts the Sandbox and waits for it to be ready.
Parameters:
timeout?number = 60 - Maximum time to wait in seconds. 0 means no timeout. Defaults to 60-second timeout.
Returns:
Promise<void>
Throws:
DaytonaError- If Sandbox fails to start or times out
Example:
const sandbox = await daytona.getCurrentSandbox('my-sandbox');await sandbox.start(40); // Wait up to 40 secondsconsole.log('Sandbox started successfully');stop()
Section titled “stop()”stop(timeout?: number, force?: boolean): Promise<void>Stops the Sandbox.
This method stops the Sandbox and waits for it to be fully stopped.
Parameters:
timeout?number = 60 - Maximum time to wait in seconds. 0 means no timeout. Defaults to 60-second timeout.force?boolean = false - If true, uses SIGKILL instead of SIGTERM. Defaults to false.
Returns:
Promise<void>
Example:
const sandbox = await daytona.get('my-sandbox-id');await sandbox.stop();console.log('Sandbox stopped successfully');updateEnv()
Section titled “updateEnv()”updateEnv(env: Record<string, string>, options?: { unset: string[];}): Promise<void>Updates the Sandbox daemon’s process environment.
Variables in env are set (added or overwritten) and variables listed in options.unset
are removed. Newly spawned processes, sessions and PTYs inherit the change; already-running
processes keep their environment.
Parameters:
envRecord<string, string> - Map of environment variable names to values to set.options?Optional settings.unset?string[] - Names of environment variables to remove beforeenvis applied.
Returns:
Promise<void>
Example:
// Set a variable and remove anotherawait sandbox.updateEnv({ NODE_ENV: 'production' }, { unset: ['DEBUG'] });updateNetworkSettings()
Section titled “updateNetworkSettings()”updateNetworkSettings(settings: UpdateSandboxNetworkSettings): Promise<void>Updates outbound network policy for this sandbox on the runner (for example block all traffic, restore general internet access, or apply a CIDR allow list) without stopping the sandbox.
This maps to the same mechanism as creating a sandbox with networkBlockAll / networkAllowList /
domainAllowList: the runner applies iptables rules to the sandbox container.
Parameters:
settingsUpdateSandboxNetworkSettings - At least one ofnetworkBlockAll,networkAllowListordomainAllowListmust be set. SetnetworkBlockAlltofalseto restore outbound access after a block (and clear a stored allow list).
Returns:
Promise<void>
Example:
// Pause internet (outbound blocked)await sandbox.updateNetworkSettings({ networkBlockAll: true });// Resume internetawait sandbox.updateNetworkSettings({ networkBlockAll: false });// Allow only specific domainsawait sandbox.updateNetworkSettings({ domainAllowList: 'example.com,*.daytona.io' });updateSecrets()
Section titled “updateSecrets()”updateSecrets(secrets: Record<string, string>): Promise<void>Replaces the set of vault secrets mounted in the Sandbox.
Each key is an environment variable name and each value is the name of an existing organization Secret to mount under that name. The provided map replaces the previously mounted set — pass an empty object to detach all secrets.
Attached, detached, or rotated secrets take effect for outbound requests within seconds. However, newly attached env vars only become visible to processes spawned after the update; already-running processes keep their environment. A Sandbox created without any secrets must be restarted for newly attached secrets to work.
Parameters:
secretsRecord<string, string> - Map of environment variable name to the name of an existing organization Secret. Every referenced Secret name must already exist in the organization.
Returns:
Promise<void>
Example:
// Mount two secretsawait sandbox.updateSecrets({ API_KEY: 'my-api-key', DB_PASSWORD: 'prod-db-password' });// Detach all secretsawait sandbox.updateSecrets({});validateSshAccess()
Section titled “validateSshAccess()”validateSshAccess(token: string): Promise<SshAccessValidationDto>Validates an SSH access token for the sandbox.
Parameters:
tokenstring - The token to validate.
Returns:
Promise<SshAccessValidationDto>- The SSH access validation result.
waitForResizeComplete()
Section titled “waitForResizeComplete()”waitForResizeComplete(timeout?: number): Promise<void>Waits for the Sandbox resize operation to complete.
This method polls the Sandbox status until the state is no longer ‘resizing’.
Parameters:
timeout?number = 60 - Maximum time to wait in seconds. 0 means no timeout.
Returns:
Promise<void>
Throws:
- If the sandbox ends up in an error state or resize times out.
waitUntilStarted()
Section titled “waitUntilStarted()”waitUntilStarted(timeout?: number): Promise<void>Waits for the Sandbox to reach the ‘started’ state.
This method polls the Sandbox status until it reaches the ‘started’ state or encounters an error.
Parameters:
timeout?number = 60 - Maximum time to wait in seconds. 0 means no timeout. Defaults to 60 seconds.
Returns:
Promise<void>
Throws:
DaytonaError- If the sandbox ends up in an error state or fails to start within the timeout period.
waitUntilStopped()
Section titled “waitUntilStopped()”waitUntilStopped(timeout?: number): Promise<void>Wait for Sandbox to reach ‘stopped’ state.
This method polls the Sandbox status until it reaches the ‘stopped’ state or encounters an error.
Parameters:
timeout?number = 60 - Maximum time to wait in seconds. 0 means no timeout. Defaults to 60 seconds.
Returns:
Promise<void>
Throws:
DaytonaError- If the sandbox fails to stop within the timeout period.
ListSandboxesQuery
Section titled “ListSandboxesQuery”Properties:
createdAtAfter?Date - Include sandboxes created after this timestampcreatedAtBefore?Date - Include sandboxes created before this timestampid?string - Filter by ID prefix (case-insensitive)isPublic?boolean - Filter by public statusisRecoverable?boolean - Filter by recoverable statuslabels?Record<string, string> - Filter by labelslastActivityAfter?Date - Include sandboxes with last activity after this timestamplastActivityBefore?Date - Include sandboxes with last activity before this timestamplimit?number - Per-page fetch size. Does NOT limit the total number of Sandboxes returned.maxCpu?number - Filter by maximum CPUmaxDiskGib?number - Filter by maximum disk space in GiBmaxMemoryGib?number - Filter by maximum memory in GiBminCpu?number - Filter by minimum CPUminDiskGib?number - Filter by minimum disk space in GiBminMemoryGib?number - Filter by minimum memory in GiBname?string - Filter by name prefix (case-insensitive)order?SandboxListSortDirection - Sort directionsnapshots?string[] - Filter by snapshot namessort?SandboxListSortField - Sort by fieldstates?SandboxState[] - Filter by statestargets?string[] - Filter by targets
SandboxMetrics
Section titled “SandboxMetrics”A single point-in-time sample of historical Sandbox resource usage.
Properties:
cpuCountnumber - Number of CPU cores allocated to the Sandbox.cpuUsedPctnumber - CPU utilization as a percentage of the allocated limit.diskTotalnumber - Total disk space in bytes.diskUsednumber - Used disk space in bytes.memCachenumber - Memory used by the page cache in bytes.memTotalnumber - Total memory in bytes.memUsednumber - Used memory in bytes.timestampDate - Timestamp of this sample.