Skip to main content
This page is the runtime API surface of the Sandbox SDK in one place. It maps the Python and TypeScript sandbox-management APIs you’ll use to create sandboxes, execute work inside them, manage files and processes, and interact with desktop sandboxes. Each detail page linked below expands on the same APIs with longer examples and edge cases.
All method names below use the Python form. The TypeScript SDK mirrors them in camelCase (start_processstartProcess, read_filereadFile, memory_mbmemoryMb, etc.). The same JavaScript runtime API is used from Node.js.
This page focuses on the sandbox runtime SDK surface. Related interfaces documented elsewhere include the CLI and HTTP API, the image-building DSLs in Sandbox Images, and the browser/VNC integration details in Computer Use.

SandboxClient

SandboxClient is the top-level entry point for managing sandboxes in your namespace. Instantiate it once and reuse it — it handles auth, discovery, and the HTTP transport underneath.
from tensorlake.sandbox import SandboxClient

# Authentication comes from `tl login` or TENSORLAKE_API_KEY env var
client = SandboxClient()
See Authentication for the full auth flow.

Create

Create a sandbox. Omit name for an ephemeral sandbox (cannot be suspended); pass name to create a named sandbox that supports suspend/resume. Returns a SandboxInfo describing the new sandbox.
ParameterTypeDefaultDescription
namestr | NoneNoneHuman-readable name. Required for suspend/resume.
cpusfloat1.0Number of CPUs to allocate.
memory_mbint1024Memory in megabytes. 1024–8192 MB per CPU core.
timeout_secsint | NoneNoneAuto-suspend (named) or auto-terminate (ephemeral) after this many seconds.
imagestr | Noneplatform defaultName or ID of a prebuilt Sandbox Image.
snapshot_idstr | NoneNoneRestore from a snapshot instead of booting a fresh VM.
secret_nameslist[str] | NoneNoneSecrets to inject as environment variables. Must be pre-registered with tl secrets set.
expose_portslist[int] | NoneNoneUser ports to route public traffic to (see Networking).
allow_unauthenticated_accessboolFalseIf true, exposed ports accept unauthenticated internet traffic.
sandbox = client.create(
    name="my-env",
    cpus=2.0,
    memory_mb=4096,
    timeout_secs=1800,
    secret_names=["OPENAI_API_KEY"],
)
print(sandbox.sandbox_id, sandbox.status)

Create and connect

create_and_connect creates a sandbox and returns a live Sandbox handle you can immediately run commands against — one call instead of two.
with client.create_and_connect(cpus=2.0, memory_mb=2048) as sandbox:
    result = sandbox.run("python", ["-c", "print('hello')"])
    print(result.stdout)
# Context manager terminates the sandbox on exit

Connect

Get a Sandbox handle for an existing sandbox (by ID or name) without creating a new one. Use this to rejoin a named sandbox after resume, or to operate on a sandbox a different process created.
sandbox = client.connect(identifier="my-env")
print(sandbox.sandbox_id)  # always UUID, even if you connected by name
print(sandbox.name)        # "my-env"

List and get

Inspect sandboxes in your namespace. list() returns all sandboxes; get() returns one by ID or name.
for sb in client.list():
    print(sb.sandbox_id, sb.status)

info = client.get("my-env")
print(info.status, info.image, info.resources.cpus, info.resources.memory_mb)

Rename

Assigning a name to an ephemeral sandbox converts it to a named sandbox that supports suspend/resume.
renamed = client.update_sandbox("sbx-123", "my-env")

Suspend and resume

Pause a running named sandbox in place; resume it later under the same ID with its memory, filesystem, and running processes intact. Ephemeral sandboxes return an error on suspend.
client.suspend("my-env")
client.resume("my-env")

Terminate

delete() ends the sandbox permanently. Terminated is a final state and cannot be reversed.
client.delete("my-env")
See Lifecycle for the full state machine.

Expose and unexpose ports

Route public internet traffic to services listening on user ports inside the sandbox. Requests arrive at https://<port>-<sandbox-id-or-name>.sandbox.tensorlake.ai.
client.expose_ports("my-env", [8080], allow_unauthenticated_access=False)
client.unexpose_ports("my-env", [8080])
See Networking for authenticated vs. unauthenticated access and how clients reach user ports.

Snapshot and restore

Capture a reusable artifact of the sandbox (filesystem + memory + running processes). Restore by passing snapshot_id to create or create_and_connect.
snapshot = client.snapshot_and_wait(sandbox.sandbox_id)

# Restore into a fresh sandbox
restored = client.create_and_connect(snapshot_id=snapshot.snapshot_id)

# Manage snapshots
client.list_snapshots()
client.get_snapshot(snapshot.snapshot_id)
client.delete_snapshot(snapshot.snapshot_id)
Suspend pauses this sandbox; snapshot captures a reusable artifact you restore into a new sandbox. See Snapshots.

Sandbox handle

The Sandbox object returned by create_and_connect() or connect() is how you execute work inside a running sandbox. All methods below target a single live sandbox.
Property (Python)Property (TypeScript)TypeDescription
sandbox_idsandboxIdstrServer-assigned UUID.
namenamestr | NoneHuman-readable name, or None for ephemeral.

Run a command

run() is the short-lived foreground execution primitive: send a command, wait for it to exit, receive captured output. Use it for the common case of “do this one thing and give me the result.”
result = sandbox.run("python", ["-c", "print('hello')"], timeout_secs=30)
print(result.stdout)
print(result.stderr)
print(result.exit_code)
Pass env={"KEY": "value"} (Python) or env: { KEY: "value" } (TypeScript) for per-command environment variables. See Environment Variables. See Execute Commands for streaming, multi-step shell pipelines, and error handling.

