Skip to content

An open-source, faster Devin alternative

TypeScript

fix: VM network connectivity + exec SDK improvements

motatoesabdfc4e064a9
diff --git a/deploy/ec2/deploy-aws-dev.sh b/deploy/ec2/deploy-aws-dev.sh
index 2741f548..57f34c70 100755
--- a/deploy/ec2/deploy-aws-dev.sh
+++ b/deploy/ec2/deploy-aws-dev.sh
@@ -384,6 +384,13 @@ cmd_deploy() {
echo ' Server started'
sudo systemctl restart opensandbox-worker
echo ' Worker started'
+
+ # Docker sets FORWARD policy to DROP — add rules so Firecracker VMs can reach the internet
+ sudo iptables -C FORWARD -s 172.16.0.0/16 -j ACCEPT 2>/dev/null || \
+ sudo iptables -I FORWARD -s 172.16.0.0/16 -j ACCEPT
+ sudo iptables -C FORWARD -d 172.16.0.0/16 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT 2>/dev/null || \
+ sudo iptables -I FORWARD -d 172.16.0.0/16 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
+ echo ' iptables FORWARD rules for VM subnet added'
"
log "Step 6: Waiting for migrations, then seeding database..."
diff --git a/internal/agent/exec_session.go b/internal/agent/exec_session.go
index 7c08584f..00029a52 100644
--- a/internal/agent/exec_session.go
+++ b/internal/agent/exec_session.go
@@ -104,7 +104,11 @@ func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreat
s.execMu.Unlock()
// Pipe stdout/stderr into scrollback buffer
+ var pipeWg sync.WaitGroup
+ pipeWg.Add(2)
+
go func() {
+ defer pipeWg.Done()
buf := make([]byte, 4096)
for {
n, err := stdoutPipe.Read(buf)
@@ -118,6 +122,7 @@ func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreat
}()
go func() {
+ defer pipeWg.Done()
buf := make([]byte, 4096)
for {
n, err := stderrPipe.Read(buf)
@@ -130,9 +135,11 @@ func (s *Server) ExecSessionCreate(ctx context.Context, req *pb.ExecSessionCreat
}
}()
- // Wait for command exit
+ // Wait for command exit — ensure all pipe output is collected first
go func() {
_ = cmd.Wait()
+ // Wait for stdout/stderr goroutines to finish reading remaining pipe data
+ pipeWg.Wait()
code := int32(cmd.ProcessState.ExitCode())
sess.mu.Lock()
sess.exitCode = &code
diff --git a/internal/firecracker/network.go b/internal/firecracker/network.go
index ea3b1ea1..ecca2896 100644
--- a/internal/firecracker/network.go
+++ b/internal/firecracker/network.go
@@ -228,6 +228,20 @@ func EnableForwarding() error {
"-j", "MASQUERADE")
}
+ // Allow FORWARD for VM traffic — many distros (and Docker) default FORWARD to DROP.
+ // Without these rules, packets from VMs are silently dropped even with masquerade.
+ fwdOut, _ := exec.Command("iptables", "-S", "FORWARD").CombinedOutput()
+ fwdRules := string(fwdOut)
+ if !strings.Contains(fwdRules, "172.16.0.0/16 -j ACCEPT") {
+ _ = run("iptables", "-I", "FORWARD",
+ "-s", "172.16.0.0/16",
+ "-j", "ACCEPT")
+ _ = run("iptables", "-I", "FORWARD",
+ "-d", "172.16.0.0/16",
+ "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED",
+ "-j", "ACCEPT")
+ }
+
return nil
}
diff --git a/sdks/python/examples/test_exec.py b/sdks/python/examples/test_exec.py
index 3652f8b9..ba93176f 100644
--- a/sdks/python/examples/test_exec.py
+++ b/sdks/python/examples/test_exec.py
@@ -7,7 +7,7 @@ Usage:
python examples/test_exec.py
Environment:
- OPENCOMPUTER_API_URL (default: http://50.17.44.74:8080)
+ OPENCOMPUTER_API_URL (default: http://localhost:8080)
OPENCOMPUTER_API_KEY (default: opensandbox-dev)
"""
@@ -16,7 +16,7 @@ import os
from opencomputer import Sandbox
-API_URL = os.environ.get("OPENCOMPUTER_API_URL", "http://50.17.44.74:8080")
+API_URL = os.environ.get("OPENCOMPUTER_API_URL", "http://localhost:8080")
API_KEY = os.environ.get("OPENCOMPUTER_API_KEY", "opensandbox-dev")
passed = 0
diff --git a/sdks/typescript/examples/test-exec.ts b/sdks/typescript/examples/test-exec.ts
index 8b026f1e..00f526c9 100644
--- a/sdks/typescript/examples/test-exec.ts
+++ b/sdks/typescript/examples/test-exec.ts
@@ -3,16 +3,16 @@
*
* Usage:
* cd sdks/typescript
- * npx tsx test-exec.ts
+ * npx tsx examples/test-exec.ts
*
* Environment:
- * OPENCOMPUTER_API_URL (default: http://50.17.44.74:8080)
+ * OPENCOMPUTER_API_URL (default: http://localhost:8080)
* OPENCOMPUTER_API_KEY (default: opensandbox-dev)
*/
import { Sandbox } from "../src/index.js";
-const API_URL = process.env.OPENCOMPUTER_API_URL || "http://50.17.44.74:8080";
+const API_URL = process.env.OPENCOMPUTER_API_URL || "http://localhost:8080";
const API_KEY = process.env.OPENCOMPUTER_API_KEY || "opensandbox-dev";
const decoder = new TextDecoder();
@@ -104,7 +104,7 @@ async function main() {
},
});
console.log(` session: ${session.sessionId}`);
- await new Promise((resolve) => setTimeout(resolve, 2000));
+ await session.done;
assert(lines.includes("line-1"), "got line-1");
assert(lines.includes("line-3"), "got line-3");
assert(streamExitCode === 0, `stream exit code is 0 (got ${streamExitCode})`);
@@ -126,7 +126,7 @@ async function main() {
});
await new Promise((resolve) => setTimeout(resolve, 500));
await sleepSession.kill();
- await new Promise((resolve) => setTimeout(resolve, 1000));
+ await sleepSession.done;
console.log(` exit after kill: ${killExitCode}`);
assert(killExitCode !== -999, "got exit callback after kill");
@@ -146,24 +146,39 @@ async function main() {
assert(scriptResult.stdout.includes("hostname="), "has hostname");
assert(scriptResult.stdout.includes("user="), "has user");
- // 13. apt update shell script
- console.log("\n--- 13. apt update script ---");
- const aptUpdate = await sandbox.exec.start("apt", {
- args: ["update"],
+ // 13. Network connectivity
+ console.log("\n--- 13. Network connectivity ---");
+ const extPing = await sandbox.exec.run("ping -c 1 -W 3 8.8.8.8 2>&1", { timeout: 10 });
+ const extReachable = extPing.stdout.includes("bytes from");
+ console.log(` ping 8.8.8.8: ${extReachable ? "reachable" : "unreachable"}`);
+ assert(extReachable, "external ping works");
+
+ const dnsResult = await sandbox.exec.run("getent hosts google.com 2>&1 | head -1", { timeout: 10 });
+ const dnsOk = dnsResult.exitCode === 0 && dnsResult.stdout.trim().length > 0;
+ console.log(` DNS: ${dnsOk ? dnsResult.stdout.trim() : "failed"}`);
+ assert(dnsOk, "DNS resolution works");
+
+ // 14. apt-get update (streaming via start + await done)
+ console.log("\n--- 14. apt-get update (streaming) ---");
+ const aptLines: string[] = [];
+ const aptSession = await sandbox.exec.start("sh", {
+ args: ["-c", "apt-get update 2>&1 | head -10"],
+ timeout: 30,
onStdout: (data) => {
const text = decoder.decode(data);
- text
- .split("\n")
- .filter(Boolean)
- .forEach((l) => lines.push(l));
- },
- onExit: (code) => {
- killExitCode = code;
+ for (const line of text.split("\n").filter(Boolean)) {
+ aptLines.push(line);
+ process.stdout.write(` > ${line}\n`);
+ }
},
});
+ const aptExitCode = await aptSession.done;
+ console.log(` exit: ${aptExitCode} (${aptLines.length} lines)`);
+ assert(aptExitCode === 0, "apt-get update succeeds");
+ assert(aptLines.some((l) => l.includes("Hit:") || l.includes("Get:")), "apt-get fetched package lists");
- // 14. Cleanup
- console.log("\n--- 13. Killing sandbox ---");
+ // 15. Cleanup
+ console.log("\n--- 15. Killing sandbox ---");
await sandbox.kill();
assert(sandbox.status === "stopped", "sandbox stopped");
diff --git a/sdks/typescript/src/exec.ts b/sdks/typescript/src/exec.ts
index a5860b26..9d919bce 100644
--- a/sdks/typescript/src/exec.ts
+++ b/sdks/typescript/src/exec.ts
@@ -41,6 +41,8 @@ export interface ExecSessionInfo {
export interface ExecSession {
sessionId: string;
+ /** Resolves with the exit code when the process exits. */
+ done: Promise<number>;
sendStdin(data: string | Uint8Array): void;
kill(signal?: number): Promise<void>;
close(): void;
@@ -103,6 +105,10 @@ export class Exec {
const ws = new WebSocket(wsEndpoint);
ws.binaryType = "arraybuffer";
+ let gotExit = false;
+ let resolveDone: (code: number) => void;
+ const done = new Promise<number>((resolve) => { resolveDone = resolve; });
+
ws.onmessage = (event) => {
const buf = new Uint8Array(event.data as ArrayBuffer);
if (buf.length < 1) return;
@@ -118,10 +124,15 @@ export class Exec {
opts.onStderr?.(payload);
break;
case 0x03: // exit
+ gotExit = true;
if (payload.length >= 4) {
const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
const exitCode = view.getInt32(0, false); // big-endian
opts.onExit?.(exitCode);
+ resolveDone(exitCode);
+ } else {
+ opts.onExit?.(0);
+ resolveDone(0);
}
break;
case 0x04: // scrollback_end
@@ -130,11 +141,27 @@ export class Exec {
}
};
+ ws.onclose = () => {
+ if (!gotExit) {
+ opts.onExit?.(-1);
+ resolveDone(-1);
+ }
+ };
+
+ ws.onerror = () => {
+ if (!gotExit) {
+ opts.onExit?.(-1);
+ resolveDone(-1);
+ }
+ };
+
const exec = this;
return {
sessionId,
+ done,
sendStdin(data: string | Uint8Array): void {
+ if (ws.readyState !== WebSocket.OPEN) return;
const payload = typeof data === "string"
? new TextEncoder().encode(data)
: data;
@@ -183,15 +210,17 @@ export class Exec {
async run(command: string, opts: RunOpts = {}): Promise<ProcessResult> {
let stdout = "";
let stderr = "";
+ const timeout = opts.timeout ?? 60;
return new Promise<ProcessResult>((resolve, reject) => {
const decoder = new TextDecoder();
+ let resolved = false;
this.start("sh", {
args: ["-c", command],
env: opts.env,
cwd: opts.cwd,
- timeout: opts.timeout,
+ timeout,
onStdout: (data) => {
stdout += decoder.decode(data, { stream: true });
},
@@ -199,9 +228,17 @@ export class Exec {
stderr += decoder.decode(data, { stream: true });
},
onExit: (exitCode) => {
- resolve({ exitCode, stdout, stderr });
+ if (!resolved) {
+ resolved = true;
+ resolve({ exitCode, stdout, stderr });
+ }
},
- }).catch(reject);
+ }).catch((err) => {
+ if (!resolved) {
+ resolved = true;
+ reject(err);
+ }
+ });
});
}
}