` |
Use `leap0-authorization` when the `authorization` header is already consumed by another layer (e.g. a proxy, gateway, or a service running inside the sandbox).
## Organization scope [#organization-scope]
API keys are scoped to a single organization. All resources created with a key (sandboxes, templates, snapshots) belong to that organization. Keys cannot access resources in other organizations.
See Limits for all organization quotas.
# Limits (/limits)
Public preview
Limits may change during the public preview period. Contact us if you need higher limits for your use case.
## Sandbox resource limits [#sandbox-resource-limits]
| Resource | Limit |
| ---------------------- | ------------------------------- |
| vCPU | 1 - 8 |
| Memory | 512 MiB - 8 GB (must be even) |
| Timeout | 1 min - 8 hours (default 5 min) |
| Disk | 10 GiB |
| Max request/response | 10 MiB |
| WebSocket idle timeout | 5 minutes |
## Organization quotas [#organization-quotas]
When a limit is reached, related endpoints reject new creates or invites.
| Resource | Limit |
| ----------------------------------- | ------------------- |
| API keys per organization | 100 |
| Templates per organization | 25 |
| Users + pending invitations per org | 20 |
| API rate limit | 1000 requests / 60s |
# Code Interpreter (/code-interpreter)
Execute code inside a running sandbox. The interpreter keeps a persistent REPL process alive so that variables, imports, and working directory survive across calls. Send code, get back stdout, stderr, rich results (text, images, HTML, JSON), and structured errors. For a full endpoint reference, see the Code Interpreter API.
Two runtimes are available:
| Alias | Runtime | Notes |
| ----------------------------------------------------- | ------------------------ | ---------------------------------------------------------------------------------------- |
| `python`, `py`, `python3` | Python 3.12 | 50+ pre-installed data-science packages. Matplotlib charts auto-captured as PNG and SVG. |
| `typescript`, `ts`, `javascript`, `js`, `bun`, `node` | Bun v1.3.10 (TypeScript) | Last expression is returned as a result. State accumulates across calls. |
### Create a context [#create-a-context]
```python
from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)
context = sandbox.code_interpreter.create_context(
language="python",
cwd="/home/user",
)
print(context.id, context.language)
```
```ts
import { DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
templateName: DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME,
});
const context = await sandbox.codeInterpreter.createContext("python", "/home/user");
console.log(context.id, context.language);
await client.close();
```
| Field | Type | Required | Description |
| ---------- | ------ | -------- | ---------------------------------------------------- |
| `language` | string | Yes | One of the supported language aliases. |
| `cwd` | string | No | Initial working directory. Defaults to `/home/user`. |
### List contexts [#list-contexts]
```python
from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)
for context in sandbox.code_interpreter.list_contexts():
print(context.id, context.language, context.cwd)
```
```ts
import { DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
templateName: DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME,
});
for (const context of await sandbox.codeInterpreter.listContexts()) {
console.log(context.id, context.language, context.cwd);
}
await client.close();
```
### Get a context [#get-a-context]
```python
from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)
context = sandbox.code_interpreter.get_context("")
print(context)
```
```ts
import { DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
templateName: DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME,
});
const context = await sandbox.codeInterpreter.getContext("");
console.log(context);
await client.close();
```
### Delete a context [#delete-a-context]
```python
from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)
sandbox.code_interpreter.delete_context("")
```
```ts
import { DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
templateName: DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME,
});
await sandbox.codeInterpreter.deleteContext("");
await client.close();
```
## Execute code [#execute-code]
Run code synchronously. The sandbox waits for the code to finish and returns the full result in one response.
```python
from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)
first = sandbox.code_interpreter.execute(
code="prices = [10, 20, 30, 40, 50]",
language="python",
)
second = sandbox.code_interpreter.execute(
code="sum(prices) / len(prices)",
language="python",
context_id=first.context_id,
)
for item in second.items:
if item.text:
print(item.text)
```
```ts
import { DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
templateName: DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME,
});
const first = await sandbox.codeInterpreter.execute({
code: "prices = [10, 20, 30, 40, 50]",
language: "python",
});
const second = await sandbox.codeInterpreter.execute({
code: "sum(prices) / len(prices)",
language: "python",
contextId: first.contextId,
});
for (const item of second.items) {
if (item.text) console.log(item.text);
}
await client.close();
```
### Request fields [#request-fields]
| Field | Type | Required | Default | Description |
| ------------ | ------- | -------- | -------------- | ----------------------------------- |
| `code` | string | Yes | | Source code to execute. |
| `language` | string | No | `python` | Any supported alias. |
| `context_id` | string | No | auto-generated | Reuse an existing session. |
| `timeout_ms` | integer | No | `30000` | Max execution time in milliseconds. |
## Stream execution [#stream-execution]
Execute code and receive output line-by-line as Server-Sent Events. Use this for long-running scripts or anything where you want to show progress to the user before the process exits.
```python
from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)
for event in sandbox.code_interpreter.execute_stream(
code="""import time
for i in range(5):
print(f'Step {i}')
time.sleep(1)""",
language="python",
timeout_ms=60000,
):
if event.type == "stdout":
print(event.data)
elif event.type == "exit":
print(f"Done (exit code {event.code})")
```
```ts
import { DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
templateName: DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME,
});
for await (const event of sandbox.codeInterpreter.executeStream({
code:
"import time\n" +
"for i in range(5):\n" +
" print(f'Step {i}')\n" +
" time.sleep(1)",
language: "python",
timeoutMs: 60000,
})) {
if (event.type === "stdout") console.log(event.data);
if (event.type === "exit") console.log("Done (exit code " + event.code + ")");
}
await client.close();
```
### Event types [#event-types]
Each `data:` line in the SSE stream is a JSON object:
| Type | Fields | Meaning |
| -------- | ------ | --------------------------------------------- |
| `stdout` | `data` | A line printed to standard output. |
| `stderr` | `data` | A line printed to standard error. |
| `exit` | `code` | Process finished. `code` is `0` on success. |
| `error` | `data` | Interpreter-level failure (e.g. `"timeout"`). |
Example stream for `print("hello")`:
```
data: {"type":"stdout","data":"hello"}
data: {"type":"exit","code":0}
```
## Generating charts [#generating-charts]
Python's matplotlib is pre-installed and patched to automatically capture figures. Call `plt.show()` and the PNG and SVG representations appear in the `items` array - no file I/O required.
```python
from leap0 import DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME)
result = sandbox.code_interpreter.execute(
code="""import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
plt.figure(figsize=(8, 4))
plt.plot(x, np.sin(x), label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
plt.legend()
plt.title('Trigonometric Functions')
plt.show()""",
language="python",
)
for item in result.items:
if item.png:
print(f"PNG image: {len(item.png)} base64 chars")
if item.svg:
print(f"SVG image: {len(item.svg)} chars")
```
```ts
import { DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
templateName: DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME,
});
const result = await sandbox.codeInterpreter.execute({
code:
"import matplotlib.pyplot as plt\n" +
"import numpy as np\n\n" +
"x = np.linspace(0, 2 * np.pi, 100)\n" +
"plt.figure(figsize=(8, 4))\n" +
"plt.plot(x, np.sin(x), label='sin(x)')\n" +
"plt.plot(x, np.cos(x), label='cos(x)')\n" +
"plt.legend()\n" +
"plt.title('Trigonometric Functions')\n" +
"plt.show()",
language: "python",
});
for (const item of result.items) {
if (item.png) console.log("PNG image:", item.png.length, "base64 chars");
if (item.svg) console.log("SVG image:", item.svg.length, "chars");
}
await client.close();
```
## Pre-installed Python packages [#pre-installed-python-packages]
The Python runtime ships with these packages ready to import:
| Category | Packages |
| -------------------- | -------------------------------------------- |
| Data science | numpy, pandas, scipy, scikit-learn, sympy |
| Visualization | matplotlib, seaborn, plotly, bokeh, kaleido |
| Image processing | pillow, opencv-python, scikit-image, imageio |
| Audio | librosa, soundfile |
| HTTP / Web | requests, aiohttp, beautifulsoup4, urllib3 |
| Data formats | orjson, openpyxl, xlrd, python-docx |
| Scientific computing | numba, xarray |
| NLP | nltk, gensim, spacy, textblob |
| Utilities | pytz, joblib, pytest |
# Computer Use (Desktop) (/desktop)
Computer use endpoints let you programmatically control a full Linux desktop running inside a sandbox.
The runtime is based on Ubuntu 22.04 with an XFCE4 desktop at 1440x900 resolution. Firefox ESR, Google Chrome, and VS Code are pre-installed.
Sandbox template requirement
Computer Use requires a sandbox created with the `system/desktop:v0.1.0` template. Sandboxes created with other templates do not include the desktop environment or VNC support unless you install the required packages. See Sandboxes for how to create one.
For a full endpoint reference, see the Computer Use (Desktop) API.
## Desktop access [#desktop-access]
To open the desktop in a browser, see VNC Access.
## Display info [#display-info]
Query the current display name and resolution. Useful for calculating coordinates before sending mouse or screenshot commands.
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
print(sandbox.desktop.display_info())
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
console.log(await sandbox.desktop.displayInfo());
await client.close();
```
## Resize screen [#resize-screen]
Change the virtual display resolution. Width must be between 320 and 7680, height between 320 and 4320.
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
print(sandbox.desktop.resize_screen(width=1280, height=800))
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
console.log(await sandbox.desktop.resizeScreen({ width: 1280, height: 800 }));
await client.close();
```
## List windows [#list-windows]
Inspect all open windows on the desktop. Each window includes its position, size, class, title, and whether it is focused.
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
for window in sandbox.desktop.windows():
print(f"{window.title} ({window.width}x{window.height}) focused={window.focused}")
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
const windows = await sandbox.desktop.windows();
windows.forEach((window) =>
console.log(window.title, window.width + "x" + window.height, "focused=" + window.focused),
);
await client.close();
```
## Screenshots [#screenshots]
### Full screen [#full-screen]
Capture the entire screen. Supports `png`, `jpg`, or `jpeg` format via the `format` query parameter. JPEG quality can be set with `quality` (1--100).
```python
from pathlib import Path
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
screenshot = sandbox.desktop.screenshot(image_format="png")
Path("screen.png").write_bytes(screenshot)
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
const bytes = await sandbox.desktop.screenshot({ format: "png" });
console.log("screenshot bytes", bytes.byteLength);
await client.close();
```
### Region [#region]
Capture a specific region of the screen.
```python
from pathlib import Path
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
region = sandbox.desktop.screenshot_region(
x=0,
y=0,
width=800,
height=600,
image_format="jpg",
quality=85,
)
Path("region.jpg").write_bytes(region)
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
const bytes = await sandbox.desktop.screenshotRegion({
x: 0,
y: 0,
width: 800,
height: 600,
format: "jpg",
quality: 85,
});
console.log("region bytes", bytes.byteLength);
await client.close();
```
## Mouse [#mouse]
### Get pointer position [#get-pointer-position]
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
print(sandbox.desktop.pointer_position())
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
console.log(await sandbox.desktop.pointerPosition());
await client.close();
```
### Move pointer [#move-pointer]
Move the cursor to absolute coordinates. Returns the new pointer position.
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
print(sandbox.desktop.move_pointer(x=320, y=240))
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
console.log(await sandbox.desktop.movePointer(320, 240));
await client.close();
```
### Click [#click]
Click at the current pointer position or at optional `x`, `y` coordinates. The `button` field maps to X11 buttons: `1` (left, default), `2` (middle), `3` (right). Returns the pointer position after the click.
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
sandbox.desktop.click(x=320, y=240, button=1)
sandbox.desktop.click(button=3)
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
await sandbox.desktop.click({ x: 320, y: 240, button: 1 });
await sandbox.desktop.click({ button: 3 });
await client.close();
```
### Drag [#drag]
Drag from one coordinate to another. Uses button `1` (left) by default.
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
print(
sandbox.desktop.drag(
from_x=100,
from_y=200,
to_x=400,
to_y=200,
)
)
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
console.log(
await sandbox.desktop.drag({
fromX: 100,
fromY: 200,
toX: 400,
toY: 200,
}),
);
await client.close();
```
### Scroll [#scroll]
Scroll at the current pointer position. Direction must be `up`, `down`, `left`, or `right`. The `amount` field controls how many scroll steps to perform (1--100, defaults to 1).
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
sandbox.desktop.scroll(direction="down", amount=3)
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
await sandbox.desktop.scroll({ direction: "down", amount: 3 });
await client.close();
```
## Keyboard [#keyboard]
### Type text [#type-text]
Type a string of text as if entered from the keyboard. Supports up to 50,000 characters.
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
sandbox.desktop.type_text(text="hello from Leap0")
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
await sandbox.desktop.typeText("hello from Leap0");
await client.close();
```
### Press key [#press-key]
Press a single key by its X11 keysym name (e.g. `Return`, `Escape`, `Tab`, `BackSpace`, `space`).
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
sandbox.desktop.press_key(key="Return")
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
await sandbox.desktop.pressKey("Return");
await client.close();
```
### Hotkey [#hotkey]
Press a multi-key shortcut. Pass an array of keys that will be joined with `+` and sent as a single xdotool key combination (e.g. `["ctrl", "l"]` becomes `ctrl+l`). Accepts 1--10 keys.
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
sandbox.desktop.hotkey(keys=["ctrl", "l"])
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
await sandbox.desktop.hotkey(["ctrl", "l"]);
await client.close();
```
## Recordings [#recordings]
Screen recordings are captured as MP4 files (H.264/libx264, yuv420p) using ffmpeg at 12 fps. Files are saved inside the sandbox at `~/.cache/leap0-recordings` by default (configurable via the `LEAP0_RECORDINGS_DIR` environment variable). Only one recording can be active at a time.
### Start recording [#start-recording]
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
print(sandbox.desktop.start_recording())
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
console.log(await sandbox.desktop.startRecording());
await client.close();
```
### Stop recording [#stop-recording]
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
print(sandbox.desktop.stop_recording())
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
console.log(await sandbox.desktop.stopRecording());
await client.close();
```
### Recording status [#recording-status]
Get the state of the current or most recent recording.
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
print(sandbox.desktop.recording_status())
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
console.log(await sandbox.desktop.recordingStatus());
await client.close();
```
### List recordings [#list-recordings]
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
for recording in sandbox.desktop.recordings():
print(f"{recording.id}: {recording.size_bytes} bytes")
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
const recordings = await sandbox.desktop.recordings();
recordings.forEach((recording) => console.log(recording.id, recording.sizeBytes + " bytes"));
await client.close();
```
### Get recording [#get-recording]
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
print(sandbox.desktop.get_recording(""))
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
console.log(await sandbox.desktop.getRecording(""));
await client.close();
```
### Download recording [#download-recording]
Returns the MP4 file as a binary download.
```python
from pathlib import Path
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
recording = sandbox.desktop.download_recording("")
Path("recording.mp4").write_bytes(recording)
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
const bytes = await sandbox.desktop.downloadRecording("");
console.log("recording bytes", bytes.byteLength);
await client.close();
```
### Delete recording [#delete-recording]
Delete a saved recording. Active recordings cannot be deleted. Stop them first. Returns `204 No Content` on success.
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
sandbox.desktop.delete_recording("")
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
await sandbox.desktop.deleteRecording("");
await client.close();
```
## Process management [#process-management]
The template runs five processes: `xvfb` (virtual framebuffer), `xfce4` (desktop session), `x11vnc` (VNC server), `novnc` (web-based VNC client via websockify), and `control` (the HTTP API server). The four managed processes (`xvfb`, `xfce4`, `x11vnc`, `novnc`) can be inspected and restarted through the endpoints below.
### Overall status [#overall-status]
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
print(sandbox.desktop.process_status())
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
console.log(await sandbox.desktop.processStatus());
await client.close();
```
### Status stream (SSE) [#status-stream-sse]
Subscribe to a live Server-Sent Events stream of process status. The server sends an event immediately on connect, whenever a process status changes (e.g. after a restart), and every 2 seconds as a heartbeat. Each event has the same payload as `GET /api/status`. The connection stays open until the client disconnects.
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
for status in sandbox.desktop.status_stream():
print(status)
break
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
for await (const status of sandbox.desktop.statusStream()) {
console.log(status);
break;
}
await client.close();
```
### Per-process endpoints [#per-process-endpoints]
Inspect or restart individual processes. Replace `{name}` with `xvfb`, `xfce4`, `x11vnc`, or `novnc`.
```python
from leap0 import DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(template_name=DEFAULT_DESKTOP_TEMPLATE_NAME)
print(sandbox.desktop.get_process("x11vnc"))
print(sandbox.desktop.restart_process("xfce4"))
print(sandbox.desktop.process_logs("novnc"))
```
```ts
import { DEFAULT_DESKTOP_TEMPLATE_NAME, Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({ templateName: DEFAULT_DESKTOP_TEMPLATE_NAME });
console.log(await sandbox.desktop.getProcess("x11vnc"));
console.log(await sandbox.desktop.restartProcess("xfce4"));
console.log(await sandbox.desktop.processLogs("novnc"));
await client.close();
```
```
```
# Filesystem (/filesystem)
Filesystem endpoints let you list, read, write, move, copy, delete, and search files inside a running sandbox. File content is transferred as raw binary bytes.
## List files [#list-files]
List directory entries.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.filesystem.ls(
path="/workspace",
recursive=False,
exclude=["node_modules", ".git"],
)
print(len(result.items))
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.filesystem.ls("/workspace", {
recursive: false,
exclude: ["node_modules", ".git"],
});
console.log(result.items.length);
await client.close();
```
## Stat path [#stat-path]
Get metadata for a single path.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
info = sandbox.filesystem.stat(path="/workspace/main.py")
print(info.size)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const info = await sandbox.filesystem.stat("/workspace/main.py");
console.log(info.size);
await client.close();
```
## Make directory [#make-directory]
Create a directory. Set `recursive` to create parent directories.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.filesystem.mkdir(
path="/workspace/src",
recursive=True,
permissions="755",
)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
await sandbox.filesystem.mkdir("/workspace/src", {
recursive: true,
permissions: "755",
});
await client.close();
```
## Write file [#write-file]
Write raw binary content to a single path. The file path is passed as a query parameter and the request body is the raw file bytes.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.filesystem.write_bytes(
path="/workspace/hello.txt",
content=b"Hello, world!",
permissions="644",
)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
await sandbox.filesystem.writeFile("/workspace/hello.txt", "Hello, world!", { permissions: "644" });
await client.close();
```
## Write multiple files [#write-multiple-files]
Write multiple files in a single request using multipart/form-data. Each part's name is the file path and the body is the raw file bytes.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.filesystem.write_files_bytes(
files={
"/workspace/a.txt": b"a",
"/workspace/b.txt": b"b",
}
)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
await sandbox.filesystem.writeFiles({
"/workspace/a.txt": "a",
"/workspace/b.txt": "b",
});
await client.close();
```
## Read file [#read-file]
Read a single file. The response body contains the raw file bytes with content type `application/octet-stream`.
Use `head` to read only the first N lines or `tail` to read only the last N lines. These options are mutually exclusive.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
print(sandbox.filesystem.read_bytes(path="/workspace/main.py"))
print(sandbox.filesystem.read_bytes(path="/workspace/main.py", head=20))
print(sandbox.filesystem.read_bytes(path="/workspace/main.py", tail=10))
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
console.log(await sandbox.filesystem.readFile("/workspace/main.py"));
console.log(await sandbox.filesystem.readFile("/workspace/main.py", { head: 20 }));
console.log(await sandbox.filesystem.readFile("/workspace/main.py", { tail: 10 }));
await client.close();
```
## Read multiple files [#read-multiple-files]
Read multiple files. The response is `multipart/form-data` where each part's name is the file path and the body is the raw file bytes.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
files = sandbox.filesystem.read_files_bytes(
paths=["/workspace/a.txt", "/workspace/b.txt"],
)
for path, content in files.items():
print(path, content)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const files = await sandbox.filesystem.readFiles(["/workspace/a.txt", "/workspace/b.txt"]);
for (const [path, content] of Object.entries(files)) {
console.log(path, content);
}
await client.close();
```
## Delete path [#delete-path]
Delete a file or directory. Set `recursive` for directories with contents.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.filesystem.delete(path="/workspace/old", recursive=True)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
await sandbox.filesystem.delete("/workspace/old", true);
await client.close();
```
## Set permissions [#set-permissions]
Set file mode and optionally change owner and group.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.filesystem.set_permissions(
path="/workspace/script.sh",
mode="755",
owner="root",
group="root",
)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
await sandbox.filesystem.setPermissions("/workspace/script.sh", {
mode: "755",
owner: "root",
group: "root",
});
await client.close();
```
## Glob [#glob]
Find file paths matching a glob pattern.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
matches = sandbox.filesystem.glob(
path="/workspace",
pattern="*.ts",
exclude=["node_modules"],
)
print(len(matches))
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const matches = await sandbox.filesystem.glob("/workspace", "*.ts", {
exclude: ["node_modules"],
});
console.log(matches.length);
await client.close();
```
## Grep [#grep]
Search for a text pattern across files in a directory.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
matches = sandbox.filesystem.grep(
path="/workspace",
pattern="TODO",
include="*.py",
exclude=["node_modules", ".git"],
)
print(len(matches))
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const matches = await sandbox.filesystem.grep("/workspace", "TODO", {
include: "*.py",
exclude: ["node_modules", ".git"],
});
console.log(matches.length);
await client.close();
```
## Edit file [#edit-file]
Apply one or more find-and-replace edits to a single file. The response includes a unified diff and the total number of replacements made.
```python
from leap0 import FileEdit, Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.filesystem.edit_file(
path="/workspace/main.py",
edits=[
FileEdit(find="hello", replace="hi"),
FileEdit(find="world", replace="earth"),
],
)
print(result.diff)
print(result.replacements)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.filesystem.editFile("/workspace/main.py", [
{ find: "hello", replace: "hi" },
{ find: "world", replace: "earth" },
]);
console.log(result.diff);
console.log(result.replacements);
await client.close();
```
## Edit files [#edit-files]
Replace text across multiple files at once.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
results = sandbox.filesystem.edit_files(
paths=["/workspace/a.py", "/workspace/b.py"],
find="old_name",
replace="new_name",
)
print(len(results))
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const results = await sandbox.filesystem.editFiles({
paths: ["/workspace/a.py", "/workspace/b.py"],
find: "old_name",
replace: "new_name",
});
console.log(results.items?.length ?? 0);
await client.close();
```
## Move path [#move-path]
Move or rename a file or directory.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.filesystem.move(
src_path="/workspace/old.txt",
dst_path="/workspace/new.txt",
overwrite=False,
)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
await sandbox.filesystem.move("/workspace/old.txt", "/workspace/new.txt", false);
await client.close();
```
## Copy [#copy]
Copy a file or directory. Set `recursive` to copy directories with contents.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.filesystem.copy(
src_path="/home/user/file.txt",
dst_path="/home/user/file-copy.txt",
recursive=False,
overwrite=False,
)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
await sandbox.filesystem.copy("/home/user/file.txt", "/home/user/file-copy.txt", {
recursive: false,
overwrite: false,
});
await client.close();
```
## Exists [#exists]
Check whether a path exists in the sandbox.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
print(sandbox.filesystem.exists(path="/workspace/main.py"))
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
console.log(await sandbox.filesystem.exists("/workspace/main.py"));
await client.close();
```
## Tree [#tree]
Get a recursive directory tree. Use `exclude` to skip directories and `max_depth` to limit traversal depth. The response is JSON: `{"items": [{"name": "src", "type": "directory", "children": [...]}, ...]}`.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
tree = sandbox.filesystem.tree(
path="/workspace",
exclude=["node_modules", ".git"],
max_depth=3,
)
print(tree.items)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const tree = await sandbox.filesystem.tree("/workspace", {
exclude: ["node_modules", ".git"],
maxDepth: 3,
});
console.log(tree.items);
await client.close();
```
# Git (/git)
Git endpoints let you clone repositories, inspect diffs and history, manage branches, stage files, commit, push, and pull inside a running sandbox.
## Clone repository [#clone-repository]
Clone a remote repository into the sandbox.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.clone(
url="https://github.com/octocat/Hello-World.git",
path="/workspace/repo",
branch="main",
username="x-access-token",
password="",
)
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.clone({
url: "https://github.com/octocat/Hello-World.git",
path: "/workspace/repo",
branch: "main",
username: "x-access-token",
password: "",
});
console.log(result.output);
await client.close();
```
## Status [#status]
Get the current repository status as raw `git status --porcelain=v2 --branch` output.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.status(path="/workspace/repo")
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.status("/workspace/repo");
console.log(result.output);
await client.close();
```
## List branches [#list-branches]
List branches in the repository as raw `git branch` output.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.branches(path="/workspace/repo", branch_type="all")
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.branches({
path: "/workspace/repo",
branchType: "all",
});
console.log(result.output);
await client.close();
```
## Diff unstaged [#diff-unstaged]
Show working tree changes that are not staged yet.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.diff_unstaged(path="/workspace/repo", context_lines=5)
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.diffUnstaged("/workspace/repo", 5);
console.log(result.output);
await client.close();
```
## Diff staged [#diff-staged]
Show changes that are already staged for the next commit.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.diff_staged(path="/workspace/repo", context_lines=5)
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.diffStaged("/workspace/repo", 5);
console.log(result.output);
await client.close();
```
## Diff target [#diff-target]
Compare the current repository state against a branch, tag, or commit.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.diff(path="/workspace/repo", target="origin/main", context_lines=3)
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.diff("/workspace/repo", "origin/main", 3);
console.log(result.output);
await client.close();
```
## Reset staged changes [#reset-staged-changes]
Unstage all currently staged changes in the repository.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.reset(path="/workspace/repo")
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.reset("/workspace/repo");
console.log(result.output);
await client.close();
```
## Log [#log]
Show commit history with optional limits and date filters.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.log(path="/workspace/repo", max_count=10)
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.log({
path: "/workspace/repo",
maxCount: 10,
});
console.log(result.output);
await client.close();
```
## Show revision [#show-revision]
Show the full output for a commit, branch, or tag revision.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.show(path="/workspace/repo", revision="HEAD~1")
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.show("/workspace/repo", "HEAD~1");
console.log(result.output);
await client.close();
```
## Create branch [#create-branch]
Create a new branch. Set `checkout` to switch to it immediately, and optionally pass `base_branch` to branch from a specific revision.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.create_branch(
path="/workspace/repo",
name="feature/docs",
checkout=True,
base_branch="main",
)
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.createBranch({
path: "/workspace/repo",
name: "feature/docs",
checkout: true,
baseBranch: "main",
});
console.log(result.output);
await client.close();
```
## Checkout branch [#checkout-branch]
Switch to an existing branch.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.checkout_branch(path="/workspace/repo", branch="main")
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.checkoutBranch({
path: "/workspace/repo",
branch: "main",
});
console.log(result.output);
await client.close();
```
## Delete branch [#delete-branch]
Delete a branch. Set `force` to delete even if unmerged.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.delete_branch(path="/workspace/repo", name="feature/docs", force=True)
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.deleteBranch("/workspace/repo", "feature/docs", true);
console.log(result.output);
await client.close();
```
## Add files [#add-files]
Stage files for the next commit.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.add(path="/workspace/repo", files=["README.md"])
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.add("/workspace/repo", ["README.md"]);
console.log(result.output);
await client.close();
```
## Commit [#commit]
Create a commit from staged changes.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
commit = sandbox.git.commit(
path="/workspace/repo",
message="docs: update filesystem guide",
author="Leap0 Bot",
email="bot@example.com",
)
print(commit.sha)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const commit = await sandbox.git.commit({
path: "/workspace/repo",
message: "docs: update filesystem guide",
author: "Leap0 Bot",
email: "bot@example.com",
});
console.log(commit.sha);
await client.close();
```
## Push [#push]
Push commits to a remote.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.push(
path="/workspace/repo",
remote="origin",
branch="main",
set_upstream=True,
)
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.push({
path: "/workspace/repo",
remote: "origin",
branch: "main",
setUpstream: true,
});
console.log(result.output);
await client.close();
```
## Pull [#pull]
Pull commits from a remote. Set `rebase` to rebase instead of merge. Set `set_upstream` to set upstream tracking for the branch.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.git.pull(
path="/workspace/repo",
remote="origin",
branch="main",
rebase=True,
set_upstream=True,
)
print(result.output)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const result = await sandbox.git.pull({
path: "/workspace/repo",
remote: "origin",
branch: "main",
rebase: true,
setUpstream: true,
});
console.log(result.output);
await client.close();
```
# Language Server Protocol (/lsp)
LSP endpoints let you start language servers inside a sandbox and interact with them for code completions, document symbols, and document lifecycle notifications. Supported languages: **Python** (pyright) and **TypeScript/JavaScript** (typescript-language-server).
## Start a language server [#start-a-language-server]
Start the LSP server for a language and project. This spawns the server process and sends the LSP `initialize` handshake automatically.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
print(
sandbox.lsp.start(
language_id="python",
path_to_project="/home/user/project",
)
)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
console.log(
await sandbox.lsp.start({
languageId: "python",
pathToProject: "/home/user/project",
}),
);
await client.close();
```
## Open a document [#open-a-document]
Notify the language server that a document was opened. This must be called before requesting completions or symbols.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.lsp.did_open_path(
language_id="python",
path_to_project="/home/user/project",
path="/home/user/project/main.py",
text="import os\nos.path.",
version=1,
)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
await sandbox.lsp.didOpenPath({
languageId: "python",
pathToProject: "/home/user/project",
path: "/home/user/project/main.py",
text: "import os\nos.path.",
version: 1,
});
await client.close();
```
## Get completions [#get-completions]
Request code completions at a cursor position.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
response = sandbox.lsp.completions_path(
language_id="python",
path_to_project="/home/user/project",
path="/home/user/project/main.py",
line=1,
character=8,
)
items = response.result or []
for item in items[:5]:
print(item["label"])
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const response = await sandbox.lsp.completionsPath({
languageId: "python",
pathToProject: "/home/user/project",
path: "/home/user/project/main.py",
line: 1,
character: 8,
});
const items = response.result ?? [];
items.slice(0, 5).forEach((item) => console.log(item.label));
await client.close();
```
## Get document symbols [#get-document-symbols]
Request all symbols (functions, classes, variables) in a document.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
response = sandbox.lsp.document_symbols_path(
language_id="python",
path_to_project="/home/user/project",
path="/home/user/project/main.py",
)
for symbol in response.result or []:
print(symbol["name"], symbol["kind"])
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const response = await sandbox.lsp.documentSymbolsPath({
languageId: "python",
pathToProject: "/home/user/project",
path: "/home/user/project/main.py",
});
for (const symbol of response.result ?? []) {
console.log(symbol.name, symbol.kind);
}
await client.close();
```
## Close a document [#close-a-document]
Notify the language server that a document was closed.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.lsp.did_close_path(
language_id="python",
path_to_project="/home/user/project",
path="/home/user/project/main.py",
)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
await sandbox.lsp.didClosePath({
languageId: "python",
pathToProject: "/home/user/project",
path: "/home/user/project/main.py",
});
await client.close();
```
## Stop the language server [#stop-the-language-server]
Send `shutdown` and `exit` to the language server and terminate the process.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.lsp.stop(
language_id="python",
path_to_project="/home/user/project",
)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
await sandbox.lsp.stop({
languageId: "python",
pathToProject: "/home/user/project",
});
await client.close();
```
# MCP Server (/mcp)
[`@leap0/mcp`](https://www.npmjs.com/package/@leap0/mcp) is a [Model Context Protocol](https://modelcontextprotocol.io) server for Leap0. It exposes sandbox lifecycle, filesystem, and process tools over **stdio** so coding agents can create and manage Leap0 sandboxes from their host environment.
## Install [#install]
```bash
npm install -g @leap0/mcp
```
```bash
pnpm add -g @leap0/mcp
```
```bash
yarn global add @leap0/mcp
```
```bash
bun add -g @leap0/mcp
```
Or run without a global install:
```bash
npx @leap0/mcp --help
```
```bash
pnpm dlx @leap0/mcp --help
```
```bash
yarn dlx @leap0/mcp --help
```
```bash
bunx @leap0/mcp --help
```
## Agent configuration [#agent-configuration]
Generate a JSON snippet you can merge into your client's MCP settings:
```bash
leap0-mcp --print-config
```
This prints a `mcpServers` block using your current `node` binary and the resolved path to the package's `cli.js`. Placeholders use `${VAR}` so you can rely on the shell or replace them with real values.
1. Copy the JSON into your app's MCP config (e.g. Cursor **Settings → MCP**).
2. Ensure `LEAP0_API_KEY` is set in the server `env` (or remove the placeholder and set it in your user environment before starting the agent).
3. Remove or set optional entries (`LEAP0_BASE_URL`, `LEAP0_SANDBOX_DOMAIN`) if you use non-default endpoints.
4. Restart the editor or MCP host.
On **Windows**, the printed config includes `APPDATA` in `env` so tools resolve user paths correctly.
## CLI [#cli]
| Flag | Meaning |
| ------------------ | ------------------------------------------------------- |
| *(none)* | Start the MCP server on stdio (JSON-RPC on stdout only) |
| `--print-config` | Print MCP JSON config to stdout |
| `--version` / `-V` | Print package version |
| `--help` / `-h` | Print usage |
Diagnostics and errors go to **stderr**; MCP traffic uses **stdout**.
## Troubleshooting [#troubleshooting]
* **`Failed to create Leap0 client` / API key errors** — Set `LEAP0_API_KEY` in the MCP `env` or in the process environment before launching `leap0-mcp`.
* **401 / 403 from tools** — Key invalid or missing; confirm the key in the Leap0 dashboard and that the same env is visible to the MCP process.
* **Connection / timeout errors** — Check `LEAP0_BASE_URL`, firewall, and that the machine running MCP can reach the API.
* **Empty or wrong PATH in `--print-config`** — The printed `PATH` is taken from the shell that ran the command; adjust in the MCP config if `node` or other binaries are not found when the editor spawns the server.
# Process (/process)
Process endpoints let you execute one-shot commands inside a running sandbox.
## Execute a command [#execute-a-command]
Run a shell command and wait for the result. The command runs inside `/bin/sh -c`.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
result = sandbox.process.execute(
command="echo Hello from Leap0",
cwd="/home/user",
timeout=30,
)
print(result.exit_code)
print(result.stdout)
print(result.stderr)
```
```js
import { Leap0Client } from "leap0"
const client = new Leap0Client()
const sandbox = await client.sandboxes.create()
const result = await sandbox.process.execute({
command: "echo Hello from Leap0",
cwd: "/home/user",
timeout: 30,
})
console.log(result.exitCode) // 0
console.log(result.stdout) // Hello from Leap0
console.log(result.stderr) // ""
await client.close()
```
# Pseudo Terminal (PTY) (/pty)
PTY endpoints let you create interactive terminal sessions with a persistent shell process. Connect via WebSocket for real-time bidirectional I/O, similar to SSH or a browser-based terminal.
## Create a PTY session [#create-a-pty-session]
Create a terminal session with a shell process.
By default, the shell starts when the PTY session is created. If you set `lazy_start: true`, Leap0 creates the PTY session first and waits to start the shell until the first WebSocket connection is opened for that session.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
session = sandbox.pty.create(
session_id="my-terminal",
cols=120,
rows=40,
cwd="/home/user",
envs={"TERM": "xterm-256color"},
)
print(session.id, session.cwd, session.cols, session.rows)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const session = await sandbox.pty.create({
id: "my-terminal",
cols: 120,
rows: 40,
cwd: "/home/user",
envs: { TERM: "xterm-256color" },
});
console.log(session.id, session.cwd, session.cols, session.rows);
await client.close();
```
### Lazy start example [#lazy-start-example]
Use `lazy_start: true` when you want to create the PTY session now but wait to start the shell until the first WebSocket connection.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
session = sandbox.pty.create(
session_id="lazy-terminal",
cwd="/workspace",
cols=120,
rows=40,
lazy_start=True,
)
print(session.id, session.lazy_start)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const session = await sandbox.pty.create({
id: "lazy-terminal",
cwd: "/workspace",
cols: 120,
rows: 40,
lazyStart: true,
});
console.log(session.id, session.lazyStart);
await client.close();
```
## Connect via WebSocket [#connect-via-websocket]
Open a WebSocket connection for interactive terminal I/O. All messages are binary frames containing raw terminal bytes.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
session = sandbox.pty.get("my-terminal")
connection = sandbox.pty.connect(session.id)
try:
connection.send("ls -la\n")
print(connection.recv().decode("utf-8", errors="replace"), end="")
finally:
connection.close()
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const pty = sandbox.pty.connect("my-terminal");
pty.send("ls -la\n");
const output = await pty.recv();
console.log(output);
pty.close();
await client.close();
```
## Resize terminal [#resize-terminal]
Change the terminal dimensions while connected.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
session = sandbox.pty.resize("my-terminal", cols=200, rows=50)
print(session.cols, session.rows)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const session = await sandbox.pty.resize("my-terminal", 200, 50);
console.log(session.cols, session.rows);
await client.close();
```
## List PTY sessions [#list-pty-sessions]
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
for session in sandbox.pty.list():
print(session.id, session.active)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const sessions = await sandbox.pty.list();
sessions.forEach((session) => console.log(session.id, session.active));
await client.close();
```
## Delete a PTY session [#delete-a-pty-session]
Kill the shell process and remove the session.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.pty.delete("my-terminal")
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
await sandbox.pty.delete("my-terminal");
await client.close();
```
# SSH (/ssh)
SSH endpoints let you create and manage SSH access credentials for a sandbox. Generate credentials, validate them, regenerate them, or revoke access entirely.
## Create SSH access [#create-ssh-access]
Generate SSH credentials for a sandbox. Returns an `id` to use as the SSH username, a `password`, and the SSH command to connect.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
access = sandbox.ssh.create_access()
print("SSH username:", access.id)
print(access.ssh_command)
print("Password:", access.password)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const access = await client.ssh.createAccess(sandbox);
console.log("SSH username:", access.id);
console.log(access.sshCommand);
console.log("Password:", access.password);
await client.close();
```
## Validate SSH access [#validate-ssh-access]
Check whether a specific SSH access credential is still valid and not expired.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
access = sandbox.ssh.create_access()
validation = sandbox.ssh.validate_access(
id=access.id,
password=access.password,
)
print("Valid:", validation.valid)
print("Sandbox:", validation.sandbox_id)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const access = await client.ssh.createAccess(sandbox);
const validation = await client.ssh.validateAccess(sandbox, {
id: access.id,
password: access.password,
});
console.log("Valid:", validation.valid);
console.log("Sandbox:", validation.sandboxId);
await client.close();
```
## Regenerate SSH access [#regenerate-ssh-access]
Invalidate a specific credential and generate a new one. The expiry is also reset.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
access = sandbox.ssh.create_access()
regenerated = sandbox.ssh.regenerate_access(id=access.id)
print("New password:", regenerated.password)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const access = await client.ssh.createAccess(sandbox);
const regenerated = await client.ssh.regenerateAccess(sandbox, { id: access.id });
console.log("New password:", regenerated.password);
await client.close();
```
## Delete SSH access [#delete-ssh-access]
Revoke a specific SSH access credential. The credential is invalidated immediately.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
access = sandbox.ssh.create_access()
sandbox.ssh.delete_access(id=access.id)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const access = await client.ssh.createAccess(sandbox);
await client.ssh.deleteAccess(sandbox, { id: access.id });
await client.close();
```
# VNC Access (/vnc)
VNC access gives you a full graphical Linux desktop inside a sandbox, streamed directly to your browser through [noVNC](https://novnc.com). No local VNC client or browser plugin is needed.
Sandbox template requirement
VNC requires a sandbox created with the `system/desktop:v0.1.0` template. See Sandboxes for how to create one.
## Open the desktop [#open-the-desktop]
Open the sandbox invoke URL in any browser. The noVNC client loads and connects to the XFCE4 desktop automatically.
{`https://.${env.LEAP0_SANDBOX_DOMAIN}/`}
Mouse and keyboard input works the same as a native desktop.
## What is noVNC [#what-is-novnc]
[noVNC](https://novnc.com) is an open-source VNC client written in JavaScript. It uses WebSockets and the HTML5 Canvas API to render a remote desktop directly in a browser tab. Input events (mouse clicks, keystrokes, scrolling) travel back over the same WebSocket connection, giving you interactive control without installing anything locally.
See Computer Use (Desktop) for the full desktop architecture, pre-installed software, and programmatic automation API.
# Presigned URLs (/presigned-urls)
A presigned URL is a temporary public hostname that routes traffic to a specific port inside a sandbox.
The URL format is: {`https://.${env.LEAP0_PRESIGNED_DOMAIN}`}
The token is only returned once when the URL is created. Leap0 stores only a SHA-256 hash of that token server-side.
## Create a presigned URL [#create-a-presigned-url]
Create a presigned URL with:
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
presigned_url = sandbox.create_presigned_url(port=8080, expires_in=900)
print(presigned_url.id)
print(presigned_url.url)
# Treat the token as a secret. Do not log or commit it.
token = presigned_url.token
client.close()
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const presignedUrl = await sandbox.createPresignedUrl(8080, 900);
console.log(presignedUrl.id);
console.log(presignedUrl.url);
// Treat the token as a secret. Do not log or commit it.
const token = presignedUrl.token;
await client.close();
```
## Delete a presigned URL [#delete-a-presigned-url]
Revoke a URL with:
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
presigned_url = sandbox.create_presigned_url(port=8080)
sandbox.delete_presigned_url(presigned_url.id)
client.close()
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
const presignedUrl = await sandbox.createPresignedUrl(8080);
await sandbox.deletePresignedUrl(presignedUrl.id);
await client.close();
```
## Notes [#notes]
* Presigned URLs are public and do not require an API key.
* Treat presigned URLs and their one-time tokens as secrets. Avoid logging or committing them.
* Each URL maps to one sandbox port.
* Expired URLs stop resolving automatically.
* If the sandbox is paused, Leap0 resumes it before proxying the request.
# Quickstart (/)
## What is Leap0? [#what-is-leap0]
Leap0 is secure infrastructure for running AI-generated code. You start a sandbox from a template, run shell commands, call your running app over HTTP/SSE/WebSocket, interact with files and git, and delete the sandbox when done.
## Create an account [#create-an-account]
Open the Leap0 app, create an account (or sign in).
## Create an API key [#create-an-api-key]
Generate an API key in the dashboard to authenticate requests to Leap0, then save it securely because it is shown only once and send it in the `authorization` header.
## Install the SDK [#install-the-sdk]
```text
pip install leap0
```
```text
npm install leap0
```
## Code example [#code-example]
Create a sandbox, run a shell command with process.execute, then delete the sandbox. Set `LEAP0_API_KEY` in your environment so the client can authenticate.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
try:
result = sandbox.process.execute(
command="echo Hello from Leap0",
cwd="/home/user",
timeout=30,
)
print(result.exit_code)
print(result.stdout)
print(result.stderr)
finally:
sandbox.delete()
```
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
let sandbox;
try {
sandbox = await client.sandboxes.create();
const result = await sandbox.process.execute({
command: "echo Hello from Leap0",
cwd: "/home/user",
timeout: 30,
});
console.log(result.exitCode);
console.log(result.stdout);
console.log(result.stderr);
} finally {
if (sandbox) await sandbox.delete();
await client.close();
}
```
## Full lifecycle example [#full-lifecycle-example]
When your template runs an HTTP app, you can invoke it, work with git and files, then delete the sandbox.
```python
import os
import httpx
from leap0 import Leap0Client
API_KEY = os.environ["LEAP0_API_KEY"]
client = Leap0Client()
sandbox = client.sandboxes.create(
vcpu=2,
memory=2048,
timeout=30,
)
try:
response = httpx.get(
sandbox.invoke_url("/"),
headers={"authorization": API_KEY},
)
response.raise_for_status()
print(response.text)
cloned = sandbox.git.clone(
url="https://github.com/octocat/Hello-World.git",
path="/workspace/repo",
branch="main",
)
print(cloned.output)
git_status = sandbox.git.status(path="/workspace/repo")
print(git_status.output)
files = sandbox.filesystem.ls(path="/workspace", recursive=False)
print(len(files.items))
finally:
sandbox.delete()
```
```js
import { Leap0Client } from "leap0";
const apiKey = process.env.LEAP0_API_KEY ?? "";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
templateName: "",
vcpu: 2,
memory: 2048,
timeout: 30,
});
try {
// 1. Invoke the sandbox
const invoke = await fetch(sandbox.invokeUrl("/"), {
headers: { authorization: apiKey },
});
console.log(await invoke.text());
// 2. Clone a repository
const cloned = await sandbox.git.clone({
url: "https://github.com/octocat/Hello-World.git",
path: "/workspace/repo",
branch: "main",
});
console.log(cloned.output);
// 3. Check git status
const gitStatus = await sandbox.git.status("/workspace/repo");
console.log(gitStatus.output);
// 4. List files in the sandbox
const files = await sandbox.filesystem.ls("/workspace");
console.log(files.items.length);
} finally {
await sandbox.delete();
await client.close();
}
```
# Sandboxes (/sandboxes)
A sandbox is an isolated runtime environment.
Create one from a template, invoke it over HTTP or WebSocket, then delete it when you are done.
## Why use sandboxes? [#why-use-sandboxes]
Sandboxes exist for security. They let agents execute arbitrary code, access files, and use the network without compromising your credentials, local files, or host system. This isolation is essential when agents run autonomously.
## Isolation and security [#isolation-and-security]
Every sandbox runs in its own Firecracker microVM:
* Firecracker is launched with the Jailer for additional process and filesystem isolation.
* Sandboxes run on the Linux 6.1 LTS kernel.
* Each sandbox gets dedicated network boundaries with egress policy enforcement. Control outbound access with `network_policy`.
See Firewall for egress configuration details.
## Lifecycle [#lifecycle]
A sandbox can have several different states. Each state reflects the current status of your sandbox.
* `starting`: The sandbox is booting and preparing its runtime environment before it can accept requests.
* `running`: The sandbox is active and ready to handle HTTP, WebSocket, filesystem, process, and other tool requests.
* `paused`: The sandbox's memory and disk state have been saved, and compute is no longer running. It resumes automatically when it receives a request.
* `unpausing`: The sandbox is being restored from its paused state so it can return to `running`.
* `stopping`: The sandbox is shutting down while preserving disk changes, but not in-memory execution state.
* `stopped`: The sandbox is fully off, but its disk changes are preserved. Call `start` to boot it again.
* `deleting`: The sandbox is being cleaned up and permanently removed.
* `deleted`: The sandbox has been permanently removed and is no longer available.
## Create a sandbox [#create-a-sandbox]
Set `auto_pause` to `true` if you want Leap0 to pause the sandbox when its timeout is reached.
```python
from leap0 import Leap0Client, NetworkPolicyMode
client = Leap0Client()
sandbox = client.sandboxes.create(
vcpu=2,
memory=2048,
timeout=30,
auto_pause=True,
env_vars={
"NODE_ENV": "production",
},
network_policy={
"mode": NetworkPolicyMode.CUSTOM,
"allow_cidrs": ["1.2.3.4/32"],
},
)
print(sandbox.id, sandbox.state)
```
```js
import { Leap0Client, NetworkPolicyMode } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
vcpu: 2,
memory: 2048,
timeout: 30,
autoPause: true,
envVars: {
NODE_ENV: "production",
},
networkPolicy: {
mode: NetworkPolicyMode.CUSTOM,
allowCidrs: ["1.2.3.4/32"],
},
});
console.log(sandbox.id, sandbox.state);
await client.close();
```
## Get a sandbox [#get-a-sandbox]
Returns the sandbox status, resource configuration, and current state.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
print(sandbox.id, sandbox.state, sandbox.vcpu, sandbox.memory)
```
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.get("");
console.log(sandbox.id, sandbox.state, sandbox.vcpu, sandbox.memory);
await client.close();
```
## Invoke a sandbox [#invoke-a-sandbox]
Send any HTTP or WebSocket request directly to the sandbox host. Whatever your app serves inside the sandbox is reachable.
By default, traffic is routed to the port defined by the template image's `PORT` environment variable.
If your app serves on a different port, append `-` to the sandbox subdomain.
Port routing
Only one port can be reached per request. To target a specific port, append `-` to the sandbox subdomain (e.g. `sbx-abc123-3000`). If no port suffix is set, traffic routes to the port from the template's `PORT` environment variable.
Examples:
* Default port from image metadata: {`https://sbx-abc123.${env.LEAP0_SANDBOX_DOMAIN}/health`}
* Explicit port routing: {`https://sbx-abc123-3000.${env.LEAP0_SANDBOX_DOMAIN}/health`}
### HTTP [#http]
```python
import os
import httpx
from leap0 import Leap0Client
API_KEY = os.environ["LEAP0_API_KEY"]
client = Leap0Client()
sandbox = client.sandboxes.create()
response = httpx.get(
sandbox.invoke_url("/"),
headers={"authorization": API_KEY},
)
response.raise_for_status()
print(response.text)
```
```js
import { Leap0Client } from "leap0";
import WebSocket from "ws";
const apiKey = process.env.LEAP0_API_KEY ?? "";
const client = new Leap0Client();
const sandbox = await client.sandboxes.get("");
const res = await fetch(sandbox.invokeUrl("/"), {
headers: { authorization: apiKey },
});
console.log(await res.text());
await client.close();
```
### Server-Sent Events [#server-sent-events]
```python
import os
import httpx
from leap0 import Leap0Client
API_KEY = os.environ["LEAP0_API_KEY"]
client = Leap0Client()
sandbox = client.sandboxes.create()
with httpx.stream(
"GET",
sandbox.invoke_url("/"),
headers={
"authorization": API_KEY,
"Accept": "text/event-stream",
},
) as response:
response.raise_for_status()
for line in response.iter_lines():
if line:
print(line)
```
```js
import { Leap0Client } from "leap0";
const apiKey = process.env.LEAP0_API_KEY ?? "";
const client = new Leap0Client();
const sandbox = await client.sandboxes.get("");
// EventSource does not support custom headers.
// Use fetch + ReadableStream to send an Authorization header.
const res = await fetch(sandbox.invokeUrl("/"), {
headers: {
authorization: apiKey,
Accept: "text/event-stream",
},
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
const lines = buf.split("\n");
buf = lines.pop();
for (const line of lines) {
if (line.startsWith("data: ")) {
console.log(line.slice(6));
}
}
}
await client.close();
```
### WebSocket [#websocket]
```python
import asyncio
import os
import websockets
from leap0 import Leap0Client
API_KEY = os.environ["LEAP0_API_KEY"]
client = Leap0Client()
sandbox = client.sandboxes.create()
async def connect() -> None:
async with websockets.connect(
sandbox.websocket_url("/"),
additional_headers={"authorization": API_KEY},
) as ws:
await ws.send("hello")
response = await ws.recv()
print(response)
asyncio.run(connect())
```
```js
import { Leap0Client } from "leap0";
const apiKey = process.env.LEAP0_API_KEY ?? "";
const client = new Leap0Client();
const sandbox = await client.sandboxes.get("");
const ws = new WebSocket(sandbox.websocketUrl("/"), {
headers: { authorization: apiKey },
});
await new Promise((resolve, reject) => {
ws.on("open", () => ws.send("hello"));
ws.on("message", (data) => {
console.log(data.toString());
ws.close();
});
ws.on("close", resolve);
ws.on("error", reject);
});
await client.close();
```
## Pause a sandbox [#pause-a-sandbox]
Pause a running sandbox. The VM state, memory, and disk are captured and uploaded, the sandbox is marked as `paused`, and the VM is terminated.
The sandbox can later be resumed automatically when it receives a request.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.pause()
print(sandbox.state)
```
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.get("");
await sandbox.pause();
console.log(sandbox.state);
await client.close();
```
## Stop a sandbox [#stop-a-sandbox]
Stop a running sandbox when you want to shut compute down but keep filesystem changes for later. Unlike `pause`, this does not preserve in-memory execution state.
```bash
curl -X POST \
-H "Authorization: Bearer " \
"https://api.leap0.dev/v1/sandbox//stop"
```
The sandbox moves through `stopping` and then `stopped`.
## Start a stopped sandbox [#start-a-stopped-sandbox]
Start a sandbox that is currently `stopped`. Leap0 boots a fresh VM from the original template and reapplies the persisted writable disk state.
```bash
curl -X POST \
-H "Authorization: Bearer " \
"https://api.leap0.dev/v1/sandbox//start"
```
The response now includes the full updated sandbox metadata, so SDKs do not need to issue a follow-up `get` after `start`.
The sandbox returns to `running` when the request completes.
`start` is for `stopped` sandboxes only. You do not need to call it for `paused` sandboxes.
## Delete a sandbox [#delete-a-sandbox]
Running, paused, and stopped sandboxes can all be deleted.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
sandbox.delete()
```
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
await client.sandboxes.delete("");
await client.close();
```
# Snapshots (/snapshots)
Snapshots let you create a point-in-time capture of a running sandbox, including its in-memory execution state and writable disk state.
You can then restore that snapshot into a brand new sandbox that starts from the same checkpoint.
If you only need to shut compute down and later boot the same sandbox with its writable disk changes, use sandbox `stop`/`start` instead. Snapshots are named, reusable checkpoints. Stopped sandboxes are not.
Sandbox state
Snapshots can only be created from a `running` sandbox. The VM is briefly paused during the capture and then resumed automatically unless you set `kill_sandbox_after`.
## Restore behavior [#restore-behavior]
Restoring a snapshot creates a brand new sandbox.
* Compute settings come from the snapshot, not the restore request.
* The snapshot's template is reattached automatically.
* `timeout` can be overridden when restoring.
* `auto_pause` can be enabled when restoring if you want the new sandbox to pause itself at timeout.
* `network_policy` defaults to the snapshot values, but you can override it on restore.
* Restore requests address snapshots by `snapshot_name`.
## Create a snapshot [#create-a-snapshot]
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
snapshot = sandbox.create_snapshot(name="workspace-warm")
print(snapshot.id, snapshot.name)
```
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.get("");
const snapshot = await sandbox.createSnapshot({
name: "workspace-warm",
});
console.log(snapshot.id, snapshot.name);
await client.close();
```
## Snapshot and terminate a sandbox [#snapshot-and-terminate-a-sandbox]
Use this when you want to create a named snapshot and shut the sandbox down immediately after the snapshot is stored.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
snapshot = sandbox.create_snapshot(name="workspace-warm", kill_sandbox_after=True)
print(snapshot.id, snapshot.name)
```
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.get("");
const snapshot = await sandbox.createSnapshot({
name: "workspace-warm",
killSandboxAfter: true,
});
console.log(snapshot.id, snapshot.name);
await client.close();
```
## Restore a snapshot [#restore-a-snapshot]
```python
from leap0 import Leap0Client, NetworkPolicyMode
client = Leap0Client()
sandbox = client.snapshots.restore(
snapshot_name="workspace-warm",
auto_pause=True,
timeout=30,
network_policy={
"mode": NetworkPolicyMode.CUSTOM,
"allow_cidrs": ["1.2.3.4/32"],
},
)
print(sandbox.id, sandbox.state)
```
```js
import { Leap0Client, NetworkPolicyMode } from "leap0";
const client = new Leap0Client();
const sandbox = await client.snapshots.restore({
snapshotName: "workspace-warm",
autoPause: true,
timeout: 30,
networkPolicy: {
mode: NetworkPolicyMode.CUSTOM,
allowCidrs: ["1.2.3.4/32"],
},
});
console.log(sandbox.id, sandbox.state);
await client.close();
```
## Delete a snapshot [#delete-a-snapshot]
When a snapshot is deleted, all stored data for that sandbox (memory state, disk state) is permanently removed.
```python
from leap0 import Leap0Client
client = Leap0Client()
client.snapshots.delete("")
```
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
await client.snapshots.delete("");
await client.close();
```
# Templates (/templates)
A template defines the container image and startup configuration that sandboxes are created from. Create a template once, then use it to spawn any number of sandboxes.
## System templates [#system-templates]
System templates are maintained by Leap0 and available to all accounts. Their names are prefixed with `system/` and cannot be created or modified through the API.
| Template | Description |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `system/debian:bookworm` | Debian 12 (Bookworm) base image for general-purpose Linux sandboxes. |
| `system/code-interpreter:v0.1.0` | Python 3.12 and Bun runtimes with 50+ pre-installed data-science packages. Used with the Code Interpreter agent tool. |
| `system/desktop:v0.1.0` | XFCE desktop sandbox with noVNC access, screenshots, input automation, window inspection, and screen recording. Used with the Computer Use (Desktop) agent tool. |
Use a system template the same way you use your own. Pass its name as `template_name` when creating a sandbox.
## Create a template [#create-a-template]
Provide a name and a container image URI.
```python
from leap0 import Leap0Client
client = Leap0Client()
template = client.templates.create(
name="python-fastapi-hello",
uri="docker.io/library/python:3.12-slim",
)
print(template.id)
```
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const template = await client.templates.create({
name: "python-fastapi-hello",
uri: "docker.io/library/python:3.12-slim",
});
console.log(template.id);
await client.close();
```
## Rename a template [#rename-a-template]
Change the display name of a template.
```python
from leap0 import Leap0Client
client = Leap0Client()
client.templates.rename("", name="python-fastapi-v2")
```
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
await client.templates.rename("", { name: "python-fastapi-v2" });
await client.close();
```
## Delete a template [#delete-a-template]
Permanently remove a template. Existing sandboxes created from the template are not affected.
```python
from leap0 import Leap0Client
client = Leap0Client()
client.templates.delete("")
```
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
await client.templates.delete("");
await client.close();
```
## Private registries [#private-registries]
Templates can pull images from private container registries. Pass a `credentials` object with the authentication details for your registry provider.
```json
{
"name": "my-private-image",
"uri": "registry.example.com/org/app:latest",
"credentials": {
"type": "basic",
"username": "my-user",
"password": "my-password"
}
}
```
```json
{
"name": "my-ecr-image",
"uri": "123456789012.dkr.ecr.us-east-1.amazonaws.com/my-repo:latest",
"credentials": {
"type": "aws",
"aws_access_key_id": "AKIAIOSFODNN7EXAMPLE",
"aws_secret_access_key": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
"aws_region": "us-east-1"
}
}
```
```json
{
"name": "my-gcp-image",
"uri": "us-docker.pkg.dev/my-project/my-repo/my-image:latest",
"credentials": {
"type": "gcp",
"gcp_service_account_json": "{ ... }"
}
}
```
```json
{
"name": "my-azure-image",
"uri": "myregistry.azurecr.io/my-image:latest",
"credentials": {
"type": "azure",
"azure_client_id": "00000000-0000-0000-0000-000000000000",
"azure_client_secret": "my-client-secret",
"azure_tenant_id": "00000000-0000-0000-0000-000000000000"
}
}
```
# Public Preview (/public-preview)
Leap0 is free to use during the public preview period.
During this time:
* Breaking changes may happen as we improve the platform.
* Short periods of downtime may occur.
## Report a bug [#report-a-bug]
Email us at {env.LEAP0_CONTACT_EMAIL} with steps to reproduce and any relevant logs.
# Roadmap (/roadmap)
Roadmap items are subject to change. Features may be added, reordered, or removed based on user feedback.
* CLI
* VPN connections
* eBPF observability
* Managed observability
# Firewall (/firewall)
Control what a sandbox can reach over the network using the `network_policy` field when creating or restoring a sandbox.
When `network_policy` is omitted, all outbound traffic is allowed.
## Policy modes [#policy-modes]
| Mode | Behavior |
| ----------- | --------------------------------------------------------------------------------- |
| `allow-all` | All outbound traffic is permitted (default). |
| `deny-all` | All outbound traffic is blocked. |
| `custom` | Traffic is filtered by `allow_domains`, `allow_cidrs`, and optional `transforms`. |
## Allow all traffic (default) [#allow-all-traffic-default]
Omit `network_policy` or set it explicitly:
```python
from leap0 import Leap0Client, NetworkPolicyMode
client = Leap0Client()
sandbox = client.sandboxes.create(
vcpu=2,
memory=2048,
network_policy={"mode": NetworkPolicyMode.ALLOW_ALL},
)
print(sandbox.id, sandbox.network_policy)
```
```ts
import { Leap0Client, NetworkPolicyMode } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
vcpu: 2,
memory: 2048,
networkPolicy: { mode: NetworkPolicyMode.ALLOW_ALL },
});
console.log(sandbox.id, sandbox.networkPolicy);
await client.close();
```
## Block all outbound traffic [#block-all-outbound-traffic]
Completely isolate the sandbox from the network.
```python
from leap0 import Leap0Client, NetworkPolicyMode
client = Leap0Client()
sandbox = client.sandboxes.create(
vcpu=2,
memory=2048,
network_policy={"mode": NetworkPolicyMode.DENY_ALL},
)
print(sandbox.id, sandbox.network_policy)
```
```ts
import { Leap0Client, NetworkPolicyMode } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
vcpu: 2,
memory: 2048,
networkPolicy: { mode: NetworkPolicyMode.DENY_ALL },
});
console.log(sandbox.id, sandbox.networkPolicy);
await client.close();
```
## Custom policy with domains and CIDRs [#custom-policy-with-domains-and-cidrs]
Allow specific domains and IP ranges while blocking everything else.
```python
from leap0 import Leap0Client, NetworkPolicyMode
client = Leap0Client()
sandbox = client.sandboxes.create(
vcpu=2,
memory=2048,
network_policy={
"mode": NetworkPolicyMode.CUSTOM,
"allow_domains": ["api.openai.com", "pypi.org"],
"allow_cidrs": ["10.0.0.0/24"],
},
)
print(sandbox.id, sandbox.network_policy)
```
```ts
import { Leap0Client, NetworkPolicyMode } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
vcpu: 2,
memory: 2048,
networkPolicy: {
mode: NetworkPolicyMode.CUSTOM,
allowDomains: ["api.openai.com", "pypi.org"],
allowCidrs: ["10.0.0.0/24"],
},
});
console.log(sandbox.id, sandbox.networkPolicy);
await client.close();
```
## Transforms [#transforms]
Transforms let you inject or strip headers on a per-domain basis. This is useful for credential brokering: the sandbox code makes requests without API keys, and the firewall injects the credentials on the host side. The secrets never enter the sandbox.
Domains with transform rules are implicitly allowed. You don't need to add them to `allow_domains` separately.
```python
from leap0 import Leap0Client, NetworkPolicyMode
client = Leap0Client()
sandbox = client.sandboxes.create(
vcpu=2,
memory=2048,
network_policy={
"mode": NetworkPolicyMode.CUSTOM,
"allow_domains": ["api.openai.com"],
"transforms": [
{
"domain": "api.openai.com",
"inject_headers": {
"Authorization": "Bearer sk-proj-...",
},
"strip_headers": ["X-Debug"],
}
],
},
)
print(sandbox.id, sandbox.network_policy)
```
```ts
import { Leap0Client, NetworkPolicyMode } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
vcpu: 2,
memory: 2048,
networkPolicy: {
mode: NetworkPolicyMode.CUSTOM,
allowDomains: ["api.openai.com"],
transforms: [
{
domain: "api.openai.com",
injectHeaders: {
Authorization: "Bearer sk-proj-...",
},
stripHeaders: ["X-Debug"],
},
],
},
});
console.log(sandbox.id, sandbox.networkPolicy);
await client.close();
```
## TLS termination [#tls-termination]
To perform request transformation on HTTPS traffic, the firewall terminates TLS connections. Only connections to domains with defined transform rules are terminated. All other allowed domains pass through as an opaque TCP tunnel without any inspection.
A unique, per-sandbox CA is added to the system certificates. Standard environment variables are configured automatically to ensure compatibility with most clients.
## Snapshots [#snapshots]
Network policy is persisted with snapshots. When restoring a snapshot, the policy from the snapshot is used by default. You can override it by passing a new `network_policy` in the restore request.
```
```
# Metadata Service (/metadata-service)
Leap0 exposes a metadata service inside each sandbox at `169.254.169.254`.
It publishes Leap0-specific metadata under `http://169.254.169.254/latest/meta-data/leap0`.
Read the root document when you want the full payload, or read nested paths such as `http://169.254.169.254/latest/meta-data/leap0/mounts` when you only need one section.
The root payload includes `schema_version` so guest code can identify the metadata document version.
The full response schema is documented in the [Metadata Service API reference](/metadata-service/api).
## Authentication [#authentication]
The metadata service uses IMDSv2. First request a token, then include it on metadata reads.
```bash
TOKEN=$(curl -sf -X PUT http://169.254.169.254/latest/api/token \
-H 'X-metadata-token-ttl-seconds: 60')
curl -sf \
-H "X-metadata-token: $TOKEN" \
-H 'Accept: application/json' \
http://169.254.169.254/latest/meta-data/leap0
```
## Read metadata from a sandbox [#read-metadata-from-a-sandbox]
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(
mounts=[
{
"type": "object-storage",
"bucket": "cloud-samples-data",
"endpoint": "https://storage.googleapis.com",
"mount_path": "/data/assets",
"prefix": "adc/",
"read_only": True,
}
],
)
result = sandbox.process.execute(
command=(
"TOKEN=$(curl -sf -X PUT http://169.254.169.254/latest/api/token "
"-H 'X-metadata-token-ttl-seconds: 60') && "
"curl -sf -H 'X-metadata-token: $TOKEN' -H 'Accept: application/json' "
"http://169.254.169.254/latest/meta-data/leap0"
)
)
print(result.stdout)
client.close()
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
mounts: [
{
type: "object-storage",
bucket: "cloud-samples-data",
endpoint: "https://storage.googleapis.com",
mountPath: "/data/assets",
prefix: "adc/",
readOnly: true,
},
],
});
const result = await sandbox.process.execute({
command:
`TOKEN=$(curl -sf -X PUT http://169.254.169.254/latest/api/token -H 'X-metadata-token-ttl-seconds: 60') && ` +
`curl -sf -H 'X-metadata-token: $TOKEN' -H 'Accept: application/json' ` +
`http://169.254.169.254/latest/meta-data/leap0`,
});
console.log(result.stdout);
await client.close();
```
# Object Storage (/object-storage)
Object storage mounts let a sandbox access bucket contents as files.
Leap0 mounts the bucket inside the sandbox with `s3fs` without exposing the storage credentials in the sandbox.
## Configure a mount [#configure-a-mount]
Each mount has four main fields:
* `bucket`: the S3 bucket name.
* `endpoint`: the base S3-compatible service endpoint URL.
* `mount_path`: the absolute path inside the sandbox where the bucket appears.
* `prefix`: optional key prefix inside the bucket.
You can also set `read_only`.
Credentials are optional. Omit `access_key_id` and `secret_access_key` for public buckets.
## Use service endpoints, not bucket-hosted URLs [#use-service-endpoints-not-bucket-hosted-urls]
Pass the base S3-compatible service endpoint directly, not a bucket-hosted URL, for example `https://storage.googleapis.com` instead of `https://project-assets.storage.googleapis.com`.
## Create a sandbox with object storage [#create-a-sandbox-with-object-storage]
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(
mounts=[
{
"type": "object-storage",
"bucket": "project-assets",
"endpoint": "https://storage.googleapis.com",
"mount_path": "/data/assets",
"prefix": "docs/",
"read_only": True,
}
],
)
print(sandbox.mounts)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
mounts: [
{
type: "object-storage",
bucket: "project-assets",
endpoint: "https://storage.googleapis.com",
mountPath: "/data/assets",
prefix: "docs/",
readOnly: true,
},
],
});
console.log(sandbox.mounts);
await client.close();
```
## Add a mount [#add-a-mount]
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
mount = sandbox.add_mount(
{
"type": "object-storage",
"bucket": "project-assets",
"endpoint": "https://storage.googleapis.com",
"mount_path": "/data/assets",
"prefix": "docs/",
"read_only": True,
}
)
print(mount.id, mount.bucket, mount.mount_path)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({});
const mount = await sandbox.addMount({
type: "object-storage",
bucket: "project-assets",
endpoint: "https://storage.googleapis.com",
mountPath: "/data/assets",
prefix: "docs/",
readOnly: true,
});
console.log(mount.id, mount.bucket, mount.mountPath);
await client.close();
```
## Edit a mount [#edit-a-mount]
Use the returned mount `id` and pass only the fields you want to change.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
mount = sandbox.add_mount(
{
"type": "object-storage",
"bucket": "project-assets",
"endpoint": "https://storage.googleapis.com",
"mount_path": "/data/assets",
}
)
updated_mount = sandbox.update_mount(
mount.id,
{
"prefix": "docs/",
"read_only": False,
},
)
print(updated_mount.id, updated_mount.prefix, updated_mount.read_only)
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({});
const mount = await sandbox.addMount({
type: "object-storage",
bucket: "project-assets",
endpoint: "https://storage.googleapis.com",
mountPath: "/data/assets",
});
const updatedMount = await sandbox.updateMount(mount.id, {
prefix: "docs/",
readOnly: false,
});
console.log(updatedMount.id, updatedMount.prefix, updatedMount.readOnly);
await client.close();
```
## Delete a mount [#delete-a-mount]
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
mount = sandbox.add_mount(
{
"type": "object-storage",
"bucket": "project-assets",
"endpoint": "https://storage.googleapis.com",
"mount_path": "/data/assets",
}
)
sandbox.delete_mount(mount.id)
print(f"Deleted mount {mount.id}")
```
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({});
const mount = await sandbox.addMount({
type: "object-storage",
bucket: "project-assets",
endpoint: "https://storage.googleapis.com",
mountPath: "/data/assets",
});
await sandbox.deleteMount(mount.id);
console.log("Deleted mount", mount.id);
await client.close();
```
## Behavior and limits [#behavior-and-limits]
* Mounts can be configured as read-only or read-write.
* Bucket contents are fetched lazily as the sandbox reads files.
* Credentials are not returned by the API and are not exposed inside the guest.
* A sandbox can attach up to 8 object storage mounts.
# Telemetry (/telemetry)
Every sandbox runs an [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) that collects host metrics, logs, traces, and spans and pushes them to an OTLP HTTP endpoint that you configure via environment variables. Your code can also send its own OTLP telemetry to the local collector, which forwards it alongside the host data.
The JavaScript and Python SDKs can also emit OpenTelemetry spans and metrics for SDK calls such as sandbox creation and tool usage. That lets you correlate client-side operations with sandbox-side telemetry in the same backend.
## Metrics [#metrics]
Each sandbox automatically collects the following metrics:
| Metric | Description |
| -------------------------------------- | ------------------------ |
| `leap0.sandbox.cpu.utilization` | CPU usage percentage |
| `leap0.sandbox.cpu.limit` | Logical CPU count |
| `leap0.sandbox.memory.utilization` | Memory usage percentage |
| `leap0.sandbox.memory.usage` | Memory used in bytes |
| `leap0.sandbox.memory.limit` | Memory limit in bytes |
| `leap0.sandbox.filesystem.utilization` | Disk usage percentage |
| `leap0.sandbox.filesystem.usage` | Disk space used in bytes |
## Logs, traces, and spans [#logs-traces-and-spans]
Any OTLP logs, traces, and spans your code sends to the local collector (ports 4317/4318) are forwarded to the configured endpoint.
## SDK OpenTelemetry [#sdk-opentelemetry]
The JavaScript and Python SDKs can emit OpenTelemetry spans and metrics for SDK operations such as creating sandboxes and calling sandbox tools.
Enable that client-side instrumentation by setting `sdkOtelEnabled: true` on `new Leap0Client(...)`, `sdk_otel_enabled=True` on the Python client, or `LEAP0_SDK_OTEL_ENABLED=true` in your local environment.
If `OTEL_EXPORTER_OTLP_ENDPOINT` is already set locally, the SDK enables this instrumentation automatically.
This is separate from sandbox telemetry: use `otelExport: true` in the JavaScript SDK or `otel_export=True` in Python to forward telemetry produced inside the sandbox itself.
### JavaScript SDK and sandbox example [#javascript-sdk-and-sandbox-example]
```ts
import { Leap0Client } from "leap0";
process.env.OTEL_EXPORTER_OTLP_ENDPOINT = "https://otel.example.com";
process.env.OTEL_EXPORTER_OTLP_HEADERS = "x-api-key=abc123";
const client = new Leap0Client({ sdkOtelEnabled: true });
const sandbox = await client.sandboxes.create({
vcpu: 2,
memory: 2048,
timeout: 30,
otelExport: true,
});
console.log(sandbox.id);
await client.close();
```
## Resource attributes [#resource-attributes]
Every signal is tagged with `leap0.sandbox.id`, `leap0.org.id`, and `leap0.template.id` so you can filter and group by sandbox.
## Configuration [#configuration]
Set these environment variables when creating a sandbox to enable telemetry export.
### Your own endpoint [#your-own-endpoint]
If you run your own observability backend (Grafana, Datadog, etc.), pass the standard OTLP environment variables in the sandbox `env_vars`:
| Variable | Description |
| ----------------------------- | ------------------------------------------------------------------ |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | Your OTLP HTTP endpoint (e.g. `https://otel.example.com`) |
| `OTEL_EXPORTER_OTLP_HEADERS` | Comma-separated `key=value` auth headers (e.g. `x-api-key=abc123`) |
## Example [#example]
Create a sandbox with telemetry export enabled. Metrics, logs, and traces will be pushed to the configured endpoint as OTLP HTTP.
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create(
vcpu=2,
memory=2048,
timeout=30,
otel_export=True,
)
print(sandbox.id)
```
```ts
import { Leap0Client } from "leap0";
process.env.OTEL_EXPORTER_OTLP_ENDPOINT = "https://otel.example.com";
process.env.OTEL_EXPORTER_OTLP_HEADERS = "x-api-key=abc123";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create({
vcpu: 2,
memory: 2048,
timeout: 30,
otelExport: true,
});
console.log(sandbox.id);
await client.close();
```
# Claude Code (/guides/claude-code)
Run Claude Code, Anthropic's agentic coding tool, inside Leap0 sandboxes. You can either bake it into a template or install it at runtime using `process.execute`.
## Install at runtime [#install-at-runtime]
Install Claude Code directly in a running sandbox using the process API:
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
// Install Claude Code
await sandbox.process.execute({
command: "curl -fsSL https://claude.ai/install.sh | bash",
timeout: 120,
});
// Verify installation
const result = await sandbox.process.execute({
command: "claude --version",
});
console.log(result.stdout);
await client.close();
```
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
# Install Claude Code
sandbox.process.execute(
command="curl -fsSL https://claude.ai/install.sh | bash",
timeout=120,
)
# Verify installation
result = sandbox.process.execute(command="claude --version")
print(result.stdout)
```
## Template Dockerfile [#template-dockerfile]
To avoid installing on every boot, bake Claude Code into a template:
```dockerfile
FROM ubuntu:22.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
curl \
git \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# Install Node.js 18+
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
apt-get install -y nodejs && \
rm -rf /var/lib/apt/lists/*
# Install Claude Code
RUN npm install -g @anthropic-ai/claude-code
CMD ["bash"]
```
## Build and publish the image [#build-and-publish-the-image]
```bash
docker build -t registry.example.com/my-org/claude-code-template:v1 ./claude-code
docker push registry.example.com/my-org/claude-code-template:v1
```
## Create the Leap0 template [#create-the-leap0-template]
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const template = await client.templates.create({
name: "claude-code",
uri: "registry.example.com/my-org/claude-code-template:v1",
});
console.log(template.id);
await client.close();
```
## Start a sandbox [#start-a-sandbox]
```js
const sandbox = await client.sandboxes.create({
template_name: "claude-code",
});
// Run Claude Code with your API key
await sandbox.process.execute({
command: "claude 'explain the main function in this project'",
env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY },
cwd: "/home/user/project",
timeout: 300,
});
```
# Codex (/guides/codex)
Run OpenAI Codex, an agentic coding tool powered by ChatGPT, inside Leap0 sandboxes. You can either bake it into a template or install it at runtime using `process.execute`.
## Install at runtime [#install-at-runtime]
Install Codex directly in a running sandbox using the process API:
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
// Install Node.js if not available
await sandbox.process.execute({
command: "curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && apt-get install -y nodejs",
timeout: 120,
});
// Install Codex
await sandbox.process.execute({
command: "npm install -g @openai/codex",
timeout: 60,
});
// Verify installation
const result = await sandbox.process.execute({
command: "codex --version",
});
console.log(result.stdout);
await client.close();
```
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
# Install Node.js if not available
sandbox.process.execute(
command="curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && apt-get install -y nodejs",
timeout=120,
)
# Install Codex
sandbox.process.execute(
command="npm install -g @openai/codex",
timeout=60,
)
# Verify installation
result = sandbox.process.execute(command="codex --version")
print(result.stdout)
```
## Template Dockerfile [#template-dockerfile]
To avoid installing on every boot, bake Codex into a template:
```dockerfile
FROM ubuntu:22.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
curl \
git \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# Install Node.js 18+
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
apt-get install -y nodejs && \
rm -rf /var/lib/apt/lists/*
# Install Codex
RUN npm install -g @openai/codex
CMD ["bash"]
```
## Build and publish the image [#build-and-publish-the-image]
```bash
docker build -t registry.example.com/my-org/codex-template:v1 ./codex
docker push registry.example.com/my-org/codex-template:v1
```
## Create the Leap0 template [#create-the-leap0-template]
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const template = await client.templates.create({
name: "codex",
uri: "registry.example.com/my-org/codex-template:v1",
});
console.log(template.id);
await client.close();
```
## Start a sandbox [#start-a-sandbox]
```js
const sandbox = await client.sandboxes.create({
template_name: "codex",
});
// Run Codex with your API key
await sandbox.process.execute({
command: "codex 'add error handling to the API routes'",
e env: { OPENAI_API_KEY: process.env.OPENAI_API_KEY },
cwd: "/home/user/project",
timeout: 300,
});
```
# Docker with systemd (/guides/docker-systemd)
A Docker template with systemd lets you manage the Docker daemon as a service. This approach is useful when you need better control over Docker lifecycle and integration with other systemd services inside Leap0 sandboxes.
## Dockerfile [#dockerfile]
Create a Dockerfile to set up Docker with systemd:
```dockerfile
FROM ubuntu:22.04
ENV DEBIAN_FRONTEND=noninteractive
ENV container=docker
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
curl \
gnupg \
systemd systemd-sysv \
&& rm -rf /var/lib/apt/lists/*
# Install Docker GPG key and repository
RUN install -m 0755 -d /etc/apt/keyrings \
&& curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc \
&& chmod a+r /etc/apt/keyrings/docker.asc \
&& . /etc/os-release \
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu ${VERSION_CODENAME} stable" \
> /etc/apt/sources.list.d/docker.list \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
docker-ce \
docker-ce-cli \
containerd.io \
docker-buildx-plugin \
docker-compose-plugin \
&& rm -rf /var/lib/apt/lists/*
# Enable Docker service on boot
RUN systemctl enable docker
STOPSIGNAL SIGRTMIN+3
CMD ["/sbin/init"]
```
## Build and publish the image [#build-and-publish-the-image]
Build the Docker template and push it to a registry that Leap0 can pull from:
```bash
docker build -t registry.example.com/my-org/docker-systemd-template:v1 ./docker-systemd
docker push registry.example.com/my-org/docker-systemd-template:v1
```
## Create the Leap0 template [#create-the-leap0-template]
Create a Leap0 template that points to the Docker systemd image:
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const template = await client.templates.create({
name: "docker-systemd",
uri: "registry.example.com/my-org/docker-systemd-template:v1",
});
console.log(template.id);
await client.close();
```
## Start a sandbox with Docker [#start-a-sandbox-with-docker]
Create a sandbox from the Docker systemd template:
```js
const sandbox = await client.sandboxes.create({
template_name: "docker-systemd",
});
```
# Docker (/guides/docker)
A Docker template lets you start sandboxes with Docker already installed and configured. This is useful for development, testing containerized applications, or running Docker-based workflows inside Leap0 sandboxes.
## Basic Dockerfile [#basic-dockerfile]
Create a minimal Dockerfile to set up Docker in your sandbox:
```dockerfile
FROM ubuntu:22.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
curl \
gnupg \
&& rm -rf /var/lib/apt/lists/*
# Install Docker GPG key and repository
RUN install -m 0755 -d /etc/apt/keyrings \
&& curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc \
&& chmod a+r /etc/apt/keyrings/docker.asc \
&& . /etc/os-release \
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu ${VERSION_CODENAME} stable" \
> /etc/apt/sources.list.d/docker.list \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
docker-ce \
docker-ce-cli \
containerd.io \
docker-buildx-plugin \
docker-compose-plugin \
&& rm -rf /var/lib/apt/lists/*
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["bash"]
```
## Docker entrypoint script [#docker-entrypoint-script]
Create `entrypoint.sh` to start the Docker daemon when the sandbox boots:
```bash
#!/bin/bash
set -e
command -v dockerd > /dev/null 2>&1 && ! pgrep -x dockerd > /dev/null 2>&1 && dockerd &>/var/log/dockerd.log &
exec "$@"
```
## Build and publish the image [#build-and-publish-the-image]
Build the Docker template and push it to a registry that Leap0 can pull from:
```bash
docker build -t registry.example.com/my-org/docker-template:v1 ./docker
docker push registry.example.com/my-org/docker-template:v1
```
## Create the Leap0 template [#create-the-leap0-template]
Create a Leap0 template that points to the Docker image:
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const template = await client.templates.create({
name: "docker",
uri: "registry.example.com/my-org/docker-template:v1",
});
console.log(template.id);
await client.close();
```
## Start a sandbox with Docker [#start-a-sandbox-with-docker]
Create a sandbox from the Docker template:
```js
const sandbox = await client.sandboxes.create({
template_name: "docker",
});
```
# k3s (/guides/k3s)
A k3s template lets you start sandboxes with k3s (lightweight Kubernetes) already installed and bootstrapped. k3s is a minimal, production-grade Kubernetes distribution ideal for resource-constrained environments, development, and testing.
## Dockerfile [#dockerfile]
Create a Dockerfile to set up k3s in your sandbox:
```dockerfile
FROM ubuntu:22.04
ENV DEBIAN_FRONTEND=noninteractive
ENV container=docker
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
curl \
systemd systemd-sysv \
&& rm -rf /var/lib/apt/lists/*
# Download and install k3s binary
RUN mkdir -p /usr/local/bin && \
curl -sfL https://github.com/k3s-io/k3s/releases/download/v1.35.5%2Bk3s1/k3s -o /usr/local/bin/k3s && \
chmod +x /usr/local/bin/k3s && \
ln -sf /usr/local/bin/k3s /usr/local/bin/kubectl && \
mkdir -p /var/lib/rancher/k3s
# Copy k3s service file
COPY files/k3s.service /etc/systemd/system/k3s.service
# Copy bootstrap script
COPY files/init-k3s.sh /usr/local/share/k3s/init-k3s.sh
RUN chmod +x /usr/local/share/k3s/init-k3s.sh
# Copy bootstrap service
COPY files/init-k3s.service /etc/systemd/system/init-k3s.service
# Enable services by creating symlinks
RUN mkdir -p /etc/systemd/system/multi-user.target.wants && \
ln -sf /etc/systemd/system/k3s.service /etc/systemd/system/multi-user.target.wants/k3s.service && \
ln -sf /etc/systemd/system/init-k3s.service /etc/systemd/system/multi-user.target.wants/init-k3s.service
STOPSIGNAL SIGRTMIN+3
CMD ["/sbin/init"]
```
## Bootstrap script [#bootstrap-script]
Create `files/init-k3s.sh` to ensure k3s is properly initialized:
```bash
#!/bin/bash
set -euo pipefail
fail() {
printf '%s\n' "$1"
shift
"$@" || true
exit 1
}
wait_for() {
local attempts="$1"
local delay="$2"
shift 2
for _ in $(seq 1 "$attempts"); do
if "$@" >/dev/null 2>&1; then
return 0
fi
sleep "$delay"
done
return 1
}
# Wait for k3s to be ready
if ! wait_for 60 2 test -f /etc/rancher/k3s/k3s.yaml; then
fail "k3s kubeconfig did not appear" journalctl -u k3s --no-pager
fi
# Copy kubeconfig to root home for easy access
mkdir -p /root/.kube
cp /etc/rancher/k3s/k3s.yaml /root/.kube/config
chmod 600 /root/.kube/config
# Wait for nodes to be ready
if ! wait_for 60 2 kubectl --kubeconfig /root/.kube/config get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' | grep -q .; then
fail "k3s node did not become ready" journalctl -u k3s --no-pager
fi
```
## k3s service file [#k3s-service-file]
Create `files/k3s.service` for k3s systemd integration:
```ini
[Unit]
Description=Lightweight Kubernetes
Documentation=https://k3s.io
Wants=network-online.target
After=network-online.target
[Service]
Type=notify
EnvironmentFile=-/etc/systemd/system/k3s.service.env
EnvironmentFile=-/etc/sysconfig/k3s
ExecStartPre=/bin/sh -c 'mkdir -p /var/lib/rancher/k3s/agent/containerd'
ExecStart=/usr/local/bin/k3s server
KillMode=process
Delegate=yes
LimitNOFILE=1048576
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
TimeoutStartSec=0
Restart=always
RestartSec=5s
[Install]
WantedBy=multi-user.target
```
## Bootstrap service [#bootstrap-service]
Create `files/init-k3s.service` to run the bootstrap script:
```ini
[Unit]
Description=Bootstrap k3s
After=k3s.service
Wants=k3s.service
[Service]
Type=oneshot
ExecStart=/usr/local/share/k3s/init-k3s.sh
RemainAfterExit=yes
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
```
## Build and publish the image [#build-and-publish-the-image]
Build the k3s template and push it to a registry that Leap0 can pull from:
```bash
docker build -t registry.example.com/my-org/k3s-template:v1 ./k3s
docker push registry.example.com/my-org/k3s-template:v1
```
## Create the Leap0 template [#create-the-leap0-template]
Create a Leap0 template that points to the k3s image:
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const template = await client.templates.create({
name: "k3s",
uri: "registry.example.com/my-org/k3s-template:v1",
});
console.log(template.id);
await client.close();
```
## Start a sandbox with k3s [#start-a-sandbox-with-k3s]
Create a sandbox from the k3s template:
```js
const sandbox = await client.sandboxes.create({
template_name: "k3s",
});
```
After the sandbox is ready, k3s will be running with kubectl available:
```bash
# Get nodes
kubectl get nodes
# Get pods in all namespaces
kubectl get pods -A
# Deploy a test pod
kubectl run test-pod --image=alpine --restart=Never -- sleep 1000
```
# Kubernetes (/guides/kubernetes)
A Kubernetes template lets you start sandboxes with Kubernetes already installed and bootstrapped. Use this guide as a starting point when you want a reusable cluster for development, tests, or agent workflows.
## Dockerfile [#dockerfile]
Use the Dockerfile to install Kubernetes, copy the bootstrap files, and enable the systemd service.
```dockerfile
FROM ubuntu:22.04
ARG K8S_SERIES=v1.33
ARG K8S_DEB_VERSION=1.33.11-1.1
ARG FLANNEL_VERSION=v0.28.4
ARG FLANNEL_CNI_PLUGIN_VERSION=v1.9.1-flannel1
ENV DEBIAN_FRONTEND=noninteractive
ENV container=docker
RUN apt-get update && apt-get install -y \
containerd \
systemd systemd-sysv \
curl ca-certificates gnupg lsb-release \
iproute2 iptables ethtool socat conntrack \
ebtables ipset containernetworking-plugins \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
RUN mkdir -p /etc/apt/keyrings && \
curl -fsSL "https://pkgs.k8s.io/core:/stable:/${K8S_SERIES}/deb/Release.key" | gpg --dearmor -o /etc/apt/keyrings/kubernetes.gpg && \
echo "deb [signed-by=/etc/apt/keyrings/kubernetes.gpg] https://pkgs.k8s.io/core:/stable:/${K8S_SERIES}/deb/ /" \
> /etc/apt/sources.list.d/kubernetes.list
RUN apt-get update && apt-get install -y \
kubelet="$K8S_DEB_VERSION" kubeadm="$K8S_DEB_VERSION" kubectl="$K8S_DEB_VERSION" \
&& apt-mark hold kubelet kubeadm kubectl \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
COPY files/init-k8s.sh /usr/local/share/k8/init-k8s.sh
COPY files/init-k8s.service /etc/systemd/system/init-k8s.service
COPY files/kube-flannel.yml.tmpl /usr/local/share/k8/kube-flannel.yml.tmpl
RUN sed -i "s|__K8S_VERSION__|v${K8S_DEB_VERSION%%-*}|g" /usr/local/share/k8/init-k8s.sh && \
sed -i "s|__FLANNEL_IMAGE__|ghcr.io/flannel-io/flannel:${FLANNEL_VERSION}|g" /usr/local/share/k8/init-k8s.sh && \
sed -i "s|__FLANNEL_CNI_PLUGIN_IMAGE__|ghcr.io/flannel-io/flannel-cni-plugin:${FLANNEL_CNI_PLUGIN_VERSION}|g" /usr/local/share/k8/init-k8s.sh && \
sed -i "s|__FLANNEL_IMAGE__|ghcr.io/flannel-io/flannel:${FLANNEL_VERSION}|g" /usr/local/share/k8/kube-flannel.yml.tmpl && \
sed -i "s|__FLANNEL_CNI_PLUGIN_IMAGE__|ghcr.io/flannel-io/flannel-cni-plugin:${FLANNEL_CNI_PLUGIN_VERSION}|g" /usr/local/share/k8/kube-flannel.yml.tmpl && \
install -m 0755 /usr/local/share/k8/init-k8s.sh /init-k8s.sh && \
ln -sf /lib/systemd/system/containerd.service /etc/systemd/system/multi-user.target.wants/containerd.service && \
ln -sf /etc/systemd/system/init-k8s.service /etc/systemd/system/multi-user.target.wants/init-k8s.service
STOPSIGNAL SIGRTMIN+3
CMD ["/sbin/init"]
```
## Bootstrap service [#bootstrap-service]
Create `files/init-k8s.service` to run your bootstrap script when the sandbox starts.
```ini
[Unit]
Description=Bootstrap Kubernetes
After=network-online.target containerd.service
Wants=network-online.target
[Service]
Type=oneshot
TimeoutStartSec=1800
ExecStart=/init-k8s.sh
RemainAfterExit=yes
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
```
## Bootstrap script [#bootstrap-script]
Create `files/init-k8s.sh` to configure containerd, initialize Kubernetes with `kubeadm`, install Flannel, and copy the kubeconfig to `/root/.kube/config`.
```bash
#!/bin/bash
set -euo pipefail
PAUSE_IMAGE="registry.k8s.io/pause:3.10.2"
FLANNEL_IMAGE="__FLANNEL_IMAGE__"
FLANNEL_CNI_PLUGIN_IMAGE="__FLANNEL_CNI_PLUGIN_IMAGE__"
CRI_SOCKET="unix:///run/containerd/containerd.sock"
K8S_VERSION="__K8S_VERSION__"
KUBEADM_CONFIG="/etc/kubeadm-config.yaml"
FLANNEL_MANIFEST="/etc/kube-flannel.yml"
FLANNEL_MANIFEST_TEMPLATE="/usr/local/share/k8/kube-flannel.yml.tmpl"
K8S_NODE_NAME="${K8S_NODE_NAME:-leap0}"
BOOTSTRAP_COMPLETE_FILE="/var/lib/kube-bootstrap/finished"
log() {
printf '%s\n' "$1"
}
sync_root_kubeconfig() {
if [ -f /etc/kubernetes/admin.conf ]; then
mkdir -p /root/.kube
cp /etc/kubernetes/admin.conf /root/.kube/config
fi
}
fail() {
log "$1"
shift
"$@" || true
exit 1
}
retry() {
local attempts="$1"
local delay="$2"
shift 2
for _ in $(seq 1 "$attempts"); do
if "$@"; then
return 0
fi
sleep "$delay"
done
return 1
}
normalize_kubelet_flags() {
if [ -f /var/lib/kubelet/kubeadm-flags.env ]; then
sed -i -E 's/ --pod-infra-container-image=[^" ]+//g' /var/lib/kubelet/kubeadm-flags.env
fi
}
write_flannel_manifest() {
cp "$FLANNEL_MANIFEST_TEMPLATE" "$FLANNEL_MANIFEST"
}
start_kubelet() {
normalize_kubelet_flags
if systemctl is-active --quiet kubelet; then
return 0
fi
systemctl start kubelet
}
wait_for_api() {
wait_for 120 2 curl -sk https://127.0.0.1:6443/readyz
}
wait_for() {
local attempts="$1"
local delay="$2"
shift 2
for _ in $(seq 1 "$attempts"); do
if "$@" >/dev/null 2>&1; then
return 0
fi
sleep "$delay"
done
return 1
}
start_containerd() {
mkdir -p /etc/containerd
containerd config default >/etc/containerd/config.toml
sed -i 's#sandbox_image = ".*"#sandbox_image = "'"$PAUSE_IMAGE"'"#' /etc/containerd/config.toml
sed -i "s#sandbox = '.*'#sandbox = '$PAUSE_IMAGE'#" /etc/containerd/config.toml
sed -i 's/SystemdCgroup = false/SystemdCgroup = true/' /etc/containerd/config.toml
sed -i 's/snapshotter = "overlayfs"/snapshotter = "native"/' /etc/containerd/config.toml
systemctl restart containerd
if ! wait_for 30 1 test -S /run/containerd/containerd.sock; then
fail "containerd socket did not appear" journalctl -u containerd --no-pager
fi
}
pull_images() {
local arch image
arch="$(dpkg --print-architecture)"
if ! ctr -n k8s.io images pull --local --snapshotter native --platform "linux/$arch" "$PAUSE_IMAGE"; then
fail "failed to preload image $PAUSE_IMAGE" journalctl -u containerd --no-pager
fi
while IFS= read -r image; do
if ! ctr -n k8s.io images pull --local --snapshotter native --platform "linux/$arch" "$image"; then
fail "failed to preload image $image" journalctl -u containerd --no-pager
fi
done < "$KUBEADM_CONFIG"
apiVersion: kubeadm.k8s.io/v1beta4
kind: InitConfiguration
nodeRegistration:
name: "$K8S_NODE_NAME"
criSocket: $CRI_SOCKET
kubeletExtraArgs:
- name: node-ip
value: "$NODE_IP"
- name: hostname-override
value: "$K8S_NODE_NAME"
---
apiVersion: kubeadm.k8s.io/v1beta4
kind: ClusterConfiguration
kubernetesVersion: $K8S_VERSION
networking:
podSubnet: 10.244.0.0/16
apiServer:
certSANs:
- leap0
- "$K8S_NODE_NAME"
- "$NODE_IP"
- "127.0.0.1"
- "$(hostname -f 2>/dev/null || hostname)"
proxy: {}
---
apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
cgroupDriver: systemd
failSwapOn: false
containerRuntimeEndpoint: $CRI_SOCKET
staticPodPath: /etc/kubernetes/manifests
EOF_KUBEADM
if [ ! -f /etc/kubernetes/admin.conf ]; then
pull_images
fi
run_bootstrap
sync_root_kubeconfig
write_flannel_manifest
if kubectl --kubeconfig /etc/kubernetes/admin.conf get node "$K8S_NODE_NAME" -o jsonpath='{range .spec.taints[*]}{.key}{"\n"}{end}' 2>/dev/null | grep -qx 'node-role.kubernetes.io/control-plane'; then
kubectl --kubeconfig /etc/kubernetes/admin.conf taint node "$K8S_NODE_NAME" node-role.kubernetes.io/control-plane-
fi
retry 5 5 kubectl --kubeconfig /etc/kubernetes/admin.conf apply -f "$FLANNEL_MANIFEST" || fail "failed to apply flannel manifest" true
kubectl --kubeconfig /root/.kube/config -n kube-flannel rollout status ds/kube-flannel-ds --timeout=180s
wait_for 90 2 test -f /run/flannel/subnet.env || fail "flannel subnet.env did not appear" journalctl -u kubelet --no-pager
kubectl --kubeconfig /root/.kube/config -n kube-system rollout status deployment/coredns --timeout=180s
kubectl --kubeconfig /root/.kube/config wait --for=condition=Ready "node/$K8S_NODE_NAME" --timeout=180s
touch "$BOOTSTRAP_COMPLETE_FILE"
fi
if [ -f /etc/kubernetes/admin.conf ]; then
sync_root_kubeconfig
start_kubelet
fi
```
## Flannel manifest [#flannel-manifest]
Create `files/kube-flannel.yml.tmpl` from the upstream Flannel Kubernetes manifest, then pin the image versions you want to use. The manifest should create the `kube-flannel` namespace, RBAC resources, config map, and `kube-flannel-ds` daemon set.
Use the same pod subnet in the Flannel config that you used in `kubeadm`:
```yaml
---
kind: Namespace
apiVersion: v1
metadata:
name: kube-flannel
labels:
k8s-app: flannel
pod-security.kubernetes.io/enforce: privileged
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
labels:
k8s-app: flannel
name: flannel
rules:
- apiGroups:
- ""
resources:
- pods
verbs:
- get
- apiGroups:
- ""
resources:
- nodes
verbs:
- get
- list
- watch
- apiGroups:
- ""
resources:
- nodes/status
verbs:
- patch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
labels:
k8s-app: flannel
name: flannel
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: flannel
subjects:
- kind: ServiceAccount
name: flannel
namespace: kube-flannel
---
apiVersion: v1
kind: ServiceAccount
metadata:
labels:
k8s-app: flannel
name: flannel
namespace: kube-flannel
---
kind: ConfigMap
apiVersion: v1
metadata:
name: kube-flannel-cfg
namespace: kube-flannel
labels:
tier: node
k8s-app: flannel
app: flannel
data:
cni-conf.json: |
{
"name": "cbr0",
"cniVersion": "0.3.1",
"plugins": [
{
"type": "flannel",
"delegate": {
"hairpinMode": true,
"isDefaultGateway": true
}
},
{
"type": "portmap",
"capabilities": {
"portMappings": true
}
}
]
}
net-conf.json: |
{
"Network": "10.244.0.0/16",
"EnableNFTables": false,
"Backend": {
"Type": "vxlan"
}
}
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: kube-flannel-ds
namespace: kube-flannel
labels:
tier: node
app: flannel
k8s-app: flannel
spec:
selector:
matchLabels:
app: flannel
template:
metadata:
labels:
tier: node
app: flannel
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/os
operator: In
values:
- linux
hostNetwork: true
priorityClassName: system-node-critical
tolerations:
- operator: Exists
effect: NoSchedule
serviceAccountName: flannel
initContainers:
- name: install-cni-plugin
image: __FLANNEL_CNI_PLUGIN_IMAGE__
command:
- cp
args:
- -f
- /flannel
- /opt/cni/bin/flannel
volumeMounts:
- name: cni-plugin
mountPath: /opt/cni/bin
- name: install-cni
image: __FLANNEL_IMAGE__
command:
- cp
args:
- -f
- /etc/kube-flannel/cni-conf.json
- /etc/cni/net.d/10-flannel.conflist
volumeMounts:
- name: cni
mountPath: /etc/cni/net.d
- name: flannel-cfg
mountPath: /etc/kube-flannel/
containers:
- name: kube-flannel
image: __FLANNEL_IMAGE__
command:
- /opt/bin/flanneld
args:
- --ip-masq
- --kube-subnet-mgr
- --kube-api-url=https://127.0.0.1:6443
- --kubeconfig-file=/etc/kube-flannel-kubeconfig/admin.conf
resources:
requests:
cpu: "100m"
memory: "50Mi"
securityContext:
privileged: false
capabilities:
add: ["NET_ADMIN", "NET_RAW"]
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: EVENT_QUEUE_DEPTH
value: "5000"
- name: CONT_WHEN_CACHE_NOT_READY
value: "false"
volumeMounts:
- name: run
mountPath: /run/flannel
- name: flannel-cfg
mountPath: /etc/kube-flannel/
- name: kubeconfig
mountPath: /etc/kube-flannel-kubeconfig/admin.conf
subPath: admin.conf
readOnly: true
- name: xtables-lock
mountPath: /run/xtables.lock
volumes:
- name: run
hostPath:
path: /run/flannel
type: DirectoryOrCreate
- name: cni-plugin
hostPath:
path: /opt/cni/bin
type: DirectoryOrCreate
- name: cni
hostPath:
path: /etc/cni/net.d
type: DirectoryOrCreate
- name: flannel-cfg
configMap:
name: kube-flannel-cfg
- name: kubeconfig
hostPath:
path: /etc/kubernetes
type: Directory
- name: xtables-lock
hostPath:
path: /run/xtables.lock
type: FileOrCreate
```
## Build and publish the image [#build-and-publish-the-image]
Build the image and push it to a registry that Leap0 can pull from.
```bash
docker build -t registry.example.com/my-org/k8-template:v1 ./k8
docker push registry.example.com/my-org/k8-template:v1
```
## Create the Leap0 template [#create-the-leap0-template]
Create a Leap0 template that points to the image.
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const template = await client.templates.create({
name: "kubernetes",
uri: "registry.example.com/my-org/k8-template:v1",
});
console.log(template.id);
await client.close();
```
## Start a sandbox [#start-a-sandbox]
Create a sandbox from the template and wait for Kubernetes to finish bootstrapping.
```js
const sandbox = await client.sandboxes.create({
template_name: "kubernetes",
});
```
After the sandbox is ready, SSH or run a process in the sandbox and verify the node:
```bash
kubectl get nodes
kubectl get pods -A
```
# OpenCode (/guides/opencode)
Run OpenCode, a open-source AI coding agent, inside Leap0 sandboxes. You can either bake it into a template or install it at runtime using `process.execute`.
## Install at runtime [#install-at-runtime]
Install OpenCode directly in a running sandbox using the process API:
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
// Install OpenCode
await sandbox.process.execute({
command: "curl -fsSL https://opencode.ai/install | bash",
timeout: 120,
});
// Verify installation
const result = await sandbox.process.execute({
command: "opencode --version",
});
console.log(result.stdout);
await client.close();
```
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
# Install OpenCode
sandbox.process.execute(
command="curl -fsSL https://opencode.ai/install | bash",
timeout=120,
)
# Verify installation
result = sandbox.process.execute(command="opencode --version")
print(result.stdout)
```
## Template Dockerfile [#template-dockerfile]
To avoid installing on every boot, bake OpenCode into a template:
```dockerfile
FROM ubuntu:22.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
curl \
git \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# Install Node.js 18+
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
apt-get install -y nodejs && \
rm -rf /var/lib/apt/lists/*
# Install OpenCode
RUN npm install -g opencode-ai
CMD ["bash"]
```
## Build and publish the image [#build-and-publish-the-image]
```bash
docker build -t registry.example.com/my-org/opencode-template:v1 ./opencode
docker push registry.example.com/my-org/opencode-template:v1
```
## Create the Leap0 template [#create-the-leap0-template]
```js
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const template = await client.templates.create({
name: "opencode",
uri: "registry.example.com/my-org/opencode-template:v1",
});
console.log(template.id);
await client.close();
```
## Start a sandbox [#start-a-sandbox]
```js
const sandbox = await client.sandboxes.create({
template_name: "opencode",
});
// Run OpenCode with your API key
await sandbox.process.execute({
command: "opencode 'refactor the database module'",
env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY },
cwd: "/home/user/project",
timeout: 300,
});
```
# Defaults (/reference/javascript-sdk/common/defaults)
Source: [`src/config/constants.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/config/constants.ts)
## Constants [#constants]
* `DEFAULT_BASE_URL`: `"https://api.leap0.dev"`
* `DEFAULT_SANDBOX_DOMAIN`: `"sandbox.leap0.dev"`
* `DEFAULT_TEMPLATE_NAME`: `"system/debian:bookworm"`
* `DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME`: `"system/code-interpreter:v0.1.0"`
* `DEFAULT_DESKTOP_TEMPLATE_NAME`: `"system/desktop:v0.1.0"`
* `DEFAULT_VCPU`: `1`
* `DEFAULT_MEMORY_MIB`: `1024`
* `DEFAULT_TIMEOUT`: `300`
* `DEFAULT_CLIENT_TIMEOUT`: `300`
* `SDK_SOURCE`: `"sdk-ts"`
* `OTEL_EXPORTER_OTLP_ENDPOINT`: `"OTEL_EXPORTER_OTLP_ENDPOINT"`
* `OTEL_EXPORTER_OTLP_HEADERS`: `"OTEL_EXPORTER_OTLP_HEADERS"`
# Errors (/reference/javascript-sdk/common/errors)
Source: [`src/core/errors.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/core/errors.ts)
## Error Hierarchy [#error-hierarchy]
### `Leap0Error` [#leap0error]
Extends `Error`.
Base SDK error for request, transport, and response-validation failures.
Includes optional HTTP metadata and a `retryable` hint for transient failures.
### `Leap0PermissionError` [#leap0permissionerror]
Extends `Leap0Error`.
Error thrown when the API rejects a request due to missing permissions.
### `Leap0NotFoundError` [#leap0notfounderror]
Extends `Leap0Error`.
Error thrown when a requested API resource does not exist.
### `Leap0ConflictError` [#leap0conflicterror]
Extends `Leap0Error`.
Error thrown when a request conflicts with the current server state.
### `Leap0RateLimitError` [#leap0ratelimiterror]
Extends `Leap0Error`.
Error thrown when the API rate-limits a request.
### `Leap0TimeoutError` [#leap0timeouterror]
Extends `Leap0Error`.
Error thrown when a request exceeds the configured timeout.
### `Leap0WebSocketError` [#leap0websocketerror]
Extends `Leap0Error`.
Error thrown for websocket-specific failures such as disconnects or protocol issues.
# Leap0Client (/reference/javascript-sdk/core/leap0-client)
Source: [`src/client/index.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/client/index.ts)
## Signature [#signature]
```ts
Leap0Client(config: Leap0ConfigInput = {})
```
## Overview [#overview]
Top-level Leap0 SDK client that exposes all service groups.
#### Throws [#throws]
* `Leap0Error`: If config validation fails during client construction.
#### Examples [#examples]
```ts
const client = new Leap0Client({ apiKey: process.env.LEAP0_API_KEY! });
const sandbox = await client.sandboxes.create({ templateName: "base" });
```
## Methods [#methods]
### `close` [#close]
```ts
async close(): Promise
```
Closes the underlying transport.
#### Throws [#throws-1]
* `Leap0Error`: If shutting down the transport fails.
# Sandbox (/reference/javascript-sdk/core/sandbox)
Source: [`src/client/sandbox.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/client/sandbox.ts)
## Signature [#signature]
```ts
Sandbox(client: Leap0Client, data: SandboxData)
```
## Overview [#overview]
Bound sandbox handle with convenience methods and resource-scoped helpers.
#### Throws [#throws]
* `Leap0Error`: If API requests or response validation fail.
## Methods [#methods]
### `refresh` [#refresh]
```ts
async refresh(): Promise
```
Fetches the latest sandbox state from the API.
#### Returns [#returns]
* The refreshed sandbox handle.
#### Throws [#throws-1]
* `Leap0Error`: If fetching the sandbox fails.
### `pause` [#pause]
```ts
async pause(options?: { timeout?: number }): Promise
```
Pauses the sandbox and updates local state.
#### Parameters [#parameters]
* `options`: Optional request settings.
#### Returns [#returns-1]
* The paused sandbox handle.
#### Throws [#throws-2]
* `Leap0Error`: If pausing the sandbox fails.
### `stop` [#stop]
```ts
async stop(options?: { timeout?: number }): Promise
```
Stops the sandbox and updates local state.
#### Parameters [#parameters-1]
* `options`: Optional request settings.
#### Returns [#returns-2]
* The stopped sandbox handle.
#### Throws [#throws-3]
* `Leap0Error`: If stopping the sandbox fails.
### `start` [#start]
```ts
async start(options?: { timeout?: number }): Promise
```
Starts a previously stopped sandbox and updates local state.
#### Parameters [#parameters-2]
* `options`: Optional request settings.
#### Returns [#returns-3]
* The started sandbox handle.
#### Throws [#throws-4]
* `Leap0Error`: If starting the sandbox fails.
### `createSnapshot` [#createsnapshot]
```ts
async createSnapshot(params: CreateSnapshotParams = {}, options?: { timeout?: number })
```
Creates a snapshot from this sandbox.
#### Parameters [#parameters-3]
* `params`: Optional snapshot naming and lifecycle parameters.
* `options`: Optional request settings.
#### Returns [#returns-4]
* The created snapshot resource.
#### Throws [#throws-5]
* `Leap0Error`: If creating the snapshot fails.
### `delete` [#delete]
```ts
async delete(options?: { timeout?: number }): Promise
```
Deletes the sandbox.
#### Parameters [#parameters-4]
* `options`: Optional request settings.
#### Throws [#throws-6]
* `Leap0Error`: If deleting the sandbox fails.
### `addMount` [#addmount]
```ts
async addMount(mount: ObjectStorageMount, options?: { timeout?: number }): Promise
```
Adds an object storage mount to the sandbox.
#### Parameters [#parameters-5]
* `mount`: Object storage mount configuration.
* `options`: Optional request settings.
#### Returns [#returns-5]
* The created mount summary.
### `updateMount` [#updatemount]
```ts
async updateMount(mountID: string, mount: ObjectStorageMountUpdate, options?: { timeout?: number }): Promise
```
Updates an existing object storage mount on the sandbox.
#### Parameters [#parameters-6]
* `mountID`: Mount identifier.
* `mount`: Partial mount update payload.
* `options`: Optional request settings.
#### Returns [#returns-6]
* The updated mount summary.
### `deleteMount` [#deletemount]
```ts
async deleteMount(mountID: string, options?: { timeout?: number }): Promise
```
Deletes an object storage mount from the sandbox.
#### Parameters [#parameters-7]
* `mountID`: Mount identifier.
* `options`: Optional request settings.
### `createPresignedUrl` [#createpresignedurl]
```ts
async createPresignedUrl(params: { port: number; expiresIn?: number }, options?: { timeout?: number }): Promise
```
Creates a temporary public URL for a specific sandbox port.
#### Parameters [#parameters-8]
* `params`: Presigned URL creation parameters.
* `options`: Optional request settings.
#### Returns [#returns-7]
* The created presigned URL.
### `deletePresignedUrl` [#deletepresignedurl]
```ts
async deletePresignedUrl(id: string, options?: { timeout?: number }): Promise
```
Deletes a previously issued presigned URL.
#### Parameters [#parameters-9]
* `id`: Presigned URL identifier.
* `options`: Optional request settings.
### `invokeUrl` [#invokeurl]
```ts
invokeUrl(path = "/", port?: number): string
```
Returns the public invoke URL for the sandbox.
#### Parameters [#parameters-10]
* `path`: Route path to append.
* `port`: Optional forwarded port.
#### Returns [#returns-8]
* The public HTTPS URL.
### `websocketUrl` [#websocketurl]
```ts
websocketUrl(path = "/", port?: number): string
```
Returns the public websocket URL for the sandbox.
#### Parameters [#parameters-11]
* `path`: Route path to append.
* `port`: Optional forwarded port.
#### Returns [#returns-9]
* The public websocket URL.
### `getUserHomeDir` [#getuserhomedir]
```ts
async getUserHomeDir(options?: { timeout?: number }): Promise
```
Fetches the resolved home directory for the sandbox user.
#### Parameters [#parameters-12]
* `options`: Optional request settings.
#### Returns [#returns-10]
* The resolved sandbox user home directory.
### `getWorkdir` [#getworkdir]
```ts
async getWorkdir(options?: { timeout?: number }): Promise
```
Fetches the configured working directory for the sandbox.
#### Parameters [#parameters-13]
* `options`: Optional request settings.
#### Returns [#returns-11]
* The configured sandbox workdir.
# JavaScript SDK Reference (/reference/javascript-sdk)
## Overview [#overview]
The Leap0 JavaScript SDK is a typed Node.js client for sandbox lifecycle, files, git, process execution, PTY sessions, LSP, SSH, code interpreter, desktop automation, snapshots, and templates.
## Installation [#installation]
```text
npm install leap0
```
## Runtime [#runtime]
* Node.js 20.6.0 or newer
* ESM package
## Getting Started [#getting-started]
```ts
import { Leap0Client } from "leap0";
const client = new Leap0Client();
const sandbox = await client.sandboxes.create();
console.log(sandbox.id);
```
Use the sidebar to browse shared defaults, errors, core classes, and service clients.
# CodeInterpreterClient (/reference/javascript-sdk/services/code-interpreter-client)
Source: [`src/services/code-interpreter.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/services/code-interpreter.ts)
## Signature [#signature]
```ts
CodeInterpreterClient(transport: Leap0Transport)
```
## Overview [#overview]
Talks to the sandbox-hosted code interpreter service.
#### Throws [#throws]
* `Leap0Error`: If API calls, stream decoding, or response validation fail.
## Methods [#methods]
### `health` [#health]
```ts
async health(sandbox: SandboxRef, options: RequestOptions = {}): Promise
```
Returns whether the code interpreter service is healthy.
#### Parameters [#parameters]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns]
* Whether the code interpreter reports a healthy status.
### `createContext` [#createcontext]
```ts
async createContext(sandbox: SandboxRef, language: CodeLanguage = "python" as CodeLanguage, cwd?: string, options: RequestOptions = {}): Promise
```
Creates a reusable interpreter context.
#### Parameters [#parameters-1]
* `sandbox`: Sandbox ID or sandbox-like object.
* `language`: Interpreter language for the context.
* `cwd`: Optional working directory.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-1]
* The created interpreter context.
### `listContexts` [#listcontexts]
```ts
async listContexts(sandbox: SandboxRef, options: RequestOptions = {}): Promise
```
Lists active interpreter contexts.
#### Parameters [#parameters-2]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-2]
* The active interpreter contexts.
### `getContext` [#getcontext]
```ts
async getContext(sandbox: SandboxRef, contextId: string, options: RequestOptions = {}): Promise
```
Fetches a single interpreter context by ID.
#### Parameters [#parameters-3]
* `sandbox`: Sandbox ID or sandbox-like object.
* `contextId`: Interpreter context ID.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-3]
* The requested interpreter context.
### `deleteContext` [#deletecontext]
```ts
async deleteContext(sandbox: SandboxRef, contextId: string, options: RequestOptions = {}): Promise
```
Deletes an interpreter context by ID.
#### Parameters [#parameters-4]
* `sandbox`: Sandbox ID or sandbox-like object.
* `contextId`: Interpreter context ID.
* `options`: Optional request settings such as timeout and query params.
### `execute` [#execute]
```ts
async execute(sandbox: SandboxRef, params: { code: string; language?: CodeLanguage; contextId?: string; envVars?: Record; timeoutMs?: number; }, options: RequestOptions = {}): Promise
```
Executes code and waits for the final result.
#### Parameters [#parameters-5]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Execution parameters.
* `params.code`: Source code to execute.
* `params.language`: Optional interpreter language.
* `params.contextId`: Optional existing context ID to reuse.
* `params.envVars`: Optional environment variables for execution.
* `params.timeoutMs`: Optional execution timeout in milliseconds.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-4]
* The completed execution result.
#### Examples [#examples]
```ts
const result = await sandbox.codeInterpreter.execute({
language: "python",
code: "print('hello')",
});
```
### `executeStream` [#executestream]
```ts
async executeStream(sandbox: SandboxRef, params: { code: string; language?: CodeLanguage; contextId?: string; timeoutMs?: number; }, options: RequestOptions = {}): AsyncIterable
```
Streams code execution events until the interpreter exits.
#### Parameters [#parameters-6]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Stream execution parameters.
* `params.code`: Source code to execute.
* `params.language`: Optional interpreter language.
* `params.contextId`: Optional existing context ID to reuse.
* `params.timeoutMs`: Optional execution timeout in milliseconds.
* `options`: Optional request settings such as timeout and query params.
#### Throws [#throws-1]
* `Leap0Error`: If the stream returns malformed events or reports an execution error.
#### Examples [#examples-1]
```ts
for await (const event of sandbox.codeInterpreter.executeStream({
language: "python",
code: "print('hello')",
})) {
console.log(event);
}
```
# DesktopClient (/reference/javascript-sdk/services/desktop-client)
Source: [`src/services/desktop.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/services/desktop.ts)
## Signature [#signature]
```ts
DesktopClient(transport: Leap0Transport)
```
## Overview [#overview]
Drives the desktop sandbox APIs for browser and GUI automation.
#### Throws [#throws]
* `Leap0Error`: If API calls, stream decoding, or response validation fail.
## Methods [#methods]
### `desktopUrl` [#desktopurl]
```ts
desktopUrl(sandbox: SandboxRef): string
```
Returns the base desktop URL for opening the remote UI in a browser.
#### Parameters [#parameters]
* `sandbox`: Sandbox ID or sandbox-like object.
#### Returns [#returns]
* The base desktop URL.
### `displayInfo` [#displayinfo]
```ts
async displayInfo(sandbox: SandboxRef, options?: RequestOptions): Promise
```
Returns display metadata for the desktop session.
#### Parameters [#parameters-1]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-1]
* Desktop display metadata.
### `screen` [#screen]
```ts
async screen(sandbox: SandboxRef, options?: RequestOptions): Promise
```
Returns the currently active desktop screen geometry.
#### Parameters [#parameters-2]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-2]
* Desktop screen geometry.
### `resizeScreen` [#resizescreen]
```ts
async resizeScreen(sandbox: SandboxRef, payload: DesktopSetScreenParams, options?: RequestOptions): Promise
```
Resizes the desktop screen to the requested dimensions.
#### Parameters [#parameters-3]
* `sandbox`: Sandbox ID or sandbox-like object.
* `payload`: Screen resize parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-3]
* Updated desktop display metadata.
### `windows` [#windows]
```ts
async windows(sandbox: SandboxRef, options?: RequestOptions): Promise
```
Lists windows visible on the desktop.
#### Parameters [#parameters-4]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-4]
* The visible desktop windows.
### `screenshot` [#screenshot]
```ts
async screenshot(sandbox: SandboxRef, params: DesktopScreenshotParams = {}, options?: RequestOptions): Promise
```
Captures a screenshot and returns raw image bytes.
#### Parameters [#parameters-5]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Screenshot parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-5]
* Raw screenshot bytes.
### `screenshotRegion` [#screenshotregion]
```ts
async screenshotRegion(sandbox: SandboxRef, payload: DesktopScreenshotRegionParams, options?: RequestOptions): Promise
```
Captures a screenshot of a required rectangular region.
#### Parameters [#parameters-6]
* `sandbox`: Sandbox ID or sandbox-like object.
* `payload`: Region screenshot parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-6]
* Raw screenshot bytes.
### `pointerPosition` [#pointerposition]
```ts
async pointerPosition(sandbox: SandboxRef, options?: RequestOptions): Promise
```
Returns the current pointer position.
#### Parameters [#parameters-7]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-7]
* The current pointer position.
### `movePointer` [#movepointer]
```ts
async movePointer(sandbox: SandboxRef, params: { x: number; y: number }, options?: RequestOptions): Promise
```
Moves the desktop pointer to a coordinate.
#### Parameters [#parameters-8]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Pointer move parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-8]
* The updated pointer position.
### `click` [#click]
```ts
async click(sandbox: SandboxRef, params: DesktopClickParams = {}, options?: RequestOptions): Promise
```
Clicks the current pointer position or an explicit coordinate.
#### Parameters [#parameters-9]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Click parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-9]
* The resulting pointer position.
### `drag` [#drag]
```ts
async drag(sandbox: SandboxRef, payload: DesktopDragParams, options?: RequestOptions): Promise
```
Drags the pointer from one coordinate to another.
#### Parameters [#parameters-10]
* `sandbox`: Sandbox ID or sandbox-like object.
* `payload`: Drag parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-10]
* The resulting pointer position.
### `scroll` [#scroll]
```ts
async scroll(sandbox: SandboxRef, payload: DesktopScrollParams, options?: RequestOptions): Promise
```
Scrolls the desktop in the requested direction.
#### Parameters [#parameters-11]
* `sandbox`: Sandbox ID or sandbox-like object.
* `payload`: Scroll parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-11]
* The resulting pointer position.
### `typeText` [#typetext]
```ts
async typeText(sandbox: SandboxRef, text: string, options?: RequestOptions): Promise
```
Types text into the active desktop input target.
#### Parameters [#parameters-12]
* `sandbox`: Sandbox ID or sandbox-like object.
* `text`: Text to type.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-12]
* Whether the action succeeded.
### `pressKey` [#presskey]
```ts
async pressKey(sandbox: SandboxRef, key: string, options?: RequestOptions): Promise
```
Sends a single key press to the desktop.
#### Parameters [#parameters-13]
* `sandbox`: Sandbox ID or sandbox-like object.
* `key`: Key to press.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-13]
* Whether the action succeeded.
### `hotkey` [#hotkey]
```ts
async hotkey(sandbox: SandboxRef, keys: string[], options?: RequestOptions): Promise
```
Sends a key chord such as `Ctrl+C` or `Cmd+Shift+P`.
#### Parameters [#parameters-14]
* `sandbox`: Sandbox ID or sandbox-like object.
* `keys`: Keys to press together.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-14]
* Whether the action succeeded.
### `recordingStatus` [#recordingstatus]
```ts
async recordingStatus(sandbox: SandboxRef, options?: RequestOptions): Promise
```
Returns current desktop recording state.
#### Parameters [#parameters-15]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-15]
* The current recording state.
### `startRecording` [#startrecording]
```ts
async startRecording(sandbox: SandboxRef, options?: RequestOptions): Promise
```
Starts desktop recording.
#### Parameters [#parameters-16]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-16]
* The updated recording state.
### `stopRecording` [#stoprecording]
```ts
async stopRecording(sandbox: SandboxRef, options?: RequestOptions): Promise
```
Stops desktop recording.
#### Parameters [#parameters-17]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-17]
* The updated recording state.
### `recordings` [#recordings]
```ts
async recordings(sandbox: SandboxRef, options?: RequestOptions): Promise
```
Lists recorded desktop sessions.
#### Parameters [#parameters-18]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-18]
* Desktop recording summaries.
### `getRecording` [#getrecording]
```ts
async getRecording(sandbox: SandboxRef, id: string, options?: RequestOptions): Promise
```
Fetches metadata for a single recording.
#### Parameters [#parameters-19]
* `sandbox`: Sandbox ID or sandbox-like object.
* `id`: Recording identifier.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-19]
* The recording metadata.
### `downloadRecording` [#downloadrecording]
```ts
async downloadRecording(sandbox: SandboxRef, id: string, options?: RequestOptions): Promise
```
Downloads a recording and returns raw file bytes.
#### Parameters [#parameters-20]
* `sandbox`: Sandbox ID or sandbox-like object.
* `id`: Recording identifier.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-20]
* Raw recording file bytes.
### `deleteRecording` [#deleterecording]
```ts
async deleteRecording(sandbox: SandboxRef, id: string, options?: RequestOptions): Promise
```
Deletes a recording by ID.
#### Parameters [#parameters-21]
* `sandbox`: Sandbox ID or sandbox-like object.
* `id`: Recording identifier.
* `options`: Optional request settings such as timeout and query params.
### `health` [#health]
```ts
async health(sandbox: SandboxRef, options?: RequestOptions): Promise
```
Returns desktop service health, accepting both healthy and degraded status codes.
#### Parameters [#parameters-22]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-21]
* Desktop health information.
### `processStatus` [#processstatus]
```ts
async processStatus(sandbox: SandboxRef, options?: RequestOptions): Promise
```
Returns aggregate status for desktop-managed processes.
#### Parameters [#parameters-23]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-22]
* Aggregate process status information.
### `getProcess` [#getprocess]
```ts
async getProcess(sandbox: SandboxRef, name: string, options?: RequestOptions): Promise
```
Returns status for a named desktop-managed process.
#### Parameters [#parameters-24]
* `sandbox`: Sandbox ID or sandbox-like object.
* `name`: Process name.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-23]
* Status for the named process.
### `restartProcess` [#restartprocess]
```ts
async restartProcess(sandbox: SandboxRef, name: string, options?: RequestOptions): Promise
```
Restarts a named desktop-managed process.
#### Parameters [#parameters-25]
* `sandbox`: Sandbox ID or sandbox-like object.
* `name`: Process name.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-24]
* The restart operation result.
### `processLogs` [#processlogs]
```ts
async processLogs(sandbox: SandboxRef, name: string, options?: RequestOptions): Promise
```
Returns logs for a named desktop-managed process.
#### Parameters [#parameters-26]
* `sandbox`: Sandbox ID or sandbox-like object.
* `name`: Process name.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-25]
* Process logs.
### `processErrors` [#processerrors]
```ts
async processErrors(sandbox: SandboxRef, name: string, options?: RequestOptions): Promise
```
Returns error logs for a named desktop-managed process.
#### Parameters [#parameters-27]
* `sandbox`: Sandbox ID or sandbox-like object.
* `name`: Process name.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-26]
* Process error logs.
### `statusStream` [#statusstream]
```ts
async statusStream(sandbox: SandboxRef, options: RequestOptions = {}): AsyncIterable
```
Streams desktop process status updates.
#### Parameters [#parameters-28]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Throws [#throws-1]
* `Leap0Error`: If the stream returns malformed events or reports an error envelope.
### `waitUntilReady` [#waituntilready]
```ts
async waitUntilReady(sandbox: SandboxRef, params: { timeout?: number } = {}, options: RequestOptions = {}): Promise
```
Waits until the desktop reports a running state or all tracked processes are up.
#### Parameters [#parameters-29]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Wait parameters.
* `options`: Optional request settings such as timeout and query params.
#### Throws [#throws-2]
* `Leap0Error`: If the desktop never becomes ready or a non-retryable error occurs.
#### Examples [#examples]
```ts
await sandbox.desktop.waitUntilReady();
```
# FilesystemClient (/reference/javascript-sdk/services/filesystem-client)
Source: [`src/services/filesystem.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/services/filesystem.ts)
## Signature [#signature]
```ts
FilesystemClient(transport: Leap0Transport)
```
## Overview [#overview]
Performs filesystem operations inside a sandbox.
#### Throws [#throws]
* `Leap0Error`: If API calls or response validation fail.
## Methods [#methods]
### `ls` [#ls]
```ts
async ls(sandbox: SandboxRef, path: string, params: { recursive?: boolean; exclude?: string[] } = {}, options: RequestOptions = {}): Promise
```
Lists directory contents, optionally recursively.
#### Parameters [#parameters]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Directory path to list.
* `params`: Listing options.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns]
* The directory listing result.
### `stat` [#stat]
```ts
async stat(sandbox: SandboxRef, path: string, options: RequestOptions = {}): Promise
```
Fetches metadata for a path.
#### Parameters [#parameters-1]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Filesystem path to stat.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-1]
* The path metadata.
### `mkdir` [#mkdir]
```ts
async mkdir(sandbox: SandboxRef, path: string, params: { recursive?: boolean; permissions?: string } = {}, options: RequestOptions = {}): Promise
```
Creates a directory. Set `recursive` to create parent directories.
#### Parameters [#parameters-2]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Directory path to create.
* `params`: Directory creation options.
* `options`: Optional request settings such as timeout and query params.
### `writeBytes` [#writebytes]
```ts
async writeBytes(sandbox: SandboxRef, path: string, content: Uint8Array, params: { permissions?: string } = {}, options: RequestOptions = {}): Promise
```
Writes raw bytes to a single file path.
#### Parameters [#parameters-3]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: File path to write.
* `content`: File bytes to write.
* `params`: File write options.
* `options`: Optional request settings such as timeout and query params.
### `writeFile` [#writefile]
```ts
async writeFile(sandbox: SandboxRef, path: string, content: string, params: { permissions?: string } = {}, options: RequestOptions = {}): Promise
```
Writes UTF-8 text to a single file path.
#### Parameters [#parameters-4]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: File path to write.
* `content`: UTF-8 text content to write.
* `params`: File write options.
* `options`: Optional request settings such as timeout and query params.
### `writeFilesBytes` [#writefilesbytes]
```ts
async writeFilesBytes(sandbox: SandboxRef, files: Record, options: RequestOptions = {}): Promise
```
Writes multiple files in a single request using multipart upload.
#### Parameters [#parameters-5]
* `sandbox`: Sandbox ID or sandbox-like object.
* `files`: Files keyed by destination path.
* `options`: Optional request settings such as timeout and query params.
### `writeFiles` [#writefiles]
```ts
async writeFiles(sandbox: SandboxRef, files: Record, options: RequestOptions = {}): Promise
```
Writes multiple UTF-8 text files in a single request.
#### Parameters [#parameters-6]
* `sandbox`: Sandbox ID or sandbox-like object.
* `files`: Files keyed by destination path.
* `options`: Optional request settings such as timeout and query params.
### `readBytes` [#readbytes]
```ts
async readBytes(sandbox: SandboxRef, path: string, params: { offset?: number; limit?: number; head?: number; tail?: number } = {}, options: RequestOptions = {}): Promise
```
Reads a single file and returns its raw bytes.
#### Parameters [#parameters-7]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: File path to read.
* `params`: Read options.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-2]
* The file contents as bytes.
#### Throws [#throws-1]
* `Error`: If both `head` and `tail` are provided.
* `Leap0Error`: If the read request fails.
### `readFile` [#readfile]
```ts
async readFile(sandbox: SandboxRef, path: string, params: { offset?: number; limit?: number; head?: number; tail?: number } = {}, options: RequestOptions = {}): Promise
```
Reads a single file and returns its content decoded as text.
#### Parameters [#parameters-8]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: File path to read.
* `params`: Read options.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-3]
* The file contents decoded as text.
#### Throws [#throws-2]
* `Error`: If both `head` and `tail` are provided.
* `Leap0Error`: If the read request fails.
#### Examples [#examples]
```ts
const readme = await sandbox.filesystem.readFile("/workspace/README.md");
```
### `readFilesBytes` [#readfilesbytes]
```ts
async readFilesBytes(sandbox: SandboxRef, paths: string[], options: RequestOptions = {}): Promise>
```
Reads multiple files and returns raw bytes keyed by path.
#### Parameters [#parameters-9]
* `sandbox`: Sandbox ID or sandbox-like object.
* `paths`: File paths to read.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-4]
* File contents keyed by path.
#### Throws [#throws-3]
* `Error`: If the multipart response is malformed.
* `Leap0Error`: If the read request fails.
### `readFiles` [#readfiles]
```ts
async readFiles(sandbox: SandboxRef, paths: string[], options: RequestOptions = {}): Promise>
```
Reads multiple files and returns decoded text keyed by path.
#### Parameters [#parameters-10]
* `sandbox`: Sandbox ID or sandbox-like object.
* `paths`: File paths to read.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-5]
* Decoded file contents keyed by path.
### `delete` [#delete]
```ts
async delete(sandbox: SandboxRef, params: { path: string; recursive?: boolean }, options: RequestOptions = {}): Promise
```
Deletes a file or directory. Set `recursive` for non-empty directories.
#### Parameters [#parameters-11]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Delete parameters.
* `options`: Optional request settings such as timeout and query params.
### `setPermissions` [#setpermissions]
```ts
async setPermissions(sandbox: SandboxRef, path: string, params: { mode?: string; owner?: string; group?: string } = {}, options: RequestOptions = {}): Promise
```
Sets file mode and optionally changes owner and group.
#### Parameters [#parameters-12]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: File or directory path to update.
* `params`: Permission update parameters.
* `options`: Optional request settings such as timeout and query params.
#### Throws [#throws-4]
* `Leap0Error`: If params are invalid or the request fails.
### `glob` [#glob]
```ts
async glob(sandbox: SandboxRef, path: string, pattern: string, params: { exclude?: string[] } = {}, options: RequestOptions = {}): Promise
```
Finds file paths matching a glob pattern.
#### Parameters [#parameters-13]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Base directory to search.
* `pattern`: Glob pattern to match.
* `params`: Glob options.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-6]
* Matching file paths.
### `grep` [#grep]
```ts
async grep(sandbox: SandboxRef, path: string, pattern: string, params: { include?: string; exclude?: string[] } = {}, options: RequestOptions = {}): Promise
```
Searches for a text pattern across files in a directory.
#### Parameters [#parameters-14]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Base directory to search.
* `pattern`: Text or regex pattern to search for.
* `params`: Grep options.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-7]
* Matching search results.
### `editFile` [#editfile]
```ts
async editFile(sandbox: SandboxRef, path: string, edits: FileEdit[], options: RequestOptions = {}): Promise
```
Applies one or more find-and-replace edits to a single file.
#### Parameters [#parameters-15]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: File path to edit.
* `edits`: Edit operations to apply.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-8]
* The single-file edit result.
### `editFiles` [#editfiles]
```ts
async editFiles(sandbox: SandboxRef, params: { paths: string[]; find: string; replace?: string }, options: RequestOptions = {}): Promise
```
Replaces text across multiple files at once.
#### Parameters [#parameters-16]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Multi-file edit parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-9]
* The multi-file edit result.
### `move` [#move]
```ts
async move(sandbox: SandboxRef, params: { srcPath: string; dstPath: string; overwrite?: boolean }, options: RequestOptions = {}): Promise
```
Moves or renames a file or directory.
#### Parameters [#parameters-17]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Move parameters.
* `options`: Optional request settings such as timeout and query params.
### `copy` [#copy]
```ts
async copy(sandbox: SandboxRef, srcPath: string, dstPath: string, params: { recursive?: boolean; overwrite?: boolean } = {}, options: RequestOptions = {}): Promise
```
Copies a file or directory.
#### Parameters [#parameters-18]
* `sandbox`: Sandbox ID or sandbox-like object.
* `srcPath`: Source path.
* `dstPath`: Destination path.
* `params`: Copy options.
* `options`: Optional request settings such as timeout and query params.
### `exists` [#exists]
```ts
async exists(sandbox: SandboxRef, path: string, options: RequestOptions = {}): Promise
```
Checks whether a path exists in the sandbox.
#### Parameters [#parameters-19]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: File or directory path to check.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-10]
* Whether the path exists.
### `tree` [#tree]
```ts
async tree(sandbox: SandboxRef, path: string, params: { maxDepth?: number; exclude?: string[] } = {}, options: RequestOptions = {}): Promise
```
Gets a recursive directory tree.
#### Parameters [#parameters-20]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Root path for the tree.
* `params`: Tree options.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-11]
* The recursive tree result.
# GitClient (/reference/javascript-sdk/services/git-client)
Source: [`src/services/git.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/services/git.ts)
## Signature [#signature]
```ts
GitClient(transport: Leap0Transport)
```
## Overview [#overview]
Runs git operations inside a sandbox repository.
#### Throws [#throws]
* `Leap0Error`: If an API call fails.
* `Error`: If the service returns an unexpected empty response.
## Methods [#methods]
### `clone` [#clone]
```ts
async clone(sandbox: SandboxRef, params: { url: string; path: string; branch?: string; commitId?: string; depth?: number; username?: string; password?: string; }, options?: RequestOptions): Promise
```
Clones a git repository into the sandbox filesystem.
#### Parameters [#parameters]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Clone parameters.
* `params.url`: Repository URL to clone.
* `params.path`: Destination path inside the sandbox.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns]
* The git command result.
#### Examples [#examples]
```ts
await sandbox.git.clone({
url: "https://github.com/example/repo.git",
path: "/workspace/repo",
branch: "main",
});
```
### `status` [#status]
```ts
async status(sandbox: SandboxRef, path: string, options?: RequestOptions): Promise
```
Returns repository status information for a sandbox path.
#### Parameters [#parameters-1]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Repository path inside the sandbox.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-1]
* The git status result.
### `branches` [#branches]
```ts
async branches(sandbox: SandboxRef, params: { path: string; branchType?: "local" | "remote" | "all"; contains?: string; notContains?: string; }, options?: RequestOptions): Promise
```
Lists branches for a repository path.
#### Parameters [#parameters-2]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Branch listing parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-2]
* The git branch listing result.
### `diffUnstaged` [#diffunstaged]
```ts
async diffUnstaged(sandbox: SandboxRef, path: string, contextLines?: number, options?: RequestOptions): Promise
```
Returns the unstaged diff for a repository path.
#### Parameters [#parameters-3]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Repository path inside the sandbox.
* `contextLines`: Optional unified diff context line count.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-3]
* The git diff result.
### `diffStaged` [#diffstaged]
```ts
async diffStaged(sandbox: SandboxRef, path: string, contextLines?: number, options?: RequestOptions): Promise
```
Returns the staged diff for a repository path.
#### Parameters [#parameters-4]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Repository path inside the sandbox.
* `contextLines`: Optional unified diff context line count.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-4]
* The git diff result.
### `diff` [#diff]
```ts
async diff(sandbox: SandboxRef, path: string, target: string, contextLines?: number, options?: RequestOptions): Promise
```
Returns a diff against a target revision, branch, or commit.
#### Parameters [#parameters-5]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Repository path inside the sandbox.
* `target`: Revision, branch, or commit to diff against.
* `contextLines`: Optional unified diff context line count.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-5]
* The git diff result.
### `reset` [#reset]
```ts
async reset(sandbox: SandboxRef, path: string, options?: RequestOptions): Promise
```
Resets staged and unstaged changes for a repository path.
#### Parameters [#parameters-6]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Repository path inside the sandbox.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-6]
* The git reset result.
### `log` [#log]
```ts
async log(sandbox: SandboxRef, params: { path: string; maxCount?: number; startTimestamp?: string; endTimestamp?: string; }, options?: RequestOptions): Promise
```
Returns commit history for a repository path.
#### Parameters [#parameters-7]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Log query parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-7]
* The git log result.
### `show` [#show]
```ts
async show(sandbox: SandboxRef, path: string, revision = "HEAD", options?: RequestOptions): Promise
```
Shows a revision for a repository path.
#### Parameters [#parameters-8]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Repository path inside the sandbox.
* `revision`: Revision to show.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-8]
* The git show result.
### `createBranch` [#createbranch]
```ts
async createBranch(sandbox: SandboxRef, params: { path: string; name: string; checkout?: boolean; baseBranch?: string; }, options?: RequestOptions): Promise
```
Creates a new branch, optionally checking it out immediately.
#### Parameters [#parameters-9]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Branch creation parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-9]
* The git branch creation result.
### `checkoutBranch` [#checkoutbranch]
```ts
async checkoutBranch(sandbox: SandboxRef, params: { path: string; branch: string; create?: boolean; setUpstream?: boolean; }, options?: RequestOptions): Promise
```
Checks out an existing branch or creates one on demand.
#### Parameters [#parameters-10]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Checkout parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-10]
* The git checkout result.
### `deleteBranch` [#deletebranch]
```ts
async deleteBranch(sandbox: SandboxRef, path: string, name: string, force = false, options?: RequestOptions): Promise
```
Deletes a branch from the repository.
#### Parameters [#parameters-11]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Repository path inside the sandbox.
* `name`: Branch name to delete.
* `force`: Whether to force-delete the branch.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-11]
* The git branch deletion result.
### `add` [#add]
```ts
async add(sandbox: SandboxRef, path: string, files: string[], options?: RequestOptions): Promise
```
Adds files to the git index.
#### Parameters [#parameters-12]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Repository path inside the sandbox.
* `files`: File paths to stage.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-12]
* The git add result.
### `commit` [#commit]
```ts
async commit(sandbox: SandboxRef, params: { path: string; message: string; author?: string; email?: string; allowEmpty?: boolean; }, options?: RequestOptions): Promise
```
Creates a git commit from staged changes.
#### Parameters [#parameters-13]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Commit parameters.
* `params.path`: Repository path inside the sandbox.
* `params.message`: Commit message.
* `params.author`: Optional author name.
* `params.email`: Optional author email.
* `params.allowEmpty`: Whether to allow empty commits.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-13]
* The commit result, including the created commit ID when available.
### `push` [#push]
```ts
async push(sandbox: SandboxRef, params: { path: string; remote?: string; branch?: string; setUpstream?: boolean; username?: string; password?: string; }, options?: RequestOptions): Promise
```
Pushes local commits to a remote.
#### Parameters [#parameters-14]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Push parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-14]
* The git push result.
### `pull` [#pull]
```ts
async pull(sandbox: SandboxRef, params: { path: string; remote?: string; branch?: string; rebase?: boolean; setUpstream?: boolean; username?: string; password?: string; }, options?: RequestOptions): Promise
```
Pulls remote changes into the local repository.
#### Parameters [#parameters-15]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Pull parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-15]
* The git pull result.
# LspClient (/reference/javascript-sdk/services/lsp-client)
Source: [`src/services/lsp.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/services/lsp.ts)
## Signature [#signature]
```ts
LspClient(transport: Leap0Transport)
```
## Overview [#overview]
Starts and interacts with language servers inside a sandbox.
#### Throws [#throws]
* `Leap0Error`: If an API call fails.
* `Error`: If the service returns an unexpected empty response.
## Methods [#methods]
### `start` [#start]
```ts
async start(sandbox: SandboxRef, params: Pick, options?: RequestOptions): Promise
```
Starts a language server for a project path inside the sandbox.
#### Parameters [#parameters]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Language server start parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns]
* The language server response payload.
### `stop` [#stop]
```ts
async stop(sandbox: SandboxRef, params: Pick, options?: RequestOptions): Promise
```
Stops a previously started language server.
#### Parameters [#parameters-1]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Language server stop parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-1]
* The language server response payload.
### `didOpen` [#didopen]
```ts
async didOpen(sandbox: SandboxRef, params: LspRequestParams, options?: RequestOptions): Promise
```
Opens a document in the language server.
#### Parameters [#parameters-2]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Document open parameters.
* `options`: Optional request options.
#### Examples [#examples]
```ts
await sandbox.lsp.didOpen({
languageId: "typescript",
pathToProject: "/workspace/app",
uri: "file:///workspace/app/src/index.ts",
text: "const x = 1;",
version: 1,
});
```
### `didOpenPath` [#didopenpath]
```ts
async didOpenPath(sandbox: SandboxRef, params: Omit & { path: string }, options?: RequestOptions): Promise
```
Opens a document by filesystem path instead of a file URI.
#### Parameters [#parameters-3]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Document open parameters using a filesystem path.
* `options`: Optional request options.
### `didClose` [#didclose]
```ts
async didClose(sandbox: SandboxRef, params: Pick, options?: RequestOptions): Promise
```
Closes a previously opened document.
#### Parameters [#parameters-4]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Document close parameters.
* `options`: Optional request settings such as timeout and query params.
### `didClosePath` [#didclosepath]
```ts
async didClosePath(sandbox: SandboxRef, params: Pick & { path: string }, options?: RequestOptions): Promise
```
Closes a document by filesystem path instead of a file URI.
#### Parameters [#parameters-5]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Document close parameters using a filesystem path.
* `options`: Optional request settings such as timeout and query params.
### `completions` [#completions]
```ts
async completions(sandbox: SandboxRef, params: Pick & { line: number; character: number; }, options?: RequestOptions): Promise
```
Requests completion items at a line/character position.
#### Parameters [#parameters-6]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Completion request parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-2]
* The raw JSON-RPC response from the language server.
### `completionsPath` [#completionspath]
```ts
async completionsPath(sandbox: SandboxRef, params: Pick & { path: string; line: number; character: number; }, options?: RequestOptions): Promise
```
Requests completion items for a filesystem path.
#### Parameters [#parameters-7]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Completion request parameters using a filesystem path.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-3]
* The raw JSON-RPC response from the language server.
### `documentSymbols` [#documentsymbols]
```ts
async documentSymbols(sandbox: SandboxRef, params: Pick, options?: RequestOptions): Promise
```
Returns document symbols for an open document.
#### Parameters [#parameters-8]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Document symbol request parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-4]
* The raw JSON-RPC response from the language server.
### `documentSymbolsPath` [#documentsymbolspath]
```ts
async documentSymbolsPath(sandbox: SandboxRef, params: Pick & { path: string }, options?: RequestOptions): Promise
```
Returns document symbols for a filesystem path.
#### Parameters [#parameters-9]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Document symbol request parameters using a filesystem path.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-5]
* The raw JSON-RPC response from the language server.
# ProcessClient (/reference/javascript-sdk/services/process-client)
Source: [`src/services/process.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/services/process.ts)
## Signature [#signature]
```ts
ProcessClient(transport: Leap0Transport)
```
## Overview [#overview]
Executes one-shot commands inside a sandbox.
#### Throws [#throws]
* `Leap0Error`: If the process request or response validation fails.
## Methods [#methods]
### `execute` [#execute]
```ts
async execute(sandbox: SandboxRef, params: ExecuteProcessParams, options: RequestOptions = {}): Promise
```
Executes a one-shot command inside the sandbox.
#### Parameters [#parameters]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Command execution parameters.
* `params.command`: Command line to execute.
* `params.cwd`: Optional working directory.
* `params.timeout`: Optional command timeout in seconds.
* `params.env`: Optional environment variables applied to the spawned process.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns]
* The process exit code and collected stdout/stderr output.
#### Examples [#examples]
```ts
const result = await sandbox.process.execute({ command: "node --version" });
```
# PtyClient (/reference/javascript-sdk/services/pty-client)
Source: [`src/services/pty.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/services/pty.ts)
## Signature [#signature]
```ts
PtyClient(transport: Leap0Transport)
```
## Overview [#overview]
Creates and manages PTY sessions for interactive terminals.
#### Throws [#throws]
* `Leap0Error`: If API calls or response validation fail.
## Methods [#methods]
### `list` [#list]
```ts
async list(sandbox: SandboxRef, options: RequestOptions = {}): Promise
```
Lists PTY sessions for a sandbox.
#### Parameters [#parameters]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns]
* The PTY sessions in the sandbox.
### `create` [#create]
```ts
async create(sandbox: SandboxRef, params: CreatePtySessionParams = {}, options: RequestOptions = {}): Promise
```
Creates a PTY session.
#### Parameters [#parameters-1]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: PTY session creation parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-1]
* The created PTY session.
### `get` [#get]
```ts
async get(sandbox: SandboxRef, sessionId: string, options: RequestOptions = {}): Promise
```
Fetches a PTY session by ID.
#### Parameters [#parameters-2]
* `sandbox`: Sandbox ID or sandbox-like object.
* `sessionId`: PTY session identifier.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-2]
* The requested PTY session.
### `delete` [#delete]
```ts
async delete(sandbox: SandboxRef, sessionId: string, options: RequestOptions = {}): Promise
```
Deletes a PTY session.
#### Parameters [#parameters-3]
* `sandbox`: Sandbox ID or sandbox-like object.
* `sessionId`: PTY session identifier.
* `options`: Optional request settings such as timeout and query params.
### `resize` [#resize]
```ts
async resize(sandbox: SandboxRef, params: { sessionId: string; cols: number; rows: number }, options: RequestOptions = {}): Promise
```
Resizes an existing PTY session.
#### Parameters [#parameters-4]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Resize parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-3]
* The updated PTY session.
### `websocketUrl` [#websocketurl]
```ts
websocketUrl(sandbox: SandboxRef, sessionId: string): string
```
Returns the websocket URL for a PTY session.
#### Parameters [#parameters-5]
* `sandbox`: Sandbox ID or sandbox-like object.
* `sessionId`: PTY session identifier.
#### Returns [#returns-4]
* The PTY websocket URL.
### `websocketHeaders` [#websocketheaders]
```ts
websocketHeaders(): Record
```
Returns auth headers to use when opening the PTY websocket manually.
#### Returns [#returns-5]
* Headers required for PTY websocket authentication.
### `connect` [#connect]
```ts
connect(sandbox: SandboxRef, sessionId: string): PtyConnection
```
Opens a websocket connection for an existing PTY session.
#### Parameters [#parameters-6]
* `sandbox`: Sandbox ID or sandbox-like object.
* `sessionId`: PTY session identifier.
#### Returns [#returns-6]
* The PTY websocket connection wrapper.
#### Throws [#throws-1]
* `Leap0WebSocketError`: If subsequent websocket reads fail.
#### Examples [#examples]
```ts
const pty = sandbox.pty.connect("shell");
pty.send("ls\n");
const output = await pty.recv();
```
# PtyConnection (/reference/javascript-sdk/services/pty-connection)
Source: [`src/services/pty.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/services/pty.ts)
## Signature [#signature]
```ts
PtyConnection(socket: WebSocket)
```
## Overview [#overview]
Thin wrapper around an interactive PTY websocket connection.
#### Throws [#throws]
* `Leap0WebSocketError`: If the websocket errors or closes while receiving data.
## Methods [#methods]
### `send` [#send]
```ts
send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void
```
Sends raw data to the PTY websocket.
#### Parameters [#parameters]
* `data`: Raw payload to send.
### `recv` [#recv]
```ts
recv(): Promise
```
Waits for the next websocket message.
#### Returns [#returns]
* The next websocket payload as bytes.
#### Throws [#throws-1]
* `Leap0WebSocketError`: If the websocket errors or closes before a message arrives.
### `close` [#close]
```ts
close(): void
```
Closes the websocket connection.
# SandboxesClient (/reference/javascript-sdk/services/sandboxes-client)
Source: [`src/services/sandboxes.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/services/sandboxes.ts)
## Signature [#signature]
```ts
SandboxesClient(transport: Leap0Transport)
```
## Overview [#overview]
Creates, fetches, pauses, stops, starts, and deletes sandboxes.
#### Throws [#throws]
* `Leap0Error`: If request validation, API calls, or response validation fail.
## Methods [#methods]
### `create` [#create]
```ts
async create(params: CreateSandboxParams = {}, options: RequestOptions = {}): Promise
```
Creates a sandbox from a template and resource config.
#### Parameters [#parameters]
* `params`: Sandbox creation parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns]
* The created sandbox resource.
#### Throws [#throws-1]
* `Leap0Error`: If params are invalid, local OTEL env is missing, or sandbox creation fails.
#### Examples [#examples]
```ts
const sandbox = await client.sandboxes.create({
templateName: "base",
timeout: 1800,
});
```
### `list` [#list]
```ts
async list(params: ListSandboxesParams = {}, options: RequestOptions = {}): Promise
```
Lists sandboxes for the authenticated organization.
#### Parameters [#parameters-1]
* `params`: Optional filter, sort, and pagination parameters.
* `options`: Optional request settings such as timeout and headers.
#### Returns [#returns-1]
* Paginated sandbox summaries.
### `pause` [#pause]
```ts
async pause(sandbox: SandboxRef, options: RequestOptions = {}): Promise
```
Pauses a running sandbox.
#### Parameters [#parameters-2]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-2]
* The updated sandbox resource.
### `stop` [#stop]
```ts
async stop(sandbox: SandboxRef, options: RequestOptions = {}): Promise
```
Stops a running sandbox while preserving writable disk changes.
#### Parameters [#parameters-3]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-3]
* The updated sandbox resource.
### `start` [#start]
```ts
async start(sandbox: SandboxRef, options: RequestOptions = {}): Promise
```
Starts a previously stopped sandbox.
#### Parameters [#parameters-4]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-4]
* The current sandbox resource after start completes.
### `createSnapshot` [#createsnapshot]
```ts
async createSnapshot(sandbox: SandboxRef, params: CreateSnapshotParams = {}, options: RequestOptions = {}): Promise
```
Creates a snapshot from a running sandbox.
#### Parameters [#parameters-5]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: Optional snapshot naming parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-5]
* The created snapshot resource.
### `get` [#get]
```ts
async get(sandbox: SandboxRef, options: RequestOptions = {}): Promise
```
Fetches a sandbox by ID.
#### Parameters [#parameters-6]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-6]
* The current sandbox resource.
### `delete` [#delete]
```ts
async delete(sandbox: SandboxRef, options: RequestOptions = {}): Promise
```
Deletes a sandbox by ID.
#### Parameters [#parameters-7]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
### `addMount` [#addmount]
```ts
async addMount(sandbox: SandboxRef, mount: ObjectStorageMount, options: RequestOptions = {}): Promise
```
Adds an object storage mount to a running sandbox.
#### Parameters [#parameters-8]
* `sandbox`: Sandbox ID or sandbox-like object.
* `mount`: Object storage mount configuration.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-7]
* The created mount summary.
### `updateMount` [#updatemount]
```ts
async updateMount(sandbox: SandboxRef, mountID: string, mount: ObjectStorageMountUpdate, options: RequestOptions = {}): Promise
```
Updates an existing object storage mount on a sandbox.
#### Parameters [#parameters-9]
* `sandbox`: Sandbox ID or sandbox-like object.
* `mountID`: Mount identifier.
* `mount`: Partial mount update payload.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-8]
* The updated mount summary.
### `deleteMount` [#deletemount]
```ts
async deleteMount(sandbox: SandboxRef, mountID: string, options: RequestOptions = {}): Promise
```
Deletes an object storage mount from a sandbox.
#### Parameters [#parameters-10]
* `sandbox`: Sandbox ID or sandbox-like object.
* `mountID`: Mount identifier.
* `options`: Optional request settings such as timeout and query params.
### `getUserHomeDir` [#getuserhomedir]
```ts
async getUserHomeDir(sandbox: SandboxRef, options: RequestOptions = {}): Promise
```
Fetches the resolved home directory for the sandbox user.
#### Parameters [#parameters-11]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-9]
* The resolved sandbox user home directory.
### `getWorkdir` [#getworkdir]
```ts
async getWorkdir(sandbox: SandboxRef, options: RequestOptions = {}): Promise
```
Fetches the configured working directory for the sandbox.
#### Parameters [#parameters-12]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-10]
* The configured sandbox workdir.
### `createPresignedUrl` [#createpresignedurl]
```ts
async createPresignedUrl(sandbox: SandboxRef, params: CreatePresignedUrlParams, options: RequestOptions = {}): Promise
```
Creates a temporary public URL for a specific sandbox port.
### `deletePresignedUrl` [#deletepresignedurl]
```ts
async deletePresignedUrl(sandbox: SandboxRef, id: string, options: RequestOptions = {}): Promise
```
Deletes a previously issued presigned URL.
### `invokeUrl` [#invokeurl]
```ts
invokeUrl(sandbox: SandboxRef, path = "/", port?: number): string
```
Builds the public invoke URL for a sandbox.
#### Parameters [#parameters-13]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Route path to append to the sandbox base URL.
* `port`: Optional forwarded port.
#### Returns [#returns-11]
* The public HTTPS URL for the sandbox.
### `websocketUrl` [#websocketurl]
```ts
websocketUrl(sandbox: SandboxRef, path = "/", port?: number): string
```
Builds the public websocket URL for a sandbox.
#### Parameters [#parameters-14]
* `sandbox`: Sandbox ID or sandbox-like object.
* `path`: Route path to append to the sandbox base URL.
* `port`: Optional forwarded port.
#### Returns [#returns-12]
* The public websocket URL for the sandbox.
# SnapshotsClient (/reference/javascript-sdk/services/snapshots-client)
Source: [`src/services/snapshots.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/services/snapshots.ts)
## Signature [#signature]
```ts
SnapshotsClient(transport: Leap0Transport, sandboxFactory?: (data: SandboxData) => T)
```
## Overview [#overview]
Lists, restores, and deletes named snapshots.
#### Throws [#throws]
* `Leap0Error`: If request validation, API calls, or response validation fail.
## Methods [#methods]
### `list` [#list]
```ts
async list(params: ListSnapshotsParams = {}, options: RequestOptions = {}): Promise
```
Lists snapshots for the authenticated organization.
#### Parameters [#parameters]
* `params`: Optional filter, sort, and pagination parameters.
* `options`: Optional request settings such as timeout and headers.
#### Returns [#returns]
* Paginated snapshot summaries.
### `restore` [#restore]
```ts
async restore(params: RestoreSnapshotParams, options: RequestOptions = {}): Promise
```
Restores a sandbox from a snapshot.
#### Parameters [#parameters-1]
* `params`: Snapshot name and optional sandbox overrides.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-1]
* The restored sandbox, optionally wrapped in a custom sandbox type.
### `delete` [#delete]
```ts
async delete(snapshot: SnapshotRef, options: RequestOptions = {}): Promise
```
Deletes a snapshot by ID.
#### Parameters [#parameters-2]
* `snapshot`: Snapshot ID or snapshot-like object.
* `options`: Optional request settings such as timeout and query params.
# SshClient (/reference/javascript-sdk/services/ssh-client)
Source: [`src/services/ssh.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/services/ssh.ts)
## Signature [#signature]
```ts
SshClient(transport: Leap0Transport)
```
## Overview [#overview]
Manages SSH access credentials for a sandbox.
#### Throws [#throws]
* `Leap0Error`: If API calls or response validation fail.
## Methods [#methods]
### `createAccess` [#createaccess]
```ts
async createAccess(sandbox: SandboxRef, options: RequestOptions = {}): Promise
```
Creates SSH credentials for a sandbox.
#### Parameters [#parameters]
* `sandbox`: Sandbox ID or sandbox-like object.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns]
* The generated SSH access payload.
### `deleteAccess` [#deleteaccess]
```ts
async deleteAccess(sandbox: SandboxRef, params: { id: string }, options: RequestOptions = {}): Promise
```
Deletes a specific SSH credential for a sandbox.
#### Parameters [#parameters-1]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: SSH credential deletion parameters.
* `options`: Optional request settings such as timeout and query params.
### `validateAccess` [#validateaccess]
```ts
async validateAccess(sandbox: SandboxRef, params: { id: string; password: string }, options: RequestOptions = {}): Promise
```
Verifies a specific previously issued SSH credential pair.
#### Parameters [#parameters-2]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: SSH credential validation parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-1]
* The validation result.
### `regenerateAccess` [#regenerateaccess]
```ts
async regenerateAccess(sandbox: SandboxRef, params: { id: string }, options: RequestOptions = {}): Promise
```
Rotates a specific SSH credential for a sandbox.
#### Parameters [#parameters-3]
* `sandbox`: Sandbox ID or sandbox-like object.
* `params`: SSH credential rotation parameters.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns-2]
* The newly generated SSH access payload.
# TemplatesClient (/reference/javascript-sdk/services/templates-client)
Source: [`src/services/templates.ts`](https://github.com/leap0-dev/leap0-js/blob/main/src/services/templates.ts)
## Signature [#signature]
```ts
TemplatesClient(transport: Leap0Transport)
```
## Overview [#overview]
Uploads and manages reusable container templates.
#### Throws [#throws]
* `Leap0Error`: If request validation, API calls, or response validation fail.
## Methods [#methods]
### `create` [#create]
```ts
async create(params: CreateTemplateParams, options: RequestOptions = {}): Promise
```
Uploads a new template from a container image URI.
#### Parameters [#parameters]
* `params`: Template creation parameters.
* `params.name`: Template name to create.
* `params.uri`: Container image URI to import.
* `params.credentials`: Optional private registry credentials.
* `options`: Optional request settings such as timeout and query params.
#### Returns [#returns]
* The created template.
### `rename` [#rename]
```ts
async rename(template: TemplateRef, params: RenameTemplateParams, options: RequestOptions = {}): Promise
```
Renames a template.
#### Parameters [#parameters-1]
* `template`: Template ID or template-like object.
* `params`: New template name.
* `options`: Optional request settings such as timeout and query params.
### `delete` [#delete]
```ts
async delete(template: TemplateRef, options: RequestOptions = {}): Promise
```
Deletes a template by ID.
#### Parameters [#parameters-2]
* `template`: Template ID or template-like object.
* `options`: Optional request settings such as timeout and query params.
# AsyncCodeInterpreterClient (/reference/python-sdk/async/async-code-interpreter-client)
Source: [`leap0/_async/code_interpreter.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/code_interpreter.py)
## Signature [#signature]
```python
AsyncCodeInterpreterClient(transport: AsyncTransport, *, sandbox_domain: str | None = None)
```
## Overview [#overview]
Execute code inside a sandbox with asynchronous APIs.
Attributes:
None.
## Methods [#methods]
### `health` [#health]
```python
async health(sandbox: SandboxRef, http_timeout: float | None = None) -> bool
```
Check service health.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bool: Result returned by this operation.
### `create_context` [#create_context]
```python
async create_context(sandbox: SandboxRef, *, language: str = 'python', cwd: str | None = None, http_timeout: float | None = None) -> CodeContext
```
Create a new execution context.
Args:
sandbox: Sandbox ID or object.
language: Language runtime (e.g. `"python"`, `"typescript"`).
cwd: Working directory (default `"/home/user"`).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
CodeContext: Newly created persistent execution context.
### `list_contexts` [#list_contexts]
```python
async list_contexts(sandbox: SandboxRef, http_timeout: float | None = None) -> list[CodeContext]
```
List execution contexts.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
list\[CodeContext]: Result returned by this operation.
### `get_context` [#get_context]
```python
async get_context(sandbox: SandboxRef, context_id: str, http_timeout: float | None = None) -> CodeContext
```
Get a single execution context by ID.
Returns:
CodeContext: Matching execution context.
Args:
sandbox: Sandbox ID or object.
context\_id: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
### `delete_context` [#delete_context]
```python
async delete_context(sandbox: SandboxRef, context_id: str, http_timeout: float | None = None) -> None
```
Delete an execution context.
Args:
sandbox: Sandbox ID or object.
context\_id: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `execute` [#execute]
```python
async execute(sandbox: SandboxRef, *, code: str, language: str = 'python', context_id: str | None = None, env_vars: dict[str, str] | None = None, timeout_ms: int | None = None, http_timeout: float | None = None) -> CodeExecutionResult
```
Execute code and wait for the full result.
Args:
sandbox: Sandbox ID or object.
code: Source code to execute.
language: Language runtime (default `"python"`).
context\_id: Link to an existing context to share state. Auto-generated if omitted.
env\_vars: Environment variables for the execution.
timeout\_ms: Execution timeout in milliseconds (default 30000).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
CodeExecutionResult: Structured execution output, errors, and logs.
### `execute_stream` [#execute_stream]
```python
async execute_stream(sandbox: SandboxRef, *, code: str, language: str = 'python', context_id: str | None = None, timeout_ms: int | None = None, http_timeout: float | None = None) -> AsyncIterator[StreamEvent]
```
Execute code and stream output events via SSE.
Yields \:class:`StreamEvent` objects with type `"stdout"`,
`"stderr"`, `"exit"`, or `"error"`.
Args:
sandbox: Sandbox ID or object. code: Source code to execute. language: Language runtime for the operation. context\_id: Parameter for this operation. timeout\_ms: Execution timeout in milliseconds. http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
code: Parameter for this operation.
language: Parameter for this operation.
context\_id: Parameter for this operation.
timeout\_ms: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
AsyncIterator\[StreamEvent]: Result returned by this operation.
# AsyncDesktopClient (/reference/python-sdk/async/async-desktop-client)
Source: [`leap0/_async/desktop.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/desktop.py)
## Signature [#signature]
```python
AsyncDesktopClient(transport: AsyncTransport, *, sandbox_domain: str | None = None)
```
## Overview [#overview]
Control a sandbox desktop through asynchronous APIs.
Attributes:
None.
## Methods [#methods]
### `desktop_url` [#desktop_url]
```python
desktop_url(sandbox: SandboxRef) -> str
```
Build the browser URL for the desktop viewer.
Args:
sandbox: Sandbox ID or object.
Returns:
str: Result returned by this operation.
### `display_info` [#display_info]
```python
async display_info(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopDisplayInfo
```
Get display information for the desktop.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopDisplayInfo: Result returned by this operation.
### `screen` [#screen]
```python
async screen(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopDisplayInfo
```
Get the current desktop screen geometry.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopDisplayInfo: Result returned by this operation.
### `resize_screen` [#resize_screen]
```python
async resize_screen(sandbox: SandboxRef, *, width: int, height: int, http_timeout: float | None = None) -> DesktopDisplayInfo
```
Resize the virtual display (width: 320-7680, height: 320-4320).
Args:
sandbox: Sandbox ID or object.
width: Parameter for this operation.
height: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopDisplayInfo: Result returned by this operation.
### `windows` [#windows]
```python
async windows(sandbox: SandboxRef, http_timeout: float | None = None) -> list[DesktopWindow]
```
List open desktop windows.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
list\[DesktopWindow]: Result returned by this operation.
### `screenshot` [#screenshot]
```python
async screenshot(sandbox: SandboxRef, *, image_format: str | None = None, quality: int | None = None, x: int | None = None, y: int | None = None, width: int | None = None, height: int | None = None, http_timeout: float | None = None) -> bytes
```
Take a screenshot and return the image as bytes.
Args:
sandbox: Sandbox ID or object.
image\_format: `"png"`, `"jpg"`, or `"jpeg"` (default `"png"`).
quality: JPEG quality (1-100).
x: Left edge of capture region.
y: Top edge of capture region.
width: Region width in pixels.
height: Region height in pixels.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bytes: Result returned by this operation.
### `screenshot_region` [#screenshot_region]
```python
async screenshot_region(sandbox: SandboxRef, *, x: int, y: int, width: int, height: int, image_format: str | None = None, quality: int | None = None, http_timeout: float | None = None) -> bytes
```
Take a screenshot of a specific region and return the image as bytes.
Args:
sandbox: Sandbox ID or object.
x: Parameter for this operation.
y: Parameter for this operation.
width: Parameter for this operation.
height: Parameter for this operation.
image\_format: Parameter for this operation.
quality: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bytes: Result returned by this operation.
### `pointer_position` [#pointer_position]
```python
async pointer_position(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopPointerPosition
```
Get the current pointer position.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopPointerPosition: Result returned by this operation.
### `move_pointer` [#move_pointer]
```python
async move_pointer(sandbox: SandboxRef, *, x: int, y: int, http_timeout: float | None = None) -> DesktopPointerPosition
```
Move the mouse pointer to the given coordinates.
Args:
sandbox: Sandbox ID or object.
x: Parameter for this operation.
y: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopPointerPosition: Result returned by this operation.
### `click` [#click]
```python
async click(sandbox: SandboxRef, *, x: int | None = None, y: int | None = None, button: int | None = None, http_timeout: float | None = None) -> DesktopPointerPosition
```
Click the mouse. Clicks at the current position if coordinates are omitted.
Args:
sandbox: Sandbox ID or object.
x: X coordinate.
y: Y coordinate.
button: 1=left, 2=middle, 3=right (default 1).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopPointerPosition: Result returned by this operation.
### `drag` [#drag]
```python
async drag(sandbox: SandboxRef, *, from_x: int, from_y: int, to_x: int, to_y: int, button: int | None = None, http_timeout: float | None = None) -> DesktopPointerPosition
```
Drag from one position to another.
Args:
sandbox: Sandbox ID or object.
from\_x: Parameter for this operation.
from\_y: Parameter for this operation.
to\_x: Parameter for this operation.
to\_y: Parameter for this operation.
button: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopPointerPosition: Result returned by this operation.
### `scroll` [#scroll]
```python
async scroll(sandbox: SandboxRef, *, direction: str, amount: int | None = None, http_timeout: float | None = None) -> DesktopPointerPosition
```
Scroll the mouse wheel.
Args:
sandbox: Sandbox ID or object.
direction: `"up"`, `"down"`, `"left"`, or `"right"`.
amount: Number of scroll steps (1-100, default 1).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopPointerPosition: Result returned by this operation.
### `type_text` [#type_text]
```python
async type_text(sandbox: SandboxRef, *, text: str, http_timeout: float | None = None) -> bool
```
Type text through the desktop input service.
Args:
sandbox: Sandbox ID or object.
text: Text to type.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bool: Result returned by this operation.
### `press_key` [#press_key]
```python
async press_key(sandbox: SandboxRef, *, key: str, http_timeout: float | None = None) -> bool
```
Press a single key by X11 keysym name (e.g. `"Return"`, `"Escape"`).
Args:
sandbox: Sandbox ID or object.
key: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bool: Result returned by this operation.
### `hotkey` [#hotkey]
```python
async hotkey(sandbox: SandboxRef, *, keys: list[str], http_timeout: float | None = None) -> bool
```
Send a multi-key hotkey combination.
Args:
sandbox: Sandbox ID or object.
keys: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bool: Result returned by this operation.
### `recording_status` [#recording_status]
```python
async recording_status(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopRecordingStatus
```
Get the current screen recording status.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopRecordingStatus: Result returned by this operation.
### `start_recording` [#start_recording]
```python
async start_recording(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopRecordingStatus
```
Start desktop recording.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopRecordingStatus: Result returned by this operation.
### `stop_recording` [#stop_recording]
```python
async stop_recording(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopRecordingStatus
```
Stop the active screen recording.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopRecordingStatus: Result returned by this operation.
### `recordings` [#recordings]
```python
async recordings(sandbox: SandboxRef, http_timeout: float | None = None) -> list[DesktopRecordingSummary]
```
List saved desktop recordings.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
list\[DesktopRecordingSummary]: Result returned by this operation.
### `get_recording` [#get_recording]
```python
async get_recording(sandbox: SandboxRef, recording_id: str, http_timeout: float | None = None) -> DesktopRecordingSummary
```
Get details for a single recording.
Args:
sandbox: Sandbox ID or object.
recording\_id: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopRecordingSummary: Result returned by this operation.
### `download_recording` [#download_recording]
```python
async download_recording(sandbox: SandboxRef, recording_id: str, http_timeout: float | None = None) -> bytes
```
Download a desktop recording as bytes.
Args:
sandbox: Sandbox ID or object.
recording\_id: Recording identifier.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bytes: Result returned by this operation.
### `delete_recording` [#delete_recording]
```python
async delete_recording(sandbox: SandboxRef, recording_id: str, http_timeout: float | None = None) -> None
```
Delete a recording. Cannot delete an active recording.
Args:
sandbox: Sandbox ID or object.
recording\_id: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `health` [#health]
```python
async health(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopHealth
```
Check service health.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopHealth: Result returned by this operation.
### `process_status` [#process_status]
```python
async process_status(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopProcessStatusList
```
Get the status of all desktop processes (xvfb, xfce4, x11vnc, novnc).
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopProcessStatusList: Result returned by this operation.
### `get_process` [#get_process]
```python
async get_process(sandbox: SandboxRef, process_name: str, http_timeout: float | None = None) -> DesktopProcessStatus
```
Get status for one desktop process.
Args:
sandbox: Sandbox ID or object.
process\_name: Desktop process name.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopProcessStatus: Result returned by this operation.
### `restart_process` [#restart_process]
```python
async restart_process(sandbox: SandboxRef, process_name: str, http_timeout: float | None = None) -> DesktopProcessRestart
```
Restart a desktop process.
Args:
sandbox: Sandbox ID or object.
process\_name: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopProcessRestart: Result returned by this operation.
### `process_logs` [#process_logs]
```python
async process_logs(sandbox: SandboxRef, process_name: str, http_timeout: float | None = None) -> DesktopProcessLogs
```
Get logs for one desktop process.
Args:
sandbox: Sandbox ID or object.
process\_name: Desktop process name.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopProcessLogs: Result returned by this operation.
### `process_errors` [#process_errors]
```python
async process_errors(sandbox: SandboxRef, process_name: str, http_timeout: float | None = None) -> DesktopProcessErrors
```
Get stderr logs for a desktop process.
Args:
sandbox: Sandbox ID or object.
process\_name: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopProcessErrors: Result returned by this operation.
### `status_stream` [#status_stream]
```python
async status_stream(sandbox: SandboxRef, *, deadline: float | None = None, http_timeout: float | None = None) -> AsyncIterator[DesktopProcessStatusList]
```
Subscribe to a live SSE stream of process status updates.
Args:
sandbox: Sandbox ID or object. deadline: Absolute `time.monotonic()` deadline. When set, a \:class:`Leap0TimeoutError` is raised once the deadline is exceeded. `None` means no deadline. http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
deadline: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
AsyncIterator\[DesktopProcessStatusList]: Result returned by this operation.
### `wait_until_ready` [#wait_until_ready]
```python
async wait_until_ready(sandbox: SandboxRef, *, timeout: float = 60.0, http_timeout: float | None = None) -> None
```
Block until all desktop processes are running.
Connects to the SSE status stream and waits for the aggregate
status to become `"running"` (all four desktop processes alive).
Automatically retries the stream connection on transient errors
using exponential back-off, bounded by *timeout* seconds total.
Args:
sandbox: Sandbox ID or object.
timeout: Maximum seconds to wait (default 60).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Raises:
Leap0TimeoutError: If the desktop does not become ready within *timeout* seconds.
Returns:
None: Result returned by this operation.
# AsyncFilesystemClient (/reference/python-sdk/async/async-filesystem-client)
Source: [`leap0/_async/filesystem.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/filesystem.py)
## Signature [#signature]
```python
AsyncFilesystemClient(transport: AsyncTransport)
```
## Overview [#overview]
List, read, write, move, copy, delete, and search files inside a sandbox.
Text helpers such as \:meth:`write_file` and \:meth:`read_file` provide the
most ergonomic default API. Use the `*_bytes` variants when you need raw
binary access or want to avoid text decoding.
Attributes:
None.
## Methods [#methods]
### `ls` [#ls]
```python
async ls(sandbox: SandboxRef, *, path: str, recursive: bool = False, exclude: list[str] | None = None, http_timeout: float | None = None) -> LsResult
```
List directory entries.
Args:
sandbox: Sandbox ID or object.
path: Directory path to list.
recursive: List recursively.
exclude: Glob patterns to exclude.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
LsResult: Result returned by this operation.
### `stat` [#stat]
```python
async stat(sandbox: SandboxRef, *, path: str, http_timeout: float | None = None) -> FileInfo
```
Get metadata for a single path.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
FileInfo: Result returned by this operation.
### `mkdir` [#mkdir]
```python
async mkdir(sandbox: SandboxRef, *, path: str, recursive: bool = False, permissions: str | None = None, http_timeout: float | None = None) -> None
```
Create a directory. Set *recursive* to create parent directories.
Args:
sandbox: Sandbox ID or object.
path: Directory path to create.
recursive: Create parents as needed.
permissions: Octal permission string (e.g. `"755"`).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `write_bytes` [#write_bytes]
```python
async write_bytes(sandbox: SandboxRef, *, path: str, content: bytes, permissions: str | None = None, http_timeout: float | None = None) -> None
```
Write raw bytes to a single file path.
Args:
sandbox: Sandbox ID or object. path: Destination file path. content: Raw file bytes. permissions: Optional octal permission string.
path: Path used by this operation.
content: Parameter for this operation.
permissions: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `write_file` [#write_file]
```python
async write_file(sandbox: SandboxRef, *, path: str, content: str, encoding: str = 'utf-8', permissions: str | None = None, http_timeout: float | None = None) -> None
```
Write text to a single file path.
Args:
sandbox: Sandbox ID or object. path: Destination file path. content: Text content to write. encoding: Text encoding used before upload. permissions: Optional octal permission string.
path: Path used by this operation.
content: Parameter for this operation.
encoding: Parameter for this operation.
permissions: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call. Example: \`\`\`python await sandbox.filesystem.write\_file( path="/workspace/app.py", content="print('hello')
Returns:
None: Result returned by this operation.
### `write_files_bytes` [#write_files_bytes]
```python
async write_files_bytes(sandbox: SandboxRef, *, files: dict[str, bytes], http_timeout: float | None = None) -> None
```
Write multiple files in a single request.
Args:
sandbox: Sandbox ID or object. files: Mapping of file path to raw bytes content.
files: Files used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `write_files` [#write_files]
```python
async write_files(sandbox: SandboxRef, *, files: dict[str, str], encoding: str = 'utf-8', http_timeout: float | None = None) -> None
```
Write multiple text files in a single request.
Args:
sandbox: Sandbox ID or object.
files: Mapping of file path to text content.
encoding: Text encoding used before upload.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `read_bytes` [#read_bytes]
```python
async read_bytes(sandbox: SandboxRef, *, path: str, offset: int | None = None, limit: int | None = None, head: int | None = None, tail: int | None = None, http_timeout: float | None = None) -> bytes
```
Read a single file and return its raw bytes.
Args:
sandbox: Sandbox ID or object.
path: Path to the file.
offset: Byte offset to start from.
limit: Maximum bytes to read.
head: Return only the first N lines (mutually exclusive with *tail*).
tail: Return only the last N lines (mutually exclusive with *head*).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bytes: File contents as raw bytes.
Example: `python content = await sandbox.filesystem.read_bytes(path="/workspace/logo.png") print(content) `
### `read_file` [#read_file]
```python
async read_file(sandbox: SandboxRef, *, path: str, offset: int | None = None, limit: int | None = None, head: int | None = None, tail: int | None = None, encoding: str = 'utf-8', http_timeout: float | None = None) -> str
```
Read a single file and return its content decoded as text.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
offset: Parameter for this operation.
limit: Parameter for this operation.
head: Parameter for this operation.
tail: Parameter for this operation.
encoding: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
str: Result returned by this operation.
### `read_files_bytes` [#read_files_bytes]
```python
async read_files_bytes(sandbox: SandboxRef, *, paths: list[str], http_timeout: float | None = None) -> dict[str, bytes]
```
Read multiple files and return raw bytes keyed by path.
Args:
sandbox: Sandbox ID or object.
paths: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
dict\[str, bytes]: Result returned by this operation.
### `read_files` [#read_files]
```python
async read_files(sandbox: SandboxRef, *, paths: list[str], encoding: str = 'utf-8', http_timeout: float | None = None) -> dict[str, str]
```
Read multiple files and return decoded text keyed by path.
Args:
sandbox: Sandbox ID or object.
paths: File paths to read.
encoding: Text encoding used to decode each file.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
dict\[str, str]: Mapping of file path to decoded text content.
### `delete` [#delete]
```python
async delete(sandbox: SandboxRef, *, path: str, recursive: bool = False, http_timeout: float | None = None) -> None
```
Delete a file or directory.
Args:
sandbox: Sandbox ID or object.
path: Path to delete.
recursive: Required when deleting a non-empty directory.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `set_permissions` [#set_permissions]
```python
async set_permissions(sandbox: SandboxRef, *, path: str, mode: str | None = None, owner: str | None = None, group: str | None = None, http_timeout: float | None = None) -> None
```
Set file mode and optionally change owner and group.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
mode: Parameter for this operation.
owner: Parameter for this operation.
group: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `glob` [#glob]
```python
async glob(sandbox: SandboxRef, *, path: str, pattern: str, exclude: list[str] | None = None, http_timeout: float | None = None) -> list[str]
```
Find file paths matching a glob pattern.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
pattern: Parameter for this operation.
exclude: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
list\[str]: Matching file paths.
### `grep` [#grep]
```python
async grep(sandbox: SandboxRef, *, path: str, pattern: str, include: str | None = None, exclude: list[str] | None = None, http_timeout: float | None = None) -> list[SearchMatch]
```
Search for a text pattern across files in a directory.
Args:
sandbox: Sandbox ID or object.
path: Base directory to search from.
pattern: Text pattern to search for.
include: File pattern filter (e.g. `"*.py"`).
exclude: Glob patterns to exclude.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
list\[SearchMatch]: Matching lines with file and line metadata.
### `edit_file` [#edit_file]
```python
async edit_file(sandbox: SandboxRef, *, path: str, edits: list[FileEdit], http_timeout: float | None = None) -> EditFileResult
```
Apply one or more find-and-replace edits to a single file.
Returns:
EditFileResult: Unified diff and replacement count.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
edits: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
### `edit_files` [#edit_files]
```python
async edit_files(sandbox: SandboxRef, *, paths: list[str], find: str, replace: str = '', http_timeout: float | None = None) -> list[EditResult]
```
Replace text across multiple files at once.
Args:
sandbox: Sandbox ID or object.
paths: Parameter for this operation.
find: Parameter for this operation.
replace: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
list\[EditResult]: Per-file edit results.
### `move` [#move]
```python
async move(sandbox: SandboxRef, *, src_path: str, dst_path: str, overwrite: bool = False, http_timeout: float | None = None) -> None
```
Move or rename a file or directory.
Args:
sandbox: Sandbox ID or object.
src\_path: Parameter for this operation.
dst\_path: Parameter for this operation.
overwrite: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `copy` [#copy]
```python
async copy(sandbox: SandboxRef, *, src_path: str, dst_path: str, recursive: bool = False, overwrite: bool | None = None, http_timeout: float | None = None) -> None
```
Copy a file or directory.
Args:
sandbox: Sandbox ID or object.
src\_path: Source path.
dst\_path: Destination path.
recursive: Required when copying a directory.
overwrite: Overwrite the destination if it already exists.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `exists` [#exists]
```python
async exists(sandbox: SandboxRef, *, path: str, http_timeout: float | None = None) -> bool
```
Check whether a path exists in the sandbox.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bool: `True` when the path exists.
### `tree` [#tree]
```python
async tree(sandbox: SandboxRef, *, path: str, max_depth: int | None = None, exclude: list[str] | None = None, http_timeout: float | None = None) -> TreeResult
```
Get a recursive directory tree.
Args:
sandbox: Sandbox ID or object.
path: Root directory path.
max\_depth: Maximum traversal depth.
exclude: Glob patterns to exclude.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
TreeResult: Recursive directory tree rooted at `path`.
# AsyncGitClient (/reference/python-sdk/async/async-git-client)
Source: [`leap0/_async/git.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/git.py)
## Signature [#signature]
```python
AsyncGitClient(transport: AsyncTransport)
```
## Overview [#overview]
Clone repositories, inspect diffs and history, manage branches, stage
files, commit, push, and pull inside a running sandbox.
This client is useful when you want to automate Git workflows without
shelling out manually through \:class:`ProcessClient`.
Attributes:
None.
## Methods [#methods]
### `clone` [#clone]
```python
async clone(sandbox: SandboxRef, *, url: str, path: str, branch: str | None = None, commit_id: str | None = None, depth: int | None = None, username: str | None = None, password: str | None = None, http_timeout: float | None = None) -> GitResult
```
Clone a remote repository into the sandbox.
Args:
sandbox: Sandbox ID or object.
url: Repository URL.
path: Destination path inside the sandbox.
branch: Branch to clone.
commit\_id: Specific commit to checkout after cloning.
depth: Shallow clone depth.
username: Auth username (for private repos).
password: Auth password or token (for private repos).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Command output and exit status from the clone operation.
### `status` [#status]
```python
async status(sandbox: SandboxRef, *, path: str, http_timeout: float | None = None) -> GitResult
```
Get the current repository status.
Returns:
GitResult: Git status output and exit status.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
### `branches` [#branches]
```python
async branches(sandbox: SandboxRef, *, path: str, branch_type: str = 'local', contains: str | None = None, not_contains: str | None = None, http_timeout: float | None = None) -> GitResult
```
List branches in the repository.
Args:
sandbox: Sandbox ID or object.
path: Path to the git repo.
branch\_type: Filter by `"local"`, `"remote"`, or `"all"`.
contains: Only branches containing this commit SHA.
not\_contains: Exclude branches containing this commit SHA.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `diff_unstaged` [#diff_unstaged]
```python
async diff_unstaged(sandbox: SandboxRef, *, path: str, context_lines: int | None = None, http_timeout: float | None = None) -> GitResult
```
Show working tree changes that are not staged yet.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
context\_lines: Number of context lines to include.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `diff_staged` [#diff_staged]
```python
async diff_staged(sandbox: SandboxRef, *, path: str, context_lines: int | None = None, http_timeout: float | None = None) -> GitResult
```
Show changes that are already staged for the next commit.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
context\_lines: Number of context lines to include.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `diff` [#diff]
```python
async diff(sandbox: SandboxRef, *, path: str, target: str, context_lines: int | None = None, http_timeout: float | None = None) -> GitResult
```
Compare the current state against a branch, tag, or commit.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
target: Branch, tag, or commit to compare against.
context\_lines: Number of context lines to include.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `reset` [#reset]
```python
async reset(sandbox: SandboxRef, *, path: str) -> GitResult
```
Unstage all currently staged changes.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
Returns:
GitResult: Result returned by this operation.
### `log` [#log]
```python
async log(sandbox: SandboxRef, *, path: str, max_count: int | None = None, start_timestamp: str | None = None, end_timestamp: str | None = None, http_timeout: float | None = None) -> GitResult
```
Show commit history with optional limits and date filters.
Args:
sandbox: Sandbox ID or object.
path: Path to the git repo.
max\_count: Maximum number of commits to return (default 10).
start\_timestamp: Start timestamp filter.
end\_timestamp: End timestamp filter.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `show` [#show]
```python
async show(sandbox: SandboxRef, *, path: str, revision: str = 'HEAD') -> GitResult
```
Show the full output for a commit, branch, or tag revision.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
revision: Parameter for this operation.
Returns:
GitResult: Result returned by this operation.
### `create_branch` [#create_branch]
```python
async create_branch(sandbox: SandboxRef, *, path: str, name: str, checkout: bool | None = None, base_branch: str | None = None, http_timeout: float | None = None) -> GitResult
```
Create a new branch.
Args:
sandbox: Sandbox ID or object.
path: Path to the git repo.
name: New branch name.
checkout: Switch to the new branch immediately.
base\_branch: Branch from a specific revision.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `checkout_branch` [#checkout_branch]
```python
async checkout_branch(sandbox: SandboxRef, *, path: str, branch: str, create: bool | None = None, http_timeout: float | None = None) -> GitResult
```
Switch to an existing branch. Set *create* to create it if it does not exist.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
branch: Branch name.
create: Create the branch if it does not exist.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `delete_branch` [#delete_branch]
```python
async delete_branch(sandbox: SandboxRef, *, path: str, name: str, force: bool = False) -> GitResult
```
Delete a branch. Set *force* to delete even if unmerged.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
name: Name used by this operation.
force: Parameter for this operation.
Returns:
GitResult: Result returned by this operation.
### `add` [#add]
```python
async add(sandbox: SandboxRef, *, path: str, files: list[str], http_timeout: float | None = None) -> GitResult
```
Stage files for the next commit.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
files: Files used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `commit` [#commit]
```python
async commit(sandbox: SandboxRef, *, path: str, message: str, author: str | None = None, email: str | None = None, allow_empty: bool | None = None, http_timeout: float | None = None) -> GitCommitResult
```
Create a commit from staged changes.
Args:
sandbox: Sandbox ID or object.
path: Path to the git repo.
message: Commit message.
author: Author name.
email: Author email.
allow\_empty: Allow creating an empty commit.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitCommitResult: Commit result including commit ID when successful.
### `push` [#push]
```python
async push(sandbox: SandboxRef, *, path: str, remote: str | None = None, branch: str | None = None, set_upstream: bool | None = None, username: str | None = None, password: str | None = None, http_timeout: float | None = None) -> GitResult
```
Push commits to a remote.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
remote: Parameter for this operation.
branch: Parameter for this operation.
set\_upstream: Parameter for this operation.
username: Parameter for this operation.
password: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `pull` [#pull]
```python
async pull(sandbox: SandboxRef, *, path: str, remote: str | None = None, branch: str | None = None, rebase: bool | None = None, set_upstream: bool | None = None, username: str | None = None, password: str | None = None, http_timeout: float | None = None) -> GitResult
```
Pull commits from a remote. Set *rebase* to rebase instead of merge.
Args:
sandbox: Sandbox ID or object.
path: Path to the git repo.
remote: Remote name (default `"origin"`).
branch: Branch name.
rebase: Rebase instead of merge.
set\_upstream: Set upstream tracking.
username: Auth username.
password: Auth password or token.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
# AsyncLeap0Client (/reference/python-sdk/async/async-leap0-client)
Source: [`leap0/_async/client.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/client.py)
## Signature [#signature]
```python
AsyncLeap0Client(*, config: Leap0Config | None = None, api_key: str | None = None, base_url: str | None = None, sandbox_domain: str | None = None, timeout: float = DEFAULT_CLIENT_TIMEOUT, auth_header: str = 'authorization', bearer: bool = True, sdk_otel_enabled: bool | None = None)
```
## Overview [#overview]
Top-level asynchronous client for the Leap0 API.
Use this client to create sandboxes and access top-level control-plane
services. Sandbox-scoped services are exposed through bound sandbox objects.
Attributes:
sandboxes: Client for sandbox lifecycle operations.
snapshots: Client for snapshot lifecycle operations.
templates: Client for template management.
## Methods [#methods]
### `get_sandbox` [#get_sandbox]
```python
async get_sandbox(sandbox_id: str) -> AsyncSandbox
```
Get a sandbox by ID.
Args:
sandbox\_id: Sandbox identifier.
Returns:
AsyncSandbox: Sandbox object with bound service clients.
### `create_sandbox` [#create_sandbox]
```python
async create_sandbox(**kwargs: object) -> AsyncSandbox
```
Create a sandbox.
Args:
kwargs: Parameter for this operation.
Returns:
AsyncSandbox: Sandbox object with bound service clients.
### `close` [#close]
```python
async close() -> None
```
Close the client and release resources.
Returns:
None: Result returned by this operation.
# AsyncLspClient (/reference/python-sdk/async/async-lsp-client)
Source: [`leap0/_async/lsp.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/lsp.py)
## Signature [#signature]
```python
AsyncLspClient(transport: AsyncTransport)
```
## Overview [#overview]
Start and interact with language servers for code intelligence inside
a sandbox.
Supported languages: Python (pyright) and TypeScript/JavaScript
(typescript-language-server).
The typical flow is `start` -> `did_open` -> `completions` or
`document_symbols` -> `did_close` -> `stop`.
Attributes:
None.
## Methods [#methods]
### `start` [#start]
```python
async start(sandbox: SandboxRef, *, language_id: str, path_to_project: str) -> LspResponse
```
Start the LSP server for a language and project.
Spawns the server process and sends the LSP `initialize` handshake
automatically.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier (`"python"`, `"typescript"`, or `"javascript"`).
path\_to\_project: Project directory path inside the sandbox.
Returns:
LspResponse: Server startup result.
### `stop` [#stop]
```python
async stop(sandbox: SandboxRef, *, language_id: str, path_to_project: str) -> LspResponse
```
Send `shutdown` and `exit` to the language server and terminate it.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
Returns:
LspResponse: Result returned by this operation.
### `did_open` [#did_open]
```python
async did_open(sandbox: SandboxRef, *, language_id: str, path_to_project: str, uri: str, text: str | None = None, version: int = 1, http_timeout: float | None = None) -> None
```
Notify the language server that a document was opened.
Must be called before requesting completions or symbols.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
uri: Document URI.
text: Parameter for this operation.
version: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `did_open_path` [#did_open_path]
```python
async did_open_path(sandbox: SandboxRef, *, language_id: str, path_to_project: str, path: str, text: str | None = None, version: int = 1, http_timeout: float | None = None) -> None
```
Like \:meth:`did_open` but accepts a file path instead of a URI.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
path: Path used by this operation.
text: Full document text.
version: Document version number.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `did_close` [#did_close]
```python
async did_close(sandbox: SandboxRef, *, language_id: str, path_to_project: str, uri: str, http_timeout: float | None = None) -> None
```
Notify the language server that a document was closed.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
uri: Document URI.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `did_close_path` [#did_close_path]
```python
async did_close_path(sandbox: SandboxRef, *, language_id: str, path_to_project: str, path: str, http_timeout: float | None = None) -> None
```
Like \:meth:`did_close` but accepts a file path instead of a URI.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
path: Path used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `completions` [#completions]
```python
async completions(sandbox: SandboxRef, *, language_id: str, path_to_project: str, uri: str, line: int, character: int, http_timeout: float | None = None) -> LspJsonRpcResponse
```
Request completions from the language server.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
uri: Document URI.
line: Zero-based line number.
character: Zero-based character offset.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
LspJsonRpcResponse: Raw JSON-RPC response payload.
### `completions_path` [#completions_path]
```python
async completions_path(sandbox: SandboxRef, *, language_id: str, path_to_project: str, path: str, line: int, character: int, http_timeout: float | None = None) -> LspJsonRpcResponse
```
Like \:meth:`completions` but accepts a file path instead of a URI.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
path: Path used by this operation.
line: Zero-based line number.
character: Zero-based character offset.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
LspJsonRpcResponse: Result returned by this operation.
### `document_symbols` [#document_symbols]
```python
async document_symbols(sandbox: SandboxRef, *, language_id: str, path_to_project: str, uri: str, http_timeout: float | None = None) -> LspJsonRpcResponse
```
Request document symbols from the language server.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
uri: Document URI.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
LspJsonRpcResponse: Raw JSON-RPC response payload.
### `document_symbols_path` [#document_symbols_path]
```python
async document_symbols_path(sandbox: SandboxRef, *, language_id: str, path_to_project: str, path: str, http_timeout: float | None = None) -> LspJsonRpcResponse
```
Like \:meth:`document_symbols` but accepts a file path instead of a URI.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
path: Path used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
LspJsonRpcResponse: Result returned by this operation.
# AsyncProcessClient (/reference/python-sdk/async/async-process-client)
Source: [`leap0/_async/process.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/process.py)
## Signature [#signature]
```python
AsyncProcessClient(transport: AsyncTransport)
```
## Overview [#overview]
Execute one-shot shell commands inside a running sandbox.
Use this client for non-interactive command execution where you want the
full result back as a single response.
Attributes:
None.
## Methods [#methods]
### `execute` [#execute]
```python
async execute(sandbox: SandboxRef, *, command: str, cwd: str | None = None, env: dict[str, str] | None = None, timeout: int | None = None) -> ProcessResult
```
Run a shell command and wait for the result.
The command runs inside `/bin/sh -c`.
Args:
sandbox: Sandbox ID or object.
command: Shell command to execute.
cwd: Working directory.
env: Optional environment variables applied to the spawned process.
timeout: Timeout in seconds (default 30).
Returns:
ProcessResult: Command result including exit code, stdout, and stderr.
Example: `python result = await sandbox.process.execute( command="ls -la /workspace", ) print(result.stdout) print(result.stderr) `
# AsyncPtyClient (/reference/python-sdk/async/async-pty-client)
Source: [`leap0/_async/pty.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/pty.py)
## Signature [#signature]
```python
AsyncPtyClient(transport: AsyncTransport)
```
## Overview [#overview]
Create and connect to PTY sessions asynchronously.
Attributes:
None.
## Methods [#methods]
### `list` [#list]
```python
async list(sandbox: SandboxRef) -> list[PtySession]
```
List PTY sessions for a sandbox.
Args:
sandbox: Sandbox ID or object.
Returns:
list\[PtySession]: Result returned by this operation.
### `create` [#create]
```python
async create(sandbox: SandboxRef, *, session_id: str | None = None, cols: int | None = None, rows: int | None = None, cwd: str | None = None, envs: dict[str, str] | None = None, lazy_start: bool | None = None, http_timeout: float | None = None) -> PtySession
```
Create a terminal session with a shell process.
Args:
sandbox: Sandbox ID or object.
session\_id: Session ID. Auto-generated if omitted.
cols: Terminal columns.
rows: Terminal rows.
cwd: Starting directory.
envs: Environment variables.
lazy\_start: Defer shell start until the first WebSocket connection.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
PtySession: Metadata for the created PTY session.
### `get` [#get]
```python
async get(sandbox: SandboxRef, session_id: str) -> PtySession
```
Get an object by ID or identifier.
Args:
sandbox: Sandbox ID or object.
session\_id: PTY session identifier.
Returns:
PtySession: Result returned by this operation.
### `delete` [#delete]
```python
async delete(sandbox: SandboxRef, session_id: str, http_timeout: float | None = None) -> None
```
Kill the shell process and remove the session.
Args:
sandbox: Sandbox ID or object.
session\_id: PTY session identifier.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `resize` [#resize]
```python
async resize(sandbox: SandboxRef, session_id: str, *, cols: int, rows: int) -> PtySession
```
Resize a PTY session.
Args:
sandbox: Sandbox ID or object.
session\_id: PTY session identifier.
cols: Parameter for this operation.
rows: Parameter for this operation.
Returns:
PtySession: Result returned by this operation.
### `websocket_url` [#websocket_url]
```python
websocket_url(sandbox: SandboxRef, session_id: str) -> str
```
Build a websocket URL for this sandbox.
Args:
sandbox: Sandbox ID or object.
session\_id: PTY session identifier.
Returns:
str: Result returned by this operation.
### `connect` [#connect]
```python
async connect(sandbox: SandboxRef, session_id: str, open_timeout: float | None = None, http_timeout: float | None = None, **kwargs: Any) -> AsyncPtyConnection
```
Open a WebSocket connection for interactive terminal I/O.
Important:
Callers are responsible for closing the returned connection, ideally
with `try/finally` or an async context manager wrapper.
Args:
sandbox: Sandbox ID or object.
session\_id: PTY session identifier.
open\_timeout: Optional WebSocket open timeout in seconds.
http\_timeout: Deprecated alias for `open_timeout`.
kwargs: Parameter for this operation.
Returns:
AsyncPtyConnection: Open WebSocket-backed PTY connection.
# AsyncSandbox (/reference/python-sdk/async/async-sandbox)
Source: [`leap0/_async/sandbox.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/sandbox.py)
## Signature [#signature]
```python
AsyncSandbox(client: 'AsyncLeap0Client', data: SandboxData | SandboxStatus)
```
## Overview [#overview]
Sandbox object with bound asynchronous service clients.
Attributes:
filesystem: Bound filesystem client.
git: Bound git client.
process: Bound process client.
pty: Bound PTY client.
lsp: Bound LSP client.
ssh: Bound SSH client.
code\_interpreter: Bound code interpreter client.
desktop: Bound desktop client.
## Methods [#methods]
### `refresh` [#refresh]
```python
async refresh() -> AsyncSandbox
```
Refresh this sandbox object with the latest metadata.
Returns:
AsyncSandbox: This sandbox object with refreshed metadata.
### `pause` [#pause]
```python
async pause(http_timeout: float | None = None) -> AsyncSandbox
```
Pause the sandbox and return updated metadata.
Args:
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
AsyncSandbox: This sandbox object with updated metadata.
### `stop` [#stop]
```python
async stop(http_timeout: float | None = None) -> AsyncSandbox
```
Stop the sandbox and return updated metadata.
Args:
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
AsyncSandbox: This sandbox object with updated metadata.
### `start` [#start]
```python
async start(http_timeout: float | None = None) -> AsyncSandbox
```
Start a previously stopped sandbox and return updated metadata.
Args:
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
AsyncSandbox: This sandbox object with updated metadata.
### `create_snapshot` [#create_snapshot]
```python
async create_snapshot(*, name: str | None = None, kill_sandbox_after: bool = False, http_timeout: float | None = None) -> Snapshot
```
Create a snapshot from this sandbox.
Args:
name: Optional snapshot name. Auto-generated if omitted.
kill\_sandbox\_after: Terminate the source sandbox after the snapshot is stored.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
Snapshot: Created snapshot metadata.
### `delete` [#delete]
```python
async delete(http_timeout: float | None = None) -> None
```
Terminate and delete a sandbox.
Args:
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `create_presigned_url` [#create_presigned_url]
```python
async create_presigned_url(*, port: int, expires_in: int | None = None, http_timeout: float | None = None) -> PresignedURL
```
Create a temporary public URL for a specific sandbox port.
Returns:
PresignedURL: Result returned by this operation.
### `delete_presigned_url` [#delete_presigned_url]
```python
async delete_presigned_url(presigned_url_id: str, http_timeout: float | None = None) -> None
```
Delete a previously issued presigned URL.
Returns:
None: Result returned by this operation.
### `invoke_url` [#invoke_url]
```python
invoke_url(path: str = '/', *, port: int | None = None) -> str
```
Build an HTTPS URL for this sandbox.
Args:
path: Request path inside the sandbox application.
port: Port number for the generated URL.
Returns:
str: Sandbox-scoped HTTPS URL.
### `websocket_url` [#websocket_url]
```python
websocket_url(path: str = '/', *, port: int | None = None) -> str
```
Build a websocket URL for this sandbox.
Args:
path: Request path inside the sandbox application.
port: Port number for the generated URL.
Returns:
str: Sandbox-scoped websocket URL.
### `get_user_home_dir` [#get_user_home_dir]
```python
async get_user_home_dir(http_timeout: float | None = None) -> str
```
Fetch the resolved home directory for the sandbox user.
Returns:
str: Result returned by this operation.
### `get_workdir` [#get_workdir]
```python
async get_workdir(http_timeout: float | None = None) -> str
```
Fetch the configured working directory for the sandbox.
Returns:
str: Result returned by this operation.
### `add_mount` [#add_mount]
```python
async add_mount(mount: ObjectStorageMountRequestDict, http_timeout: float | None = None) -> ObjectStorageMount
```
Attach an object storage mount to this sandbox.
Returns:
ObjectStorageMount: Result returned by this operation.
### `update_mount` [#update_mount]
```python
async update_mount(mount_id: str, mount: ObjectStorageMountUpdateDict, http_timeout: float | None = None) -> ObjectStorageMount
```
Update an existing object storage mount on this sandbox.
Returns:
ObjectStorageMount: Result returned by this operation.
### `delete_mount` [#delete_mount]
```python
async delete_mount(mount_id: str, http_timeout: float | None = None) -> None
```
Delete an object storage mount from this sandbox.
Returns:
None: Result returned by this operation.
# AsyncSandboxesClient (/reference/python-sdk/async/async-sandboxes-client)
Source: [`leap0/_async/sandbox.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/sandbox.py)
## Signature [#signature]
```python
AsyncSandboxesClient(transport: AsyncTransport, *, sandbox_domain: str | None = None, sandbox_factory: SandboxFactory[SandboxData | SandboxStatus, AsyncSandboxT] | None = None)
```
## Overview [#overview]
Create, inspect, pause, stop, start, and delete sandboxes asynchronously.
Attributes:
None.
## Methods [#methods]
### `create` [#create]
```python
async create(*, template_name: str = DEFAULT_TEMPLATE_NAME, vcpu: int = DEFAULT_VCPU, memory: int = DEFAULT_MEMORY_MIB, timeout: int = DEFAULT_TIMEOUT, auto_pause: bool = False, otel_export: bool = False, env_vars: dict[str, str] | None = None, network_policy: NetworkPolicyDict | None = None, mounts: list[ObjectStorageMountRequestDict] | None = None, http_timeout: float | None = None) -> AsyncSandboxT | SandboxData | SandboxStatus
```
Create a new sandbox from a template.
Args:
template\_name: Name of the template to use.
vcpu: Number of virtual CPUs (1 to 8).
memory: Memory in MiB (512 to 8192, must be even).
timeout: Sandbox timeout in seconds (1 to 28800).
auto\_pause: Whether the sandbox should auto-pause on timeout.
otel\_export: Inject OpenTelemetry exporter environment into the sandbox. Requires `OTEL_EXPORTER_OTLP_ENDPOINT` in the local environment and also forwards `OTEL_EXPORTER_OTLP_HEADERS` when present.
env\_vars: Environment variables to set inside the sandbox.
network\_policy: Outbound network policy for the sandbox.
mounts: Object storage mounts to attach before boot.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
AsyncSandboxT | SandboxData | SandboxStatus: Created sandbox object.
### `list` [#list]
```python
async list(*, state: str | None = None, sort: str = 'created_at', order_by: str = 'desc', page: int = 1, page_size: int = 20, http_timeout: float | None = None) -> SandboxListResponse
```
List sandboxes for the authenticated organization.
Args:
state: Optional sandbox state filter.
sort: Sort field, either `created_at` or `state`.
order\_by: Sort direction, either `asc` or `desc`.
page: 1-based page number.
page\_size: Page size between 1 and 100.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SandboxListResponse: Paginated sandbox summaries.
### `pause` [#pause]
```python
async pause(sandbox: SandboxRef, http_timeout: float | None = None) -> AsyncSandboxT | SandboxData | SandboxStatus
```
Pause the sandbox and return updated metadata.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
AsyncSandboxT | SandboxData | SandboxStatus: Updated sandbox object.
### `stop` [#stop]
```python
async stop(sandbox: SandboxRef, http_timeout: float | None = None) -> AsyncSandboxT | SandboxData | SandboxStatus
```
Stop a running sandbox while preserving writable disk changes.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
AsyncSandboxT | SandboxData | SandboxStatus: Updated sandbox object.
### `start` [#start]
```python
async start(sandbox: SandboxRef, http_timeout: float | None = None) -> AsyncSandboxT | SandboxData | SandboxStatus
```
Start a previously stopped sandbox.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
AsyncSandboxT | SandboxData | SandboxStatus: Updated sandbox object.
### `create_snapshot` [#create_snapshot]
```python
async create_snapshot(sandbox: SandboxRef, *, name: str | None = None, kill_sandbox_after: bool = False, http_timeout: float | None = None) -> Snapshot
```
Create a snapshot from a running sandbox.
Returns:
Snapshot: Result returned by this operation.
### `get` [#get]
```python
async get(sandbox: SandboxRef, http_timeout: float | None = None) -> AsyncSandboxT | SandboxData | SandboxStatus
```
Get the latest sandbox metadata.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
AsyncSandboxT | SandboxData | SandboxStatus: Current sandbox object.
### `delete` [#delete]
```python
async delete(sandbox: SandboxRef, http_timeout: float | None = None) -> None
```
Terminate and delete a sandbox.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `get_user_home_dir` [#get_user_home_dir]
```python
async get_user_home_dir(sandbox: SandboxRef, http_timeout: float | None = None) -> str
```
Get the resolved home directory for the sandbox user.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
str: Resolved sandbox user home directory.
### `get_workdir` [#get_workdir]
```python
async get_workdir(sandbox: SandboxRef, http_timeout: float | None = None) -> str
```
Get the configured working directory for the sandbox.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
str: Configured sandbox workdir.
### `create_presigned_url` [#create_presigned_url]
```python
async create_presigned_url(sandbox: SandboxRef, *, port: int, expires_in: int | None = None, http_timeout: float | None = None) -> PresignedURL
```
Returns:
PresignedURL: Result returned by this operation.
### `delete_presigned_url` [#delete_presigned_url]
```python
async delete_presigned_url(sandbox: SandboxRef, presigned_url_id: str, http_timeout: float | None = None) -> None
```
Returns:
None: Result returned by this operation.
### `add_mount` [#add_mount]
```python
async add_mount(sandbox: SandboxRef, mount: ObjectStorageMountRequestDict, http_timeout: float | None = None) -> ObjectStorageMount
```
Returns:
ObjectStorageMount: Result returned by this operation.
### `update_mount` [#update_mount]
```python
async update_mount(sandbox: SandboxRef, mount_id: str, mount: ObjectStorageMountUpdateDict, http_timeout: float | None = None) -> ObjectStorageMount
```
Returns:
ObjectStorageMount: Result returned by this operation.
### `delete_mount` [#delete_mount]
```python
async delete_mount(sandbox: SandboxRef, mount_id: str, http_timeout: float | None = None) -> None
```
Returns:
None: Result returned by this operation.
### `invoke_url` [#invoke_url]
```python
invoke_url(sandbox: SandboxRef, path: str = '/', *, port: int | None = None) -> str
```
Build an HTTPS URL for this sandbox.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
port: Port number for the generated URL.
Returns:
str: Result returned by this operation.
### `websocket_url` [#websocket_url]
```python
websocket_url(sandbox: SandboxRef, path: str = '/', *, port: int | None = None) -> str
```
Build a websocket URL for this sandbox.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
port: Port number for the generated URL.
Returns:
str: Result returned by this operation.
# AsyncSnapshotsClient (/reference/python-sdk/async/async-snapshots-client)
Source: [`leap0/_async/snapshots.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/snapshots.py)
## Signature [#signature]
```python
AsyncSnapshotsClient(transport: AsyncTransport, *, sandbox_factory: SandboxFactory[Sandbox, AsyncSnapshotSandboxT] | None = None)
```
## Overview [#overview]
List, restore, and delete sandbox snapshots.
A snapshot captures the full state of a running sandbox so it can be
restored later.
Use snapshots when you want a reusable checkpoint of an initialized
sandbox environment.
Attributes:
None.
## Methods [#methods]
### `list` [#list]
```python
async list(*, query: str = '', sort: str = 'created_at', order_by: str = 'desc', page: int = 1, page_size: int = 20, http_timeout: float | None = None) -> SnapshotListResponse
```
List snapshots for the authenticated organization.
Returns:
SnapshotListResponse: Result returned by this operation.
### `restore` [#restore]
```python
async restore(*, snapshot_name: str, auto_pause: bool = False, timeout: int | None = None, network_policy: NetworkPolicyDict | None = None, http_timeout: float | None = None) -> AsyncSnapshotSandboxT | Sandbox
```
Restore a sandbox from a snapshot.
Args:
snapshot\_name: Name of the snapshot to restore.
auto\_pause: Automatically pause the restored sandbox on timeout.
timeout: Sandbox timeout in seconds.
network\_policy: Override the network policy from the snapshot.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
Sandbox: Newly restored sandbox.
### `delete` [#delete]
```python
async delete(snapshot: SnapshotRef, http_timeout: float | None = None) -> None
```
Delete a snapshot.
Args:
snapshot: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
# AsyncSshClient (/reference/python-sdk/async/async-ssh-client)
Source: [`leap0/_async/ssh.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/ssh.py)
## Signature [#signature]
```python
AsyncSshClient(transport: AsyncTransport)
```
## Overview [#overview]
Manage SSH access credentials for a sandbox.
Example:
```python
sandbox = await client.sandboxes.create()
access = await sandbox.ssh.create_access()
print(access.command)
```
Attributes:
None.
## Methods [#methods]
### `create_access` [#create_access]
```python
async create_access(sandbox: SandboxRef, http_timeout: float | None = None) -> SshAccess
```
Generate SSH credentials for a sandbox.
Returns an access ID (used as the SSH username), a password, and the
full SSH command to connect.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SshAccess: Generated SSH credential bundle.
### `delete_access` [#delete_access]
```python
async delete_access(sandbox: SandboxRef, *, id: str, http_timeout: float | None = None) -> None
```
Revoke a specific SSH access credential. The credential is invalidated immediately.
Args:
sandbox: Sandbox ID or object.
id: SSH credential ID.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `validate_access` [#validate_access]
```python
async validate_access(sandbox: SandboxRef, *, id: str, password: str, http_timeout: float | None = None) -> SshValidation
```
Check whether a specific SSH access credential is still valid and not expired.
Args:
sandbox: Sandbox ID or object.
id: SSH credential ID.
password: SSH password.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SshValidation: Validation result for the supplied credential pair.
### `regenerate_access` [#regenerate_access]
```python
async regenerate_access(sandbox: SandboxRef, *, id: str, http_timeout: float | None = None) -> SshAccess
```
Invalidate a specific credential and generate a new one. The expiry is also reset.
Args:
sandbox: Sandbox ID or object.
id: SSH credential ID.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SshAccess: Newly generated SSH credential bundle.
# AsyncTemplatesClient (/reference/python-sdk/async/async-templates-client)
Source: [`leap0/_async/templates.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_async/templates.py)
## Signature [#signature]
```python
AsyncTemplatesClient(transport: AsyncTransport)
```
## Overview [#overview]
Create, rename, and delete sandbox templates.
A template is a container image that has been converted into a sandbox
root filesystem. Sandboxes are always created from a template.
Example:
```python
template = client.templates.create(
name="my-template",
uri="docker.io/library/python:3.12",
)
print(template.id)
```
Attributes:
None.
## Methods [#methods]
### `create` [#create]
```python
async create(*, name: str, uri: str, credentials: RegistryCredentials | RegistryCredentialsDict | None = None) -> Template
```
Upload a new template from a container image URI.
Args:
name: Template name. Must not start with `system/` or contain whitespace.
uri: Container image URI to pull and convert (e.g. `docker.io/library/python:3.12`).
credentials: Optional registry credentials for private images. Supports basic, AWS, GCP, and Azure authentication.
Returns:
Template: Uploaded template metadata.
### `rename` [#rename]
```python
async rename(template_id: str, *, name: str, http_timeout: float | None = None) -> None
```
Rename an existing template.
Args:
template\_id: ID of the template to rename.
name: New template name.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `delete` [#delete]
```python
async delete(template_id: str, http_timeout: float | None = None) -> None
```
Delete a template by ID.
Args:
template\_id: ID of the template to delete.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
# Defaults (/reference/python-sdk/common/defaults)
## Default Values [#default-values]
* `DEFAULT_TEMPLATE_NAME`: `"system/debian:bookworm"`
* `DEFAULT_CODE_INTERPRETER_TEMPLATE_NAME`: `"system/code-interpreter:v0.1.0"`
* `DEFAULT_DESKTOP_TEMPLATE_NAME`: `"system/desktop:v0.1.0"`
* `DEFAULT_VCPU`: `1`
* `DEFAULT_MEMORY_MIB`: `1024`
## Environment Variables [#environment-variables]
* `LEAP0_API_KEY_ENV`: `"LEAP0_API_KEY"`
* `LEAP0_BASE_URL_ENV`: `"LEAP0_BASE_URL"`
* `LEAP0_SANDBOX_DOMAIN_ENV`: `"LEAP0_SANDBOX_DOMAIN"`
* `LEAP0_SDK_OTEL_ENABLED_ENV`: `"LEAP0_SDK_OTEL_ENABLED"`
* `OTEL_EXPORTER_OTLP_ENDPOINT_ENV`: `"OTEL_EXPORTER_OTLP_ENDPOINT"`
* `OTEL_EXPORTER_OTLP_HEADERS_ENV`: `"OTEL_EXPORTER_OTLP_HEADERS"`
# Errors (/reference/python-sdk/common/errors)
Source: [`leap0/models/errors.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/models/errors.py)
## Exception Hierarchy [#exception-hierarchy]
### `Leap0Error` [#leap0error]
Extends `Exception`.
Base error for the Leap0 SDK.
Every SDK exception carries optional HTTP context so callers can
inspect the original response without parsing strings.
Attributes:
message: Human-readable error description.
status\_code: HTTP status code, if the error originated from an API response.
headers: Response headers from the API, if available.
error\_message: Parsed `message` field from a JSON response body, if present.
### `Leap0NotFoundError` [#leap0notfounderror]
Extends `Leap0Error`.
The requested resource does not exist (HTTP 404).
Raised when a sandbox, file, directory, PTY session, LSP server,
SSH access, or other resource cannot be found.
### `Leap0PermissionError` [#leap0permissionerror]
Extends `Leap0Error`.
Permission denied for the requested operation (HTTP 403).
Raised when the sandbox filesystem denies access due to
file permissions or ownership.
### `Leap0ConflictError` [#leap0conflicterror]
Extends `Leap0Error`.
The operation conflicts with the current resource state (HTTP 409).
Raised when a resource already exists (e.g. `mkdir` on an existing
directory), or when there are too many active sessions.
### `Leap0RateLimitError` [#leap0ratelimiterror]
Extends `Leap0Error`.
Rate limit exceeded (HTTP 429).
Callers should back off and retry after the interval indicated
by the `Retry-After` header, if present.
### `Leap0TimeoutError` [#leap0timeouterror]
Extends `Leap0Error`.
The operation timed out.
Raised when a sandbox operation or API call exceeds its deadline.
### `Leap0WebSocketError` [#leap0websocketerror]
Extends `Leap0Error`.
A WebSocket connection to a sandbox failed.
# Python SDK Reference (/reference/python-sdk)
## Overview [#overview]
The Leap0 Python SDK provides synchronous and asynchronous clients for sandbox lifecycle, files, git, process execution, PTY sessions, LSP, SSH, code interpreter, desktop automation, snapshots, and templates.
## Installation [#installation]
```text
pip install leap0
```
## Getting Started [#getting-started]
```python
from leap0 import Leap0Client
client = Leap0Client()
sandbox = client.sandboxes.create()
print(sandbox.id)
```
Use the sidebar to browse shared defaults, errors, sync clients, and async clients.
# CodeInterpreterClient (/reference/python-sdk/sync/code-interpreter-client)
Source: [`leap0/_sync/code_interpreter.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/code_interpreter.py)
## Signature [#signature]
```python
CodeInterpreterClient(transport: Transport, *, sandbox_domain: str | None = None)
```
## Overview [#overview]
Execute code inside a sandbox using a managed interpreter runtime.
Supports Python and TypeScript/JavaScript. Each execution can be linked
to a persistent context to share state across multiple calls.
Example:
```python
result = sandbox.code_interpreter.execute(
code="sum([1, 2, 3])",
language="python",
)
print(result.main_text)
```
Attributes:
None.
## Methods [#methods]
### `health` [#health]
```python
health(sandbox: SandboxRef, http_timeout: float | None = None) -> bool
```
Check whether the code interpreter is healthy.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bool: `True` when the service reports `"ok"`.
### `create_context` [#create_context]
```python
create_context(sandbox: SandboxRef, *, language: str = 'python', cwd: str | None = None, http_timeout: float | None = None) -> CodeContext
```
Create a new execution context.
Args:
sandbox: Sandbox ID or object.
language: Language runtime (default `"python"`).
cwd: Working directory for the new context.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
CodeContext: Newly created persistent execution context.
### `list_contexts` [#list_contexts]
```python
list_contexts(sandbox: SandboxRef, http_timeout: float | None = None) -> list[CodeContext]
```
List all execution contexts in the sandbox.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
list\[CodeContext]: Active execution contexts.
### `get_context` [#get_context]
```python
get_context(sandbox: SandboxRef, context_id: str, http_timeout: float | None = None) -> CodeContext
```
Get a single execution context by ID.
Args:
sandbox: Sandbox ID or object.
context\_id: Execution context identifier.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
CodeContext: Matching execution context.
### `delete_context` [#delete_context]
```python
delete_context(sandbox: SandboxRef, context_id: str, http_timeout: float | None = None) -> None
```
Delete an execution context.
Args:
sandbox: Sandbox ID or object.
context\_id: Execution context identifier.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `execute` [#execute]
```python
execute(sandbox: SandboxRef, *, code: str, language: str = 'python', context_id: str | None = None, env_vars: dict[str, str] | None = None, timeout_ms: int | None = None, http_timeout: float | None = None) -> CodeExecutionResult
```
Execute code and wait for the full result.
Args:
sandbox: Sandbox ID or object.
code: Source code to execute.
language: Language runtime (default `"python"`).
context\_id: Link to an existing context to share state. Auto-generated if omitted.
env\_vars: Environment variables for the execution.
timeout\_ms: Execution timeout in milliseconds (default 30000).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
CodeExecutionResult: Structured execution output, errors, and logs.
### `execute_stream` [#execute_stream]
```python
execute_stream(sandbox: SandboxRef, *, code: str, language: str = 'python', context_id: str | None = None, timeout_ms: int | None = None, http_timeout: float | None = None) -> Iterator[StreamEvent]
```
Execute code and stream output events via SSE.
Yields \:class:`StreamEvent` objects with type `"stdout"`,
`"stderr"`, `"exit"`, or `"error"`.
Args:
sandbox: Sandbox ID or object. code: Source code to execute. language: Language runtime for the operation. context\_id: Parameter for this operation. timeout\_ms: Execution timeout in milliseconds. http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
code: Parameter for this operation.
language: Parameter for this operation.
context\_id: Parameter for this operation.
timeout\_ms: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
Iterator\[StreamEvent]: Result returned by this operation.
# DesktopClient (/reference/python-sdk/sync/desktop-client)
Source: [`leap0/_sync/desktop.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/desktop.py)
## Signature [#signature]
```python
DesktopClient(transport: Transport, *, sandbox_domain: str | None = None)
```
## Overview [#overview]
Control a graphical Linux desktop inside a sandbox.
Requires a sandbox created with the
\:data:`~leap0.constants.DEFAULT_DESKTOP_TEMPLATE_NAME`
(`system/desktop:v0.1.0`) template. Provides display info, screenshots,
mouse/keyboard input, and screen recording.
Attributes:
None.
## Methods [#methods]
### `desktop_url` [#desktop_url]
```python
desktop_url(sandbox: SandboxRef) -> str
```
Build the browser URL for the noVNC desktop viewer.
Args:
sandbox: Sandbox ID or object.
Returns:
str: Result returned by this operation.
### `display_info` [#display_info]
```python
display_info(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopDisplayInfo
```
Get display information (display name, width, height).
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopDisplayInfo: Result returned by this operation.
### `screen` [#screen]
```python
screen(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopDisplayInfo
```
Get the current screen resolution.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopDisplayInfo: Result returned by this operation.
### `resize_screen` [#resize_screen]
```python
resize_screen(sandbox: SandboxRef, *, width: int, height: int, http_timeout: float | None = None) -> DesktopDisplayInfo
```
Resize the virtual display (width: 320-7680, height: 320-4320).
Args:
sandbox: Sandbox ID or object.
width: Parameter for this operation.
height: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopDisplayInfo: Result returned by this operation.
### `windows` [#windows]
```python
windows(sandbox: SandboxRef, http_timeout: float | None = None) -> list[DesktopWindow]
```
List all open windows on the desktop.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
list\[DesktopWindow]: Result returned by this operation.
### `screenshot` [#screenshot]
```python
screenshot(sandbox: SandboxRef, *, image_format: str | None = None, quality: int | None = None, x: int | None = None, y: int | None = None, width: int | None = None, height: int | None = None, http_timeout: float | None = None) -> bytes
```
Take a screenshot and return the image as bytes.
Args:
sandbox: Sandbox ID or object.
image\_format: `"png"`, `"jpg"`, or `"jpeg"` (default `"png"`).
quality: JPEG quality (1-100).
x: Left edge of capture region.
y: Top edge of capture region.
width: Region width in pixels.
height: Region height in pixels.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bytes: Result returned by this operation.
### `screenshot_region` [#screenshot_region]
```python
screenshot_region(sandbox: SandboxRef, *, x: int, y: int, width: int, height: int, image_format: str | None = None, quality: int | None = None, http_timeout: float | None = None) -> bytes
```
Take a screenshot of a specific region and return the image as bytes.
Args:
sandbox: Sandbox ID or object.
x: Parameter for this operation.
y: Parameter for this operation.
width: Parameter for this operation.
height: Parameter for this operation.
image\_format: Parameter for this operation.
quality: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bytes: Result returned by this operation.
### `pointer_position` [#pointer_position]
```python
pointer_position(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopPointerPosition
```
Get the current mouse pointer position.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopPointerPosition: Result returned by this operation.
### `move_pointer` [#move_pointer]
```python
move_pointer(sandbox: SandboxRef, *, x: int, y: int, http_timeout: float | None = None) -> DesktopPointerPosition
```
Move the mouse pointer to the given coordinates.
Args:
sandbox: Sandbox ID or object.
x: Parameter for this operation.
y: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopPointerPosition: Result returned by this operation.
### `click` [#click]
```python
click(sandbox: SandboxRef, *, x: int | None = None, y: int | None = None, button: int | None = None, http_timeout: float | None = None) -> DesktopPointerPosition
```
Click the mouse. Clicks at the current position if coordinates are omitted.
Args:
sandbox: Sandbox ID or object.
x: X coordinate.
y: Y coordinate.
button: 1=left, 2=middle, 3=right (default 1).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopPointerPosition: Result returned by this operation.
### `drag` [#drag]
```python
drag(sandbox: SandboxRef, *, from_x: int, from_y: int, to_x: int, to_y: int, button: int | None = None, http_timeout: float | None = None) -> DesktopPointerPosition
```
Drag from one position to another.
Args:
sandbox: Sandbox ID or object.
from\_x: Parameter for this operation.
from\_y: Parameter for this operation.
to\_x: Parameter for this operation.
to\_y: Parameter for this operation.
button: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopPointerPosition: Result returned by this operation.
### `scroll` [#scroll]
```python
scroll(sandbox: SandboxRef, *, direction: str, amount: int | None = None, http_timeout: float | None = None) -> DesktopPointerPosition
```
Scroll the mouse wheel.
Args:
sandbox: Sandbox ID or object.
direction: `"up"`, `"down"`, `"left"`, or `"right"`.
amount: Number of scroll steps (1-100, default 1).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopPointerPosition: Result returned by this operation.
### `type_text` [#type_text]
```python
type_text(sandbox: SandboxRef, *, text: str, http_timeout: float | None = None) -> bool
```
Type text using simulated keyboard input (max 50,000 characters).
Args:
sandbox: Sandbox ID or object.
text: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bool: Result returned by this operation.
### `press_key` [#press_key]
```python
press_key(sandbox: SandboxRef, *, key: str, http_timeout: float | None = None) -> bool
```
Press a single key by X11 keysym name (e.g. `"Return"`, `"Escape"`).
Args:
sandbox: Sandbox ID or object.
key: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bool: Result returned by this operation.
### `hotkey` [#hotkey]
```python
hotkey(sandbox: SandboxRef, *, keys: list[str], http_timeout: float | None = None) -> bool
```
Press multiple keys simultaneously (e.g. `["Control_L", "c"]`).
Args:
sandbox: Sandbox ID or object.
keys: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bool: Result returned by this operation.
### `recording_status` [#recording_status]
```python
recording_status(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopRecordingStatus
```
Get the current screen recording status.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopRecordingStatus: Result returned by this operation.
### `start_recording` [#start_recording]
```python
start_recording(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopRecordingStatus
```
Start recording the screen. Returns 409 if a recording is already active.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopRecordingStatus: Result returned by this operation.
### `stop_recording` [#stop_recording]
```python
stop_recording(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopRecordingStatus
```
Stop the active screen recording.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopRecordingStatus: Result returned by this operation.
### `recordings` [#recordings]
```python
recordings(sandbox: SandboxRef, http_timeout: float | None = None) -> list[DesktopRecordingSummary]
```
List all screen recordings.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
list\[DesktopRecordingSummary]: Result returned by this operation.
### `get_recording` [#get_recording]
```python
get_recording(sandbox: SandboxRef, recording_id: str, http_timeout: float | None = None) -> DesktopRecordingSummary
```
Get details for a single recording.
Args:
sandbox: Sandbox ID or object.
recording\_id: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopRecordingSummary: Result returned by this operation.
### `download_recording` [#download_recording]
```python
download_recording(sandbox: SandboxRef, recording_id: str, http_timeout: float | None = None) -> bytes
```
Download a recording as MP4 bytes.
Args:
sandbox: Sandbox ID or object.
recording\_id: Recording identifier.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bytes: Result returned by this operation.
### `delete_recording` [#delete_recording]
```python
delete_recording(sandbox: SandboxRef, recording_id: str, http_timeout: float | None = None) -> None
```
Delete a recording. Cannot delete an active recording.
Args:
sandbox: Sandbox ID or object.
recording\_id: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `health` [#health]
```python
health(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopHealth
```
Check the health of the desktop environment.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopHealth: Result returned by this operation.
### `process_status` [#process_status]
```python
process_status(sandbox: SandboxRef, http_timeout: float | None = None) -> DesktopProcessStatusList
```
Get the status of all desktop processes (xvfb, xfce4, x11vnc, novnc).
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopProcessStatusList: Result returned by this operation.
### `get_process` [#get_process]
```python
get_process(sandbox: SandboxRef, process_name: str, http_timeout: float | None = None) -> DesktopProcessStatus
```
Get the status of a single desktop process by name.
Args:
sandbox: Sandbox ID or object.
process\_name: Desktop process name.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopProcessStatus: Result returned by this operation.
### `restart_process` [#restart_process]
```python
restart_process(sandbox: SandboxRef, process_name: str, http_timeout: float | None = None) -> DesktopProcessRestart
```
Restart a desktop process.
Args:
sandbox: Sandbox ID or object.
process\_name: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopProcessRestart: Result returned by this operation.
### `process_logs` [#process_logs]
```python
process_logs(sandbox: SandboxRef, process_name: str, http_timeout: float | None = None) -> DesktopProcessLogs
```
Get stdout logs for a desktop process.
Args:
sandbox: Sandbox ID or object.
process\_name: Desktop process name.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopProcessLogs: Result returned by this operation.
### `process_errors` [#process_errors]
```python
process_errors(sandbox: SandboxRef, process_name: str, http_timeout: float | None = None) -> DesktopProcessErrors
```
Get stderr logs for a desktop process.
Args:
sandbox: Sandbox ID or object.
process\_name: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
DesktopProcessErrors: Result returned by this operation.
### `status_stream` [#status_stream]
```python
status_stream(sandbox: SandboxRef, *, deadline: float | None = None, http_timeout: float | None = None) -> Iterator[DesktopProcessStatusList]
```
Subscribe to a live SSE stream of process status updates.
Args:
sandbox: Sandbox ID or object. deadline: Absolute `time.monotonic()` deadline. When set, a \:class:`Leap0TimeoutError` is raised once the deadline is exceeded. `None` means no deadline. http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
deadline: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
Iterator\[DesktopProcessStatusList]: Result returned by this operation.
### `wait_until_ready` [#wait_until_ready]
```python
wait_until_ready(sandbox: SandboxRef, *, timeout: float = 60.0, http_timeout: float | None = None) -> None
```
Block until all desktop processes are running.
Connects to the SSE status stream and waits for the aggregate
status to become `"running"` (all four desktop processes alive).
Automatically retries the stream connection on transient errors
using exponential back-off, bounded by *timeout* seconds total.
Args:
sandbox: Sandbox ID or object.
timeout: Maximum seconds to wait (default 60).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Raises:
Leap0TimeoutError: If the desktop does not become ready within *timeout* seconds.
Returns:
None: Result returned by this operation.
# FilesystemClient (/reference/python-sdk/sync/filesystem-client)
Source: [`leap0/_sync/filesystem.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/filesystem.py)
## Signature [#signature]
```python
FilesystemClient(transport: Transport)
```
## Overview [#overview]
List, read, write, move, copy, delete, and search files inside a sandbox.
Text helpers such as \:meth:`write_file` and \:meth:`read_file` provide the
most ergonomic default API. Use the `*_bytes` variants when you need raw
binary access or want to avoid text decoding.
Attributes:
None.
## Methods [#methods]
### `ls` [#ls]
```python
ls(sandbox: SandboxRef, *, path: str, recursive: bool = False, exclude: list[str] | None = None) -> LsResult
```
List directory entries.
Args:
sandbox: Sandbox ID or object.
path: Directory path to list.
recursive: List recursively.
exclude: Glob patterns to exclude.
Returns:
LsResult: Result returned by this operation.
### `stat` [#stat]
```python
stat(sandbox: SandboxRef, *, path: str) -> FileInfo
```
Get metadata for a single path.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
Returns:
FileInfo: Result returned by this operation.
### `mkdir` [#mkdir]
```python
mkdir(sandbox: SandboxRef, *, path: str, recursive: bool = False, permissions: str | None = None, http_timeout: float | None = None) -> None
```
Create a directory. Set *recursive* to create parent directories.
Args:
sandbox: Sandbox ID or object.
path: Directory path to create.
recursive: Create parents as needed.
permissions: Octal permission string (e.g. `"755"`).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `write_bytes` [#write_bytes]
```python
write_bytes(sandbox: SandboxRef, *, path: str, content: bytes, permissions: str | None = None, http_timeout: float | None = None) -> None
```
Write raw bytes to a single file path.
Args:
sandbox: Sandbox ID or object. path: Destination file path. content: Raw file bytes. permissions: Optional octal permission string.
path: Path used by this operation.
content: Parameter for this operation.
permissions: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `write_file` [#write_file]
```python
write_file(sandbox: SandboxRef, *, path: str, content: str, encoding: str = 'utf-8', permissions: str | None = None, http_timeout: float | None = None) -> None
```
Write text to a single file path.
Args:
sandbox: Sandbox ID or object. path: Destination file path. content: Text content to write. encoding: Text encoding used before upload. permissions: Optional octal permission string.
path: Path used by this operation.
content: Parameter for this operation.
encoding: Parameter for this operation.
permissions: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call. Example: \`\`\`python sandbox.filesystem.write\_file( path="/workspace/app.py", content="print('hello')
Returns:
None: Result returned by this operation.
### `write_files_bytes` [#write_files_bytes]
```python
write_files_bytes(sandbox: SandboxRef, *, files: dict[str, bytes], http_timeout: float | None = None) -> None
```
Write multiple files in a single request.
Args:
sandbox: Sandbox ID or object. files: Mapping of file path to raw bytes content.
files: Files used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `write_files` [#write_files]
```python
write_files(sandbox: SandboxRef, *, files: dict[str, str], encoding: str = 'utf-8', http_timeout: float | None = None) -> None
```
Write multiple text files in a single request.
Args:
sandbox: Sandbox ID or object.
files: Mapping of file path to text content.
encoding: Text encoding used before upload.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `read_bytes` [#read_bytes]
```python
read_bytes(sandbox: SandboxRef, *, path: str, offset: int | None = None, limit: int | None = None, head: int | None = None, tail: int | None = None, http_timeout: float | None = None) -> bytes
```
Read a single file and return its raw bytes.
Args:
sandbox: Sandbox ID or object.
path: Path to the file.
offset: Byte offset to start from.
limit: Maximum bytes to read.
head: Return only the first N lines (mutually exclusive with *tail*).
tail: Return only the last N lines (mutually exclusive with *head*).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bytes: File contents as raw bytes.
Example: `python content = sandbox.filesystem.read_bytes(path="/workspace/logo.png") print(content) `
### `read_file` [#read_file]
```python
read_file(sandbox: SandboxRef, *, path: str, offset: int | None = None, limit: int | None = None, head: int | None = None, tail: int | None = None, encoding: str = 'utf-8', http_timeout: float | None = None) -> str
```
Read a single file and return its content decoded as text.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
offset: Parameter for this operation.
limit: Parameter for this operation.
head: Parameter for this operation.
tail: Parameter for this operation.
encoding: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
str: Result returned by this operation.
### `read_files_bytes` [#read_files_bytes]
```python
read_files_bytes(sandbox: SandboxRef, *, paths: list[str], http_timeout: float | None = None) -> dict[str, bytes]
```
Read multiple files and return raw bytes keyed by path.
Args:
sandbox: Sandbox ID or object.
paths: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
dict\[str, bytes]: Result returned by this operation.
### `read_files` [#read_files]
```python
read_files(sandbox: SandboxRef, *, paths: list[str], encoding: str = 'utf-8', http_timeout: float | None = None) -> dict[str, str]
```
Read multiple files and return decoded text keyed by path.
Args:
sandbox: Sandbox ID or object.
paths: Parameter for this operation.
encoding: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
dict\[str, str]: Result returned by this operation.
### `delete` [#delete]
```python
delete(sandbox: SandboxRef, *, path: str, recursive: bool = False, http_timeout: float | None = None) -> None
```
Delete a file or directory.
Args:
sandbox: Sandbox ID or object.
path: Path to delete.
recursive: Required when deleting a non-empty directory.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `set_permissions` [#set_permissions]
```python
set_permissions(sandbox: SandboxRef, *, path: str, mode: str | None = None, owner: str | None = None, group: str | None = None, http_timeout: float | None = None) -> None
```
Set file mode and optionally change owner and group.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
mode: Parameter for this operation.
owner: Parameter for this operation.
group: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `glob` [#glob]
```python
glob(sandbox: SandboxRef, *, path: str, pattern: str, exclude: list[str] | None = None, http_timeout: float | None = None) -> list[str]
```
Find file paths matching a glob pattern.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
pattern: Parameter for this operation.
exclude: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
list\[str]: Matching file paths.
### `grep` [#grep]
```python
grep(sandbox: SandboxRef, *, path: str, pattern: str, include: str | None = None, exclude: list[str] | None = None, http_timeout: float | None = None) -> list[SearchMatch]
```
Search for a text pattern across files in a directory.
Args:
sandbox: Sandbox ID or object.
path: Base directory to search from.
pattern: Text pattern to search for.
include: File pattern filter (e.g. `"*.py"`).
exclude: Glob patterns to exclude.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
list\[SearchMatch]: Matching lines with file and line metadata.
### `edit_file` [#edit_file]
```python
edit_file(sandbox: SandboxRef, *, path: str, edits: list[FileEdit], http_timeout: float | None = None) -> EditFileResult
```
Apply one or more find-and-replace edits to a single file.
Returns:
EditFileResult: Unified diff and replacement count.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
edits: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
### `edit_files` [#edit_files]
```python
edit_files(sandbox: SandboxRef, *, paths: list[str], find: str, replace: str = '', http_timeout: float | None = None) -> list[EditResult]
```
Replace text across multiple files at once.
Args:
sandbox: Sandbox ID or object.
paths: Parameter for this operation.
find: Parameter for this operation.
replace: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
list\[EditResult]: Per-file edit results.
### `move` [#move]
```python
move(sandbox: SandboxRef, *, src_path: str, dst_path: str, overwrite: bool = False, http_timeout: float | None = None) -> None
```
Move or rename a file or directory.
Args:
sandbox: Sandbox ID or object.
src\_path: Parameter for this operation.
dst\_path: Parameter for this operation.
overwrite: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `copy` [#copy]
```python
copy(sandbox: SandboxRef, *, src_path: str, dst_path: str, recursive: bool = False, overwrite: bool | None = None, http_timeout: float | None = None) -> None
```
Copy a file or directory.
Args:
sandbox: Sandbox ID or object.
src\_path: Source path.
dst\_path: Destination path.
recursive: Required when copying a directory.
overwrite: Overwrite the destination if it already exists.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `exists` [#exists]
```python
exists(sandbox: SandboxRef, *, path: str, http_timeout: float | None = None) -> bool
```
Check whether a path exists in the sandbox.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
bool: `True` when the path exists.
### `tree` [#tree]
```python
tree(sandbox: SandboxRef, *, path: str, max_depth: int | None = None, exclude: list[str] | None = None, http_timeout: float | None = None) -> TreeResult
```
Get a recursive directory tree.
Args:
sandbox: Sandbox ID or object.
path: Root directory path.
max\_depth: Maximum traversal depth.
exclude: Glob patterns to exclude.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
TreeResult: Recursive directory tree rooted at `path`.
# GitClient (/reference/python-sdk/sync/git-client)
Source: [`leap0/_sync/git.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/git.py)
## Signature [#signature]
```python
GitClient(transport: Transport)
```
## Overview [#overview]
Clone repositories, inspect diffs and history, manage branches, stage
files, commit, push, and pull inside a running sandbox.
This client is useful when you want to automate Git workflows without
shelling out manually through \:class:`ProcessClient`.
Attributes:
None.
## Methods [#methods]
### `clone` [#clone]
```python
clone(sandbox: SandboxRef, *, url: str, path: str, branch: str | None = None, commit_id: str | None = None, depth: int | None = None, username: str | None = None, password: str | None = None, http_timeout: float | None = None) -> GitResult
```
Clone a remote repository into the sandbox.
Args:
sandbox: Sandbox ID or object.
url: Repository URL.
path: Destination path inside the sandbox.
branch: Branch to clone.
commit\_id: Specific commit to checkout after cloning.
depth: Shallow clone depth.
username: Auth username (for private repos).
password: Auth password or token (for private repos).
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Command output and exit status from the clone operation.
### `status` [#status]
```python
status(sandbox: SandboxRef, *, path: str, http_timeout: float | None = None) -> GitResult
```
Get the current repository status.
Returns:
GitResult: Git status output and exit status.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
### `branches` [#branches]
```python
branches(sandbox: SandboxRef, *, path: str, branch_type: str = 'local', contains: str | None = None, not_contains: str | None = None, http_timeout: float | None = None) -> GitResult
```
List branches in the repository.
Args:
sandbox: Sandbox ID or object.
path: Path to the git repo.
branch\_type: Filter by `"local"`, `"remote"`, or `"all"`.
contains: Only branches containing this commit SHA.
not\_contains: Exclude branches containing this commit SHA.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `diff_unstaged` [#diff_unstaged]
```python
diff_unstaged(sandbox: SandboxRef, *, path: str, context_lines: int | None = None, http_timeout: float | None = None) -> GitResult
```
Show working tree changes that are not staged yet.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
context\_lines: Number of context lines to include.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `diff_staged` [#diff_staged]
```python
diff_staged(sandbox: SandboxRef, *, path: str, context_lines: int | None = None, http_timeout: float | None = None) -> GitResult
```
Show changes that are already staged for the next commit.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
context\_lines: Number of context lines to include.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `diff` [#diff]
```python
diff(sandbox: SandboxRef, *, path: str, target: str, context_lines: int | None = None, http_timeout: float | None = None) -> GitResult
```
Compare the current state against a branch, tag, or commit.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
target: Branch, tag, or commit to compare against.
context\_lines: Number of context lines to include.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `reset` [#reset]
```python
reset(sandbox: SandboxRef, *, path: str, http_timeout: float | None = None) -> GitResult
```
Unstage all currently staged changes.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `log` [#log]
```python
log(sandbox: SandboxRef, *, path: str, max_count: int | None = None, start_timestamp: str | None = None, end_timestamp: str | None = None, http_timeout: float | None = None) -> GitResult
```
Show commit history with optional limits and date filters.
Args:
sandbox: Sandbox ID or object.
path: Path to the git repo.
max\_count: Maximum number of commits to return (default 10).
start\_timestamp: Start timestamp filter.
end\_timestamp: End timestamp filter.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `show` [#show]
```python
show(sandbox: SandboxRef, *, path: str, revision: str = 'HEAD', http_timeout: float | None = None) -> GitResult
```
Show the full output for a commit, branch, or tag revision.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
revision: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `create_branch` [#create_branch]
```python
create_branch(sandbox: SandboxRef, *, path: str, name: str, checkout: bool | None = None, base_branch: str | None = None, http_timeout: float | None = None) -> GitResult
```
Create a new branch.
Args:
sandbox: Sandbox ID or object.
path: Path to the git repo.
name: New branch name.
checkout: Switch to the new branch immediately.
base\_branch: Branch from a specific revision.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `checkout_branch` [#checkout_branch]
```python
checkout_branch(sandbox: SandboxRef, *, path: str, branch: str, create: bool | None = None, http_timeout: float | None = None) -> GitResult
```
Switch to an existing branch. Set *create* to create it if it does not exist.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
branch: Branch name.
create: Create the branch if it does not exist.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `delete_branch` [#delete_branch]
```python
delete_branch(sandbox: SandboxRef, *, path: str, name: str, force: bool = False, http_timeout: float | None = None) -> GitResult
```
Delete a branch. Set *force* to delete even if unmerged.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
name: Name used by this operation.
force: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `add` [#add]
```python
add(sandbox: SandboxRef, *, path: str, files: list[str], http_timeout: float | None = None) -> GitResult
```
Stage files for the next commit.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
files: Files used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `commit` [#commit]
```python
commit(sandbox: SandboxRef, *, path: str, message: str, author: str | None = None, email: str | None = None, allow_empty: bool | None = None, http_timeout: float | None = None) -> GitCommitResult
```
Create a commit from staged changes.
Args:
sandbox: Sandbox ID or object.
path: Path to the git repo.
message: Commit message.
author: Author name.
email: Author email.
allow\_empty: Allow creating an empty commit.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitCommitResult: Commit result including commit ID when successful.
### `push` [#push]
```python
push(sandbox: SandboxRef, *, path: str, remote: str | None = None, branch: str | None = None, set_upstream: bool | None = None, username: str | None = None, password: str | None = None, http_timeout: float | None = None) -> GitResult
```
Push commits to a remote.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
remote: Parameter for this operation.
branch: Parameter for this operation.
set\_upstream: Parameter for this operation.
username: Parameter for this operation.
password: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
### `pull` [#pull]
```python
pull(sandbox: SandboxRef, *, path: str, remote: str | None = None, branch: str | None = None, rebase: bool | None = None, set_upstream: bool | None = None, username: str | None = None, password: str | None = None, http_timeout: float | None = None) -> GitResult
```
Pull commits from a remote. Set *rebase* to rebase instead of merge.
Args:
sandbox: Sandbox ID or object.
path: Path to the git repo.
remote: Remote name (default `"origin"`).
branch: Branch name.
rebase: Rebase instead of merge.
set\_upstream: Set upstream tracking.
username: Auth username.
password: Auth password or token.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
GitResult: Result returned by this operation.
# Leap0Client (/reference/python-sdk/sync/leap0-client)
Source: [`leap0/_sync/client.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/client.py)
## Signature [#signature]
```python
Leap0Client(*, api_key: str | None = None, base_url: str | None = None, sandbox_domain: str | None = None, timeout: float = DEFAULT_CLIENT_TIMEOUT, auth_header: str = 'authorization', bearer: bool = True, otel_enabled: bool | None = None, sdk_otel_enabled: bool | None = None)
```
## Overview [#overview]
Top-level client for the Leap0 API.
Use this client to create sandboxes and access top-level control-plane
services. Sandbox-scoped services are exposed through bound sandbox objects.
It can be used directly or as a context manager.
Args:
api\_key: API key for authentication. Falls back to `LEAP0_API_KEY`.
base\_url: Control-plane base URL. Falls back to `LEAP0_BASE_URL`.
sandbox\_domain: Sandbox domain suffix. Falls back to
`LEAP0_SANDBOX_DOMAIN`.
timeout: Default HTTP timeout in seconds.
auth\_header: Header name used to send the API key.
bearer: Whether to prefix the API key with `Bearer`.
Attributes:
sandboxes: Client for sandbox lifecycle operations.
snapshots: Client for snapshot lifecycle operations.
templates: Client for template management.
## Methods [#methods]
### `get_sandbox` [#get_sandbox]
```python
get_sandbox(sandbox_id: str) -> Sandbox
```
Get a sandbox object with bound service clients by ID.
Args:
sandbox\_id: Sandbox identifier.
Returns:
Sandbox: Sandbox object with bound service clients.
### `create_sandbox` [#create_sandbox]
```python
create_sandbox(**kwargs: object) -> Sandbox
```
Create a sandbox and return it as a bound sandbox object.
Args:
kwargs: Parameter for this operation.
Returns:
Sandbox: Sandbox object with bound service clients.
### `close` [#close]
```python
close() -> None
```
Close the underlying HTTP transport.
Call this when you are done with the client if you are not using a
context manager.
Returns:
None: Result returned by this operation.
# LspClient (/reference/python-sdk/sync/lsp-client)
Source: [`leap0/_sync/lsp.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/lsp.py)
## Signature [#signature]
```python
LspClient(transport: Transport)
```
## Overview [#overview]
Start and interact with language servers for code intelligence inside
a sandbox.
Supported languages: Python (pyright) and TypeScript/JavaScript
(typescript-language-server).
The typical flow is `start` -> `did_open` -> `completions` or
`document_symbols` -> `did_close` -> `stop`.
Attributes:
None.
## Methods [#methods]
### `start` [#start]
```python
start(sandbox: SandboxRef, *, language_id: str, path_to_project: str) -> LspResponse
```
Start the LSP server for a language and project.
Spawns the server process and sends the LSP `initialize` handshake
automatically.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier (`"python"`, `"typescript"`, or `"javascript"`).
path\_to\_project: Project directory path inside the sandbox.
Returns:
LspResponse: Server startup result.
### `stop` [#stop]
```python
stop(sandbox: SandboxRef, *, language_id: str, path_to_project: str) -> LspResponse
```
Send `shutdown` and `exit` to the language server and terminate it.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
Returns:
LspResponse: Result returned by this operation.
### `did_open` [#did_open]
```python
did_open(sandbox: SandboxRef, *, language_id: str, path_to_project: str, uri: str, text: str | None = None, version: int = 1, http_timeout: float | None = None) -> None
```
Notify the language server that a document was opened.
Must be called before requesting completions or symbols.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
uri: Document URI.
text: Parameter for this operation.
version: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `did_open_path` [#did_open_path]
```python
did_open_path(sandbox: SandboxRef, *, language_id: str, path_to_project: str, path: str, text: str | None = None, version: int = 1, http_timeout: float | None = None) -> None
```
Like \:meth:`did_open` but accepts a file path instead of a URI.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
path: File path inside the sandbox.
text: Optional full document text to send with the open notification.
version: Document version number.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `did_close` [#did_close]
```python
did_close(sandbox: SandboxRef, *, language_id: str, path_to_project: str, uri: str, http_timeout: float | None = None) -> None
```
Notify the language server that a document was closed.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
uri: Document URI.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `did_close_path` [#did_close_path]
```python
did_close_path(sandbox: SandboxRef, *, language_id: str, path_to_project: str, path: str, http_timeout: float | None = None) -> None
```
Like \:meth:`did_close` but accepts a file path instead of a URI.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
path: Path used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `completions` [#completions]
```python
completions(sandbox: SandboxRef, *, language_id: str, path_to_project: str, uri: str, line: int, character: int, http_timeout: float | None = None) -> LspJsonRpcResponse
```
Request completions from the language server.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
uri: Document URI.
line: Zero-based line number.
character: Zero-based character offset.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
LspJsonRpcResponse: Raw JSON-RPC response payload.
### `completions_path` [#completions_path]
```python
completions_path(sandbox: SandboxRef, *, language_id: str, path_to_project: str, path: str, line: int, character: int, http_timeout: float | None = None) -> LspJsonRpcResponse
```
Like \:meth:`completions` but accepts a file path instead of a URI.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
path: Path used by this operation.
line: Zero-based line number.
character: Zero-based character offset.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
LspJsonRpcResponse: Result returned by this operation.
### `document_symbols` [#document_symbols]
```python
document_symbols(sandbox: SandboxRef, *, language_id: str, path_to_project: str, uri: str, http_timeout: float | None = None) -> LspJsonRpcResponse
```
Request document symbols from the language server.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
uri: Document URI.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
LspJsonRpcResponse: Raw JSON-RPC response payload.
### `document_symbols_path` [#document_symbols_path]
```python
document_symbols_path(sandbox: SandboxRef, *, language_id: str, path_to_project: str, path: str, http_timeout: float | None = None) -> LspJsonRpcResponse
```
Like \:meth:`document_symbols` but accepts a file path instead of a URI.
Args:
sandbox: Sandbox ID or object.
language\_id: Language identifier for the LSP operation.
path\_to\_project: Project path inside the sandbox.
path: Path used by this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
LspJsonRpcResponse: Result returned by this operation.
# ProcessClient (/reference/python-sdk/sync/process-client)
Source: [`leap0/_sync/process.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/process.py)
## Signature [#signature]
```python
ProcessClient(transport: Transport)
```
## Overview [#overview]
Execute one-shot shell commands inside a running sandbox.
Use this client for non-interactive command execution where you want the
full result back as a single response.
Attributes:
None.
## Methods [#methods]
### `execute` [#execute]
```python
execute(sandbox: SandboxRef, *, command: str, cwd: str | None = None, env: dict[str, str] | None = None, timeout: int | None = None, http_timeout: int | None = None) -> ProcessResult
```
Run a shell command and wait for the result.
The command runs inside `/bin/sh -c`.
Args:
sandbox: Sandbox ID or object.
command: Shell command to execute.
cwd: Working directory.
env: Optional environment variables applied to the spawned process.
timeout: Timeout in seconds. If omitted, the server-side default is used.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
ProcessResult: Command result including exit code, stdout, and stderr.
Example: `python result = sandbox.process.execute( command="ls -la /workspace", ) print(result.stdout) print(result.stderr) `
# PtyClient (/reference/python-sdk/sync/pty-client)
Source: [`leap0/_sync/pty.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/pty.py)
## Signature [#signature]
```python
PtyClient(transport: Transport)
```
## Overview [#overview]
Create and manage interactive terminal sessions inside a sandbox.
Connect via WebSocket for real-time bidirectional I/O, similar to SSH or
a browser-based terminal.
Example:
```python
sandbox = client.sandboxes.create()
session = sandbox.pty.create(cols=120, rows=30)
conn = sandbox.pty.connect(session.id)
conn.send("pwd
")
print(conn.recv().decode())
conn.close()
```
Attributes:
None.
## Methods [#methods]
### `list` [#list]
```python
list(sandbox: SandboxRef) -> list[PtySession]
```
List all PTY sessions for a sandbox.
Args:
sandbox: Sandbox ID or object.
Returns:
list\[PtySession]: Result returned by this operation.
### `create` [#create]
```python
create(sandbox: SandboxRef, *, session_id: str | None = None, cols: int | None = None, rows: int | None = None, cwd: str | None = None, envs: dict[str, str] | None = None, lazy_start: bool | None = None, http_timeout: float | None = None) -> PtySession
```
Create a terminal session with a shell process.
Args:
sandbox: Sandbox ID or object.
session\_id: Session ID. Auto-generated if omitted.
cols: Terminal columns.
rows: Terminal rows.
cwd: Starting directory.
envs: Environment variables.
lazy\_start: Defer shell start until the first WebSocket connection.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
PtySession: Metadata for the created PTY session.
### `get` [#get]
```python
get(sandbox: SandboxRef, session_id: str) -> PtySession
```
Get details for a single PTY session.
Args:
sandbox: Sandbox ID or object.
session\_id: PTY session identifier.
Returns:
PtySession: Result returned by this operation.
### `delete` [#delete]
```python
delete(sandbox: SandboxRef, session_id: str, http_timeout: float | None = None) -> None
```
Kill the shell process and remove the session.
Args:
sandbox: Sandbox ID or object.
session\_id: PTY session identifier.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `resize` [#resize]
```python
resize(sandbox: SandboxRef, session_id: str, *, cols: int, rows: int) -> PtySession
```
Change the terminal dimensions while connected.
Args:
sandbox: Sandbox ID or object.
session\_id: PTY session identifier.
cols: Parameter for this operation.
rows: Parameter for this operation.
Returns:
PtySession: Result returned by this operation.
### `websocket_url` [#websocket_url]
```python
websocket_url(sandbox: SandboxRef, session_id: str) -> str
```
Build the WSS URL for connecting to a PTY session.
Args:
sandbox: Sandbox ID or object.
session\_id: PTY session identifier.
Returns:
str: Result returned by this operation.
### `connect` [#connect]
```python
connect(sandbox: SandboxRef, session_id: str, http_timeout: float | None = None, **kwargs: Any) -> PtyConnection
```
Open a WebSocket connection for interactive terminal I/O.
Returns a \:class:`PtyConnection` with `send`, `recv`, and
`close` methods. All messages are binary frames containing raw
terminal bytes.
Args:
sandbox: Sandbox ID or object.
session\_id: PTY session identifier.
http\_timeout: Optional WebSocket open timeout in seconds.
kwargs: Parameter for this operation.
Returns:
PtyConnection: Open WebSocket-backed PTY connection.
# Sandbox (/reference/python-sdk/sync/sandbox)
Source: [`leap0/_sync/sandbox.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/sandbox.py)
## Signature [#signature]
```python
Sandbox(client: object, data: SandboxData | SandboxStatus)
```
## Overview [#overview]
Sandbox object with bound service clients.
This object exposes sandbox metadata directly and provides bound service
handles so you can call methods like `sandbox.filesystem.read_file(...)`
instead of passing the sandbox object into every client call.
Attributes:
filesystem: Bound filesystem client.
git: Bound git client.
process: Bound process client.
pty: Bound PTY client.
lsp: Bound LSP client.
ssh: Bound SSH client.
code\_interpreter: Bound code interpreter client.
desktop: Bound desktop client.
## Methods [#methods]
### `refresh` [#refresh]
```python
refresh() -> Sandbox
```
Refresh sandbox metadata in place.
Returns:
Sandbox: This sandbox object with refreshed metadata.
### `pause` [#pause]
```python
pause(http_timeout: float | None = None) -> Sandbox
```
Pause the sandbox and update this handle with the latest metadata.
Args:
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
Sandbox: This sandbox object with updated metadata.
### `stop` [#stop]
```python
stop(http_timeout: float | None = None) -> Sandbox
```
Stop the sandbox and update this handle with the latest metadata.
Args:
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
Sandbox: This sandbox object with updated metadata.
### `start` [#start]
```python
start(http_timeout: float | None = None) -> Sandbox
```
Start a previously stopped sandbox and refresh this handle.
Args:
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
Sandbox: This sandbox object with updated metadata.
### `create_snapshot` [#create_snapshot]
```python
create_snapshot(*, name: str | None = None, kill_sandbox_after: bool = False, http_timeout: float | None = None) -> Snapshot
```
Create a snapshot from this sandbox.
Args:
name: Optional snapshot name. Auto-generated if omitted.
kill\_sandbox\_after: Terminate the source sandbox after the snapshot is stored.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
Snapshot: Created snapshot metadata.
### `delete` [#delete]
```python
delete(http_timeout: float | None = None) -> None
```
Delete the sandbox.
Args:
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `create_presigned_url` [#create_presigned_url]
```python
create_presigned_url(*, port: int, expires_in: int | None = None, http_timeout: float | None = None) -> PresignedURL
```
Create a temporary public URL for a specific sandbox port.
Returns:
PresignedURL: Result returned by this operation.
### `delete_presigned_url` [#delete_presigned_url]
```python
delete_presigned_url(presigned_url_id: str, http_timeout: float | None = None) -> None
```
Delete a previously issued presigned URL.
Returns:
None: Result returned by this operation.
### `invoke_url` [#invoke_url]
```python
invoke_url(path: str = '/', *, port: int | None = None) -> str
```
Build an HTTPS URL that routes directly to this sandbox.
Args:
path: Request path inside the sandbox application.
port: Port number for the generated URL.
Returns:
str: Sandbox-scoped HTTPS URL.
### `websocket_url` [#websocket_url]
```python
websocket_url(path: str = '/', *, port: int | None = None) -> str
```
Build a WSS URL that routes directly to this sandbox.
Args:
path: Request path inside the sandbox application.
port: Port number for the generated URL.
Returns:
str: Sandbox-scoped websocket URL.
### `get_user_home_dir` [#get_user_home_dir]
```python
get_user_home_dir(http_timeout: float | None = None) -> str
```
Fetch the resolved home directory for the sandbox user.
Returns:
str: Result returned by this operation.
### `get_workdir` [#get_workdir]
```python
get_workdir(http_timeout: float | None = None) -> str
```
Fetch the configured working directory for the sandbox.
Returns:
str: Result returned by this operation.
### `add_mount` [#add_mount]
```python
add_mount(mount: ObjectStorageMountRequestDict, http_timeout: float | None = None) -> ObjectStorageMount
```
Attach an object storage mount to this sandbox.
Returns:
ObjectStorageMount: Result returned by this operation.
### `update_mount` [#update_mount]
```python
update_mount(mount_id: str, mount: ObjectStorageMountUpdateDict, http_timeout: float | None = None) -> ObjectStorageMount
```
Update an existing object storage mount on this sandbox.
Returns:
ObjectStorageMount: Result returned by this operation.
### `delete_mount` [#delete_mount]
```python
delete_mount(mount_id: str, http_timeout: float | None = None) -> None
```
Delete an object storage mount from this sandbox.
Returns:
None: Result returned by this operation.
# SandboxesClient (/reference/python-sdk/sync/sandboxes-client)
Source: [`leap0/_sync/sandbox.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/sandbox.py)
## Signature [#signature]
```python
SandboxesClient(transport: Transport, *, sandbox_domain: str | None = None, sandbox_factory: SandboxFactory[SandboxData | SandboxStatus, SandboxT] | None = None)
```
## Overview [#overview]
Create, inspect, pause, stop, start, and delete sandboxes.
Sandboxes are isolated execution environments with their own compute,
filesystem, and network boundary.
Attributes:
None.
## Methods [#methods]
### `create` [#create]
```python
create(*, template_name: str = DEFAULT_TEMPLATE_NAME, vcpu: int = DEFAULT_VCPU, memory: int = DEFAULT_MEMORY_MIB, timeout: int = DEFAULT_TIMEOUT, auto_pause: bool = False, otel_export: bool | None = None, telemetry: bool | None = None, env_vars: dict[str, str] | None = None, network_policy: NetworkPolicyDict | None = None, mounts: list[ObjectStorageMountRequestDict] | None = None, http_timeout: float | None = None) -> SandboxT | SandboxData | SandboxStatus
```
Create a new sandbox from a template.
Args:
template\_name: Name of the template to use.
vcpu: Number of virtual CPUs (1 to 8).
memory: Memory in MiB (512 to 8192, must be even).
timeout: Sandbox timeout in seconds (1 to 28800, default 300).
auto\_pause: Automatically pause the sandbox into a snapshot on timeout.
otel\_export: Inject OpenTelemetry exporter environment into the sandbox. Requires `OTEL_EXPORTER_OTLP_ENDPOINT` in the local environment and also forwards `OTEL_EXPORTER_OTLP_HEADERS` when present.
telemetry: Deprecated alias for `otel_export`. Use `otel_export` instead.
env\_vars: Environment variables to set inside the sandbox.
network\_policy: Outbound network policy for the sandbox.
mounts: Object storage mounts to attach before boot.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SandboxT | SandboxData | SandboxStatus: Created sandbox object.
### `list` [#list]
```python
list(*, state: str | None = None, sort: str = 'created_at', order_by: str = 'desc', page: int = 1, page_size: int = 20, http_timeout: float | None = None) -> SandboxListResponse
```
List sandboxes for the authenticated organization.
Args:
state: Optional sandbox state filter.
sort: Sort field, either `created_at` or `state`.
order\_by: Sort direction, either `asc` or `desc`.
page: 1-based page number.
page\_size: Page size between 1 and 100.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SandboxListResponse: Paginated sandbox summaries.
### `pause` [#pause]
```python
pause(sandbox: SandboxRef, http_timeout: float | None = None) -> SandboxT | SandboxData | SandboxStatus
```
Pause a running sandbox.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SandboxT | SandboxData | SandboxStatus: Updated sandbox object.
### `stop` [#stop]
```python
stop(sandbox: SandboxRef, http_timeout: float | None = None) -> SandboxT | SandboxData | SandboxStatus
```
Stop a running sandbox while preserving writable disk changes.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SandboxT | SandboxData | SandboxStatus: Updated sandbox object.
### `start` [#start]
```python
start(sandbox: SandboxRef, http_timeout: float | None = None) -> SandboxT | SandboxData | SandboxStatus
```
Start a previously stopped sandbox.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SandboxT | SandboxData | SandboxStatus: Updated sandbox object.
### `create_snapshot` [#create_snapshot]
```python
create_snapshot(sandbox: SandboxRef, *, name: str | None = None, kill_sandbox_after: bool = False, http_timeout: float | None = None) -> Snapshot
```
Create a snapshot from a running sandbox.
Returns:
Snapshot: Result returned by this operation.
### `get` [#get]
```python
get(sandbox: SandboxRef, http_timeout: float | None = None) -> SandboxT | SandboxData | SandboxStatus
```
Get the latest sandbox metadata.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SandboxT | SandboxData | SandboxStatus: Current sandbox object.
### `delete` [#delete]
```python
delete(sandbox: SandboxRef, http_timeout: float | None = None) -> None
```
Terminate and delete a sandbox.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `get_user_home_dir` [#get_user_home_dir]
```python
get_user_home_dir(sandbox: SandboxRef, http_timeout: float | None = None) -> str
```
Get the resolved home directory for the sandbox user.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
str: Resolved sandbox user home directory.
### `get_workdir` [#get_workdir]
```python
get_workdir(sandbox: SandboxRef, http_timeout: float | None = None) -> str
```
Get the configured working directory for the sandbox.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
str: Configured sandbox workdir.
### `create_presigned_url` [#create_presigned_url]
```python
create_presigned_url(sandbox: SandboxRef, *, port: int, expires_in: int | None = None, http_timeout: float | None = None) -> PresignedURL
```
Returns:
PresignedURL: Result returned by this operation.
### `delete_presigned_url` [#delete_presigned_url]
```python
delete_presigned_url(sandbox: SandboxRef, presigned_url_id: str, http_timeout: float | None = None) -> None
```
Returns:
None: Result returned by this operation.
### `add_mount` [#add_mount]
```python
add_mount(sandbox: SandboxRef, mount: ObjectStorageMountRequestDict, http_timeout: float | None = None) -> ObjectStorageMount
```
Returns:
ObjectStorageMount: Result returned by this operation.
### `update_mount` [#update_mount]
```python
update_mount(sandbox: SandboxRef, mount_id: str, mount: ObjectStorageMountUpdateDict, http_timeout: float | None = None) -> ObjectStorageMount
```
Returns:
ObjectStorageMount: Result returned by this operation.
### `delete_mount` [#delete_mount]
```python
delete_mount(sandbox: SandboxRef, mount_id: str, http_timeout: float | None = None) -> None
```
Returns:
None: Result returned by this operation.
### `invoke_url` [#invoke_url]
```python
invoke_url(sandbox: SandboxRef, path: str = '/', *, port: int | None = None) -> str
```
Build an HTTPS URL that routes directly to the sandbox.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
port: Port number for the generated URL.
Returns:
str: Result returned by this operation.
### `websocket_url` [#websocket_url]
```python
websocket_url(sandbox: SandboxRef, path: str = '/', *, port: int | None = None) -> str
```
Build a WSS URL that routes directly to the sandbox.
Args:
sandbox: Sandbox ID or object.
path: Path used by this operation.
port: Port number for the generated URL.
Returns:
str: Result returned by this operation.
# SnapshotsClient (/reference/python-sdk/sync/snapshots-client)
Source: [`leap0/_sync/snapshots.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/snapshots.py)
## Signature [#signature]
```python
SnapshotsClient(transport: Transport, *, sandbox_factory: SandboxFactory[Sandbox, SnapshotSandboxT] | None = None)
```
## Overview [#overview]
List, restore, and delete sandbox snapshots.
A snapshot captures the full state of a running sandbox so it can be
restored later.
Use snapshots when you want a reusable checkpoint of an initialized
sandbox environment.
Attributes:
None.
## Methods [#methods]
### `list` [#list]
```python
list(*, query: str = '', sort: str = 'created_at', order_by: str = 'desc', page: int = 1, page_size: int = 20, http_timeout: float | None = None) -> SnapshotListResponse
```
List snapshots for the authenticated organization.
Returns:
SnapshotListResponse: Result returned by this operation.
### `restore` [#restore]
```python
restore(*, snapshot_name: str, auto_pause: bool = False, timeout: int | None = None, network_policy: NetworkPolicyDict | None = None, http_timeout: float | None = None) -> SnapshotSandboxT | Sandbox
```
Restore a sandbox from a snapshot.
Args:
snapshot\_name: Name of the snapshot to restore.
auto\_pause: Automatically pause the restored sandbox on timeout.
timeout: Sandbox timeout in seconds.
network\_policy: Override the network policy from the snapshot.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
Sandbox: Newly restored sandbox.
### `delete` [#delete]
```python
delete(snapshot: SnapshotRef, http_timeout: float | None = None) -> None
```
Delete a snapshot.
Args:
snapshot: Parameter for this operation.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
# SshClient (/reference/python-sdk/sync/ssh-client)
Source: [`leap0/_sync/ssh.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/ssh.py)
## Signature [#signature]
```python
SshClient(transport: Transport)
```
## Overview [#overview]
Manage SSH access credentials for a sandbox.
Example:
```python
sandbox = client.sandboxes.create()
access = sandbox.ssh.create_access()
print(access.command)
```
Attributes:
None.
## Methods [#methods]
### `create_access` [#create_access]
```python
create_access(sandbox: SandboxRef, http_timeout: float | None = None) -> SshAccess
```
Generate SSH credentials for a sandbox.
Returns an access ID (used as the SSH username), a password, and the
full SSH command to connect.
Args:
sandbox: Sandbox ID or object.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SshAccess: Generated SSH credential bundle.
### `delete_access` [#delete_access]
```python
delete_access(sandbox: SandboxRef, *, id: str, http_timeout: float | None = None) -> None
```
Revoke a specific SSH access credential. The credential is invalidated immediately.
Args:
sandbox: Sandbox ID or object.
id: SSH credential ID.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `validate_access` [#validate_access]
```python
validate_access(sandbox: SandboxRef, *, id: str, password: str, http_timeout: float | None = None) -> SshValidation
```
Check whether a specific SSH access credential is still valid and not expired.
Args:
sandbox: Sandbox ID or object.
id: SSH credential ID.
password: SSH password.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SshValidation: Validation result for the supplied credential pair.
### `regenerate_access` [#regenerate_access]
```python
regenerate_access(sandbox: SandboxRef, *, id: str, http_timeout: float | None = None) -> SshAccess
```
Invalidate a specific credential and generate a new one. The expiry is also reset.
Args:
sandbox: Sandbox ID or object.
id: SSH credential ID.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
SshAccess: Newly generated SSH credential bundle.
# TemplatesClient (/reference/python-sdk/sync/templates-client)
Source: [`leap0/_sync/templates.py`](https://github.com/leap0-dev/leap0-python/blob/main/leap0/_sync/templates.py)
## Signature [#signature]
```python
TemplatesClient(transport: Transport)
```
## Overview [#overview]
Create, rename, and delete sandbox templates.
A template is a container image that has been converted into a sandbox
root filesystem. Sandboxes are always created from a template.
Example:
```python
template = client.templates.create(
name="my-template",
uri="docker.io/library/python:3.12",
)
print(template.id)
```
Attributes:
None.
## Methods [#methods]
### `create` [#create]
```python
create(*, name: str, uri: str, credentials: RegistryCredentials | RegistryCredentialsDict | None = None) -> Template
```
Upload a new template from a container image URI.
Args:
name: Template name. Must not start with `system/` or contain whitespace.
uri: Container image URI to pull and convert (e.g. `docker.io/library/python:3.12`).
credentials: Optional registry credentials for private images. Supports basic, AWS, GCP, and Azure authentication.
Returns:
Template: Uploaded template metadata.
### `rename` [#rename]
```python
rename(template_id: str, *, name: str, http_timeout: float | None = None) -> None
```
Rename an existing template.
Args:
template\_id: ID of the template to rename.
name: New template name.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.
### `delete` [#delete]
```python
delete(template_id: str, http_timeout: float | None = None) -> None
```
Delete a template by ID.
Args:
template\_id: ID of the template to delete.
http\_timeout: Optional HTTP request timeout in seconds for this SDK call.
Returns:
None: Result returned by this operation.