### Utilize Language Server Protocol for Code Intelligence Source: https://context7.com/leap0-dev/leap0-python/llms.txt Shows how to start an LSP server, create files, open documents, get completions, document symbols, and stop the server. Ensure the project path and file paths are correctly specified. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() project_path = "/workspace/myproject" try: # Create a Python file client.filesystem.mkdir(sandbox, path=project_path, recursive=True) client.filesystem.write_file_text( sandbox, path=f"{project_path}/main.py", content=""" import os def greet(name: str) -> str: return f"Hello, {name}!" result = greet("World") os.path # cursor here for completions """, ) # Start LSP server for Python client.lsp.start(sandbox, language_id="python", path_to_project=project_path) # Open document (required before completions) client.lsp.did_open_path( sandbox, language_id="python", path_to_project=project_path, path=f"{project_path}/main.py", ) # Get completions at a position (line 8, after "os.") completions = client.lsp.completions_path( sandbox, language_id="python", path_to_project=project_path, path=f"{project_path}/main.py", line=7, # 0-indexed character=8, # after "os.path" ) print("Completions:", completions) # Get document symbols symbols = client.lsp.document_symbols_path( sandbox, language_id="python", path_to_project=project_path, path=f"{project_path}/main.py", ) print("Symbols:", symbols) # Close document client.lsp.did_close_path( sandbox, language_id="python", path_to_project=project_path, path=f"{project_path}/main.py", ) # Stop LSP server client.lsp.stop(sandbox, language_id="python", path_to_project=project_path) finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Initialize Desktop Automation Client Source: https://context7.com/leap0-dev/leap0-python/llms.txt Setup the Leap0 client for controlling graphical Linux desktop environments. ```python import time from pathlib import Path from leap0 import Leap0, Leap0Config, Leap0APIError client = Leap0(Leap0Config()) ``` -------------------------------- ### Install Leap0 SDK Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Installation commands for the Leap0 Python package. ```bash pip install leap0 ``` ```bash git clone https://github.com/leap0dev/leap0-python.git cd leap0-python pip install . ``` -------------------------------- ### Network Controls Example Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Example of how to configure network controls for a sandbox. ```APIDOC ## Network Controls Fine-grained egress control per sandbox. Allow-list specific domains or IP ranges, or block all outbound traffic entirely. ### Example ```python sandbox = client.sandboxes.create( network_policy="custom", allowed_domains=["api.example.com"], ) ``` ``` -------------------------------- ### Install Leap0 with Development Dependencies Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Install the Leap0 SDK with development dependencies and run tests. ```bash pip install -e ".[dev]" pytest ``` -------------------------------- ### Quick Start Sandbox Execution Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Basic usage patterns for creating a sandbox and executing code, either manually or using a context manager. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: result = client.code_interpreter.execute( sandbox, code="sum([10, 20, 30, 40]) / 4", language="python", ) print(result.main_text) # "25.0" finally: client.sandboxes.delete(sandbox) client.close() ``` ```python from leap0 import Leap0Client with Leap0Client(api_key="your-api-key") as client: sandbox = client.sandboxes.create() result = client.code_interpreter.execute( sandbox, code="print('Hello from the sandbox!')", language="python" ) print(result.main_text) client.sandboxes.delete(sandbox) ``` -------------------------------- ### Language Server Protocol Integration Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Start and interact with language servers for code analysis. ```python client.lsp.start(sandbox, language="python") client.lsp.did_open(sandbox, uri="file:///workspace/main.py", language="python") completions = client.lsp.completions(sandbox, uri="file:///workspace/main.py", line=10, character=5) ``` -------------------------------- ### Perform Git Operations in a Sandbox Source: https://context7.com/leap0-dev/leap0-python/llms.txt Use this snippet to clone repositories, manage branches, stage files, commit, push, and pull changes. It includes examples for both public and private repositories, checking status, viewing diffs, and viewing commit logs. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() repo_path = "/workspace/repo" try: # Clone a repository clone_result = client.git.clone( sandbox, url="https://github.com/octocat/Hello-World.git", path=repo_path, branch="master", depth=1, # Shallow clone ) print(f"Clone exit code: {clone_result.exit_code}") # Clone private repo with authentication client.git.clone( sandbox, url="https://github.com/user/private-repo.git", path="/workspace/private", username="user", password="github_pat_token", ) # Check status status = client.git.status(sandbox, path=repo_path) print(status.output) # List branches branches = client.git.branches(sandbox, path=repo_path, branch_type="all") print(branches.output) # Create and checkout branch client.git.create_branch(sandbox, path=repo_path, name="feature-branch", checkout=True) client.git.checkout_branch(sandbox, path=repo_path, branch="master") # Make changes client.filesystem.write_file_text( sandbox, path=f"{repo_path}/new-file.txt", content="New content from SDK", ) # View diffs unstaged = client.git.diff_unstaged(sandbox, path=repo_path) print(f"Unstaged changes:\n{unstaged.output}") # Stage and commit client.git.add(sandbox, path=repo_path, files=["new-file.txt"]) staged = client.git.diff_staged(sandbox, path=repo_path) print(f"Staged changes:\n{staged.output}") commit_result = client.git.commit( sandbox, path=repo_path, message="Add new file via SDK", author="SDK User", email="sdk@example.com", ) print(f"Commit SHA: {commit_result.sha}") # View commit history log = client.git.log(sandbox, path=repo_path, max_count=5) print(log.output) # Push changes (with auth for private repos) push_result = client.git.push( sandbox, path=repo_path, remote="origin", branch="feature-branch", set_upstream=True, username="user", password="token", ) # Pull changes pull_result = client.git.pull(sandbox, path=repo_path, rebase=True) # Reset staged changes client.git.reset(sandbox, path=repo_path) finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Create and Interact with a Desktop Sandbox Source: https://context7.com/leap0-dev/leap0-python/llms.txt Demonstrates creating a desktop sandbox, waiting for it to be ready, and performing various desktop operations like resizing, window management, mouse and keyboard input, screenshots, screen recording, and process management. Includes cleanup by deleting the sandbox. ```python sandbox = client.sandboxes.create(template_name="system/desktop:v0.1.0") try: # Wait for desktop to be ready for _ in range(60): try: health = client.desktop.health(sandbox) if health.ok and health.state == "ready": break except Leap0APIError: pass time.sleep(1) # Get desktop URL for browser viewing desktop_url = client.desktop.desktop_url(sandbox) print(f"View desktop at: {desktop_url}") # Get display information display = client.desktop.display_info(sandbox) print(f"Display: {display.width}x{display.height}") # Resize screen client.desktop.resize_screen(sandbox, width=1920, height=1080) # List open windows windows = client.desktop.windows(sandbox) for window in windows: print(f"Window: {window.title} ({window.width}x{window.height})") # Mouse operations position = client.desktop.pointer_position(sandbox) print(f"Pointer at: ({position.x}, {position.y})") client.desktop.move_pointer(sandbox, x=500, y=300) client.desktop.click(sandbox, button=1) # Left click client.desktop.click(sandbox, x=100, y=100, button=3) # Right click at position # Drag operation client.desktop.drag(sandbox, from_x=100, from_y=100, to_x=300, to_y=300) # Scroll client.desktop.scroll(sandbox, direction="down", amount=3) # Keyboard input client.desktop.type_text(sandbox, text="Hello, Desktop!") client.desktop.press_key(sandbox, key="Return") client.desktop.hotkey(sandbox, keys=["Control_L", "c"]) # Ctrl+C # Take screenshot screenshot = client.desktop.screenshot(sandbox, image_format="png") Path("screenshot.png").write_bytes(screenshot) # Screenshot of specific region region = client.desktop.screenshot_region( sandbox, x=100, y=100, width=400, height=300, image_format="jpeg", quality=90, ) # Screen recording recording = client.desktop.start_recording(sandbox) print(f"Recording ID: {recording.id}") # ... perform actions ... time.sleep(5) client.desktop.stop_recording(sandbox) # List and download recordings recordings = client.desktop.recordings(sandbox) for rec in recordings: print(f"Recording: {rec.file_name} ({rec.size_bytes} bytes)") video = client.desktop.download_recording(sandbox, rec.id) Path(rec.file_name).write_bytes(video) # Process management status = client.desktop.process_status(sandbox) for proc in status.items: print(f"Process {proc.name}: running={proc.running}, pid={proc.pid}") # Get process logs logs = client.desktop.process_logs(sandbox, "xfce4") print(f"XFCE4 logs: {logs.logs}") finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Manage Snapshots Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Create and resume sandbox state snapshots. ```python snapshot = client.snapshots.create(sandbox, name="my-checkpoint") restored = client.snapshots.resume(snapshot_name="my-checkpoint") ``` -------------------------------- ### Configure and Initialize Leap0 Client Source: https://context7.com/leap0-dev/leap0-python/llms.txt Initialize the Leap0 client using environment variables, direct API keys, or full configuration objects. Use the context manager pattern to ensure resources are cleaned up automatically. ```python # Install from PyPI # pip install leap0 # Or install from source # git clone https://github.com/leap0dev/leap0-python.git # cd leap0-python && pip install . import os from leap0 import Leap0, Leap0Client, Leap0Config # Option 1: Using environment variable (recommended) os.environ["LEAP0_API_KEY"] = "your-api-key" client = Leap0(Leap0Config()) # Option 2: Direct API key client = Leap0Client(api_key="your-api-key") # Option 3: Full configuration config = Leap0Config( api_key="your-api-key", base_url="https://api.leap0.dev", sandbox_domain="sandbox.leap0.dev", timeout=300.0, ) client = Leap0(config) # Using context manager for automatic cleanup with Leap0Client(api_key="your-api-key") as client: sandbox = client.sandboxes.create() # ... use sandbox ... client.sandboxes.delete(sandbox) ``` -------------------------------- ### Write Text Files Source: https://context7.com/leap0-dev/leap0-python/llms.txt Demonstrates writing single and multiple text files to the sandbox filesystem. Permissions can be specified. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: # Write files client.filesystem.write_file_text( sandbox, path="/workspace/hello.txt", content="Hello, World!", permissions="644", ) # Write multiple files at once client.filesystem.write_files_text( sandbox, files={ "/workspace/config.json": '{"debug": true}', "/workspace/data.csv": "name,value\nfoo,1\nbar,2", }, ) finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Create Sandbox with Network Policy Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Use this to create a new sandbox with custom network policies, such as allowing specific domains. ```python sandbox = client.sandboxes.create( network_policy="custom", allowed_domains=["api.example.com"], ) ``` -------------------------------- ### Configure Leap0 Client Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Initialize the Leap0 client with your API key and base URL. The API key can also be set via the LEAP0_API_KEY environment variable. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config( api_key="your-api-key", # or set LEAP0_API_KEY env var base_url="https://api.leap0.dev", timeout=300, )) ``` -------------------------------- ### Create and Manage Interactive Terminal Sessions Source: https://context7.com/leap0-dev/leap0-python/llms.txt Demonstrates creating, listing, connecting to, sending commands, resizing, and deleting PTY sessions. Ensure a sandbox is created and deleted to manage resources. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: # Create a terminal session session = client.pty.create( sandbox, session_id="my-terminal", cols=120, rows=30, cwd="/workspace", envs={"TERM": "xterm-256color"}, ) print(f"Session ID: {session.id}") # List active sessions sessions = client.pty.list(sandbox) for s in sessions: print(f"Session {s.id}: active={s.active}") # Connect via WebSocket connection = client.pty.connect(sandbox, session.id) try: # Send commands connection.send("pwd\n") output = connection.recv().decode("utf-8", errors="replace") print(output) connection.send("ls -la\n") output = connection.recv().decode("utf-8", errors="replace") print(output) # Interactive loop example connection.send("echo 'Hello from PTY'\n") print(connection.recv().decode()) finally: connection.close() # Resize terminal client.pty.resize(sandbox, session.id, cols=160, rows=40) # Get WebSocket URL for external clients ws_url = client.pty.websocket_url(sandbox, session.id) print(f"WebSocket URL: {ws_url}") # Clean up session client.pty.delete(sandbox, session.id) finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Custom Sandbox Templates Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Create and use custom sandbox templates based on container images. ```python template = client.templates.create( name="my-template", image="my-registry.com/my-image:latest", ) sandbox = client.sandboxes.create(template_name="my-template") ``` -------------------------------- ### Desktop Automation Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Control a graphical desktop environment within a sandbox. ```python sandbox = client.sandboxes.create(template_name="system/desktop:v0.1.0") client.desktop.move_pointer(sandbox, x=500, y=300) client.desktop.click(sandbox, button=1) screenshot = client.desktop.screenshot(sandbox, image_format="png") ``` -------------------------------- ### Generate and Manage SSH Access Credentials Source: https://context7.com/leap0-dev/leap0-python/llms.txt Demonstrates creating, validating, regenerating, and revoking time-bound SSH access credentials for a sandbox. Ensure sandbox and access resources are cleaned up. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: # Create SSH access credentials ssh = client.ssh.create_access(sandbox) print(f"SSH Command: {ssh.ssh_command}") print(f"Username (Access ID): {ssh.id}") print(f"Password: {ssh.password}") print(f"Expires at: {ssh.expires_at}") # Example SSH command output: # ssh @ -p # Validate credentials validation = client.ssh.validate_access( sandbox, access_id=ssh.id, password=ssh.password, ) print(f"Valid: {validation.valid}") # Regenerate credentials (invalidates old ones) new_ssh = client.ssh.regenerate_access(sandbox) print(f"New password: {new_ssh.password}") # Revoke SSH access client.ssh.delete_access(sandbox) finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Manage Sandbox Lifecycle and Resources Source: https://context7.com/leap0-dev/leap0-python/llms.txt Create, configure, and monitor isolated compute environments. Supports custom resource allocation, network policies, and direct URL generation for sandbox access. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) # Create a basic sandbox sandbox = client.sandboxes.create() print(f"Sandbox ID: {sandbox.id}") print(f"State: {sandbox.state}") print(f"vCPU: {sandbox.vcpu}, Memory: {sandbox.memory_mib} MiB") # Create sandbox with custom configuration sandbox = client.sandboxes.create( template_name="system/default:v0.1.0", vcpu=4, # 1-8 vCPUs memory_mib=4096, # 512-8192 MiB timeout_min=30, # 1-480 minutes auto_pause=True, # Snapshot on timeout env_vars={"MY_VAR": "value"}, network_policy={ "policy": "custom", "allowed_domains": ["api.example.com", "pypi.org"], }, ) # Get sandbox status status = client.sandboxes.get(sandbox) print(f"State: {status.state}") # starting, running, paused, stopped # Pause a running sandbox paused = client.sandboxes.pause(sandbox) # Build URLs for direct sandbox access url = client.sandboxes.invoke_url(sandbox, path="/api/endpoint", port=8080) ws_url = client.sandboxes.websocket_url(sandbox, path="/ws") # Delete sandbox when done client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Create Custom Sandbox Templates in Python Source: https://context7.com/leap0-dev/leap0-python/llms.txt Define reusable sandbox environments from container images, supporting public registries, private authentication, and AWS ECR. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) try: # Create template from public image template = client.templates.create( name="my-python-env", uri="docker.io/library/python:3.12-slim", ) print(f"Template ID: {template.id}") print(f"Template Name: {template.name}") print(f"Digest: {template.digest}") # Create template from private registry with basic auth private_template = client.templates.create( name="my-private-image", uri="my-registry.com/my-image:latest", credentials={ "type": "basic", "username": "user", "password": "password", }, ) # AWS ECR credentials ecr_template = client.templates.create( name="ecr-image", uri="123456789.dkr.ecr.us-east-1.amazonaws.com/my-image:latest", credentials={ "type": "aws", "access_key_id": "AKIA...", "secret_access_key": "...", "region": "us-east-1", }, ) # Use the template sandbox = client.sandboxes.create(template_name="my-python-env") # Rename template renamed = client.templates.rename(template.id, name="python-3.12-env") # Delete template client.templates.delete(template.id) finally: client.close() ``` -------------------------------- ### Manage Filesystem Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Perform common filesystem operations like writing, reading, listing, and searching files. ```python client.filesystem.write_file_text(sandbox, path="/workspace/hello.txt", content="Hello!") content = client.filesystem.read_file_text(sandbox, path="/workspace/hello.txt") tree = client.filesystem.tree(sandbox, path="/workspace", max_depth=2) matches = client.filesystem.grep(sandbox, path="/workspace", pattern="TODO") ``` -------------------------------- ### Read Text Files Source: https://context7.com/leap0-dev/leap0-python/llms.txt Shows how to read single or multiple text files from the sandbox. Supports reading specific lines using head/tail. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: # Read files content = client.filesystem.read_file_text(sandbox, path="/workspace/hello.txt") print(content) # "Hello, World!" # Read with offset/limit or head/tail first_10_lines = client.filesystem.read_file_text(sandbox, path="/workspace/data.csv", head=10) last_5_lines = client.filesystem.read_file_text(sandbox, path="/workspace/log.txt", tail=5) # Read multiple files files = client.filesystem.read_files_text(sandbox, paths=["/workspace/hello.txt", "/workspace/config.json"]) finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Manage Sandbox Snapshots in Python Source: https://context7.com/leap0-dev/leap0-python/llms.txt Create, pause, and resume sandbox states to checkpoint and restore work. Snapshots can be deleted once they are no longer required. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: # Set up state client.filesystem.write_file_text(sandbox, path="/workspace/state.txt", content="Important data") client.code_interpreter.execute(sandbox, code="x = 42", language="python") # Create a snapshot without stopping the sandbox snapshot = client.snapshots.create(sandbox, name="checkpoint-1") print(f"Snapshot ID: {snapshot.snapshot_id}") print(f"Snapshot Name: {snapshot.name}") # Continue working... client.filesystem.write_file_text(sandbox, path="/workspace/more.txt", content="More work") # Pause sandbox and create snapshot (stops the sandbox) final_snapshot = client.snapshots.pause(sandbox, name="final-state") finally: client.close() # Later: Resume from snapshot client = Leap0(Leap0Config()) try: # Resume sandbox from snapshot restored = client.snapshots.resume( snapshot_name="checkpoint-1", auto_pause=True, timeout_min=60, ) print(f"Restored Sandbox ID: {restored.id}") # State is preserved content = client.filesystem.read_file_text(restored, path="/workspace/state.txt") print(content) # "Important data" # Delete snapshot when no longer needed client.snapshots.delete(snapshot) finally: client.sandboxes.delete(restored) client.close() ``` -------------------------------- ### Directory Operations Source: https://context7.com/leap0-dev/leap0-python/llms.txt Manage directories within the sandbox, including creation, listing contents, and viewing directory structure. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: # Directory operations client.filesystem.mkdir(sandbox, path="/workspace/subdir", recursive=True) ls_result = client.filesystem.ls(sandbox, path="/workspace", recursive=False) for item in ls_result.items: print(f"{'[DIR]' if item.is_dir else '[FILE]'} {item.name} ({item.size} bytes)") # Tree view tree = client.filesystem.tree(sandbox, path="/workspace", max_depth=3, exclude=["node_modules", ".git"]) for entry in tree.items: print(f"{entry.type}: {entry.name}") finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Execute Shell Commands Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Run one-shot shell commands within a running sandbox. ```python result = client.process.execute(sandbox, command=["ls", "-la", "/workspace"]) print(result.stdout) ``` -------------------------------- ### Configure API Key Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Methods for setting the Leap0 API key via environment variables or client initialization. ```bash export LEAP0_API_KEY="your-api-key" ``` ```python from leap0 import Leap0Client client = Leap0Client(api_key="your-api-key") ``` -------------------------------- ### Search Files and Content Source: https://context7.com/leap0-dev/leap0-python/llms.txt Utilize glob patterns for file searching and grep for content searching within files, with options to include/exclude specific paths and patterns. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: # Search files with glob py_files = client.filesystem.glob(sandbox, path="/workspace", pattern="**/*.py") # Search content with grep matches = client.filesystem.grep( sandbox, path="/workspace", pattern="TODO", include="*.py", exclude=["venv/*", "__pycache__/*"], ) for match in matches: print(f"{match.path}:{match.line}: {match.content}") finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Leap0 Client Configuration Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Configure the Leap0 client with your API key, base URL, and other options. ```APIDOC ## Leap0 Client Configuration Configure the Leap0 client with your API key, base URL, and other options. ### Configuration Options | Option | Default | Description | |---------------|---------------------|------------------------------------------------| | `api_key` | `LEAP0_API_API_KEY` | API key for authentication | | `base_url` | `https://api.leap0.dev` | API base URL | | `sandbox_domain` | `sandbox.leap0.dev` | Domain for sandbox-scoped endpoints | | `timeout` | `300` | HTTP client timeout in seconds | ### Example ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config( api_key="your-api-key", # or set LEAP0_API_KEY env var base_url="https://api.leap0.dev", timeout=300, )) ``` ``` -------------------------------- ### Execute Code and Streams Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Execute code in a stateful REPL or stream output in real-time. ```python result = client.code_interpreter.execute( sandbox, code="x = 42", language="python" ) # Stream output in real-time for event in client.code_interpreter.execute_stream( sandbox, code="for i in range(5): print(i)", language="python" ): print(event.type, event.data) ``` -------------------------------- ### Execute Shell Commands in a Sandbox Source: https://context7.com/leap0-dev/leap0-python/llms.txt Run shell commands within the sandbox environment. This snippet demonstrates executing simple commands, commands with a specified working directory and timeout, and handling command failures. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: # Run a simple command result = client.process.execute(sandbox, command="ls -la /workspace") print(f"Exit code: {result.exit_code}") print(f"Output:\n{result.result}") # Run with working directory and timeout result = client.process.execute( sandbox, command="pip install requests && python -c 'import requests; print(requests.__version__)'", cwd="/workspace", timeout=60, ) print(result.result) # Check for errors result = client.process.execute(sandbox, command="cat /nonexistent") if result.exit_code != 0: print(f"Command failed with code {result.exit_code}") print(f"Error: {result.result}") finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### API Reference - Service Clients Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Overview of the available service clients and their functionalities. ```APIDOC ## API Reference The SDK is organized into service clients accessible from the top-level `Leap0Client`: | Client | Description | |---------------------|---------------------------------------------------| | `client.sandboxes` | Create, get, pause, and delete sandboxes | | `client.snapshots` | Create, pause, resume, and delete snapshots | | `client.templates` | Create, rename, and delete templates | | `client.filesystem` | File operations (read, write, edit, search, tree, etc.) | | `client.git` | Git operations (clone, commit, push, pull, branch, etc.) | | `client.process` | Execute shell commands | | `client.pty` | Interactive terminal sessions over WebSocket | | `client.lsp` | Language Server Protocol for code intelligence | | `client.ssh` | SSH credential management | | `client.code_interpreter` | Code execution with streaming support | | `client.desktop` | Graphical desktop control and screen recording | ``` -------------------------------- ### Perform Git Operations Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Manage Git repositories inside the sandbox environment. ```python client.git.clone(sandbox, url="https://github.com/user/repo.git", path="/workspace/repo") status = client.git.status(sandbox, path="/workspace/repo") client.git.add(sandbox, path="/workspace/repo", files=["README.md"]) client.git.commit(sandbox, path="/workspace/repo", message="Update README") client.git.push(sandbox, path="/workspace/repo") ``` -------------------------------- ### SSH Access Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Generate credentials for direct SSH access to a sandbox. ```python ssh = client.ssh.create_access(sandbox) print(ssh.hostname, ssh.port, ssh.username) ``` -------------------------------- ### File Operations Source: https://context7.com/leap0-dev/leap0-python/llms.txt Perform essential file operations like copy, move, delete, check existence, and retrieve metadata. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: # File operations client.filesystem.copy(sandbox, src_path="/workspace/hello.txt", dst_path="/workspace/hello_backup.txt") client.filesystem.move(sandbox, src_path="/workspace/hello_backup.txt", dst_path="/workspace/archive/hello.txt") client.filesystem.delete(sandbox, path="/workspace/archive", recursive=True) # Check existence exists = client.filesystem.exists(sandbox, path="/workspace/hello.txt") # Get file metadata info = client.filesystem.stat(sandbox, path="/workspace/hello.txt") print(f"Size: {info.size}, Mode: {info.mode}, Owner: {info.owner}") finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Execute Code in Sandboxes Source: https://context7.com/leap0-dev/leap0-python/llms.txt Run Python or TypeScript code within a sandbox using stateful execution contexts. Contexts allow variables and state to persist across multiple execution calls. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: # Simple code execution result = client.code_interpreter.execute( sandbox, code="sum([10, 20, 30, 40]) / 4", language="python", ) print(result.main_text) # "25.0" # With context for state persistence ctx = client.code_interpreter.create_context(sandbox, language="python", cwd="/workspace") result1 = client.code_interpreter.execute( sandbox, code="x = 42", language="python", context_id=ctx.id, ) result2 = client.code_interpreter.execute( sandbox, code="x * 2", language="python", context_id=ctx.id, ) print(result2.main_text) # "84" - x persists across calls # Access execution details print(f"Stdout: {result2.logs.stdout}") print(f"Stderr: {result2.logs.stderr}") if result2.error: print(f"Error: {result2.error.name}: {result2.error.value}") # TypeScript execution ts_result = client.code_interpreter.execute( sandbox, code="const msg: string = 'Hello TypeScript'; console.log(msg);", language="typescript", ) # List and manage contexts contexts = client.code_interpreter.list_contexts(sandbox) client.code_interpreter.delete_context(sandbox, ctx.id) finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Interactive Terminal Sessions Source: https://github.com/leap0-dev/leap0-python/blob/main/README.md Establish persistent interactive terminal sessions via WebSocket. ```python session = client.pty.create(sandbox, cols=120, rows=30, cwd="/home/user") conn = client.pty.connect(sandbox, session.id) conn.send("ls -la\n") print(conn.recv().decode()) conn.close() ``` -------------------------------- ### Leap0 SDK Error Handling Source: https://context7.com/leap0-dev/leap0-python/llms.txt Illustrates how to handle different types of errors from the Leap0 SDK, including base Leap0Error, API errors (Leap0APIError), WebSocket errors (Leap0WebSocketError), and configuration errors (ValueError). ```python from leap0 import ( Leap0, Leap0Config, Leap0Error, Leap0APIError, Leap0WebSocketError, ) client = Leap0(Leap0Config()) try: sandbox = client.sandboxes.create() try: # API errors (HTTP errors from the server) result = client.code_interpreter.execute( sandbox, code="invalid python syntax !!!", language="python", ) if result.error: print(f"Execution error: {result.error.name}") print(f"Message: {result.error.value}") print(f"Traceback:\n{result.error.traceback}") except Leap0APIError as e: print(f"API Error: {e}") try: # WebSocket errors session = client.pty.create(sandbox) conn = client.pty.connect(sandbox, session.id) except Leap0WebSocketError as e: print(f"WebSocket Error: {e}") except Leap0Error as e: # Base exception for all SDK errors print(f"Leap0 Error: {e}") except ValueError as e: # Configuration errors (missing API key) print(f"Configuration Error: {e}") finally: try: client.sandboxes.delete(sandbox) except Leap0Error: pass client.close() ``` -------------------------------- ### Stream Code Execution Output Source: https://context7.com/leap0-dev/leap0-python/llms.txt Use this to stream code execution output in real-time via Server-Sent Events. Ensure proper error handling and sandbox cleanup. ```python from leap0 import Leap0, Leap0Config client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: code = """ import time for i in range(5): print(f'Processing step {i}...') time.sleep(0.5) print('Done!') """ # Stream execution events for event in client.code_interpreter.execute_stream( sandbox, code=code, language="python", timeout_ms=30000, ): if event.type == "stdout": print(f"[OUT] {event.data}", end="") elif event.type == "stderr": print(f"[ERR] {event.data}", end="") elif event.type == "exit": print(f"\n[EXIT] Code: {event.code}") elif event.type == "error": print(f"[ERROR] {event.data}") finally: client.sandboxes.delete(sandbox) client.close() ``` -------------------------------- ### Edit Files with Find and Replace Source: https://context7.com/leap0-dev/leap0-python/llms.txt Modify file content by specifying find-and-replace operations. The result includes the number of replacements and a diff of the changes. ```python from leap0 import Leap0, Leap0Config, FileEdit client = Leap0(Leap0Config()) sandbox = client.sandboxes.create() try: # Edit files with find-and-replace edit_result = client.filesystem.edit_file( sandbox, path="/workspace/config.json", edits=[ FileEdit(find='"debug": true', replace='"debug": false'), ], ) print(f"Replacements: {edit_result.replacements}") print(f"Diff:\n{edit_result.diff}") finally: client.sandboxes.delete(sandbox) client.close() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.