Skip to content

An open-source, faster Devin alternative

TypeScript

adjustments and fixes, deployment

Brian Reardon769cc8c83e06
diff --git a/.github/workflows/deploy-server.yml b/.github/workflows/deploy-server.yml
index 5c3b6ba9..5847d4fc 100644
--- a/.github/workflows/deploy-server.yml
+++ b/.github/workflows/deploy-server.yml
@@ -13,7 +13,7 @@ on:
workflow_dispatch:
env:
- SSH_USER: ubuntu
+ SSH_USER: azureuser
GOARCH: amd64
jobs:
@@ -52,38 +52,6 @@ jobs:
scp -i ~/.ssh/deploy.pem bin/opensandbox-server ${{ env.SSH_USER }}@${{ secrets.SERVER_IP }}:/tmp/opensandbox-server
scp -i ~/.ssh/deploy.pem bin/web-dist.tar.gz ${{ env.SSH_USER }}@${{ secrets.SERVER_IP }}:/tmp/web-dist.tar.gz
- - name: Pull secrets from AWS Secrets Manager
- run: |
- ssh -i ~/.ssh/deploy.pem ${{ env.SSH_USER }}@${{ secrets.SERVER_IP }} '
- SECRETS_ARN=$(grep OPENSANDBOX_SECRETS_ARN /etc/opensandbox/server.env 2>/dev/null | cut -d= -f2-) || true
- if [ -n "$SECRETS_ARN" ]; then
- SECRETS_JSON=$(aws --region us-east-2 secretsmanager get-secret-value \
- --secret-id "$SECRETS_ARN" --query SecretString --output text 2>&1) || {
- echo "WARNING: Failed to pull secrets, using existing env file."
- exit 0
- }
- echo "$SECRETS_JSON" | python3 -c "
- import json, sys
- secrets = json.load(sys.stdin)
- existing = {}
- try:
- with open(\"/etc/opensandbox/server.env\") as f:
- for line in f:
- line = line.strip()
- if line and not line.startswith(\"#\") and \"=\" in line:
- k, v = line.split(\"=\", 1)
- existing[k] = v
- except FileNotFoundError:
- pass
- existing.update(secrets)
- with open(\"/tmp/server.env.new\", \"w\") as f:
- for k, v in existing.items():
- f.write(f\"{k}={v}\n\")
- " && sudo mv /tmp/server.env.new /etc/opensandbox/server.env
- echo "Secrets merged."
- fi
- '
-
- name: Install and restart
run: |
ssh -i ~/.ssh/deploy.pem ${{ env.SSH_USER }}@${{ secrets.SERVER_IP }} '
diff --git a/.github/workflows/deploy-worker.yml b/.github/workflows/deploy-worker.yml
index de8c4935..825d6194 100644
--- a/.github/workflows/deploy-worker.yml
+++ b/.github/workflows/deploy-worker.yml
@@ -17,8 +17,8 @@ on:
workflow_dispatch:
env:
- SSH_USER: ubuntu
- GOARCH: arm64
+ SSH_USER: azureuser
+ GOARCH: amd64
jobs:
deploy:
@@ -42,15 +42,15 @@ jobs:
mkdir -p ~/.ssh
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/deploy.pem
chmod 600 ~/.ssh/deploy.pem
- ssh-keyscan -H ${{ secrets.WORKER_IP }} >> ~/.ssh/known_hosts
+ ssh-keyscan -H ${{ secrets.SERVER_IP }} >> ~/.ssh/known_hosts
- - name: Upload binaries
+ - name: Upload binaries and rootfs context to control plane
run: |
- scp -i ~/.ssh/deploy.pem bin/opensandbox-worker ${{ env.SSH_USER }}@${{ secrets.WORKER_IP }}:/tmp/opensandbox-worker
- scp -i ~/.ssh/deploy.pem bin/osb-agent ${{ env.SSH_USER }}@${{ secrets.WORKER_IP }}:/tmp/osb-agent
+ # Upload binaries to control plane as staging area
+ scp -i ~/.ssh/deploy.pem bin/opensandbox-worker bin/osb-agent \
+ ${{ env.SSH_USER }}@${{ secrets.SERVER_IP }}:/tmp/
- - name: Sync rootfs build context to instance
- run: |
+ # Sync rootfs build context
rsync -az \
-e "ssh -i ~/.ssh/deploy.pem" \
--include='deploy/ec2/build-rootfs-docker.sh' \
@@ -61,37 +61,90 @@ jobs:
--include='deploy/firecracker/' \
--include='scripts/' \
--exclude='*' \
- ./ ${{ env.SSH_USER }}@${{ secrets.WORKER_IP }}:/tmp/osb-rootfs-ctx/
+ ./ ${{ env.SSH_USER }}@${{ secrets.SERVER_IP }}:/tmp/osb-rootfs-ctx/
- - name: Install binaries, rebuild rootfs, and restart
+ - name: Discover workers and deploy
run: |
- ssh -i ~/.ssh/deploy.pem ${{ env.SSH_USER }}@${{ secrets.WORKER_IP }} '
+ ssh -i ~/.ssh/deploy.pem ${{ env.SSH_USER }}@${{ secrets.SERVER_IP }} '
set -euo pipefail
- # Install binaries
- sudo mv /tmp/opensandbox-worker /usr/local/bin/opensandbox-worker
- sudo chmod +x /usr/local/bin/opensandbox-worker
- sudo mv /tmp/osb-agent /usr/local/bin/osb-agent
- sudo chmod +x /usr/local/bin/osb-agent
-
- # Rebuild rootfs with new agent baked in
- # Read IMAGES_DIR from the worker systemd unit (matches OPENSANDBOX_IMAGES_DIR)
- IMAGES_DIR=$(systemctl show opensandbox-worker -p Environment --value | tr " " "\n" | grep OPENSANDBOX_IMAGES_DIR | cut -d= -f2-)
- IMAGES_DIR="${IMAGES_DIR:-/data/sandboxes/firecracker/images}"
- echo "Rebuilding rootfs in $IMAGES_DIR"
- cd /tmp/osb-rootfs-ctx
- sudo rm -f "$IMAGES_DIR/default.ext4"
- sudo bash deploy/ec2/build-rootfs-docker.sh /usr/local/bin/osb-agent "$IMAGES_DIR" default
-
- # Cleanup
- rm -rf /tmp/osb-rootfs-ctx
+ API_KEY=$(grep OPENSANDBOX_API_KEY /etc/opensandbox/server.env | cut -d= -f2-)
+
+ # Get all worker private IPs from the control plane API
+ WORKER_IPS=$(curl -sf -H "X-API-Key: $API_KEY" http://localhost:8080/api/workers \
+ | python3 -c "
+ import json, sys, re
+ workers = json.load(sys.stdin)
+ for w in workers:
+ addr = w.get(\"http_addr\", \"\")
+ # Extract IP from http://10.200.1.5:8081
+ m = re.search(r\"//([^:]+)\", addr)
+ if m:
+ print(m.group(1))
+ ")
+
+ if [ -z "$WORKER_IPS" ]; then
+ echo "ERROR: No workers found"
+ exit 1
+ fi
+
+ echo "Found workers:"
+ echo "$WORKER_IPS"
+
+ # Deploy to each worker
+ for IP in $WORKER_IPS; do
+ echo ""
+ echo "=== Deploying to worker $IP ==="
+
+ # Copy binaries from control plane to worker (via private network)
+ scp -o StrictHostKeyChecking=no /tmp/opensandbox-worker /tmp/osb-agent \
+ '"${{ env.SSH_USER }}"'@${IP}:/tmp/
+
+ # Copy rootfs build context
+ rsync -az -e "ssh -o StrictHostKeyChecking=no" \
+ /tmp/osb-rootfs-ctx/ '"${{ env.SSH_USER }}"'@${IP}:/tmp/osb-rootfs-ctx/
+
+ # Install and restart on worker
+ ssh -o StrictHostKeyChecking=no '"${{ env.SSH_USER }}"'@${IP} "
+ set -euo pipefail
- # Restart worker
- sudo systemctl restart opensandbox-worker
+ # Install binaries
+ sudo mv /tmp/opensandbox-worker /usr/local/bin/opensandbox-worker
+ sudo chmod +x /usr/local/bin/opensandbox-worker
+ sudo mv /tmp/osb-agent /usr/local/bin/osb-agent
+ sudo chmod +x /usr/local/bin/osb-agent
+
+ # Rebuild rootfs with new agent
+ IMAGES_DIR=\$(grep OPENSANDBOX_IMAGES_DIR /etc/opensandbox/worker.env 2>/dev/null | cut -d= -f2- || echo '/data/firecracker/images')
+ IMAGES_DIR=\"\${IMAGES_DIR:-/data/firecracker/images}\"
+ echo \"Rebuilding rootfs in \$IMAGES_DIR\"
+ cd /tmp/osb-rootfs-ctx
+ sudo rm -f \"\$IMAGES_DIR/default.ext4\"
+ sudo bash deploy/ec2/build-rootfs-docker.sh /usr/local/bin/osb-agent \"\$IMAGES_DIR\" default
+
+ # Delete golden snapshot so it rebuilds with new agent
+ DATA_DIR=\$(grep OPENSANDBOX_DATA_DIR /etc/opensandbox/worker.env 2>/dev/null | cut -d= -f2- || echo '/data/sandboxes')
+ sudo rm -rf \"\${DATA_DIR}/golden\" 2>/dev/null || true
+
+ # Cleanup
+ rm -rf /tmp/osb-rootfs-ctx
+
+ # Restart worker
+ sudo systemctl restart opensandbox-worker
+ echo \"Worker on \$(hostname) deployed and restarted\"
+ "
+
+ # Verify
+ sleep 3
+ ssh -o StrictHostKeyChecking=no '"${{ env.SSH_USER }}"'@${IP} \
+ "sudo systemctl is-active opensandbox-worker"
+ echo "=== Worker $IP: OK ==="
+ done
+
+ # Cleanup staging on control plane
+ rm -f /tmp/opensandbox-worker /tmp/osb-agent
+ rm -rf /tmp/osb-rootfs-ctx
'
- - name: Verify deployment
- run: |
- sleep 3
- ssh -i ~/.ssh/deploy.pem ${{ env.SSH_USER }}@${{ secrets.WORKER_IP }} 'sudo systemctl is-active opensandbox-worker'
- echo "Worker deployed successfully!"
+ - name: Summary
+ run: echo "Worker deployment complete!"
diff --git a/.github/workflows/preview-env-destroy.yml b/.github/workflows/preview-env-destroy.yml
index 8a4c46bc..d1f89cbd 100644
--- a/.github/workflows/preview-env-destroy.yml
+++ b/.github/workflows/preview-env-destroy.yml
@@ -1,10 +1,12 @@
name: Preview Environment — Destroy
+# TODO: Rewrite for Azure/QEMU — currently disabled (was AWS Terraform-based)
on:
- pull_request:
- types: [closed]
- issue_comment:
- types: [created]
+ workflow_dispatch: {}
+ # pull_request:
+ # types: [closed]
+ # issue_comment:
+ # types: [created]
permissions:
contents: read
diff --git a/.github/workflows/preview-env.yml b/.github/workflows/preview-env.yml
index 84adfd6f..e8d4dcbf 100644
--- a/.github/workflows/preview-env.yml
+++ b/.github/workflows/preview-env.yml
@@ -1,10 +1,12 @@
name: Preview Environment — Deploy
+# TODO: Rewrite for Azure/QEMU — currently disabled (was AWS Terraform-based)
on:
- issue_comment:
- types: [created]
- pull_request:
- types: [synchronize]
+ workflow_dispatch: {}
+ # issue_comment:
+ # types: [created]
+ # pull_request:
+ # types: [synchronize]
permissions:
contents: read
diff --git a/deploy/firecracker/rootfs/Dockerfile.default b/deploy/firecracker/rootfs/Dockerfile.default
index 3d6a2a72..d998d60d 100644
--- a/deploy/firecracker/rootfs/Dockerfile.default
+++ b/deploy/firecracker/rootfs/Dockerfile.default
@@ -94,6 +94,14 @@ RUN locale-gen en_US.UTF-8
ENV LANG=en_US.UTF-8
ENV LC_ALL=en_US.UTF-8
+# ── Sandbox user (non-root with passwordless sudo) ───────────────────────────
+# The agent (PID 1) runs as root, but all user commands run as "sandbox".
+# This matches user expectations for a normal Linux environment and allows
+# Claude Code to work without --allow-dangerously-skip-permissions.
+RUN useradd -m -s /bin/bash -G sudo sandbox \
+ && echo "sandbox ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/sandbox \
+ && chmod 440 /etc/sudoers.d/sandbox
+
# ── Overlay mount points (data disk backs all writes via overlayfs) ───────────
RUN mkdir -p /mnt/data /mnt/overlay
-WORKDIR /root
+WORKDIR /home/sandbox
diff --git a/internal/agent/exec.go b/internal/agent/exec.go
index b06be827..acaacf45 100644
--- a/internal/agent/exec.go
+++ b/internal/agent/exec.go
@@ -13,15 +13,24 @@ import (
pb "github.com/opensandbox/opensandbox/proto/agent"
)
-// baseEnv returns the current OS environment with HOME set to /root and
-// PATH guaranteed to include /usr/local/bin and /usr/local/sbin.
-// With overlayfs, the entire filesystem is backed by the data disk,
-// so /root (the standard root home) has full disk space available.
+const (
+ sandboxHome = "/home/sandbox"
+ sandboxUser = "sandbox"
+)
+
+// sandboxCredential returns the SysProcAttr.Credential for the sandbox user.
+func sandboxCredential() *syscall.Credential {
+ return &syscall.Credential{Uid: sandboxUID, Gid: sandboxGID}
+}
+
+// baseEnv returns the environment for sandbox user commands.
+// HOME is set to /home/sandbox, USER to sandbox, and
+// PATH is guaranteed to include /usr/local/bin and /usr/local/sbin.
func baseEnv() []string {
var env []string
hasPath := false
for _, e := range os.Environ() {
- if strings.HasPrefix(e, "HOME=") {
+ if strings.HasPrefix(e, "HOME=") || strings.HasPrefix(e, "USER=") || strings.HasPrefix(e, "LOGNAME=") {
continue
}
if strings.HasPrefix(e, "PATH=") {
@@ -39,7 +48,9 @@ func baseEnv() []string {
if !hasPath {
env = append(env, "PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin")
}
- env = append(env, "HOME=/root")
+ env = append(env, "HOME="+sandboxHome)
+ env = append(env, "USER="+sandboxUser)
+ env = append(env, "LOGNAME="+sandboxUser)
return env
}
@@ -69,7 +80,7 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecRespons
if req.Cwd != "" {
cmd.Dir = req.Cwd
} else {
- cmd.Dir = "/root"
+ cmd.Dir = sandboxHome
}
// Build env: base < sandbox-level < per-command
@@ -83,8 +94,11 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecRespons
cmd.Env = append(cmd.Env, mapToEnv(req.Envs)...)
}
- // Set process group so we can kill the entire tree
- cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ // Run as sandbox user in its own process group
+ cmd.SysProcAttr = &syscall.SysProcAttr{
+ Setpgid: true,
+ Credential: sandboxCredential(),
+ }
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
@@ -151,7 +165,7 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStre
if req.Cwd != "" {
cmd.Dir = req.Cwd
} else {
- cmd.Dir = "/root"
+ cmd.Dir = sandboxHome
}
// Build env: base < sandbox-level < per-command
@@ -166,7 +180,8 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStre
}
cmd.SysProcAttr = &syscall.SysProcAttr{
- Setpgid: true,
+ Setpgid: true,
+ Credential: sandboxCredential(),
}
stdoutPipe, err := cmd.StdoutPipe()
diff --git a/internal/agent/exec_session.go b/internal/agent/exec_session.go
index b2127894..320891d3 100644
--- a/internal/agent/exec_session.go
+++ b/internal/agent/exec_session.go
@@ -44,7 +44,7 @@ func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreat
cmd := exec.CommandContext(sessCtx, req.Command, req.Args...)
cmd.Dir = req.Cwd
if cmd.Dir == "" {
- cmd.Dir = "/root"
+ cmd.Dir = sandboxHome
}
// Build environment: base < sandbox-level < per-command
@@ -55,8 +55,11 @@ func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreat
env = append(env, mapToEnv(req.Envs)...)
cmd.Env = env
- // Run in its own process group (for clean kill on timeout)
- cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ // Run as sandbox user in its own process group
+ cmd.SysProcAttr = &syscall.SysProcAttr{
+ Setpgid: true,
+ Credential: sandboxCredential(),
+ }
stdinPipe, err := cmd.StdinPipe()
if err != nil {
diff --git a/internal/agent/filesystem.go b/internal/agent/filesystem.go
index eaa04b3f..facb2931 100644
--- a/internal/agent/filesystem.go
+++ b/internal/agent/filesystem.go
@@ -203,10 +203,10 @@ func (s *Server) WriteFileStream(stream pb.SandboxAgent_WriteFileStreamServer) e
return stream.SendAndClose(&pb.WriteFileStreamResponse{BytesWritten: total})
}
-// resolvePath ensures paths are rooted in /root for relative paths.
+// resolvePath ensures paths are rooted in the sandbox home for relative paths.
func resolvePath(path string) string {
if filepath.IsAbs(path) {
return filepath.Clean(path)
}
- return filepath.Join("/root", path)
+ return filepath.Join(sandboxHome, path)
}
diff --git a/internal/agent/pty.go b/internal/agent/pty.go
index 1386bac1..e7c794c1 100644
--- a/internal/agent/pty.go
+++ b/internal/agent/pty.go
@@ -50,13 +50,15 @@ func (s *Server) PTYCreate(ctx context.Context, req *pb.PTYCreateRequest) (*pb.P
sessCtx, cancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(sessCtx, shell)
- cmd.Dir = "/root"
+ cmd.Dir = sandboxHome
cmd.Env = append(baseEnv(),
"TERM=xterm-256color",
fmt.Sprintf("COLUMNS=%d", req.Cols),
fmt.Sprintf("LINES=%d", req.Rows),
)
- _ = syscall.Getuid() // keep syscall import for future use
+ cmd.SysProcAttr = &syscall.SysProcAttr{
+ Credential: sandboxCredential(),
+ }
cols := uint16(req.Cols)
rows := uint16(req.Rows)
diff --git a/internal/api/image_builder.go b/internal/api/image_builder.go
index ef6bcb85..4c34e621 100644
--- a/internal/api/image_builder.go
+++ b/internal/api/image_builder.go
@@ -63,7 +63,7 @@ func translateStepToCommand(step ImageStep) (string, error) {
if err != nil {
return "", fmt.Errorf("apt_install: %w", err)
}
- return fmt.Sprintf("DEBIAN_FRONTEND=noninteractive apt-get update -qq && apt-get install -y -qq %s", strings.Join(packages, " ")), nil
+ return fmt.Sprintf("sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq && sudo apt-get install -y -qq %s", strings.Join(packages, " ")), nil
case "pip_install":
pkgs, ok := step.Args["packages"]
@@ -74,7 +74,7 @@ func translateStepToCommand(step ImageStep) (string, error) {
if err != nil {
return "", fmt.Errorf("pip_install: %w", err)
}
- return fmt.Sprintf("pip install -q %s", strings.Join(packages, " ")), nil
+ return fmt.Sprintf("sudo pip install -q %s", strings.Join(packages, " ")), nil
case "run":
cmds, ok := step.Args["commands"]
@@ -100,9 +100,9 @@ func translateStepToCommand(step ImageStep) (string, error) {
for k, v := range varsMap {
val := fmt.Sprintf("%v", v)
// Write to /etc/environment for persistence across sessions
- parts = append(parts, fmt.Sprintf("echo '%s=%s' >> /etc/environment", k, val))
+ parts = append(parts, fmt.Sprintf("sudo sh -c \"echo '%s=%s' >> /etc/environment\"", k, val))
// Also write to profile.d for interactive shells
- parts = append(parts, fmt.Sprintf("echo 'export %s=\"%s\"' >> /etc/profile.d/osb-image.sh", k, val))
+ parts = append(parts, fmt.Sprintf("sudo sh -c \"echo 'export %s=\\\"%s\\\"' >> /etc/profile.d/osb-image.sh\"", k, val))
}
return strings.Join(parts, " && "), nil
@@ -115,7 +115,7 @@ func translateStepToCommand(step ImageStep) (string, error) {
if !ok {
return "", fmt.Errorf("workdir: path must be a string")
}
- return fmt.Sprintf("mkdir -p %s", pathStr), nil
+ return fmt.Sprintf("sudo mkdir -p %s", pathStr), nil
case "add_file":
remotePath, ok := step.Args["path"]
@@ -136,7 +136,7 @@ func translateStepToCommand(step ImageStep) (string, error) {
}
// Create parent directory and decode base64 content
dir := pathStr[:strings.LastIndex(pathStr, "/")]
- return fmt.Sprintf("mkdir -p %s && echo '%s' | base64 -d > %s", dir, contentStr, pathStr), nil
+ return fmt.Sprintf("sudo mkdir -p %s && echo '%s' | base64 -d | sudo tee %s > /dev/null", dir, contentStr, pathStr), nil
case "add_dir":
remotePath, ok := step.Args["path"]
@@ -157,7 +157,7 @@ func translateStepToCommand(step ImageStep) (string, error) {
}
var parts []string
- parts = append(parts, fmt.Sprintf("mkdir -p %s", pathStr))
+ parts = append(parts, fmt.Sprintf("sudo mkdir -p %s", pathStr))
for _, fileRaw := range filesArr {
fileMap, ok := fileRaw.(map[string]interface{})
if !ok {
@@ -170,7 +170,7 @@ func translateStepToCommand(step ImageStep) (string, error) {
}
fullPath := pathStr + "/" + relPath
dir := fullPath[:strings.LastIndex(fullPath, "/")]
- parts = append(parts, fmt.Sprintf("mkdir -p %s && echo '%s' | base64 -d > %s", dir, fileContent, fullPath))
+ parts = append(parts, fmt.Sprintf("sudo mkdir -p %s && echo '%s' | base64 -d | sudo tee %s > /dev/null", dir, fileContent, fullPath))
}
return strings.Join(parts, " && "), nil
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 39e2e006..4576fe79 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -216,6 +216,25 @@ func (s *Server) createSandboxWithSSE(c echo.Context, ctx context.Context, orgID
flusher.Flush()
}
+ // Send SSE keepalive comments every 15s to prevent Cloudflare 524 timeouts
+ keepaliveDone := make(chan struct{})
+ defer close(keepaliveDone)
+ go func() {
+ ticker := time.NewTicker(15 * time.Second)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ fmt.Fprintf(c.Response(), ": keepalive\n\n")
+ flusher.Flush()
+ case <-keepaliveDone:
+ return
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+
// Build log callback — emits SSE events during image build
logFn := BuildLogFunc(func(step int, stepType string, message string) {
emit("build_log", map[string]interface{}{
diff --git a/internal/api/snapshots.go b/internal/api/snapshots.go
index e684f4d0..a8892a00 100644
--- a/internal/api/snapshots.go
+++ b/internal/api/snapshots.go
@@ -6,6 +6,7 @@ import (
"fmt"
"log"
"net/http"
+ "time"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
@@ -137,6 +138,26 @@ func (s *Server) createSnapshotWithSSE(c echo.Context, ctx context.Context, orgI
flusher.Flush()
}
+ // Send SSE keepalive comments every 15s to prevent Cloudflare 524 timeouts
+ // during long build steps (e.g., installing Rust takes ~3 minutes with no output).
+ keepaliveDone := make(chan struct{})
+ defer close(keepaliveDone)
+ go func() {
+ ticker := time.NewTicker(15 * time.Second)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ fmt.Fprintf(c.Response(), ": keepalive\n\n")
+ flusher.Flush()
+ case <-keepaliveDone:
+ return
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+
logFn := BuildLogFunc(func(step int, stepType string, message string) {
emit("build_log", map[string]interface{}{
"step": step,
diff --git a/internal/config/config.go b/internal/config/config.go
index 5bdded50..191983e4 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -153,7 +153,7 @@ func Load() (*Config, error) {
S3SecretAccessKey: os.Getenv("OPENSANDBOX_S3_SECRET_ACCESS_KEY"),
S3ForcePathStyle: os.Getenv("OPENSANDBOX_S3_FORCE_PATH_STYLE") == "true",
- DefaultSandboxMemoryMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB", 1024),
+ DefaultSandboxMemoryMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB", 256),
DefaultSandboxCPUs: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_CPUS", 1),
DefaultSandboxDiskMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB", 0),
diff --git a/internal/qemu/docs_compliance_test.go b/internal/qemu/docs_compliance_test.go
index 403a7eb5..9aa6f8d3 100644
--- a/internal/qemu/docs_compliance_test.go
+++ b/internal/qemu/docs_compliance_test.go
@@ -274,14 +274,14 @@ func TestDocumentedSandboxResponseFields(t *testing.T) {
// TestDocumentedDefaultValues verifies that QEMU manager defaults match docs.
//
-// Docs say: cpuCount=1, memoryMB=512, timeout=300, port=80
+// Docs say: cpuCount=1, memoryMB=256, timeout=300, port=80
func TestDocumentedDefaultValues(t *testing.T) {
// NewManager applies defaults to zero-valued Config fields.
// We simulate that logic here since NewManager needs real dirs.
cfg := Config{DataDir: "/tmp"}
// Apply the same defaults as NewManager (lines 110-120 of manager.go)
if cfg.DefaultMemoryMB == 0 {
- cfg.DefaultMemoryMB = 512
+ cfg.DefaultMemoryMB = 256
}
if cfg.DefaultCPUs == 0 {
cfg.DefaultCPUs = 1
@@ -296,7 +296,7 @@ func TestDocumentedDefaultValues(t *testing.T) {
expected int
}{
{"DefaultCPUs (docs: 1)", cfg.DefaultCPUs, 1},
- {"DefaultMemoryMB (docs: 512)", cfg.DefaultMemoryMB, 512},
+ {"DefaultMemoryMB (docs: 256)", cfg.DefaultMemoryMB, 256},
{"DefaultPort (docs: 80)", cfg.DefaultPort, 80},
}
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 25cbc2de..b4199f62 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -144,7 +144,7 @@ func NewManager(cfg Config) (*Manager, error) {
cfg.QEMUBin = "qemu-system-x86_64"
}
if cfg.DefaultMemoryMB == 0 {
- cfg.DefaultMemoryMB = 512
+ cfg.DefaultMemoryMB = 256
}
if cfg.DefaultCPUs == 0 {
cfg.DefaultCPUs = 1
@@ -655,10 +655,19 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
// Mount /workspace — the golden snapshot was taken with /workspace unmounted
// to keep the vdb device state clean for fresh workspace qcow2 files.
+ // Then bind-mount /home/sandbox onto /workspace/.home so that user home writes
+ // (cargo install, rustup, pip --user, etc.) use the large workspace disk
+ // instead of the small ~1.7GB rootfs.
mountCtx, mountCancel := context.WithTimeout(context.Background(), 10*time.Second)
_, mountErr := agentClient.Exec(mountCtx, &pb.ExecRequest{
Command: "/bin/sh",
- Args: []string{"-c", "mount /dev/vdb /workspace 2>/dev/null || true"},
+ Args: []string{"-c", strings.Join([]string{
+ "mount /dev/vdb /workspace 2>/dev/null || true",
+ "mkdir -p /workspace/.home",
+ "cp -a /home/sandbox/. /workspace/.home/ 2>/dev/null || true",
+ "mount --bind /workspace/.home /home/sandbox",
+ "chown 1000:1000 /workspace /workspace/.home",
+ }, " && ")},
})
mountCancel()
if mountErr != nil {
@@ -720,7 +729,9 @@ func patchGuestNetwork(ctx context.Context, agent *AgentClient, netCfg *NetworkC
"ip addr flush dev eth0 && "+
"ip addr add %s/%d dev eth0 && "+
"ip link set eth0 up && "+
- "ip route add default via %s",
+ "ip route add default via %s && "+
+ "echo 'nameserver 8.8.8.8' > /etc/resolv.conf && "+
+ "echo 'nameserver 1.1.1.1' >> /etc/resolv.conf",
netCfg.GuestIP, prefixLen, netCfg.HostIP,
)
diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.go
index 369f1d08..661c7166 100644
--- a/internal/qemu/snapshot.go
+++ b/internal/qemu/snapshot.go
@@ -397,11 +397,16 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
return nil, fmt.Errorf("agent not ready: %w", err)
}
- // Mount workspace (was unmounted before savevm) + patch network + clock
+ // Mount workspace (was unmounted before savevm) + bind-mount /home/sandbox onto workspace
postCtx, postCancel := context.WithTimeout(context.Background(), 10*time.Second)
_, _ = agentClient.Exec(postCtx, &pb.ExecRequest{
Command: "/bin/sh",
- Args: []string{"-c", "mount /dev/vdb /workspace 2>/dev/null || true"},
+ Args: []string{"-c", strings.Join([]string{
+ "mount /dev/vdb /workspace 2>/dev/null || true",
+ "mkdir -p /workspace/.home",
+ "mount --bind /workspace/.home /home/sandbox 2>/dev/null || true",
+ "chown 1000:1000 /workspace /workspace/.home",
+ }, " && ")},
})
postCancel()
diff --git a/internal/worker/handlers.go b/internal/worker/handlers.go
index 64ee6be3..271c59ad 100644
--- a/internal/worker/handlers.go
+++ b/internal/worker/handlers.go
@@ -258,6 +258,41 @@ func (s *HTTPServer) execRun(c echo.Context) error {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "cmd is required"})
}
+ // For long-running commands (timeout > 30s), send response headers
+ // immediately and write periodic keepalive whitespace. This prevents
+ // Cloudflare (and other reverse proxies) from timing out:
+ // - 524 first-byte timeout (~100s): solved by sending headers early
+ // - Body idle timeout (~600s): solved by periodic space bytes
+ // JSON parsers ignore leading whitespace, so the final JSON body
+ // is parsed cleanly regardless of how many spaces precede it.
+ earlyFlush := req.Timeout > 30
+ var keepaliveDone chan struct{}
+ if earlyFlush {
+ c.Response().Header().Set("Content-Type", "application/json")
+ c.Response().WriteHeader(http.StatusOK)
+ flusher, _ := c.Response().Writer.(http.Flusher)
+ if flusher != nil {
+ flusher.Flush()
+ }
+
+ keepaliveDone = make(chan struct{})
+ go func() {
+ ticker := time.NewTicker(15 * time.Second)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ c.Response().Write([]byte(" "))
+ if flusher != nil {
+ flusher.Flush()
+ }
+ case <-keepaliveDone:
+ return
+ }
+ }
+ }()
+ }
+
var result *types.ProcessResult
routeOp := func(ctx context.Context) error {
@@ -266,16 +301,27 @@ func (s *HTTPServer) execRun(c echo.Context) error {
return err
}
+ var execErr error
if s.router != nil {
- if err := s.router.Route(c.Request().Context(), id, "execRun", routeOp); err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
- }
+ execErr = s.router.Route(c.Request().Context(), id, "execRun", routeOp)
} else {
- if err := routeOp(c.Request().Context()); err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ execErr = routeOp(c.Request().Context())
+ }
+
+ if keepaliveDone != nil {
+ close(keepaliveDone)
+ }
+
+ if execErr != nil {
+ if earlyFlush {
+ return json.NewEncoder(c.Response()).Encode(map[string]string{"error": execErr.Error()})
}
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": execErr.Error()})
}
+ if earlyFlush {
+ return json.NewEncoder(c.Response()).Encode(result)
+ }
return c.JSON(http.StatusOK, result)
}
diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.go
index 74d3ef75..62789b1d 100644
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@ -43,7 +43,7 @@ type SandboxConfig struct {
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
+ MemoryMB int `json:"memoryMB,omitempty"` // default 256
Envs map[string]string `json:"envs,omitempty"`
Port int `json:"port,omitempty"` // container port to expose via subdomain (default 80)
NetworkEnabled bool `json:"networkEnabled,omitempty"`
diff --git a/sdks/python/opencomputer/snapshot.py b/sdks/python/opencomputer/snapshot.py
index 0b22510c..c3da8db2 100644
--- a/sdks/python/opencomputer/snapshot.py
+++ b/sdks/python/opencomputer/snapshot.py
@@ -66,21 +66,19 @@ class Snapshots:
"""
body = {"name": name, "image": image.to_dict()}
- if on_build_logs is not None:
- headers = {**self._headers, "Accept": "text/event-stream"}
- client = httpx.AsyncClient(
- base_url=self._api_base, headers=headers, timeout=300.0,
- )
- try:
- async with client.stream("POST", "/snapshots", json=body) as resp:
- resp.raise_for_status()
- return await parse_sse_stream(resp, on_build_logs)
- finally:
- await client.aclose()
-
- resp = await self._client.post("/snapshots", json=body)
- resp.raise_for_status()
- return resp.json()
+ # Always use SSE streaming — builds can take minutes and
+ # non-streaming requests will hit Cloudflare 524 timeouts.
+ headers = {**self._headers, "Accept": "text/event-stream"}
+ log_fn = on_build_logs if on_build_logs is not None else lambda _: None
+ client = httpx.AsyncClient(
+ base_url=self._api_base, headers=headers, timeout=600.0,
+ )
+ try:
+ async with client.stream("POST", "/snapshots", json=body) as resp:
+ resp.raise_for_status()
+ return await parse_sse_stream(resp, log_fn)
+ finally:
+ await client.aclose()
async def list(self) -> list[dict[str, Any]]:
"""List all named snapshots for the current org."""
diff --git a/sdks/typescript/examples/test-environment.ts b/sdks/typescript/examples/test-environment.ts
index 660618d4..e55ad3ae 100644
--- a/sdks/typescript/examples/test-environment.ts
+++ b/sdks/typescript/examples/test-environment.ts
@@ -44,22 +44,26 @@ async function main() {
green(`Created sandbox: ${sandbox.sandboxId}`);
console.log();
- // ── Test 1: Running as root ─────────────────────────────────
- bold("━━━ Test 1: Running as root ━━━\n");
+ // ── Test 1: Running as sandbox user with sudo ──────────────
+ bold("━━━ Test 1: Running as sandbox user ━━━\n");
const whoami = await sandbox.commands.run("whoami");
- check("Running as root", whoami.stdout.trim() === "root",
+ check("Running as sandbox", whoami.stdout.trim() === "sandbox",
`got "${whoami.stdout.trim()}"`);
const idResult = await sandbox.commands.run("id -u");
- check("UID is 0", idResult.stdout.trim() === "0",
+ check("UID is 1000", idResult.stdout.trim() === "1000",
`got "${idResult.stdout.trim()}"`);
- // ── Test 2: HOME is /root ───────────────────────────────────
+ const sudoResult = await sandbox.commands.run("sudo whoami");
+ check("sudo works (passwordless)", sudoResult.stdout.trim() === "root",
+ `got "${sudoResult.stdout.trim()}"`);
+
+ // ── Test 2: HOME is /home/sandbox ────────────────────────────
bold("━━━ Test 2: HOME environment ━━━\n");
const homeResult = await sandbox.commands.run("echo $HOME");
- check("HOME is /root", homeResult.stdout.trim() === "/root",
+ check("HOME is /home/sandbox", homeResult.stdout.trim() === "/home/sandbox",
`got "${homeResult.stdout.trim()}"`);
// ── Test 3: /workspace is a separate disk ───────────────────
diff --git a/sdks/typescript/src/snapshot.ts b/sdks/typescript/src/snapshot.ts
index 56cef097..fdea9b53 100644
--- a/sdks/typescript/src/snapshot.ts
+++ b/sdks/typescript/src/snapshot.ts
@@ -54,10 +54,10 @@ export class Snapshots {
* The server boots a sandbox, runs the image steps, checkpoints it, and stores it under the given name.
*/
async create(opts: CreateSnapshotOpts): Promise<SnapshotInfo> {
- const headers: Record<string, string> = { ...this.headers };
- if (opts.onBuildLogs) {
- headers["Accept"] = "text/event-stream";
- }
+ const headers: Record<string, string> = {
+ ...this.headers,
+ Accept: "text/event-stream",
+ };
const resp = await fetch(`${this.apiUrl}/snapshots`, {
method: "POST",
@@ -73,8 +73,9 @@ export class Snapshots {
throw new Error(`Failed to create snapshot: ${resp.status} ${text}`);
}
- if (opts.onBuildLogs && resp.headers.get("content-type")?.includes("text/event-stream")) {
- return parseSSEStream<SnapshotInfo>(resp, opts.onBuildLogs);
+ if (resp.headers.get("content-type")?.includes("text/event-stream")) {
+ const onLog = opts.onBuildLogs ?? (() => {});
+ return parseSSEStream<SnapshotInfo>(resp, onLog);
}
return resp.json();