Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Daytona
https://github.com/daytonaio/daytona
Admin
Daytona provides secure and elastic infrastructure for running AI-generated code, offering fast
...
Tokens:
452,528
Snippets:
2,390
Trust Score:
9.5
Update:
3 weeks ago
Context
Skills
Chat
Benchmark
83
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Daytona SDK Daytona is a secure and elastic infrastructure platform for running AI-generated code in isolated sandbox environments. It provides SDKs for Python, TypeScript, Go, and Ruby that enable developers to programmatically create, manage, and interact with sandboxes for secure code execution, file system operations, Git workflows, and Language Server Protocol (LSP) features. The platform offers sub-90ms sandbox creation, unlimited persistence, and OCI/Docker compatibility. The SDK architecture centers around the `Daytona` client class which manages sandbox lifecycle (create, start, stop, delete), and the `Sandbox` class which provides access to file system (`fs`), process execution (`process`), Git operations (`git`), code interpreter (`codeInterpreter`), and LSP functionality. Sandboxes can be created from pre-built snapshots or custom Docker images, with configurable resources (CPU, memory, disk, GPU) and automatic lifecycle management (auto-stop, auto-archive, auto-delete intervals). ## Daytona Client Initialization The main entry point for interacting with the Daytona API. Can be initialized with explicit configuration or environment variables (`DAYTONA_API_KEY`, `DAYTONA_API_URL`, `DAYTONA_TARGET`). ```python from daytona import Daytona, DaytonaConfig # Using environment variables (reads from DAYTONA_API_KEY, DAYTONA_API_URL) daytona = Daytona() # Using explicit configuration config = DaytonaConfig( api_key="your-api-key", api_url="https://app.daytona.io/api", target="us" ) daytona = Daytona(config) ``` ```typescript import { Daytona } from '@daytonaio/sdk' // Using environment variables const daytona = new Daytona() // Using explicit configuration const daytona = new Daytona({ apiKey: 'your-api-key', apiUrl: 'https://app.daytona.io/api', target: 'us' }) ``` ## Create Sandbox Creates a new sandbox from a snapshot or custom image. Returns a ready-to-use Sandbox instance after waiting for it to start. ```python from daytona import Daytona, CreateSandboxFromSnapshotParams, CreateSandboxFromImageParams, Resources daytona = Daytona() # Create default Python sandbox sandbox = daytona.create() # Create from snapshot with custom settings sandbox = daytona.create(CreateSandboxFromSnapshotParams( language="python", snapshot="my-snapshot-id", env_vars={"DEBUG": "true"}, auto_stop_interval=60, # Minutes of inactivity before auto-stop auto_archive_interval=1440, # Minutes before auto-archive (default: 7 days) auto_delete_interval=2880 # Minutes before auto-delete (negative to disable) ), timeout=60) # Create from Docker image with resources sandbox = daytona.create(CreateSandboxFromImageParams( image="python:3.12-slim", language="python", resources=Resources(cpu=2, memory=4, disk=20), ), timeout=150, on_snapshot_create_logs=print) ``` ```typescript const sandbox = await daytona.create({ language: 'typescript', envVars: { NODE_ENV: 'development' }, autoStopInterval: 60, autoArchiveInterval: 1440, }, { timeout: 60 }) // Create from image const sandbox = await daytona.create({ image: 'node:20-slim', language: 'javascript', resources: { cpu: 2, memory: 4, disk: 20 } }, { timeout: 150, onSnapshotCreateLogs: console.log }) ``` ## Execute Code and Commands Run code snippets or shell commands securely inside the sandbox. The `codeRun` method uses the appropriate language runtime based on the sandbox configuration. ```python from daytona import Daytona daytona = Daytona() sandbox = daytona.create() # Run Python code response = sandbox.process.code_run('print("Hello World!")') print(response.result) # Output: Hello World! print(response.exit_code) # 0 for success # Execute shell command response = sandbox.process.exec('ls -la /home', timeout=10) if response.exit_code == 0: print(response.result) # Execute with environment variables and working directory response = sandbox.process.exec( 'echo $MY_VAR', cwd='/tmp', env={'MY_VAR': 'Hello'} ) daytona.delete(sandbox) ``` ```typescript const sandbox = await daytona.create({ language: 'typescript' }) // Run TypeScript code const response = await sandbox.process.codeRun(` const x = 10 const y = 20 console.log(\`Sum: \${x + y}\`) `) console.log(response.result) // Output: Sum: 30 // Execute shell command with timeout const result = await sandbox.process.executeCommand('npm install', '/app', {}, 120) await daytona.delete(sandbox) ``` ## Stateful Code Interpreter Execute Python code in a stateful interpreter that maintains variable state between calls. Supports isolated execution contexts. ```python from daytona import Daytona, OutputMessage, ExecutionError daytona = Daytona() sandbox = daytona.create() # Run code maintaining state result = sandbox.code_interpreter.run_code("counter = 1\nprint(f'Counter: {counter}')") print(result.stdout) # Counter: 1 result = sandbox.code_interpreter.run_code("counter += 1\nprint(f'Counter: {counter}')") print(result.stdout) # Counter: 2 # Create isolated context ctx = sandbox.code_interpreter.create_context() try: result = sandbox.code_interpreter.run_code( "isolated_var = 'only in this context'", context=ctx ) # Access isolated_var only in same context result = sandbox.code_interpreter.run_code("print(isolated_var)", context=ctx) finally: sandbox.code_interpreter.delete_context(ctx) # With streaming callbacks def handle_stdout(msg: OutputMessage): print(f"[STDOUT] {msg.output}") def handle_error(error: ExecutionError): print(f"[ERROR] {error.name}: {error.value}") result = sandbox.code_interpreter.run_code( "print('streaming output')", on_stdout=handle_stdout, on_error=handle_error, timeout=30 ) daytona.delete(sandbox) ``` ## File System Operations Upload, download, create, delete, and search files within the sandbox. Supports both in-memory buffers and local file streaming. ```python from daytona import Daytona, FileUpload, FileDownloadRequest import json daytona = Daytona() sandbox = daytona.create() # Create directory sandbox.fs.create_folder("project/data", "755") # Upload files - from bytes or local path sandbox.fs.upload_files([ FileUpload(source=b'{"key": "value"}', destination="project/config.json"), FileUpload(source="local_file.txt", destination="project/file.txt"), ]) # Single file upload sandbox.fs.upload_file(b'print("hello")', "project/script.py") # List files files = sandbox.fs.list_files("project") for f in files: print(f"{f.name} - {f.size} bytes") # Download files results = sandbox.fs.download_files([ FileDownloadRequest(source="project/config.json"), # To memory FileDownloadRequest(source="project/file.txt", destination="local_copy.txt"), # To file ]) for result in results: if result.error: print(f"Error: {result.error}") elif isinstance(result.result, bytes): print(f"Content: {result.result.decode()}") # Search for files by pattern matches = sandbox.fs.search_files("project", "*.json") print(f"Found {len(matches.files)} JSON files") # Find text in files matches = sandbox.fs.find_files("project", "TODO:") for match in matches: print(f"{match.file}:{match.line}: {match.content}") # Replace text in files sandbox.fs.replace_in_files(["project/config.json"], '"key"', '"newKey"') # Delete file sandbox.fs.delete_file("project/script.py") daytona.delete(sandbox) ``` ```typescript await sandbox.fs.createFolder('app/data', '755') await sandbox.fs.uploadFiles([ { source: Buffer.from('content'), destination: 'app/file.txt' }, { source: 'local_file.txt', destination: 'app/copy.txt' } ]) const files = await sandbox.fs.listFiles('app') const content = await sandbox.fs.downloadFile('app/file.txt') await sandbox.fs.replaceInFiles(['app/file.txt'], 'old', 'new') await sandbox.fs.deleteFile('app/file.txt') ``` ## Git Operations Clone repositories, manage branches, stage changes, commit, push, and pull within the sandbox. ```python from daytona import Daytona daytona = Daytona() sandbox = daytona.create() # Clone repository sandbox.git.clone( url="https://github.com/user/repo.git", path="workspace/repo", branch="main", # Optional: specific branch username="user", # Optional: for private repos password="token" ) # Get repository status status = sandbox.git.status("workspace/repo") print(f"Branch: {status.current_branch}") print(f"Ahead: {status.ahead}, Behind: {status.behind}") # Branch operations branches = sandbox.git.branches("workspace/repo") sandbox.git.create_branch("workspace/repo", "feature-branch") sandbox.git.checkout_branch("workspace/repo", "feature-branch") # Stage, commit, and push sandbox.git.add("workspace/repo", ["."]) # Stage all response = sandbox.git.commit( path="workspace/repo", message="Add new feature", author="John Doe", email="john@example.com" ) print(f"Commit SHA: {response.sha}") sandbox.git.push("workspace/repo", username="user", password="token") # Pull changes sandbox.git.pull("workspace/repo") # Delete branch sandbox.git.delete_branch("workspace/repo", "old-branch") daytona.delete(sandbox) ``` ## Language Server Protocol (LSP) Get IDE-like features including code completion, symbol search, and document analysis for TypeScript, Python, and JavaScript. ```python from daytona import Daytona, CreateSandboxFromImageParams, Image, LspCompletionPosition daytona = Daytona() # Create sandbox with TypeScript support sandbox = daytona.create(CreateSandboxFromImageParams( image=Image.base("ubuntu:24.04").run_commands( "apt-get update && apt-get install -y nodejs npm", "npm install -g typescript typescript-language-server" ) ), timeout=200, on_snapshot_create_logs=print) # Clone a TypeScript project sandbox.git.clone("https://github.com/user/ts-project.git", "project") # Create and start LSP server lsp = sandbox.create_lsp_server("typescript", "project") lsp.start() # Open a file for analysis lsp.did_open("project/src/index.ts") # Get document symbols (functions, classes, variables) symbols = lsp.document_symbols("project/src/index.ts") for symbol in symbols: print(f"{symbol.kind}: {symbol.name} at {symbol.location}") # Get code completions at position completions = lsp.completions( "project/src/index.ts", LspCompletionPosition(line=10, character=15) ) for item in completions.items: print(f"{item.label}: {item.detail}") # Search symbols across project symbols = lsp.sandbox_symbols("UserService") # Clean up lsp.did_close("project/src/index.ts") lsp.stop() daytona.delete(sandbox) ``` ## Background Sessions Create persistent shell sessions for running long commands and maintaining state between executions. ```python from daytona import Daytona daytona = Daytona() sandbox = daytona.create() # Create session sandbox.process.create_session("build-session") # Execute commands in session (maintains state like cd) result = sandbox.process.exec_session_command("build-session", { "command": "cd /app && export BUILD_ENV=production" }) result = sandbox.process.exec_session_command("build-session", { "command": "npm run build" }) print(f"[STDOUT] {result.stdout}") print(f"[STDERR] {result.stderr}") print(f"Exit code: {result.exit_code}") # Run async command result = sandbox.process.exec_session_command("build-session", { "command": "npm run watch", "run_async": True }) cmd_id = result.cmd_id # Get command logs (streaming) sandbox.process.get_session_command_logs( "build-session", cmd_id, on_stdout=lambda chunk: print(f"[OUT] {chunk}"), on_stderr=lambda chunk: print(f"[ERR] {chunk}") ) # List sessions sessions = sandbox.process.list_sessions() # Delete session when done sandbox.process.delete_session("build-session") daytona.delete(sandbox) ``` ## PTY (Pseudo-Terminal) Sessions Create interactive terminal sessions for real-time command execution with input/output streaming. ```python from daytona import Daytona daytona = Daytona() sandbox = daytona.create() def handle_output(data: bytes): print(data.decode(), end='') # Create PTY session pty = sandbox.process.create_pty({ "id": "interactive-shell", "cwd": "/home/daytona", "cols": 120, "rows": 30, "on_data": handle_output }) # Wait for connection pty.wait_for_connection() # Send commands pty.send_input("ls -la\n") pty.send_input("echo 'Hello PTY'\n") pty.send_input("exit\n") # Wait for completion result = pty.wait() print(f"Exit code: {result.exit_code}") # Resize terminal pty.resize(150, 40) # Disconnect pty.disconnect() daytona.delete(sandbox) ``` ## Declarative Image Builder Build custom Docker images programmatically with pip packages, local files, environment variables, and shell commands. ```python from daytona import Daytona, CreateSandboxFromImageParams, Image, Resources daytona = Daytona() # Build image with pip packages image = ( Image.debian_slim("3.12") .pip_install(["numpy", "pandas", "scikit-learn"]) .env({"PYTHONUNBUFFERED": "1"}) .workdir("/app") ) # Build from requirements.txt image = ( Image.debian_slim("3.12") .pip_install_from_requirements("requirements.txt") ) # Build with custom commands and local files image = ( Image.base("ubuntu:24.04") .run_commands( "apt-get update && apt-get install -y curl git", "curl -fsSL https://deb.nodesource.com/setup_20.x | bash -", "apt-get install -y nodejs" ) .add_local_file("config.json", "/app/config.json") .add_local_dir("src", "/app/src") .env({"NODE_ENV": "production"}) .entrypoint(["node", "/app/src/index.js"]) ) # Create sandbox from image sandbox = daytona.create( CreateSandboxFromImageParams( image=image, resources=Resources(cpu=2, memory=4, disk=20) ), timeout=300, on_snapshot_create_logs=print ) daytona.delete(sandbox) ``` ```typescript import { Image } from '@daytonaio/sdk' const image = Image.debianSlim('3.12') .pipInstall(['numpy', 'pandas']) .env({ PYTHONUNBUFFERED: '1' }) .workdir('/app') const sandbox = await daytona.create({ image, resources: { cpu: 2, memory: 4 } }, { timeout: 300, onSnapshotCreateLogs: console.log }) ``` ## Snapshot Management Create, list, and manage reusable sandbox snapshots for faster startup times. ```python from daytona import Daytona, Image, Resources daytona = Daytona() # List snapshots result = daytona.snapshot.list(page=1, limit=10) for snapshot in result.items: print(f"{snapshot.name}: {snapshot.state}") # Get snapshot by name snapshot = daytona.snapshot.get("my-snapshot") # Create new snapshot from image image = Image.debian_slim("3.12").pip_install(["numpy"]) snapshot = daytona.snapshot.create( { "name": "ml-snapshot", "image": image, "resources": Resources(cpu=2, memory=4, disk=20), "entrypoint": ["python"] }, {"on_logs": print, "timeout": 300} ) # Delete snapshot daytona.snapshot.delete(snapshot) ``` ```typescript const snapshots = await daytona.snapshot.list(1, 10) const snapshot = await daytona.snapshot.create({ name: 'my-snapshot', image: Image.debianSlim('3.12').pipInstall(['numpy']), resources: { cpu: 2, memory: 4 } }, { onLogs: console.log }) await daytona.snapshot.delete(snapshot) ``` ## Volume Management Create and manage persistent storage volumes that can be mounted to sandboxes. ```python from daytona import Daytona, CreateSandboxFromSnapshotParams, VolumeMount daytona = Daytona() # Create volume volume = daytona.volume.create("my-data-volume") print(f"Created volume: {volume.id}") # List volumes volumes = daytona.volume.list() for v in volumes: print(f"{v.name}: {v.state}") # Get volume (create if not exists) volume = daytona.volume.get("shared-data", create=True) # Mount volume to sandbox sandbox = daytona.create(CreateSandboxFromSnapshotParams( language="python", volumes=[ VolumeMount( volume_id=volume.id, mount_path="/data", subpath="project1" # Optional: mount specific prefix ) ] )) # Use mounted volume sandbox.fs.upload_file(b"shared data", "/data/file.txt") daytona.delete(sandbox) daytona.volume.delete(volume) ``` ## Sandbox Lifecycle Management Control sandbox state with start, stop, archive, resize, and automatic lifecycle management. ```python from daytona import Daytona, Resources daytona = Daytona() sandbox = daytona.create() # Stop sandbox sandbox.stop(timeout=60) # Archive for long-term storage (must be stopped first) sandbox.archive() # Start sandbox sandbox.start(timeout=60) # Resize resources (hot resize for CPU/memory, cold resize for disk) sandbox.resize(Resources(cpu=4, memory=8), timeout=60) # Set auto-stop interval (minutes of inactivity) sandbox.set_autostop_interval(30) # 0 to disable # Set auto-archive interval (minutes after stop) sandbox.set_auto_archive_interval(1440) # 24 hours # Set auto-delete interval (minutes after stop, negative to disable) sandbox.set_auto_delete_interval(2880) # 48 hours # Refresh activity timer sandbox.refresh_activity() # Get updated sandbox data sandbox.refresh_data() print(f"State: {sandbox.state}") print(f"CPU: {sandbox.cpu}, Memory: {sandbox.memory}GB") # Delete sandbox daytona.delete(sandbox, timeout=60) ``` ## Preview URLs and SSH Access Generate preview URLs for web applications and SSH access for direct terminal connections. ```python from daytona import Daytona daytona = Daytona() sandbox = daytona.create() # Start a web server sandbox.process.exec("python -m http.server 8080 &") # Get preview URL for port preview = sandbox.get_preview_link(8080) print(f"URL: {preview.url}") print(f"Token: {preview.token}") # For private sandboxes # Get signed preview URL with expiration signed = sandbox.get_signed_preview_url(8080, expires_in_seconds=3600) print(f"Signed URL: {signed.url}") # Expire signed URL sandbox.expire_signed_preview_url(8080, signed.token) # Create SSH access ssh = sandbox.create_ssh_access(expires_in_minutes=60) print(f"SSH Command: ssh -p {ssh.port} {ssh.user}@{ssh.host}") print(f"Token: {ssh.token}") # Validate SSH token validation = sandbox.validate_ssh_access(ssh.token) print(f"Valid: {validation.valid}") # Revoke SSH access sandbox.revoke_ssh_access(ssh.token) daytona.delete(sandbox) ``` ## Error Handling Handle Daytona-specific errors including timeouts, rate limits, and not found errors. ```python from daytona import ( Daytona, DaytonaError, DaytonaTimeoutError, DaytonaNotFoundError, DaytonaRateLimitError ) daytona = Daytona() try: sandbox = daytona.create(timeout=30) result = sandbox.process.code_run("import time; time.sleep(60)", timeout=5) except DaytonaTimeoutError as e: print(f"Operation timed out: {e}") except DaytonaNotFoundError as e: print(f"Resource not found: {e}") except DaytonaRateLimitError as e: print(f"Rate limited: {e}") print(f"Retry after: {e.headers.get('Retry-After')} seconds") except DaytonaError as e: print(f"Daytona error: {e}") print(f"Status code: {e.status_code}") finally: if 'sandbox' in locals(): daytona.delete(sandbox) ``` ```typescript import { DaytonaError, DaytonaNotFoundError, DaytonaRateLimitError } from '@daytonaio/sdk' try { const sandbox = await daytona.create({}, { timeout: 30 }) } catch (error) { if (error instanceof DaytonaNotFoundError) { console.error('Resource not found:', error.message) } else if (error instanceof DaytonaRateLimitError) { console.error('Rate limited, retry after:', error.headers?.['retry-after']) } else if (error instanceof DaytonaError) { console.error('Daytona error:', error.message, error.statusCode) } } ``` ## Summary Daytona SDK provides a comprehensive platform for secure AI code execution with multi-language support (Python, TypeScript, Go, Ruby). The primary use cases include: running untrusted AI-generated code in isolated sandboxes, building automated development workflows with Git and LSP integration, creating reproducible development environments from Docker images or snapshots, and implementing stateful code interpreters for interactive sessions. The declarative Image builder enables custom environment configuration without manual Dockerfile management. Integration patterns typically follow a lifecycle of: initialize client with API credentials, create sandbox from snapshot or custom image with resource specifications, execute code or commands via the process API, manage files through the filesystem API, optionally use Git for version control and LSP for code intelligence, and finally clean up by deleting the sandbox. For production deployments, configure auto-stop/archive/delete intervals to manage costs, use volumes for persistent shared storage, create snapshots for frequently-used environments, and implement proper error handling with the typed exception hierarchy.