Commands and PTY
sandbox.commands runs processes through the guest agent. A command runs under /bin/bash -l -c as the template’s default user.
Run a command
Section titled “Run a command”from svm import Sandbox
with Sandbox.create(template="base") as sandbox: result = sandbox.commands.run( 'echo "$GREETING from $(pwd)"', envs={"GREETING": "hello"}, cwd="/tmp", ) print(result.exit_code, result.stdout, result.stderr)
# A non-zero exit is not an exception: check exit_code. failed = sandbox.commands.run("ls /does-not-exist") if failed.exit_code != 0: print(f"exit {failed.exit_code}: {failed.stderr.strip()}")import { Sandbox } from "@svm/sandbox";
const sandbox = await Sandbox.create({ template: "base" });try { const result = await sandbox.commands.run("echo $GREETING from $(pwd)", { envs: { GREETING: "hello" }, cwd: "/tmp", }); console.log(result.exitCode, result.stdout, result.stderr);
// A non-zero exit does not throw: check exitCode on the result. const failed = await sandbox.commands.run("ls /does-not-exist"); if (failed.exitCode !== 0) { console.log(`exit ${failed.exitCode}: ${failed.stderr}`); }} finally { await sandbox.kill();}commands, err := sandbox.Commands()if err != nil { return err}result, err := commands.Run(ctx, "echo $GREETING from $(pwd)", svm.RunOptions{ Envs: map[string]string{"GREETING": "hello"}, CWD: "/tmp",})if err != nil { return err}fmt.Println("exit:", result.ExitCode)fmt.Printf("stdout: %s", result.Stdout)fmt.Printf("stderr: %s", result.Stderr)
// A non-zero exit is not a Go error: err is only for a call that failed. Check ExitCode.failed, err := commands.Run(ctx, "ls /does-not-exist", svm.RunOptions{})if err != nil { return err}if failed.ExitCode != 0 { fmt.Printf("exit %d: %s", failed.ExitCode, failed.Stderr)}require "svm"
box = SVM::Sandbox.create(template: "base")begin result = box.commands.run('echo "$GREETING from $(pwd)"', envs: { "GREETING" => "hello" }, cwd: "/tmp") puts "exit #{result.exit_code}" puts "stdout: #{result.stdout}" puts "stderr: #{result.stderr}"
# A non-zero exit is not raised: check the result. failed = box.commands.run("ls /does-not-exist") unless failed.success? puts "failed with exit #{failed.exit_code}: #{failed.stderr}" endensure box.killendimport dev.svm.sandbox.Client;import dev.svm.sandbox.ProcessResult;import dev.svm.sandbox.RunOptions;import dev.svm.sandbox.Sandbox;import java.util.Map;
public class CommandsRunExample { public static void main(String[] args) { Client client = Client.fromEnvironment(); try (Sandbox sandbox = Sandbox.create(client, "base")) { RunOptions options = new RunOptions(); options.envs = Map.of("GREETING", "hello"); options.cwd = "/tmp"; ProcessResult ok = sandbox.commands().run("echo $GREETING from $(pwd)", options); System.out.println("exit " + ok.exitCode + ": " + ok.stdout().trim());
// A non-zero exit is not an exception: check exitCode or success(). ProcessResult failed = sandbox.commands().run("ls /does-not-exist"); if (!failed.success()) { System.out.println("exit " + failed.exitCode + ", stderr: " + failed.stderr().trim()); } } }}Stream output
Section titled “Stream output”Callbacks get stdout and stderr as they arrive. The call still returns the complete result at the end.
from svm import Sandbox
with Sandbox.create(template="base") as sandbox: result = sandbox.commands.run( "for i in 1 2 3; do echo step $i; echo warning $i >&2; sleep 1; done", on_stdout=lambda data: print("out:", data, end=""), on_stderr=lambda data: print("err:", data, end=""), ) print("exit code", result.exit_code)import { Sandbox } from "@svm/sandbox";
const sandbox = await Sandbox.create({ template: "base" });try { const result = await sandbox.commands.run( "for i in 1 2 3; do echo out $i; echo err $i >&2; sleep 1; done", { onStdout: (chunk) => process.stdout.write(`[stdout] ${chunk}`), onStderr: (chunk) => process.stderr.write(`[stderr] ${chunk}`), }, ); console.log("exit", result.exitCode);} finally { await sandbox.kill();}commands, err := sandbox.Commands()if err != nil { return err}script := "for i in 1 2 3; do echo step $i; echo warn $i >&2; sleep 1; done"result, err := commands.Run(ctx, script, svm.RunOptions{ OnStdout: func(chunk []byte) { fmt.Printf("[stdout] %s", chunk) }, OnStderr: func(chunk []byte) { fmt.Printf("[stderr] %s", chunk) },})if err != nil { return err}fmt.Println("exit:", result.ExitCode)require "svm"
box = SVM::Sandbox.create(template: "base")begin script = "for i in 1 2 3; do echo step $i; echo warn $i >&2; sleep 1; done" result = box.commands.run( script, on_stdout: ->(chunk) { print "[out] #{chunk}" }, on_stderr: ->(chunk) { print "[err] #{chunk}" } ) puts "exit #{result.exit_code}"ensure box.killendimport dev.svm.sandbox.Client;import dev.svm.sandbox.ProcessResult;import dev.svm.sandbox.RunOptions;import dev.svm.sandbox.Sandbox;import java.nio.charset.StandardCharsets;
public class CommandsStreamExample { public static void main(String[] args) { Client client = Client.fromEnvironment(); try (Sandbox sandbox = Sandbox.create(client, "base")) { RunOptions options = new RunOptions(); options.onStdout = chunk -> System.out.print("out: " + new String(chunk, StandardCharsets.UTF_8)); options.onStderr = chunk -> System.out.print("err: " + new String(chunk, StandardCharsets.UTF_8));
// The callbacks see each chunk as it arrives; run returns when the command ends. ProcessResult result = sandbox.commands().run( "for i in 1 2 3; do echo step $i; echo warn $i >&2; sleep 1; done", options); System.out.println("exit " + result.exitCode); } }}Background processes
Section titled “Background processes”background returns once the process starts, with a handle. You can wait on it, kill it, send it stdin, or disconnect from it
and leave it running. Any client can list the sandbox’s processes and kill one by pid.
from svm import Sandbox
with Sandbox.create(template="base") as sandbox: # stdin="" keeps the command's stdin open for send_stdin. writer = sandbox.commands.run("cat > /tmp/notes.txt", background=True, stdin="") server = sandbox.commands.run("python3 -m http.server 8000", background=True)
for process in sandbox.commands.list(): print(process.pid, process.cmd, process.args)
writer.send_stdin("written through stdin\n") writer.close_stdin() print("cat exited with", writer.wait().exit_code) print(sandbox.files.read_text("/tmp/notes.txt"))
sandbox.commands.kill(server.pid) # or server.kill()import { Sandbox } from "@svm/sandbox";
const sandbox = await Sandbox.create({ template: "base" });try { // stdin: "" keeps the background command's stdin open for sendStdin. const cat = await sandbox.commands.run("cat", { background: true, stdin: "" }); await cat.sendStdin("hello over stdin\n"); await cat.closeStdin(); console.log((await cat.wait()).stdout);
const server = await sandbox.commands.run("python3 -m http.server 8000", { background: true }); for (const p of await sandbox.commands.list()) console.log(p.pid, p.cmd, p.args.join(" "));
await server.kill(); // or: await sandbox.commands.kill(server.pid)} finally { await sandbox.kill();}server, err := commands.Run(ctx, "python3 -m http.server 8000", svm.RunOptions{Background: true})if err != nil { return err}fmt.Println("server pid", server.PID)
processes, err := commands.List(ctx)if err != nil { return err}for _, p := range processes { fmt.Println(p.PID, p.Command, p.Args)}
// Stdin: []byte{} keeps a background command's stdin open for SendStdin.reader, err := commands.Run(ctx, "read line; echo got $line", svm.RunOptions{Background: true, Stdin: []byte{}})if err != nil { return err}if err := reader.Handle.SendStdin(ctx, []byte("hello\n")); err != nil { return err}done, err := reader.Handle.Wait(ctx)if err != nil { return err}fmt.Printf("%s", done.Stdout)
if _, err := server.Handle.Kill(ctx); err != nil { // or commands.Kill(ctx, server.PID) return err}require "svm"
box = SVM::Sandbox.create(template: "base")begin # stdin: "" keeps the command's stdin open for send_stdin. handle = box.commands.run("cat", background: true, stdin: "") puts "started pid #{handle.pid}"
box.commands.list.each { |p| puts "#{p.pid} #{p.command} #{p.args.join(' ')}" }
handle.send_stdin("hello\n") handle.close_stdin result = handle.wait puts "cat printed #{result.stdout.inspect}, exit #{result.exit_code}"
server = box.commands.run("python3 -m http.server 8000", background: true) server.kill # or: box.commands.kill(server.pid)ensure box.killendimport dev.svm.sandbox.Client;import dev.svm.sandbox.ProcessInfo;import dev.svm.sandbox.ProcessResult;import dev.svm.sandbox.RunOptions;import dev.svm.sandbox.Sandbox;import java.nio.charset.StandardCharsets;
public class CommandsBackgroundExample { public static void main(String[] args) { Client client = Client.fromEnvironment(); try (Sandbox sandbox = Sandbox.create(client, "base")) { RunOptions options = new RunOptions(); options.background = true; options.stdin = new byte[0]; // keep stdin open for sendStdin ProcessResult started = sandbox.commands().run("cat", options);
for (ProcessInfo p : sandbox.commands().list()) System.out.println(p.pid + " " + p.command + " " + p.args);
started.handle.sendStdin("hello\n".getBytes(StandardCharsets.UTF_8)); started.handle.closeStdin(); System.out.print("cat said: " + started.handle.waitFor().stdout());
ProcessResult sleeper = sandbox.commands().run("sleep 300", options); sleeper.handle.kill(); // by handle sandbox.commands().kill(sleeper.pid); // or by pid: false, it is already gone } }}Interactive terminals (PTY)
Section titled “Interactive terminals (PTY)”A PTY runs a shell with a terminal size. Write to it with send_input, change its size with resize, and receive its bytes in the
data callback. To put it in a web page, pair it with xterm.js.
import time
from svm import Sandbox
with Sandbox.create(template="base") as sandbox: terminal = sandbox.pty.create( "bash", cols=80, rows=24, on_data=lambda data: print(data, end=""), ) sandbox.pty.send_input(terminal.pid, "echo hello from the terminal\n")
sandbox.pty.resize(terminal.pid, cols=120, rows=40) sandbox.pty.send_input(terminal.pid, "tput cols\n") # 120
time.sleep(1) # on_data prints the output as it arrives sandbox.pty.kill(terminal.pid)import { Sandbox } from "@svm/sandbox";
const sandbox = await Sandbox.create({ template: "base" });try { const terminal = await sandbox.pty.create({ command: "bash", cols: 80, rows: 24, onData: (chunk) => process.stdout.write(chunk), }); await sandbox.pty.sendInput(terminal.pid, "echo hello from the pty\n"); await sandbox.pty.resize(terminal.pid, 120, 40); await new Promise((resolve) => setTimeout(resolve, 1000)); // let the output arrive await sandbox.pty.kill(terminal.pid);} finally { await sandbox.kill();}pty, err := sandbox.Pty()if err != nil { return err}terminal, err := pty.Create(ctx, svm.PTYOptions{Command: "/bin/bash", Cols: 80, Rows: 24})if err != nil { return err}pid := terminal.PID// Connect streams the terminal's output to the callback until it ends.go pty.ConnectFromStart(ctx, pid, func(data []byte) { os.Stdout.Write(data) })
if err := pty.SendInput(ctx, pid, []byte("echo hello from the pty\n")); err != nil { return err}if err := pty.Resize(ctx, pid, 120, 40); err != nil { return err}time.Sleep(2 * time.Second)if _, err := pty.Kill(ctx, pid); err != nil { return err}require "svm"
box = SVM::Sandbox.create(template: "base")begin terminal = box.pty.create("/bin/bash", cols: 80, rows: 24, on_data: ->(chunk) { print chunk })
box.pty.send_input(terminal.pid, "echo hello from the pty\n") sleep 1 box.pty.resize(terminal.pid, cols: 120, rows: 40) box.pty.send_input(terminal.pid, "tput cols\n") sleep 1
box.pty.kill(terminal.pid)ensure box.killendimport dev.svm.sandbox.Client;import dev.svm.sandbox.ProcessResult;import dev.svm.sandbox.Sandbox;import java.nio.charset.StandardCharsets;
public class PtyExample { public static void main(String[] args) throws InterruptedException { Client client = Client.fromEnvironment(); try (Sandbox sandbox = Sandbox.create(client, "base")) { // An interactive bash in an 80x24 terminal; output streams to the callback. ProcessResult terminal = sandbox.pty().create(80, 24, data -> System.out.print(new String(data, StandardCharsets.UTF_8)));
sandbox.pty().sendInput(terminal.pid, "echo hello from the pty\n".getBytes(StandardCharsets.UTF_8)); sandbox.pty().resize(terminal.pid, 120, 40); sandbox.pty().sendInput(terminal.pid, "stty size\n".getBytes(StandardCharsets.UTF_8)); Thread.sleep(1000);
sandbox.pty().kill(terminal.pid); } }}When the connection breaks
Section titled “When the connection breaks”Output is addressed by byte offset. When a stream breaks, the SDK reattaches from the offsets it has already seen, so no output is lost and none is repeated.
- A foreground command whose caller gives up is killed, for example after an exception in a callback or a cancelled context.
- The sandbox also kills a foreground process whose stream has been gone for 30 seconds.