An open-source, faster Devin alternative
TypeScript
add more examples
motatoesf9e7cbf94da5
diff --git a/.dockerignore b/.dockerignoreindex be89e42b..667428e9 100644--- a/.dockerignore+++ b/.dockerignore@@ -2,8 +2,12 @@ target/.git/.gitignore*.md-examples/docker-compose.ymlfly.toml.env.env.*++# Exclude most examples but allow specific ones+examples/*+!examples/claude-agent-sdk-test/+!examples/claude-chat/diff --git a/Dockerfile b/Dockerfileindex 90a1a0bb..055f2c62 100644--- a/Dockerfile+++ b/Dockerfile@@ -31,6 +31,14 @@ RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg -o&& apt-get install -y gh \&& rm -rf /var/lib/apt/lists/*+# Install Node.js 20.x+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 CLI+RUN npm install -g @anthropic-ai/claude-code+COPY --from=builder /app/target/release/isolate /usr/local/bin/isolateEXPOSE 8080diff --git a/examples/claude-agent-sdk-test/.env.example b/examples/claude-agent-sdk-test/.env.examplenew file mode 100644index 00000000..3dfb0597--- /dev/null+++ b/examples/claude-agent-sdk-test/.env.example@@ -0,0 +1,12 @@+# Copy this file to .env and fill in your values++# Required for Claude Agent SDK: Your Anthropic API key+ANTHROPIC_API_KEY=sk-ant-...++# Optional: OpenSandbox server URL (defaults to http://localhost:8080)+OPENSANDBOX_URL=http://localhost:8080+OPENSANDBOX_GRPC_PORT=50051++# Optional: E2B API key (for comparison tests)+# Get one at https://e2b.dev+E2B_API_KEY=e2b_...diff --git a/examples/claude-agent-sdk-test/Dockerfile b/examples/claude-agent-sdk-test/Dockerfilenew file mode 100644index 00000000..bd28d6d1--- /dev/null+++ b/examples/claude-agent-sdk-test/Dockerfile@@ -0,0 +1,40 @@+# Dockerfile for testing OpenSandbox + Claude Agent SDK+# This image can be used as:+# 1. A client that connects to OpenSandbox and runs Claude Agent SDK tasks+# 2. A base for the sandbox itself (with Claude Code pre-installed)++FROM python:3.11-slim++WORKDIR /app++# Install system dependencies+RUN apt-get update && apt-get install -y \+ curl \+ git \+ ca-certificates \+ gnupg \+ && rm -rf /var/lib/apt/lists/*++# Install Node.js (required for Claude Code CLI)+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 CLI globally via npm+# Note: This may fail if the package isn't published yet - that's OK for testing+RUN npm install -g @anthropic-ai/claude-code || echo "Claude Code npm package not yet available"++# Install Python dependencies first (for caching)+COPY requirements.txt .+RUN pip install --no-cache-dir -r requirements.txt || \+ pip install --no-cache-dir grpcio grpcio-tools protobuf httpx pytest pytest-asyncio++# Copy test scripts+COPY *.py ./++# Set environment variables+ENV PYTHONUNBUFFERED=1+ENV PYTHONPATH=/app++# Default command - can be overridden+CMD ["python", "test_agent.py"]diff --git a/examples/claude-agent-sdk-test/Dockerfile.full b/examples/claude-agent-sdk-test/Dockerfile.fullnew file mode 100644index 00000000..8ff0e19c--- /dev/null+++ b/examples/claude-agent-sdk-test/Dockerfile.full@@ -0,0 +1,46 @@+# Dockerfile.full - Build from repo root to include OpenSandbox SDK+# Usage: docker build -f examples/claude-agent-sdk-test/Dockerfile.full -t claude-sandbox-test .++FROM python:3.11-slim++WORKDIR /app++# Install system dependencies+RUN apt-get update && apt-get install -y \+ curl \+ git \+ ca-certificates \+ gnupg \+ && rm -rf /var/lib/apt/lists/*++# Install Node.js (required for Claude Code CLI)+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 CLI globally via npm+RUN npm install -g @anthropic-ai/claude-code 2>/dev/null || \+ echo "Note: Claude Code npm package not available, will test without it"++# Copy and install the OpenSandbox Python SDK+COPY sdk/python /app/opensandbox-sdk+RUN pip install --no-cache-dir /app/opensandbox-sdk++# Install additional Python dependencies+RUN pip install --no-cache-dir \+ pytest \+ pytest-asyncio++# Install Claude Code SDK and E2B for comparison+RUN pip install --no-cache-dir claude-code-sdk e2b 2>/dev/null || \+ echo "Note: Some SDKs may not be available"++# Copy test scripts+COPY examples/claude-agent-sdk-test/*.py ./++# Set environment variables+ENV PYTHONUNBUFFERED=1+ENV PYTHONPATH=/app++# Default command+CMD ["python", "test_agent.py"]diff --git a/examples/claude-agent-sdk-test/compare_e2b.py b/examples/claude-agent-sdk-test/compare_e2b.pynew file mode 100644index 00000000..1f9fb333--- /dev/null+++ b/examples/claude-agent-sdk-test/compare_e2b.py@@ -0,0 +1,290 @@+#!/usr/bin/env python3+"""+Compare OpenSandbox vs E2B for Claude Agent SDK integration.++This script runs the same operations on both sandbox providers+to compare their APIs and performance.++Requirements:+- E2B_API_KEY environment variable for E2B+- OPENSANDBOX_URL environment variable for OpenSandbox (or localhost:8080)+"""++import asyncio+import os+import time+from dataclasses import dataclass+from typing import Optional, Protocol+++@dataclass+class CommandResult:+ """Result of a command execution."""+ stdout: str+ stderr: str+ exit_code: int+ duration_ms: float = 0.0+++class SandboxProvider(Protocol):+ """Protocol for sandbox providers."""++ @property+ def name(self) -> str: ...+ async def create(self) -> None: ...+ async def run_command(self, command: str) -> CommandResult: ...+ async def write_file(self, path: str, content: str) -> float: ...+ async def read_file(self, path: str) -> str: ...+ async def destroy(self) -> None: ...+++class OpenSandboxProvider:+ """OpenSandbox implementation."""++ def __init__(self):+ self._client = None+ self._sandbox = None++ @property+ def name(self) -> str:+ return "OpenSandbox"++ async def create(self) -> None:+ from opensandbox import OpenSandbox++ url = os.environ.get("OPENSANDBOX_URL", "http://localhost:8080")+ grpc_port = int(os.environ.get("OPENSANDBOX_GRPC_PORT", "50051"))+ # Use insecure gRPC for Fly.io (raw TCP, no TLS on gRPC port)+ grpc_insecure = os.environ.get("OPENSANDBOX_GRPC_INSECURE", "").lower() in ("1", "true", "yes")++ self._client = OpenSandbox(url, grpc_port=grpc_port, grpc_insecure=grpc_insecure)+ await self._client._ensure_connected()+ self._sandbox = await self._client.create()++ async def run_command(self, command: str) -> CommandResult:+ start = time.perf_counter()+ result = await self._sandbox.run(command)+ duration = (time.perf_counter() - start) * 1000++ return CommandResult(+ stdout=result.stdout,+ stderr=result.stderr,+ exit_code=result.exit_code,+ duration_ms=duration,+ )++ async def write_file(self, path: str, content: str) -> float:+ start = time.perf_counter()+ await self._sandbox.write_file(path, content)+ return (time.perf_counter() - start) * 1000++ async def read_file(self, path: str) -> str:+ content = await self._sandbox.read_file_text(path)+ return content++ async def destroy(self) -> None:+ if self._sandbox:+ await self._sandbox.destroy()+ if self._client:+ await self._client.close()+++class E2BProvider:+ """E2B implementation."""++ def __init__(self):+ self._sandbox = None++ @property+ def name(self) -> str:+ return "E2B"++ async def create(self) -> None:+ from e2b import Sandbox+ # E2B SDK is synchronous, run in executor+ loop = asyncio.get_event_loop()+ self._sandbox = await loop.run_in_executor(+ None, lambda: Sandbox.create(timeout=300)+ )++ async def run_command(self, command: str) -> CommandResult:+ loop = asyncio.get_event_loop()++ start = time.perf_counter()+ result = await loop.run_in_executor(+ None, lambda: self._sandbox.commands.run(command, timeout=60)+ )+ duration = (time.perf_counter() - start) * 1000++ return CommandResult(+ stdout=result.stdout,+ stderr=result.stderr,+ exit_code=result.exit_code,+ duration_ms=duration,+ )++ async def write_file(self, path: str, content: str) -> float:+ loop = asyncio.get_event_loop()+ start = time.perf_counter()+ await loop.run_in_executor(+ None, lambda: self._sandbox.files.write(path, content)+ )+ return (time.perf_counter() - start) * 1000++ async def read_file(self, path: str) -> str:+ loop = asyncio.get_event_loop()+ content = await loop.run_in_executor(+ None, lambda: self._sandbox.files.read(path)+ )+ return content++ async def destroy(self) -> None:+ if self._sandbox:+ loop = asyncio.get_event_loop()+ await loop.run_in_executor(None, self._sandbox.kill)+++async def run_benchmark(provider: SandboxProvider) -> dict:+ """Run a set of benchmark operations on a provider."""+ results = {+ "name": provider.name,+ "create_ms": 0,+ "command_ms": [],+ "write_ms": [],+ "read_ms": [],+ "errors": [],+ }++ try:+ # Create sandbox+ start = time.perf_counter()+ await provider.create()+ results["create_ms"] = (time.perf_counter() - start) * 1000+ print(f" Created sandbox: {results['create_ms']:.1f}ms")++ # Run commands+ for cmd in ["echo hello", "uname -a", "ls -la /", "cat /etc/os-release"]:+ result = await provider.run_command(cmd)+ results["command_ms"].append(result.duration_ms)+ print(f" Command '{cmd[:20]}...': {result.duration_ms:.1f}ms")++ # Write files+ for size in [100, 1000, 10000]:+ content = "x" * size+ duration = await provider.write_file(f"/tmp/test_{size}.txt", content)+ results["write_ms"].append(duration)+ print(f" Write {size} bytes: {duration:.1f}ms")++ # Read files+ for size in [100, 1000, 10000]:+ start = time.perf_counter()+ content = await provider.read_file(f"/tmp/test_{size}.txt")+ duration = (time.perf_counter() - start) * 1000+ results["read_ms"].append(duration)+ print(f" Read {size} bytes: {duration:.1f}ms")++ except Exception as e:+ results["errors"].append(str(e))+ print(f" Error: {e}")++ finally:+ try:+ await provider.destroy()+ print(" Destroyed sandbox")+ except Exception as e:+ results["errors"].append(f"Destroy error: {e}")++ return results+++def print_comparison(results: list[dict]):+ """Print a comparison table of results."""+ print("\n" + "=" * 70)+ print("COMPARISON SUMMARY")+ print("=" * 70)++ headers = ["Metric", *[r["name"] for r in results]]+ print(f"\n{headers[0]:<25} {headers[1]:<20} {headers[2] if len(headers) > 2 else '':<20}")+ print("-" * 65)++ metrics = [+ ("Create sandbox", "create_ms", None),+ ("Avg command exec", "command_ms", lambda x: sum(x) / len(x) if x else 0),+ ("Avg file write", "write_ms", lambda x: sum(x) / len(x) if x else 0),+ ("Avg file read", "read_ms", lambda x: sum(x) / len(x) if x else 0),+ ]++ for label, key, transform in metrics:+ row = [label]+ for r in results:+ val = r.get(key, 0)+ if transform and isinstance(val, list):+ val = transform(val)+ if isinstance(val, (int, float)):+ row.append(f"{val:.1f}ms")+ else:+ row.append("N/A")++ print(f"{row[0]:<25} {row[1]:<20} {row[2] if len(row) > 2 else '':<20}")++ print("\n" + "=" * 70)+++async def main():+ """Run comparison between E2B and OpenSandbox."""+ print("\n" + "=" * 70)+ print("E2B vs OpenSandbox Comparison")+ print("=" * 70)++ results = []++ # Test OpenSandbox+ print("\n[OpenSandbox]")+ try:+ provider = OpenSandboxProvider()+ result = await run_benchmark(provider)+ results.append(result)+ except ImportError:+ print(" OpenSandbox SDK not available")+ except Exception as e:+ print(f" OpenSandbox failed: {e}")++ # Test E2B+ print("\n[E2B]")+ e2b_key = os.environ.get("E2B_API_KEY")+ if not e2b_key:+ print(" Skipped: E2B_API_KEY not set")+ else:+ try:+ provider = E2BProvider()+ result = await run_benchmark(provider)+ results.append(result)+ except ImportError:+ print(" E2B SDK not available (pip install e2b)")+ except Exception as e:+ print(f" E2B failed: {e}")++ if len(results) >= 1:+ print_comparison(results)++ # Print feature comparison+ print("\n" + "=" * 70)+ print("FEATURE COMPARISON")+ print("=" * 70)+ print("""+| Feature | OpenSandbox | E2B |+|----------------------------|----------------------|------------------------|+| Hosting | Self-hosted / Fly.io | Cloud only |+| Protocol | gRPC + HTTP | HTTP (WebSocket) |+| Pricing | Free (self-hosted) | Pay per use |+| Session timeout | 5 min default | Configurable |+| Network access | Full | Full |+| Custom images | Docker-based | Custom templates |+| File operations | Native gRPC | HTTP-based |+| Interactive terminal | No | Yes (WebSocket) |+| Claude Code integration | Via SDK | Via SDK |+""")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/claude-agent-sdk-test/docker-compose.yml b/examples/claude-agent-sdk-test/docker-compose.ymlnew file mode 100644index 00000000..4515ded6--- /dev/null+++ b/examples/claude-agent-sdk-test/docker-compose.yml@@ -0,0 +1,34 @@+services:+ # OpenSandbox server+ opensandbox:+ build:+ context: ../..+ dockerfile: Dockerfile+ ports:+ - "8080:8080"+ - "50051:50051"+ privileged: true # Required for Linux namespaces+ environment:+ - RUST_LOG=info+ healthcheck:+ test: ["CMD", "curl", "-f", "http://localhost:8080/health"]+ interval: 5s+ timeout: 5s+ retries: 10+ start_period: 10s++ # The test runner - connects to OpenSandbox and runs Claude Agent SDK+ # Built from repo root to include the SDK+ test-runner:+ build:+ context: ../..+ dockerfile: examples/claude-agent-sdk-test/Dockerfile.full+ environment:+ - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}+ - E2B_API_KEY=${E2B_API_KEY}+ - OPENSANDBOX_URL=http://opensandbox:8080+ - OPENSANDBOX_GRPC_PORT=50051+ depends_on:+ opensandbox:+ condition: service_healthy+ command: python test_agent.pydiff --git a/examples/claude-agent-sdk-test/requirements.txt b/examples/claude-agent-sdk-test/requirements.txtnew file mode 100644index 00000000..f5e68ec5--- /dev/null+++ b/examples/claude-agent-sdk-test/requirements.txt@@ -0,0 +1,15 @@+# OpenSandbox SDK dependencies+grpcio>=1.60.0+grpcio-tools>=1.60.0+protobuf>=4.25.0+httpx>=0.27.0++# Claude Agent SDK (Python wrapper)+claude-code-sdk>=0.0.25++# E2B (optional, for comparison)+e2b>=1.0.0++# For testing+pytest>=7.0.0+pytest-asyncio>=0.21.0diff --git a/examples/claude-agent-sdk-test/run.sh b/examples/claude-agent-sdk-test/run.shnew file mode 100755index 00000000..30647109--- /dev/null+++ b/examples/claude-agent-sdk-test/run.sh@@ -0,0 +1,85 @@+#!/bin/bash+# Run script for testing OpenSandbox + Claude Agent SDK++set -e++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+NC='\033[0m' # No Color++echo -e "${GREEN}OpenSandbox + Claude Agent SDK Test${NC}"+echo "========================================"++# Check for .env file+if [ ! -f "$SCRIPT_DIR/.env" ]; then+ echo -e "${YELLOW}Warning: No .env file found. Creating from .env.example${NC}"+ if [ -f "$SCRIPT_DIR/.env.example" ]; then+ cp "$SCRIPT_DIR/.env.example" "$SCRIPT_DIR/.env"+ echo -e "${YELLOW}Please edit .env and add your ANTHROPIC_API_KEY${NC}"+ fi+fi++# Parse arguments+ACTION="${1:-up}"++case "$ACTION" in+ build)+ echo -e "\n${GREEN}Building images...${NC}"+ cd "$SCRIPT_DIR"+ docker compose build+ ;;++ up)+ echo -e "\n${GREEN}Starting services...${NC}"+ cd "$SCRIPT_DIR"+ docker compose up --build+ ;;++ down)+ echo -e "\n${GREEN}Stopping services...${NC}"+ cd "$SCRIPT_DIR"+ docker compose down+ ;;++ test-local)+ echo -e "\n${GREEN}Running tests locally (requires OpenSandbox running)...${NC}"+ cd "$SCRIPT_DIR"++ # Check if ANTHROPIC_API_KEY is set+ if [ -z "$ANTHROPIC_API_KEY" ]; then+ if [ -f .env ]; then+ export $(grep -v '^#' .env | xargs)+ fi+ fi++ # Install dependencies if needed+ pip install -q grpcio grpcio-tools protobuf httpx+ pip install -q -e "$REPO_ROOT/sdk/python" 2>/dev/null || true++ python test_agent.py+ ;;++ build-full)+ echo -e "\n${GREEN}Building full image from repo root...${NC}"+ cd "$REPO_ROOT"+ docker build -f examples/claude-agent-sdk-test/Dockerfile.full -t claude-sandbox-test .+ ;;++ *)+ echo "Usage: $0 {build|up|down|test-local|build-full}"+ echo ""+ echo " build - Build Docker images"+ echo " up - Start all services with docker compose"+ echo " down - Stop all services"+ echo " test-local - Run tests locally (OpenSandbox must be running)"+ echo " build-full - Build image from repo root (includes SDK)"+ exit 1+ ;;+esac++echo -e "\n${GREEN}Done!${NC}"diff --git a/examples/claude-agent-sdk-test/test_agent.py b/examples/claude-agent-sdk-test/test_agent.pynew file mode 100644index 00000000..f63dfdae--- /dev/null+++ b/examples/claude-agent-sdk-test/test_agent.py@@ -0,0 +1,181 @@+#!/usr/bin/env python3+"""+Test script for OpenSandbox + Claude Agent SDK integration.++This script demonstrates two approaches:+1. Running Claude Agent SDK directly (tools execute locally)+2. Using OpenSandbox to isolate code execution+"""++import asyncio+import os+from typing import Optional+++async def test_claude_sdk_direct():+ """Test Claude Agent SDK running directly (no sandbox)."""+ try:+ from claude_code_sdk import query, ClaudeCodeOptions++ print("=" * 60)+ print("Test 1: Claude Agent SDK (Direct Execution)")+ print("=" * 60)++ api_key = os.environ.get("ANTHROPIC_API_KEY")+ if not api_key:+ print("Skipped: ANTHROPIC_API_KEY not set\n")+ return++ prompt = "What is 2 + 2? Reply with just the number."++ print(f"Prompt: {prompt}\n")+ print("Response:")++ async for message in query(+ prompt=prompt,+ options=ClaudeCodeOptions(+ max_turns=3,+ )+ ):+ if hasattr(message, 'content'):+ print(message.content)+ elif hasattr(message, 'result'):+ print(f"Result: {message.result}")++ print("\n[Direct execution test completed]\n")++ except ImportError as e:+ print("=" * 60)+ print("Test 1: Claude Agent SDK (Direct Execution)")+ print("=" * 60)+ print(f"Claude Agent SDK not available: {e}")+ print("Make sure claude-code-sdk is installed.\n")+ except Exception as e:+ print(f"Error during Claude SDK test: {e}\n")+++async def test_opensandbox_connection():+ """Test basic OpenSandbox connectivity."""+ try:+ from opensandbox import OpenSandbox++ print("=" * 60)+ print("Test 2: OpenSandbox Connection")+ print("=" * 60)++ sandbox_url = os.environ.get("OPENSANDBOX_URL", "http://localhost:8080")+ grpc_port = int(os.environ.get("OPENSANDBOX_GRPC_PORT", "50051"))++ print(f"Connecting to: {sandbox_url} (gRPC port: {grpc_port})\n")++ async with OpenSandbox(sandbox_url, grpc_port=grpc_port) as client:+ # Create a sandbox session+ sandbox = await client.create(+ env={"TEST_VAR": "hello_from_sandbox"}+ )++ print(f"Created sandbox session: {sandbox.session_id}")++ # Run a simple command+ result = await sandbox.run("echo $TEST_VAR && uname -a")+ print(f"Command output:\n{result.stdout}")++ if result.stderr:+ print(f"Stderr: {result.stderr}")++ print(f"Exit code: {result.exit_code}")++ # Test file operations+ print("\nTesting file operations...")+ await sandbox.write_file("/tmp/test.txt", "Hello from OpenSandbox!")+ content = await sandbox.read_file_text("/tmp/test.txt")+ print(f"File content: {content}")++ # Clean up+ await sandbox.destroy()+ print("\n[Sandbox session destroyed]\n")++ except ImportError as e:+ print("=" * 60)+ print("Test 2: OpenSandbox Connection")+ print("=" * 60)+ print(f"OpenSandbox SDK not available: {e}\n")+ except Exception as e:+ print("=" * 60)+ print("Test 2: OpenSandbox Connection")+ print("=" * 60)+ print(f"OpenSandbox test failed: {e}\n")+ import traceback+ traceback.print_exc()+++async def test_claude_in_sandbox():+ """+ Test running Claude Agent SDK with tools executing inside OpenSandbox.++ This is the advanced use case where:+ - Claude Agent SDK runs in the host/orchestrator+ - Tool execution (Bash, file ops) happens inside the sandbox+ """+ try:+ from opensandbox import OpenSandbox++ print("=" * 60)+ print("Test 3: Check Claude Code in Sandbox")+ print("=" * 60)+ print("Checking if Claude Code CLI is available in the sandbox...\n")++ sandbox_url = os.environ.get("OPENSANDBOX_URL", "http://localhost:8080")+ grpc_port = int(os.environ.get("OPENSANDBOX_GRPC_PORT", "50051"))++ async with OpenSandbox(sandbox_url, grpc_port=grpc_port) as client:+ sandbox = await client.create()++ print(f"Created sandbox session: {sandbox.session_id}")++ # Check available tools+ result = await sandbox.run("which python3 git curl")+ print(f"Available tools:\n{result.stdout}")++ # Check if Claude Code could be installed+ result = await sandbox.run("which node npm 2>/dev/null || echo 'Node.js not installed'")+ print(f"Node.js status: {result.stdout.strip()}")++ await sandbox.destroy()+ print("\n[Integration test completed]\n")++ except ImportError as e:+ print("=" * 60)+ print("Test 3: Check Claude Code in Sandbox")+ print("=" * 60)+ print(f"OpenSandbox SDK not available: {e}\n")+ except Exception as e:+ print("=" * 60)+ print("Test 3: Check Claude Code in Sandbox")+ print("=" * 60)+ print(f"Integration test failed: {e}\n")+++async def main():+ """Run all tests."""+ print("\n" + "=" * 60)+ print("OpenSandbox + Claude Agent SDK Test Suite")+ print("=" * 60 + "\n")++ # Check for required environment variables+ api_key = os.environ.get("ANTHROPIC_API_KEY")+ if not api_key:+ print("Note: ANTHROPIC_API_KEY not set. Claude SDK tests will be skipped.\n")++ # Run tests+ await test_opensandbox_connection()+ await test_claude_sdk_direct()+ await test_claude_in_sandbox()++ print("=" * 60)+ print("All tests completed!")+ print("=" * 60)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/claude-chat/.env.example b/examples/claude-chat/.env.examplenew file mode 100644index 00000000..6260f6b0--- /dev/null+++ b/examples/claude-chat/.env.example@@ -0,0 +1,4 @@+# Copy to .env and fill in your values++# Required: Your Anthropic API key+ANTHROPIC_API_KEY=sk-ant-...diff --git a/examples/claude-chat/Dockerfile b/examples/claude-chat/Dockerfilenew file mode 100644index 00000000..8c61c1b9--- /dev/null+++ b/examples/claude-chat/Dockerfile@@ -0,0 +1,40 @@+# Dockerfile for Claude Chat with OpenSandbox+# Build from repo root: docker build -f examples/claude-chat/Dockerfile -t claude-chat .++FROM python:3.11-slim++WORKDIR /app++# Install system dependencies+RUN apt-get update && apt-get install -y \+ curl \+ git \+ ca-certificates \+ gnupg \+ && rm -rf /var/lib/apt/lists/*++# Install Node.js (required for Claude Code CLI)+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 CLI+RUN npm install -g @anthropic-ai/claude-code++# Copy and install OpenSandbox SDK+COPY sdk/python /app/opensandbox-sdk+RUN pip install --no-cache-dir /app/opensandbox-sdk++# Copy and install chat app requirements+COPY examples/claude-chat/requirements.txt /app/requirements.txt+RUN pip install --no-cache-dir -r requirements.txt++# Copy chat application+COPY examples/claude-chat/app.py /app/+COPY examples/claude-chat/static /app/static/++ENV PYTHONUNBUFFERED=1++EXPOSE 8000++CMD ["python", "app.py"]diff --git a/examples/claude-chat/app.py b/examples/claude-chat/app.pynew file mode 100644index 00000000..3f381ec5--- /dev/null+++ b/examples/claude-chat/app.py@@ -0,0 +1,246 @@+#!/usr/bin/env python3+"""+Real-time chat interface for Claude Agent SDK with OpenSandbox integration.++This provides a WebSocket-based chat interface where you can interact with+Claude in real-time, with code execution happening in an isolated sandbox.+"""++import asyncio+import json+import os+from pathlib import Path+from typing import Optional++from fastapi import FastAPI, WebSocket, WebSocketDisconnect+from fastapi.responses import HTMLResponse+from fastapi.staticfiles import StaticFiles++app = FastAPI(title="Claude Chat with OpenSandbox")++# Store active sandbox sessions per WebSocket connection+active_sessions: dict[str, any] = {}++[email protected]("/", response_class=HTMLResponse)+async def get_chat_page():+ """Serve the chat interface."""+ html_path = Path(__file__).parent / "static" / "index.html"+ return HTMLResponse(content=html_path.read_text())++[email protected]("/health")+async def health():+ """Health check endpoint."""+ return {"status": "ok"}+++async def create_sandbox():+ """Create an OpenSandbox session."""+ try:+ from opensandbox import OpenSandbox++ url = os.environ.get("OPENSANDBOX_URL", "http://localhost:8080")+ grpc_port = int(os.environ.get("OPENSANDBOX_GRPC_PORT", "50051"))++ client = OpenSandbox(url, grpc_port=grpc_port)+ await client._ensure_connected()++ sandbox = await client.create(+ env={+ "ANTHROPIC_API_KEY": os.environ.get("ANTHROPIC_API_KEY", ""),+ }+ )++ return client, sandbox+ except Exception as e:+ print(f"Failed to create sandbox: {e}")+ return None, None+++async def run_claude_query(prompt: str, websocket: WebSocket, sandbox=None):+ """Run a Claude Agent SDK query and stream results via WebSocket."""+ try:+ from claude_code_sdk import query, ClaudeCodeOptions++ # Send start message+ await websocket.send_json({+ "type": "start",+ "message": "Processing your request..."+ })++ # Configure options with timeout+ options = ClaudeCodeOptions(+ max_turns=10,+ timeout_ms=300000, # 5 minute timeout for entire conversation+ )++ # Stream responses+ full_response = ""+ async for message in query(prompt=prompt, options=options):+ # Handle different message types+ if hasattr(message, 'content'):+ # Text content+ for block in message.content if isinstance(message.content, list) else [message.content]:+ if hasattr(block, 'text'):+ text = block.text+ full_response += text+ await websocket.send_json({+ "type": "text",+ "content": text+ })+ elif hasattr(block, 'type') and block.type == 'tool_use':+ await websocket.send_json({+ "type": "tool_use",+ "tool": block.name if hasattr(block, 'name') else "unknown",+ "input": str(block.input) if hasattr(block, 'input') else ""+ })++ elif hasattr(message, 'result'):+ await websocket.send_json({+ "type": "result",+ "content": str(message.result)+ })++ # Send completion message+ await websocket.send_json({+ "type": "complete",+ "message": "Request completed"+ })++ except Exception as e:+ await websocket.send_json({+ "type": "error",+ "message": str(e)+ })+++async def run_in_sandbox(command: str, sandbox) -> dict:+ """Execute a command in the sandbox."""+ try:+ result = await sandbox.run(command, timeout_ms=60000)+ return {+ "stdout": result.stdout,+ "stderr": result.stderr,+ "exit_code": result.exit_code+ }+ except Exception as e:+ return {+ "error": str(e)+ }++[email protected]("/ws/chat")+async def websocket_chat(websocket: WebSocket):+ """WebSocket endpoint for real-time chat."""+ await websocket.accept()++ client = None+ sandbox = None++ try:+ # Send welcome message+ await websocket.send_json({+ "type": "system",+ "message": "Connected to Claude Chat. Type a message to start!"+ })++ # Create sandbox session+ await websocket.send_json({+ "type": "system",+ "message": "Creating sandbox session..."+ })++ client, sandbox = await create_sandbox()++ if sandbox:+ await websocket.send_json({+ "type": "system",+ "message": f"Sandbox ready: {sandbox.session_id}"+ })++ # Check available tools+ result = await sandbox.run("which node claude git")+ await websocket.send_json({+ "type": "system",+ "message": f"Available tools: {result.stdout.strip()}"+ })+ else:+ await websocket.send_json({+ "type": "system",+ "message": "Running without sandbox (OpenSandbox not available)"+ })++ # Main chat loop+ while True:+ # Receive message from client+ data = await websocket.receive_text()++ try:+ msg = json.loads(data)+ prompt = msg.get("message", data)+ except json.JSONDecodeError:+ prompt = data++ if not prompt.strip():+ continue++ # Check for special commands+ if prompt.startswith("/sandbox "):+ # Run command in sandbox+ if sandbox:+ cmd = prompt[9:]+ await websocket.send_json({+ "type": "system",+ "message": f"Running in sandbox: {cmd}"+ })+ result = await run_in_sandbox(cmd, sandbox)+ await websocket.send_json({+ "type": "sandbox_result",+ "result": result+ })+ else:+ await websocket.send_json({+ "type": "error",+ "message": "Sandbox not available"+ })+ elif prompt == "/help":+ await websocket.send_json({+ "type": "system",+ "message": """Available commands:+- Just type to chat with Claude+- /sandbox <command> - Run a command in the sandbox+- /help - Show this help message"""+ })+ else:+ # Regular chat with Claude+ await run_claude_query(prompt, websocket, sandbox)++ except WebSocketDisconnect:+ print("Client disconnected")+ except Exception as e:+ print(f"WebSocket error: {e}")+ try:+ await websocket.send_json({+ "type": "error",+ "message": str(e)+ })+ except:+ pass+ finally:+ # Cleanup sandbox+ if sandbox:+ try:+ await sandbox.destroy()+ except:+ pass+ if client:+ try:+ await client.close()+ except:+ pass+++if __name__ == "__main__":+ import uvicorn+ uvicorn.run(app, host="0.0.0.0", port=8000)diff --git a/examples/claude-chat/docker-compose.yml b/examples/claude-chat/docker-compose.ymlnew file mode 100644index 00000000..4d06dbf1--- /dev/null+++ b/examples/claude-chat/docker-compose.yml@@ -0,0 +1,37 @@+services:+ # OpenSandbox server for isolated code execution+ opensandbox:+ build:+ context: ../..+ dockerfile: Dockerfile+ ports:+ - "8080:8080"+ - "50051:50051"+ privileged: true+ environment:+ - RUST_LOG=info+ healthcheck:+ test: ["CMD", "curl", "-f", "http://localhost:8080/health"]+ interval: 5s+ timeout: 5s+ retries: 10+ start_period: 10s++ # Claude Chat web interface+ chat:+ build:+ context: ../..+ dockerfile: examples/claude-chat/Dockerfile+ ports:+ - "8000:8000"+ environment:+ - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}+ - OPENSANDBOX_URL=http://opensandbox:8080+ - OPENSANDBOX_GRPC_PORT=50051+ depends_on:+ opensandbox:+ condition: service_healthy+ volumes:+ # Mount for live development+ - ./app.py:/app/app.py+ - ./static:/app/staticdiff --git a/examples/claude-chat/requirements.txt b/examples/claude-chat/requirements.txtnew file mode 100644index 00000000..ac9cd73d--- /dev/null+++ b/examples/claude-chat/requirements.txt@@ -0,0 +1,12 @@+# Web framework+fastapi>=0.115.0+uvicorn[standard]>=0.32.0+websockets>=12.0++# Claude Agent SDK+claude-code-sdk>=0.0.25++# OpenSandbox SDK dependencies+grpcio>=1.60.0+protobuf>=4.25.0+httpx>=0.27.0diff --git a/examples/claude-chat/static/index.html b/examples/claude-chat/static/index.htmlnew file mode 100644index 00000000..670ccff7--- /dev/null+++ b/examples/claude-chat/static/index.html@@ -0,0 +1,405 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Claude Chat + OpenSandbox</title>+ <style>+ * {+ box-sizing: border-box;+ margin: 0;+ padding: 0;+ }++ body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;+ background: #1a1a2e;+ color: #eee;+ height: 100vh;+ display: flex;+ flex-direction: column;+ }++ .header {+ background: #16213e;+ padding: 1rem 2rem;+ border-bottom: 1px solid #0f3460;+ display: flex;+ align-items: center;+ gap: 1rem;+ }++ .header h1 {+ font-size: 1.5rem;+ font-weight: 600;+ }++ .header .status {+ margin-left: auto;+ display: flex;+ align-items: center;+ gap: 0.5rem;+ font-size: 0.875rem;+ color: #888;+ }++ .status-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: #888;+ }++ .status-dot.connected {+ background: #00d26a;+ }++ .chat-container {+ flex: 1;+ overflow-y: auto;+ padding: 1rem 2rem;+ display: flex;+ flex-direction: column;+ gap: 1rem;+ }++ .message {+ max-width: 80%;+ padding: 0.75rem 1rem;+ border-radius: 12px;+ line-height: 1.5;+ }++ .message.user {+ align-self: flex-end;+ background: #0f3460;+ border-bottom-right-radius: 4px;+ }++ .message.assistant {+ align-self: flex-start;+ background: #1f4068;+ border-bottom-left-radius: 4px;+ }++ .message.system {+ align-self: center;+ background: #2d3a4f;+ font-size: 0.875rem;+ color: #aaa;+ max-width: 90%;+ }++ .message.error {+ align-self: center;+ background: #4a1c1c;+ color: #ff6b6b;+ }++ .message.tool {+ align-self: flex-start;+ background: #1a3a1a;+ font-family: monospace;+ font-size: 0.875rem;+ border-left: 3px solid #00d26a;+ }++ .message.sandbox {+ align-self: flex-start;+ background: #1a1a3a;+ font-family: monospace;+ font-size: 0.875rem;+ border-left: 3px solid #6b7bff;+ white-space: pre-wrap;+ word-break: break-all;+ }++ .message pre {+ background: #0d1117;+ padding: 0.75rem;+ border-radius: 6px;+ overflow-x: auto;+ margin: 0.5rem 0;+ }++ .message code {+ font-family: 'Fira Code', 'Consolas', monospace;+ font-size: 0.875rem;+ }++ .input-container {+ padding: 1rem 2rem;+ background: #16213e;+ border-top: 1px solid #0f3460;+ }++ .input-wrapper {+ display: flex;+ gap: 0.75rem;+ max-width: 1200px;+ margin: 0 auto;+ }++ #message-input {+ flex: 1;+ padding: 0.75rem 1rem;+ border: 1px solid #0f3460;+ border-radius: 8px;+ background: #1a1a2e;+ color: #eee;+ font-size: 1rem;+ outline: none;+ transition: border-color 0.2s;+ }++ #message-input:focus {+ border-color: #4a6fa5;+ }++ #message-input::placeholder {+ color: #666;+ }++ #send-btn {+ padding: 0.75rem 1.5rem;+ background: #0f3460;+ color: #eee;+ border: none;+ border-radius: 8px;+ cursor: pointer;+ font-size: 1rem;+ transition: background 0.2s;+ }++ #send-btn:hover {+ background: #1a4a7a;+ }++ #send-btn:disabled {+ background: #333;+ cursor: not-allowed;+ }++ .typing-indicator {+ display: none;+ align-self: flex-start;+ padding: 0.75rem 1rem;+ background: #1f4068;+ border-radius: 12px;+ border-bottom-left-radius: 4px;+ }++ .typing-indicator.active {+ display: flex;+ gap: 4px;+ }++ .typing-indicator span {+ width: 8px;+ height: 8px;+ background: #888;+ border-radius: 50%;+ animation: bounce 1.4s infinite ease-in-out;+ }++ .typing-indicator span:nth-child(1) { animation-delay: 0s; }+ .typing-indicator span:nth-child(2) { animation-delay: 0.2s; }+ .typing-indicator span:nth-child(3) { animation-delay: 0.4s; }++ @keyframes bounce {+ 0%, 80%, 100% { transform: translateY(0); }+ 40% { transform: translateY(-6px); }+ }++ .help-text {+ font-size: 0.75rem;+ color: #666;+ margin-top: 0.5rem;+ text-align: center;+ }+ </style>+</head>+<body>+ <div class="header">+ <h1>Claude Chat + OpenSandbox</h1>+ <div class="status">+ <div class="status-dot" id="status-dot"></div>+ <span id="status-text">Connecting...</span>+ </div>+ </div>++ <div class="chat-container" id="chat-container">+ <!-- Messages will be added here -->+ </div>++ <div class="typing-indicator" id="typing-indicator">+ <span></span>+ <span></span>+ <span></span>+ </div>++ <div class="input-container">+ <div class="input-wrapper">+ <input+ type="text"+ id="message-input"+ placeholder="Type a message... (or /help for commands)"+ autocomplete="off"+ >+ <button id="send-btn">Send</button>+ </div>+ <div class="help-text">+ Press Enter to send | /sandbox <cmd> to run in sandbox | /help for more+ </div>+ </div>++ <script>+ const chatContainer = document.getElementById('chat-container');+ const messageInput = document.getElementById('message-input');+ const sendBtn = document.getElementById('send-btn');+ const statusDot = document.getElementById('status-dot');+ const statusText = document.getElementById('status-text');+ const typingIndicator = document.getElementById('typing-indicator');++ let ws = null;+ let currentAssistantMessage = null;+ let isProcessing = false;++ function connect() {+ const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';+ ws = new WebSocket(`${protocol}//${window.location.host}/ws/chat`);++ ws.onopen = () => {+ statusDot.classList.add('connected');+ statusText.textContent = 'Connected';+ sendBtn.disabled = false;+ };++ ws.onclose = () => {+ statusDot.classList.remove('connected');+ statusText.textContent = 'Disconnected';+ sendBtn.disabled = true;+ // Reconnect after 3 seconds+ setTimeout(connect, 3000);+ };++ ws.onerror = (error) => {+ console.error('WebSocket error:', error);+ addMessage('Connection error', 'error');+ };++ ws.onmessage = (event) => {+ const data = JSON.parse(event.data);+ handleMessage(data);+ };+ }++ function handleMessage(data) {+ switch (data.type) {+ case 'system':+ addMessage(data.message, 'system');+ break;++ case 'error':+ addMessage(data.message, 'error');+ hideTyping();+ isProcessing = false;+ break;++ case 'start':+ showTyping();+ isProcessing = true;+ // Start a new assistant message+ currentAssistantMessage = addMessage('', 'assistant');+ break;++ case 'text':+ if (currentAssistantMessage) {+ currentAssistantMessage.textContent += data.content;+ scrollToBottom();+ }+ break;++ case 'tool_use':+ addMessage(`Using tool: ${data.tool}\n${data.input}`, 'tool');+ break;++ case 'sandbox_result':+ const result = data.result;+ let output = '';+ if (result.stdout) output += result.stdout;+ if (result.stderr) output += `\nStderr: ${result.stderr}`;+ if (result.error) output = `Error: ${result.error}`;+ if (result.exit_code !== undefined) output += `\n[Exit code: ${result.exit_code}]`;+ addMessage(output.trim() || '(no output)', 'sandbox');+ break;++ case 'result':+ if (currentAssistantMessage && data.content) {+ if (currentAssistantMessage.textContent) {+ currentAssistantMessage.textContent += '\n\n' + data.content;+ } else {+ currentAssistantMessage.textContent = data.content;+ }+ }+ break;++ case 'complete':+ hideTyping();+ isProcessing = false;+ currentAssistantMessage = null;+ break;+ }+ }++ function addMessage(content, type) {+ const message = document.createElement('div');+ message.className = `message ${type}`;+ message.textContent = content;+ chatContainer.appendChild(message);+ scrollToBottom();+ return message;+ }++ function showTyping() {+ typingIndicator.classList.add('active');+ scrollToBottom();+ }++ function hideTyping() {+ typingIndicator.classList.remove('active');+ }++ function scrollToBottom() {+ chatContainer.scrollTop = chatContainer.scrollHeight;+ }++ function sendMessage() {+ const message = messageInput.value.trim();+ if (!message || !ws || ws.readyState !== WebSocket.OPEN) return;++ // Add user message to chat+ addMessage(message, 'user');++ // Send to server+ ws.send(JSON.stringify({ message }));++ // Clear input+ messageInput.value = '';+ }++ // Event listeners+ sendBtn.addEventListener('click', sendMessage);++ messageInput.addEventListener('keypress', (e) => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ sendMessage();+ }+ });++ // Connect on page load+ connect();+ </script>+</body>+</html>diff --git a/sdk/python/opensandbox/client.py b/sdk/python/opensandbox/client.pyindex 6626d834..f8138a53 100644--- a/sdk/python/opensandbox/client.py+++ b/sdk/python/opensandbox/client.py@@ -29,6 +29,7 @@ class OpenSandbox:base_url: str,*,grpc_port: Optional[int] = None,+ grpc_insecure: Optional[bool] = None,timeout: float = 30.0,):"""Initialize the OpenSandbox client.@@ -36,6 +37,8 @@ class OpenSandbox:Args:base_url: Base URL of the OpenSandbox server (e.g., "https://opensandbox.fly.dev").grpc_port: gRPC port (default: 50051). If None, uses 50051.+ grpc_insecure: Force insecure gRPC even with HTTPS. Useful for Fly.io where+ gRPC is exposed as raw TCP. If None, auto-detects from URL scheme.timeout: Default timeout for HTTP requests in seconds."""self._base_url = base_url.rstrip("/")@@ -47,7 +50,8 @@ class OpenSandbox:# Parse the URL to get host for gRPCparsed = urlparse(self._base_url)self._host = parsed.hostname or "localhost"- self._is_secure = parsed.scheme == "https"+ # Use secure gRPC for HTTPS unless explicitly set to insecure+ self._grpc_secure = parsed.scheme == "https" and not grpc_insecureasync def _ensure_connected(self) -> None:"""Ensure HTTP and gRPC connections are established."""@@ -56,12 +60,12 @@ class OpenSandbox:if self._grpc_channel is None:grpc_target = f"{self._host}:{self._grpc_port}"- if self._is_secure:+ if self._grpc_secure:# Use secure channel for HTTPScredentials = grpc.ssl_channel_credentials()self._grpc_channel = grpc.aio.secure_channel(grpc_target, credentials)else:- # Use insecure channel for HTTP (local dev)+ # Use insecure channel for HTTP or when grpc_insecure=Trueself._grpc_channel = grpc.aio.insecure_channel(grpc_target)async def create(