An open-source, faster Devin alternative
TypeScript
new sdk
motatoes5731e181079f
diff --git a/Makefile b/Makefilenew file mode 100644index 00000000..b34b598d--- /dev/null+++ b/Makefile@@ -0,0 +1,65 @@+.PHONY: build run test fmt lint clean help++# Build variables+BINARY_SERVER = opensandbox-server+BINARY_WORKER = opensandbox-worker+BUILD_DIR = bin++## help: Show this help message+help:+ @grep -E '^##' $(MAKEFILE_LIST) | sed 's/## //' | column -t -s ':'++## build: Build server and worker binaries+build: build-server build-worker++## build-server: Build the control plane server+build-server:+ go build -o $(BUILD_DIR)/$(BINARY_SERVER) ./cmd/server++## build-worker: Build the sandbox worker+build-worker:+ go build -o $(BUILD_DIR)/$(BINARY_WORKER) ./cmd/worker++## run: Run the server in combined mode+run: build-server+ OPENSANDBOX_MODE=combined $(BUILD_DIR)/$(BINARY_SERVER)++## run-dev: Run the server with no auth for development+run-dev: build-server+ OPENSANDBOX_MODE=combined OPENSANDBOX_API_KEY= $(BUILD_DIR)/$(BINARY_SERVER)++## test: Run all tests+test:+ go test ./... -v -count=1++## test-unit: Run unit tests only (skip integration)+test-unit:+ go test ./... -v -count=1 -short++## fmt: Format code+fmt:+ go fmt ./...+ goimports -w . 2>/dev/null || true++## lint: Run linter+lint:+ golangci-lint run ./... 2>/dev/null || go vet ./...++## tidy: Tidy go modules+tidy:+ go mod tidy++## clean: Remove build artifacts+clean:+ rm -rf $(BUILD_DIR)++## docker-server: Build server Docker image+docker-server:+ docker build -f deploy/Dockerfile.server -t opensandbox-server .++## docker-worker: Build worker Docker image+docker-worker:+ docker build -f deploy/Dockerfile.worker -t opensandbox-worker .++## docker: Build all Docker images+docker: docker-server docker-workerdiff --git a/README.md b/README.mdnew file mode 100644index 00000000..35e3ac55--- /dev/null+++ b/README.md@@ -0,0 +1,156 @@+# OpenSandbox++Podman-based sandbox platform with E2B-compatible APIs for secure, isolated code execution.++## Quick Start++### Prerequisites++- Go 1.22++- [Podman](https://podman.io/) installed and configured (rootless)++### Build & Run++```bash+# Build+make build++# Run in combined mode (server + worker in one process)+make run-dev++# Server starts on http://localhost:8080+```++### Create a Sandbox++```bash+# Create a sandbox+curl -X POST http://localhost:8080/sandboxes \+ -H "Content-Type: application/json" \+ -d '{"templateID": "base", "timeout": 300}'++# Run a command+curl -X POST http://localhost:8080/sandboxes/{id}/commands \+ -H "Content-Type: application/json" \+ -d '{"cmd": "echo hello world"}'++# Write a file+curl -X PUT "http://localhost:8080/sandboxes/{id}/files?path=/tmp/hello.txt" \+ -d "Hello from OpenSandbox!"++# Read a file+curl "http://localhost:8080/sandboxes/{id}/files?path=/tmp/hello.txt"++# Kill the sandbox+curl -X DELETE http://localhost:8080/sandboxes/{id}+```++### Python SDK++```python+import asyncio+from opensandbox import Sandbox++async def main():+ async with await Sandbox.create(template="python") as sb:+ result = await sb.commands.run("python3 -c 'print(1+1)'")+ print(result.stdout) # "2\n"++ await sb.files.write("/tmp/hello.py", "print('hello')")+ result = await sb.commands.run("python3 /tmp/hello.py")+ print(result.stdout) # "hello\n"++asyncio.run(main())+```++### TypeScript SDK++```typescript+import { Sandbox } from "opensandbox";++const sb = await Sandbox.create({ template: "node" });++const result = await sb.commands.run("node -e 'console.log(1+1)'");+console.log(result.stdout); // "2\n"++await sb.files.write("/tmp/hello.js", "console.log('hello')");+const r2 = await sb.commands.run("node /tmp/hello.js");+console.log(r2.stdout); // "hello\n"++await sb.kill();+```++## Architecture++```+Client SDKs (Python / TypeScript)+ │ REST API + WebSocket+ ▼+Control Plane (Go/Echo)+ ├── API Server+ ├── Template Registry+ ├── Sandbox Router+ └── Compute Pool+ ├── Local (development)+ ├── Fly.io (production)+ └── ... (extensible)+ │ gRPC (internal)+ ▼+Sandbox Worker (Go)+ ├── Sandbox Manager+ ├── Filesystem Service+ └── PTY Manager+ ▼ Podman (rootless, crun)+ [sandbox containers]+```++## API Endpoints++| Method | Path | Description |+|--------|------|-------------|+| POST | `/sandboxes` | Create sandbox |+| GET | `/sandboxes` | List sandboxes |+| GET | `/sandboxes/:id` | Get sandbox info |+| DELETE | `/sandboxes/:id` | Kill sandbox |+| POST | `/sandboxes/:id/timeout` | Update timeout |+| POST | `/sandboxes/:id/commands` | Run command |+| GET | `/sandboxes/:id/files?path=` | Read file |+| PUT | `/sandboxes/:id/files?path=` | Write file |+| GET | `/sandboxes/:id/files/list?path=` | List directory |+| POST | `/sandboxes/:id/files/mkdir?path=` | Create directory |+| DELETE | `/sandboxes/:id/files?path=` | Remove file/dir |+| POST | `/sandboxes/:id/pty` | Create PTY session |+| WS | `/sandboxes/:id/pty/:sessionID` | PTY WebSocket |+| DELETE | `/sandboxes/:id/pty/:sessionID` | Kill PTY |+| POST | `/templates` | Build template |+| GET | `/templates` | List templates |+| GET | `/templates/:name` | Get template |+| DELETE | `/templates/:name` | Delete template |++## Configuration++| Environment Variable | Default | Description |+|---------------------|---------|-------------|+| `OPENSANDBOX_PORT` | `8080` | Server port |+| `OPENSANDBOX_API_KEY` | (empty) | API key (empty = no auth) |+| `OPENSANDBOX_WORKER_ADDR` | `localhost:9090` | Worker address |+| `OPENSANDBOX_MODE` | `combined` | `server`, `worker`, or `combined` |+| `FLY_API_TOKEN` | (empty) | Fly.io API token (for cloud deployment) |++## Security++Every sandbox container runs with:+- **Rootless Podman** — no root privileges+- `--cap-drop=ALL` — all capabilities dropped+- `--read-only` — read-only root filesystem+- `--security-opt=no-new-privileges`+- `--userns=auto` — user namespace isolation+- `--pids-limit=256` — fork bomb protection+- `--memory=512m` — memory limit+- `--cpus=1` — CPU limit+- `--network=none` — network isolation (opt-in)+- Default Podman seccomp profile++## License++MITdiff --git a/cmd/server/main.go b/cmd/server/main.gonew file mode 100644index 00000000..d3f571e4--- /dev/null+++ b/cmd/server/main.go@@ -0,0 +1,73 @@+package main++import (+ "context"+ "fmt"+ "log"+ "os"+ "os/exec"+ "os/signal"+ "syscall"++ "github.com/opensandbox/opensandbox/internal/api"+ "github.com/opensandbox/opensandbox/internal/config"+ "github.com/opensandbox/opensandbox/internal/podman"+ "github.com/opensandbox/opensandbox/internal/sandbox"+ "github.com/opensandbox/opensandbox/internal/template"+)++func main() {+ cfg, err := config.Load()+ if err != nil {+ log.Fatalf("failed to load config: %v", err)+ }++ podmanClient, err := podman.NewClient()+ if err != nil {+ log.Fatalf("failed to initialize podman: %v", err)+ }++ // Verify podman is working+ ctx := context.Background()+ version, err := podmanClient.Version(ctx)+ if err != nil {+ log.Fatalf("failed to get podman version: %v", err)+ }+ log.Printf("opensandbox: using podman %s", version)++ // Initialize sandbox manager+ mgr := sandbox.NewManager(podmanClient)+ defer mgr.Close()++ // Initialize PTY manager+ podmanPath, _ := exec.LookPath("podman")+ ptyMgr := sandbox.NewPTYManager(podmanPath, podmanClient.AuthFile())+ defer ptyMgr.CloseAll()++ // Initialize template system+ registry := template.NewRegistry()+ builder := template.NewBuilder(podmanClient, registry)++ // Create API server+ server := api.NewServer(mgr, ptyMgr, cfg.APIKey)+ server.SetTemplateDeps(registry, builder)++ // Graceful shutdown+ quit := make(chan os.Signal, 1)+ signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)++ addr := fmt.Sprintf(":%d", cfg.Port)+ log.Printf("opensandbox: starting server on %s (mode=%s)", addr, cfg.Mode)++ go func() {+ if err := server.Start(addr); err != nil {+ log.Printf("server error: %v", err)+ }+ }()++ <-quit+ log.Println("opensandbox: shutting down...")+ if err := server.Close(); err != nil {+ log.Printf("error closing server: %v", err)+ }+}diff --git a/cmd/worker/main.go b/cmd/worker/main.gonew file mode 100644index 00000000..79e0a945--- /dev/null+++ b/cmd/worker/main.go@@ -0,0 +1,38 @@+package main++import (+ "context"+ "log"+ "os"+ "os/signal"+ "syscall"++ "github.com/opensandbox/opensandbox/internal/podman"+)++func main() {+ log.Println("opensandbox-worker: starting...")++ client, err := podman.NewClient()+ if err != nil {+ log.Fatalf("failed to initialize podman: %v", err)+ }++ ctx := context.Background()+ version, err := client.Version(ctx)+ if err != nil {+ log.Fatalf("failed to get podman version: %v", err)+ }+ log.Printf("opensandbox-worker: using podman %s", version)++ // TODO: Start gRPC server for control plane communication+ // For now, the worker functionality is embedded in the server (combined mode)+ log.Println("opensandbox-worker: running in standalone mode (gRPC server not yet implemented)")+ log.Println("opensandbox-worker: use --mode=combined on the server for single-machine deployment")++ quit := make(chan os.Signal, 1)+ signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)+ <-quit++ log.Println("opensandbox-worker: shutting down...")+}diff --git a/deploy/Dockerfile.server b/deploy/Dockerfile.servernew file mode 100644index 00000000..1119711f--- /dev/null+++ b/deploy/Dockerfile.server@@ -0,0 +1,19 @@+FROM golang:1.22-bookworm AS builder++WORKDIR /app+COPY go.mod go.sum ./+RUN go mod download++COPY . .+RUN CGO_ENABLED=0 go build -o /opensandbox-server ./cmd/server++FROM debian:bookworm-slim++RUN apt-get update && apt-get install -y --no-install-recommends \+ ca-certificates \+ && rm -rf /var/lib/apt/lists/*++COPY --from=builder /opensandbox-server /usr/local/bin/opensandbox-server++EXPOSE 8080+CMD ["opensandbox-server"]diff --git a/deploy/Dockerfile.worker b/deploy/Dockerfile.workernew file mode 100644index 00000000..1c2ba682--- /dev/null+++ b/deploy/Dockerfile.worker@@ -0,0 +1,29 @@+FROM golang:1.22-bookworm AS builder++WORKDIR /app+COPY go.mod go.sum ./+RUN go mod download++COPY . .+RUN CGO_ENABLED=0 go build -o /opensandbox-worker ./cmd/worker++FROM ubuntu:22.04++RUN apt-get update && apt-get install -y --no-install-recommends \+ podman \+ crun \+ uidmap \+ fuse-overlayfs \+ slirp4netns \+ ca-certificates \+ && rm -rf /var/lib/apt/lists/*++COPY --from=builder /opensandbox-worker /usr/local/bin/opensandbox-worker++# Pre-pull default template images+RUN podman pull docker.io/library/ubuntu:22.04 && \+ podman pull docker.io/library/python:3.12-slim && \+ podman pull docker.io/library/node:20-slim || true++EXPOSE 9090+CMD ["opensandbox-worker"]diff --git a/deploy/fly.toml b/deploy/fly.tomlnew file mode 100644index 00000000..74f19ef8--- /dev/null+++ b/deploy/fly.toml@@ -0,0 +1,16 @@+app = "opensandbox"+primary_region = "iad"++[build]+ dockerfile = "Dockerfile.server"++[http_service]+ internal_port = 8080+ force_https = true+ auto_stop_machines = true+ auto_start_machines = true+ min_machines_running = 1++[env]+ OPENSANDBOX_MODE = "server"+ OPENSANDBOX_PORT = "8080"diff --git a/examples/test.py b/examples/test.pynew file mode 100644index 00000000..2cfc437e--- /dev/null+++ b/examples/test.py@@ -0,0 +1,77 @@+import asyncio+import sys+sys.path.insert(0, "../sdks/python")++from opensandbox import Sandbox+++async def main():+ print("Creating sandbox...")+ async with await Sandbox.create(template="base", timeout=3600) as sb:+ print(f"Sandbox created: {sb.sandbox_id}")++ # Run commands+ print("\n--- Commands ---")+ result = await sb.commands.run("echo hello from python sdk")+ print(f"stdout: {result.stdout.strip()}")+ print(f"exit code: {result.exit_code}")++ uname = await sb.commands.run("uname -a")+ print(f"uname: {uname.stdout.strip()}")++ # Filesystem+ print("\n--- Filesystem ---")+ await sb.files.write("/tmp/greeting.txt", "Hello from Python SDK!")+ content = await sb.files.read("/tmp/greeting.txt")+ print(f"file content: {content}")++ exists = await sb.files.exists("/tmp/greeting.txt")+ print(f"file exists: {exists}")++ await sb.files.make_dir("/tmp/mydir")+ await sb.files.write("/tmp/mydir/test.py", 'print("hello from python")')++ entries = await sb.files.list("/tmp")+ print("ls /tmp:")+ for entry in entries:+ kind = "d" if entry.is_dir else "-"+ print(f" {kind} {entry.name}")++ # Run a multi-line script+ print("\n--- Script execution ---")+ await sb.files.write("/tmp/script.sh", "\n".join([+ "#!/bin/bash",+ 'echo "Current directory: $(pwd)"',+ 'echo "User: $(whoami)"',+ 'echo "Date: $(date)"',+ 'echo "Files in /tmp:"',+ "ls /tmp",+ ]))++ script = await sb.commands.run("bash /tmp/script.sh")+ print(script.stdout)++ # Run Python inside the sandbox+ print("--- Python in sandbox ---")+ await sb.files.write("/tmp/hello.py", "\n".join([+ "import os",+ "print(f'PID: {os.getpid()}')",+ "print(f'CWD: {os.getcwd()}')",+ "print('2 + 2 =', 2 + 2)",+ ]))+ py = await sb.commands.run("python /tmp/hello.py")+ if py.exit_code == 0:+ print(py.stdout)+ else:+ print(f"python3 not available in base image (exit {py.exit_code})")++ # Check sandbox status+ print("--- Status ---")+ running = await sb.is_running()+ print(f"running: {running}")++ # sandbox auto-killed by async with+ print("\nSandbox killed. Done!")+++asyncio.run(main())diff --git a/examples/test.ts b/examples/test.tsnew file mode 100644index 00000000..c61811fa--- /dev/null+++ b/examples/test.ts@@ -0,0 +1,59 @@+import { Sandbox } from "../sdks/typescript/src/index";++async function main() {+ console.log("Creating sandbox...");+ const sb = await Sandbox.create({ template: "base", timeout: 3600 });+ console.log(`Sandbox created: ${sb.sandboxId}`);++ // Run commands+ console.log("\n--- Commands ---");+ const result = await sb.commands.run("echo hello from typescript sdk");+ console.log(`stdout: ${result.stdout.trim()}`);+ console.log(`exit code: ${result.exitCode}`);++ const uname = await sb.commands.run("uname -a");+ console.log(`uname: ${uname.stdout.trim()}`);++ // Filesystem+ console.log("\n--- Filesystem ---");+ await sb.files.write("/tmp/greeting.txt", "Hello from TypeScript SDK!");+ const content = await sb.files.read("/tmp/greeting.txt");+ console.log(`file content: ${content}`);++ const exists = await sb.files.exists("/tmp/greeting.txt");+ console.log(`file exists: ${exists}`);++ await sb.files.makeDir("/tmp/mydir");+ await sb.files.write("/tmp/mydir/test.py", 'print("hello from python")');++ const entries = await sb.files.list("/tmp");+ console.log("ls /tmp:");+ for (const entry of entries) {+ console.log(` ${entry.isDir ? "d" : "-"} ${entry.name}`);+ }++ // Run a multi-line script+ console.log("\n--- Script execution ---");+ await sb.files.write("/tmp/script.sh", [+ "#!/bin/bash",+ 'echo "Current directory: $(pwd)"',+ 'echo "User: $(whoami)"',+ 'echo "Date: $(date)"',+ 'echo "Files in /tmp:"',+ "ls /tmp",+ ].join("\n"));++ const script = await sb.commands.run("bash /tmp/script.sh");+ console.log(script.stdout);++ // Check sandbox status+ console.log("--- Status ---");+ const running = await sb.isRunning();+ console.log(`running: ${running}`);++ // Clean up+ await sb.kill();+ console.log("\nSandbox killed. Done!");+}++main().catch(console.error);diff --git a/go.mod b/go.modnew file mode 100644index 00000000..2c21135a--- /dev/null+++ b/go.mod@@ -0,0 +1,24 @@+module github.com/opensandbox/opensandbox++go 1.22++require (+ github.com/google/uuid v1.6.0+ github.com/gorilla/websocket v1.5.3+ github.com/labstack/echo/v4 v4.12.0+)++require (+ github.com/creack/pty v1.1.24 // indirect+ github.com/golang-jwt/jwt v3.2.2+incompatible // indirect+ github.com/labstack/gommon v0.4.2 // indirect+ github.com/mattn/go-colorable v0.1.13 // indirect+ github.com/mattn/go-isatty v0.0.20 // indirect+ github.com/valyala/bytebufferpool v1.0.0 // indirect+ github.com/valyala/fasttemplate v1.2.2 // indirect+ golang.org/x/crypto v0.31.0 // indirect+ golang.org/x/net v0.33.0 // indirect+ golang.org/x/sys v0.28.0 // indirect+ golang.org/x/text v0.21.0 // indirect+ golang.org/x/time v0.8.0 // indirect+)diff --git a/go.sum b/go.sumnew file mode 100644index 00000000..91d85a05--- /dev/null+++ b/go.sum@@ -0,0 +1,41 @@+github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=+github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=+github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=+github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=+github.com/labstack/echo/v4 v4.12.0 h1:IKpw49IMryVB2p1a4dzwlhP1O2Tf2E0Ir/450lH+kI0=+github.com/labstack/echo/v4 v4.12.0/go.mod h1:UP9Cr2DJXbOK3Kr9ONYzNowSh7HP0aG0ShAyycHSJvM=+github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=+github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=+github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=+github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=+github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=+github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=+github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=+github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=+github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=+golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=+golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=+golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=+golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=+golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=+golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=+golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=+golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=+golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg=+golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/internal/api/commands.go b/internal/api/commands.gonew file mode 100644index 00000000..57cb7762--- /dev/null+++ b/internal/api/commands.go@@ -0,0 +1,34 @@+package api++import (+ "net/http"++ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/pkg/types"+)++func (s *Server) runCommand(c echo.Context) error {+ id := c.Param("id")++ var cfg types.ProcessConfig+ if err := c.Bind(&cfg); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "invalid request body: " + err.Error(),+ })+ }++ if cfg.Command == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "cmd is required",+ })+ }++ result, err := s.manager.Exec(c.Request().Context(), id, cfg)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ return c.JSON(http.StatusOK, result)+}diff --git a/internal/api/filesystem.go b/internal/api/filesystem.gonew file mode 100644index 00000000..96e72f29--- /dev/null+++ b/internal/api/filesystem.go@@ -0,0 +1,105 @@+package api++import (+ "io"+ "net/http"++ "github.com/labstack/echo/v4"+)++func (s *Server) readFile(c echo.Context) error {+ id := c.Param("id")+ path := c.QueryParam("path")+ if path == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "path query parameter is required",+ })+ }++ content, err := s.manager.ReadFile(c.Request().Context(), id, path)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ return c.String(http.StatusOK, content)+}++func (s *Server) writeFile(c echo.Context) error {+ id := c.Param("id")+ path := c.QueryParam("path")+ if path == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "path query parameter is required",+ })+ }++ body, err := io.ReadAll(c.Request().Body)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "failed to read request body: " + err.Error(),+ })+ }++ if err := s.manager.WriteFile(c.Request().Context(), id, path, string(body)); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ return c.NoContent(http.StatusNoContent)+}++func (s *Server) listDir(c echo.Context) error {+ id := c.Param("id")+ path := c.QueryParam("path")+ if path == "" {+ path = "/"+ }++ entries, err := s.manager.ListDir(c.Request().Context(), id, path)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ return c.JSON(http.StatusOK, entries)+}++func (s *Server) makeDir(c echo.Context) error {+ id := c.Param("id")+ path := c.QueryParam("path")+ if path == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "path query parameter is required",+ })+ }++ if err := s.manager.MakeDir(c.Request().Context(), id, path); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ return c.NoContent(http.StatusNoContent)+}++func (s *Server) removeFile(c echo.Context) error {+ id := c.Param("id")+ path := c.QueryParam("path")+ if path == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "path query parameter is required",+ })+ }++ if err := s.manager.Remove(c.Request().Context(), id, path); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ return c.NoContent(http.StatusNoContent)+}diff --git a/internal/api/pty.go b/internal/api/pty.gonew file mode 100644index 00000000..763e583a--- /dev/null+++ b/internal/api/pty.go@@ -0,0 +1,115 @@+package api++import (+ "net/http"+ "time"++ "github.com/gorilla/websocket"+ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/pkg/types"+)++var upgrader = websocket.Upgrader{+ CheckOrigin: func(r *http.Request) bool {+ return true // Allow all origins for now; tighten in production+ },+ ReadBufferSize: 1024,+ WriteBufferSize: 1024,+}++func (s *Server) createPTY(c echo.Context) error {+ id := c.Param("id")++ var req types.PTYCreateRequest+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "invalid request body: " + err.Error(),+ })+ }++ session, err := s.ptyManager.CreateSession(id, req)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ return c.JSON(http.StatusCreated, types.PTYSession{+ SessionID: session.ID,+ SandboxID: id,+ })+}++func (s *Server) ptyWebSocket(c echo.Context) error {+ sessionID := c.Param("sessionID")++ session, err := s.ptyManager.GetSession(sessionID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{+ "error": err.Error(),+ })+ }++ ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)+ if err != nil {+ return err+ }+ defer ws.Close()++ // Read from PTY -> send to WebSocket+ done := make(chan struct{})+ go func() {+ defer close(done)+ buf := make([]byte, 4096)+ for {+ n, err := session.PTY.Read(buf)+ if n > 0 {+ if writeErr := ws.WriteMessage(websocket.BinaryMessage, buf[:n]); writeErr != nil {+ return+ }+ }+ if err != nil {+ return+ }+ }+ }()++ // Read from WebSocket -> write to PTY+ go func() {+ for {+ _, msg, err := ws.ReadMessage()+ if err != nil {+ return+ }+ if _, err := session.PTY.Write(msg); err != nil {+ return+ }+ }+ }()++ // Wait for PTY process to end or connection to close+ select {+ case <-done:+ case <-session.Done:+ }++ // Give the reader goroutine a moment to flush remaining output+ ws.WriteControl(websocket.CloseMessage,+ websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),+ time.Now().Add(time.Second))++ return nil+}++func (s *Server) killPTY(c echo.Context) error {+ sessionID := c.Param("sessionID")++ if err := s.ptyManager.KillSession(sessionID); err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{+ "error": err.Error(),+ })+ }++ return c.NoContent(http.StatusNoContent)+}+diff --git a/internal/api/router.go b/internal/api/router.gonew file mode 100644index 00000000..5b782e25--- /dev/null+++ b/internal/api/router.go@@ -0,0 +1,86 @@+package api++import (+ "net/http"++ "github.com/labstack/echo/v4"+ "github.com/labstack/echo/v4/middleware"+ "github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/sandbox"+)++// Server holds the API server dependencies.+type Server struct {+ echo *echo.Echo+ manager *sandbox.Manager+ ptyManager *sandbox.PTYManager+ templates *templateDeps+}++// NewServer creates a new API server with all routes configured.+func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string) *Server {+ e := echo.New()+ e.HideBanner = true+ e.HidePort = true++ s := &Server{+ echo: e,+ manager: mgr,+ ptyManager: ptyMgr,+ }++ // Global middleware+ e.Use(middleware.Recover())+ e.Use(middleware.Logger())+ e.Use(middleware.CORS())+ e.Use(middleware.RequestID())++ // Health check (no auth)+ e.GET("/health", func(c echo.Context) error {+ return c.JSON(http.StatusOK, map[string]string{"status": "ok"})+ })++ // API routes (with auth)+ api := e.Group("")+ api.Use(auth.APIKeyMiddleware(apiKey))++ // Sandbox lifecycle+ api.POST("/sandboxes", s.createSandbox)+ api.GET("/sandboxes", s.listSandboxes)+ api.GET("/sandboxes/:id", s.getSandbox)+ api.DELETE("/sandboxes/:id", s.killSandbox)+ api.POST("/sandboxes/:id/timeout", s.setTimeout)++ // Commands+ api.POST("/sandboxes/:id/commands", s.runCommand)++ // Filesystem+ api.GET("/sandboxes/:id/files", s.readFile)+ api.PUT("/sandboxes/:id/files", s.writeFile)+ api.GET("/sandboxes/:id/files/list", s.listDir)+ api.POST("/sandboxes/:id/files/mkdir", s.makeDir)+ api.DELETE("/sandboxes/:id/files", s.removeFile)++ // PTY+ api.POST("/sandboxes/:id/pty", s.createPTY)+ api.GET("/sandboxes/:id/pty/:sessionID", s.ptyWebSocket)+ api.DELETE("/sandboxes/:id/pty/:sessionID", s.killPTY)++ // Templates+ api.POST("/templates", s.buildTemplate)+ api.GET("/templates", s.listTemplates)+ api.GET("/templates/:name", s.getTemplate)+ api.DELETE("/templates/:name", s.deleteTemplate)++ return s+}++// Start starts the HTTP server on the given address.+func (s *Server) Start(addr string) error {+ return s.echo.Start(addr)+}++// Close gracefully shuts down the server.+func (s *Server) Close() error {+ return s.echo.Close()+}diff --git a/internal/api/sandbox.go b/internal/api/sandbox.gonew file mode 100644index 00000000..8a4a5399--- /dev/null+++ b/internal/api/sandbox.go@@ -0,0 +1,87 @@+package api++import (+ "net/http"++ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/pkg/types"+)++func (s *Server) createSandbox(c echo.Context) error {+ var cfg types.SandboxConfig+ if err := c.Bind(&cfg); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "invalid request body: " + err.Error(),+ })+ }++ sb, err := s.manager.Create(c.Request().Context(), cfg)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ return c.JSON(http.StatusCreated, sb)+}++func (s *Server) getSandbox(c echo.Context) error {+ id := c.Param("id")++ sb, err := s.manager.Get(c.Request().Context(), id)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{+ "error": err.Error(),+ })+ }++ return c.JSON(http.StatusOK, sb)+}++func (s *Server) killSandbox(c echo.Context) error {+ id := c.Param("id")++ if err := s.manager.Kill(c.Request().Context(), id); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ return c.NoContent(http.StatusNoContent)+}++func (s *Server) listSandboxes(c echo.Context) error {+ sandboxes, err := s.manager.List(c.Request().Context())+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ return c.JSON(http.StatusOK, sandboxes)+}++func (s *Server) setTimeout(c echo.Context) error {+ id := c.Param("id")++ var req types.TimeoutRequest+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "invalid request body: " + err.Error(),+ })+ }++ if req.Timeout <= 0 {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "timeout must be positive",+ })+ }++ if err := s.manager.SetTimeout(c.Request().Context(), id, req.Timeout); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ return c.NoContent(http.StatusNoContent)+}diff --git a/internal/api/sandbox_test.go b/internal/api/sandbox_test.gonew file mode 100644index 00000000..e864240d--- /dev/null+++ b/internal/api/sandbox_test.go@@ -0,0 +1,34 @@+package api++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/labstack/echo/v4"+)++func TestHealthEndpoint(t *testing.T) {+ e := echo.New()+ e.GET("/health", func(c echo.Context) error {+ return c.JSON(http.StatusOK, map[string]string{"status": "ok"})+ })++ req := httptest.NewRequest(http.MethodGet, "/health", nil)+ rec := httptest.NewRecorder()+ e.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", rec.Code)+ }++ var body map[string]string+ if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {+ t.Fatalf("failed to decode response: %v", err)+ }++ if body["status"] != "ok" {+ t.Errorf("expected status ok, got %s", body["status"])+ }+}diff --git a/internal/api/templates.go b/internal/api/templates.gonew file mode 100644index 00000000..29bc1a94--- /dev/null+++ b/internal/api/templates.go@@ -0,0 +1,96 @@+package api++import (+ "net/http"++ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/template"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// templateDeps holds template-related dependencies injected into the server.+type templateDeps struct {+ registry *template.Registry+ builder *template.Builder+}++// SetTemplateDeps sets the template dependencies on the server.+func (s *Server) SetTemplateDeps(registry *template.Registry, builder *template.Builder) {+ s.templates = &templateDeps{+ registry: registry,+ builder: builder,+ }+}++func (s *Server) buildTemplate(c echo.Context) error {+ if s.templates == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "template service not configured",+ })+ }++ var req types.TemplateBuildRequest+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "invalid request body: " + err.Error(),+ })+ }++ if req.Name == "" || req.Dockerfile == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "name and dockerfile are required",+ })+ }++ tmpl, err := s.templates.builder.Build(c.Request().Context(), req.Dockerfile, req.Name)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": err.Error(),+ })+ }++ return c.JSON(http.StatusCreated, tmpl)+}++func (s *Server) listTemplates(c echo.Context) error {+ if s.templates == nil {+ return c.JSON(http.StatusOK, []types.Template{})+ }++ return c.JSON(http.StatusOK, s.templates.registry.List())+}++func (s *Server) getTemplate(c echo.Context) error {+ if s.templates == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "template service not configured",+ })+ }++ name := c.Param("name")+ tmpl, err := s.templates.registry.Get(name)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{+ "error": err.Error(),+ })+ }++ return c.JSON(http.StatusOK, tmpl)+}++func (s *Server) deleteTemplate(c echo.Context) error {+ if s.templates == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "template service not configured",+ })+ }++ name := c.Param("name")+ if err := s.templates.registry.Delete(name); err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{+ "error": err.Error(),+ })+ }++ return c.NoContent(http.StatusNoContent)+}diff --git a/internal/auth/apikey.go b/internal/auth/apikey.gonew file mode 100644index 00000000..aa181af5--- /dev/null+++ b/internal/auth/apikey.go@@ -0,0 +1,39 @@+package auth++import (+ "crypto/subtle"+ "net/http"++ "github.com/labstack/echo/v4"+)++// APIKeyMiddleware validates the X-API-Key header against the configured key.+// If the configured key is empty, authentication is disabled (development mode).+func APIKeyMiddleware(apiKey string) echo.MiddlewareFunc {+ return func(next echo.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error {+ if apiKey == "" {+ return next(c)+ }++ provided := c.Request().Header.Get("X-API-Key")+ if provided == "" {+ provided = c.QueryParam("api_key")+ }++ if provided == "" {+ return c.JSON(http.StatusUnauthorized, map[string]string{+ "error": "missing API key",+ })+ }++ if subtle.ConstantTimeCompare([]byte(provided), []byte(apiKey)) != 1 {+ return c.JSON(http.StatusForbidden, map[string]string{+ "error": "invalid API key",+ })+ }++ return next(c)+ }+ }+}diff --git a/internal/auth/apikey_test.go b/internal/auth/apikey_test.gonew file mode 100644index 00000000..673f09c6--- /dev/null+++ b/internal/auth/apikey_test.go@@ -0,0 +1,91 @@+package auth++import (+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/labstack/echo/v4"+)++func TestAPIKeyMiddleware_NoKeyConfigured(t *testing.T) {+ e := echo.New()+ e.Use(APIKeyMiddleware(""))+ e.GET("/test", func(c echo.Context) error {+ return c.String(http.StatusOK, "ok")+ })++ req := httptest.NewRequest(http.MethodGet, "/test", nil)+ rec := httptest.NewRecorder()+ e.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Errorf("expected 200 with no key configured, got %d", rec.Code)+ }+}++func TestAPIKeyMiddleware_ValidKey(t *testing.T) {+ e := echo.New()+ e.Use(APIKeyMiddleware("secret-key"))+ e.GET("/test", func(c echo.Context) error {+ return c.String(http.StatusOK, "ok")+ })++ req := httptest.NewRequest(http.MethodGet, "/test", nil)+ req.Header.Set("X-API-Key", "secret-key")+ rec := httptest.NewRecorder()+ e.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Errorf("expected 200 with valid key, got %d", rec.Code)+ }+}++func TestAPIKeyMiddleware_InvalidKey(t *testing.T) {+ e := echo.New()+ e.Use(APIKeyMiddleware("secret-key"))+ e.GET("/test", func(c echo.Context) error {+ return c.String(http.StatusOK, "ok")+ })++ req := httptest.NewRequest(http.MethodGet, "/test", nil)+ req.Header.Set("X-API-Key", "wrong-key")+ rec := httptest.NewRecorder()+ e.ServeHTTP(rec, req)++ if rec.Code != http.StatusForbidden {+ t.Errorf("expected 403 with invalid key, got %d", rec.Code)+ }+}++func TestAPIKeyMiddleware_MissingKey(t *testing.T) {+ e := echo.New()+ e.Use(APIKeyMiddleware("secret-key"))+ e.GET("/test", func(c echo.Context) error {+ return c.String(http.StatusOK, "ok")+ })++ req := httptest.NewRequest(http.MethodGet, "/test", nil)+ rec := httptest.NewRecorder()+ e.ServeHTTP(rec, req)++ if rec.Code != http.StatusUnauthorized {+ t.Errorf("expected 401 with missing key, got %d", rec.Code)+ }+}++func TestAPIKeyMiddleware_QueryParam(t *testing.T) {+ e := echo.New()+ e.Use(APIKeyMiddleware("secret-key"))+ e.GET("/test", func(c echo.Context) error {+ return c.String(http.StatusOK, "ok")+ })++ req := httptest.NewRequest(http.MethodGet, "/test?api_key=secret-key", nil)+ rec := httptest.NewRecorder()+ e.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Errorf("expected 200 with key in query param, got %d", rec.Code)+ }+}diff --git a/internal/compute/fly.go b/internal/compute/fly.gonew file mode 100644index 00000000..b36a622b--- /dev/null+++ b/internal/compute/fly.go@@ -0,0 +1,182 @@+package compute++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "os"+)++const flyAPIBase = "https://api.machines.dev/v1"++// FlyPool implements the compute pool interface for Fly.io Machines.+type FlyPool struct {+ appName string+ token string+ client *http.Client+}++// NewFlyPool creates a Fly.io compute pool.+func NewFlyPool(appName string) (*FlyPool, error) {+ token := os.Getenv("FLY_API_TOKEN")+ if token == "" {+ return nil, fmt.Errorf("FLY_API_TOKEN environment variable is required")+ }+ return &FlyPool{+ appName: appName,+ token: token,+ client: &http.Client{},+ }, nil+}++func (p *FlyPool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machine, error) {+ body := map[string]interface{}{+ "config": map[string]interface{}{+ "image": opts.Image,+ "guest": map[string]interface{}{+ "cpu_kind": "shared",+ "cpus": 2,+ "memory_mb": 2048,+ },+ "services": []map[string]interface{}{+ {+ "ports": []map[string]interface{}{{"port": 9090, "handlers": []string{"tls", "http"}}},+ "protocol": "tcp",+ "internal_port": 9090,+ },+ },+ },+ "region": opts.Region,+ }++ data, _ := json.Marshal(body)+ url := fmt.Sprintf("%s/apps/%s/machines", flyAPIBase, p.appName)++ req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data))+ if err != nil {+ return nil, err+ }+ req.Header.Set("Authorization", "Bearer "+p.token)+ req.Header.Set("Content-Type", "application/json")++ resp, err := p.client.Do(req)+ if err != nil {+ return nil, fmt.Errorf("fly API request failed: %w", err)+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {+ respBody, _ := io.ReadAll(resp.Body)+ return nil, fmt.Errorf("fly API returned %d: %s", resp.StatusCode, string(respBody))+ }++ var result struct {+ ID string `json:"id"`+ PrivateIP string `json:"private_ip"`+ Region string `json:"region"`+ State string `json:"state"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {+ return nil, fmt.Errorf("failed to decode fly response: %w", err)+ }++ return &Machine{+ ID: result.ID,+ Addr: fmt.Sprintf("%s:9090", result.PrivateIP),+ Region: result.Region,+ Status: result.State,+ Capacity: 50,+ }, nil+}++func (p *FlyPool) DestroyMachine(ctx context.Context, machineID string) error {+ return p.machineAction(ctx, machineID, "DELETE", "")+}++func (p *FlyPool) StartMachine(ctx context.Context, machineID string) error {+ return p.machineAction(ctx, machineID, "POST", "/start")+}++func (p *FlyPool) StopMachine(ctx context.Context, machineID string) error {+ return p.machineAction(ctx, machineID, "POST", "/stop")+}++func (p *FlyPool) ListMachines(ctx context.Context) ([]*Machine, error) {+ url := fmt.Sprintf("%s/apps/%s/machines", flyAPIBase, p.appName)+ req, err := http.NewRequestWithContext(ctx, "GET", url, nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("Authorization", "Bearer "+p.token)++ resp, err := p.client.Do(req)+ if err != nil {+ return nil, fmt.Errorf("fly API request failed: %w", err)+ }+ defer resp.Body.Close()++ var results []struct {+ ID string `json:"id"`+ PrivateIP string `json:"private_ip"`+ Region string `json:"region"`+ State string `json:"state"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {+ return nil, err+ }++ machines := make([]*Machine, len(results))+ for i, r := range results {+ machines[i] = &Machine{+ ID: r.ID,+ Addr: fmt.Sprintf("%s:9090", r.PrivateIP),+ Region: r.Region,+ Status: r.State,+ }+ }+ return machines, nil+}++func (p *FlyPool) HealthCheck(ctx context.Context, machineID string) error {+ url := fmt.Sprintf("%s/apps/%s/machines/%s", flyAPIBase, p.appName, machineID)+ req, err := http.NewRequestWithContext(ctx, "GET", url, nil)+ if err != nil {+ return err+ }+ req.Header.Set("Authorization", "Bearer "+p.token)++ resp, err := p.client.Do(req)+ if err != nil {+ return fmt.Errorf("health check failed: %w", err)+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ return fmt.Errorf("machine %s returned status %d", machineID, resp.StatusCode)+ }+ return nil+}++func (p *FlyPool) machineAction(ctx context.Context, machineID, method, action string) error {+ url := fmt.Sprintf("%s/apps/%s/machines/%s%s", flyAPIBase, p.appName, machineID, action)+ req, err := http.NewRequestWithContext(ctx, method, url, nil)+ if err != nil {+ return err+ }+ req.Header.Set("Authorization", "Bearer "+p.token)++ resp, err := p.client.Do(req)+ if err != nil {+ return fmt.Errorf("fly API request failed: %w", err)+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ respBody, _ := io.ReadAll(resp.Body)+ return fmt.Errorf("fly API returned %d: %s", resp.StatusCode, string(respBody))+ }+ return nil+}diff --git a/internal/compute/local.go b/internal/compute/local.gonew file mode 100644index 00000000..3a1cb9e6--- /dev/null+++ b/internal/compute/local.go@@ -0,0 +1,53 @@+package compute++import (+ "context"+ "fmt"+)++// LocalPool is a single-machine compute pool for development.+type LocalPool struct {+ workerAddr string+ machine *Machine+}++// NewLocalPool creates a local compute pool pointing to localhost.+func NewLocalPool(workerAddr string) *LocalPool {+ return &LocalPool{+ workerAddr: workerAddr,+ machine: &Machine{+ ID: "local",+ Addr: workerAddr,+ Region: "local",+ Status: "running",+ Capacity: 100,+ Current: 0,+ },+ }+}++func (p *LocalPool) CreateMachine(_ context.Context, _ MachineOpts) (*Machine, error) {+ return p.machine, nil+}++func (p *LocalPool) DestroyMachine(_ context.Context, _ string) error {+ return fmt.Errorf("cannot destroy local machine")+}++func (p *LocalPool) StartMachine(_ context.Context, _ string) error {+ p.machine.Status = "running"+ return nil+}++func (p *LocalPool) StopMachine(_ context.Context, _ string) error {+ p.machine.Status = "stopped"+ return nil+}++func (p *LocalPool) ListMachines(_ context.Context) ([]*Machine, error) {+ return []*Machine{p.machine}, nil+}++func (p *LocalPool) HealthCheck(_ context.Context, _ string) error {+ return nil // Local machine is always healthy+}diff --git a/internal/compute/local_test.go b/internal/compute/local_test.gonew file mode 100644index 00000000..7b3bc906--- /dev/null+++ b/internal/compute/local_test.go@@ -0,0 +1,50 @@+package compute++import (+ "context"+ "testing"+)++func TestLocalPool_ListMachines(t *testing.T) {+ pool := NewLocalPool("localhost:9090")+ machines, err := pool.ListMachines(context.Background())+ if err != nil {+ t.Fatalf("ListMachines() error: %v", err)+ }+ if len(machines) != 1 {+ t.Fatalf("expected 1 machine, got %d", len(machines))+ }+ if machines[0].ID != "local" {+ t.Errorf("expected machine ID 'local', got %s", machines[0].ID)+ }+ if machines[0].Status != "running" {+ t.Errorf("expected status 'running', got %s", machines[0].Status)+ }+}++func TestLocalPool_CreateMachine(t *testing.T) {+ pool := NewLocalPool("localhost:9090")+ m, err := pool.CreateMachine(context.Background(), MachineOpts{})+ if err != nil {+ t.Fatalf("CreateMachine() error: %v", err)+ }+ if m.Addr != "localhost:9090" {+ t.Errorf("expected addr localhost:9090, got %s", m.Addr)+ }+}++func TestLocalPool_DestroyMachine(t *testing.T) {+ pool := NewLocalPool("localhost:9090")+ err := pool.DestroyMachine(context.Background(), "local")+ if err == nil {+ t.Error("expected error when destroying local machine")+ }+}++func TestLocalPool_HealthCheck(t *testing.T) {+ pool := NewLocalPool("localhost:9090")+ err := pool.HealthCheck(context.Background(), "local")+ if err != nil {+ t.Errorf("HealthCheck() error: %v", err)+ }+}diff --git a/internal/compute/pool.go b/internal/compute/pool.gonew file mode 100644index 00000000..eaed0186--- /dev/null+++ b/internal/compute/pool.go@@ -0,0 +1,30 @@+package compute++import "context"++// Machine represents a worker machine in the compute pool.+type Machine struct {+ ID string `json:"id"`+ Addr string `json:"addr"` // internal address (host:port)+ Region string `json:"region"`+ Status string `json:"status"` // "running", "stopped", "creating"+ Capacity int `json:"capacity"` // max sandboxes+ Current int `json:"current"` // current sandbox count+}++// MachineOpts are options for creating a new machine.+type MachineOpts struct {+ Region string+ Size string // provider-specific machine size+ Image string // worker Docker image+}++// Pool is the interface for compute pool providers.+type Pool interface {+ CreateMachine(ctx context.Context, opts MachineOpts) (*Machine, error)+ DestroyMachine(ctx context.Context, machineID string) error+ StartMachine(ctx context.Context, machineID string) error+ StopMachine(ctx context.Context, machineID string) error+ ListMachines(ctx context.Context) ([]*Machine, error)+ HealthCheck(ctx context.Context, machineID string) error+}diff --git a/internal/compute/router.go b/internal/compute/router.gonew file mode 100644index 00000000..44c58b2b--- /dev/null+++ b/internal/compute/router.go@@ -0,0 +1,72 @@+package compute++import (+ "context"+ "fmt"+ "sync"+)++// Router routes sandbox operations to the appropriate machine.+type Router struct {+ pool Pool+ mu sync.RWMutex+ mapping map[string]string // sandbox ID -> machine ID+}++// NewRouter creates a new sandbox router.+func NewRouter(pool Pool) *Router {+ return &Router{+ pool: pool,+ mapping: make(map[string]string),+ }+}++// Assign picks the least-loaded machine for a new sandbox.+func (r *Router) Assign(ctx context.Context, sandboxID string) (*Machine, error) {+ machines, err := r.pool.ListMachines(ctx)+ if err != nil {+ return nil, fmt.Errorf("failed to list machines: %w", err)+ }++ // Find the machine with the most remaining capacity+ var best *Machine+ for _, m := range machines {+ if m.Status != "running" {+ continue+ }+ remaining := m.Capacity - m.Current+ if best == nil || remaining > (best.Capacity-best.Current) {+ best = m+ }+ }++ if best == nil {+ return nil, fmt.Errorf("no available machines in compute pool")+ }++ r.mu.Lock()+ r.mapping[sandboxID] = best.ID+ best.Current+++ r.mu.Unlock()++ return best, nil+}++// Lookup returns the machine that hosts a given sandbox.+func (r *Router) Lookup(sandboxID string) (string, error) {+ r.mu.RLock()+ defer r.mu.RUnlock()++ machineID, ok := r.mapping[sandboxID]+ if !ok {+ return "", fmt.Errorf("sandbox %s not found in routing table", sandboxID)+ }+ return machineID, nil+}++// Release removes a sandbox from the routing table.+func (r *Router) Release(sandboxID string) {+ r.mu.Lock()+ defer r.mu.Unlock()+ delete(r.mapping, sandboxID)+}diff --git a/internal/compute/router_test.go b/internal/compute/router_test.gonew file mode 100644index 00000000..b08b1956--- /dev/null+++ b/internal/compute/router_test.go@@ -0,0 +1,54 @@+package compute++import (+ "context"+ "testing"+)++func TestRouter_AssignAndLookup(t *testing.T) {+ pool := NewLocalPool("localhost:9090")+ router := NewRouter(pool)++ machine, err := router.Assign(context.Background(), "sandbox-1")+ if err != nil {+ t.Fatalf("Assign() error: %v", err)+ }+ if machine.ID != "local" {+ t.Errorf("expected machine ID 'local', got %s", machine.ID)+ }++ machineID, err := router.Lookup("sandbox-1")+ if err != nil {+ t.Fatalf("Lookup() error: %v", err)+ }+ if machineID != "local" {+ t.Errorf("expected machine ID 'local', got %s", machineID)+ }+}++func TestRouter_LookupNotFound(t *testing.T) {+ pool := NewLocalPool("localhost:9090")+ router := NewRouter(pool)++ _, err := router.Lookup("nonexistent")+ if err == nil {+ t.Error("expected error for nonexistent sandbox")+ }+}++func TestRouter_Release(t *testing.T) {+ pool := NewLocalPool("localhost:9090")+ router := NewRouter(pool)++ _, err := router.Assign(context.Background(), "sandbox-1")+ if err != nil {+ t.Fatalf("Assign() error: %v", err)+ }++ router.Release("sandbox-1")++ _, err = router.Lookup("sandbox-1")+ if err == nil {+ t.Error("expected error after release")+ }+}diff --git a/internal/config/config.go b/internal/config/config.gonew file mode 100644index 00000000..0c4095d2--- /dev/null+++ b/internal/config/config.go@@ -0,0 +1,44 @@+package config++import (+ "fmt"+ "os"+ "strconv"+)++// Config holds all configuration for the opensandbox server.+type Config struct {+ Port int+ APIKey string+ WorkerAddr string+ Mode string // "server", "worker", "combined"+ LogLevel string+}++// Load reads configuration from environment variables with sensible defaults.+func Load() (*Config, error) {+ cfg := &Config{+ Port: 8080,+ APIKey: os.Getenv("OPENSANDBOX_API_KEY"),+ WorkerAddr: envOrDefault("OPENSANDBOX_WORKER_ADDR", "localhost:9090"),+ Mode: envOrDefault("OPENSANDBOX_MODE", "combined"),+ LogLevel: envOrDefault("OPENSANDBOX_LOG_LEVEL", "info"),+ }++ if portStr := os.Getenv("OPENSANDBOX_PORT"); portStr != "" {+ port, err := strconv.Atoi(portStr)+ if err != nil {+ return nil, fmt.Errorf("invalid OPENSANDBOX_PORT %q: %w", portStr, err)+ }+ cfg.Port = port+ }++ return cfg, nil+}++func envOrDefault(key, fallback string) string {+ if v := os.Getenv(key); v != "" {+ return v+ }+ return fallback+}diff --git a/internal/config/config_test.go b/internal/config/config_test.gonew file mode 100644index 00000000..574d09b4--- /dev/null+++ b/internal/config/config_test.go@@ -0,0 +1,65 @@+package config++import (+ "os"+ "testing"+)++func TestLoadDefaults(t *testing.T) {+ // Clear env to test defaults+ os.Unsetenv("OPENSANDBOX_PORT")+ os.Unsetenv("OPENSANDBOX_API_KEY")+ os.Unsetenv("OPENSANDBOX_WORKER_ADDR")+ os.Unsetenv("OPENSANDBOX_MODE")++ cfg, err := Load()+ if err != nil {+ t.Fatalf("Load() returned error: %v", err)+ }++ if cfg.Port != 8080 {+ t.Errorf("expected port 8080, got %d", cfg.Port)+ }+ if cfg.Mode != "combined" {+ t.Errorf("expected mode combined, got %s", cfg.Mode)+ }+ if cfg.WorkerAddr != "localhost:9090" {+ t.Errorf("expected worker addr localhost:9090, got %s", cfg.WorkerAddr)+ }+}++func TestLoadFromEnv(t *testing.T) {+ os.Setenv("OPENSANDBOX_PORT", "9999")+ os.Setenv("OPENSANDBOX_API_KEY", "test-key")+ os.Setenv("OPENSANDBOX_MODE", "server")+ defer func() {+ os.Unsetenv("OPENSANDBOX_PORT")+ os.Unsetenv("OPENSANDBOX_API_KEY")+ os.Unsetenv("OPENSANDBOX_MODE")+ }()++ cfg, err := Load()+ if err != nil {+ t.Fatalf("Load() returned error: %v", err)+ }++ if cfg.Port != 9999 {+ t.Errorf("expected port 9999, got %d", cfg.Port)+ }+ if cfg.APIKey != "test-key" {+ t.Errorf("expected API key test-key, got %s", cfg.APIKey)+ }+ if cfg.Mode != "server" {+ t.Errorf("expected mode server, got %s", cfg.Mode)+ }+}++func TestLoadInvalidPort(t *testing.T) {+ os.Setenv("OPENSANDBOX_PORT", "not-a-number")+ defer os.Unsetenv("OPENSANDBOX_PORT")++ _, err := Load()+ if err == nil {+ t.Fatal("expected error for invalid port, got nil")+ }+}diff --git a/internal/podman/client.go b/internal/podman/client.gonew file mode 100644index 00000000..1a8d2cc9--- /dev/null+++ b/internal/podman/client.go@@ -0,0 +1,116 @@+package podman++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+)++// Client wraps the podman CLI for container operations.+type Client struct {+ binaryPath string+ authFile string // dedicated auth file to avoid Docker credential helper conflicts+}++// NewClient creates a new Podman client. It verifies podman is available.+func NewClient() (*Client, error) {+ path, err := exec.LookPath("podman")+ if err != nil {+ return nil, fmt.Errorf("podman not found in PATH: %w", err)+ }++ // Create a dedicated auth file so Podman doesn't inherit Docker Desktop's+ // credential helpers (docker-credential-gcloud, docker-credential-desktop, etc.)+ authFile, err := ensureAuthFile()+ if err != nil {+ return nil, fmt.Errorf("failed to set up podman auth: %w", err)+ }++ return &Client{binaryPath: path, authFile: authFile}, nil+}++// AuthFile returns the path to the dedicated auth file.+func (c *Client) AuthFile() string {+ return c.authFile+}++func ensureAuthFile() (string, error) {+ home, err := os.UserHomeDir()+ if err != nil {+ return "", err+ }+ dir := filepath.Join(home, ".config", "opensandbox")+ if err := os.MkdirAll(dir, 0700); err != nil {+ return "", err+ }+ authFile := filepath.Join(dir, "auth.json")+ if _, err := os.Stat(authFile); os.IsNotExist(err) {+ if err := os.WriteFile(authFile, []byte(`{"auths":{}}`), 0600); err != nil {+ return "", err+ }+ }+ return authFile, nil+}++// ExecResult holds the output from a podman command.+type ExecResult struct {+ Stdout string+ Stderr string+ ExitCode int+}++// Run executes a podman command and returns the result.+func (c *Client) Run(ctx context.Context, args ...string) (*ExecResult, error) {+ cmd := exec.CommandContext(ctx, c.binaryPath, args...)+ cmd.Env = append(os.Environ(), "REGISTRY_AUTH_FILE="+c.authFile)+ var stdout, stderr bytes.Buffer+ cmd.Stdout = &stdout+ cmd.Stderr = &stderr++ err := cmd.Run()++ result := &ExecResult{+ Stdout: stdout.String(),+ Stderr: stderr.String(),+ }++ if err != nil {+ if exitErr, ok := err.(*exec.ExitError); ok {+ result.ExitCode = exitErr.ExitCode()+ return result, nil+ }+ return result, fmt.Errorf("podman exec failed: %w", err)+ }++ return result, nil+}++// RunJSON executes a podman command and parses JSON output into dest.+func (c *Client) RunJSON(ctx context.Context, dest interface{}, args ...string) error {+ result, err := c.Run(ctx, args...)+ if err != nil {+ return err+ }+ if result.ExitCode != 0 {+ return fmt.Errorf("podman %s failed (exit %d): %s",+ strings.Join(args, " "), result.ExitCode, strings.TrimSpace(result.Stderr))+ }+ if err := json.Unmarshal([]byte(result.Stdout), dest); err != nil {+ return fmt.Errorf("failed to parse podman output: %w", err)+ }+ return nil+}++// Version returns the podman version string.+func (c *Client) Version(ctx context.Context) (string, error) {+ result, err := c.Run(ctx, "version", "--format", "{{.Client.Version}}")+ if err != nil {+ return "", err+ }+ return strings.TrimSpace(result.Stdout), nil+}diff --git a/internal/podman/container.go b/internal/podman/container.gonew file mode 100644index 00000000..979973b6--- /dev/null+++ b/internal/podman/container.go@@ -0,0 +1,273 @@+package podman++import (+ "context"+ "encoding/json"+ "fmt"+ "strings"+)++// ContainerConfig defines how to create a container.+type ContainerConfig struct {+ Name string+ Image string+ Labels map[string]string+ Env map[string]string+ Memory string // e.g. "512m"+ CPUs string // e.g. "1"+ PidsLimit int+ NetworkMode string // "none", "slirp4netns"+ ReadOnly bool+ TmpFS map[string]string // mount -> options+ CapDrop []string+ SecurityOpts []string+ UserNS string+ Entrypoint []string+ Command []string+}++// DefaultContainerConfig returns a security-hardened container config.+func DefaultContainerConfig(name, image string) ContainerConfig {+ return ContainerConfig{+ Name: name,+ Image: image,+ Labels: make(map[string]string),+ Env: make(map[string]string),+ Memory: "512m",+ CPUs: "1",+ PidsLimit: 256,+ NetworkMode: "none",+ ReadOnly: true,+ TmpFS: map[string]string{+ "/tmp": "rw,size=100m",+ },+ CapDrop: []string{"ALL"},+ SecurityOpts: []string{"no-new-privileges"},+ UserNS: "",+ Entrypoint: []string{"/bin/sleep"},+ Command: []string{"infinity"},+ }+}++// CreateContainer creates a container with the given config. Returns the container ID.+func (c *Client) CreateContainer(ctx context.Context, cfg ContainerConfig) (string, error) {+ args := []string{"create", "--name", cfg.Name}++ for k, v := range cfg.Labels {+ args = append(args, "--label", fmt.Sprintf("%s=%s", k, v))+ }++ for k, v := range cfg.Env {+ args = append(args, "--env", fmt.Sprintf("%s=%s", k, v))+ }++ if cfg.Memory != "" {+ args = append(args, "--memory", cfg.Memory)+ }+ if cfg.CPUs != "" {+ args = append(args, "--cpus", cfg.CPUs)+ }+ if cfg.PidsLimit > 0 {+ args = append(args, "--pids-limit", fmt.Sprintf("%d", cfg.PidsLimit))+ }+ if cfg.NetworkMode != "" {+ args = append(args, "--network", cfg.NetworkMode)+ }+ if cfg.ReadOnly {+ args = append(args, "--read-only")+ }+ for mount, opts := range cfg.TmpFS {+ args = append(args, "--tmpfs", fmt.Sprintf("%s:%s", mount, opts))+ }+ for _, cap := range cfg.CapDrop {+ args = append(args, "--cap-drop", cap)+ }+ for _, opt := range cfg.SecurityOpts {+ args = append(args, "--security-opt", opt)+ }+ if cfg.UserNS != "" {+ args = append(args, "--userns", cfg.UserNS)+ }++ if len(cfg.Entrypoint) > 0 {+ args = append(args, "--entrypoint", cfg.Entrypoint[0])+ }++ args = append(args, cfg.Image)+ args = append(args, cfg.Command...)++ result, err := c.Run(ctx, args...)+ if err != nil {+ return "", fmt.Errorf("failed to create container %s: %w", cfg.Name, err)+ }+ if result.ExitCode != 0 {+ return "", fmt.Errorf("podman create failed (exit %d): %s",+ result.ExitCode, strings.TrimSpace(result.Stderr))+ }++ return strings.TrimSpace(result.Stdout), nil+}++// StartContainer starts a container by name or ID.+func (c *Client) StartContainer(ctx context.Context, nameOrID string) error {+ result, err := c.Run(ctx, "start", nameOrID)+ if err != nil {+ return fmt.Errorf("failed to start container %s: %w", nameOrID, err)+ }+ if result.ExitCode != 0 {+ return fmt.Errorf("podman start failed (exit %d): %s",+ result.ExitCode, strings.TrimSpace(result.Stderr))+ }+ return nil+}++// StopContainer stops a container by name or ID.+func (c *Client) StopContainer(ctx context.Context, nameOrID string, timeoutSec int) error {+ args := []string{"stop"}+ if timeoutSec > 0 {+ args = append(args, "--time", fmt.Sprintf("%d", timeoutSec))+ }+ args = append(args, nameOrID)++ result, err := c.Run(ctx, args...)+ if err != nil {+ return fmt.Errorf("failed to stop container %s: %w", nameOrID, err)+ }+ if result.ExitCode != 0 {+ return fmt.Errorf("podman stop failed (exit %d): %s",+ result.ExitCode, strings.TrimSpace(result.Stderr))+ }+ return nil+}++// RemoveContainer removes a container by name or ID. Force=true kills running containers.+func (c *Client) RemoveContainer(ctx context.Context, nameOrID string, force bool) error {+ args := []string{"rm"}+ if force {+ args = append(args, "--force", "--time", "0")+ }+ args = append(args, nameOrID)++ result, err := c.Run(ctx, args...)+ if err != nil {+ return fmt.Errorf("failed to remove container %s: %w", nameOrID, err)+ }+ if result.ExitCode != 0 {+ return fmt.Errorf("podman rm failed (exit %d): %s",+ result.ExitCode, strings.TrimSpace(result.Stderr))+ }+ return nil+}++// ContainerInfo holds inspect output for a container.+type ContainerInfo struct {+ ID string `json:"Id"`+ Name string `json:"Name"`+ State struct {+ Status string `json:"Status"`+ Running bool `json:"Running"`+ StartedAt string `json:"StartedAt"`+ } `json:"State"`+ Config struct {+ Labels map[string]string `json:"Labels"`+ Image string `json:"Image"`+ } `json:"Config"`+}++// InspectContainer returns detailed info about a container.+func (c *Client) InspectContainer(ctx context.Context, nameOrID string) (*ContainerInfo, error) {+ var infos []ContainerInfo+ if err := c.RunJSON(ctx, &infos, "inspect", nameOrID); err != nil {+ return nil, fmt.Errorf("failed to inspect container %s: %w", nameOrID, err)+ }+ if len(infos) == 0 {+ return nil, fmt.Errorf("container %s not found", nameOrID)+ }+ return &infos[0], nil+}++// PSEntry represents a container from podman ps.+type PSEntry struct {+ ID string `json:"Id"`+ Names []string `json:"Names"`+ State string `json:"State"`+ Labels map[string]string `json:"Labels"`+ Image string `json:"Image"`+}++// ListContainers lists containers matching the given label filter.+func (c *Client) ListContainers(ctx context.Context, labelFilter string) ([]PSEntry, error) {+ args := []string{"ps", "-a", "--format", "json"}+ if labelFilter != "" {+ args = append(args, "--filter", fmt.Sprintf("label=%s", labelFilter))+ }++ result, err := c.Run(ctx, args...)+ if err != nil {+ return nil, err+ }+ if result.ExitCode != 0 {+ return nil, fmt.Errorf("podman ps failed (exit %d): %s",+ result.ExitCode, strings.TrimSpace(result.Stderr))+ }++ output := strings.TrimSpace(result.Stdout)+ if output == "" {+ return nil, nil+ }++ var entries []PSEntry+ if err := parseJSONOutput(output, &entries); err != nil {+ return nil, fmt.Errorf("failed to parse podman ps output: %w", err)+ }+ return entries, nil+}++// parseJSONOutput handles both JSON array and newline-delimited JSON.+func parseJSONOutput(output string, dest *[]PSEntry) error {+ output = strings.TrimSpace(output)+ if output == "" || output == "[]" {+ return nil+ }++ // Try array first (newer podman versions)+ if strings.HasPrefix(output, "[") {+ return json.Unmarshal([]byte(output), dest)+ }++ // Newline-delimited JSON (older podman versions)+ for _, line := range strings.Split(output, "\n") {+ line = strings.TrimSpace(line)+ if line == "" {+ continue+ }+ var entry PSEntry+ if err := json.Unmarshal([]byte(line), &entry); err != nil {+ return err+ }+ *dest = append(*dest, entry)+ }+ return nil+}++// PullImage pulls a container image.+func (c *Client) PullImage(ctx context.Context, image string) error {+ result, err := c.Run(ctx, "pull", image)+ if err != nil {+ return fmt.Errorf("failed to pull image %s: %w", image, err)+ }+ if result.ExitCode != 0 {+ return fmt.Errorf("podman pull failed (exit %d): %s",+ result.ExitCode, strings.TrimSpace(result.Stderr))+ }+ return nil+}++// ImageExists checks whether an image is available locally.+func (c *Client) ImageExists(ctx context.Context, image string) (bool, error) {+ result, err := c.Run(ctx, "image", "exists", image)+ if err != nil {+ return false, err+ }+ return result.ExitCode == 0, nil+}diff --git a/internal/podman/exec.go b/internal/podman/exec.gonew file mode 100644index 00000000..72bc0ff9--- /dev/null+++ b/internal/podman/exec.go@@ -0,0 +1,85 @@+package podman++import (+ "bytes"+ "context"+ "fmt"+ "io"+ "os"+ "os/exec"+ "strings"+)++// ExecConfig defines options for executing a command inside a container.+type ExecConfig struct {+ Container string+ Command []string+ Env map[string]string+ Cwd string+ Stdin io.Reader+ TTY bool+}++// ExecInContainer runs a command inside a running container and returns the result.+func (c *Client) ExecInContainer(ctx context.Context, cfg ExecConfig) (*ExecResult, error) {+ args := []string{"exec"}++ if cfg.TTY {+ args = append(args, "-it")+ } else if cfg.Stdin != nil {+ args = append(args, "-i")+ }++ for k, v := range cfg.Env {+ args = append(args, "--env", fmt.Sprintf("%s=%s", k, v))+ }+ if cfg.Cwd != "" {+ args = append(args, "--workdir", cfg.Cwd)+ }++ args = append(args, cfg.Container)+ args = append(args, cfg.Command...)++ cmd := exec.CommandContext(ctx, c.binaryPath, args...)+ cmd.Env = append(os.Environ(), "REGISTRY_AUTH_FILE="+c.authFile)+ var stdout, stderr bytes.Buffer+ cmd.Stdout = &stdout+ cmd.Stderr = &stderr++ if cfg.Stdin != nil {+ cmd.Stdin = cfg.Stdin+ }++ err := cmd.Run()++ result := &ExecResult{+ Stdout: stdout.String(),+ Stderr: stderr.String(),+ }++ if err != nil {+ if exitErr, ok := err.(*exec.ExitError); ok {+ result.ExitCode = exitErr.ExitCode()+ return result, nil+ }+ return result, fmt.Errorf("podman exec failed: %w", err)+ }++ return result, nil+}++// ExecSimple runs a simple command inside a container and returns stdout.+func (c *Client) ExecSimple(ctx context.Context, container string, command ...string) (string, error) {+ result, err := c.ExecInContainer(ctx, ExecConfig{+ Container: container,+ Command: command,+ })+ if err != nil {+ return "", err+ }+ if result.ExitCode != 0 {+ return "", fmt.Errorf("command %v failed (exit %d): %s",+ command, result.ExitCode, strings.TrimSpace(result.Stderr))+ }+ return result.Stdout, nil+}diff --git a/internal/sandbox/exec.go b/internal/sandbox/exec.gonew file mode 100644index 00000000..e6d7aac4--- /dev/null+++ b/internal/sandbox/exec.go@@ -0,0 +1,59 @@+package sandbox++import (+ "context"+ "fmt"+ "strings"+ "time"++ "github.com/opensandbox/opensandbox/internal/podman"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// Exec runs a command inside a sandbox and returns the result.+func (m *Manager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error) {+ container := m.ContainerName(sandboxID)++ timeout := cfg.Timeout+ if timeout <= 0 {+ timeout = 60+ }++ execCtx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second)+ defer cancel()++ command := buildCommand(cfg.Command, cfg.Args)++ result, err := m.podman.ExecInContainer(execCtx, podman.ExecConfig{+ Container: container,+ Command: command,+ Env: cfg.Env,+ Cwd: cfg.Cwd,+ })+ if err != nil {+ if execCtx.Err() == context.DeadlineExceeded {+ return &types.ProcessResult{+ ExitCode: 124,+ Stderr: fmt.Sprintf("command timed out after %ds", timeout),+ }, nil+ }+ return nil, fmt.Errorf("exec in sandbox %s failed: %w", sandboxID, err)+ }++ return &types.ProcessResult{+ ExitCode: result.ExitCode,+ Stdout: result.Stdout,+ Stderr: result.Stderr,+ }, nil+}++func buildCommand(cmd string, args []string) []string {+ if len(args) > 0 {+ return append([]string{cmd}, args...)+ }+ // If no args, use shell to interpret the command string+ if strings.Contains(cmd, " ") || strings.Contains(cmd, "|") || strings.Contains(cmd, ";") {+ return []string{"/bin/sh", "-c", cmd}+ }+ return []string{cmd}+}diff --git a/internal/sandbox/filesystem.go b/internal/sandbox/filesystem.gonew file mode 100644index 00000000..689a06e9--- /dev/null+++ b/internal/sandbox/filesystem.go@@ -0,0 +1,160 @@+package sandbox++import (+ "context"+ "fmt"+ "strconv"+ "strings"++ "github.com/opensandbox/opensandbox/internal/podman"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// ReadFile reads a file from inside the sandbox.+func (m *Manager) ReadFile(ctx context.Context, sandboxID, path string) (string, error) {+ container := m.ContainerName(sandboxID)+ content, err := m.podman.ExecSimple(ctx, container, "cat", path)+ if err != nil {+ return "", fmt.Errorf("failed to read %s in sandbox %s: %w", path, sandboxID, err)+ }+ return content, nil+}++// WriteFile writes content to a file inside the sandbox.+func (m *Manager) WriteFile(ctx context.Context, sandboxID, path, content string) error {+ container := m.ContainerName(sandboxID)++ // Ensure parent directory exists+ dir := path[:strings.LastIndex(path, "/")]+ if dir != "" {+ _, _ = m.podman.ExecSimple(ctx, container, "mkdir", "-p", dir)+ }++ result, err := m.podman.ExecInContainer(ctx, podman.ExecConfig{+ Container: container,+ Command: []string{"/bin/sh", "-c", fmt.Sprintf("cat > %s", shellQuote(path))},+ Stdin: strings.NewReader(content),+ })+ if err != nil {+ return fmt.Errorf("failed to write %s in sandbox %s: %w", path, sandboxID, err)+ }+ if result.ExitCode != 0 {+ return fmt.Errorf("write to %s failed: %s", path, strings.TrimSpace(result.Stderr))+ }+ return nil+}++// ListDir lists directory contents inside the sandbox.+func (m *Manager) ListDir(ctx context.Context, sandboxID, path string) ([]types.EntryInfo, error) {+ container := m.ContainerName(sandboxID)++ // Use a script that outputs machine-parseable format+ script := fmt.Sprintf(+ `find %s -maxdepth 1 -mindepth 1 -printf '%%y\t%%s\t%%f\n' 2>/dev/null || ls -1a %s`,+ shellQuote(path), shellQuote(path),+ )+ output, err := m.podman.ExecSimple(ctx, container, "/bin/sh", "-c", script)+ if err != nil {+ return nil, fmt.Errorf("failed to list %s in sandbox %s: %w", path, sandboxID, err)+ }++ var entries []types.EntryInfo+ for _, line := range strings.Split(strings.TrimSpace(output), "\n") {+ if line == "" {+ continue+ }++ parts := strings.SplitN(line, "\t", 3)+ if len(parts) == 3 {+ // find -printf output: type\tsize\tname+ isDir := parts[0] == "d"+ size, _ := strconv.ParseInt(parts[1], 10, 64)+ name := parts[2]+ entryPath := path + "/" + name+ if strings.HasSuffix(path, "/") {+ entryPath = path + name+ }+ entries = append(entries, types.EntryInfo{+ Name: name,+ IsDir: isDir,+ Size: size,+ Path: entryPath,+ })+ } else {+ // Fallback: ls output (just names)+ name := strings.TrimSpace(line)+ if name == "." || name == ".." {+ continue+ }+ entries = append(entries, types.EntryInfo{+ Name: name,+ Path: path + "/" + name,+ })+ }+ }+ return entries, nil+}++// MakeDir creates a directory inside the sandbox.+func (m *Manager) MakeDir(ctx context.Context, sandboxID, path string) error {+ container := m.ContainerName(sandboxID)+ _, err := m.podman.ExecSimple(ctx, container, "mkdir", "-p", path)+ if err != nil {+ return fmt.Errorf("failed to mkdir %s in sandbox %s: %w", path, sandboxID, err)+ }+ return nil+}++// Remove removes a file or directory inside the sandbox.+func (m *Manager) Remove(ctx context.Context, sandboxID, path string) error {+ container := m.ContainerName(sandboxID)+ _, err := m.podman.ExecSimple(ctx, container, "rm", "-rf", path)+ if err != nil {+ return fmt.Errorf("failed to remove %s in sandbox %s: %w", path, sandboxID, err)+ }+ return nil+}++// Exists checks if a path exists inside the sandbox.+func (m *Manager) Exists(ctx context.Context, sandboxID, path string) (bool, error) {+ container := m.ContainerName(sandboxID)+ result, err := m.podman.ExecInContainer(ctx, podman.ExecConfig{+ Container: container,+ Command: []string{"test", "-e", path},+ })+ if err != nil {+ return false, err+ }+ return result.ExitCode == 0, nil+}++// Stat returns file info for a path inside the sandbox.+func (m *Manager) Stat(ctx context.Context, sandboxID, path string) (*types.FileInfo, error) {+ container := m.ContainerName(sandboxID)+ output, err := m.podman.ExecSimple(ctx, container,+ "stat", "--format", "%n\t%F\t%s\t%a\t%Y", path)+ if err != nil {+ return nil, fmt.Errorf("failed to stat %s in sandbox %s: %w", path, sandboxID, err)+ }++ parts := strings.SplitN(strings.TrimSpace(output), "\t", 5)+ if len(parts) < 5 {+ return nil, fmt.Errorf("unexpected stat output for %s", path)+ }++ size, _ := strconv.ParseInt(parts[2], 10, 64)+ isDir := strings.Contains(parts[1], "directory")++ return &types.FileInfo{+ Name: parts[0],+ IsDir: isDir,+ Size: size,+ Mode: parts[3],+ ModTime: parts[4],+ Path: path,+ }, nil+}++func shellQuote(s string) string {+ return "'" + strings.ReplaceAll(s, "'", "'\\''") + "'"+}diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.gonew file mode 100644index 00000000..cdb6b737--- /dev/null+++ b/internal/sandbox/manager.go@@ -0,0 +1,266 @@+package sandbox++import (+ "context"+ "fmt"+ "strconv"+ "sync"+ "time"++ "github.com/google/uuid"+ "github.com/opensandbox/opensandbox/internal/podman"+ "github.com/opensandbox/opensandbox/pkg/types"+)++const (+ labelPrefix = "opensandbox"+ labelID = labelPrefix + ".id"+ labelTemplate = labelPrefix + ".template"+ labelCreated = labelPrefix + ".created"+ labelTimeout = labelPrefix + ".timeout"+ containerName = "osb"++ defaultTimeout = 300 // 5 minutes+ defaultImage = "docker.io/library/ubuntu:22.04"+ defaultMemoryMB = 512+ defaultCPU = 1+)++// Manager handles sandbox lifecycle operations.+type Manager struct {+ podman *podman.Client+ mu sync.RWMutex+ timers map[string]*time.Timer // sandbox ID -> timeout timer+}++// NewManager creates a new sandbox manager.+func NewManager(client *podman.Client) *Manager {+ return &Manager{+ podman: client,+ timers: make(map[string]*time.Timer),+ }+}++// Create creates a new sandbox container and starts it.+func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {+ id := uuid.New().String()[:8]+ name := fmt.Sprintf("%s-%s", containerName, id)++ timeout := cfg.Timeout+ if timeout <= 0 {+ timeout = defaultTimeout+ }++ image := defaultImage+ if cfg.Template != "" {+ image = resolveTemplateImage(cfg.Template)+ }++ memoryMB := cfg.MemoryMB+ if memoryMB <= 0 {+ memoryMB = defaultMemoryMB+ }+ cpuCount := cfg.CpuCount+ if cpuCount <= 0 {+ cpuCount = defaultCPU+ }++ now := time.Now()++ ccfg := podman.DefaultContainerConfig(name, image)+ ccfg.Labels[labelID] = id+ ccfg.Labels[labelTemplate] = cfg.Template+ ccfg.Labels[labelCreated] = now.Format(time.RFC3339)+ ccfg.Labels[labelTimeout] = strconv.Itoa(timeout)+ ccfg.Memory = fmt.Sprintf("%dm", memoryMB)+ ccfg.CPUs = fmt.Sprintf("%d", cpuCount)++ for k, v := range cfg.Envs {+ ccfg.Env[k] = v+ }++ if cfg.NetworkEnabled {+ ccfg.NetworkMode = "slirp4netns"+ }++ // Make /tmp writable for sandbox use+ ccfg.TmpFS["/tmp"] = "rw,size=100m"+ // Add a writable home directory+ ccfg.TmpFS["/home/user"] = "rw,size=200m"++ if _, err := m.podman.CreateContainer(ctx, ccfg); err != nil {+ return nil, fmt.Errorf("failed to create sandbox %s: %w", id, err)+ }++ if err := m.podman.StartContainer(ctx, name); err != nil {+ // Clean up the created container on start failure+ _ = m.podman.RemoveContainer(ctx, name, true)+ return nil, fmt.Errorf("failed to start sandbox %s: %w", id, err)+ }++ sandbox := &types.Sandbox{+ ID: id,+ Template: cfg.Template,+ Alias: cfg.Alias,+ Status: types.SandboxStatusRunning,+ StartedAt: now,+ EndAt: now.Add(time.Duration(timeout) * time.Second),+ Metadata: cfg.Metadata,+ CpuCount: cpuCount,+ MemoryMB: memoryMB,+ }++ m.scheduleTimeout(id, name, time.Duration(timeout)*time.Second)++ return sandbox, nil+}++// Get returns sandbox info by ID.+func (m *Manager) Get(ctx context.Context, id string) (*types.Sandbox, error) {+ name := fmt.Sprintf("%s-%s", containerName, id)+ info, err := m.podman.InspectContainer(ctx, name)+ if err != nil {+ return nil, fmt.Errorf("sandbox %s not found: %w", id, err)+ }+ return containerInfoToSandbox(info), nil+}++// Kill forcefully removes a sandbox.+func (m *Manager) Kill(ctx context.Context, id string) error {+ name := fmt.Sprintf("%s-%s", containerName, id)+ m.cancelTimeout(id)+ if err := m.podman.RemoveContainer(ctx, name, true); err != nil {+ return fmt.Errorf("failed to kill sandbox %s: %w", id, err)+ }+ return nil+}++// List returns all sandboxes.+func (m *Manager) List(ctx context.Context) ([]types.Sandbox, error) {+ entries, err := m.podman.ListContainers(ctx, labelID)+ if err != nil {+ return nil, fmt.Errorf("failed to list sandboxes: %w", err)+ }++ sandboxes := make([]types.Sandbox, 0, len(entries))+ for _, e := range entries {+ sandboxes = append(sandboxes, psEntryToSandbox(e))+ }+ return sandboxes, nil+}++// SetTimeout updates the timeout for a running sandbox.+func (m *Manager) SetTimeout(ctx context.Context, id string, timeoutSec int) error {+ name := fmt.Sprintf("%s-%s", containerName, id)++ // Verify sandbox exists and is running+ info, err := m.podman.InspectContainer(ctx, name)+ if err != nil {+ return fmt.Errorf("sandbox %s not found: %w", id, err)+ }+ if !info.State.Running {+ return fmt.Errorf("sandbox %s is not running", id)+ }++ m.scheduleTimeout(id, name, time.Duration(timeoutSec)*time.Second)+ return nil+}++// ContainerName returns the podman container name for a sandbox ID.+func (m *Manager) ContainerName(id string) string {+ return fmt.Sprintf("%s-%s", containerName, id)+}++// Close cancels all timeout timers.+func (m *Manager) Close() {+ m.mu.Lock()+ defer m.mu.Unlock()+ for _, timer := range m.timers {+ timer.Stop()+ }+ m.timers = make(map[string]*time.Timer)+}++func (m *Manager) scheduleTimeout(id, name string, d time.Duration) {+ m.mu.Lock()+ defer m.mu.Unlock()++ if existing, ok := m.timers[id]; ok {+ existing.Stop()+ }++ m.timers[id] = time.AfterFunc(d, func() {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ _ = m.podman.RemoveContainer(ctx, name, true)++ m.mu.Lock()+ delete(m.timers, id)+ m.mu.Unlock()+ })+}++func (m *Manager) cancelTimeout(id string) {+ m.mu.Lock()+ defer m.mu.Unlock()+ if timer, ok := m.timers[id]; ok {+ timer.Stop()+ delete(m.timers, id)+ }+}++func resolveTemplateImage(template string) string {+ switch template {+ case "base", "":+ return "docker.io/library/ubuntu:22.04"+ case "python":+ return "docker.io/library/python:3.12-slim"+ case "node":+ return "docker.io/library/node:20-slim"+ default:+ // Custom template: assume it's an image name tagged by the template system+ return fmt.Sprintf("localhost/opensandbox-template/%s:latest", template)+ }+}++func containerInfoToSandbox(info *podman.ContainerInfo) *types.Sandbox {+ status := types.SandboxStatusStopped+ if info.State.Running {+ status = types.SandboxStatusRunning+ }++ id := info.Config.Labels[labelID]++ startedAt, _ := time.Parse(time.RFC3339, info.Config.Labels[labelCreated])+ timeoutSec, _ := strconv.Atoi(info.Config.Labels[labelTimeout])+ endAt := startedAt.Add(time.Duration(timeoutSec) * time.Second)++ return &types.Sandbox{+ ID: id,+ Template: info.Config.Labels[labelTemplate],+ Status: status,+ StartedAt: startedAt,+ EndAt: endAt,+ }+}++func psEntryToSandbox(entry podman.PSEntry) types.Sandbox {+ status := types.SandboxStatusStopped+ if entry.State == "running" {+ status = types.SandboxStatusRunning+ }++ id := entry.Labels[labelID]++ startedAt, _ := time.Parse(time.RFC3339, entry.Labels[labelCreated])+ timeoutSec, _ := strconv.Atoi(entry.Labels[labelTimeout])+ endAt := startedAt.Add(time.Duration(timeoutSec) * time.Second)++ return types.Sandbox{+ ID: id,+ Template: entry.Labels[labelTemplate],+ Status: status,+ StartedAt: startedAt,+ EndAt: endAt,+ }+}diff --git a/internal/sandbox/pty.go b/internal/sandbox/pty.gonew file mode 100644index 00000000..0e7320f7--- /dev/null+++ b/internal/sandbox/pty.go@@ -0,0 +1,158 @@+package sandbox++import (+ "fmt"+ "os"+ "os/exec"+ "sync"++ ptylib "github.com/creack/pty"+ "github.com/google/uuid"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// PTYManager manages PTY sessions.+type PTYManager struct {+ podmanPath string+ authFile string+ mu sync.RWMutex+ sessions map[string]*PTYSessionHandle+}++// PTYSessionHandle holds the state for an active PTY session.+type PTYSessionHandle struct {+ ID string+ SandboxID string+ Cmd *exec.Cmd+ PTY *os.File // master side of the pseudo-terminal (read + write)+ Done chan struct{}+}++// NewPTYManager creates a new PTY manager.+func NewPTYManager(podmanPath, authFile string) *PTYManager {+ return &PTYManager{+ podmanPath: podmanPath,+ authFile: authFile,+ sessions: make(map[string]*PTYSessionHandle),+ }+}++// CreateSession starts a new PTY session inside a sandbox.+func (pm *PTYManager) CreateSession(sandboxID string, req types.PTYCreateRequest) (*PTYSessionHandle, error) {+ sessionID := uuid.New().String()[:8]+ containerName := fmt.Sprintf("osb-%s", sandboxID)++ shell := req.Shell+ if shell == "" {+ shell = "/bin/bash"+ }++ cols := req.Cols+ if cols <= 0 {+ cols = 80+ }+ rows := req.Rows+ if rows <= 0 {+ rows = 24+ }++ args := []string{+ "exec", "-it",+ "--env", "TERM=xterm-256color",+ containerName,+ shell,+ }++ cmd := exec.Command(pm.podmanPath, args...)+ cmd.Env = append(os.Environ(), "REGISTRY_AUTH_FILE="+pm.authFile)++ // Start with a real pseudo-terminal+ ptmx, err := ptylib.StartWithSize(cmd, &ptylib.Winsize{+ Rows: uint16(rows),+ Cols: uint16(cols),+ })+ if err != nil {+ return nil, fmt.Errorf("failed to start PTY session: %w", err)+ }++ handle := &PTYSessionHandle{+ ID: sessionID,+ SandboxID: sandboxID,+ Cmd: cmd,+ PTY: ptmx,+ Done: make(chan struct{}),+ }++ go func() {+ _ = cmd.Wait()+ close(handle.Done)+ }()++ pm.mu.Lock()+ pm.sessions[sessionID] = handle+ pm.mu.Unlock()++ return handle, nil+}++// Resize changes the terminal size for a PTY session.+func (pm *PTYManager) Resize(sessionID string, cols, rows int) error {+ pm.mu.RLock()+ session, ok := pm.sessions[sessionID]+ pm.mu.RUnlock()++ if !ok {+ return fmt.Errorf("PTY session %s not found", sessionID)+ }++ return ptylib.Setsize(session.PTY, &ptylib.Winsize{+ Rows: uint16(rows),+ Cols: uint16(cols),+ })+}++// GetSession returns a PTY session by ID.+func (pm *PTYManager) GetSession(sessionID string) (*PTYSessionHandle, error) {+ pm.mu.RLock()+ defer pm.mu.RUnlock()++ session, ok := pm.sessions[sessionID]+ if !ok {+ return nil, fmt.Errorf("PTY session %s not found", sessionID)+ }+ return session, nil+}++// KillSession terminates a PTY session.+func (pm *PTYManager) KillSession(sessionID string) error {+ pm.mu.Lock()+ session, ok := pm.sessions[sessionID]+ if ok {+ delete(pm.sessions, sessionID)+ }+ pm.mu.Unlock()++ if !ok {+ return fmt.Errorf("PTY session %s not found", sessionID)+ }++ session.PTY.Close()+ if session.Cmd.Process != nil {+ _ = session.Cmd.Process.Kill()+ }+ return nil+}++// CloseAll terminates all PTY sessions.+func (pm *PTYManager) CloseAll() {+ pm.mu.Lock()+ defer pm.mu.Unlock()++ for _, session := range pm.sessions {+ session.PTY.Close()+ if session.Cmd.Process != nil {+ _ = session.Cmd.Process.Kill()+ }+ }+ pm.sessions = make(map[string]*PTYSessionHandle)+}diff --git a/internal/template/builder.go b/internal/template/builder.gonew file mode 100644index 00000000..ee23d77c--- /dev/null+++ b/internal/template/builder.go@@ -0,0 +1,68 @@+package template++import (+ "context"+ "fmt"+ "os"+ "path/filepath"+ "time"++ "github.com/google/uuid"+ "github.com/opensandbox/opensandbox/internal/podman"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// Builder builds container images from Dockerfiles.+type Builder struct {+ podman *podman.Client+ registry *Registry+}++// NewBuilder creates a new template builder.+func NewBuilder(client *podman.Client, registry *Registry) *Builder {+ return &Builder{+ podman: client,+ registry: registry,+ }+}++// Build builds a template from Dockerfile content.+func (b *Builder) Build(ctx context.Context, dockerfileContent, name string) (*types.Template, error) {+ buildID := uuid.New().String()[:8]+ tag := "latest"+ imageName := fmt.Sprintf("localhost/opensandbox-template/%s:%s", name, tag)++ // Write Dockerfile to temp directory+ tmpDir, err := os.MkdirTemp("", "opensandbox-build-*")+ if err != nil {+ return nil, fmt.Errorf("failed to create temp dir for build: %w", err)+ }+ defer os.RemoveAll(tmpDir)++ dockerfilePath := filepath.Join(tmpDir, "Dockerfile")+ if err := os.WriteFile(dockerfilePath, []byte(dockerfileContent), 0644); err != nil {+ return nil, fmt.Errorf("failed to write Dockerfile: %w", err)+ }++ // Build image with podman+ result, err := b.podman.Run(ctx, "build", "-t", imageName, "-f", dockerfilePath, tmpDir)+ if err != nil {+ return nil, fmt.Errorf("failed to build template %s: %w", name, err)+ }+ if result.ExitCode != 0 {+ return nil, fmt.Errorf("podman build failed (exit %d): %s", result.ExitCode, result.Stderr)+ }++ tmpl := &types.Template{+ ID: name,+ Name: name,+ Tag: tag,+ ImageID: imageName,+ BuildID: buildID,+ Status: "ready",+ CreatedAt: time.Now(),+ }++ b.registry.Register(tmpl)+ return tmpl, nil+}diff --git a/internal/template/registry.go b/internal/template/registry.gonew file mode 100644index 00000000..36fb26ac--- /dev/null+++ b/internal/template/registry.go@@ -0,0 +1,89 @@+package template++import (+ "fmt"+ "sync"+ "time"++ "github.com/opensandbox/opensandbox/pkg/types"+)++// Registry stores template metadata in-memory.+type Registry struct {+ mu sync.RWMutex+ templates map[string]*types.Template // keyed by name+}++// NewRegistry creates a new template registry with default templates.+func NewRegistry() *Registry {+ r := &Registry{+ templates: make(map[string]*types.Template),+ }++ // Register default templates+ defaults := []struct {+ name string+ imageID string+ }{+ {"base", "docker.io/library/ubuntu:22.04"},+ {"python", "docker.io/library/python:3.12-slim"},+ {"node", "docker.io/library/node:20-slim"},+ }++ now := time.Now()+ for _, d := range defaults {+ r.templates[d.name] = &types.Template{+ ID: d.name,+ Name: d.name,+ Tag: "latest",+ ImageID: d.imageID,+ Status: "ready",+ CreatedAt: now,+ }+ }++ return r+}++// Get returns a template by name.+func (r *Registry) Get(name string) (*types.Template, error) {+ r.mu.RLock()+ defer r.mu.RUnlock()++ t, ok := r.templates[name]+ if !ok {+ return nil, fmt.Errorf("template %q not found", name)+ }+ return t, nil+}++// List returns all templates.+func (r *Registry) List() []types.Template {+ r.mu.RLock()+ defer r.mu.RUnlock()++ result := make([]types.Template, 0, len(r.templates))+ for _, t := range r.templates {+ result = append(result, *t)+ }+ return result+}++// Register adds or updates a template.+func (r *Registry) Register(t *types.Template) {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.templates[t.Name] = t+}++// Delete removes a template by name. Returns error if it's a default template.+func (r *Registry) Delete(name string) error {+ r.mu.Lock()+ defer r.mu.Unlock()++ if _, ok := r.templates[name]; !ok {+ return fmt.Errorf("template %q not found", name)+ }+ delete(r.templates, name)+ return nil+}diff --git a/internal/template/registry_test.go b/internal/template/registry_test.gonew file mode 100644index 00000000..c2e71aa0--- /dev/null+++ b/internal/template/registry_test.go@@ -0,0 +1,70 @@+package template++import (+ "testing"++ "github.com/opensandbox/opensandbox/pkg/types"+)++func TestNewRegistry_HasDefaults(t *testing.T) {+ r := NewRegistry()+ templates := r.List()+ if len(templates) != 3 {+ t.Fatalf("expected 3 default templates, got %d", len(templates))+ }++ base, err := r.Get("base")+ if err != nil {+ t.Fatalf("Get(base) error: %v", err)+ }+ if base.ImageID != "docker.io/library/ubuntu:22.04" {+ t.Errorf("expected ubuntu image, got %s", base.ImageID)+ }+}++func TestRegistry_RegisterAndGet(t *testing.T) {+ r := NewRegistry()+ r.Register(&types.Template{+ ID: "custom",+ Name: "custom",+ Tag: "v1",+ ImageID: "test-image",+ Status: "ready",+ })++ tmpl, err := r.Get("custom")+ if err != nil {+ t.Fatalf("Get(custom) error: %v", err)+ }+ if tmpl.Tag != "v1" {+ t.Errorf("expected tag v1, got %s", tmpl.Tag)+ }+}++func TestRegistry_Delete(t *testing.T) {+ r := NewRegistry()+ if err := r.Delete("base"); err != nil {+ t.Fatalf("Delete(base) error: %v", err)+ }++ _, err := r.Get("base")+ if err == nil {+ t.Error("expected error after deleting base template")+ }+}++func TestRegistry_DeleteNotFound(t *testing.T) {+ r := NewRegistry()+ err := r.Delete("nonexistent")+ if err == nil {+ t.Error("expected error for nonexistent template")+ }+}++func TestRegistry_GetNotFound(t *testing.T) {+ r := NewRegistry()+ _, err := r.Get("nonexistent")+ if err == nil {+ t.Error("expected error for nonexistent template")+ }+}diff --git a/pkg/types/filesystem.go b/pkg/types/filesystem.gonew file mode 100644index 00000000..32202f9f--- /dev/null+++ b/pkg/types/filesystem.go@@ -0,0 +1,26 @@+package types++// EntryInfo represents a file or directory entry.+type EntryInfo struct {+ Name string `json:"name"`+ IsDir bool `json:"isDir"`+ Size int64 `json:"size,omitempty"`+ Path string `json:"path"`+}++// FileInfo provides detailed information about a file.+type FileInfo struct {+ Name string `json:"name"`+ IsDir bool `json:"isDir"`+ Size int64 `json:"size"`+ Mode string `json:"mode"`+ ModTime string `json:"modTime"`+ Path string `json:"path"`+}++// WatchEvent is sent over WebSocket when a file system change occurs.+type WatchEvent struct {+ Type string `json:"type"` // "create", "modify", "delete"+ Path string `json:"path"`+ Name string `json:"name"`+}diff --git a/pkg/types/process.go b/pkg/types/process.gonew file mode 100644index 00000000..4422ca26--- /dev/null+++ b/pkg/types/process.go@@ -0,0 +1,29 @@+package types++// ProcessResult is the result of a completed command execution.+type ProcessResult struct {+ ExitCode int `json:"exitCode"`+ Stdout string `json:"stdout"`+ Stderr string `json:"stderr"`+}++// ProcessConfig is the request body for running a command.+type ProcessConfig struct {+ Command string `json:"cmd"`+ Args []string `json:"args,omitempty"`+ Env map[string]string `json:"envs,omitempty"`+ Cwd string `json:"cwd,omitempty"`+ Timeout int `json:"timeout,omitempty"` // seconds, default 60+}++// BackgroundProcess represents a background process.+type BackgroundProcess struct {+ PID int `json:"pid"`+ Tag string `json:"tag,omitempty"`+}++// ProcessInfo describes a running process inside a sandbox.+type ProcessInfo struct {+ PID int `json:"pid"`+ Command string `json:"cmd"`+}diff --git a/pkg/types/pty.go b/pkg/types/pty.gonew file mode 100644index 00000000..f0b81a64--- /dev/null+++ b/pkg/types/pty.go@@ -0,0 +1,21 @@+package types++// PTYCreateRequest is the request body for creating a PTY session.+type PTYCreateRequest struct {+ Cols int `json:"cols,omitempty"` // default 80+ Rows int `json:"rows,omitempty"` // default 24+ Shell string `json:"shell,omitempty"` // default /bin/bash+}++// PTYSession represents an active PTY session.+type PTYSession struct {+ SessionID string `json:"sessionID"`+ SandboxID string `json:"sandboxID"`+}++// PTYResizeRequest is a WebSocket control frame for resizing the terminal.+type PTYResizeRequest struct {+ Type string `json:"type"` // "resize"+ Cols int `json:"cols"`+ Rows int `json:"rows"`+}diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.gonew file mode 100644index 00000000..75779ab9--- /dev/null+++ b/pkg/types/sandbox.go@@ -0,0 +1,49 @@+package types++import "time"++// SandboxStatus represents the current state of a sandbox.+type SandboxStatus string++const (+ SandboxStatusRunning SandboxStatus = "running"+ SandboxStatusStopped SandboxStatus = "stopped"+ SandboxStatusError SandboxStatus = "error"+)++// Sandbox represents a running sandbox instance.+type Sandbox struct {+ ID string `json:"sandboxID"`+ Template string `json:"templateID,omitempty"`+ Alias string `json:"alias,omitempty"`+ ClientID string `json:"clientID,omitempty"`+ Status SandboxStatus `json:"status"`+ StartedAt time.Time `json:"startedAt"`+ EndAt time.Time `json:"endAt"`+ Metadata map[string]string `json:"metadata,omitempty"`+ CpuCount int `json:"cpuCount"`+ MemoryMB int `json:"memoryMB"`+ MachineID string `json:"machineID,omitempty"`+}++// SandboxConfig is the request body for creating a sandbox.+type SandboxConfig struct {+ Template string `json:"templateID,omitempty"`+ Alias string `json:"alias,omitempty"`+ Metadata map[string]string `json:"metadata,omitempty"`+ Timeout int `json:"timeout,omitempty"` // seconds, default 300+ CpuCount int `json:"cpuCount,omitempty"` // default 1+ MemoryMB int `json:"memoryMB,omitempty"` // default 512+ Envs map[string]string `json:"envs,omitempty"`+ NetworkEnabled bool `json:"networkEnabled,omitempty"`+}++// SandboxListResponse is the response for listing sandboxes.+type SandboxListResponse struct {+ Sandboxes []Sandbox `json:"sandboxes"`+}++// TimeoutRequest is the request body for updating sandbox timeout.+type TimeoutRequest struct {+ Timeout int `json:"timeout"` // seconds+}diff --git a/pkg/types/template.go b/pkg/types/template.gonew file mode 100644index 00000000..4b59cd7f--- /dev/null+++ b/pkg/types/template.go@@ -0,0 +1,21 @@+package types++import "time"++// Template represents a sandbox template (a container image).+type Template struct {+ ID string `json:"templateID"`+ Name string `json:"name"`+ Tag string `json:"tag,omitempty"`+ ImageID string `json:"imageID,omitempty"`+ BuildID string `json:"buildID,omitempty"`+ Status string `json:"status"` // "ready", "building", "error"+ CreatedAt time.Time `json:"createdAt"`+}++// TemplateBuildRequest is the request body for building a template.+type TemplateBuildRequest struct {+ Dockerfile string `json:"dockerfile"`+ Name string `json:"name"`+ Tag string `json:"tag,omitempty"`+}diff --git a/proto/worker/worker.proto b/proto/worker/worker.protonew file mode 100644index 00000000..696dd79f--- /dev/null+++ b/proto/worker/worker.proto@@ -0,0 +1,146 @@+syntax = "proto3";++package worker;++option go_package = "github.com/opensandbox/opensandbox/proto/worker";++service SandboxWorker {+ rpc CreateSandbox(CreateSandboxRequest) returns (CreateSandboxResponse);+ rpc DestroySandbox(DestroySandboxRequest) returns (DestroySandboxResponse);+ rpc GetSandbox(GetSandboxRequest) returns (GetSandboxResponse);+ rpc ListSandboxes(ListSandboxesRequest) returns (ListSandboxesResponse);++ rpc ExecCommand(ExecCommandRequest) returns (ExecCommandResponse);+ rpc ExecCommandStream(ExecCommandRequest) returns (stream ExecOutputChunk);++ rpc ReadFile(ReadFileRequest) returns (ReadFileResponse);+ rpc WriteFile(WriteFileRequest) returns (WriteFileResponse);+ rpc ListDir(ListDirRequest) returns (ListDirResponse);++ rpc CreatePTY(CreatePTYRequest) returns (CreatePTYResponse);+ rpc PTYStream(stream PTYInput) returns (stream PTYOutput);+}++message CreateSandboxRequest {+ string template = 1;+ int32 timeout = 2;+ map<string, string> envs = 3;+ int32 memory_mb = 4;+ int32 cpu_count = 5;+ bool network_enabled = 6;+}++message CreateSandboxResponse {+ string sandbox_id = 1;+ string status = 2;+}++message DestroySandboxRequest {+ string sandbox_id = 1;+}++message DestroySandboxResponse {}++message GetSandboxRequest {+ string sandbox_id = 1;+}++message GetSandboxResponse {+ string sandbox_id = 1;+ string status = 2;+ string template = 3;+ int64 started_at = 4;+ int64 end_at = 5;+}++message ListSandboxesRequest {}++message ListSandboxesResponse {+ repeated GetSandboxResponse sandboxes = 1;+}++message ExecCommandRequest {+ string sandbox_id = 1;+ string command = 2;+ repeated string args = 3;+ map<string, string> envs = 4;+ string cwd = 5;+ int32 timeout = 6;+}++message ExecCommandResponse {+ int32 exit_code = 1;+ string stdout = 2;+ string stderr = 3;+}++message ExecOutputChunk {+ enum Stream {+ STDOUT = 0;+ STDERR = 1;+ }+ Stream stream = 1;+ bytes data = 2;+}++message ReadFileRequest {+ string sandbox_id = 1;+ string path = 2;+}++message ReadFileResponse {+ bytes content = 1;+}++message WriteFileRequest {+ string sandbox_id = 1;+ string path = 2;+ bytes content = 3;+}++message WriteFileResponse {}++message ListDirRequest {+ string sandbox_id = 1;+ string path = 2;+}++message DirEntry {+ string name = 1;+ bool is_dir = 2;+ int64 size = 3;+ string path = 4;+}++message ListDirResponse {+ repeated DirEntry entries = 1;+}++message CreatePTYRequest {+ string sandbox_id = 1;+ int32 cols = 2;+ int32 rows = 3;+ string shell = 4;+}++message CreatePTYResponse {+ string session_id = 1;+}++message PTYInput {+ string session_id = 1;+ oneof input {+ bytes data = 2;+ PTYResize resize = 3;+ }+}++message PTYResize {+ int32 cols = 1;+ int32 rows = 2;+}++message PTYOutput {+ string session_id = 1;+ bytes data = 2;+}diff --git a/sdks/python/opensandbox/__init__.py b/sdks/python/opensandbox/__init__.pynew file mode 100644index 00000000..69135aef--- /dev/null+++ b/sdks/python/opensandbox/__init__.py@@ -0,0 +1,19 @@+"""OpenSandbox Python SDK - E2B-compatible sandbox platform."""++from opensandbox.sandbox import Sandbox+from opensandbox.filesystem import Filesystem+from opensandbox.commands import Commands, ProcessResult+from opensandbox.pty import Pty, PtySession+from opensandbox.template import Template++__all__ = [+ "Sandbox",+ "Filesystem",+ "Commands",+ "ProcessResult",+ "Pty",+ "PtySession",+ "Template",+]++__version__ = "0.1.0"diff --git a/sdks/python/opensandbox/commands.py b/sdks/python/opensandbox/commands.pynew file mode 100644index 00000000..4ccdd998--- /dev/null+++ b/sdks/python/opensandbox/commands.py@@ -0,0 +1,56 @@+"""Command execution inside a sandbox."""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++import httpx+++@dataclass+class ProcessResult:+ """Result of a command execution."""++ exit_code: int+ stdout: str+ stderr: str+++@dataclass+class Commands:+ """Command execution for a sandbox."""++ _client: httpx.AsyncClient+ _sandbox_id: str++ async def run(+ self,+ command: str,+ timeout: int = 60,+ env: dict[str, str] | None = None,+ cwd: str | None = None,+ ) -> ProcessResult:+ """Run a command and wait for completion."""+ body: dict[str, Any] = {+ "cmd": command,+ "timeout": timeout,+ }+ if env:+ body["envs"] = env+ if cwd:+ body["cwd"] = cwd++ resp = await self._client.post(+ f"/sandboxes/{self._sandbox_id}/commands",+ json=body,+ timeout=timeout + 5,+ )+ resp.raise_for_status()+ data = resp.json()++ return ProcessResult(+ exit_code=data.get("exitCode", -1),+ stdout=data.get("stdout", ""),+ stderr=data.get("stderr", ""),+ )diff --git a/sdks/python/opensandbox/filesystem.py b/sdks/python/opensandbox/filesystem.pynew file mode 100644index 00000000..b4451a46--- /dev/null+++ b/sdks/python/opensandbox/filesystem.py@@ -0,0 +1,100 @@+"""Filesystem operations inside a sandbox."""++from __future__ import annotations++from dataclasses import dataclass++import httpx+++@dataclass+class EntryInfo:+ """File or directory entry."""++ name: str+ is_dir: bool+ path: str+ size: int = 0+++@dataclass+class Filesystem:+ """Filesystem operations for a sandbox."""++ _client: httpx.AsyncClient+ _sandbox_id: str++ async def read(self, path: str) -> str:+ """Read a file as text."""+ resp = await self._client.get(+ f"/sandboxes/{self._sandbox_id}/files",+ params={"path": path},+ )+ resp.raise_for_status()+ return resp.text++ async def read_bytes(self, path: str) -> bytes:+ """Read a file as bytes."""+ resp = await self._client.get(+ f"/sandboxes/{self._sandbox_id}/files",+ params={"path": path},+ )+ resp.raise_for_status()+ return resp.content++ async def write(self, path: str, content: str | bytes) -> None:+ """Write content to a file."""+ data = content if isinstance(content, bytes) else content.encode()+ resp = await self._client.put(+ f"/sandboxes/{self._sandbox_id}/files",+ params={"path": path},+ content=data,+ )+ resp.raise_for_status()++ async def list(self, path: str = "/") -> list[EntryInfo]:+ """List directory contents."""+ resp = await self._client.get(+ f"/sandboxes/{self._sandbox_id}/files/list",+ params={"path": path},+ )+ resp.raise_for_status()+ data = resp.json()+ if data is None:+ return []+ return [+ EntryInfo(+ name=entry["name"],+ is_dir=entry.get("isDir", False),+ path=entry.get("path", ""),+ size=entry.get("size", 0),+ )+ for entry in data+ ]++ async def make_dir(self, path: str) -> None:+ """Create a directory (and parents)."""+ resp = await self._client.post(+ f"/sandboxes/{self._sandbox_id}/files/mkdir",+ params={"path": path},+ )+ resp.raise_for_status()++ async def remove(self, path: str) -> None:+ """Remove a file or directory."""+ resp = await self._client.delete(+ f"/sandboxes/{self._sandbox_id}/files",+ params={"path": path},+ )+ resp.raise_for_status()++ async def exists(self, path: str) -> bool:+ """Check if a path exists."""+ try:+ resp = await self._client.get(+ f"/sandboxes/{self._sandbox_id}/files",+ params={"path": path},+ )+ return resp.status_code == 200+ except httpx.HTTPError:+ return Falsediff --git a/sdks/python/opensandbox/pty.py b/sdks/python/opensandbox/pty.pynew file mode 100644index 00000000..99c2d387--- /dev/null+++ b/sdks/python/opensandbox/pty.py@@ -0,0 +1,96 @@+"""PTY terminal sessions inside a sandbox."""++from __future__ import annotations++import asyncio+from dataclasses import dataclass+from typing import Callable++import httpx+import websockets+++@dataclass+class PtySession:+ """An active PTY terminal session."""++ session_id: str+ sandbox_id: str+ _ws: websockets.WebSocketClientProtocol | None = None+ _read_task: asyncio.Task | None = None++ async def send(self, data: str | bytes) -> None:+ """Send input to the terminal."""+ if self._ws is None:+ raise RuntimeError("PTY session not connected")+ payload = data if isinstance(data, bytes) else data.encode()+ await self._ws.send(payload)++ async def recv(self) -> bytes:+ """Receive output from the terminal."""+ if self._ws is None:+ raise RuntimeError("PTY session not connected")+ data = await self._ws.recv()+ return data if isinstance(data, bytes) else data.encode()++ async def close(self) -> None:+ """Close the PTY session."""+ if self._read_task and not self._read_task.done():+ self._read_task.cancel()+ if self._ws:+ await self._ws.close()+++@dataclass+class Pty:+ """PTY terminal session manager for a sandbox."""++ _client: httpx.AsyncClient+ _sandbox_id: str+ _api_url: str+ _api_key: str++ async def create(+ self,+ cols: int = 80,+ rows: int = 24,+ on_output: Callable[[bytes], None] | None = None,+ ) -> PtySession:+ """Create a new PTY session and connect via WebSocket."""+ # Create session via REST+ resp = await self._client.post(+ f"/sandboxes/{self._sandbox_id}/pty",+ json={"cols": cols, "rows": rows},+ )+ resp.raise_for_status()+ data = resp.json()+ session_id = data["sessionID"]++ # Connect via WebSocket+ ws_url = self._api_url.replace("http://", "ws://").replace("https://", "wss://")+ ws_url = f"{ws_url}/sandboxes/{self._sandbox_id}/pty/{session_id}"++ headers = {}+ if self._api_key:+ headers["X-API-Key"] = self._api_key++ ws = await websockets.connect(ws_url, additional_headers=headers)++ session = PtySession(+ session_id=session_id,+ sandbox_id=self._sandbox_id,+ _ws=ws,+ )++ if on_output:+ async def _reader() -> None:+ try:+ async for msg in ws:+ output = msg if isinstance(msg, bytes) else msg.encode()+ on_output(output)+ except websockets.ConnectionClosed:+ pass++ session._read_task = asyncio.create_task(_reader())++ return sessiondiff --git a/sdks/python/opensandbox/sandbox.py b/sdks/python/opensandbox/sandbox.pynew file mode 100644index 00000000..31b3c61b--- /dev/null+++ b/sdks/python/opensandbox/sandbox.py@@ -0,0 +1,148 @@+"""Sandbox class - main entry point for the OpenSandbox SDK."""++from __future__ import annotations++import os+from dataclasses import dataclass, field+from typing import Any++import httpx++from opensandbox.commands import Commands+from opensandbox.filesystem import Filesystem+from opensandbox.pty import Pty+++@dataclass+class Sandbox:+ """E2B-compatible sandbox interface."""++ sandbox_id: str+ status: str = "running"+ template: str = ""+ _api_url: str = ""+ _api_key: str = ""+ _client: httpx.AsyncClient = field(default=None, repr=False)++ @classmethod+ async def create(+ cls,+ template: str = "base",+ timeout: int = 300,+ api_key: str | None = None,+ api_url: str | None = None,+ envs: dict[str, str] | None = None,+ metadata: dict[str, str] | None = None,+ ) -> Sandbox:+ """Create a new sandbox instance."""+ url = api_url or os.environ.get("OPENSANDBOX_API_URL", "http://localhost:8080")+ key = api_key or os.environ.get("OPENSANDBOX_API_KEY", "")++ headers = {}+ if key:+ headers["X-API-Key"] = key++ client = httpx.AsyncClient(base_url=url, headers=headers, timeout=30.0)++ body: dict[str, Any] = {+ "templateID": template,+ "timeout": timeout,+ }+ if envs:+ body["envs"] = envs+ if metadata:+ body["metadata"] = metadata++ resp = await client.post("/sandboxes", json=body)+ resp.raise_for_status()+ data = resp.json()++ return cls(+ sandbox_id=data["sandboxID"],+ status=data.get("status", "running"),+ template=template,+ _api_url=url,+ _api_key=key,+ _client=client,+ )++ @classmethod+ async def connect(+ cls,+ sandbox_id: str,+ api_key: str | None = None,+ api_url: str | None = None,+ ) -> Sandbox:+ """Connect to an existing sandbox."""+ url = api_url or os.environ.get("OPENSANDBOX_API_URL", "http://localhost:8080")+ key = api_key or os.environ.get("OPENSANDBOX_API_KEY", "")++ headers = {}+ if key:+ headers["X-API-Key"] = key++ client = httpx.AsyncClient(base_url=url, headers=headers, timeout=30.0)++ resp = await client.get(f"/sandboxes/{sandbox_id}")+ resp.raise_for_status()+ data = resp.json()++ return cls(+ sandbox_id=sandbox_id,+ status=data.get("status", "running"),+ template=data.get("templateID", ""),+ _api_url=url,+ _api_key=key,+ _client=client,+ )++ async def kill(self) -> None:+ """Kill and remove the sandbox."""+ resp = await self._client.delete(f"/sandboxes/{self.sandbox_id}")+ resp.raise_for_status()+ self.status = "stopped"++ async def is_running(self) -> bool:+ """Check if the sandbox is still running."""+ try:+ resp = await self._client.get(f"/sandboxes/{self.sandbox_id}")+ resp.raise_for_status()+ data = resp.json()+ self.status = data.get("status", "stopped")+ return self.status == "running"+ except httpx.HTTPStatusError:+ return False++ async def set_timeout(self, timeout: int) -> None:+ """Update the sandbox timeout in seconds."""+ resp = await self._client.post(+ f"/sandboxes/{self.sandbox_id}/timeout",+ json={"timeout": timeout},+ )+ resp.raise_for_status()++ @property+ def files(self) -> Filesystem:+ """Access filesystem operations."""+ return Filesystem(self._client, self.sandbox_id)++ @property+ def commands(self) -> Commands:+ """Access command execution."""+ return Commands(self._client, self.sandbox_id)++ @property+ def pty(self) -> Pty:+ """Access PTY terminal sessions."""+ return Pty(self._client, self.sandbox_id, self._api_url, self._api_key)++ async def close(self) -> None:+ """Close the HTTP client (does not kill the sandbox)."""+ await self._client.aclose()++ async def __aenter__(self) -> Sandbox:+ return self++ async def __aexit__(self, *args: object) -> None:+ await self.kill()+ await self.close()diff --git a/sdks/python/opensandbox/template.py b/sdks/python/opensandbox/template.pynew file mode 100644index 00000000..7c026e14--- /dev/null+++ b/sdks/python/opensandbox/template.py@@ -0,0 +1,75 @@+"""Template management for custom sandbox environments."""++from __future__ import annotations++from dataclasses import dataclass++import httpx+++@dataclass+class TemplateInfo:+ """Template metadata."""++ template_id: str+ name: str+ tag: str+ status: str+++@dataclass+class Template:+ """Template management operations."""++ _client: httpx.AsyncClient++ @classmethod+ def _from_client(cls, client: httpx.AsyncClient) -> Template:+ return cls(_client=client)++ async def build(self, name: str, dockerfile: str) -> TemplateInfo:+ """Build a new template from a Dockerfile."""+ resp = await self._client.post(+ "/templates",+ json={"name": name, "dockerfile": dockerfile},+ timeout=300.0,+ )+ resp.raise_for_status()+ data = resp.json()+ return TemplateInfo(+ template_id=data["templateID"],+ name=data["name"],+ tag=data.get("tag", "latest"),+ status=data.get("status", "ready"),+ )++ async def list(self) -> list[TemplateInfo]:+ """List all available templates."""+ resp = await self._client.get("/templates")+ resp.raise_for_status()+ return [+ TemplateInfo(+ template_id=t["templateID"],+ name=t["name"],+ tag=t.get("tag", "latest"),+ status=t.get("status", "ready"),+ )+ for t in resp.json()+ ]++ async def get(self, name: str) -> TemplateInfo:+ """Get template details by name."""+ resp = await self._client.get(f"/templates/{name}")+ resp.raise_for_status()+ data = resp.json()+ return TemplateInfo(+ template_id=data["templateID"],+ name=data["name"],+ tag=data.get("tag", "latest"),+ status=data.get("status", "ready"),+ )++ async def delete(self, name: str) -> None:+ """Delete a template."""+ resp = await self._client.delete(f"/templates/{name}")+ resp.raise_for_status()diff --git a/sdks/python/pyproject.toml b/sdks/python/pyproject.tomlnew file mode 100644index 00000000..fb5527a0--- /dev/null+++ b/sdks/python/pyproject.toml@@ -0,0 +1,21 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[project]+name = "opensandbox"+version = "0.1.0"+description = "Python SDK for OpenSandbox - E2B-compatible sandbox platform"+readme = "README.md"+requires-python = ">=3.10"+license = "MIT"+dependencies = [+ "httpx>=0.27.0",+ "websockets>=12.0",+]++[project.optional-dependencies]+dev = [+ "pytest>=8.0",+ "pytest-asyncio>=0.23",+]diff --git a/sdks/typescript/package.json b/sdks/typescript/package.jsonnew file mode 100644index 00000000..08cfe15b--- /dev/null+++ b/sdks/typescript/package.json@@ -0,0 +1,18 @@+{+ "name": "opensandbox",+ "version": "0.1.0",+ "description": "TypeScript SDK for OpenSandbox - E2B-compatible sandbox platform",+ "main": "dist/index.js",+ "types": "dist/index.d.ts",+ "files": ["dist"],+ "scripts": {+ "build": "tsc",+ "test": "vitest run",+ "lint": "tsc --noEmit"+ },+ "license": "MIT",+ "devDependencies": {+ "typescript": "^5.4.0",+ "vitest": "^1.6.0"+ }+}diff --git a/sdks/typescript/src/commands.ts b/sdks/typescript/src/commands.tsnew file mode 100644index 00000000..d1567af6--- /dev/null+++ b/sdks/typescript/src/commands.ts@@ -0,0 +1,57 @@+export interface ProcessResult {+ exitCode: number;+ stdout: string;+ stderr: string;+}++export interface RunOpts {+ timeout?: number;+ env?: Record<string, string>;+ cwd?: string;+}++export class Commands {+ constructor(+ private apiUrl: string,+ private apiKey: string,+ private sandboxId: string,+ ) {}++ private get headers(): Record<string, string> {+ const h: Record<string, string> = { "Content-Type": "application/json" };+ if (this.apiKey) h["X-API-Key"] = this.apiKey;+ return h;+ }++ async run(command: string, opts: RunOpts = {}): Promise<ProcessResult> {+ const timeout = opts.timeout ?? 60;++ const body: Record<string, unknown> = {+ cmd: command,+ timeout,+ };+ if (opts.env) body.envs = opts.env;+ if (opts.cwd) body.cwd = opts.cwd;++ const controller = new AbortController();+ const timeoutId = globalThis.setTimeout(() => controller.abort(), (timeout + 5) * 1000);++ try {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/commands`, {+ method: "POST",+ headers: this.headers,+ body: JSON.stringify(body),+ signal: controller.signal,+ });++ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Command failed: ${resp.status} ${text}`);+ }++ return await resp.json();+ } finally {+ globalThis.clearTimeout(timeoutId);+ }+ }+}diff --git a/sdks/typescript/src/filesystem.ts b/sdks/typescript/src/filesystem.tsnew file mode 100644index 00000000..e24ee40b--- /dev/null+++ b/sdks/typescript/src/filesystem.ts@@ -0,0 +1,86 @@+export interface EntryInfo {+ name: string;+ isDir: boolean;+ path: string;+ size: number;+}++export class Filesystem {+ constructor(+ private apiUrl: string,+ private apiKey: string,+ private sandboxId: string,+ ) {}++ private get headers(): Record<string, string> {+ return this.apiKey ? { "X-API-Key": this.apiKey } : {};+ }++ async read(path: string): Promise<string> {+ const resp = await fetch(+ `${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`,+ { headers: this.headers },+ );+ if (!resp.ok) throw new Error(`Failed to read ${path}: ${resp.status}`);+ return resp.text();+ }++ async readBytes(path: string): Promise<Uint8Array> {+ const resp = await fetch(+ `${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`,+ { headers: this.headers },+ );+ if (!resp.ok) throw new Error(`Failed to read ${path}: ${resp.status}`);+ return new Uint8Array(await resp.arrayBuffer());+ }++ async write(path: string, content: string | Uint8Array): Promise<void> {+ const resp = await fetch(+ `${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`,+ {+ method: "PUT",+ headers: this.headers,+ body: content,+ },+ );+ if (!resp.ok) throw new Error(`Failed to write ${path}: ${resp.status}`);+ }++ async list(path: string = "/"): Promise<EntryInfo[]> {+ const resp = await fetch(+ `${this.apiUrl}/sandboxes/${this.sandboxId}/files/list?path=${encodeURIComponent(path)}`,+ { headers: this.headers },+ );+ if (!resp.ok) throw new Error(`Failed to list ${path}: ${resp.status}`);+ const data = await resp.json();+ return data ?? [];+ }++ async makeDir(path: string): Promise<void> {+ const resp = await fetch(+ `${this.apiUrl}/sandboxes/${this.sandboxId}/files/mkdir?path=${encodeURIComponent(path)}`,+ { method: "POST", headers: this.headers },+ );+ if (!resp.ok) throw new Error(`Failed to mkdir ${path}: ${resp.status}`);+ }++ async remove(path: string): Promise<void> {+ const resp = await fetch(+ `${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`,+ { method: "DELETE", headers: this.headers },+ );+ if (!resp.ok) throw new Error(`Failed to remove ${path}: ${resp.status}`);+ }++ async exists(path: string): Promise<boolean> {+ try {+ const resp = await fetch(+ `${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`,+ { headers: this.headers },+ );+ return resp.ok;+ } catch {+ return false;+ }+ }+}diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.tsnew file mode 100644index 00000000..99f955fc--- /dev/null+++ b/sdks/typescript/src/index.ts@@ -0,0 +1,5 @@+export { Sandbox, type SandboxOpts } from "./sandbox";+export { Filesystem, type EntryInfo } from "./filesystem";+export { Commands, type ProcessResult, type RunOpts } from "./commands";+export { Pty, type PtySession, type PtyOpts } from "./pty";+export { Templates, type TemplateInfo } from "./template";diff --git a/sdks/typescript/src/pty.ts b/sdks/typescript/src/pty.tsnew file mode 100644index 00000000..b18e92a6--- /dev/null+++ b/sdks/typescript/src/pty.ts@@ -0,0 +1,77 @@+export interface PtyOpts {+ cols?: number;+ rows?: number;+ onOutput?: (data: Uint8Array) => void;+}++export interface PtySession {+ sessionId: string;+ send(data: string | Uint8Array): void;+ close(): void;+}++export class Pty {+ constructor(+ private apiUrl: string,+ private apiKey: string,+ private sandboxId: string,+ ) {}++ private get headers(): Record<string, string> {+ const h: Record<string, string> = { "Content-Type": "application/json" };+ if (this.apiKey) h["X-API-Key"] = this.apiKey;+ return h;+ }++ async create(opts: PtyOpts = {}): Promise<PtySession> {+ // Create session via REST+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/pty`, {+ method: "POST",+ headers: this.headers,+ body: JSON.stringify({+ cols: opts.cols ?? 80,+ rows: opts.rows ?? 24,+ }),+ });++ if (!resp.ok) {+ throw new Error(`Failed to create PTY: ${resp.status}`);+ }++ const data = await resp.json();+ const sessionId: string = data.sessionID;++ // Connect via WebSocket+ const wsUrl = this.apiUrl+ .replace("http://", "ws://")+ .replace("https://", "wss://");+ const wsEndpoint = `${wsUrl}/sandboxes/${this.sandboxId}/pty/${sessionId}`;++ const ws = new WebSocket(wsEndpoint);+ ws.binaryType = "arraybuffer";++ if (opts.onOutput) {+ const onOutput = opts.onOutput;+ ws.onmessage = (event) => {+ const data = event.data instanceof ArrayBuffer+ ? new Uint8Array(event.data)+ : new TextEncoder().encode(event.data as string);+ onOutput(data);+ };+ }++ return {+ sessionId,+ send(data: string | Uint8Array): void {+ if (typeof data === "string") {+ ws.send(data);+ } else {+ ws.send(data);+ }+ },+ close(): void {+ ws.close();+ },+ };+ }+}diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.tsnew file mode 100644index 00000000..81c3e386--- /dev/null+++ b/sdks/typescript/src/sandbox.ts@@ -0,0 +1,129 @@+import { Filesystem } from "./filesystem";+import { Commands } from "./commands";+import { Pty } from "./pty";++export interface SandboxOpts {+ template?: string;+ timeout?: number;+ apiKey?: string;+ apiUrl?: string;+ envs?: Record<string, string>;+ metadata?: Record<string, string>;+}++interface SandboxData {+ sandboxID: string;+ status: string;+ templateID?: string;+}++export class Sandbox {+ readonly sandboxId: string;+ readonly files: Filesystem;+ readonly commands: Commands;+ readonly pty: Pty;++ private apiUrl: string;+ private apiKey: string;+ private _status: string;++ private constructor(data: SandboxData, apiUrl: string, apiKey: string) {+ this.sandboxId = data.sandboxID;+ this._status = data.status;+ this.apiUrl = apiUrl;+ this.apiKey = apiKey;+ this.files = new Filesystem(apiUrl, apiKey, this.sandboxId);+ this.commands = new Commands(apiUrl, apiKey, this.sandboxId);+ this.pty = new Pty(apiUrl, apiKey, this.sandboxId);+ }++ get status(): string {+ return this._status;+ }++ static async create(opts: SandboxOpts = {}): Promise<Sandbox> {+ const apiUrl = opts.apiUrl ?? process.env.OPENSANDBOX_API_URL ?? "http://localhost:8080";+ const apiKey = opts.apiKey ?? process.env.OPENSANDBOX_API_KEY ?? "";++ const body: Record<string, unknown> = {+ templateID: opts.template ?? "base",+ timeout: opts.timeout ?? 300,+ };+ if (opts.envs) body.envs = opts.envs;+ if (opts.metadata) body.metadata = opts.metadata;++ const resp = await fetch(`${apiUrl}/sandboxes`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(apiKey ? { "X-API-Key": apiKey } : {}),+ },+ body: JSON.stringify(body),+ });++ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to create sandbox: ${resp.status} ${text}`);+ }++ const data: SandboxData = await resp.json();+ return new Sandbox(data, apiUrl, apiKey);+ }++ static async connect(sandboxId: string, opts: Pick<SandboxOpts, "apiKey" | "apiUrl"> = {}): Promise<Sandbox> {+ const apiUrl = opts.apiUrl ?? process.env.OPENSANDBOX_API_URL ?? "http://localhost:8080";+ const apiKey = opts.apiKey ?? process.env.OPENSANDBOX_API_KEY ?? "";++ const resp = await fetch(`${apiUrl}/sandboxes/${sandboxId}`, {+ headers: apiKey ? { "X-API-Key": apiKey } : {},+ });++ if (!resp.ok) {+ throw new Error(`Failed to connect to sandbox ${sandboxId}: ${resp.status}`);+ }++ const data: SandboxData = await resp.json();+ return new Sandbox(data, apiUrl, apiKey);+ }++ async kill(): Promise<void> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}`, {+ method: "DELETE",+ headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},+ });++ if (!resp.ok) {+ throw new Error(`Failed to kill sandbox: ${resp.status}`);+ }+ this._status = "stopped";+ }++ async isRunning(): Promise<boolean> {+ try {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}`, {+ headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},+ });+ if (!resp.ok) return false;+ const data: SandboxData = await resp.json();+ this._status = data.status;+ return data.status === "running";+ } catch {+ return false;+ }+ }++ async setTimeout(timeout: number): Promise<void> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/timeout`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),+ },+ body: JSON.stringify({ timeout }),+ });++ if (!resp.ok) {+ throw new Error(`Failed to set timeout: ${resp.status}`);+ }+ }+}diff --git a/sdks/typescript/src/template.ts b/sdks/typescript/src/template.tsnew file mode 100644index 00000000..a38b1f25--- /dev/null+++ b/sdks/typescript/src/template.ts@@ -0,0 +1,68 @@+export interface TemplateInfo {+ templateID: string;+ name: string;+ tag: string;+ status: string;+}++export class Templates {+ constructor(+ private apiUrl: string,+ private apiKey: string,+ ) {}++ private get headers(): Record<string, string> {+ const h: Record<string, string> = { "Content-Type": "application/json" };+ if (this.apiKey) h["X-API-Key"] = this.apiKey;+ return h;+ }++ async build(name: string, dockerfile: string): Promise<TemplateInfo> {+ const resp = await fetch(`${this.apiUrl}/templates`, {+ method: "POST",+ headers: this.headers,+ body: JSON.stringify({ name, dockerfile }),+ });++ if (!resp.ok) {+ throw new Error(`Failed to build template: ${resp.status}`);+ }++ return resp.json();+ }++ async list(): Promise<TemplateInfo[]> {+ const resp = await fetch(`${this.apiUrl}/templates`, {+ headers: this.headers,+ });++ if (!resp.ok) {+ throw new Error(`Failed to list templates: ${resp.status}`);+ }++ return resp.json();+ }++ async get(name: string): Promise<TemplateInfo> {+ const resp = await fetch(`${this.apiUrl}/templates/${name}`, {+ headers: this.headers,+ });++ if (!resp.ok) {+ throw new Error(`Failed to get template: ${resp.status}`);+ }++ return resp.json();+ }++ async delete(name: string): Promise<void> {+ const resp = await fetch(`${this.apiUrl}/templates/${name}`, {+ method: "DELETE",+ headers: this.headers,+ });++ if (!resp.ok) {+ throw new Error(`Failed to delete template: ${resp.status}`);+ }+ }+}diff --git a/sdks/typescript/tsconfig.json b/sdks/typescript/tsconfig.jsonnew file mode 100644index 00000000..35f58b7d--- /dev/null+++ b/sdks/typescript/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "lib": ["ES2022", "DOM"],+ "outDir": "dist",+ "rootDir": "src",+ "declaration": true,+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true+ },+ "include": ["src"],+ "exclude": ["node_modules", "dist", "tests"]+}