Background processes

For long-running or concurrent work, start a process and keep the handle so you can monitor, stream output, and signal it.
proc = sandbox.start_process("python", ["-m", "http.server", "8080"])
print(proc.pid)

for p in sandbox.list_processes():
    print(p.pid, p.command, p.status)

for event in sandbox.follow_output(proc.pid):
    print(event.line, end="")

import signal
sandbox.send_signal(proc.pid, signal.SIGTERM)

Writing to stdin

Drive a process interactively from code by writing bytes to its stdin, then closing the stream when you’re done.
proc = sandbox.start_process("python", ["-c", "import sys; print(sys.stdin.read())"])
sandbox.write_stdin(proc.pid, b"hello from stdin\n")
sandbox.close_stdin(proc.pid)
See Process Management for the full API.

PTY sessions

Open an interactive terminal inside the sandbox. The PTY is created over HTTPS; terminal I/O then moves over a WebSocket attached to the session.
pty = sandbox.create_pty(
    command="bash",
    cols=120,
    rows=40,
    env={"PS1": "sandbox$ "},
)
# Drive pty.websocket_url with a WebSocket client, or reconnect later
reattached = sandbox.connect_pty(pty.session_id, pty.token)
See PTY Sessions for the wire protocol, reconnect flow, and resize frames.

File operations

Copy data in and out of the sandbox filesystem without spawning a shell.
sandbox.write_file("/workspace/data.csv", b"name,score\nAlice,95\n")

content = bytes(sandbox.read_file("/workspace/data.csv"))
print(content.decode("utf-8"))

for entry in sandbox.list_directory("/workspace"):
    print(entry.name, entry.is_dir, entry.size)

sandbox.delete_file("/workspace/data.csv")
See File Operations for binary uploads, recursive listings, and move/copy patterns.

Desktop sessions

Desktop sandboxes expose a higher-level remote-control handle on top of the normal Sandbox APIs. Use this with tensorlake/ubuntu-vnc to capture screenshots and drive mouse and keyboard input through the authenticated sandbox proxy.
with sandbox.connect_desktop(password="tensorlake") as desktop:
    png_bytes = desktop.screenshot()
    desktop.move_mouse(640, 400)
    desktop.click()
    desktop.type_text("hello from desktop")
    print(desktop.width, desktop.height)
Common desktop methods are:
PythonTypeScriptDescription
screenshot()screenshot()Capture the current desktop as PNG bytes.
move_mouse(x, y)moveMouse(x, y)Move the pointer to absolute screen coordinates.
click()click()Click the current pointer location.
double_click()doubleClick()Double-click the current pointer location.
scroll_up() / scroll_down()scrollUp() / scrollDown()Scroll vertically.
press(keys)press(keys)Send a key or key chord.
type_text(text)typeText(text)Type text into the active window.
width, heightwidth, heightDesktop resolution.
See Computer Use for reconnect patterns, coordinate workflows, and noVNC integration.

Terminate

Shortcut for client.delete(sandbox.sandbox_id) that uses the handle you already have.
# Python uses the client for termination
client.delete(sandbox.sandbox_id)

Data models

The SDK returns typed objects for every API call. The fields below are the ones you’ll read most often. Field names shown in Python snake_case; TypeScript uses the camelCase equivalent.

SandboxInfo

Returned by client.create(), client.get(), client.list(), and the suspend/resume/expose calls.
FieldTypeDescription
sandbox_idstrServer UUID.
namestr | NoneName, or None for ephemeral.
namespacestrNamespace owning the sandbox.
statusstrPending, Running, Suspending, Suspended, Snapshotting, Terminated.
imagestrSandbox image in use.
resourcesContainerResourcesInfo.cpus: float, .memory_mb: int.
secret_nameslist[str]Injected secrets.
timeout_secsintAuto-suspend/terminate timeout.
exposed_portslist[int]Public-routed user ports.
allow_unauthenticated_accessboolWhether exposed ports accept unauthenticated traffic.
entrypointlist[str]Custom entrypoint command.
created_atdatetime | NoneCreation timestamp.
terminated_atdatetime | NoneTermination timestamp (if terminated).

Sandbox

Returned by client.create_and_connect() and client.connect(). Exposes the runtime methods documented above plus:
PropertyTypeDescription
sandbox_id / sandboxIdstrUUID, even if connected by name.
namestr | NoneHuman-readable name.

ProcessInfo

Returned by start_process() and list_processes().
FieldTypeDescription
pidintProcess ID inside the sandbox.
commandstrThe executed command.
argslist[str]Command arguments.
statusstrRunning, Exited, etc.
exit_codeint | NoneExit code once the process has exited.

CommandResult

Returned by run().
FieldTypeDescription
stdoutstrCaptured standard output.
stderrstrCaptured standard error.
exit_codeintProcess exit code.

SnapshotInfo

Returned by the snapshot APIs.
FieldTypeDescription
snapshot_idstrServer-assigned ID, use to restore.
sandbox_idstrSource sandbox this snapshot was captured from.
statusstrPending, Ready, Failed.
size_bytesint | NoneSize of the snapshot artifact.
created_atdatetime | NoneCapture timestamp.

Learn more

Lifecycle

State machine, suspend/resume, timeouts.

Execute Commands

Run commands, capture output, stream.

Process Management

Background processes, stdin, signals.

PTY Sessions

Interactive shells over WebSocket.

File Operations

Read, write, list, delete.

Snapshots

Capture and restore full VM state.

Sandbox Images

Prebuild dependencies into reusable images.

Computer Use

Desktop sessions, screenshots, mouse, keyboard.

Networking

Expose user ports to the internet.

Environment Variables

Per-command and per-PTY environment.