An open-source, faster Devin alternative
TypeScript
test fixes
Brian Reardon9add54ade396
diff --git a/internal/agent/exec.go b/internal/agent/exec.goindex acaacf45..0403c5dc 100644--- a/internal/agent/exec.go+++ b/internal/agent/exec.go@@ -94,10 +94,10 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecResponscmd.Env = append(cmd.Env, mapToEnv(req.Envs)...)}- // Run as sandbox user in its own process group- cmd.SysProcAttr = &syscall.SysProcAttr{- Setpgid: true,- Credential: sandboxCredential(),+ // Run in its own process group; use sandbox user unless run_as_root is set+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}+ if !req.RunAsRoot {+ cmd.SysProcAttr.Credential = sandboxCredential()}var stdout, stderr bytes.Buffer@@ -179,9 +179,9 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStrecmd.Env = append(cmd.Env, mapToEnv(req.Envs)...)}- cmd.SysProcAttr = &syscall.SysProcAttr{- Setpgid: true,- Credential: sandboxCredential(),+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}+ if !req.RunAsRoot {+ cmd.SysProcAttr.Credential = sandboxCredential()}stdoutPipe, err := cmd.StdoutPipe()diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex b4199f62..0e4c4246 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -335,8 +335,9 @@ func (m *Manager) PrepareGoldenSnapshot() error {// VMs can use virtio-mem for dynamic memory add/remove.modCtx, modCancel := context.WithTimeout(context.Background(), 5*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"},+ 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,})modCancel()if modErr != nil || (modResp != nil && modResp.ExitCode != 0) {@@ -351,8 +352,9 @@ func (m *Manager) PrepareGoldenSnapshot() error {// workspace.qcow2 that createFromGolden boots with.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"},+ Command: "/bin/sh",+ Args: []string{"-c", "umount /workspace 2>/dev/null; sync"},+ RunAsRoot: true,})umountCancel()if umountErr != nil {@@ -668,6 +670,7 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,"mount --bind /workspace/.home /home/sandbox","chown 1000:1000 /workspace /workspace/.home",}, " && ")},+ RunAsRoot: true,})mountCancel()if mountErr != nil {@@ -731,7 +734,8 @@ func patchGuestNetwork(ctx context.Context, agent *AgentClient, netCfg *NetworkC"ip link set eth0 up && "+"ip route add default via %s && "+"echo 'nameserver 8.8.8.8' > /etc/resolv.conf && "+- "echo 'nameserver 1.1.1.1' >> /etc/resolv.conf",+ "echo 'nameserver 1.1.1.1' >> /etc/resolv.conf && "++ "grep -q \"$(hostname)\" /etc/hosts || echo \"127.0.0.1 $(hostname)\" >> /etc/hosts",netCfg.GuestIP, prefixLen, netCfg.HostIP,)@@ -742,6 +746,7 @@ func patchGuestNetwork(ctx context.Context, agent *AgentClient, netCfg *NetworkCCommand: "/bin/sh",Args: []string{"-c", script},TimeoutSeconds: 5,+ RunAsRoot: true,})if err != nil {return fmt.Errorf("exec network patch: %w", err)@@ -1688,8 +1693,9 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDif vm.agent != nil {syncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)_, syncErr := vm.agent.Exec(syncCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", "sync; kill -USR1 1"},+ Command: "/bin/sh",+ Args: []string{"-c", "sync; kill -USR1 1"},+ RunAsRoot: true,})cancel()if syncErr != nil {@@ -2460,8 +2466,9 @@ func (m *Manager) upgradeAgentIfNeeded(ctx context.Context, vm *VMInstance) {log.Printf("qemu: agent %s: upgrade aborted (chunk at %d): %v", vm.ID, offset, err)cleanCtx, cleanCancel := context.WithTimeout(context.Background(), 5*time.Second)vm.agent.Exec(cleanCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", fmt.Sprintf("rm -f %s %s.chunk", tmpPath, tmpPath)},+ Command: "/bin/sh",+ Args: []string{"-c", fmt.Sprintf("rm -f %s %s.chunk", tmpPath, tmpPath)},+ RunAsRoot: true,})cleanCancel()return@@ -2469,16 +2476,18 @@ func (m *Manager) upgradeAgentIfNeeded(ctx context.Context, vm *VMInstance) {appendCtx, appendCancel := context.WithTimeout(ctx, 5*time.Second)_, _ = vm.agent.Exec(appendCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", fmt.Sprintf("cat %s.chunk >> %s", tmpPath, tmpPath)},+ Command: "/bin/sh",+ Args: []string{"-c", fmt.Sprintf("cat %s.chunk >> %s", tmpPath, tmpPath)},+ RunAsRoot: true,})appendCancel()}chmodCtx, chmodCancel := context.WithTimeout(ctx, 5*time.Second)_, _ = vm.agent.Exec(chmodCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", fmt.Sprintf("chmod +x %s && rm -f %s.chunk", tmpPath, tmpPath)},+ Command: "/bin/sh",+ Args: []string{"-c", fmt.Sprintf("chmod +x %s && rm -f %s.chunk", tmpPath, tmpPath)},+ RunAsRoot: true,})chmodCancel()diff --git a/internal/qemu/migration.go b/internal/qemu/migration.goindex 5e1b6ff1..8e3cc07e 100644--- a/internal/qemu/migration.go+++ b/internal/qemu/migration.go@@ -76,7 +76,7 @@ func (mc *MigrationCoordinator) MigrateToS3(ctx context.Context, sandboxID strin// Sync guest filesystems before copyingif vm.agent != nil {syncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)- _, _ = vm.agent.Exec(syncCtx, &pb.ExecRequest{Command: "sync"})+ _, _ = vm.agent.Exec(syncCtx, &pb.ExecRequest{Command: "sync", RunAsRoot: true})cancel()}diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex 661c7166..c562dab4 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -64,8 +64,9 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoif vm.agent != nil {shutdownCtx, cancel := context.WithTimeout(ctx, 10*time.Second)_, _ = vm.agent.Exec(shutdownCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", "sync; kill -USR1 1"},+ Command: "/bin/sh",+ Args: []string{"-c", "sync; kill -USR1 1"},+ RunAsRoot: true,})cancel()vm.agent.Close()@@ -407,6 +408,7 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c"mount --bind /workspace/.home /home/sandbox 2>/dev/null || true","chown 1000:1000 /workspace /workspace/.home",}, " && ")},+ RunAsRoot: true,})postCancel()@@ -687,6 +689,7 @@ func syncGuestClock(ctx context.Context, agent *AgentClient) error {Command: "/bin/sh",Args: []string{"-c", cmd},TimeoutSeconds: 5,+ RunAsRoot: true,})if err != nil {return fmt.Errorf("exec clock sync: %w", err)diff --git a/internal/worker/handlers.go b/internal/worker/handlers.goindex 271c59ad..5b25d7f4 100644--- a/internal/worker/handlers.go+++ b/internal/worker/handlers.go@@ -4,7 +4,6 @@ import ("context""encoding/binary""encoding/json"- "fmt""io""net/http""time"@@ -366,11 +365,10 @@ func (s *HTTPServer) readFile(c echo.Context) error {return c.JSON(http.StatusBadRequest, map[string]string{"error": "path query parameter is required"})}- var reader io.ReadCloser- var totalSize int64+ var content stringrouteOp := func(ctx context.Context) error {var err error- reader, totalSize, err = s.manager.ReadFileStream(ctx, id, path)+ content, err = s.manager.ReadFile(ctx, id, path)return err}@@ -383,16 +381,8 @@ func (s *HTTPServer) readFile(c echo.Context) error {return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})}}- defer reader.Close()- resp := c.Response()- resp.Header().Set("Content-Type", "application/octet-stream")- if totalSize > 0 {- resp.Header().Set("Content-Length", fmt.Sprintf("%d", totalSize))- }- resp.WriteHeader(http.StatusOK)- _, err := io.Copy(resp.Writer, reader)- return err+ return c.Blob(http.StatusOK, "application/octet-stream", []byte(content))}func (s *HTTPServer) writeFile(c echo.Context) error {@@ -402,9 +392,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"})+ }+routeOp := func(ctx context.Context) error {- _, err := s.manager.WriteFileStream(ctx, id, path, 0644, c.Request().Body)- return err+ return s.manager.WriteFile(ctx, id, path, string(body))}if s.router != nil {diff --git a/proto/agent/agent.pb.go b/proto/agent/agent.pb.goindex 7787d2ee..880e26d7 100644--- a/proto/agent/agent.pb.go+++ b/proto/agent/agent.pb.go@@ -126,6 +126,7 @@ type ExecRequest struct {Envs map[string]string `protobuf:"bytes,3,rep,name=envs,proto3" json:"envs,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`Cwd string `protobuf:"bytes,4,opt,name=cwd,proto3" json:"cwd,omitempty"`TimeoutSeconds int32 `protobuf:"varint,5,opt,name=timeout_seconds,json=timeoutSeconds,proto3" json:"timeout_seconds,omitempty"` // 0 = default (60s)+ RunAsRoot bool `protobuf:"varint,6,opt,name=run_as_root,json=runAsRoot,proto3" json:"run_as_root,omitempty"` // if true, skip sandbox user credential (for internal/system ops)unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -195,6 +196,13 @@ func (x *ExecRequest) GetTimeoutSeconds() int32 {return 0}+func (x *ExecRequest) GetRunAsRoot() bool {+ if x != nil {+ return x.RunAsRoot+ }+ return false+}+type ExecResponse struct {state protoimpl.MessageState `protogen:"open.v1"`ExitCode int32 `protobuf:"varint,1,opt,name=exit_code,json=exitCode,proto3" json:"exit_code,omitempty"`@@ -2857,13 +2865,14 @@ var File_proto_agent_agent_proto protoreflect.FileDescriptorconst file_proto_agent_agent_proto_rawDesc = "" +"\n" +- "\x17proto/agent/agent.proto\x12\x05agent\"\xe1\x01\n" ++ "\x17proto/agent/agent.proto\x12\x05agent\"\x81\x02\n" +"\vExecRequest\x12\x18\n" +"\acommand\x18\x01 \x01(\tR\acommand\x12\x12\n" +"\x04args\x18\x02 \x03(\tR\x04args\x120\n" +"\x04envs\x18\x03 \x03(\v2\x1c.agent.ExecRequest.EnvsEntryR\x04envs\x12\x10\n" +"\x03cwd\x18\x04 \x01(\tR\x03cwd\x12'\n" +- "\x0ftimeout_seconds\x18\x05 \x01(\x05R\x0etimeoutSeconds\x1a7\n" ++ "\x0ftimeout_seconds\x18\x05 \x01(\x05R\x0etimeoutSeconds\x12\x1e\n" ++ "\vrun_as_root\x18\x06 \x01(\bR\trunAsRoot\x1a7\n" +"\tEnvsEntry\x12\x10\n" +"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"[\n" +diff --git a/proto/agent/agent.proto b/proto/agent/agent.protoindex b7c2c98a..b34420ec 100644--- a/proto/agent/agent.proto+++ b/proto/agent/agent.proto@@ -79,6 +79,7 @@ message ExecRequest {map<string, string> envs = 3;string cwd = 4;int32 timeout_seconds = 5; // 0 = default (60s)+ bool run_as_root = 6; // if true, skip sandbox user credential (for internal/system ops)}message ExecResponse {diff --git a/sdks/typescript/examples/test-domain-tls.ts b/sdks/typescript/examples/test-domain-tls.tsindex 7f662d42..ce0af198 100644--- a/sdks/typescript/examples/test-domain-tls.ts+++ b/sdks/typescript/examples/test-domain-tls.ts@@ -71,7 +71,7 @@ const server = http.createServer((req, res) => {timestamp: Date.now()}));});-server.listen(80, '0.0.0.0', () => console.log('Server ready'));+server.listen(8080, '0.0.0.0', () => console.log('Server ready'));`;async function main() {@@ -89,10 +89,10 @@ async function main() {for (let i = 0; i < 3; i++) {const sb = await Sandbox.create({ timeout: 120 });sandboxes.push(sb);- dim(`Sandbox ${i + 1}: ${sb.sandboxId} → ${sb.domain}`);+ dim(`Sandbox ${i + 1}: ${sb.sandboxId} → ${sb.getPreviewDomain(8080)}`);}- const domains = sandboxes.map(s => s.domain);+ const domains = sandboxes.map(s => s.getPreviewDomain(8080));const uniqueDomains = new Set(domains);check("All 3 sandboxes got unique domains", uniqueDomains.size === 3);check("All domains end with .workers.opencomputer.dev",@@ -115,7 +115,7 @@ async function main() {// Check TLS cert on first sandboxtry {- const certInfo = await getTlsCertInfo(sandboxes[0].domain);+ const certInfo = await getTlsCertInfo(sandboxes[0].getPreviewDomain(8080));check("TLS certificate is valid", certInfo.valid);check("Certificate issued by trusted CA",certInfo.issuer.includes("Let's Encrypt") ||@@ -140,7 +140,7 @@ async function main() {for (let i = 0; i < sandboxes.length; i++) {try {- const resp = await fetch(`https://${sandboxes[i].domain}/test-path`);+ const resp = await fetch(`https://${sandboxes[i].getPreviewDomain(8080)}/test-path`);check(`Sandbox ${i + 1}: HTTPS 200`, resp.ok, `status ${resp.status}`);if (resp.ok) {@@ -161,7 +161,7 @@ async function main() {const routingResults = await Promise.all(sandboxes.map(async (sb, i) => {try {- const resp = await fetch(`https://${sb.domain}/`);+ const resp = await fetch(`https://${sb.getPreviewDomain(8080)}/`);const data = await resp.json();return { index: i, sandboxId: sb.sandboxId, returnedId: data.sandboxId, hostname: data.hostname };} catch (err: any) {@@ -180,9 +180,9 @@ async function main() {// Cross-check: request to sandbox 1's domain should NOT get sandbox 2's responseif (sandboxes.length >= 2) {- const cross1 = await fetch(`https://${sandboxes[0].domain}/`);+ const cross1 = await fetch(`https://${sandboxes[0].getPreviewDomain(8080)}/`);const cross1Data = await cross1.json();- const cross2 = await fetch(`https://${sandboxes[1].domain}/`);+ const cross2 = await fetch(`https://${sandboxes[1].getPreviewDomain(8080)}/`);const cross2Data = await cross2.json();check("Cross-routing: different sandboxes return different IDs",@@ -194,7 +194,7 @@ async function main() {// ── Test 5: Multiple methods ────────────────────────────────────bold("━━━ Test 5: HTTP methods through TLS ━━━\n");- const domain = sandboxes[0].domain;+ const domain = sandboxes[0].getPreviewDomain(8080);const getResp = await fetch(`https://${domain}/get-test`);check("GET request works", getResp.ok);diff --git a/sdks/typescript/examples/test-environment.ts b/sdks/typescript/examples/test-environment.tsindex e55ad3ae..fd675c28 100644--- a/sdks/typescript/examples/test-environment.ts+++ b/sdks/typescript/examples/test-environment.ts@@ -83,7 +83,7 @@ async function main() {bold("━━━ Test 4: Package installation (apt) ━━━\n");const aptResult = await sandbox.commands.run(- "apt-get update -qq > /dev/null 2>&1 && apt-get install -y -qq cowsay > /dev/null 2>&1 && /usr/games/cowsay moo | head -1",+ "sudo apt-get update -qq > /dev/null 2>&1 && sudo apt-get install -y -qq cowsay > /dev/null 2>&1 && /usr/games/cowsay moo | head -1",{ timeout: 30 });check("apt install works", aptResult.exitCode === 0,diff --git a/sdks/typescript/examples/test-hibernation-stress.ts b/sdks/typescript/examples/test-hibernation-stress.tsindex 2a6aae7d..a9a30941 100644--- a/sdks/typescript/examples/test-hibernation-stress.ts+++ b/sdks/typescript/examples/test-hibernation-stress.ts@@ -49,7 +49,7 @@ async function main() {sandbox = await Sandbox.create({ timeout: 300 });green(`Created: ${sandbox.sandboxId}`);- dim(`Domain: ${sandbox.domain}`);+ dim(`Domain: ${sandbox.getPreviewDomain(8080)}`);// Write a server that maintains an in-memory counterconst SERVER_CODE = `@@ -70,7 +70,7 @@ const server = http.createServer((req, res) => {res.writeHead(404); res.end('not found');}});-server.listen(80, '0.0.0.0', () => console.log('Counter server on port 80'));+server.listen(8080, '0.0.0.0', () => console.log('Counter server on port 8080'));`;await sandbox.files.write("/tmp/counter-server.js", SERVER_CODE);@@ -78,7 +78,7 @@ server.listen(80, '0.0.0.0', () => console.log('Counter server on port 80'));await sleep(1500);// Verify server is up- const healthResp = await fetch(`https://${sandbox.domain}/health`);+ const healthResp = await fetch(`https://${sandbox.getPreviewDomain(8080)}/health`);check("Counter server started", healthResp.ok);const health = await healthResp.json();dim(`Initial state: counter=${health.counter}, uptime=${health.uptime}`);@@ -92,7 +92,7 @@ server.listen(80, '0.0.0.0', () => console.log('Counter server on port 80'));cyan(`Cycle ${cycle}/3: Incrementing counter...`);// Increment counter before hibernate- const incResp = await fetch(`https://${sandbox.domain}/increment`);+ const incResp = await fetch(`https://${sandbox.getPreviewDomain(8080)}/increment`);const incData = await incResp.json();dim(`Counter = ${incData.counter}`);@@ -117,7 +117,7 @@ server.listen(80, '0.0.0.0', () => console.log('Counter server on port 80'));dim(`Hibernate: ${hibMs}ms, Wake: ${wakeMs}ms`);// Verify counter persisted- const postWakeResp = await fetch(`https://${sandbox.domain}/health`);+ const postWakeResp = await fetch(`https://${sandbox.getPreviewDomain(8080)}/health`);if (postWakeResp.ok) {const postWake = await postWakeResp.json();check(`Cycle ${cycle}: Counter persisted (${postWake.counter})`, postWake.counter === cycle);@@ -187,7 +187,7 @@ server.listen(80, '0.0.0.0', () => console.log('Counter server on port 80'));// Immediately hit the domain - should trigger auto-wakecyan("Sending HTTP request to sleeping sandbox...");const autoWakeStart = Date.now();- const autoWakeResp = await fetch(`https://${sandbox.domain}/health`);+ const autoWakeResp = await fetch(`https://${sandbox.getPreviewDomain(8080)}/health`);const autoWakeMs = Date.now() - autoWakeStart;check("Auto-wake HTTP returned 200", autoWakeResp.ok, `status ${autoWakeResp.status}`);@@ -209,8 +209,8 @@ server.listen(80, '0.0.0.0', () => console.log('Counter server on port 80'));dim(`Server log: ${pidBefore.stdout.trim()}`);// Increment counter to 4- await fetch(`https://${sandbox.domain}/increment`);- const preHibHealth = await fetch(`https://${sandbox.domain}/health`);+ await fetch(`https://${sandbox.getPreviewDomain(8080)}/increment`);+ const preHibHealth = await fetch(`https://${sandbox.getPreviewDomain(8080)}/health`);const preHibData = await preHibHealth.json();check("Counter at 4 before final hibernate", preHibData.counter === 4, `counter=${preHibData.counter}`);@@ -219,7 +219,7 @@ server.listen(80, '0.0.0.0', () => console.log('Counter server on port 80'));await sleep(1000);// Auto-wake by hitting the domain instead of explicit wake()- const finalHealth = await fetch(`https://${sandbox.domain}/health`);+ const finalHealth = await fetch(`https://${sandbox.getPreviewDomain(8080)}/health`);if (finalHealth.ok) {const finalData = await finalHealth.json();check("Counter persisted through final cycle", finalData.counter === 4, `counter=${finalData.counter}`);