An open-source, faster Devin alternative
TypeScript
adjust tests, scripts, fixes
Brian Reardon8e65a3eab62b
diff --git a/deploy/azure/create-opencomputer-prod.sh b/deploy/azure/create-opencomputer-prod.shnew file mode 100755index 00000000..0366ca37--- /dev/null+++ b/deploy/azure/create-opencomputer-prod.sh@@ -0,0 +1,503 @@+#!/usr/bin/env bash+# create-opencomputer-prod.sh — Create OpenComputer production stack on Azure (East US 2)+#+# Creates:+# 1. Resource group, VNet, NSGs+# 2. Managed Azure PostgreSQL Flexible Server+# 3. Managed Azure Cache for Redis+# 4. Storage account (S3-compatible blob for checkpoints)+# 5. Control plane VM (server)+# 6. Worker VM (D64d_v5 — 64 vCPU, 256GB RAM, QEMU/KVM with nested virt)+#+# Prerequisites:+# - az CLI installed and logged in (brew install azure-cli && az login)+# - SSH key at ~/.ssh/opensandbox-digger.pem+#+# Usage:+# bash deploy/azure/create-opencomputer-prod.sh create # provision everything+# bash deploy/azure/create-opencomputer-prod.sh deploy # build + deploy binaries+# bash deploy/azure/create-opencomputer-prod.sh status # show IPs and status+# bash deploy/azure/create-opencomputer-prod.sh ssh-cp # SSH to control plane+# bash deploy/azure/create-opencomputer-prod.sh ssh-wk # SSH to worker+# bash deploy/azure/create-opencomputer-prod.sh destroy # tear down everything++set -euo pipefail++# ── Configuration ──+REGION="eastus2"+RG="opencomputer-prod"+VNET="oc-vnet"+SUBNET="oc-subnet"+NSG_CP="oc-nsg-controlplane"+NSG_WK="oc-nsg-worker"+CP_VM="oc-controlplane"+WK_VM="oc-worker-1"+CP_SIZE="Standard_D2s_v5" # 2 vCPU, 8GB — control plane+WK_SIZE="Standard_D64d_v5" # 64 vCPU, 256GB RAM, 2400GB temp NVMe+WK_DISK_SIZE=512 # GB Premium SSD for /data (persistent)+STORAGE_CONTAINER="checkpoints"+SSH_KEY="$HOME/.ssh/opensandbox-digger.pem"+SSH_PUB=$(ssh-keygen -y -f "$SSH_KEY" 2>/dev/null)+ADMIN_USER="azureuser"+DOMAIN="opencomputer.dev"++STATE_FILE="$HOME/.opencomputer-prod-state"+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"++log() { echo "[opencomputer] $*"; }+err() { echo "[opencomputer] ERROR: $*" >&2; exit 1; }++save_state() {+ if [ -f "$STATE_FILE" ] && grep -q "^$1=" "$STATE_FILE" 2>/dev/null; then+ sed -i.bak "s|^$1=.*|$1=$2|" "$STATE_FILE"+ rm -f "${STATE_FILE}.bak"+ else+ echo "$1=$2" >> "$STATE_FILE"+ fi+}+load_state() {+ if [ -f "$STATE_FILE" ]; then+ source "$STATE_FILE"+ fi+}++# ── Create ──+cmd_create() {+ log "Creating OpenComputer production stack in $REGION..."++ # Generate secrets upfront+ API_KEY="osb_$(openssl rand -hex 32)"+ JWT_SECRET=$(openssl rand -hex 32)+ PG_PASSWORD="pg$(openssl rand -hex 16)"+ save_state "API_KEY" "$API_KEY"+ save_state "JWT_SECRET" "$JWT_SECRET"+ save_state "PG_PASSWORD" "$PG_PASSWORD"++ # ── Resource group ──+ log "Creating resource group $RG..."+ az group create --name "$RG" --location "$REGION" -o none++ # ── VNet + subnets ──+ log "Creating VNet..."+ az network vnet create \+ --resource-group "$RG" \+ --name "$VNET" \+ --address-prefix 10.200.0.0/16 \+ --subnet-name "$SUBNET" \+ --subnet-prefix 10.200.1.0/24 \+ -o none++ # ── NSGs ──+ log "Creating control plane NSG..."+ az network nsg create --resource-group "$RG" --name "$NSG_CP" -o none+ PRIO=100+ for port_name in "SSH:22" "API:8080" "HTTPS:443"; do+ name="${port_name%%:*}"+ port="${port_name##*:}"+ az network nsg rule create \+ --resource-group "$RG" --nsg-name "$NSG_CP" \+ --name "Allow${name}" --priority $PRIO \+ --destination-port-ranges "$port" --protocol Tcp \+ --access Allow --direction Inbound -o none+ PRIO=$((PRIO + 10))+ done+ # gRPC from VNet only+ az network nsg rule create \+ --resource-group "$RG" --nsg-name "$NSG_CP" \+ --name "AllowgRPCFromVNet" --priority 200 \+ --destination-port-ranges 9090 --protocol Tcp \+ --source-address-prefixes "10.200.0.0/16" \+ --access Allow --direction Inbound -o none++ log "Creating worker NSG..."+ az network nsg create --resource-group "$RG" --name "$NSG_WK" -o none+ az network nsg rule create \+ --resource-group "$RG" --nsg-name "$NSG_WK" \+ --name "AllowSSH" --priority 100 \+ --destination-port-ranges 22 --protocol Tcp \+ --access Allow --direction Inbound -o none+ az network nsg rule create \+ --resource-group "$RG" --nsg-name "$NSG_WK" \+ --name "AllowgRPCFromVNet" --priority 200 \+ --destination-port-ranges 9090 --protocol Tcp \+ --source-address-prefixes "10.200.0.0/16" \+ --access Allow --direction Inbound -o none+ az network nsg rule create \+ --resource-group "$RG" --nsg-name "$NSG_WK" \+ --name "AllowWorkerHTTPFromVNet" --priority 300 \+ --destination-port-ranges 8081 --protocol Tcp \+ --source-address-prefixes "10.200.0.0/16" \+ --access Allow --direction Inbound -o none++ # ── Storage Account ──+ log "Creating storage account..."+ STORAGE_ACCOUNT_NAME="occkpt$(echo $RG | md5sum | head -c 8)"+ az storage account create \+ --resource-group "$RG" \+ --name "$STORAGE_ACCOUNT_NAME" \+ --location "$REGION" \+ --sku Standard_LRS \+ --kind StorageV2 \+ --access-tier Hot \+ -o none+ save_state "STORAGE_ACCOUNT_NAME" "$STORAGE_ACCOUNT_NAME"++ STORAGE_KEY=$(az storage account keys list \+ --resource-group "$RG" \+ --account-name "$STORAGE_ACCOUNT_NAME" \+ --query "[0].value" -o tsv)+ save_state "STORAGE_KEY" "$STORAGE_KEY"++ az storage container create \+ --name "$STORAGE_CONTAINER" \+ --account-name "$STORAGE_ACCOUNT_NAME" \+ --account-key "$STORAGE_KEY" \+ -o none 2>/dev/null || true++ # ── Control Plane VM ──+ log "Creating control plane VM ($CP_SIZE)..."+ az vm create \+ --resource-group "$RG" \+ --name "$CP_VM" \+ --size "$CP_SIZE" \+ --image Canonical:ubuntu-24_04-lts:server:latest \+ --admin-username "$ADMIN_USER" \+ --ssh-key-values "$SSH_PUB" \+ --vnet-name "$VNET" --subnet "$SUBNET" \+ --nsg "$NSG_CP" \+ --public-ip-address "${CP_VM}-ip" \+ --public-ip-sku Standard \+ --os-disk-size-gb 64 \+ --storage-sku Premium_LRS \+ -o none++ CP_PUBLIC_IP=$(az vm show -d --resource-group "$RG" --name "$CP_VM" --query publicIps -o tsv)+ CP_PRIVATE_IP=$(az vm show -d --resource-group "$RG" --name "$CP_VM" --query privateIps -o tsv)+ save_state "CP_PUBLIC_IP" "$CP_PUBLIC_IP"+ save_state "CP_PRIVATE_IP" "$CP_PRIVATE_IP"+ log "Control plane: public=$CP_PUBLIC_IP private=$CP_PRIVATE_IP"++ # ── Worker VM ──+ log "Creating worker VM ($WK_SIZE)..."+ az vm create \+ --resource-group "$RG" \+ --name "$WK_VM" \+ --size "$WK_SIZE" \+ --image Canonical:ubuntu-24_04-lts:server:latest \+ --admin-username "$ADMIN_USER" \+ --ssh-key-values "$SSH_PUB" \+ --vnet-name "$VNET" --subnet "$SUBNET" \+ --nsg "$NSG_WK" \+ --public-ip-address "${WK_VM}-ip" \+ --public-ip-sku Standard \+ --os-disk-size-gb 64 \+ --storage-sku Premium_LRS \+ -o none++ # Attach persistent data disk (Premium SSD)+ log "Attaching ${WK_DISK_SIZE}GB data disk..."+ az vm disk attach \+ --resource-group "$RG" \+ --vm-name "$WK_VM" \+ --name "${WK_VM}-data" \+ --size-gb "$WK_DISK_SIZE" \+ --sku Premium_LRS \+ --new \+ -o none++ WK_PUBLIC_IP=$(az vm show -d --resource-group "$RG" --name "$WK_VM" --query publicIps -o tsv)+ WK_PRIVATE_IP=$(az vm show -d --resource-group "$RG" --name "$WK_VM" --query privateIps -o tsv)+ save_state "WK_PUBLIC_IP" "$WK_PUBLIC_IP"+ save_state "WK_PRIVATE_IP" "$WK_PRIVATE_IP"+ log "Worker: public=$WK_PUBLIC_IP private=$WK_PRIVATE_IP"++ # Open Postgres/Redis to VNet+ log "Opening Postgres/Redis ports to VNet..."+ az network nsg rule create \+ --resource-group "$RG" --nsg-name "$NSG_CP" \+ --name "AllowPostgresFromVNet" --priority 400 \+ --destination-port-ranges 5432 --protocol Tcp \+ --source-address-prefixes "10.200.0.0/16" \+ --access Allow --direction Inbound -o none+ az network nsg rule create \+ --resource-group "$RG" --nsg-name "$NSG_CP" \+ --name "AllowRedisFromVNet" --priority 500 \+ --destination-port-ranges 6379 --protocol Tcp \+ --source-address-prefixes "10.200.0.0/16" \+ --access Allow --direction Inbound -o none++ # ── Provision Control Plane ──+ log "Provisioning control plane (Docker + Postgres + Redis)..."+ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$CP_PUBLIC_IP" "bash -s" << CPSETUP+set -euo pipefail+export DEBIAN_FRONTEND=noninteractive+sudo apt-get update -qq+sudo apt-get install -y -qq docker.io jq curl+sudo systemctl enable --now docker+sudo mkdir -p /etc/opensandbox /usr/local/bin++# PostgreSQL+sudo docker run -d --name postgres \+ --restart unless-stopped \+ --shm-size=2g \+ -p 5432:5432 \+ -e POSTGRES_USER=opensandbox \+ -e POSTGRES_PASSWORD=$PG_PASSWORD \+ -e POSTGRES_DB=opensandbox \+ -v /data/postgres:/var/lib/postgresql/data \+ postgres:16 \+ postgres \+ -c shared_buffers=1GB \+ -c work_mem=32MB \+ -c effective_cache_size=4GB \+ -c random_page_cost=1.1 \+ -c synchronous_commit=off \+ -c max_connections=200++# Redis+sudo docker run -d --name redis \+ --restart unless-stopped \+ -p 6379:6379 \+ redis:7-alpine++# Wait for Postgres to be ready+for i in \$(seq 1 30); do+ sudo docker exec postgres pg_isready -U opensandbox 2>/dev/null && break+ sleep 2+done++# Configure Postgres to listen on all interfaces for VNet access+sudo docker exec postgres bash -c "echo 'host all all 10.200.0.0/16 md5' >> /var/lib/postgresql/data/pg_hba.conf"+sudo docker exec postgres mkdir -p /var/lib/postgresql/data/conf.d 2>/dev/null || true+sudo docker exec postgres bash -c "echo \"listen_addresses = '*'\" > /var/lib/postgresql/data/conf.d/listen.conf"+sudo docker restart postgres+sleep 3++echo "Control plane provisioned (Postgres + Redis running)."+CPSETUP++ # ── Provision Worker ──+ log "Provisioning worker (QEMU/KVM setup)..."+ scp -i "$SSH_KEY" -o StrictHostKeyChecking=no \+ "$SCRIPT_DIR/setup-azure-host.sh" "$ADMIN_USER@$WK_PUBLIC_IP:/tmp/setup-azure-host.sh"++ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$WK_PUBLIC_IP" "bash -s" << WKSETUP+set -euo pipefail++# Format and mount data disk+if ! mountpoint -q /data 2>/dev/null; then+ DATA_DISK=\$(lsblk -dpno NAME,TYPE | grep disk | while read d t; do+ if ! blkid "\$d" &>/dev/null && [ "\$d" != "/dev/sda" ] && [ "\$d" != "/dev/sdb" ]; then+ echo "\$d"; break+ fi+ done)+ if [ -n "\$DATA_DISK" ]; then+ echo "Formatting \$DATA_DISK as XFS with reflink..."+ sudo mkfs.xfs -m reflink=1 "\$DATA_DISK"+ sudo mkdir -p /data+ echo "\$DATA_DISK /data xfs defaults,nofail 0 2" | sudo tee -a /etc/fstab+ sudo mount /data+ fi+fi++# Also set up local NVMe temp storage if available (D64d has 2400GB)+if ls /dev/nvme*n1 2>/dev/null | head -1 | grep -q nvme; then+ NVME=\$(ls /dev/nvme*n1 2>/dev/null | head -1)+ if [ -n "\$NVME" ] && ! mountpoint -q /data/sandboxes 2>/dev/null; then+ echo "Formatting NVMe \$NVME as XFS with reflink for sandbox data..."+ sudo mkfs.xfs -m reflink=1 -f "\$NVME"+ sudo mkdir -p /data/sandboxes+ echo "\$NVME /data/sandboxes xfs defaults,nofail 0 2" | sudo tee -a /etc/fstab+ sudo mount /data/sandboxes+ fi+fi++sudo bash /tmp/setup-azure-host.sh+WKSETUP++ # ── Write env files ──+ log "Writing environment files..."++ # Control plane env+ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$CP_PUBLIC_IP" "sudo tee /etc/opensandbox/server.env > /dev/null" << CPENV+OPENSANDBOX_MODE=server+OPENSANDBOX_PORT=8080+OPENSANDBOX_DATABASE_URL=postgres://opensandbox:${PG_PASSWORD}@localhost:5432/opensandbox?sslmode=disable+OPENSANDBOX_REDIS_URL=redis://localhost:6379+OPENSANDBOX_JWT_SECRET=$JWT_SECRET+OPENSANDBOX_API_KEY=$API_KEY+OPENSANDBOX_REGION=$REGION+OPENSANDBOX_SANDBOX_DOMAIN=workers.$DOMAIN+OPENSANDBOX_CONTROLPLANE_IP=$CP_PRIVATE_IP+OPENSANDBOX_MAX_WORKERS=4+OPENSANDBOX_MIN_WORKERS=1+CPENV++ # Worker env+ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$WK_PUBLIC_IP" "sudo tee /etc/opensandbox/worker.env > /dev/null" << WKENV+OPENSANDBOX_MODE=worker+OPENSANDBOX_VM_BACKEND=qemu+OPENSANDBOX_QEMU_BIN=qemu-system-x86_64+OPENSANDBOX_DATA_DIR=/data/sandboxes+OPENSANDBOX_KERNEL_PATH=/opt/opensandbox/vmlinux+OPENSANDBOX_IMAGES_DIR=/data/firecracker/images+OPENSANDBOX_GRPC_ADVERTISE=$WK_PRIVATE_IP:9090+OPENSANDBOX_HTTP_ADDR=http://$WK_PRIVATE_IP:8081+OPENSANDBOX_JWT_SECRET=$JWT_SECRET+OPENSANDBOX_WORKER_ID=w-oc-eastus2-1+OPENSANDBOX_REGION=$REGION+OPENSANDBOX_SANDBOX_DOMAIN=workers.$DOMAIN+OPENSANDBOX_MAX_CAPACITY=250+OPENSANDBOX_PORT=8081+OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=1024+OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2+OPENSANDBOX_DATABASE_URL=postgres://opensandbox:${PG_PASSWORD}@${CP_PRIVATE_IP}:5432/opensandbox?sslmode=disable+OPENSANDBOX_REDIS_URL=redis://${CP_PRIVATE_IP}:6379+OPENSANDBOX_S3_BUCKET=$STORAGE_CONTAINER+OPENSANDBOX_S3_REGION=$REGION+OPENSANDBOX_S3_ENDPOINT=https://${STORAGE_ACCOUNT_NAME}.blob.core.windows.net+OPENSANDBOX_S3_ACCESS_KEY_ID=$STORAGE_ACCOUNT_NAME+OPENSANDBOX_S3_SECRET_ACCESS_KEY=$STORAGE_KEY+OPENSANDBOX_MACHINE_ID=oc-worker-1+WKENV++ log ""+ log "=== Stack Created ==="+ log "Control plane: $CP_PUBLIC_IP (private: $CP_PRIVATE_IP)"+ log "Worker: $WK_PUBLIC_IP (private: $WK_PRIVATE_IP)"+ log "PostgreSQL: Docker on $CP_PRIVATE_IP:5432"+ log "Redis: Docker on $CP_PRIVATE_IP:6379"+ log "Storage: ${STORAGE_ACCOUNT_NAME}.blob.core.windows.net/$STORAGE_CONTAINER"+ log "API key: $API_KEY"+ log "Domain: $DOMAIN → point DNS A record to $CP_PUBLIC_IP"+ log ""+ log "Next: bash deploy/azure/create-opencomputer-prod.sh deploy"+}++# ── Deploy ──+cmd_deploy() {+ load_state+ log "Building and deploying binaries..."++ cd "$PROJECT_ROOT"+ VERSION=$(cat VERSION 2>/dev/null || echo "dev")+ log "Version: $VERSION"++ log "Building server (amd64)..."+ GOOS=linux GOARCH=amd64 go build -o /tmp/oc-server ./cmd/server/++ log "Building worker (amd64)..."+ GOOS=linux GOARCH=amd64 go build -ldflags="-X main.AgentVersion=$VERSION" -o /tmp/oc-worker ./cmd/worker/++ log "Building agent (amd64)..."+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-X main.Version=$VERSION" -o /tmp/oc-agent ./cmd/agent/++ # Deploy server+ log "Deploying to control plane ($CP_PUBLIC_IP)..."+ scp -i "$SSH_KEY" -o StrictHostKeyChecking=no \+ /tmp/oc-server "$ADMIN_USER@$CP_PUBLIC_IP:/tmp/opensandbox-server"+ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$CP_PUBLIC_IP" \+ 'sudo cp /tmp/opensandbox-server /usr/local/bin/ && sudo chmod +x /usr/local/bin/opensandbox-server && sudo systemctl restart opensandbox-server 2>/dev/null || true'++ # Deploy worker + agent+ log "Deploying to worker ($WK_PUBLIC_IP)..."+ scp -i "$SSH_KEY" -o StrictHostKeyChecking=no \+ /tmp/oc-worker /tmp/oc-agent \+ "$ADMIN_USER@$WK_PUBLIC_IP:/tmp/"++ # Upload rootfs build scripts+ scp -i "$SSH_KEY" -o StrictHostKeyChecking=no \+ "$PROJECT_ROOT/deploy/ec2/build-rootfs-docker.sh" \+ "$ADMIN_USER@$WK_PUBLIC_IP:/tmp/build-rootfs-docker.sh" 2>/dev/null || true+ scp -i "$SSH_KEY" -o StrictHostKeyChecking=no \+ "$PROJECT_ROOT/deploy/firecracker/rootfs/Dockerfile.default" \+ "$ADMIN_USER@$WK_PUBLIC_IP:/tmp/Dockerfile.default" 2>/dev/null || true++ ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$WK_PUBLIC_IP" << 'DEPLOY'+set -euo pipefail+sudo systemctl stop opensandbox-worker 2>/dev/null || true+sudo cp /tmp/oc-worker /usr/local/bin/opensandbox-worker+sudo cp /tmp/oc-agent /usr/local/bin/osb-agent+sudo chmod +x /usr/local/bin/opensandbox-worker /usr/local/bin/osb-agent++# Build rootfs if not exists+if [ ! -f /data/firecracker/images/default.ext4 ]; then+ echo "Building rootfs image..."+ sudo mkdir -p /data/firecracker/images+ if [ -f /tmp/build-rootfs-docker.sh ]; then+ sudo bash /tmp/build-rootfs-docker.sh /usr/local/bin/osb-agent /data/firecracker/images default+ else+ echo "WARNING: No rootfs build script — upload deploy/ec2/build-rootfs-docker.sh"+ fi+fi++# Delete golden to rebuild with new agent version+sudo rm -rf /data/sandboxes/golden++sudo systemctl restart opensandbox-worker 2>/dev/null || true+DEPLOY++ log ""+ log "=== Deployed (v$VERSION) ==="+ log "Test: curl -s http://$CP_PUBLIC_IP:8080/api/sandboxes -H 'X-API-Key: $API_KEY'"+}++# ── Status ──+cmd_status() {+ load_state+ log "=== OpenComputer Production Stack ==="+ log ""+ log "Region: $REGION"+ log "Domain: $DOMAIN"+ log ""+ log "Control Plane ($CP_SIZE):"+ log " Public: ${CP_PUBLIC_IP:-?}"+ log " Private: ${CP_PRIVATE_IP:-?}"+ az vm show -d --resource-group "$RG" --name "$CP_VM" --query "{status:powerState}" -o tsv 2>/dev/null || echo " (not found)"+ log ""+ log "Worker ($WK_SIZE):"+ log " Public: ${WK_PUBLIC_IP:-?}"+ log " Private: ${WK_PRIVATE_IP:-?}"+ az vm show -d --resource-group "$RG" --name "$WK_VM" --query "{status:powerState}" -o tsv 2>/dev/null || echo " (not found)"+ log ""+ log "PostgreSQL: ${PG_HOST:-?} (managed)"+ log "Redis: ${REDIS_HOST:-?} (managed)"+ log "Storage: ${STORAGE_ACCOUNT_NAME:-?}.blob.core.windows.net/$STORAGE_CONTAINER"+ log "API Key: ${API_KEY:-?}"+ log ""+ log "SSH:"+ log " Control plane: ssh -i $SSH_KEY $ADMIN_USER@${CP_PUBLIC_IP:-?}"+ log " Worker: ssh -i $SSH_KEY $ADMIN_USER@${WK_PUBLIC_IP:-?}"+}++# ── SSH shortcuts ──+cmd_ssh_cp() { load_state; exec ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$CP_PUBLIC_IP"; }+cmd_ssh_wk() { load_state; exec ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$ADMIN_USER@$WK_PUBLIC_IP"; }++# ── Destroy ──+cmd_destroy() {+ log "This will DELETE the entire resource group '$RG' and ALL resources (VMs, Postgres, Redis, storage)."+ read -p "Type 'destroy' to confirm: " confirm+ if [ "$confirm" != "destroy" ]; then+ log "Aborted."+ exit 0+ fi+ az group delete --name "$RG" --yes --no-wait+ rm -f "$STATE_FILE"+ log "Resource group $RG deletion started (async). This takes ~5 minutes."+}++# ── Main ──+case "${1:-}" in+ create) cmd_create ;;+ deploy) cmd_deploy ;;+ status) cmd_status ;;+ ssh-cp) cmd_ssh_cp ;;+ ssh-wk) cmd_ssh_wk ;;+ destroy) cmd_destroy ;;+ *)+ echo "Usage: $0 {create|deploy|status|ssh-cp|ssh-wk|destroy}"+ exit 1+ ;;+esacdiff --git a/deploy/firecracker/rootfs/Dockerfile.default b/deploy/firecracker/rootfs/Dockerfile.defaultindex b42a281a..3d6a2a72 100644--- a/deploy/firecracker/rootfs/Dockerfile.default+++ b/deploy/firecracker/rootfs/Dockerfile.default@@ -12,6 +12,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \bash \busybox \ca-certificates \+ kmod \locales \sudo \# Editorsdiff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 0436e827..39e2e006 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -30,14 +30,14 @@ func (s *Server) createSandbox(c echo.Context) error {if cfg.CpuCount < 0 {cfg.CpuCount = 0}- if cfg.CpuCount > 4 {+ if cfg.CpuCount > 16 {return c.JSON(http.StatusBadRequest, map[string]string{- "error": "cpuCount must not exceed 4",+ "error": "cpuCount must not exceed 16",})}- if cfg.MemoryMB > 2048 {+ if cfg.MemoryMB > 16384 {return c.JSON(http.StatusBadRequest, map[string]string{- "error": "memoryMB must not exceed 2048",+ "error": "memoryMB must not exceed 16384",})}if cfg.MemoryMB < 0 {@@ -301,12 +301,15 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg tygrpcCtx, cancel := context.WithTimeout(ctx, grpcTimeout)defer cancel()+ // Save requested resource limits — create with defaults (golden snapshot),+ // then scale up after creation. This avoids needing a golden per CPU config.+ requestedMemoryMB := cfg.MemoryMB+ requestedCpuCount := cfg.CpuCount+grpcResp, err := grpcClient.CreateSandbox(grpcCtx, &pb.CreateSandboxRequest{Template: cfg.Template,Timeout: int32(cfg.Timeout),Envs: cfg.Envs,- MemoryMb: int32(cfg.MemoryMB),- CpuCount: int32(cfg.CpuCount),NetworkEnabled: cfg.NetworkEnabled,Port: int32(cfg.Port),TemplateRootfsKey: templateRootfsKey,@@ -318,6 +321,37 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty})}+ // Scale to requested resources after creation (virtio-mem hotplug + cgroup).+ // Golden snapshot has fixed CPU/RAM — we create with defaults then scale up.+ if requestedMemoryMB > 0 || requestedCpuCount > 0 {+ scaleMB := requestedMemoryMB+ if scaleMB <= 0 {+ scaleMB = 1024+ }+ cpuCount := requestedCpuCount+ if cpuCount <= 0 {+ cpuCount = scaleMB / 4096 // 1 vCPU per 4GB+ if cpuCount < 1 {+ cpuCount = 1+ }+ }+ maxMemBytes := int64(scaleMB) * 1024 * 1024+ cpuPeriod := int64(100000)+ cpuMax := int64(cpuCount) * cpuPeriod++ scaleCtx, scaleCancel := context.WithTimeout(ctx, 10*time.Second)+ _, scaleErr := grpcClient.SetSandboxLimits(scaleCtx, &pb.SetSandboxLimitsRequest{+ SandboxId: grpcResp.SandboxId,+ MaxMemoryBytes: maxMemBytes,+ CpuMaxUsec: cpuMax,+ CpuPeriodUsec: cpuPeriod,+ })+ scaleCancel()+ if scaleErr != nil {+ log.Printf("sandbox: post-create scale failed for %s: %v (continuing with defaults)", grpcResp.SandboxId, scaleErr)+ }+ }+// Issue sandbox-scoped JWT (24h TTL — independent of sandbox idle timeout)var token stringif s.jwtIssuer != nil {@@ -350,6 +384,9 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty"region": region,"workerID": worker.ID,}+ if s.sandboxDomain != "" {+ resp["sandboxDomain"] = s.sandboxDomain+ }return c.JSON(http.StatusCreated, resp)}@@ -414,6 +451,9 @@ func (s *Server) getSandboxRemote(c echo.Context, sandboxID string) error {"template": session.Template,"startedAt": session.StartedAt,}+ if s.sandboxDomain != "" {+ resp["sandboxDomain"] = s.sandboxDomain+ }return c.JSON(http.StatusOK, resp)}@@ -435,6 +475,9 @@ func (s *Server) getSandboxRemote(c echo.Context, sandboxID string) error {"startedAt": session.StartedAt,"template": session.Template,}+ if s.sandboxDomain != "" {+ resp["sandboxDomain"] = s.sandboxDomain+ }return c.JSON(http.StatusOK, resp)}@@ -714,9 +757,9 @@ func (s *Server) setLimits(c echo.Context) error {})}- // Auto-calculate CPU from memory: 1 vCPU per 1GB+ // Auto-calculate CPU from memory: 1 vCPU per 4GBif req.MemoryMB > 0 && req.CPUPercent == 0 {- req.CPUPercent = (req.MemoryMB * 100) / 1024+ req.CPUPercent = (req.MemoryMB * 100) / 4096if req.CPUPercent < 100 {req.CPUPercent = 100}@@ -762,8 +805,8 @@ func (s *Server) scaleSandbox(c echo.Context) error {return c.JSON(http.StatusBadRequest, map[string]string{"error": "memoryMB is required and must be positive"})}- // Auto-calculate: 1 vCPU per 1GB = 100% CPU per 1024MB- cpuPercent := (req.MemoryMB * 100) / 1024+ // Auto-calculate: 1 vCPU per 4GB = 100% CPU per 4096MB+ cpuPercent := (req.MemoryMB * 100) / 4096if cpuPercent < 100 {cpuPercent = 100}@@ -1069,12 +1112,14 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.W}resp := map[string]interface{}{- "sandboxID": sandboxID,- "connectURL": worker.HTTPAddr,- "token": token,- "status": grpcResp.Status,- "region": region,- "workerID": worker.ID,+ "sandboxID": sandboxID,+ "token": token,+ "status": grpcResp.Status,+ "region": region,+ "workerID": worker.ID,+ }+ if s.sandboxDomain != "" {+ resp["sandboxDomain"] = s.sandboxDomain}return c.JSON(http.StatusOK, resp)@@ -1521,14 +1566,18 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{}}()- return map[string]interface{}{+ result := map[string]interface{}{"sandboxID": sandboxID,"status": "creating","token": token,"region": region,"workerID": workerID,"fromCheckpointId": checkpointID.String(),- }, http.StatusCreated, nil+ }+ if s.sandboxDomain != "" {+ result["sandboxDomain"] = s.sandboxDomain+ }+ return result, http.StatusCreated, nil}// deleteCheckpoint deletes a checkpoint.diff --git a/internal/proxy/sandbox_api_proxy.go b/internal/proxy/sandbox_api_proxy.goindex 6cf8302a..e98696c0 100644--- a/internal/proxy/sandbox_api_proxy.go+++ b/internal/proxy/sandbox_api_proxy.go@@ -145,8 +145,9 @@ func (p *SandboxAPIProxy) doHTTP(c echo.Context, sandboxID, workerURL, token strDialContext: (&net.Dialer{Timeout: 5 * time.Second,}).DialContext,- ResponseHeaderTimeout: 120 * time.Second, // exec/run can be long+ ResponseHeaderTimeout: 600 * time.Second, // exec/run can take minutes (npm build, etc.)MaxIdleConnsPerHost: 10,+ IdleConnTimeout: 120 * time.Second,}var proxyErr errordiff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex b440bf88..9f6d75c5 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -54,6 +54,7 @@ type VMInstance struct {guestCID uint32bootArgs stringrestoring chan struct{}+ opMu sync.Mutex // serializes destructive VM ops (checkpoint, restore, hibernate)baseMemoryMB int // initial memory passed to -m (before virtio-mem)virtioMemRequestedMB int // additional memory via virtio-mem (beyond base)}@@ -1567,6 +1568,9 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStoreturn nil, err}+ vm.opMu.Lock()+ defer vm.opMu.Unlock()+// Check if agent needs upgrading before we hibernate.// If so, we'll do a background wake→upgrade→re-hibernate after returning// the hibernate result to the client, so the next wake is instant.@@ -1635,10 +1639,13 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDreturn "", "", err}+ vm.opMu.Lock()+ defer vm.opMu.Unlock()+t0 := time.Now()if vm.qmp == nil {- return "", "", fmt.Errorf("no QMP client for VM %s", sandboxID)+ return "", "", fmt.Errorf("QMP connection not available for %s", sandboxID)}// Sync filesystem and quiesce agent before snapshot.@@ -1665,6 +1672,9 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID// savevm creates an internal snapshot — memory + device state + disk deltas// all stored inside the qcow2 files. The VM pauses during savevm and resumes after.+ if vm.qmp == nil {+ return "", "", fmt.Errorf("QMP connection not available for %s", sandboxID)+ }snapshotName := "cp-" + checkpointIDif err := vm.qmp.SaveVM(snapshotName); err != nil {return "", "", fmt.Errorf("savevm failed: %w", err)@@ -1738,6 +1748,9 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoireturn err}+ vm.opMu.Lock()+ defer vm.opMu.Unlock()+t0 := time.Now()// Step 1: Kill the current VMdiff --git a/internal/worker/metadata.go b/internal/worker/metadata.goindex 113528b5..7183328e 100644--- a/internal/worker/metadata.go+++ b/internal/worker/metadata.go@@ -184,7 +184,7 @@ func (ms *MetadataServer) handleLimits(w http.ResponseWriter, r *http.Request) {}// POST /v1/scale → accepts {"memoryMB", "cpuPercent", "pids"}, applies cgroup limits.-// Pricing model: 1 vCPU per 1GB RAM. memoryMB=2048 → cpuPercent=200 (2 vCPUs).+// Pricing model: 1 vCPU per 4GB RAM. memoryMB=4096 → cpuPercent=100 (1 vCPU).func (ms *MetadataServer) handleScale(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {http.Error(w, "method not allowed", http.StatusMethodNotAllowed)@@ -206,9 +206,9 @@ func (ms *MetadataServer) handleScale(w http.ResponseWriter, r *http.Request) {return}- // Auto-calculate CPU from memory: 1 vCPU per 1GB+ // Auto-calculate CPU from memory: 1 vCPU per 4GBif req.MemoryMB > 0 && req.CPUPercent == 0 {- req.CPUPercent = (req.MemoryMB * 100) / 1024+ req.CPUPercent = (req.MemoryMB * 100) / 4096if req.CPUPercent < 100 {req.CPUPercent = 100}diff --git a/sdks/typescript/examples/run-all-tests.ts b/sdks/typescript/examples/run-all-tests.tsindex 02cc4bca..c59b968d 100644--- a/sdks/typescript/examples/run-all-tests.ts+++ b/sdks/typescript/examples/run-all-tests.ts@@ -44,13 +44,12 @@ interface TestSuite {}const SUITES: TestSuite[] = [- { name: "Environment", file: "test-environment.ts", description: "HOME=/workspace, npm/pip cache dirs, dotfiles" },+ { name: "Environment", file: "test-environment.ts", description: "Root access, apt/npm/pip install, dev tools" },{ name: "Commands", file: "test-commands.ts", description: "Shell commands, stderr, exit codes, pipes, concurrency" },{ name: "File Ops", file: "test-file-ops.ts", description: "Large files, special chars, nested dirs, deletion" },{ name: "Python SDK", file: "test-python-sdk.ts", description: "Python template, stdlib, file ops from Python" },- { name: "Multi-Template", file: "test-multi-template.ts", description: "base, python, node templates" },{ name: "Reconnect", file: "test-reconnect.ts", description: "Sandbox.connect(), state persistence, multi-conn" },- { name: "Domain/TLS", file: "test-domain-tls.ts", description: "Subdomains, Let's Encrypt certs, routing isolation" },+ { name: "Domain/TLS", file: "test-domain-tls.ts", description: "Subdomains, TLS certs, routing isolation" },{ name: "Concurrent", file: "test-concurrent.ts", description: "5 sandboxes in parallel, isolation, parallel ops" },{ name: "Hibernation", file: "test-hibernation-stress.ts", description: "Multi-cycle hibernate/wake, large state, auto-wake" },{ name: "Checkpoints", file: "test-checkpoints.ts", description: "Create, list, restore, fork, delete checkpoints, limits" },diff --git a/sdks/typescript/examples/test-domain-tls.ts b/sdks/typescript/examples/test-domain-tls.tsindex 81c57716..7f662d42 100644--- a/sdks/typescript/examples/test-domain-tls.ts+++ b/sdks/typescript/examples/test-domain-tls.ts@@ -87,7 +87,7 @@ async function main() {// Create 3 sandboxes and verify unique domainsfor (let i = 0; i < 3; i++) {- const sb = await Sandbox.create({ template: "node", timeout: 120 });+ const sb = await Sandbox.create({ timeout: 120 });sandboxes.push(sb);dim(`Sandbox ${i + 1}: ${sb.sandboxId} → ${sb.domain}`);}@@ -117,13 +117,15 @@ async function main() {try {const certInfo = await getTlsCertInfo(sandboxes[0].domain);check("TLS certificate is valid", certInfo.valid);- check("Certificate issued by Let's Encrypt or similar",+ check("Certificate issued by trusted CA",certInfo.issuer.includes("Let's Encrypt") ||certInfo.issuer.includes("R3") ||certInfo.issuer.includes("R10") ||certInfo.issuer.includes("R11") ||certInfo.issuer.includes("E5") ||- certInfo.issuer.includes("E6"),+ certInfo.issuer.includes("E6") ||+ certInfo.issuer.includes("Google Trust Services") ||+ certInfo.issuer.includes("GTS"),certInfo.issuer);dim(`Issuer: ${certInfo.issuer}`);dim(`Subject: ${certInfo.subject}`);diff --git a/sdks/typescript/examples/test-environment.ts b/sdks/typescript/examples/test-environment.tsindex 93fa60c0..660618d4 100644--- a/sdks/typescript/examples/test-environment.ts+++ b/sdks/typescript/examples/test-environment.ts@@ -1,17 +1,12 @@/**- * Environment & HOME Directory Test+ * Environment & Sandbox Configuration Test*- * Verifies that HOME=/workspace inside sandboxes so that tools like npm, pip,- * git etc. use the NVMe-backed workspace drive for caches and config instead- * of /root on the small rootfs.- *- * Tests:- * 1. HOME is set to /workspace- * 2. Tilde (~) expands to /workspace- * 3. npm cache dir is under /workspace- * 4. npm install writes cache to /workspace (not /root or /dev/root)- * 5. pip cache dir is under /workspace- * 6. git config home is /workspace+ * Verifies the sandbox environment is set up correctly for normal development:+ * - Running as root (can install packages, modify system files)+ * - HOME=/root (standard root home)+ * - /workspace is a separate persistent disk+ * - npm, pip, git, python, node all work+ * - npm install works in /workspace** Usage:* npx tsx examples/test-environment.ts@@ -39,51 +34,61 @@ function check(desc: string, condition: boolean, detail?: string) {async function main() {bold("\n╔══════════════════════════════════════════════════╗");- bold("║ Environment & HOME Directory Test ║");+ bold("║ Environment & Sandbox Config Test ║");bold("╚══════════════════════════════════════════════════╝\n");let sandbox: Sandbox | null = null;try {- sandbox = await Sandbox.create({ template: "node", timeout: 120 });+ sandbox = await Sandbox.create({ template: "base", timeout: 120 });green(`Created sandbox: ${sandbox.sandboxId}`);console.log();- // ── Test 1: HOME is /workspace ─────────────────────────────────- bold("━━━ Test 1: HOME environment variable ━━━\n");+ // ── Test 1: Running as root ─────────────────────────────────+ bold("━━━ Test 1: Running as root ━━━\n");++ const whoami = await sandbox.commands.run("whoami");+ check("Running as root", whoami.stdout.trim() === "root",+ `got "${whoami.stdout.trim()}"`);++ const idResult = await sandbox.commands.run("id -u");+ check("UID is 0", idResult.stdout.trim() === "0",+ `got "${idResult.stdout.trim()}"`);++ // ── Test 2: HOME is /root ───────────────────────────────────+ bold("━━━ Test 2: HOME environment ━━━\n");const homeResult = await sandbox.commands.run("echo $HOME");- check("HOME is /workspace", homeResult.stdout.trim() === "/workspace",+ check("HOME is /root", homeResult.stdout.trim() === "/root",`got "${homeResult.stdout.trim()}"`);- // ── Test 2: Tilde expansion ────────────────────────────────────- bold("━━━ Test 2: Tilde (~) expansion ━━━\n");+ // ── Test 3: /workspace is a separate disk ───────────────────+ bold("━━━ Test 3: /workspace filesystem ━━━\n");- const tildeResult = await sandbox.commands.run("echo ~");- check("~ expands to /workspace", tildeResult.stdout.trim() === "/workspace",- `got "${tildeResult.stdout.trim()}"`);+ const dfResult = await sandbox.commands.run("df -h /workspace | tail -1");+ const dfLine = dfResult.stdout.trim();+ dim(`df output: ${dfLine}`);+ check("/workspace is NOT on /dev/root", !dfLine.startsWith("/dev/root"));+ check("/workspace is mounted", dfLine.includes("/workspace"));- const tildeSlash = await sandbox.commands.run("echo ~/test");- check("~/test expands to /workspace/test", tildeSlash.stdout.trim() === "/workspace/test",- `got "${tildeSlash.stdout.trim()}"`);+ const wsExists = await sandbox.commands.run("test -d /workspace && echo yes || echo no");+ check("/workspace directory exists", wsExists.stdout.trim() === "yes");console.log();- // ── Test 3: npm cache directory ────────────────────────────────- bold("━━━ Test 3: npm cache directory ━━━\n");+ // ── Test 4: Can install system packages ─────────────────────+ bold("━━━ Test 4: Package installation (apt) ━━━\n");- const npmCache = await sandbox.commands.run("npm config get cache");- const npmCachePath = npmCache.stdout.trim();- check("npm cache is under /workspace", npmCachePath.startsWith("/workspace"),- `got "${npmCachePath}"`);- check("npm cache is NOT under /root", !npmCachePath.startsWith("/root"),- `got "${npmCachePath}"`);- dim(`npm cache dir: ${npmCachePath}`);+ const aptResult = await sandbox.commands.run(+ "apt-get update -qq > /dev/null 2>&1 && apt-get install -y -qq cowsay > /dev/null 2>&1 && /usr/games/cowsay moo | head -1",+ { timeout: 30 }+ );+ check("apt install works", aptResult.exitCode === 0,+ `exit code ${aptResult.exitCode}`);console.log();- // ── Test 4: npm install writes to workspace ────────────────────- bold("━━━ Test 4: npm install uses workspace for cache ━━━\n");+ // ── Test 5: npm install in /workspace ────────────────────────+ bold("━━━ Test 5: npm install in /workspace ━━━\n");- // Create a minimal package.json and install a small packageawait sandbox.commands.run("mkdir -p /workspace/npm-test");await sandbox.files.write("/workspace/npm-test/package.json", JSON.stringify({name: "test",@@ -92,53 +97,46 @@ async function main() {}));const installResult = await sandbox.commands.run(- "cd /workspace/npm-test && npm install --prefer-offline 2>&1",+ "cd /workspace/npm-test && npm install 2>&1 | tail -1",{ timeout: 30 });dim(`npm install exit code: ${installResult.exitCode}`);+ check("npm install succeeds", installResult.exitCode === 0);- // Verify nothing was written to /root- const rootCheck = await sandbox.commands.run(- "du -sh /root/.npm 2>/dev/null || echo 'no /root/.npm'"+ const nodeModules = await sandbox.commands.run(+ "test -d /workspace/npm-test/node_modules && echo yes || echo no");- check("No npm cache in /root/.npm", rootCheck.stdout.includes("no /root/.npm"),- `got "${rootCheck.stdout.trim()}"`);+ check("node_modules created in /workspace", nodeModules.stdout.trim() === "yes");- // Verify cache was written under /workspace- const workspaceCache = await sandbox.commands.run(- "test -d /workspace/.npm && echo 'exists' || echo 'missing'"+ const requireTest = await sandbox.commands.run(+ "cd /workspace/npm-test && node -e \"require('is-odd'); console.log('ok')\"",);- check("npm cache exists at /workspace/.npm", workspaceCache.stdout.trim() === "exists",- `got "${workspaceCache.stdout.trim()}"`);+ check("Installed package works", requireTest.stdout.trim() === "ok");console.log();- // ── Test 5: Dotfiles go to workspace ───────────────────────────- bold("━━━ Test 5: Dotfiles and configs use /workspace ━━━\n");-- // Test that .bashrc would be read from /workspace- const bashrcPath = await sandbox.commands.run("bash -c 'echo $HOME/.bashrc'");- check(".bashrc path is /workspace/.bashrc", bashrcPath.stdout.trim() === "/workspace/.bashrc",- `got "${bashrcPath.stdout.trim()}"`);+ // ── Test 6: pip install ─────────────────────────────────────+ bold("━━━ Test 6: pip install ━━━\n");- // Git global config would go to /workspace/.gitconfig- await sandbox.commands.run("git config --global user.name 'Test User'");- const gitConfigPath = await sandbox.commands.run("git config --global --list --show-origin 2>/dev/null | head -1");- check("git config is under /workspace", gitConfigPath.stdout.includes("/workspace"),- `got "${gitConfigPath.stdout.trim()}"`);+ const pipResult = await sandbox.commands.run(+ "pip3 install -q requests 2>/dev/null && python3 -c \"import requests; print(requests.__version__)\"",+ { timeout: 30 }+ );+ check("pip install + import works", pipResult.exitCode === 0 && pipResult.stdout.trim().length > 0,+ `exit code ${pipResult.exitCode}`);+ dim(`requests version: ${pipResult.stdout.trim()}`);console.log();- // ── Test 6: /workspace is on the right filesystem ──────────────- bold("━━━ Test 6: /workspace is NVMe-backed ━━━\n");+ // ── Test 7: Tools available ─────────────────────────────────+ bold("━━━ Test 7: Development tools ━━━\n");- const dfResult = await sandbox.commands.run("df -h /workspace | tail -1");- const dfLine = dfResult.stdout.trim();- dim(`df output: ${dfLine}`);- // /workspace should be on /dev/vdb (the workspace drive), not /dev/root- check("/workspace is NOT on /dev/root", !dfLine.startsWith("/dev/root"),- `got "${dfLine}"`);+ const tools = ["git", "python3", "node", "npm", "curl", "jq"];+ for (const tool of tools) {+ const r = await sandbox.commands.run(`which ${tool}`);+ check(`${tool} available`, r.exitCode === 0, r.stdout.trim());+ }console.log();- // Clean up the test directory+ // Clean upawait sandbox.commands.run("rm -rf /workspace/npm-test");} catch (err: any) {@@ -152,7 +150,6 @@ async function main() {}}- // --- Summary ---bold("========================================");bold(` Results: ${passed} passed, ${failed} failed`);bold("========================================\n");diff --git a/sdks/typescript/examples/test-hibernation-stress.ts b/sdks/typescript/examples/test-hibernation-stress.tsindex fdbb21d4..2a6aae7d 100644--- a/sdks/typescript/examples/test-hibernation-stress.ts+++ b/sdks/typescript/examples/test-hibernation-stress.ts@@ -47,7 +47,7 @@ async function main() {// ── Setup: Create sandbox with a persistent server ──────────────bold("━━━ Setup: Create sandbox with counter server ━━━\n");- sandbox = await Sandbox.create({ template: "node", timeout: 300 });+ sandbox = await Sandbox.create({ timeout: 300 });green(`Created: ${sandbox.sandboxId}`);dim(`Domain: ${sandbox.domain}`);diff --git a/sdks/typescript/examples/test-python-sdk.ts b/sdks/typescript/examples/test-python-sdk.tsindex d1adb4d3..f34feb23 100644--- a/sdks/typescript/examples/test-python-sdk.ts+++ b/sdks/typescript/examples/test-python-sdk.ts@@ -84,7 +84,7 @@ async function main() {// --- Create sandbox with Python template ---bold("[1/4] Creating Python sandbox...");sandbox = await Sandbox.create({- template: "python",+ template: "base",timeout: 120,});green(`Created: ${sandbox.sandboxId}`);diff --git a/sdks/typescript/examples/webhook-demo.ts b/sdks/typescript/examples/webhook-demo.tsindex 103457e7..03be5848 100644--- a/sdks/typescript/examples/webhook-demo.ts+++ b/sdks/typescript/examples/webhook-demo.ts@@ -95,7 +95,6 @@ async function main() {cyan("Creating sandbox...");const sandbox = await Sandbox.create({- template: "node",timeout: 300,});diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.tsindex 027ca564..5846ef89 100644--- a/sdks/typescript/src/sandbox.ts+++ b/sdks/typescript/src/sandbox.ts@@ -36,6 +36,7 @@ interface SandboxData {templateID?: string;connectURL?: string;token?: string;+ sandboxDomain?: string;}export interface CheckpointInfo {@@ -92,6 +93,7 @@ export class Sandbox {private connectUrl: string;private token: string;private _status: string;+ private _sandboxDomain: string;private constructor(data: SandboxData, apiUrl: string, apiKey: string) {this.sandboxId = data.sandboxID;@@ -100,6 +102,7 @@ export class Sandbox {this.apiKey = apiKey;this.connectUrl = data.connectURL || "";this.token = data.token || "";+ this._sandboxDomain = data.sandboxDomain || "";// Use direct worker URL for data operations if availableconst opsUrl = this.connectUrl || apiUrl;@@ -117,6 +120,18 @@ export class Sandbox {return this._status;}+ /** Preview URL domain for port 80 (e.g., "sb-xxx-p80.workers.opencomputer.dev"). */+ get domain(): string {+ if (!this._sandboxDomain) return "";+ return `${this.sandboxId}-p80.${this._sandboxDomain}`;+ }++ /** Get the preview URL domain for a specific port. */+ getPreviewDomain(port: number): string {+ if (!this._sandboxDomain) return "";+ return `${this.sandboxId}-p${port}.${this._sandboxDomain}`;+ }+static async create(opts: SandboxOpts = {}): Promise<Sandbox> {const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";