An open-source, faster Devin alternative
TypeScript
fixes (#87)
Brian Reardon36844ee49273
diff --git a/deploy/azure/setup-azure-host.sh b/deploy/azure/setup-azure-host.shindex 867b0911..e52e5439 100755--- a/deploy/azure/setup-azure-host.sh+++ b/deploy/azure/setup-azure-host.sh@@ -62,7 +62,7 @@ if [ -n "$GENERIC_VMLINUZ" ]; thenGENERIC_KVER=$(basename "$GENERIC_VMLINUZ" | sed 's/vmlinuz-//')echo "Guest kernel: $GENERIC_VMLINUZ ($GENERIC_KVER)"- # Extract vsock and overlay modules for the guest rootfs (loaded via insmod at boot)+ # Extract vsock, overlay, and virtio_mem modules for the guest rootfsMODDIR="/lib/modules/$GENERIC_KVER"GUEST_MODDIR="$KERNEL_DIR/guest-modules"mkdir -p "$GUEST_MODDIR"@@ -70,7 +70,8 @@ if [ -n "$GENERIC_VMLINUZ" ]; then"$MODDIR/kernel/fs/overlayfs/overlay.ko"* \"$MODDIR/kernel/net/vmw_vsock/vsock.ko"* \"$MODDIR/kernel/net/vmw_vsock/vmw_vsock_virtio_transport_common.ko"* \- "$MODDIR/kernel/net/vmw_vsock/vmw_vsock_virtio_transport.ko"*; do+ "$MODDIR/kernel/net/vmw_vsock/vmw_vsock_virtio_transport.ko"* \+ "$MODDIR/kernel/drivers/virtio/virtio_mem.ko"*; do[ -f "$mod" ] || continuebase=$(basename "$mod")if [[ "$base" == *.zst ]]; then@@ -81,6 +82,14 @@ if [ -n "$GENERIC_VMLINUZ" ]; thendoneecho "Guest modules extracted to $GUEST_MODDIR:"ls "$GUEST_MODDIR/"++ # Validate virtio_mem.ko was extracted — fail fast if missing+ if ! ls "$GUEST_MODDIR"/virtio_mem.ko* >/dev/null 2>&1; then+ echo "FATAL: virtio_mem.ko not found for kernel $GENERIC_KVER"+ echo " Looked in: $MODDIR/kernel/drivers/virtio/virtio_mem.ko*"+ echo " Memory scaling will not work. Check that linux-image-generic includes virtio_mem."+ exit 1+ fielseecho "WARNING: No generic kernel found. Guest VMs may not boot correctly."fidiff --git a/deploy/ec2/build-rootfs-docker.sh b/deploy/ec2/build-rootfs-docker.shindex d408b18c..bbe943fb 100755--- a/deploy/ec2/build-rootfs-docker.sh+++ b/deploy/ec2/build-rootfs-docker.sh@@ -80,14 +80,19 @@ if [ -d /lib/modules/vsock ]; thenfi# Load virtio-mem module (for dynamic memory scaling)-# Check both the standard kernel path and our guest-modules dir-for vmem in "/lib/modules/$(uname -r)/kernel/drivers/virtio/virtio_mem.ko" "/lib/modules/vsock/virtio_mem.ko"; do- if [ -f "$vmem" ]; then- insmod "$vmem" 2>/dev/null || true- echo "init: virtio_mem module loaded ($vmem)"- break- fi-done+# Try modprobe first (handles signatures + deps), fall back to insmod.+# This is best-effort at boot — golden snapshot creation will fail hard if not loaded.+if command -v modprobe >/dev/null 2>&1; then+ modprobe virtio_mem 2>/dev/null && echo "init: virtio_mem loaded (modprobe)" || true+else+ for vmem in "/lib/modules/$(uname -r)/kernel/drivers/virtio/virtio_mem.ko" "/lib/modules/vsock/virtio_mem.ko"; do+ if [ -f "$vmem" ]; then+ insmod "$vmem" 2>/dev/null || true+ echo "init: virtio_mem loaded ($vmem)"+ break+ fi+ done+fi# ── Mount workspace: data disk at /workspace (persistent user data) ──mkdir -p /workspace@@ -236,6 +241,28 @@ for dir in proc sys dev dev/pts dev/shm tmp workspace run; domkdir -p "$MNT_DIR/$dir"done+# Inject host kernel modules (virtio_mem, vsock, overlay) into rootfs.+# The Docker image has modules for the container kernel, but the guest runs+# the host kernel — so we need the host's matching .ko files.+GUEST_MODDIR="/opt/opensandbox/guest-modules"+if [ -d "$GUEST_MODDIR" ] && ls "$GUEST_MODDIR"/*.ko >/dev/null 2>&1; then+ # Detect guest kernel version from the kernel binary+ GUEST_KVER=$(ls -d /lib/modules/*-generic 2>/dev/null | head -1 | xargs basename)+ if [ -n "$GUEST_KVER" ]; then+ DEST="$MNT_DIR/lib/modules/$GUEST_KVER/kernel/extra"+ mkdir -p "$DEST"+ cp "$GUEST_MODDIR"/*.ko "$DEST/"+ # Run depmod so modprobe works inside the guest+ depmod -b "$MNT_DIR" "$GUEST_KVER" 2>/dev/null || log "depmod failed (non-fatal)"+ log "Injected guest modules into rootfs for kernel $GUEST_KVER:"+ ls "$DEST/"+ else+ log "WARNING: Could not detect guest kernel version — guest modules not injected"+ fi+else+ log "WARNING: No guest modules at $GUEST_MODDIR — virtio_mem may not load"+fi+syncumount "$MNT_DIR"diff --git a/examples/python/large_file_upload.py b/examples/python/large_file_upload.pynew file mode 100644index 00000000..6755f82d--- /dev/null+++ b/examples/python/large_file_upload.py@@ -0,0 +1,101 @@+"""+Large File Upload/Download via Signed URLs++For files > 50MB, use signed URLs instead of the files API.+Signed URLs stream directly to/from the worker — no gRPC size limits.++Usage:+ OPENCOMPUTER_API_KEY=your-key python large_file_upload.py+"""++import asyncio+import hashlib+import os+import time++import httpx+from opencomputer import Sandbox+++async def main():+ print("╔═══════════════════════════════════════════╗")+ print("║ Large File Upload via Signed URLs ║")+ print("╚═══════════════════════════════════════════╝\n")++ sb = await Sandbox.create(timeout=300)+ print(f"Sandbox: {sb.sandbox_id}\n")++ try:+ # ── Upload via signed URL ──────────────────────────────────+ size_mb = 100+ print(f"Generating {size_mb}MB of random data...")+ data = os.urandom(size_mb * 1024 * 1024)+ sha = hashlib.sha256(data).hexdigest()[:16]+ print(f" SHA-256: {sha}...\n")++ # Get a signed upload URL+ print("Getting signed upload URL...")+ upload_url = await sb.upload_url("/workspace/large.bin")+ print(f" URL: {upload_url[:80]}...\n")++ # Upload directly to the worker (bypasses gRPC)+ print(f"Uploading {size_mb}MB...")+ t0 = time.time()+ async with httpx.AsyncClient(timeout=120) as client:+ resp = await client.put(+ upload_url,+ content=data,+ headers={"Content-Type": "application/octet-stream"},+ )+ elapsed = time.time() - t0+ mbps = size_mb / elapsed++ if resp.status_code < 300:+ print(f" ✓ Upload: {elapsed:.1f}s ({mbps:.1f} MB/s)\n")+ else:+ print(f" ✗ Upload failed: {resp.status_code} {resp.text[:200]}\n")+ return++ # Verify file exists and has correct size+ r = await sb.exec.run("stat -c %s /workspace/large.bin")+ file_size = int(r.stdout.strip())+ print(f" File size on disk: {file_size / 1024 / 1024:.1f}MB")+ if file_size == len(data):+ print(f" ✓ Size matches\n")+ else:+ print(f" ✗ Size mismatch: expected {len(data)}, got {file_size}\n")++ # ── Download via signed URL ────────────────────────────────+ print("Getting signed download URL...")+ download_url = await sb.download_url("/workspace/large.bin")+ print(f" URL: {download_url[:80]}...\n")++ print(f"Downloading {size_mb}MB...")+ t0 = time.time()+ async with httpx.AsyncClient(timeout=120) as client:+ resp = await client.get(download_url)+ downloaded = resp.content+ elapsed = time.time() - t0+ mbps = size_mb / elapsed++ if resp.status_code == 200:+ print(f" ✓ Download: {elapsed:.1f}s ({mbps:.1f} MB/s)\n")+ else:+ print(f" ✗ Download failed: {resp.status_code}\n")+ return++ # Verify hash matches+ dl_sha = hashlib.sha256(downloaded).hexdigest()[:16]+ if sha == dl_sha:+ print(f" ✓ Hash matches: {dl_sha}...\n")+ else:+ print(f" ✗ Hash mismatch: {sha}... vs {dl_sha}...\n")++ print("Done — all checks passed!")++ finally:+ await sb.kill()+ print(f"\nSandbox {sb.sandbox_id} destroyed.")+++asyncio.run(main())diff --git a/examples/python/validate_all_features.py b/examples/python/validate_all_features.pynew file mode 100644index 00000000..35d0c5f1--- /dev/null+++ b/examples/python/validate_all_features.py@@ -0,0 +1,533 @@+"""+OpenComputer Full SDK Validation — Python+==========================================+Tests EVERY feature exposed by the Python SDK against a live server.++Usage:+ OPENCOMPUTER_API_KEY=your-key OPENCOMPUTER_API_URL=http://your-server:8080 python validate_all_features.py++Required: pip install opencomputer httpx+"""++import asyncio+import os+import time+import traceback++import httpx+from opencomputer import Image, Sandbox, SecretStore, Snapshots++API_URL = os.environ.get("OPENCOMPUTER_API_URL", "https://app.opencomputer.dev")+API_KEY = os.environ.get("OPENCOMPUTER_API_KEY", "")++PASS = 0+FAIL = 0+SKIP = 0+ERRORS = []+++def ok(msg):+ global PASS+ PASS += 1+ print(f" ✓ {msg}")+++def fail(msg, err=None):+ global FAIL+ FAIL += 1+ detail = f" — {err}" if err else ""+ print(f" ✗ {msg}{detail}")+ ERRORS.append(f"{msg}{detail}")+++def skip(msg):+ global SKIP+ SKIP += 1+ print(f" ⊘ {msg}")+++async def wait_ready(sb, timeout=30):+ """Poll until sandbox can actually execute commands (not just status=running)."""+ for _ in range(timeout):+ try:+ r = await sb.exec.run("echo ready", timeout=3)+ if r.stdout.strip() == "ready":+ return True+ except:+ pass+ await asyncio.sleep(1)+ return False+++async def test(name, coro):+ try:+ await coro+ except Exception as e:+ fail(name, str(e))+++async def main():+ print("╔═══════════════════════════════════════════════════╗")+ print("║ OpenComputer Python SDK — Full Feature Validation ║")+ print(f"║ Server: {API_URL:<42}║")+ print("╚═══════════════════════════════════════════════════╝\n")++ sandboxes = []+ store_ids = []++ try:+ # ─── 1. SANDBOX LIFECYCLE ────────────────────────────────────+ print("▸ 1. Sandbox Lifecycle")++ sb = await Sandbox.create(timeout=600)+ sandboxes.append(sb)+ ok(f"create: {sb.sandbox_id}")++ running = await sb.is_running()+ ok(f"is_running: {running}") if running else fail("is_running: False")++ await sb.set_timeout(300)+ ok("set_timeout(300)")++ # Connect to existing+ sb2 = await Sandbox.connect(sb.sandbox_id)+ ok(f"connect: {sb2.sandbox_id}")+ await sb2.close()+ print()++ # ─── 2. EXEC.RUN ────────────────────────────────────────────+ print("▸ 2. Exec (fire-and-forget)")++ r = await sb.exec.run("echo hello")+ ok(f"echo: {r.stdout.strip()}") if r.stdout.strip() == "hello" else fail(f"echo: {r.stdout}")++ r = await sb.exec.run("python3 -c \"print(2+2)\"")+ ok(f"python3: {r.stdout.strip()}") if r.stdout.strip() == "4" else fail(f"python3: {r.stdout}")++ r = await sb.exec.run("node -e \"console.log(JSON.stringify({ok:true}))\"")+ ok(f"node: {r.stdout.strip()}") if "ok" in r.stdout else fail(f"node: {r.stdout}")++ r = await sb.exec.run("env | grep MY_VAR", env={"MY_VAR": "test123"})+ ok(f"exec with env") if "test123" in r.stdout else fail(f"exec env: {r.stdout}")++ r = await sb.exec.run("pwd", cwd="/workspace")+ ok(f"exec with cwd") if "/workspace" in r.stdout else fail(f"exec cwd: {r.stdout}")++ # Timeout — server-side exec timeout (seconds, not ms)+ t0 = time.time()+ r = await sb.exec.run("sleep 30", timeout=3)+ elapsed = time.time() - t0+ ok(f"exec timeout ({elapsed:.1f}s)") if elapsed < 10 else fail(f"exec timeout: {elapsed:.1f}s")+ print()++ # ─── 3. EXEC.START (long-running sessions) ─────────────────+ print("▸ 3. Exec Sessions")++ # Start returns session ID (Python SDK doesn't have WebSocket streaming)+ sess_id = await sb.exec.start(+ "python3",+ args=["-c", "import time\nfor i in range(3): print(f'line-{i}', flush=True); time.sleep(0.2)"],+ )+ ok(f"start session: {sess_id}") if sess_id else fail(f"start: {sess_id}")+ await asyncio.sleep(2)++ # List sessions+ sessions = await sb.exec.list()+ ok(f"list sessions: {len(sessions)}") if len(sessions) >= 1 else fail(f"list: {sessions}")++ # Start + kill+ long_id = await sb.exec.start("sleep", args=["300"])+ await asyncio.sleep(0.5)+ await sb.exec.kill(long_id)+ ok("kill session")+ print()++ # ─── 4. FILES ────────────────────────────────────────────────+ print("▸ 4. Filesystem")++ await sb.files.write("/workspace/test.txt", "hello world")+ ok("write text file")++ content = await sb.files.read("/workspace/test.txt")+ ok(f"read text: {content}") if content == "hello world" else fail(f"read: {content}")++ # Binary+ binary = bytes(range(256))+ await sb.files.write("/workspace/binary.bin", binary)+ read_back = await sb.files.read_bytes("/workspace/binary.bin")+ ok("binary round-trip") if read_back == binary else fail(f"binary: {len(read_back)} bytes")++ # List+ entries = await sb.files.list("/workspace")+ names = [e.name for e in entries]+ ok(f"list: {len(names)} files") if "test.txt" in names else fail(f"list: {names}")++ # Exists+ exists = await sb.files.exists("/workspace/test.txt")+ ok("exists: True") if exists else fail("exists: False")++ not_exists = await sb.files.exists("/workspace/nope.txt")+ ok("not exists: False") if not not_exists else fail("not exists: True")++ # Make dir+ await sb.files.make_dir("/workspace/subdir/nested")+ r = await sb.exec.run("ls -d /workspace/subdir/nested")+ ok("make_dir") if r.exit_code == 0 else fail("make_dir")++ # Remove+ await sb.files.remove("/workspace/test.txt")+ exists_after = await sb.files.exists("/workspace/test.txt")+ ok("remove file") if not exists_after else fail("remove: still exists")++ # Download/upload URLs+ try:+ url = await sb.download_url("/workspace/binary.bin")+ ok(f"download_url: {url[:40]}...") if url.startswith("http") else fail(f"download_url: {url}")+ except Exception as e:+ skip(f"download_url: {e}")++ try:+ url = await sb.upload_url("/workspace/upload-test.txt")+ ok(f"upload_url: {url[:40]}...") if url.startswith("http") else fail(f"upload_url: {url}")+ except Exception as e:+ skip(f"upload_url: {e}")+ print()++ # ─── 5. PTY ─────────────────────────────────────────────────+ print("▸ 5. PTY Sessions")+ try:+ pty = await sb.pty.create(cols=120, rows=40)+ ok(f"create PTY: {pty.session_id}")++ # Send a command+ await pty.send("echo pty-works\n")+ await asyncio.sleep(1)+ data = await pty.recv()+ ok(f"PTY I/O: {len(data)} bytes") if len(data) > 0 else fail("PTY recv empty")++ await pty.close()+ ok("close PTY")+ except Exception as e:+ skip(f"PTY: {e}")+ print()++ # ─── 6. MEMORY SCALING ───────────────────────────────────────+ print("▸ 6. Memory Scaling")+ try:+ async with httpx.AsyncClient(headers={"X-API-Key": API_KEY, "Content-Type": "application/json"}, timeout=30) as client:+ resp = await client.put(f"{API_URL}/api/sandboxes/{sb.sandbox_id}/limits", json={"memoryMB": 2048})+ if resp.status_code == 200:+ ok("scale to 2GB")+ await asyncio.sleep(1)+ r = await sb.exec.run("free -m | awk '/Mem:/{print $2}'")+ mem = int(r.stdout.strip())+ ok(f"verified: {mem}MB") if mem > 1800 else fail(f"mem: {mem}MB")++ # Scale down+ async with httpx.AsyncClient(headers={"X-API-Key": API_KEY, "Content-Type": "application/json"}, timeout=30) as client:+ resp = await client.put(f"{API_URL}/api/sandboxes/{sb.sandbox_id}/limits", json={"memoryMB": 1024})+ ok("scale down to 1GB") if resp.status_code == 200 else fail(f"scale down: {resp.status_code}")+ else:+ skip(f"scale: {resp.status_code}")+ except Exception as e:+ skip(f"scaling: {e}")+ print()++ # ─── 7. METADATA API ────────────────────────────────────────+ print("▸ 7. Metadata API (169.254.169.254)")++ r = await sb.exec.run("curl -s http://169.254.169.254/v1/status")+ ok("status") if sb.sandbox_id in r.stdout else skip(f"status: {r.stdout[:40]}")++ r = await sb.exec.run("curl -s http://169.254.169.254/v1/metadata")+ ok("metadata") if "region" in r.stdout else skip(f"metadata: {r.stdout[:40]}")++ r = await sb.exec.run("curl -s http://169.254.169.254/v1/limits")+ ok("limits") if "memLimit" in r.stdout else skip(f"limits: {r.stdout[:40]}")++ # Clock+ r = await sb.exec.run("date +%s")+ try:+ drift = abs(int(r.stdout.strip()) - int(time.time()))+ ok(f"clock drift: {drift}s") if drift <= 3 else fail(f"clock drift: {drift}s")+ except:+ skip("clock check failed")+ print()++ # ─── 8. NETWORK ─────────────────────────────────────────────+ print("▸ 8. Network")++ r = await sb.exec.run("curl -s -o /dev/null -w '%{http_code}' https://httpbin.org/ip", timeout=15000)+ ok("HTTPS outbound") if r.stdout.strip() == "200" else fail(f"HTTPS: {r.stdout}")++ r = await sb.exec.run("ping -c1 -W3 8.8.8.8 2>&1 | grep -c 'bytes from'")+ ok("ping") if r.stdout.strip() == "1" else skip(f"ping blocked (ICMP not allowed on prod)")+ print()++ # ─── 9. PREVIEW URLs ────────────────────────────────────────+ print("▸ 9. Preview URLs")++ await sb.exec.run("bash -c 'mkdir -p /workspace && echo hello > /workspace/index.html'")+ await sb.exec.run("bash -c 'setsid python3 -m http.server 3000 --directory /workspace </dev/null >/dev/null 2>&1 &'")+ await asyncio.sleep(2)++ try:+ preview = await sb.create_preview_url(port=3000)+ hostname = preview.get("hostname", "")+ ok(f"create preview: {hostname}") if hostname else fail(f"preview: {preview}")++ previews = await sb.list_preview_urls()+ ok(f"list previews: {len(previews)}") if len(previews) >= 1 else fail(f"list: {previews}")++ await sb.delete_preview_url(3000)+ ok("delete preview")+ except Exception as e:+ skip(f"preview URLs: {e}")+ print()++ # ─── 10. HIBERNATE / WAKE ───────────────────────────────────+ print("▸ 10. Hibernate / Wake")++ await sb.files.write("/workspace/persist.txt", "survive-hibernate")+ await sb.exec.run("pip3 install --quiet pyyaml 2>/dev/null", timeout=60)++ # Python SDK doesn't have hibernate/wake — use REST API directly+ try:+ async with httpx.AsyncClient(headers={"X-API-Key": API_KEY, "Content-Type": "application/json"}, timeout=120) as client:+ resp = await client.post(f"{API_URL}/api/sandboxes/{sb.sandbox_id}/hibernate")+ resp.raise_for_status()+ ok("hibernate")++ async with httpx.AsyncClient(headers={"X-API-Key": API_KEY, "Content-Type": "application/json"}, timeout=120) as client:+ resp = await client.post(f"{API_URL}/api/sandboxes/{sb.sandbox_id}/wake", json={"timeout": 600})+ resp.raise_for_status()+ ok("wake")++ content = await sb.files.read("/workspace/persist.txt")+ ok("workspace survived") if content == "survive-hibernate" else fail(f"persist: {content}")++ r = await sb.exec.run("python3 -c \"import yaml; print(yaml.__version__)\"")+ ok(f"rootfs survived: pyyaml {r.stdout.strip()}") if r.exit_code == 0 else fail("pyyaml gone")+ except Exception as e:+ skip(f"hibernate/wake: {e}")+ print()++ # ─── 11. CHECKPOINT / FORK ──────────────────────────────────+ print("▸ 11. Checkpoint & Fork")++ await sb.files.write("/workspace/checkpoint-data.txt", "at-checkpoint")+ cp = await sb.create_checkpoint(name="validate-cp")+ cp_id = cp["id"]+ ok(f"create checkpoint: {cp_id[:12]}...")++ # Wait for ready+ for _ in range(20):+ cps = await sb.list_checkpoints()+ found = [c for c in cps if c["id"] == cp_id]+ if found and found[0].get("status") == "ready":+ break+ await asyncio.sleep(1)+ ok("checkpoint ready")++ # List checkpoints+ cps = await sb.list_checkpoints()+ ok(f"list checkpoints: {len(cps)}") if len(cps) >= 1 else fail(f"list: {cps}")++ # Fork+ fork = await Sandbox.create_from_checkpoint(cp_id, timeout=300)+ sandboxes.append(fork)+ await wait_ready(fork)+ ok(f"fork: {fork.sandbox_id}")++ content = await fork.files.read("/workspace/checkpoint-data.txt")+ ok("fork has checkpoint data") if content == "at-checkpoint" else fail(f"fork: {content}")++ # Isolation+ await fork.files.write("/workspace/fork-only.txt", "fork")+ r = await sb.exec.run("cat /workspace/fork-only.txt 2>&1 || echo not-found")+ ok("fork isolated") if "not-found" in r.stdout else fail("fork leaked")++ await fork.kill()+ sandboxes.remove(fork)+ ok("fork killed")+ print()++ # ─── 12. RESTORE CHECKPOINT ─────────────────────────────────+ print("▸ 12. Restore Checkpoint")++ await sb.exec.run("rm /workspace/checkpoint-data.txt")+ await sb.files.write("/workspace/post-cp.txt", "after")++ await sb.restore_checkpoint(cp_id)+ await wait_ready(sb)+ ok("restore")++ content = await sb.files.read("/workspace/checkpoint-data.txt")+ ok("restored: file back") if content == "at-checkpoint" else fail(f"restore: {content}")++ r = await sb.exec.run("cat /workspace/post-cp.txt 2>&1 || echo gone")+ ok("restored: post-cp gone") if "gone" in r.stdout else fail("post-cp still exists")++ # Delete checkpoint+ await sb.delete_checkpoint(cp_id)+ ok("delete checkpoint")+ print()++ # ─── 13. SECRET STORES ──────────────────────────────────────+ print("▸ 13. Secret Stores")++ store_name = f"validate-{int(time.time())}"+ try:+ store = await SecretStore.create(name=store_name, egress_allowlist=["httpbin.org"])+ store_id = store["id"]+ store_ids.append(store_id)+ ok(f"create store: {store_name}")++ await SecretStore.set_secret(store_id, "TEST_KEY", "secret-value")+ ok("set secret")++ secrets = await SecretStore.list_secrets(store_id)+ ok(f"list secrets: {len(secrets)}") if len(secrets) == 1 else fail(f"secrets: {secrets}")++ # Verify plaintext not exposed+ ok("no plaintext") if "secret-value" not in str(secrets) else fail("PLAINTEXT LEAKED")++ stores = await SecretStore.list()+ ok(f"list stores: {len(stores)}") if len(stores) >= 1 else fail(f"stores: {stores}")++ store_info = await SecretStore.get(store_id)+ ok("get store") if store_info["name"] == store_name else fail(f"get: {store_info}")++ await SecretStore.update(store_id, egress_allowlist=["httpbin.org", "api.github.com"])+ ok("update store")++ await SecretStore.delete_secret(store_id, "TEST_KEY")+ ok("delete secret")++ await SecretStore.delete(store_id)+ store_ids.remove(store_id)+ ok("delete store")+ except Exception as e:+ fail(f"secret stores: {e}")+ print()++ # ─── 14. IMAGE BUILDER ──────────────────────────────────────+ print("▸ 14. Image Builder")++ try:+ image = Image.base().run_commands("echo image-built > /workspace/image-proof.txt").pip_install(["httpx"])+ img_sb = await Sandbox.create(image=image, timeout=300)+ sandboxes.append(img_sb)+ await wait_ready(img_sb)+ ok(f"image build: {img_sb.sandbox_id}")++ content = await img_sb.files.read("/workspace/image-proof.txt")+ ok("image workspace") if "image-built" in content else fail(f"image ws: {content}")++ r = await img_sb.exec.run("python3 -c \"import httpx; print(httpx.__version__)\"")+ ok(f"image pip: httpx {r.stdout.strip()}") if r.exit_code == 0 else fail("httpx missing")++ # Cache hit+ t0 = time.time()+ img_sb2 = await Sandbox.create(image=image, timeout=300)+ sandboxes.append(img_sb2)+ elapsed = time.time() - t0+ ok(f"cache hit: {elapsed:.1f}s") if elapsed < 5 else ok(f"cache: {elapsed:.1f}s")++ await img_sb.kill()+ sandboxes.remove(img_sb)+ await img_sb2.kill()+ sandboxes.remove(img_sb2)+ except Exception as e:+ fail(f"image builder: {e}")+ print()++ # ─── 15. SNAPSHOTS ──────────────────────────────────────────+ print("▸ 15. Named Snapshots")++ snap_name = f"validate-snap-{int(time.time())}"+ try:+ snapshots = Snapshots()+ snap = await snapshots.create(+ name=snap_name,+ image=Image.base().run_commands("echo snap-data > /workspace/snap.txt"),+ )+ ok(f"create snapshot: {snap_name}")++ snap_list = await snapshots.list()+ ok(f"list snapshots: {len(snap_list)}") if any(s["name"] == snap_name for s in snap_list) else fail("not in list")++ snap_info = await snapshots.get(snap_name)+ ok("get snapshot") if snap_info["status"] == "ready" else fail(f"status: {snap_info['status']}")++ snap_sb = await Sandbox.create(snapshot=snap_name, timeout=300)+ sandboxes.append(snap_sb)+ await wait_ready(snap_sb)+ content = await snap_sb.files.read("/workspace/snap.txt")+ ok("sandbox from snapshot") if "snap-data" in content else fail(f"snap content: {content}")+ await snap_sb.kill()+ sandboxes.remove(snap_sb)++ await snapshots.delete(snap_name)+ ok("delete snapshot")+ await snapshots.close()+ except Exception as e:+ fail(f"snapshots: {e}")+ print()++ # ─── 16. SANDBOX WITH SECRETS ────────────────────────────────+ print("▸ 16. Sandbox with Secret Store")++ try:+ store = await SecretStore.create(name=f"validate-inject-{int(time.time())}")+ store_ids.append(store["id"])+ await SecretStore.set_secret(store["id"], "INJECTED_KEY", "injected-value")++ secret_sb = await Sandbox.create(timeout=300, secret_store=store["name"])+ sandboxes.append(secret_sb)++ r = await secret_sb.exec.run("echo $INJECTED_KEY")+ val = r.stdout.strip()+ ok(f"secret injected: {val[:20]}") if len(val) > 0 else fail("secret not injected")++ await secret_sb.kill()+ sandboxes.remove(secret_sb)+ await SecretStore.delete(store["id"])+ store_ids.remove(store["id"])+ except Exception as e:+ skip(f"sandbox with secrets: {e}")+ print()++ except Exception as e:+ fail(f"UNEXPECTED: {traceback.format_exc()}")++ finally:+ # ─── CLEANUP ─────────────────────────────────────────────────+ print("▸ Cleanup")+ for s in sandboxes:+ try:+ await s.kill()+ print(f" Killed {s.sandbox_id}")+ except:+ pass+ for sid in store_ids:+ try:+ await SecretStore.delete(sid)+ print(f" Deleted store {sid[:12]}...")+ except:+ pass++ # ─── RESULTS ─────────────────────────────────────────────────+ print(f"\n{'═' * 55}")+ print(f" {PASS} passed, {FAIL} failed, {SKIP} skipped")+ if ERRORS:+ print(f"\n Failures:")+ for e in ERRORS:+ print(f" ✗ {e}")+ print(f"{'═' * 55}")+ return FAIL == 0+++if __name__ == "__main__":+ success = asyncio.run(main())+ exit(0 if success else 1)diff --git a/examples/typescript/large-file-upload.ts b/examples/typescript/large-file-upload.tsnew file mode 100644index 00000000..3872acc5--- /dev/null+++ b/examples/typescript/large-file-upload.ts@@ -0,0 +1,102 @@+/**+ * Large File Upload/Download via Signed URLs+ *+ * For files > 50MB, use signed URLs instead of the files API.+ * Signed URLs stream directly to/from the worker — no gRPC size limits.+ *+ * Usage:+ * OPENCOMPUTER_API_KEY=your-key npx tsx examples/typescript/large-file-upload.ts+ */++import { Sandbox } from "../../sdks/typescript/src/index.js";+import { createHash, randomBytes } from "crypto";+import { Readable } from "stream";++async function main() {+ console.log("╔═══════════════════════════════════════════╗");+ console.log("║ Large File Upload via Signed URLs ║");+ console.log("╚═══════════════════════════════════════════╝\n");++ const sb = await Sandbox.create({ timeout: 300 });+ console.log(`Sandbox: ${sb.sandboxId}\n`);++ try {+ // ── Upload via signed URL ──────────────────────────────────+ const sizeMB = 100;+ console.log(`Generating ${sizeMB}MB of random data...`);+ const data = randomBytes(sizeMB * 1024 * 1024);+ const hash = createHash("sha256").update(data).digest("hex").slice(0, 16);+ console.log(` SHA-256: ${hash}...\n`);++ // Get a signed upload URL+ console.log("Getting signed upload URL...");+ const uploadUrl = await sb.uploadUrl("/workspace/large.bin");+ console.log(` URL: ${uploadUrl.slice(0, 80)}...\n`);++ // Upload directly to the worker (bypasses gRPC)+ console.log(`Uploading ${sizeMB}MB...`);+ const t0 = Date.now();+ const uploadResp = await fetch(uploadUrl, {+ method: "PUT",+ headers: { "Content-Type": "application/octet-stream" },+ body: data,+ });+ const uploadMs = Date.now() - t0;++ if (uploadResp.ok) {+ const mbps = (sizeMB / (uploadMs / 1000)).toFixed(1);+ console.log(` ✓ Upload: ${uploadMs}ms (${mbps} MB/s)\n`);+ } else {+ console.log(` ✗ Upload failed: ${uploadResp.status} ${await uploadResp.text()}\n`);+ return;+ }++ // Verify file exists and has correct size+ const check = await sb.exec.run(`stat -c %s /workspace/large.bin`);+ const fileSize = parseInt(check.stdout.trim());+ console.log(` File size on disk: ${(fileSize / 1024 / 1024).toFixed(1)}MB`);+ if (fileSize === data.length) {+ console.log(` ✓ Size matches\n`);+ } else {+ console.log(` ✗ Size mismatch: expected ${data.length}, got ${fileSize}\n`);+ }++ // ── Download via signed URL ────────────────────────────────+ console.log("Getting signed download URL...");+ const downloadUrl = await sb.downloadUrl("/workspace/large.bin");+ console.log(` URL: ${downloadUrl.slice(0, 80)}...\n`);++ console.log(`Downloading ${sizeMB}MB...`);+ const t1 = Date.now();+ const downloadResp = await fetch(downloadUrl);+ const downloaded = Buffer.from(await downloadResp.arrayBuffer());+ const downloadMs = Date.now() - t1;++ if (downloadResp.ok) {+ const mbps = (sizeMB / (downloadMs / 1000)).toFixed(1);+ console.log(` ✓ Download: ${downloadMs}ms (${mbps} MB/s)\n`);+ } else {+ console.log(` ✗ Download failed: ${downloadResp.status}\n`);+ return;+ }++ // Verify hash matches+ const downloadHash = createHash("sha256").update(downloaded).digest("hex").slice(0, 16);+ if (hash === downloadHash) {+ console.log(` ✓ Hash matches: ${downloadHash}...\n`);+ } else {+ console.log(` ✗ Hash mismatch: ${hash}... vs ${downloadHash}...\n`);+ }++ console.log("Done — all checks passed!");++ } finally {+ await sb.kill();+ console.log(`\nSandbox ${sb.sandboxId} destroyed.`);+ }+}++main().catch((err) => {+ console.error("Fatal:", err);+ process.exit(1);+});diff --git a/examples/typescript/package-lock.json b/examples/typescript/package-lock.jsonnew file mode 100644index 00000000..b9f969af--- /dev/null+++ b/examples/typescript/package-lock.json@@ -0,0 +1,594 @@+{+ "name": "typescript",+ "version": "1.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "typescript",+ "version": "1.0.0",+ "license": "ISC",+ "dependencies": {+ "@opencomputer/sdk": "file:../../sdks/typescript"+ },+ "devDependencies": {+ "tsx": "^4.21.0",+ "typescript": "^6.0.2"+ }+ },+ "../../sdks/typescript": {+ "name": "@opencomputer/sdk",+ "version": "0.5.12",+ "license": "MIT",+ "devDependencies": {+ "@types/node": "^25.3.0",+ "tsx": "^4.21.0",+ "typescript": "^5.4.0",+ "vitest": "^1.6.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.4.tgz",+ "integrity": "sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.4.tgz",+ "integrity": "sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.4.tgz",+ "integrity": "sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.4.tgz",+ "integrity": "sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.4.tgz",+ "integrity": "sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.4.tgz",+ "integrity": "sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.4.tgz",+ "integrity": "sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.4.tgz",+ "integrity": "sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.4.tgz",+ "integrity": "sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.4.tgz",+ "integrity": "sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.4.tgz",+ "integrity": "sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.4.tgz",+ "integrity": "sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.4.tgz",+ "integrity": "sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.4.tgz",+ "integrity": "sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.4.tgz",+ "integrity": "sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.4.tgz",+ "integrity": "sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.4.tgz",+ "integrity": "sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.4.tgz",+ "integrity": "sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.4.tgz",+ "integrity": "sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.4.tgz",+ "integrity": "sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.4.tgz",+ "integrity": "sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.4.tgz",+ "integrity": "sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.4.tgz",+ "integrity": "sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.4.tgz",+ "integrity": "sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.4.tgz",+ "integrity": "sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.4.tgz",+ "integrity": "sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@opencomputer/sdk": {+ "resolved": "../../sdks/typescript",+ "link": true+ },+ "node_modules/esbuild": {+ "version": "0.27.4",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.4.tgz",+ "integrity": "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.27.4",+ "@esbuild/android-arm": "0.27.4",+ "@esbuild/android-arm64": "0.27.4",+ "@esbuild/android-x64": "0.27.4",+ "@esbuild/darwin-arm64": "0.27.4",+ "@esbuild/darwin-x64": "0.27.4",+ "@esbuild/freebsd-arm64": "0.27.4",+ "@esbuild/freebsd-x64": "0.27.4",+ "@esbuild/linux-arm": "0.27.4",+ "@esbuild/linux-arm64": "0.27.4",+ "@esbuild/linux-ia32": "0.27.4",+ "@esbuild/linux-loong64": "0.27.4",+ "@esbuild/linux-mips64el": "0.27.4",+ "@esbuild/linux-ppc64": "0.27.4",+ "@esbuild/linux-riscv64": "0.27.4",+ "@esbuild/linux-s390x": "0.27.4",+ "@esbuild/linux-x64": "0.27.4",+ "@esbuild/netbsd-arm64": "0.27.4",+ "@esbuild/netbsd-x64": "0.27.4",+ "@esbuild/openbsd-arm64": "0.27.4",+ "@esbuild/openbsd-x64": "0.27.4",+ "@esbuild/openharmony-arm64": "0.27.4",+ "@esbuild/sunos-x64": "0.27.4",+ "@esbuild/win32-arm64": "0.27.4",+ "@esbuild/win32-ia32": "0.27.4",+ "@esbuild/win32-x64": "0.27.4"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/get-tsconfig": {+ "version": "4.13.7",+ "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.7.tgz",+ "integrity": "sha512-7tN6rFgBlMgpBML5j8typ92BKFi2sFQvIdpAqLA2beia5avZDrMs0FLZiM5etShWq5irVyGcGMEA1jcDaK7A/Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "resolve-pkg-maps": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"+ }+ },+ "node_modules/resolve-pkg-maps": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",+ "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"+ }+ },+ "node_modules/tsx": {+ "version": "4.21.0",+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",+ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "~0.27.0",+ "get-tsconfig": "^4.7.5"+ },+ "bin": {+ "tsx": "dist/cli.mjs"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ }+ },+ "node_modules/typescript": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.2.tgz",+ "integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ }+ }+}diff --git a/examples/typescript/package.json b/examples/typescript/package.jsonnew file mode 100644index 00000000..64c35a9f--- /dev/null+++ b/examples/typescript/package.json@@ -0,0 +1,19 @@+{+ "name": "typescript",+ "version": "1.0.0",+ "main": "index.js",+ "scripts": {+ "test": "echo \"Error: no test specified\" && exit 1"+ },+ "keywords": [],+ "author": "",+ "license": "ISC",+ "description": "",+ "dependencies": {+ "@opencomputer/sdk": "file:../../sdks/typescript"+ },+ "devDependencies": {+ "tsx": "^4.21.0",+ "typescript": "^6.0.2"+ }+}diff --git a/examples/typescript/validate_all_features.ts b/examples/typescript/validate_all_features.tsnew file mode 100644index 00000000..b9b50326--- /dev/null+++ b/examples/typescript/validate_all_features.ts@@ -0,0 +1,361 @@+/**+ * OpenComputer Full SDK Validation — TypeScript+ * ================================================+ * Tests EVERY feature exposed by the TypeScript SDK against a live server.+ *+ * Usage:+ * OPENCOMPUTER_API_KEY=your-key OPENCOMPUTER_API_URL=http://your-server:8080 npx tsx validate_all_features.ts+ *+ * Required: npm install @opencomputer/sdk+ */++import { Sandbox, SecretStore } from "../../sdks/typescript/src/index.js";+import { Image } from "../../sdks/typescript/src/image.js";+import { Snapshots } from "../../sdks/typescript/src/snapshot.js";++const API_URL = process.env.OPENCOMPUTER_API_URL || "https://app.opencomputer.dev";+const API_KEY = process.env.OPENCOMPUTER_API_KEY || "";++let PASS = 0;+let FAIL = 0;+let SKIP = 0;+const ERRORS: string[] = [];++function ok(msg: string) { PASS++; console.log(` ✓ ${msg}`); }+function fail(msg: string, err?: string) {+ FAIL++;+ const detail = err ? ` — ${err}` : "";+ console.log(` ✗ ${msg}${detail}`);+ ERRORS.push(`${msg}${detail}`);+}+function skip(msg: string) { SKIP++; console.log(` ⊘ ${msg}`); }++function sleep(ms: number) { return new Promise(r => setTimeout(r, ms)); }++async function waitReady(sb: Sandbox, timeout = 30): Promise<boolean> {+ for (let i = 0; i < timeout; i++) {+ try {+ const r = await sb.exec.run("echo ready", { timeout: 3 });+ if (r.stdout.trim() === "ready") return true;+ } catch {}+ await sleep(1000);+ }+ return false;+}++async function main() {+ console.log("╔════════════════════════════════════════════════════════╗");+ console.log("║ OpenComputer TypeScript SDK — Full Feature Validation ║");+ console.log(`║ Server: ${API_URL.padEnd(47)}║`);+ console.log("╚════════════════════════════════════════════════════════╝\n");++ const sandboxes: Sandbox[] = [];+ const storeIds: string[] = [];++ try {+ // ─── 1. SANDBOX LIFECYCLE ────────────────────────────────────+ console.log("▸ 1. Sandbox Lifecycle");++ const sb = await Sandbox.create({ timeout: 600 });+ sandboxes.push(sb);+ ok(`create: ${sb.sandboxId}`);++ const running = await sb.isRunning();+ running ? ok(`isRunning: ${running}`) : fail("isRunning: false");++ await sb.setTimeout(300);+ ok("setTimeout(300)");++ const sb2 = await Sandbox.connect(sb.sandboxId);+ ok(`connect: ${sb2.sandboxId}`);+ console.log();++ // ─── 2. EXEC.RUN ────────────────────────────────────────────+ console.log("▸ 2. Exec (fire-and-forget)");++ let r = await sb.exec.run("echo hello");+ r.stdout.trim() === "hello" ? ok("echo") : fail(`echo: ${r.stdout}`);++ r = await sb.exec.run("python3 -c \"print(2+2)\"");+ r.stdout.trim() === "4" ? ok("python3") : fail(`python3: ${r.stdout}`);++ r = await sb.exec.run("node -e \"console.log(JSON.stringify({ok:true}))\"");+ r.stdout.includes("ok") ? ok("node") : fail(`node: ${r.stdout}`);++ r = await sb.exec.run("echo $MY_VAR", { env: { MY_VAR: "test123" } });+ r.stdout.includes("test123") ? ok("exec with env") : fail(`env: ${r.stdout}`);++ r = await sb.exec.run("pwd", { cwd: "/workspace" });+ r.stdout.includes("/workspace") ? ok("exec with cwd") : fail(`cwd: ${r.stdout}`);++ const t0 = Date.now();+ r = await sb.exec.run("sleep 30", { timeout: 3 });+ const elapsed = (Date.now() - t0) / 1000;+ elapsed < 10 ? ok(`exec timeout (${elapsed.toFixed(1)}s)`) : fail(`timeout: ${elapsed}s`);+ console.log();++ // ─── 3. EXEC.START (streaming) ──────────────────────────────+ console.log("▸ 3. Exec Sessions (streaming)");++ const chunks: string[] = [];+ const session = await sb.exec.start("python3", {+ args: ["-c", "import time\nfor i in range(3): print(f'line-{i}', flush=True); time.sleep(0.1)"],+ onStdout: (data) => chunks.push(new TextDecoder().decode(data)),+ });+ const exitCode = await session.done;+ const combined = chunks.join("");+ exitCode === 0 ? ok(`stream: exit=${exitCode}, chunks=${chunks.length}`) : fail(`exit: ${exitCode}`);+ combined.includes("line-0") && combined.includes("line-2") ? ok("all lines") : fail(`output: ${combined.slice(0, 50)}`);++ // List sessions+ const sessions = await sb.exec.list();+ sessions.length >= 1 ? ok(`list: ${sessions.length}`) : fail(`list: ${sessions.length}`);++ // Kill+ const longSession = await sb.exec.start("sleep", { args: ["300"] });+ await sleep(500);+ await longSession.kill();+ ok("kill session");+ console.log();++ // ─── 4. FILES ────────────────────────────────────────────────+ console.log("▸ 4. Filesystem");++ await sb.files.write("/workspace/test.txt", "hello world");+ ok("write");++ const content = await sb.files.read("/workspace/test.txt");+ content === "hello world" ? ok("read") : fail(`read: ${content}`);++ // Binary+ const binary = new Uint8Array(256);+ for (let i = 0; i < 256; i++) binary[i] = i;+ await sb.files.write("/workspace/binary.bin", binary);+ const readBack = await sb.files.readBytes("/workspace/binary.bin");+ readBack.length === 256 ? ok("binary round-trip") : fail(`binary: ${readBack.length}`);++ // List+ const entries = await sb.files.list("/workspace");+ const names = entries.map(e => e.name);+ names.includes("test.txt") ? ok(`list: ${names.length} files`) : fail(`list: ${names}`);++ // Exists+ const exists = await sb.files.exists("/workspace/test.txt");+ exists ? ok("exists") : fail("exists: false");++ // Make dir+ await sb.files.makeDir("/workspace/subdir/nested");+ r = await sb.exec.run("ls -d /workspace/subdir/nested");+ r.exitCode === 0 ? ok("makeDir") : fail("makeDir");++ // Remove+ await sb.files.remove("/workspace/test.txt");+ const gone = !(await sb.files.exists("/workspace/test.txt"));+ gone ? ok("remove") : fail("remove: still exists");++ // Download/upload URLs+ try {+ const dlUrl = await sb.downloadUrl("/workspace/binary.bin");+ dlUrl.startsWith("http") ? ok(`downloadUrl`) : fail(`downloadUrl: ${dlUrl}`);+ } catch (e: any) { skip(`downloadUrl: ${e.message}`); }++ try {+ const ulUrl = await sb.uploadUrl("/workspace/upload.txt");+ ulUrl.startsWith("http") ? ok(`uploadUrl`) : fail(`uploadUrl: ${ulUrl}`);+ } catch (e: any) { skip(`uploadUrl: ${e.message}`); }+ console.log();++ // ─── 5. MEMORY SCALING ──────────────────────────────────────+ console.log("▸ 5. Memory Scaling");+ try {+ const scaleResp = await fetch(`${API_URL}/api/sandboxes/${sb.sandboxId}/limits`, {+ method: "PUT",+ headers: { "Content-Type": "application/json", "X-API-Key": API_KEY },+ body: JSON.stringify({ memoryMB: 2048 }),+ });+ if (scaleResp.ok) {+ ok("scale to 2GB");+ await sleep(1000);+ r = await sb.exec.run("free -m | awk '/Mem:/{print $2}'");+ const mem = parseInt(r.stdout.trim());+ mem > 1800 ? ok(`verified: ${mem}MB`) : fail(`mem: ${mem}MB`);+ } else { skip(`scale: ${scaleResp.status}`); }+ } catch (e: any) { skip(`scaling: ${e.message}`); }+ console.log();++ // ─── 6. NETWORK ─────────────────────────────────────────────+ console.log("▸ 6. Network");+ r = await sb.exec.run("curl -s -o /dev/null -w '%{http_code}' https://httpbin.org/ip", { timeout: 15000 });+ r.stdout.trim() === "200" ? ok("HTTPS") : fail(`HTTPS: ${r.stdout}`);++ r = await sb.exec.run("ping -c1 -W3 8.8.8.8 2>&1 | grep -c 'bytes from'");+ r.stdout.trim() === "1" ? ok("ping") : skip("ping blocked (ICMP not allowed)");+ console.log();++ // ─── 7. PREVIEW URLS ────────────────────────────────────────+ console.log("▸ 7. Preview URLs");+ await sb.exec.run("bash -c 'echo hello > /workspace/index.html && setsid python3 -m http.server 3000 --directory /workspace </dev/null >/dev/null 2>&1 &'");+ await sleep(2000);+ try {+ const preview = await sb.createPreviewURL({ port: 3000 });+ preview.hostname ? ok(`create: ${preview.hostname}`) : fail(`preview: ${JSON.stringify(preview)}`);++ const previews = await sb.listPreviewURLs();+ previews.length >= 1 ? ok(`list: ${previews.length}`) : fail(`list: ${previews.length}`);++ await sb.deletePreviewURL(3000);+ ok("delete");+ } catch (e: any) { skip(`preview: ${e.message}`); }+ console.log();++ // ─── 8. HIBERNATE / WAKE ────────────────────────────────────+ console.log("▸ 8. Hibernate / Wake");+ await sb.files.write("/workspace/persist.txt", "survive");++ await sb.hibernate();+ ok("hibernate");++ await sb.wake({ timeout: 600 });+ ok("wake");++ const persisted = await sb.files.read("/workspace/persist.txt");+ persisted === "survive" ? ok("workspace survived") : fail(`persist: ${persisted}`);+ console.log();++ // ─── 9. CHECKPOINT / FORK ───────────────────────────────────+ console.log("▸ 9. Checkpoint & Fork");+ await sb.files.write("/workspace/cp-data.txt", "at-checkpoint");++ const cp = await sb.createCheckpoint("validate-cp");+ ok(`checkpoint: ${cp.id.slice(0, 12)}...`);++ for (let i = 0; i < 20; i++) {+ const cps = await sb.listCheckpoints();+ if (cps.find(c => c.id === cp.id && c.status === "ready")) break;+ await sleep(1000);+ }+ ok("ready");++ const fork = await Sandbox.createFromCheckpoint(cp.id, { timeout: 300 });+ sandboxes.push(fork);+ await waitReady(fork);+ ok(`fork: ${fork.sandboxId}`);++ const forkContent = await fork.files.read("/workspace/cp-data.txt");+ forkContent === "at-checkpoint" ? ok("fork data") : fail(`fork: ${forkContent}`);++ await fork.kill();+ sandboxes.splice(sandboxes.indexOf(fork), 1);+ console.log();++ // ─── 10. RESTORE CHECKPOINT ─────────────────────────────────+ console.log("▸ 10. Restore Checkpoint");+ await sb.exec.run("rm /workspace/cp-data.txt");+ await sb.restoreCheckpoint(cp.id);+ await waitReady(sb);+ ok("restore");++ const restored = await sb.files.read("/workspace/cp-data.txt");+ restored === "at-checkpoint" ? ok("data restored") : fail(`restore: ${restored}`);++ await sb.deleteCheckpoint(cp.id);+ ok("delete checkpoint");+ console.log();++ // ─── 11. SECRET STORES ──────────────────────────────────────+ console.log("▸ 11. Secret Stores");+ try {+ const storeName = `validate-ts-${Date.now()}`;+ const store = await SecretStore.create({ name: storeName });+ storeIds.push(store.id);+ ok(`create: ${storeName}`);++ await SecretStore.setSecret(store.id, "TS_KEY", "ts-secret");+ ok("set secret");++ const secrets = await SecretStore.listSecrets(store.id);+ secrets.length === 1 ? ok("list secrets") : fail(`secrets: ${secrets.length}`);+ JSON.stringify(secrets).includes("ts-secret") ? fail("PLAINTEXT LEAKED") : ok("no plaintext");++ await SecretStore.deleteSecret(store.id, "TS_KEY");+ ok("delete secret");++ await SecretStore.delete(store.id);+ storeIds.splice(storeIds.indexOf(store.id), 1);+ ok("delete store");+ } catch (e: any) { fail(`secrets: ${e.message}`); }+ console.log();++ // ─── 12. IMAGE BUILDER ──────────────────────────────────────+ console.log("▸ 12. Image Builder");+ try {+ const image = Image.base()+ .runCommands("echo ts-image > /workspace/proof.txt")+ .pipInstall(["httpx"]);++ const imgSb = await Sandbox.create({ image, timeout: 300 });+ sandboxes.push(imgSb);+ await waitReady(imgSb);+ ok(`build: ${imgSb.sandboxId}`);++ const imgContent = await imgSb.files.read("/workspace/proof.txt");+ imgContent.includes("ts-image") ? ok("image workspace") : fail(`content: ${imgContent}`);++ r = await imgSb.exec.run("python3 -c \"import httpx; print(httpx.__version__)\"");+ r.exitCode === 0 ? ok(`pip: httpx ${r.stdout.trim()}`) : fail("httpx missing");++ await imgSb.kill();+ sandboxes.splice(sandboxes.indexOf(imgSb), 1);+ } catch (e: any) { fail(`image builder: ${e.message}`); }+ console.log();++ // ─── 13. SNAPSHOTS ──────────────────────────────────────────+ console.log("▸ 13. Named Snapshots");+ const snapName = `validate-ts-snap-${Date.now()}`;+ try {+ const snapshots = new Snapshots();+ await snapshots.create({+ name: snapName,+ image: Image.base().runCommands("echo ts-snap > /workspace/snap.txt"),+ });+ ok(`create: ${snapName}`);++ const snapList = await snapshots.list();+ snapList.find(s => s.name === snapName) ? ok("list") : fail("not in list");++ const snapSb = await Sandbox.create({ snapshot: snapName, timeout: 300 });+ sandboxes.push(snapSb);+ await waitReady(snapSb);+ const snapContent = await snapSb.files.read("/workspace/snap.txt");+ snapContent.includes("ts-snap") ? ok("sandbox from snapshot") : fail(`content: ${snapContent}`);+ await snapSb.kill();+ sandboxes.splice(sandboxes.indexOf(snapSb), 1);++ await snapshots.delete(snapName);+ ok("delete");+ } catch (e: any) { fail(`snapshots: ${e.message}`); }+ console.log();++ } catch (e: any) {+ fail(`UNEXPECTED: ${e.message}\n${e.stack}`);+ } finally {+ console.log("▸ Cleanup");+ for (const s of sandboxes) {+ try { await s.kill(); console.log(` Killed ${s.sandboxId}`); } catch {}+ }+ for (const id of storeIds) {+ try { await SecretStore.delete(id); console.log(` Deleted store ${id.slice(0, 12)}...`); } catch {}+ }+ }++ console.log(`\n${"═".repeat(55)}`);+ console.log(` ${PASS} passed, ${FAIL} failed, ${SKIP} skipped`);+ if (ERRORS.length > 0) {+ console.log(`\n Failures:`);+ for (const e of ERRORS) console.log(` ✗ ${e}`);+ }+ console.log("═".repeat(55));+ process.exit(FAIL === 0 ? 0 : 1);+}++main();diff --git a/internal/agent/filesystem.go b/internal/agent/filesystem.goindex facb2931..b68cdba4 100644--- a/internal/agent/filesystem.go+++ b/internal/agent/filesystem.go@@ -10,11 +10,19 @@ import (pb "github.com/opensandbox/opensandbox/proto/agent")-const streamChunkSize = 256 * 1024 // 256KB per gRPC chunk+const streamChunkSize = 256 * 1024 // 256KB per gRPC chunk+const maxFileSize = 2 * 1024 * 1024 * 1024 // 2GB max file transfer// ReadFile reads a file from the VM filesystem.func (s *Server) ReadFile(ctx context.Context, req *pb.ReadFileRequest) (*pb.ReadFileResponse, error) {path := resolvePath(req.Path)+ info, err := os.Stat(path)+ if err != nil {+ return nil, fmt.Errorf("stat %s: %w", path, err)+ }+ if info.Size() > maxFileSize {+ return nil, fmt.Errorf("file %s is %d bytes, exceeds 2GB limit", path, info.Size())+ }data, err := os.ReadFile(path)if err != nil {return nil, fmt.Errorf("read %s: %w", path, err)@@ -122,6 +130,9 @@ func (s *Server) ReadFileStream(req *pb.ReadFileStreamRequest, stream pb.Sandboxif err != nil {return fmt.Errorf("stat %s: %w", path, err)}+ if info.Size() > maxFileSize {+ return fmt.Errorf("file %s is %d bytes, exceeds 2GB limit", path, info.Size())+ }buf := make([]byte, streamChunkSize)first := true@@ -197,6 +208,11 @@ func (s *Server) WriteFileStream(stream pb.SandboxAgent_WriteFileStreamServer) ereturn fmt.Errorf("write %s: %w", path, err)}total += int64(n)+ if total > maxFileSize {+ f.Close()+ os.Remove(path)+ return fmt.Errorf("upload to %s exceeds 2GB limit (%d bytes written)", path, total)+ }}}diff --git a/internal/agent/server.go b/internal/agent/server.goindex ed50631f..3730570f 100644--- a/internal/agent/server.go+++ b/internal/agent/server.go@@ -77,8 +77,8 @@ func NewServer(version string) *Server {// (e.g., on SIGUSR1 to prepare for hibernate).func (s *Server) Serve(lis net.Listener) error {grpcServer := grpc.NewServer(- grpc.MaxRecvMsgSize(64 * 1024 * 1024), // 64MB for file transfers- grpc.MaxSendMsgSize(64 * 1024 * 1024),+ grpc.MaxRecvMsgSize(256 * 1024 * 1024), // 256MB for large file transfers+ grpc.MaxSendMsgSize(256 * 1024 * 1024),)pb.RegisterSandboxAgentServer(grpcServer, s)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 9059d03b..2109d94d 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -1432,8 +1432,28 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{if cp.OrgID != orgID {return nil, http.StatusForbidden, fmt.Errorf("checkpoint does not belong to this organization")}+ // Poll for checkpoint readiness — checkpoints transition from "processing" to "ready"+ // asynchronously. Wait up to 30s so SDK/CLI users don't have to poll manually.if cp.Status != "ready" {- return nil, http.StatusBadRequest, fmt.Errorf("checkpoint is not ready (status: %s)", cp.Status)+ if cp.Status == "failed" {+ return nil, http.StatusBadRequest, fmt.Errorf("checkpoint failed")+ }+ for i := 0; i < 30; i++ {+ time.Sleep(1 * time.Second)+ cp, err = s.store.GetCheckpoint(ctx, checkpointID)+ if err != nil {+ return nil, http.StatusNotFound, fmt.Errorf("checkpoint not found")+ }+ if cp.Status == "ready" {+ break+ }+ if cp.Status == "failed" {+ return nil, http.StatusBadRequest, fmt.Errorf("checkpoint failed")+ }+ }+ if cp.Status != "ready" {+ return nil, http.StatusBadRequest, fmt.Errorf("checkpoint is not ready after 30s (status: %s)", cp.Status)+ }}// Parse optional overrides from request bodydiff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.goindex 2ba4fd66..1e25fb08 100644--- a/internal/controlplane/redis_registry.go+++ b/internal/controlplane/redis_registry.go@@ -249,6 +249,10 @@ func (r *RedisWorkerRegistry) dialWorkerLocked(workerID, grpcAddr string) {}conn, err := grpc.NewClient(grpcAddr,grpc.WithTransportCredentials(creds),+ grpc.WithDefaultCallOptions(+ grpc.MaxCallRecvMsgSize(256*1024*1024),+ grpc.MaxCallSendMsgSize(256*1024*1024),+ ),grpc.WithKeepaliveParams(keepalive.ClientParameters{Time: 30 * time.Second,Timeout: 10 * time.Second,diff --git a/internal/proxy/placeholder.go b/internal/proxy/placeholder.goindex ed1039f7..4fb426c9 100644--- a/internal/proxy/placeholder.go+++ b/internal/proxy/placeholder.go@@ -97,8 +97,10 @@ func wantsBrowserResponse(r *http.Request) bool {// (for browsers) or a JSON error (for API clients / curl).func serveUpstreamUnavailable(c echo.Context, sandboxID string, port int) error {if wantsBrowserResponse(c.Request()) {+ // Return 503 (not 502) — Cloudflare intercepts 502 and replaces the body+ // with its own "Bad Gateway" page. 503 passes through to the browser.html := fmt.Sprintf(placeholderHTML, port, port, sandboxID)- return c.HTML(http.StatusBadGateway, html)+ return c.HTML(http.StatusServiceUnavailable, html)}return c.JSON(http.StatusBadGateway, map[string]string{"error": fmt.Sprintf("sandbox %s: upstream unavailable", sandboxID),diff --git a/internal/qemu/agent_client.go b/internal/qemu/agent_client.goindex 2d05ccd2..bc7c77a6 100644--- a/internal/qemu/agent_client.go+++ b/internal/qemu/agent_client.go@@ -47,8 +47,8 @@ func NewAgentClient(guestCID uint32) (*AgentClient, error) {return dialVsock(ctx, guestCID, 1024)}),grpc.WithDefaultCallOptions(- grpc.MaxCallRecvMsgSize(64*1024*1024),- grpc.MaxCallSendMsgSize(64*1024*1024),+ grpc.MaxCallRecvMsgSize(256*1024*1024),+ grpc.MaxCallSendMsgSize(256*1024*1024),),)if err != nil {@@ -470,8 +470,8 @@ func NewAgentClientSocket(socketPath string) (*AgentClient, error) {},}),grpc.WithDefaultCallOptions(- grpc.MaxCallRecvMsgSize(64*1024*1024),- grpc.MaxCallSendMsgSize(64*1024*1024),+ grpc.MaxCallRecvMsgSize(256*1024*1024),+ grpc.MaxCallSendMsgSize(256*1024*1024),),)if err != nil {diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 0e4c4246..0ee1e6c2 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -56,6 +56,7 @@ type VMInstance struct {bootArgs stringrestoring chan struct{}opMu sync.Mutex // serializes destructive VM ops (checkpoint, restore, hibernate)+ archiveDone chan struct{} // closed when async hibernate archive completes (nil if no archive in flight)baseMemoryMB int // initial memory passed to -m (before virtio-mem)virtioMemRequestedMB int // additional memory via virtio-mem (beyond base)}@@ -167,6 +168,18 @@ func NewManager(cfg Config) (*Manager, error) {log.Printf("qemu: warning: could not enable IP forwarding: %v", err)}+ // Verify the data directory supports reflink copy (required for snapshot safety).+ if err := checkReflinkSupport(cfg.DataDir); err != nil {+ return nil, fmt.Errorf("data directory does not support reflink: %w (XFS with reflink=1 required)", err)+ }++ // Clean up stale archive-staging directories from previous crashes+ staleStaging, _ := filepath.Glob(filepath.Join(cfg.DataDir, "sandboxes", "*", "archive-staging"))+ for _, d := range staleStaging {+ os.RemoveAll(d)+ log.Printf("qemu: cleaned up stale archive-staging: %s", d)+ }+return &Manager{cfg: cfg,subnets: NewSubnetAllocator(),@@ -333,18 +346,17 @@ func (m *Manager) PrepareGoldenSnapshot() error {// Load virtio_mem kernel module for memory scaling support.// The module must be loaded before the golden snapshot so that restored// VMs can use virtio-mem for dynamic memory add/remove.- modCtx, modCancel := context.WithTimeout(context.Background(), 5*time.Second)+ // Try modprobe first (handles signed modules + dependencies), fall back to insmod.+ modCtx, modCancel := context.WithTimeout(context.Background(), 10*time.Second)modResp, modErr := agentClient.Exec(modCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", "insmod /lib/modules/$(uname -r)/kernel/drivers/virtio/virtio_mem.ko 2>/dev/null; grep -c virtio_mem /proc/modules"},- RunAsRoot: true,+ Command: "/bin/sh",+ Args: []string{"-c", "modprobe virtio_mem 2>/dev/null || insmod /lib/modules/$(uname -r)/kernel/drivers/virtio/virtio_mem.ko 2>/dev/null; grep -q virtio_mem /proc/modules"},})modCancel()if modErr != nil || (modResp != nil && modResp.ExitCode != 0) {- log.Printf("qemu: golden: WARNING: virtio_mem module load failed (memory scaling may not work): err=%v", modErr)- } else {- log.Printf("qemu: golden: virtio_mem module loaded")+ return fmt.Errorf("virtio_mem module failed to load (memory scaling will not work) — ensure the rootfs has kmod installed and virtio_mem.ko is present: %v", modErr)}+ log.Printf("qemu: golden: virtio_mem module loaded")// Unmount /workspace and sync before snapshot — the golden migration state// includes virtio-blk device state (ring buffers, pending I/O). If /workspace@@ -353,7 +365,7 @@ func (m *Manager) PrepareGoldenSnapshot() error {umountCtx, umountCancel := context.WithTimeout(context.Background(), 10*time.Second)_, umountErr := agentClient.Exec(umountCtx, &pb.ExecRequest{Command: "/bin/sh",- Args: []string{"-c", "umount /workspace 2>/dev/null; sync"},+ Args: []string{"-c", "umount -f /workspace 2>/dev/null; sync; echo 3 > /proc/sys/vm/drop_caches; echo 3 > /proc/sys/vm/drop_caches; blockdev --flushbufs /dev/vdb 2>/dev/null; true"},RunAsRoot: true,})umountCancel()@@ -657,6 +669,10 @@ 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.+ // Drop caches first: the golden VM's kernel has cached ext4 metadata from the+ // golden workspace. The new sandbox has a DIFFERENT workspace qcow2 on the same+ // virtio-blk device. Without dropping caches, the kernel uses stale superblock/+ // journal data → ext4 checksum errors ("Bad message").// 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.@@ -664,6 +680,8 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,_, mountErr := agentClient.Exec(mountCtx, &pb.ExecRequest{Command: "/bin/sh",Args: []string{"-c", strings.Join([]string{+ "echo 3 > /proc/sys/vm/drop_caches",+ "echo 3 > /proc/sys/vm/drop_caches","mount /dev/vdb /workspace 2>/dev/null || true","mkdir -p /workspace/.home","cp -a /home/sandbox/. /workspace/.home/ 2>/dev/null || true",@@ -704,7 +722,9 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,GuestPort: guestPort,}if metaJSON, err := json.Marshal(sbMeta); err == nil {- _ = os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644)+ if writeErr := os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644); writeErr != nil {+ log.Printf("qemu: WARNING: failed to write sandbox-meta.json for %s: %v", sandboxDir, writeErr)+ }}log.Printf("qemu: golden-create %s: DONE (%dms total, port=%d→%d, tap=%s, cid=%d)",@@ -859,6 +879,11 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN// Create launches a new QEMU VM.func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {+ // Check disk space before creating — refuse if >95% to prevent ENOSPC corruption+ if usage, err := diskUsagePercent(m.cfg.DataDir); err == nil && usage > 95 {+ return nil, fmt.Errorf("disk usage at %d%%, refusing new sandbox (threshold: 95%%)", usage)+ }+id := cfg.SandboxIDif id == "" {id = "sb-" + uuid.New().String()[:8]@@ -1079,7 +1104,9 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.SGuestPort: guestPort,}if metaJSON, err := json.Marshal(sbMeta); err == nil {- _ = os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644)+ if writeErr := os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644); writeErr != nil {+ log.Printf("qemu: WARNING: failed to write sandbox-meta.json for %s: %v", sandboxDir, writeErr)+ }}log.Printf("qemu: created VM %s (template=%s, cpu=%d, mem=%dMB, port=%d→%d, tap=%s, mac=%s, cid=%d)",@@ -1249,6 +1276,17 @@ func (m *Manager) destroyVM(vm *VMInstance) error {os.Remove(vm.qmpSockPath)}+ // Wait for any in-flight hibernate archive to complete before deleting files.+ // Without this, os.RemoveAll races with the archive goroutine reading from+ // archive-staging/ inside sandboxDir.+ if vm.archiveDone != nil {+ select {+ case <-vm.archiveDone:+ case <-time.After(5 * time.Minute):+ log.Printf("qemu: CRITICAL: destroy %s: archive goroutine stuck for 5min, force cleanup", vm.ID)+ }+ }+if vm.sandboxDir != "" {os.RemoveAll(vm.sandboxDir)}@@ -1603,7 +1641,9 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStoreturn nil, err}- vm.opMu.Lock()+ if !vm.opMu.TryLock() {+ return nil, fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)+ }defer vm.opMu.Unlock()// Check if agent needs upgrading before we hibernate.@@ -1640,7 +1680,16 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointSto}// Wake restores a VM from a snapshot.+// Guards against double-wake: if the sandbox is already running, returns it.func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error) {+ // Prevent double wake — if sandbox is already running, return it+ m.mu.RLock()+ if existing, ok := m.vms[sandboxID]; ok {+ m.mu.RUnlock()+ log.Printf("qemu: wake %s: already running, returning existing VM", sandboxID)+ return vmToSandbox(existing), nil+ }+ m.mu.RUnlock()return m.doWake(ctx, sandboxID, checkpointKey, checkpointStore, timeout)}@@ -1649,6 +1698,18 @@ func (m *Manager) TemplateCachePath(templateID, filename string) string {return ""}+// CleanCheckpointCache removes the local cache for a checkpoint.+// Acquires checkpointCacheMu write lock to ensure no ForkFromCheckpoint is+// reading from the cache concurrently.+func (m *Manager) CleanCheckpointCache(checkpointID string) {+ m.checkpointCacheMu.Lock()+ defer m.checkpointCacheMu.Unlock()+ cacheDir := m.checkpointCacheDir(checkpointID)+ if err := os.RemoveAll(cacheDir); err != nil {+ log.Printf("qemu: clean checkpoint cache %s: %v", checkpointID, err)+ }+}+// checkpointCacheDir returns the local cache directory for a checkpoint's qcow2 files.// Uses "checkpoint-snapshots/" (not "checkpoints/") to avoid collision with the S3// checkpoint cache which stores tar.zst files in the "checkpoints/" directory.@@ -1674,7 +1735,12 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDreturn "", "", err}- vm.opMu.Lock()+ // Reject if another destructive operation (checkpoint, hibernate, restore) is in progress.+ // Without this, rapid-fire checkpoints queue up and the agent gets into a bad state+ // from overlapping SIGUSR1/reconnect cycles.+ if !vm.opMu.TryLock() {+ return "", "", fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)+ }defer vm.opMu.Unlock()t0 := time.Now()@@ -1728,6 +1794,19 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID}if reconnErr == nil {vm.agent = agentClient+ } else {+ // Agent reconnect failed — kill the VM to prevent an unmanageable orphan.+ // The checkpoint itself is valid (savevm completed), so the user can fork from it.+ log.Printf("qemu: CreateCheckpoint %s/%s: CRITICAL: agent reconnect failed, killing orphan VM", sandboxID, checkpointID)+ if vm.qmp != nil {+ _ = vm.qmp.Quit()+ vm.qmp.Close()+ vm.qmp = nil+ }+ // Remove from vms map so it's not considered running+ m.mu.Lock()+ delete(m.vms, sandboxID)+ m.mu.Unlock()}// Cache the drive files for ForkFromCheckpoint (which needs a separate QEMU process).@@ -1784,7 +1863,9 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoireturn err}- vm.opMu.Lock()+ if !vm.opMu.TryLock() {+ return fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)+ }defer vm.opMu.Unlock()t0 := time.Now()@@ -2059,11 +2140,14 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, clog.Printf("qemu: warning: metadata DNAT failed for %s: %v", netCfg.TAPName, err)}- cpus := cfg.CpuCount+ // Use checkpoint's CPU/memory for loadvm topology match.+ // savevm captures a fixed CPU topology — loadvm fails silently+ // if the new QEMU has a different core count.+ cpus := meta.CpuCountif cpus <= 0 {cpus = m.cfg.DefaultCPUs}- memMB := cfg.MemoryMB+ memMB := meta.BaseMemoryMBif memMB <= 0 {memMB = m.cfg.DefaultMemoryMB}diff --git a/internal/qemu/migration.go b/internal/qemu/migration.goindex 8e3cc07e..9d5d7a06 100644--- a/internal/qemu/migration.go+++ b/internal/qemu/migration.go@@ -73,10 +73,12 @@ func (mc *MigrationCoordinator) MigrateToS3(ctx context.Context, sandboxID strinreturn "", "", fmt.Errorf("vm not found: %w", err)}- // Sync guest filesystems before copying+ // Sync guest + reflink-copy drives under opMu to prevent concurrent+ // checkpoint/destroy from modifying files during the copy.+ vm.opMu.Lock()if vm.agent != nil {syncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)- _, _ = vm.agent.Exec(syncCtx, &pb.ExecRequest{Command: "sync", RunAsRoot: true})+ _, _ = vm.agent.Exec(syncCtx, &pb.ExecRequest{Command: "sync"})cancel()}@@ -84,21 +86,41 @@ func (mc *MigrationCoordinator) MigrateToS3(ctx context.Context, sandboxID strinrootfsPath := detectDrivePath(sandboxDir, "rootfs")workspacePath := detectDrivePath(sandboxDir, "workspace")+ stagingDir, stageErr := os.MkdirTemp(mc.manager.cfg.DataDir, "migration-staging-")+ if stageErr != nil {+ vm.opMu.Unlock()+ return "", "", fmt.Errorf("create staging dir: %w", stageErr)+ }++ stagedRootfs := filepath.Join(stagingDir, filepath.Base(rootfsPath))+ stagedWorkspace := filepath.Join(stagingDir, filepath.Base(workspacePath))+ if cpErr := copyFileReflink(rootfsPath, stagedRootfs); cpErr != nil {+ vm.opMu.Unlock()+ os.RemoveAll(stagingDir)+ return "", "", fmt.Errorf("stage rootfs: %w", cpErr)+ }+ if cpErr := copyFileReflink(workspacePath, stagedWorkspace); cpErr != nil {+ vm.opMu.Unlock()+ os.RemoveAll(stagingDir)+ return "", "", fmt.Errorf("stage workspace: %w", cpErr)+ }+ vm.opMu.Unlock() // release — uploads read from staging copies, not originals+ defer os.RemoveAll(stagingDir)+rootfsKey = fmt.Sprintf("migrations/%s/rootfs.qcow2", sandboxID)workspaceKey = fmt.Sprintf("migrations/%s/workspace.qcow2", sandboxID)t0 := time.Now()- // Upload rootfs+ // Upload from staged copies — QEMU can continue running on originalsstate.Phase = "upload-rootfs"- rootfsSize, err := mc.uploadFile(ctx, rootfsPath, rootfsKey)+ rootfsSize, err := mc.uploadFile(ctx, stagedRootfs, rootfsKey)if err != nil {return "", "", fmt.Errorf("upload rootfs: %w", err)}- // Upload workspacestate.Phase = "upload-workspace"- wsSize, err := mc.uploadFile(ctx, workspacePath, workspaceKey)+ wsSize, err := mc.uploadFile(ctx, stagedWorkspace, workspaceKey)if err != nil {return "", "", fmt.Errorf("upload workspace: %w", err)}diff --git a/internal/qemu/network.go b/internal/qemu/network.goindex 1855b3a6..710cbd55 100644--- a/internal/qemu/network.go+++ b/internal/qemu/network.go@@ -43,14 +43,21 @@ func (a *SubnetAllocator) Allocate() (*NetworkConfig, error) {defer a.mu.Unlock()block := a.next+ start := blockfor a.used[block] {block++if block > 16383 {- return nil, fmt.Errorf("subnet pool exhausted")+ block = 0 // wrap around to recycle released blocks+ }+ if block == start {+ return nil, fmt.Errorf("subnet pool exhausted (%d in use)", len(a.used))}}a.used[block] = truea.next = block + 1+ if a.next > 16383 {+ a.next = 0+ }base := block * 4b2 := byte(base >> 8)diff --git a/internal/qemu/rootfs.go b/internal/qemu/rootfs.goindex b6a6f16a..ccbfa1ee 100644--- a/internal/qemu/rootfs.go+++ b/internal/qemu/rootfs.go@@ -72,7 +72,14 @@ func CreateWorkspaceRaw(path string, sizeMB int) error {// CreateWorkspace creates a qcow2 workspace disk with an ext4 filesystem.// First creates a raw ext4 image, then converts to qcow2 for snapshot support.-func CreateWorkspace(path string, sizeMB int) error {+// CreateWorkspace creates a fresh ext4 workspace as a qcow2 image.+// If uuid is non-empty, the ext4 filesystem gets that UUID (required for golden+// restore — the kernel caches ext4 metadata by UUID, so all workspaces must match+// the golden snapshot's workspace UUID to avoid "Bad message" checksum errors).+func CreateWorkspace(path string, sizeMB int, uuid ...string) error {+ if sizeMB <= 0 {+ sizeMB = 20480 // 20GB default workspace+ }if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {return fmt.Errorf("mkdir for workspace: %w", err)}@@ -90,9 +97,12 @@ func CreateWorkspace(path string, sizeMB int) error {}f.Close()- mkfsCmd := exec.Command("mkfs.ext4", "-q", "-F",- "-L", "workspace",- rawPath)+ mkfsArgs := []string{"-q", "-F", "-L", "workspace"}+ if len(uuid) > 0 && uuid[0] != "" {+ mkfsArgs = append(mkfsArgs, "-U", uuid[0])+ }+ mkfsArgs = append(mkfsArgs, rawPath)+ mkfsCmd := exec.Command("mkfs.ext4", mkfsArgs...)if out, err := mkfsCmd.CombinedOutput(); err != nil {os.Remove(rawPath)return fmt.Errorf("mkfs.ext4: %w (%s)", err, strings.TrimSpace(string(out)))diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex c562dab4..cbfbbe77 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -10,6 +10,7 @@ import ("os/exec""path/filepath""strings"+ "syscall""time""github.com/opensandbox/opensandbox/internal/sandbox"@@ -134,9 +135,14 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoreturn nil, fmt.Errorf("marshal snapshot meta: %w", err)}metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")- if err := os.WriteFile(metaPath, metaJSON, 0644); err != nil {+ // Atomic write: write to temp file then rename to avoid partial JSON on crash+ tmpMetaPath := metaPath + ".tmp"+ if err := os.WriteFile(tmpMetaPath, metaJSON, 0644); err != nil {return nil, fmt.Errorf("write snapshot meta: %w", err)}+ if err := os.Rename(tmpMetaPath, metaPath); err != nil {+ return nil, fmt.Errorf("rename snapshot meta: %w", err)+ }// Step 5: Clean up networkif vm.network != nil {@@ -156,20 +162,50 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStovm.ID, localElapsed.Milliseconds())// Step 9: Archive + upload to S3 in the background.+ // Reflink-copy the qcow2 drives so the archive reads from stable copies+ // while wake can freely open the originals. Without this, wake starts QEMU+ // which modifies the qcow2 files while tar is still reading them →+ // "file changed as we read it" → corrupted archive → data loss on next wake.sandboxDir := vm.sandboxDirsandboxID := vm.ID- // Determine drive filenames for archiving (rootfs + workspace)workspaceFile := filepath.Base(detectDrivePath(sandboxDir, "workspace"))rootfsFile := filepath.Base(detectDrivePath(sandboxDir, "rootfs"))++ archiveDir := filepath.Join(sandboxDir, "archive-staging")+ if err := os.MkdirAll(archiveDir, 0755); err != nil {+ return nil, fmt.Errorf("mkdir archive-staging: %w", err)+ }+ // Copy metadata+ snapshotStaging := filepath.Join(archiveDir, "snapshot")+ os.MkdirAll(snapshotStaging, 0755)+ copyFileReflink(metaPath, filepath.Join(snapshotStaging, "snapshot-meta.json"))++ // Reflink-copy drives (COW — fast, no extra disk until divergence).+ // cp --reflink=auto falls back to regular copy if reflink not supported.+ for _, driveFile := range []string{rootfsFile, workspaceFile} {+ src := filepath.Join(sandboxDir, driveFile)+ dst := filepath.Join(archiveDir, driveFile)+ if err := copyFileReflink(src, dst); err != nil {+ os.RemoveAll(archiveDir)+ return nil, fmt.Errorf("copy %s for archive staging: %w", driveFile, err)+ }+ }+ log.Printf("qemu: hibernate %s: archive staging ready (reflink copies)", sandboxID)++ // Signal channel so destroyVM can wait for archive completion before deleting files.+ archiveDone := make(chan struct{})+ vm.archiveDone = archiveDone+m.uploadWg.Add(1)go func() {defer m.uploadWg.Done()+ defer close(archiveDone)+ defer os.RemoveAll(archiveDir) // clean up staging copies when donet1 := time.Now()archivePath := filepath.Join(sandboxDir, "checkpoint.tar.zst")- // savevm stores snapshot inside the qcow2 files — no separate mem file needed.- // Archive just the metadata + drives.- if err := createArchive(archivePath, sandboxDir, []string{+ // Archive from the staging copies — originals are free for wake/QEMU.+ if err := createArchive(archivePath, archiveDir, []string{"snapshot/snapshot-meta.json",rootfsFile,workspaceFile,@@ -189,7 +225,8 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStouploadCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)defer cancel()if _, err := checkpointStore.Upload(uploadCtx, checkpointKey, archivePath); err != nil {- log.Printf("qemu: async S3 upload failed for %s: %v (keeping local archive for retry)", sandboxID, err)+ log.Printf("qemu: async S3 upload failed for %s: %v", sandboxID, err)+ os.Remove(archivePath) // clean up — local qcow2 files are the source of truth for same-worker wakereturn}log.Printf("qemu: hibernate %s: S3 upload complete (%dms, key=%s)",@@ -223,6 +260,26 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, csnapshotDir := filepath.Join(sandboxDir, "snapshot")metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")+ // Wait for any in-flight hibernate archive to finish before proceeding.+ // Same-worker wake: archive reads from staging copies (safe), but we need+ // archive-staging/ cleaned up before starting QEMU to avoid disk waste.+ // Cross-worker wake: S3 upload must complete before download can succeed.+ archiveStagingDir := filepath.Join(sandboxDir, "archive-staging")+ if fileExists(archiveStagingDir) {+ log.Printf("qemu: wake %s: waiting for in-flight archive to complete", sandboxID)+ for i := 0; i < 60; i++ { // up to 30 seconds+ if !fileExists(archiveStagingDir) {+ break+ }+ time.Sleep(500 * time.Millisecond)+ }+ if fileExists(archiveStagingDir) {+ // Don't force-remove — the archive goroutine's defer will clean up.+ // Removing while tar is mid-read corrupts the S3 archive.+ log.Printf("qemu: wake %s: archive staging still present after 30s, proceeding (goroutine will clean up)", sandboxID)+ }+ }+// Step 1: Ensure qcow2 files are localt0 := time.Now()rootfsPath := detectDrivePath(sandboxDir, "rootfs")@@ -672,6 +729,42 @@ func fileExists(path string) bool {return err == nil && !info.IsDir()}+// checkReflinkSupport verifies the filesystem supports reflink by creating a test file+// and reflink-copying it. Returns nil if reflink works, error otherwise.+func checkReflinkSupport(dir string) error {+ testFile := filepath.Join(dir, ".reflink-test")+ testCopy := filepath.Join(dir, ".reflink-test-copy")+ defer os.Remove(testFile)+ defer os.Remove(testCopy)++ if err := os.MkdirAll(dir, 0755); err != nil {+ return err+ }+ if err := os.WriteFile(testFile, []byte("reflink-test"), 0644); err != nil {+ return err+ }+ cmd := exec.Command("cp", "--reflink=always", testFile, testCopy)+ if out, err := cmd.CombinedOutput(); err != nil {+ return fmt.Errorf("reflink test failed: %w (%s)", err, strings.TrimSpace(string(out)))+ }+ return nil+}++// diskUsagePercent returns the disk usage percentage for the given path.+func diskUsagePercent(path string) (int, error) {+ var stat syscall.Statfs_t+ if err := syscall.Statfs(path, &stat); err != nil {+ return 0, err+ }+ total := stat.Blocks * uint64(stat.Bsize)+ free := stat.Bfree * uint64(stat.Bsize)+ if total == 0 {+ return 0, nil+ }+ used := total - free+ return int(used * 100 / total), nil+}+// copyFileReflink copies a file using cp --reflink=auto.func copyFileReflink(src, dst string) error {cmd := exec.Command("cp", "--reflink=auto", src, dst)diff --git a/internal/sandbox/router.go b/internal/sandbox/router.goindex 031feb8f..76b1aa8e 100644--- a/internal/sandbox/router.go+++ b/internal/sandbox/router.go@@ -15,10 +15,11 @@ import (type SandboxState intconst (- StateRunning SandboxState = iota+ StateRunning SandboxState = iotaStateHibernatedStateWaking- StateCreating // async creation in progress — commands wait until ready+ StateHibernating // transitional: hibernate in progress, blocks new operations+ StateCreating // async creation in progress — commands wait until ready)func (s SandboxState) String() string {@@ -29,6 +30,8 @@ func (s SandboxState) String() string {return "hibernated"case StateWaking:return "waking"+ case StateHibernating:+ return "hibernating"case StateCreating:return "creating"default:@@ -85,9 +88,7 @@ type SandboxRouter struct {// NewSandboxRouter creates a new sandbox router.func NewSandboxRouter(cfg RouterConfig) *SandboxRouter {dt := cfg.DefaultTimeout- if dt == 0 {- dt = 300 * time.Second- }+ // 0 = no auto-timeout (sandboxes run until explicitly killed/hibernated)return &SandboxRouter{manager: cfg.Manager,checkpointStore: cfg.CheckpointStore,@@ -129,16 +130,18 @@ func (r *SandboxRouter) Register(sandboxID string, timeout time.Duration) {state: StateRunning,timeout: timeout,}- entry.timer = time.AfterFunc(timeout, func() {- r.onTimeout(sandboxID)- })+ if timeout > 0 {+ entry.timer = time.AfterFunc(timeout, func() {+ r.onTimeout(sandboxID)+ })+ }r.sandboxes[sandboxID] = entry}// RegisterCreating registers a sandbox that is being created asynchronously.// Commands routed to this sandbox will block until MarkCreated is called.func (r *SandboxRouter) RegisterCreating(sandboxID string, timeout time.Duration) {- if timeout <= 0 {+ if timeout <= 0 && r.defaultTimeout > 0 {timeout = r.defaultTimeout}@@ -175,9 +178,11 @@ func (r *SandboxRouter) MarkCreated(sandboxID string, err error) {entry.state = StateHibernated // mark as failed} else {entry.state = StateRunning- entry.timer = time.AfterFunc(entry.timeout, func() {- r.onTimeout(sandboxID)- })+ if entry.timeout > 0 {+ entry.timer = time.AfterFunc(entry.timeout, func() {+ r.onTimeout(sandboxID)+ })+ }}close(entry.wakeCh)}@@ -282,8 +287,9 @@ func (r *SandboxRouter) SetTimeout(sandboxID string, timeout time.Duration) {entry.timeout = timeoutif entry.timer != nil {entry.timer.Stop()+ entry.timer = nil}- if entry.state == StateRunning {+ if entry.state == StateRunning && timeout > 0 {entry.timer = time.AfterFunc(timeout, func() {r.onTimeout(sandboxID)})@@ -342,7 +348,7 @@ func (r *SandboxRouter) ensureRunning(ctx context.Context, sandboxID string) errentry.mu.Unlock()return nil- case StateHibernated:+ case StateHibernated, StateHibernating:// Transition to waking, start wake, other requests will queueentry.state = StateWakingentry.wakeCh = make(chan struct{})@@ -475,9 +481,11 @@ func (r *SandboxRouter) doWake(ctx context.Context, sandboxID string, entry *san// Transition to running and start rolling timeoutentry.mu.Lock()entry.state = StateRunning- entry.timer = time.AfterFunc(entry.timeout, func() {- r.onTimeout(sandboxID)- })+ if entry.timeout > 0 {+ entry.timer = time.AfterFunc(entry.timeout, func() {+ r.onTimeout(sandboxID)+ })+ }entry.mu.Unlock()}@@ -501,6 +509,9 @@ func (r *SandboxRouter) resetTimeout(sandboxID string) {if entry.timer != nil {entry.timer.Stop()}+ if entry.timeout <= 0 {+ return+ }entry.timer = time.AfterFunc(entry.timeout, func() {r.onTimeout(sandboxID)})@@ -521,6 +532,9 @@ func (r *SandboxRouter) onTimeout(sandboxID string) {entry.mu.Unlock()return}+ // Set transitional state before releasing lock — prevents concurrent exec+ // calls from routing to a VM that's about to be hibernated.+ entry.state = StateHibernatingentry.mu.Unlock()ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex d06d4921..be51c8b6 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -52,6 +52,8 @@ type GRPCServer struct {// If OPENSANDBOX_GRPC_TLS_* env vars are set, the server uses mTLS.func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sandbox.ExecSessionManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder interface{}, store *db.Store) *GRPCServer {serverOpts := []grpc.ServerOption{+ grpc.MaxRecvMsgSize(256 * 1024 * 1024), // 256MB for large file transfers+ grpc.MaxSendMsgSize(256 * 1024 * 1024),grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{MinTime: 5 * time.Second,PermitWithoutStream: true,diff --git a/internal/worker/handlers.go b/internal/worker/handlers.goindex 5b25d7f4..7de7767d 100644--- a/internal/worker/handlers.go+++ b/internal/worker/handlers.go@@ -4,6 +4,7 @@ import ("context""encoding/binary""encoding/json"+ "fmt""io""net/http""time"@@ -365,10 +366,13 @@ func (s *HTTPServer) readFile(c echo.Context) error {return c.JSON(http.StatusBadRequest, map[string]string{"error": "path query parameter is required"})}- var content string+ // Use streaming read — receives file data in 256KB chunks from the agent+ // via gRPC streaming. Streams directly to the HTTP response without buffering.+ var reader io.ReadCloser+ var size int64routeOp := func(ctx context.Context) error {var err error- content, err = s.manager.ReadFile(ctx, id, path)+ reader, size, err = s.manager.ReadFileStream(ctx, id, path)return err}@@ -381,8 +385,15 @@ func (s *HTTPServer) readFile(c echo.Context) error {return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})}}+ defer reader.Close()- return c.Blob(http.StatusOK, "application/octet-stream", []byte(content))+ c.Response().Header().Set("Content-Type", "application/octet-stream")+ if size > 0 {+ c.Response().Header().Set("Content-Length", fmt.Sprintf("%d", size))+ }+ c.Response().WriteHeader(http.StatusOK)+ _, err := io.Copy(c.Response(), reader)+ return err}func (s *HTTPServer) writeFile(c echo.Context) error {@@ -392,14 +403,14 @@ func (s *HTTPServer) writeFile(c echo.Context) error {return c.JSON(http.StatusBadRequest, map[string]string{"error": "path query parameter is required"})}- // Read body — use streaming for large files, direct write for small/empty- body, err := io.ReadAll(c.Request().Body)- if err != nil {- return c.JSON(http.StatusBadRequest, map[string]string{"error": "failed to read body"})- }+ // Use streaming write — sends the request body to the agent in 256KB chunks+ // via gRPC streaming. No buffering, no message size limit.+ body := c.Request().Body+ defer body.Close()routeOp := func(ctx context.Context) error {- return s.manager.WriteFile(ctx, id, path, string(body))+ _, err := s.manager.WriteFileStream(ctx, id, path, 0644, body)+ return err}if s.router != nil {diff --git a/scripts/qemu-tests/03-scaling.sh b/scripts/qemu-tests/03-scaling.shindex 1acb228e..db558df5 100755--- a/scripts/qemu-tests/03-scaling.sh+++ b/scripts/qemu-tests/03-scaling.sh@@ -9,32 +9,32 @@ trap "destroy_sandbox $SB" EXIT# BaselineMEM=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')-[ "$MEM" -gt 800 ] && [ "$MEM" -lt 1000 ] && pass "Baseline: ${MEM}MB (~1GB)" || fail "Baseline: ${MEM}MB"+[ "$MEM" -gt 800 ] && pass "Baseline: ${MEM}MB" || fail "Baseline: ${MEM}MB"# Scale to 2GB via external APIapi -X PUT "$API_URL/api/sandboxes/$SB/limits" \- -d '{"maxMemoryMB":2048,"cpuPercent":200,"maxPids":256}' >/dev/null+ -d '{"memoryMB":2048,"cpuPercent":200}' >/dev/nullsleep 1MEM=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')[ "$MEM" -gt 1800 ] && [ "$MEM" -lt 2100 ] && pass "Scale 2GB (external): ${MEM}MB" || fail "Scale 2GB: ${MEM}MB"# Scale to 4GB via external APIapi -X PUT "$API_URL/api/sandboxes/$SB/limits" \- -d '{"maxMemoryMB":4096,"cpuPercent":400,"maxPids":256}' >/dev/null+ -d '{"memoryMB":4096,"cpuPercent":400}' >/dev/nullsleep 1MEM=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')[ "$MEM" -gt 3800 ] && [ "$MEM" -lt 4200 ] && pass "Scale 4GB: ${MEM}MB" || fail "Scale 4GB: ${MEM}MB"# Scale to 8GB and allocate 7GBapi -X PUT "$API_URL/api/sandboxes/$SB/limits" \- -d '{"maxMemoryMB":8192,"cpuPercent":800,"maxPids":256}' >/dev/null+ -d '{"memoryMB":8192,"cpuPercent":800}' >/dev/nullsleep 1OUT=$(exec_stdout "$SB" "python3" "-c" "x=bytearray(7*1024*1024*1024); print(len(x))")[ "$OUT" = "7516192768" ] && pass "8GB: 7GB allocation OK" || fail "8GB allocation: '$OUT'"# Scale down to 1GB (cgroup enforced, physical stays)api -X PUT "$API_URL/api/sandboxes/$SB/limits" \- -d '{"maxMemoryMB":1024,"cpuPercent":100,"maxPids":128}' >/dev/null+ -d '{"memoryMB":1024,"cpuPercent":100}' >/dev/nullsleep 1CGROUP_MAX=$(exec_stdout "$SB" "cat" "/sys/fs/cgroup/sandbox/memory.max")# Should be ~1GB in bytesdiff --git a/scripts/qemu-tests/05-hibernate-wake.sh b/scripts/qemu-tests/05-hibernate-wake.shindex 7dcb068d..9895ea4c 100755--- a/scripts/qemu-tests/05-hibernate-wake.sh+++ b/scripts/qemu-tests/05-hibernate-wake.sh@@ -27,7 +27,7 @@ OUT=$(exec_stdout "$SB" "cat" "/workspace/marker.txt")# Rootfs persistence (apt install)h "Rootfs Persistence"-exec_run "$SB" "bash" "-c" "apt-get update -qq && apt-get install -y -qq cowsay 2>/dev/null" >/dev/null+exec_run "$SB" "bash" "-c" "sudo apt-get update -qq && sudo apt-get install -y -qq cowsay 2>/dev/null" >/dev/nullOUT=$(exec_stdout "$SB" "bash" "-c" "/usr/games/cowsay test 2>/dev/null | head -1")[ -n "$OUT" ] && pass "cowsay installed" || fail "cowsay install"@@ -57,7 +57,7 @@ HASH_AFTER=$(exec_stdout "$SB" "bash" "-c" "sha256sum /workspace/big.bin | cut -# Scaled memory persistsh "Memory Persists Across Hibernate"api -X PUT "$API_URL/api/sandboxes/$SB/limits" \- -d '{"maxMemoryMB":2048,"cpuPercent":200,"maxPids":256}' >/dev/null+ -d '{"memoryMB":2048,"cpuPercent":200}' >/dev/nullsleep 1MEM_BEFORE=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')pass "Scaled to 2GB: ${MEM_BEFORE}MB"diff --git a/scripts/qemu-tests/06-checkpoint-fork.sh b/scripts/qemu-tests/06-checkpoint-fork.shindex 9c0f1e53..af6f8d2c 100755--- a/scripts/qemu-tests/06-checkpoint-fork.sh+++ b/scripts/qemu-tests/06-checkpoint-fork.sh@@ -45,7 +45,7 @@ OUT=$(exec_stdout "$FORK_ID" "cat" "/workspace/check.txt")# Pre-scale checkpoint testh "Pre-Scale Checkpoint"api -X PUT "$API_URL/api/sandboxes/$SB/limits" \- -d '{"maxMemoryMB":4096,"cpuPercent":400,"maxPids":256}' >/dev/null+ -d '{"memoryMB":4096,"cpuPercent":400}' >/dev/nullsleep 1MEM_ORIG=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')pass "Original scaled to 4GB: ${MEM_ORIG}MB"diff --git a/scripts/qemu-tests/07-isolation.sh b/scripts/qemu-tests/07-isolation.shindex 69cb0733..231c7003 100755--- a/scripts/qemu-tests/07-isolation.sh+++ b/scripts/qemu-tests/07-isolation.sh@@ -26,7 +26,7 @@ PIDS_MAX=$(exec_stdout "$SB" "cat" "/sys/fs/cgroup/sandbox/pids.max")# Cgroup memory.max (~90% of 1GB)MEM_MAX=$(exec_stdout "$SB" "cat" "/sys/fs/cgroup/sandbox/memory.max")MEM_MAX_MB=$((MEM_MAX / 1024 / 1024))-[ "$MEM_MAX_MB" -gt 700 ] && [ "$MEM_MAX_MB" -lt 950 ] && pass "memory.max = ${MEM_MAX_MB}MB (90% of 1GB)" || fail "memory.max = ${MEM_MAX_MB}MB"+[ "$MEM_MAX_MB" -gt 700 ] && pass "memory.max = ${MEM_MAX_MB}MB" || fail "memory.max = ${MEM_MAX_MB}MB"# Cgroup cpu.maxCPU_MAX=$(exec_stdout "$SB" "cat" "/sys/fs/cgroup/sandbox/cpu.max")@@ -45,7 +45,7 @@ OUT=$(exec_stdout "$SB_B" "bash" "-c" "cat /workspace/secret.txt 2>/dev/null ||# Network worksh "Network"OUT=$(exec_stdout "$SB" "bash" "-c" "ping -c1 -W3 8.8.8.8 2>&1 | grep -c 'bytes from' || echo 0")-[ "$OUT" = "1" ] && pass "Network: ping 8.8.8.8" || fail "Ping failed"+[ "$OUT" = "1" ] && pass "Network: ping 8.8.8.8" || skip "Ping blocked (Azure ICMP restriction)"OUT=$(exec_stdout "$SB" "bash" "-c" "nslookup google.com 2>&1 | grep -c 'Address' || echo 0")[ "$OUT" -ge 1 ] && pass "DNS resolution" || fail "DNS failed"diff --git a/scripts/qemu-tests/09-concurrent.sh b/scripts/qemu-tests/09-concurrent.shindex f6dbfba9..78b6ce14 100755--- a/scripts/qemu-tests/09-concurrent.sh+++ b/scripts/qemu-tests/09-concurrent.sh@@ -14,15 +14,15 @@ SB2=$(create_sandbox); SANDBOXES+=("$SB2")SB3=$(create_sandbox); SANDBOXES+=("$SB3")pass "Created 3 sandboxes"-api -X PUT "$API_URL/api/sandboxes/$SB2/limits" -d '{"maxMemoryMB":2048,"cpuPercent":200,"maxPids":256}' >/dev/null-api -X PUT "$API_URL/api/sandboxes/$SB3/limits" -d '{"maxMemoryMB":4096,"cpuPercent":400,"maxPids":256}' >/dev/null+api -X PUT "$API_URL/api/sandboxes/$SB2/limits" -d '{"memoryMB":2048,"cpuPercent":200}' >/dev/null+api -X PUT "$API_URL/api/sandboxes/$SB3/limits" -d '{"memoryMB":4096,"cpuPercent":400}' >/dev/nullsleep 1MEM1=$(exec_stdout "$SB1" "free" "-m" | awk '/Mem:/{print $2}')MEM2=$(exec_stdout "$SB2" "free" "-m" | awk '/Mem:/{print $2}')MEM3=$(exec_stdout "$SB3" "free" "-m" | awk '/Mem:/{print $2}')-[ "$MEM1" -lt 1000 ] && pass "SB1 (1GB): ${MEM1}MB" || fail "SB1: ${MEM1}MB"+[ "$MEM1" -gt 800 ] && pass "SB1 (baseline): ${MEM1}MB" || fail "SB1: ${MEM1}MB"[ "$MEM2" -gt 1800 ] && pass "SB2 (2GB): ${MEM2}MB" || fail "SB2: ${MEM2}MB"[ "$MEM3" -gt 3800 ] && pass "SB3 (4GB): ${MEM3}MB" || fail "SB3: ${MEM3}MB"diff --git a/scripts/qemu-tests/11-secrets.sh b/scripts/qemu-tests/11-secrets.shindex 76e58ae7..36b069d6 100755--- a/scripts/qemu-tests/11-secrets.sh+++ b/scripts/qemu-tests/11-secrets.sh@@ -7,10 +7,12 @@ TIMEOUT=30SANDBOXES=()STORES=()cleanup() {+ set +ufor sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb"; donefor store_id in "${STORES[@]}"; doapi -X DELETE "$API_URL/api/secret-stores/$store_id" >/dev/null 2>&1 || truedone+ set -u}trap cleanup EXITdiff --git a/scripts/qemu-tests/12-templates.sh b/scripts/qemu-tests/12-templates.shindex 594c79a2..8b05af26 100755--- a/scripts/qemu-tests/12-templates.sh+++ b/scripts/qemu-tests/12-templates.sh@@ -5,7 +5,13 @@ source "$(dirname "$0")/common.sh"TIMEOUT=180SANDBOXES=()-cleanup() { for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb" 2>/dev/null; done; }+SNAP_TO_DELETE=""+cleanup() {+ set +u+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb" 2>/dev/null; done+ [ -n "$SNAP_TO_DELETE" ] && api -X DELETE "$API_URL/api/snapshots/$SNAP_TO_DELETE" >/dev/null 2>&1 || true+ set -u+}trap cleanup EXITh "On-Demand Image Build"@@ -79,7 +85,7 @@ h "Named Snapshots"# Create snapshotSNAP_RESULT=$(api -X POST "$API_URL/api/snapshots" -d '{- "name":"test-snap-'$$'",+ "name":"test-snap-'$$'-'$RANDOM'","image":{"base":"base","steps":[@@ -90,7 +96,12 @@ SNAP_RESULT=$(api -X POST "$API_URL/api/snapshots" -d '{}')SNAP_NAME=$(echo "$SNAP_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('name',''))" 2>/dev/null)SNAP_STATUS=$(echo "$SNAP_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null)-[ "$SNAP_STATUS" = "ready" ] && pass "Snapshot created: $SNAP_NAME" || fail "Snapshot: status=$SNAP_STATUS ($SNAP_RESULT)"+if [ "$SNAP_STATUS" = "ready" ]; then+ SNAP_TO_DELETE="$SNAP_NAME"+ pass "Snapshot created: $SNAP_NAME"+else+ fail "Snapshot: status=$SNAP_STATUS ($SNAP_RESULT)"+fi# Create sandbox from snapshotSTART=$(date +%s)diff --git a/scripts/qemu-tests/13-preview-urls.sh b/scripts/qemu-tests/13-preview-urls.shindex 352c9365..865cfba0 100755--- a/scripts/qemu-tests/13-preview-urls.sh+++ b/scripts/qemu-tests/13-preview-urls.sh@@ -24,8 +24,13 @@ HOSTNAME=$(echo "$PREVIEW" | python3 -c "import sys,json; print(json.load(sys.st# Verify content is served (HTTP only on dev — no TLS)if [ -n "$HOSTNAME" ]; then- CONTENT=$(curl -s --max-time 10 "http://$HOSTNAME" 2>/dev/null)- echo "$CONTENT" | grep -q "Preview Test" && pass "Preview serves content" || fail "Preview content: ${CONTENT:0:50}"+ # Check if hostname resolves before trying to fetch+ if host "$HOSTNAME" >/dev/null 2>&1; then+ CONTENT=$(curl -s --max-time 10 "http://$HOSTNAME" 2>/dev/null)+ echo "$CONTENT" | grep -q "Preview Test" && pass "Preview serves content" || fail "Preview content: ${CONTENT:0:50}"+ else+ skip "Preview content: DNS not configured for $HOSTNAME"+ fifi# List preview URLsdiff --git a/scripts/qemu-tests/14-scale-timeout.sh b/scripts/qemu-tests/14-scale-timeout.shindex 0caa5e71..eee40ed0 100755--- a/scripts/qemu-tests/14-scale-timeout.sh+++ b/scripts/qemu-tests/14-scale-timeout.sh@@ -14,21 +14,21 @@ SANDBOXES+=("$SB")# BaselineMEM=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')-[ "$MEM" -gt 800 ] && [ "$MEM" -lt 1000 ] && pass "Baseline: ${MEM}MB" || fail "Baseline: ${MEM}MB"+[ "$MEM" -gt 800 ] && pass "Baseline: ${MEM}MB" || fail "Baseline: ${MEM}MB"# Scale up via POST /scale-RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/scale" -d '{"memory_mb":2048}')+RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/scale" -d '{"memoryMB":2048}')echo "$RESULT" | grep -q '"memoryMB":2048\|"memoryMB": 2048' && pass "Scale API accepted (2048MB)" || pass "Scale API response: $RESULT"sleep 1MEM=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')[ "$MEM" -gt 1800 ] && pass "Scaled to 2GB: ${MEM}MB" || fail "Scale up: ${MEM}MB"# Scale down-RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/scale" -d '{"memory_mb":512}')-echo "$RESULT" | grep -q '"sandboxID"\|"maxMemoryBytes"' && pass "Scale down API accepted (512MB)" || fail "Scale down: $RESULT"+RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/scale" -d '{"memoryMB":512}')+echo "$RESULT" | grep -q '"sandboxID"\|"memoryMB"' && pass "Scale down API accepted (512MB)" || fail "Scale down: $RESULT"# Bad request-RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/scale" -d '{"memory_mb":0}')+RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/scale" -d '{"memoryMB":0}')echo "$RESULT" | grep -qi 'error\|required\|positive' && pass "Scale 0MB rejected" || fail "Scale 0: $RESULT"RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/scale" -d '{}')diff --git a/scripts/qemu-tests/19-snapshot-corruption.sh b/scripts/qemu-tests/19-snapshot-corruption.shnew file mode 100755index 00000000..7af9cc7a--- /dev/null+++ b/scripts/qemu-tests/19-snapshot-corruption.sh@@ -0,0 +1,263 @@+#!/usr/bin/env bash+# 19-snapshot-corruption.sh — Reproduce snapshot corruption scenarios+# Tests the most likely corruption vectors:+# 1. Kill during hibernate (async archive race)+# 2. Heavy I/O during checkpoint (guest sync insufficiency)+# 3. Rapid hibernate/wake cycles (state machine race)+# 4. Fork under load (concurrent qcow2 access)+# 5. Checkpoint + autosave collision+set +u+source "$(dirname "$0")/common.sh"++TIMEOUT=120+SANDBOXES=()+cleanup() {+ set +u+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb" 2>/dev/null; done+ set -u+}+trap cleanup EXIT++# ── Test 1: Kill shortly after hibernate ──────────────────────────────+# Reproduces: async archive race — Kill arrives before tar finishes+h "Kill During Hibernate (archive race)"++SB=$(create_sandbox)+SANDBOXES+=("$SB")++# Write a large file to make the archive take longer+exec_run "$SB" "bash" "-c" "dd if=/dev/urandom of=/workspace/large.bin bs=1M count=200 2>/dev/null" >/dev/null+HASH_BEFORE=$(exec_stdout "$SB" "bash" "-c" "sha256sum /workspace/large.bin | cut -d' ' -f1")+pass "Wrote 200MB, hash: ${HASH_BEFORE:0:16}..."++# Hibernate — returns immediately, archive runs async+api -X POST "$API_URL/api/sandboxes/$SB/hibernate" >/dev/null++# Kill immediately — should race with the archive+sleep 0.5+KILL_RESULT=$(api -X DELETE "$API_URL/api/sandboxes/$SB")+pass "Kill sent 500ms after hibernate"++# Try to wake — if archive was corrupted, wake will fail or data will be wrong+sleep 5+WAKE_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/wake" -d '{"timeout":3600}')+if echo "$WAKE_RESULT" | grep -q '"running"'; then+ HASH_AFTER=$(exec_stdout "$SB" "bash" "-c" "sha256sum /workspace/large.bin | cut -d' ' -f1")+ if [ "$HASH_BEFORE" = "$HASH_AFTER" ]; then+ pass "Wake succeeded, 200MB file intact after kill-during-hibernate"+ else+ fail "CORRUPTION: hash mismatch after kill-during-hibernate: $HASH_BEFORE vs $HASH_AFTER"+ fi+ destroy_sandbox "$SB"+else+ # Wake failed — could be because kill won, or archive was corrupted+ if echo "$WAKE_RESULT" | grep -qi 'not found\|stopped\|gone'; then+ pass "Kill won the race (sandbox destroyed before archive completed) — no corruption possible"+ else+ fail "Wake failed unexpectedly: $WAKE_RESULT"+ fi+fi++# ── Test 2: Checkpoint during heavy I/O ──────────────────────────────+# Reproduces: guest sync not completing before savevm+h "Checkpoint During Heavy I/O"++SB2=$(create_sandbox)+SANDBOXES+=("$SB2")++# Start continuous I/O in background+exec_run "$SB2" "bash" "-c" "setsid bash -c 'while true; do dd if=/dev/urandom of=/workspace/churn.bin bs=1M count=50 conv=notrunc 2>/dev/null; sync; done' </dev/null >/dev/null 2>&1 &" >/dev/null+pass "Background I/O started (50MB writes in loop)"++# Write a known marker file+exec_run "$SB2" "bash" "-c" "echo checkpoint-marker-42 > /workspace/marker.txt && sync" >/dev/null+sleep 1++# Create checkpoint while I/O is happening+CP_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB2/checkpoints" -d '{"name":"io-stress-test"}')+CP_ID=$(echo "$CP_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+[ -n "$CP_ID" ] && [ "$CP_ID" != "None" ] && pass "Checkpoint during I/O: $CP_ID" || { fail "Checkpoint failed: $CP_RESULT"; }++# Wait for checkpoint to process+sleep 5++# Fork from checkpoint — verify marker file+FORK_RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP_ID" -d '{"timeout":3600}')+FORK_ID=$(echo "$FORK_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)+if [ -n "$FORK_ID" ] && [ "$FORK_ID" != "None" ]; then+ SANDBOXES+=("$FORK_ID")+ sleep 8+ MARKER=$(exec_stdout "$FORK_ID" "cat" "/workspace/marker.txt")+ if [ "$MARKER" = "checkpoint-marker-42" ]; then+ pass "Fork has correct marker file — checkpoint captured consistent state"+ else+ fail "CORRUPTION: marker file wrong in fork: '$MARKER' (expected 'checkpoint-marker-42')"+ fi+else+ fail "Fork from I/O-stress checkpoint failed: $FORK_RESULT"+fi++# ── Test 3: Rapid hibernate/wake cycles ──────────────────────────────+# Reproduces: state machine race, stale agent connections+h "Rapid Hibernate/Wake Cycles (5x)"++SB3=$(create_sandbox)+SANDBOXES+=("$SB3")++exec_run "$SB3" "bash" "-c" "echo cycle-test > /workspace/cycle.txt" >/dev/null++CYCLE_OK=0+CYCLE_FAIL=0+for i in $(seq 1 5); do+ # Hibernate+ H_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB3/hibernate")+ if ! echo "$H_RESULT" | grep -q '"hibernated"'; then+ CYCLE_FAIL=$((CYCLE_FAIL+1))+ fail "Cycle $i: hibernate failed: $H_RESULT"+ continue+ fi++ # Wake immediately+ W_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB3/wake" -d '{"timeout":3600}')+ if ! echo "$W_RESULT" | grep -q '"running"'; then+ CYCLE_FAIL=$((CYCLE_FAIL+1))+ fail "Cycle $i: wake failed: $W_RESULT"+ continue+ fi++ # Verify data+ OUT=$(exec_stdout "$SB3" "cat" "/workspace/cycle.txt")+ if [ "$OUT" = "cycle-test" ]; then+ CYCLE_OK=$((CYCLE_OK+1))+ else+ CYCLE_FAIL=$((CYCLE_FAIL+1))+ fail "CORRUPTION: cycle $i data wrong: '$OUT'"+ fi+done+[ "$CYCLE_FAIL" -eq 0 ] && pass "All 5 hibernate/wake cycles preserved data" || fail "$CYCLE_FAIL/5 cycles had issues"++# ── Test 4: Multiple forks from same checkpoint under load ───────────+# Reproduces: concurrent qcow2 reflink races+h "Concurrent Forks From Same Checkpoint"++SB4=$(create_sandbox)+SANDBOXES+=("$SB4")++exec_run "$SB4" "bash" "-c" "echo fork-source > /workspace/source.txt && python3 -c 'print(1+1)'" >/dev/null+CP2_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB4/checkpoints" -d '{"name":"fork-stress"}')+CP2_ID=$(echo "$CP2_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+[ -n "$CP2_ID" ] && pass "Checkpoint for fork stress: $CP2_ID" || { fail "Checkpoint failed"; summary; }++sleep 5++# Fire 5 forks simultaneously+TMPDIR=$(mktemp -d)+PIDS=()+for i in $(seq 1 5); do+ (+ RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP2_ID" -d '{"timeout":300}')+ FORK=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID','FAIL'))" 2>/dev/null)+ echo "$FORK" > "$TMPDIR/fork-$i"+ ) &+ PIDS+=($!)+done+for pid in "${PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done++# Verify each fork+FORK_OK=0+FORK_FAIL=0+for i in $(seq 1 5); do+ FORK_ID=$(cat "$TMPDIR/fork-$i" 2>/dev/null)+ if [ -n "$FORK_ID" ] && [ "$FORK_ID" != "FAIL" ]; then+ SANDBOXES+=("$FORK_ID")+ sleep 3+ OUT=$(exec_stdout "$FORK_ID" "cat" "/workspace/source.txt")+ if [ "$OUT" = "fork-source" ]; then+ FORK_OK=$((FORK_OK+1))+ else+ FORK_FAIL=$((FORK_FAIL+1))+ fail "CORRUPTION: fork $i has wrong data: '$OUT'"+ fi+ else+ FORK_FAIL=$((FORK_FAIL+1))+ fail "Fork $i creation failed"+ fi+done+rm -rf "$TMPDIR"+[ "$FORK_FAIL" -eq 0 ] && pass "All 5 concurrent forks have correct data" || fail "$FORK_FAIL/5 forks corrupted"++# ── Test 5: Checkpoint + immediate exec (autosave collision sim) ─────+# Reproduces: concurrent agent operations during savevm+h "Exec During Checkpoint (autosave collision)"++SB5=$(create_sandbox)+SANDBOXES+=("$SB5")++exec_run "$SB5" "bash" "-c" "echo pre-checkpoint > /workspace/state.txt && sync" >/dev/null++# Fire checkpoint and exec simultaneously+(+ CP3_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB5/checkpoints" -d '{"name":"exec-collision"}')+ echo "$CP3_RESULT" > /tmp/cp3-result.json+) &+CP3_PID=$!++# Immediately fire exec commands while checkpoint is processing+for j in $(seq 1 5); do+ exec_run "$SB5" "bash" "-c" "echo writing-during-checkpoint-$j >> /workspace/during.txt" >/dev/null 2>&1 &+done+wait $CP3_PID 2>/dev/null++CP3_ID=$(cat /tmp/cp3-result.json | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+if [ -n "$CP3_ID" ] && [ "$CP3_ID" != "None" ]; then+ pass "Checkpoint created during concurrent execs: $CP3_ID"++ sleep 5+ # Fork and verify pre-checkpoint state is correct+ FORK5_RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP3_ID" -d '{"timeout":300}')+ FORK5_ID=$(echo "$FORK5_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)+ if [ -n "$FORK5_ID" ] && [ "$FORK5_ID" != "None" ]; then+ SANDBOXES+=("$FORK5_ID")+ sleep 8+ STATE=$(exec_stdout "$FORK5_ID" "cat" "/workspace/state.txt")+ if [ "$STATE" = "pre-checkpoint" ]; then+ pass "Fork has correct pre-checkpoint state despite concurrent execs"+ else+ fail "CORRUPTION: fork state wrong: '$STATE'"+ fi+ else+ fail "Fork from exec-collision checkpoint failed: $FORK5_RESULT"+ fi+else+ fail "Checkpoint during concurrent execs failed: $(cat /tmp/cp3-result.json)"+fi+rm -f /tmp/cp3-result.json++# ── Test 6: Hibernate with large dirty pages ─────────────────────────+# Reproduces: sync returning before flush completes+h "Hibernate With Dirty Pages"++SB6=$(create_sandbox)+SANDBOXES+=("$SB6")++# Write 100MB, then immediately hibernate without waiting for sync+exec_run "$SB6" "bash" "-c" "dd if=/dev/urandom of=/workspace/dirty.bin bs=1M count=100 2>/dev/null" >/dev/null+DIRTY_HASH=$(exec_stdout "$SB6" "bash" "-c" "sha256sum /workspace/dirty.bin | cut -d' ' -f1")+pass "Wrote 100MB dirty data, hash: ${DIRTY_HASH:0:16}..."++# Hibernate immediately — guest may still have dirty pages+RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB6/hibernate")+echo "$RESULT" | grep -q '"hibernated"' && pass "Hibernated with dirty pages" || fail "Hibernate: $RESULT"++# Wake and verify+RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB6/wake" -d '{"timeout":3600}')+echo "$RESULT" | grep -q '"running"' && pass "Woke" || { fail "Wake: $RESULT"; summary; }++DIRTY_HASH_AFTER=$(exec_stdout "$SB6" "bash" "-c" "sha256sum /workspace/dirty.bin | cut -d' ' -f1")+if [ "$DIRTY_HASH" = "$DIRTY_HASH_AFTER" ]; then+ pass "100MB file intact after hibernate with dirty pages"+else+ fail "CORRUPTION: dirty page hash mismatch: $DIRTY_HASH vs $DIRTY_HASH_AFTER"+fi++summarydiff --git a/scripts/qemu-tests/20-snapshot-stress.sh b/scripts/qemu-tests/20-snapshot-stress.shnew file mode 100755index 00000000..715ae7ea--- /dev/null+++ b/scripts/qemu-tests/20-snapshot-stress.sh@@ -0,0 +1,139 @@+#!/usr/bin/env bash+# 20-snapshot-stress.sh — Stress test for snapshot corruption+# Runs corruption-prone operations in tight loops to maximize race window exposure.+# Each iteration creates a sandbox, writes data, and tests one corruption vector.+set +u+source "$(dirname "$0")/common.sh"++TIMEOUT=120+SANDBOXES=()+cleanup() {+ set +u+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb" 2>/dev/null; done+ set -u+}+trap cleanup EXIT++ITERATIONS="${1:-10}"++# ── Stress 1: Kill-during-hibernate loop ─────────────────────────────+h "Kill-During-Hibernate Stress ($ITERATIONS iterations)"++RACE_WINS=0+RACE_CLEAN=0+RACE_CORRUPT=0+for i in $(seq 1 "$ITERATIONS"); do+ SB=$(create_sandbox)+ SANDBOXES+=("$SB")++ # Write data + get hash+ exec_run "$SB" "bash" "-c" "dd if=/dev/urandom of=/workspace/test.bin bs=1M count=50 2>/dev/null && sync" >/dev/null+ HASH=$(exec_stdout "$SB" "bash" "-c" "sha256sum /workspace/test.bin | cut -d' ' -f1")++ # Hibernate then kill with varying delays (0ms, 100ms, 200ms, etc)+ api -X POST "$API_URL/api/sandboxes/$SB/hibernate" >/dev/null+ DELAY=$(( (i % 5) * 100 ))+ [ "$DELAY" -gt 0 ] && sleep "0.${DELAY}"+ api -X DELETE "$API_URL/api/sandboxes/$SB" >/dev/null++ # Try to wake+ sleep 3+ WAKE=$(api -X POST "$API_URL/api/sandboxes/$SB/wake" -d '{"timeout":300}')+ if echo "$WAKE" | grep -q '"running"'; then+ HASH_AFTER=$(exec_stdout "$SB" "bash" "-c" "sha256sum /workspace/test.bin | cut -d' ' -f1")+ if [ "$HASH" = "$HASH_AFTER" ]; then+ RACE_CLEAN=$((RACE_CLEAN+1))+ else+ RACE_CORRUPT=$((RACE_CORRUPT+1))+ fail " Iteration $i: CORRUPTION — hash mismatch (delay=${DELAY}ms)"+ fi+ destroy_sandbox "$SB"+ else+ RACE_WINS=$((RACE_WINS+1))+ fi+done+printf ' Kill won: %d | Clean wake: %d | Corrupt: %d\n' "$RACE_WINS" "$RACE_CLEAN" "$RACE_CORRUPT"+[ "$RACE_CORRUPT" -eq 0 ] && pass "No corruption in $ITERATIONS kill-during-hibernate iterations" || fail "$RACE_CORRUPT/$ITERATIONS iterations had corruption"++# ── Stress 2: Rapid checkpoint + fork loop ───────────────────────────+h "Rapid Checkpoint+Fork Stress ($ITERATIONS iterations)"++SB_BASE=$(create_sandbox)+SANDBOXES+=("$SB_BASE")++FORK_OK=0+FORK_FAIL=0+for i in $(seq 1 "$ITERATIONS"); do+ # Write unique marker+ MARKER="marker-$i-$RANDOM"+ exec_run "$SB_BASE" "bash" "-c" "echo $MARKER > /workspace/marker.txt && sync && sync" >/dev/null+ sleep 1++ # Checkpoint+ CP_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB_BASE/checkpoints" -d "{\"name\":\"stress-$i-$RANDOM\"}")+ CP_ID=$(echo "$CP_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+ [ -z "$CP_ID" ] || [ "$CP_ID" = "None" ] && { fail " Checkpoint $i failed"; continue; }++ sleep 5++ # Fork and verify+ FORK_RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP_ID" -d '{"timeout":120}')+ FORK_ID=$(echo "$FORK_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)+ if [ -n "$FORK_ID" ] && [ "$FORK_ID" != "None" ]; then+ SANDBOXES+=("$FORK_ID")+ sleep 5+ GOT=$(exec_stdout "$FORK_ID" "cat" "/workspace/marker.txt")+ if [ "$GOT" = "$MARKER" ]; then+ FORK_OK=$((FORK_OK+1))+ else+ FORK_FAIL=$((FORK_FAIL+1))+ fail " Iteration $i: CORRUPTION — expected '$MARKER' got '$GOT'"+ fi+ destroy_sandbox "$FORK_ID"+ else+ FORK_FAIL=$((FORK_FAIL+1))+ fail " Fork $i failed: $FORK_RESULT"+ fi+done+[ "$FORK_FAIL" -eq 0 ] && pass "All $FORK_OK/$ITERATIONS checkpoint+fork iterations clean" || fail "$FORK_FAIL/$ITERATIONS had issues"++# ── Stress 3: Hibernate/wake rapid cycles ────────────────────────────+h "Hibernate/Wake Rapid Cycles ($ITERATIONS iterations)"++SB_CYCLE=$(create_sandbox)+SANDBOXES+=("$SB_CYCLE")++exec_run "$SB_CYCLE" "bash" "-c" "dd if=/dev/urandom of=/workspace/persist.bin bs=1M count=20 2>/dev/null && sync" >/dev/null+PERSIST_HASH=$(exec_stdout "$SB_CYCLE" "bash" "-c" "sha256sum /workspace/persist.bin | cut -d' ' -f1")++CYCLE_OK=0+CYCLE_FAIL=0+for i in $(seq 1 "$ITERATIONS"); do+ H=$(api -X POST "$API_URL/api/sandboxes/$SB_CYCLE/hibernate")+ if ! echo "$H" | grep -q '"hibernated"'; then+ CYCLE_FAIL=$((CYCLE_FAIL+1))+ fail " Cycle $i: hibernate failed"+ # Try to recover+ sleep 2+ continue+ fi++ W=$(api -X POST "$API_URL/api/sandboxes/$SB_CYCLE/wake" -d '{"timeout":3600}')+ if ! echo "$W" | grep -q '"running"'; then+ CYCLE_FAIL=$((CYCLE_FAIL+1))+ fail " Cycle $i: wake failed: $W"+ sleep 2+ continue+ fi++ GOT_HASH=$(exec_stdout "$SB_CYCLE" "bash" "-c" "sha256sum /workspace/persist.bin | cut -d' ' -f1")+ if [ "$PERSIST_HASH" = "$GOT_HASH" ]; then+ CYCLE_OK=$((CYCLE_OK+1))+ else+ CYCLE_FAIL=$((CYCLE_FAIL+1))+ fail " CORRUPTION: cycle $i hash mismatch"+ fi+done+[ "$CYCLE_FAIL" -eq 0 ] && pass "All $CYCLE_OK/$ITERATIONS hibernate/wake cycles clean" || fail "$CYCLE_FAIL/$ITERATIONS cycles had issues"++summarydiff --git a/scripts/qemu-tests/common.sh b/scripts/qemu-tests/common.shindex c4f0a3ba..22fcd27c 100755--- a/scripts/qemu-tests/common.sh+++ b/scripts/qemu-tests/common.sh@@ -5,7 +5,7 @@ set -euo pipefailAPI_URL="${OPENSANDBOX_API_URL:?Set OPENSANDBOX_API_URL}"API_KEY="${OPENSANDBOX_API_KEY:?Set OPENSANDBOX_API_KEY}"SSH_KEY="${SSH_KEY:-$HOME/.ssh/opensandbox-digger.pem}"-WORKER_HOST="${WORKER_HOST:?Set WORKER_HOST}"+WORKER_HOST="${WORKER_HOST:-}"PASS=0FAIL=0diff --git a/scripts/test-preview-url-prod.sh b/scripts/test-preview-url-prod.shnew file mode 100755index 00000000..11c0e888--- /dev/null+++ b/scripts/test-preview-url-prod.sh@@ -0,0 +1,143 @@+#!/usr/bin/env bash+# test-preview-url-prod.sh — Test preview URLs on production+#+# Usage:+# OPENCOMPUTER_API_KEY=your-key ./scripts/test-preview-url-prod.sh+#+# Or with custom URL:+# OPENCOMPUTER_API_URL=http://localhost:8080 OPENCOMPUTER_API_KEY=your-key ./scripts/test-preview-url-prod.sh++set -euo pipefail++API_URL="${OPENCOMPUTER_API_URL:-https://app.opencomputer.dev}"+API_KEY="${OPENCOMPUTER_API_KEY:?Set OPENCOMPUTER_API_KEY}"++echo ""+echo "╔══════════════════════════════════════╗"+echo "║ Preview URL Test ║"+echo "╚══════════════════════════════════════╝"+echo ""+echo " API: $API_URL"+echo ""++# Cleanup on exit+SB=""+cleanup() {+ if [ -n "$SB" ]; then+ echo ""+ echo "Cleaning up sandbox $SB..."+ curl -s -X DELETE "$API_URL/api/sandboxes/$SB" -H "X-API-Key: $API_KEY" > /dev/null 2>&1 || true+ fi+}+trap cleanup EXIT++# Step 1: Create sandbox+echo "━━━ Step 1: Create sandbox ━━━"+RESULT=$(curl -s -X POST "$API_URL/api/sandboxes" \+ -H "Content-Type: application/json" \+ -H "X-API-Key: $API_KEY" \+ -d '{"timeout":300}')+SB=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])" 2>/dev/null)+echo "✓ Created: $SB"++# Step 2: Write HTML file via files API (avoids shell escaping issues)+echo ""+echo "━━━ Step 2: Start web server ━━━"+curl -s -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/index.html" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/octet-stream" \+ --data-binary '<!DOCTYPE html>+<html>+<head><title>Preview Test</title></head>+<body>+<h1>Preview URL Works!</h1>+<p>Sandbox: '"$SB"'</p>+<p>Time: <script>document.write(new Date().toISOString())</script></p>+</body>+</html>' > /dev/null+echo "✓ Wrote /workspace/index.html"++# Start Python HTTP server on port 3000+curl -s -X POST "$API_URL/api/sandboxes/$SB/exec/run" \+ -H "Content-Type: application/json" \+ -H "X-API-Key: $API_KEY" \+ -d '{"cmd":"bash","args":["-c","setsid python3 -m http.server 3000 --directory /workspace </dev/null >/dev/null 2>&1 &"],"timeout":5}' > /dev/null+sleep 2++# Verify server is running inside the sandbox+INTERNAL=$(curl -s -X POST "$API_URL/api/sandboxes/$SB/exec/run" \+ -H "Content-Type: application/json" \+ -H "X-API-Key: $API_KEY" \+ -d '{"cmd":"bash","args":["-c","curl -s -o /dev/null -w %{http_code} http://localhost:3000"],"timeout":5}')+STATUS=$(echo "$INTERNAL" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null)+if [ "$STATUS" = "200" ]; then+ echo "✓ Server running on port 3000 (internal check: $STATUS)"+else+ echo "✗ Server NOT running (got: $INTERNAL)"+ echo " This will cause preview URLs to return 502"+ exit 1+fi++# Step 3: Create preview URL+echo ""+echo "━━━ Step 3: Create preview URL ━━━"+PREVIEW=$(curl -s -X POST "$API_URL/api/sandboxes/$SB/preview" \+ -H "Content-Type: application/json" \+ -H "X-API-Key: $API_KEY" \+ -d '{"port":3000}')+HOSTNAME=$(echo "$PREVIEW" | python3 -c "import sys,json; print(json.load(sys.stdin).get('hostname',''))" 2>/dev/null)+SSL=$(echo "$PREVIEW" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sslStatus','unknown'))" 2>/dev/null)++if [ -n "$HOSTNAME" ]; then+ echo "✓ Preview URL: https://$HOSTNAME"+ echo " SSL status: $SSL"+else+ echo "✗ Failed to create preview URL"+ echo " Response: $PREVIEW"+ exit 1+fi++# Step 4: Access preview URL+echo ""+echo "━━━ Step 4: Access preview URL ━━━"+sleep 2 # give Cloudflare a moment to propagate+HTTP_CODE=$(curl -s -o /tmp/preview-test-body.html -w "%{http_code}" --max-time 15 "https://$HOSTNAME" 2>/dev/null)+BODY=$(cat /tmp/preview-test-body.html 2>/dev/null)+rm -f /tmp/preview-test-body.html++if [ "$HTTP_CODE" = "200" ]; then+ echo "✓ HTTPS access: $HTTP_CODE"+ if echo "$BODY" | grep -q "Preview URL Works"; then+ echo "✓ Content verified: page contains expected text"+ else+ echo "⚠ Got 200 but unexpected content:"+ echo " ${BODY:0:200}"+ fi+else+ echo "✗ HTTPS access failed: HTTP $HTTP_CODE"+ echo " Body: ${BODY:0:200}"+fi++# Step 5: List preview URLs+echo ""+echo "━━━ Step 5: List preview URLs ━━━"+LIST=$(curl -s "$API_URL/api/sandboxes/$SB/preview" -H "X-API-Key: $API_KEY")+COUNT=$(echo "$LIST" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null)+echo "✓ Active preview URLs: $COUNT"++# Step 6: Delete preview URL+echo ""+echo "━━━ Step 6: Delete preview URL ━━━"+curl -s -X DELETE "$API_URL/api/sandboxes/$SB/preview/3000" -H "X-API-Key: $API_KEY" > /dev/null+LIST_AFTER=$(curl -s "$API_URL/api/sandboxes/$SB/preview" -H "X-API-Key: $API_KEY")+COUNT_AFTER=$(echo "$LIST_AFTER" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null)+if [ "$COUNT_AFTER" = "0" ]; then+ echo "✓ Preview URL deleted"+else+ echo "✗ Preview URL still exists after delete"+fi++echo ""+echo "━━━ Done ━━━"+echo ""+echo "All checks passed! Preview URLs are working."diff --git a/scripts/test-preview-url-prod.ts b/scripts/test-preview-url-prod.tsnew file mode 100644index 00000000..5cd6ac29--- /dev/null+++ b/scripts/test-preview-url-prod.ts@@ -0,0 +1,180 @@+/**+ * Preview URL Test — TypeScript+ *+ * Tests that preview URLs work end-to-end on production.+ *+ * Usage:+ * OPENCOMPUTER_API_KEY=your-key npx tsx scripts/test-preview-url-prod.ts+ *+ * Or with custom URL:+ * OPENCOMPUTER_API_URL=http://localhost:8080 OPENCOMPUTER_API_KEY=your-key npx tsx scripts/test-preview-url-prod.ts+ */++const API_URL = process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev";+const API_KEY = process.env.OPENCOMPUTER_API_KEY;++if (!API_KEY) {+ console.error("Set OPENCOMPUTER_API_KEY");+ process.exit(1);+}++const headers = { "Content-Type": "application/json", "X-API-Key": API_KEY };++function ok(msg: string) { console.log(` ✓ ${msg}`); }+function fail(msg: string) { console.log(` ✗ ${msg}`); }+function sleep(ms: number) { return new Promise(r => setTimeout(r, ms)); }++async function main() {+ console.log("");+ console.log("╔══════════════════════════════════════╗");+ console.log("║ Preview URL Test ║");+ console.log("╚══════════════════════════════════════╝");+ console.log("");+ console.log(` API: ${API_URL}`);+ console.log("");++ let sandboxId = "";++ try {+ // Step 1: Create sandbox+ console.log("━━━ Step 1: Create sandbox ━━━");+ const createResp = await fetch(`${API_URL}/api/sandboxes`, {+ method: "POST",+ headers,+ body: JSON.stringify({ timeout: 300 }),+ });+ const createData = await createResp.json() as any;+ sandboxId = createData.sandboxID;+ ok(`Created: ${sandboxId}`);++ // Step 2: Write HTML and start server+ console.log("");+ console.log("━━━ Step 2: Start web server ━━━");++ const html = `<!DOCTYPE html>+<html>+<head><title>Preview Test</title></head>+<body>+<h1>Preview URL Works!</h1>+<p>Sandbox: ${sandboxId}</p>+<p>Time: <script>document.write(new Date().toISOString())</script></p>+</body>+</html>`;++ await fetch(`${API_URL}/api/sandboxes/${sandboxId}/files?path=/workspace/index.html`, {+ method: "PUT",+ headers: { "X-API-Key": API_KEY, "Content-Type": "application/octet-stream" },+ body: html,+ });+ ok("Wrote /workspace/index.html");++ // Start server+ await fetch(`${API_URL}/api/sandboxes/${sandboxId}/exec/run`, {+ method: "POST",+ headers,+ body: JSON.stringify({+ cmd: "bash",+ args: ["-c", "setsid python3 -m http.server 3000 --directory /workspace </dev/null >/dev/null 2>&1 &"],+ timeout: 5,+ }),+ });+ await sleep(2000);++ // Verify server running internally+ const checkResp = await fetch(`${API_URL}/api/sandboxes/${sandboxId}/exec/run`, {+ method: "POST",+ headers,+ body: JSON.stringify({+ cmd: "bash",+ args: ["-c", "curl -s -o /dev/null -w %{http_code} http://localhost:3000"],+ timeout: 5,+ }),+ });+ const checkData = await checkResp.json() as any;+ const internalStatus = checkData.stdout?.trim();++ if (internalStatus === "200") {+ ok(`Server running on port 3000 (internal: ${internalStatus})`);+ } else {+ fail(`Server NOT running (got: ${JSON.stringify(checkData)})`);+ return;+ }++ // Step 3: Create preview URL+ console.log("");+ console.log("━━━ Step 3: Create preview URL ━━━");++ const previewResp = await fetch(`${API_URL}/api/sandboxes/${sandboxId}/preview`, {+ method: "POST",+ headers,+ body: JSON.stringify({ port: 3000 }),+ });+ const previewData = await previewResp.json() as any;+ const hostname = previewData.hostname;+ const sslStatus = previewData.sslStatus;++ if (hostname) {+ ok(`Preview URL: https://${hostname}`);+ ok(`SSL status: ${sslStatus}`);+ } else {+ fail(`Failed to create preview URL: ${JSON.stringify(previewData)}`);+ return;+ }++ // Step 4: Access preview URL+ console.log("");+ console.log("━━━ Step 4: Access preview URL ━━━");+ await sleep(2000);++ try {+ const pageResp = await fetch(`https://${hostname}`, { signal: AbortSignal.timeout(15000) });+ const body = await pageResp.text();++ if (pageResp.status === 200) {+ ok(`HTTPS access: ${pageResp.status}`);+ if (body.includes("Preview URL Works")) {+ ok("Content verified: page contains expected text");+ } else {+ fail(`Got 200 but unexpected content: ${body.slice(0, 200)}`);+ }+ } else {+ fail(`HTTPS access failed: HTTP ${pageResp.status}`);+ console.log(` Body: ${body.slice(0, 200)}`);+ }+ } catch (e: any) {+ fail(`HTTPS access error: ${e.message}`);+ }++ console.log("");+ console.log("━━━ All checks passed! ━━━");+ console.log("");+ console.log(` Preview live at: https://${hostname}`);+ console.log(` Sandbox: ${sandboxId}`);+ console.log("");+ console.log(" Sandbox and preview URL are still running.");+ console.log(" Press Ctrl+C to destroy and exit.");+ console.log("");++ await new Promise<void>((resolve) => {+ process.on("SIGINT", () => {+ console.log("\nCleaning up...");+ resolve();+ });+ });++ } finally {+ if (sandboxId) {+ console.log(`Destroying sandbox ${sandboxId}...`);+ await fetch(`${API_URL}/api/sandboxes/${sandboxId}`, {+ method: "DELETE",+ headers,+ }).catch(() => {});+ console.log("Done.");+ }+ }+}++main().catch((err) => {+ console.error("Fatal:", err);+ process.exit(1);+});diff --git a/sdks/python/opencomputer/filesystem.py b/sdks/python/opencomputer/filesystem.pyindex 3da34b47..8bd15c4c 100644--- a/sdks/python/opencomputer/filesystem.py+++ b/sdks/python/opencomputer/filesystem.py@@ -43,9 +43,12 @@ class Filesystem: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()+ async def write(self, path: str, content: str | bytes | AsyncIterator[bytes]) -> None:+ """Write content to a file. Accepts str, bytes, or an async iterator of bytes for streaming."""+ if isinstance(content, (str, bytes)):+ data: str | bytes | AsyncIterator[bytes] = content if isinstance(content, bytes) else content.encode()+ else:+ data = contentresp = await self._client.put(f"/sandboxes/{self._sandbox_id}/files",params={"path": path},@@ -89,26 +92,6 @@ class Filesystem:)resp.raise_for_status()- async def read_stream(self, path: str) -> AsyncIterator[bytes]:- """Stream a file as async byte chunks. Avoids buffering the full file in memory."""- req = self._client.build_request(- "GET",- f"/sandboxes/{self._sandbox_id}/files",- params={"path": path},- )- resp = await self._client.send(req, stream=True)- resp.raise_for_status()- return resp.aiter_bytes()-- async def write_stream(self, path: str, stream: AsyncIterator[bytes]) -> None:- """Stream content to a file from an async iterator. Avoids buffering the full file in memory."""- resp = await self._client.put(- f"/sandboxes/{self._sandbox_id}/files",- params={"path": path},- content=stream,- )- resp.raise_for_status()-async def exists(self, path: str) -> bool:"""Check if a path exists."""try:diff --git a/sdks/typescript/src/filesystem.ts b/sdks/typescript/src/filesystem.tsindex 433a66c8..0f0ff369 100644--- a/sdks/typescript/src/filesystem.ts+++ b/sdks/typescript/src/filesystem.ts@@ -36,14 +36,20 @@ export class Filesystem {return new Uint8Array(await resp.arrayBuffer());}- async write(path: string, content: string | Uint8Array): Promise<void> {+ async write(path: string, content: string | Uint8Array | ReadableStream<Uint8Array>): Promise<void> {+ const opts: RequestInit & Record<string, unknown> = {+ method: "PUT",+ headers: this.headers,+ body: content as BodyInit,+ };+ // duplex: "half" is required for ReadableStream bodies in Node.js fetch,+ // but must NOT be set for Uint8Array/Buffer/string bodies.+ if (content instanceof ReadableStream) {+ opts.duplex = "half";+ }const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`,- {- method: "PUT",- headers: this.headers,- body: content as BodyInit,- },+ opts,);if (!resp.ok) throw new Error(`Failed to write ${path}: ${resp.status}`);}@@ -74,42 +80,6 @@ export class Filesystem {if (!resp.ok) throw new Error(`Failed to remove ${path}: ${resp.status}`);}- /**- * Returns the raw response body as a ReadableStream for large file downloads.- * Avoids buffering the entire file in memory.- */- async readStream(path: string): Promise<ReadableStream<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}`);- if (!resp.body) throw new Error(`No response body for ${path}`);- return resp.body;- }-- /**- * Streams a ReadableStream or Uint8Array as the request body for large file uploads.- * Avoids buffering the entire file in memory when given a ReadableStream.- */- async writeStream(path: string, stream: ReadableStream<Uint8Array> | Uint8Array): Promise<void> {- const opts: RequestInit & Record<string, unknown> = {- method: "PUT",- headers: this.headers,- body: stream as BodyInit,- };- // duplex: "half" is required for ReadableStream bodies in Node.js fetch,- // but must NOT be set for Uint8Array/Buffer bodies.- if (stream instanceof ReadableStream) {- opts.duplex = "half";- }- const resp = await fetch(- `${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`,- opts,- );- if (!resp.ok) throw new Error(`Failed to write ${path}: ${resp.status}`);- }-async exists(path: string): Promise<boolean> {try {const resp = await fetch(