Connect to Commands

Updated at:

Connecting to a command lets you reattach to a process that is already running in the background. This is useful for long-running tasks, service processes, and cases where you need to read results across requests.

Start a background command

const handle = await sandbox.commands.run("python3 -m http.server 8000", {
  background: true,
  timeoutMs: 10 * 60 * 1000,
});

console.log(handle.pid);

Python example:

handle = sandbox.commands.run(
    "python3 -m http.server 8000",
    background=True,
    timeout=10 * 60,
)

print(handle.pid)

Reconnect to a command

const running = await sandbox.commands.list();
const server = running.find((process) => process.pid === handle.pid);

if (server) {
  const connected = await sandbox.commands.connect(server.pid);
  console.log(connected.pid);
}

Python example:

running = sandbox.commands.list()
server = next((process for process in running if process.pid == handle.pid), None)

if server:
    connected = sandbox.commands.connect(server.pid)
    print(connected.pid)

After connecting, you can keep waiting for the process to finish or read subsequent output. CommandHandle capabilities may vary slightly across SDK versions, so use the current SDK type definitions as the source of truth.

Recommendations

Your application should persist the pid and purpose of each background command. Do not infer business state only from the process list, especially when multiple tasks run in the same sandbox.