Skip to content

An open-source, faster Devin alternative

TypeScript

exec+sdk: stateful shell sessions with reattach (#188)

Mohamed Habibeed4de6f4416
diff --git a/docs/reference/python-sdk.mdx b/docs/reference/python-sdk.mdx
index 88b7ed76..01c397ae 100644
--- a/docs/reference/python-sdk.mdx
+++ b/docs/reference/python-sdk.mdx
@@ -294,9 +294,9 @@ Run a command synchronously via `sh -c`.
result = await sandbox.exec.run("npm test", cwd="/app")
```
-### `await sandbox.exec.start(command, ...): str`
+### `await sandbox.exec.start(command, ...): ExecSession`
-Start a long-running command. Returns the **session ID** (not a session object).
+Start a long-running command with streaming I/O. Returns an `ExecSession` — see the [full reference](/reference/python-sdk/exec#await-sandbox-exec-start-command).
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
@@ -305,14 +305,37 @@ Start a long-running command. Returns the **session ID** (not a session object).
| `env` | dict[str, str] | None | Environment variables |
| `cwd` | str | None | Working directory |
| `timeout` | int | None | Timeout in seconds |
+| `max_run_after_disconnect` | int | None | Seconds to keep running after disconnect |
+| `on_stdout` | Callable[[bytes], None] | None | Stdout callback |
+| `on_stderr` | Callable[[bytes], None] | None | Stderr callback |
+| `on_exit` | Callable[[int], None] | None | Exit callback |
```python
-session_id = await sandbox.exec.start("node server.js", cwd="/app")
+session = await sandbox.exec.start(
+ "node", args=["server.js"], cwd="/app",
+ on_stdout=lambda b: print(b.decode(), end=""),
+)
+exit_code = await session.done
```
-<Note>
- Python `exec.start()` returns a session ID string. There are no streaming callbacks, `ExecSession` object, or `maxRunAfterDisconnect`. For streaming, use the [WebSocket binary protocol](/reference/api#websocket-binary-protocol).
-</Note>
+### `await sandbox.exec.background(command, ...): ExecSession`
+
+Alias for `start`. Same signature and return type.
+
+### `await sandbox.exec.shell(cwd=None, env=None): Shell`
+
+Open a stateful shell session whose `cwd`, env vars, and shell functions persist across `.run()` calls. Foreground-only. See the [full reference](/reference/python-sdk/exec#await-sandbox-exec-shell).
+
+```python
+sh = await sandbox.exec.shell(cwd="/app")
+await sh.run("export NODE_ENV=test")
+r = await sh.run("npm test")
+await sh.close()
+```
+
+### `await sandbox.exec.attach(session_id, ...): ExecSession`
+
+Reconnect to a running exec session over WebSocket, with the same streaming callbacks as `start`.
### `await sandbox.exec.list(): list[ExecSessionInfo]`
@@ -322,13 +345,6 @@ List all exec sessions.
Kill an exec session.
-### Not Available in Python
-
-- `exec.attach()` — reconnect to running session
-- Streaming callbacks (`on_stdout`, `on_stderr`, `on_exit`)
-- `ExecSession` object with `send_stdin()` and `done`
-- `max_run_after_disconnect`
-
### ProcessResult
```python
diff --git a/docs/reference/python-sdk/exec.mdx b/docs/reference/python-sdk/exec.mdx
index 8c845a15..c089c014 100644
--- a/docs/reference/python-sdk/exec.mdx
+++ b/docs/reference/python-sdk/exec.mdx
@@ -35,7 +35,7 @@ result = await sandbox.exec.run("npm test", cwd="/app")
## `await sandbox.exec.start(command, ...)`
-Start a long-running command. Returns the **session ID** (not a session object). [HTTP API →](/api-reference/exec/create-session)
+Start a long-running command with streaming I/O. [HTTP API →](/api-reference/exec/create-session)
<ParamField body="command" type="str" required>
Command
@@ -57,16 +57,116 @@ Start a long-running command. Returns the **session ID** (not a session object).
Timeout in seconds
</ParamField>
-**Returns:** `str` (session ID)
+<ParamField body="max_run_after_disconnect" type="int">
+ Seconds to keep running after disconnect
+</ParamField>
+
+<ParamField body="on_stdout" type="Callable[[bytes], None]">
+ Stdout callback
+</ParamField>
+
+<ParamField body="on_stderr" type="Callable[[bytes], None]">
+ Stderr callback
+</ParamField>
+
+<ParamField body="on_exit" type="Callable[[int], None]">
+ Exit callback
+</ParamField>
+
+**Returns:** `ExecSession`
+
+```python
+session = await sandbox.exec.start(
+ "node", args=["server.js"], cwd="/app",
+ on_stdout=lambda b: print(b.decode(), end=""),
+ on_exit=lambda code: print(f"exited {code}"),
+)
+exit_code = await session.done
+```
+
+---
+
+## `await sandbox.exec.background(command, ...)`
+
+Alias for [`start`](#await-sandbox-exec-start-command). Same signature, same return type. Use when the intent is "run this in the background and observe it".
+
+```python
+server = await sandbox.exec.background("npm", args=["run", "dev"])
+```
+
+---
+
+## `await sandbox.exec.shell(...)`
+
+Open a stateful shell session. Subsequent `.run()` calls share the same bash process, so `cwd`, exported env vars, and shell functions persist — the ergonomics of a terminal tab.
+
+Backed by a long-running `bash --noprofile --norc` session. Foreground-only: concurrent `.run()` raises `ShellBusyError`.
+
+<ParamField body="cwd" type="str">
+ Initial working directory
+</ParamField>
+
+<ParamField body="env" type="dict[str, str]">
+ Initial environment variables
+</ParamField>
+
+**Returns:** `Shell`
```python
-session_id = await sandbox.exec.start("node server.js", cwd="/app")
+sh = await sandbox.exec.shell(cwd="/app")
+
+await sh.run("npm install")
+await sh.run("export NODE_ENV=test")
+r = await sh.run("npm test", on_stdout=lambda b: print(b.decode(), end=""))
+print(r.exit_code)
+
+await sh.close()
```
+### Shell
+
+| Member | Type | Description |
+| --- | --- | --- |
+| `session_id` | `str` | Underlying exec session ID |
+| `run(cmd, on_stdout=?, on_stderr=?)` | `ProcessResult` | Run a command, blocking until it exits |
+| `close()` | `None` | Write `exit` and wait for bash to terminate |
+
<Note>
- Python `exec.start()` returns a session ID string. There are no streaming callbacks, `ExecSession` object, or `max_run_after_disconnect`. For streaming, use the [WebSocket binary protocol](/reference/api#websocket-binary-protocol).
+ Per-call `cwd`, `env`, and `timeout` are intentionally not supported in v1. Use inline shell syntax (`cd /x && cmd`, `FOO=bar cmd`) — the shell state carries across calls.
</Note>
+Errors:
+- `ShellBusyError` — another `run()` is in flight (shell is foreground-only).
+- `ShellClosedError` — bash has exited (explicit `close()`, a command ran `exit`, or the session dropped).
+
+---
+
+## `await sandbox.exec.attach(session_id, ...)`
+
+Reconnect to a running exec session over WebSocket.
+
+<ParamField body="session_id" type="str" required>
+ Session ID
+</ParamField>
+
+<ParamField body="on_stdout" type="Callable[[bytes], None]">
+ Stdout callback
+</ParamField>
+
+<ParamField body="on_stderr" type="Callable[[bytes], None]">
+ Stderr callback
+</ParamField>
+
+<ParamField body="on_exit" type="Callable[[int], None]">
+ Exit callback
+</ParamField>
+
+<ParamField body="on_scrollback_end" type="Callable[[], None]">
+ Scrollback replay done
+</ParamField>
+
+**Returns:** `ExecSession`
+
---
## `await sandbox.exec.list()`
@@ -85,12 +185,15 @@ Kill an exec session. [HTTP API →](/api-reference/exec/kill-session)
---
-## Not Available in Python
+## ExecSession
-- `exec.attach()` — reconnect to running session
-- Streaming callbacks (`on_stdout`, `on_stderr`, `on_exit`)
-- `ExecSession` object with `send_stdin()` and `done`
-- `max_run_after_disconnect`
+| Member | Type | Description |
+| --- | --- | --- |
+| `session_id` | `str` | Session ID |
+| `done` | `asyncio.Future[int]` | Resolves with exit code |
+| `send_stdin(data)` | coroutine | Send input (`str` or `bytes`) |
+| `kill(signal=9)` | coroutine | Kill process |
+| `close()` | coroutine | Detach WebSocket (process keeps running) |
---
diff --git a/docs/reference/typescript-sdk.mdx b/docs/reference/typescript-sdk.mdx
index 83299681..15340a01 100644
--- a/docs/reference/typescript-sdk.mdx
+++ b/docs/reference/typescript-sdk.mdx
@@ -361,6 +361,21 @@ const session = await sandbox.exec.start("node server.js", {
});
```
+### `sandbox.exec.background(command, opts?): Promise<ExecSession>`
+
+Alias for `start`. Same signature and return type — use when the intent is "run this in the background and observe it".
+
+### `sandbox.exec.shell(opts?): Promise<Shell>`
+
+Open a stateful shell session whose `cwd`, env vars, and shell functions persist across `.run()` calls. Foreground-only. See the [full reference](/reference/typescript-sdk/exec#sandbox-exec-shell-opts).
+
+```typescript
+const sh = await sandbox.exec.shell({ cwd: "/app" });
+await sh.run("export NODE_ENV=test");
+const r = await sh.run("npm test");
+await sh.close();
+```
+
### `sandbox.exec.attach(sessionId, opts?): Promise<ExecSession>`
Reconnect to a running exec session.
diff --git a/docs/reference/typescript-sdk/exec.mdx b/docs/reference/typescript-sdk/exec.mdx
index 3f42ae54..adb7842c 100644
--- a/docs/reference/typescript-sdk/exec.mdx
+++ b/docs/reference/typescript-sdk/exec.mdx
@@ -83,6 +83,73 @@ const session = await sandbox.exec.start("node server.js", {
---
+## `sandbox.exec.background(command, opts?)`
+
+Alias for [`start`](#sandbox-exec-start-command-opts). Same options, same return type. Use when the intent is "run this in the background and observe it" — more discoverable than `start` for that case.
+
+```typescript
+const server = await sandbox.exec.background("npm", {
+ args: ["run", "dev"],
+ onStdout: (data) => process.stdout.write(data),
+});
+```
+
+---
+
+## `sandbox.exec.shell(opts?)`
+
+Open a stateful shell session. Subsequent `.run()` calls share the same bash process, so `cwd`, exported env vars, and shell functions persist — the ergonomics of a terminal tab.
+
+Backed by a long-running `bash --noprofile --norc` session. Foreground-only: concurrent `.run()` rejects with `ShellBusyError`. Use [`background`](#sandbox-exec-background-command-opts) for fire-and-forget processes.
+
+<ParamField body="cwd" type="string">
+ Initial working directory
+</ParamField>
+
+<ParamField body="env" type="Record<string, string>">
+ Initial environment variables
+</ParamField>
+
+**Returns:** `Promise<Shell>`
+
+```typescript
+const sh = await sandbox.exec.shell({ cwd: "/app" });
+
+await sh.run("npm install");
+await sh.run("export NODE_ENV=test");
+const r = await sh.run("npm test", {
+ onStdout: (b) => process.stdout.write(b),
+});
+console.log(r.exitCode);
+
+await sh.close();
+```
+
+### Shell
+
+| Member | Type | Description |
+| --- | --- | --- |
+| `sessionId` | `string` | Underlying exec session ID |
+| `run(cmd, opts?)` | `Promise<ProcessResult>` | Run a command, blocking until it exits |
+| `close()` | `Promise<void>` | Write `exit` and wait for bash to terminate |
+
+### ShellRunOpts
+
+| Parameter | Type | Description |
+| --- | --- | --- |
+| `onStdout` | `(data: Uint8Array) => void` | Per-call stdout callback |
+| `onStderr` | `(data: Uint8Array) => void` | Per-call stderr callback |
+
+<Note>
+ Per-call `cwd`, `env`, and `timeout` are intentionally not supported in v1. Use inline shell syntax (`cd /x && cmd`, `FOO=bar cmd`) — the shell state carries across calls. Timeouts will land once we have a "signal foreground job" primitive.
+</Note>
+
+Errors:
+- `ShellBusyError` — another `run()` is in flight (shell is foreground-only).
+- `ShellClosedError` — bash has exited (explicit `close()`, a command ran `exit`, or the session dropped).
+
+---
+
## `sandbox.exec.attach(sessionId, opts?)`
Reconnect to a running exec session.
diff --git a/docs/sandboxes/running-commands.mdx b/docs/sandboxes/running-commands.mdx
index 1e23499d..950421bc 100644
--- a/docs/sandboxes/running-commands.mdx
+++ b/docs/sandboxes/running-commands.mdx
@@ -3,7 +3,21 @@ title: "Running Commands"
description: "Execute shell commands inside a sandbox"
---
-Two modes: `exec.run()` waits for the result, `exec.start()` creates a session for long-running or streaming commands.
+Three primitives, each tuned for a different shape of work:
+
+| Use | Primitive | Why |
+| ----------------------------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
+| One-shot command, wait for the result | `exec.run()` | Simplest call. Returns once the command exits. Each call is isolated — no state carries between calls. |
+| Long-running / streaming process | `exec.start()` / `exec.background()` | Returns a session handle you can stream from, send stdin to, or reattach to later. Use for servers, builds, and any job you need to observe live. |
+| Multi-step workflow, state must persist | `exec.shell()` | Opens a long-lived `bash` whose `cwd`, exported env, and shell functions persist across `.run()` calls — the ergonomics of a terminal tab. Reconnectable via `exec.reattachShell(sessionId)`. |
+
+Rules of thumb:
+
+- Need a return value and don't care about streaming? → **`run()`**.
+- Starting something that outlives the call (a server, a log tailer, a slow build)? → **`start()` / `background()`**.
+- Doing a sequence of commands where one step's state (directory, env var, activated venv) affects the next? → **`shell()`**.
+
+Under the hood `shell()` *is* an exec session — its `sessionId` shows up in `exec.list()` next to anything started via `start()`. The difference is purely how the SDK frames commands on top: a sentinel protocol per `.run()` call so you can treat one long-lived bash as many discrete calls.
<CodeGroup>
@@ -76,15 +90,13 @@ if result.exit_code != 0:
| Standard output | `stdout` | `stdout` | string |
| Standard error | `stderr` | `stderr` | string |
-## Async Commands: `exec.start()`
-
-Start a command as an exec session for long-running processes or streaming output. The TypeScript and Python SDKs differ significantly here.
+## Async Commands: `exec.start()` / `exec.background()`
-### TypeScript — Full Streaming
+Start a command as an exec session for long-running processes or streaming output. Returns an `ExecSession` with callbacks for stdout, stderr, and exit. `exec.background()` is an alias for `exec.start()` — same options, same return type.
-Returns an `ExecSession` with callbacks for stdout, stderr, and exit:
+<CodeGroup>
-```typescript
+```typescript TypeScript
const session = await sandbox.exec.start("node server.js", {
cwd: "/app",
env: { PORT: "3000" },
@@ -101,52 +113,132 @@ session.sendStdin("some input\n");
await session.kill();
```
-#### ExecStartOpts
+```python Python
+session = await sandbox.exec.start(
+ "node", args=["server.js"],
+ cwd="/app",
+ env={"PORT": "3000"},
+ on_stdout=lambda b: print(b.decode(), end=""),
+ on_stderr=lambda b: print(b.decode(), end=""),
+ on_exit=lambda code: print(f"Server exited: {code}"),
+ max_run_after_disconnect=300,
+)
-| Parameter | Type | Description |
-| --- | --- | --- |
-| `args` | string[] | Command arguments |
-| `env` | object | Environment variables |
-| `cwd` | string | Working directory |
-| `timeout` | number | Timeout in seconds |
-| `maxRunAfterDisconnect` | number | Seconds to keep running after disconnect |
-| `onStdout` | callback | `(data: Uint8Array) => void` |
-| `onStderr` | callback | `(data: Uint8Array) => void` |
-| `onExit` | callback | `(exitCode: number) => void` |
+# Send input
+await session.send_stdin("some input\n")
-#### ExecSession
+# Wait for completion (or kill)
+await session.kill()
+```
-| Member | Type | Description |
-| --- | --- | --- |
-| `sessionId` | string | Session ID |
-| `done` | `Promise<number>` | Resolves with exit code |
-| `sendStdin(data)` | method | Send input to the process |
-| `kill(signal?)` | method | Kill the process (default: SIGKILL) |
-| `close()` | method | Close the WebSocket connection |
+</CodeGroup>
-### Python — Session ID
+### ExecStartOpts
-Python's `exec.start()` returns a session ID string. There are no streaming callbacks or ExecSession object.
+| Parameter | TypeScript | Python | Description |
+| --- | --- | --- | --- |
+| Arguments | `args: string[]` | `args: list[str]` | Command arguments |
+| Env | `env: object` | `env: dict` | Environment variables |
+| Working dir | `cwd: string` | `cwd: str` | Working directory |
+| Timeout | `timeout: number` | `timeout: int` | Timeout in seconds |
+| Keep-alive | `maxRunAfterDisconnect` | `max_run_after_disconnect` | Seconds to keep running after disconnect |
+| Stdout | `onStdout` | `on_stdout` | Callback receiving raw bytes |
+| Stderr | `onStderr` | `on_stderr` | Callback receiving raw bytes |
+| Exit | `onExit` | `on_exit` | Callback receiving the exit code |
+
+### ExecSession
+
+| Member | TypeScript | Python | Description |
+| --- | --- | --- | --- |
+| Session ID | `sessionId` | `session_id` | Session identifier |
+| Done | `done: Promise<number>` | `done: asyncio.Future[int]` | Resolves with exit code |
+| Send stdin | `sendStdin(data)` | `send_stdin(data)` | Write to the process |
+| Kill | `kill(signal?)` | `kill(signal=9)` | Kill the process |
+| Detach | `close()` | `close()` | Close the WebSocket (process keeps running) |
-```python
-session_id = await sandbox.exec.start(
- "node server.js",
- args=None,
- env={"PORT": "3000"},
- cwd="/app",
-)
+## Stateful Shell: `exec.shell()`
-# Check session status
-sessions = await sandbox.exec.list()
-for s in sessions:
- print(s.session_id, "running" if s.running else f"exited ({s.exit_code})")
+Open a long-lived `bash` session whose state (`cwd`, exported env vars, shell functions) persists across `.run()` calls. Foreground-only: concurrent `.run()` rejects with `ShellBusyError`.
-# Kill when done
-await sandbox.exec.kill(session_id)
+<CodeGroup>
+
+```typescript TypeScript
+const sh = await sandbox.exec.shell({ cwd: "/app" });
+
+await sh.run("npm install");
+await sh.run("export NODE_ENV=test");
+const r = await sh.run("npm test", {
+ onStdout: (b) => process.stdout.write(b),
+});
+console.log(r.exitCode);
+
+await sh.close();
+```
+
+```python Python
+sh = await sandbox.exec.shell(cwd="/app")
+
+await sh.run("npm install")
+await sh.run("export NODE_ENV=test")
+r = await sh.run("npm test", on_stdout=lambda b: print(b.decode(), end=""))
+print(r.exit_code)
+
+await sh.close()
+```
+
+</CodeGroup>
+
+### Reattaching to an open shell
+
+The shell is just an exec session, so its `sessionId` is stable across SDK invocations. Keep the id and revisit the same shell later — cwd, env, and shell functions are still there because the bash process never went anywhere.
+
+<CodeGroup>
+
+```typescript TypeScript
+const sh = await sandbox.exec.shell();
+await sh.run("cd /srv && export DEPLOY=canary");
+const id = sh.sessionId; // persist this somewhere
+
+// ...later, possibly a different process...
+
+const sh2 = await sandbox.exec.reattachShell(id);
+const r = await sh2.run("pwd; echo $DEPLOY");
+// → "/srv\ncanary\n"
```
+```python Python
+sh = await sandbox.exec.shell()
+await sh.run("cd /srv && export DEPLOY=canary")
+sid = sh.session_id # persist this somewhere
+
+# ...later, possibly a different process...
+
+sh2 = await sandbox.exec.reattach_shell(sid)
+r = await sh2.run("pwd; echo $DEPLOY")
+# → "/srv\ncanary\n"
+```
+
+</CodeGroup>
+
+<Note>
+ Reattach assumes the shell is idle (no in-flight `.run()` from another client). If two clients try to drive the same shell concurrently, their output will interleave — coordinate at the application level.
+</Note>
+
+### Terminal-tab semantics
+
+Running `exit` (or `exit N`) inside `sh.run()` closes the shell — same as closing a terminal tab. The pending `.run()` rejects with `ShellClosedError` and any subsequent `.run()` on the same `Shell` also rejects. Start a fresh `shell()` if you need another one.
+
+### Streaming output
+
+Pass `onStdout`/`onStderr` to `sh.run()` and they fire as bytes arrive, before the promise resolves. Two caveats worth knowing:
+
+- **bash builtin output is block-buffered.** `echo`, `printf`, and other builtins go through glibc `stdio`, which only flushes when the buffer fills (~4 KB) or bash exits. If you want live output from a simple loop, use an external binary (`/bin/echo`) or a tool that flushes explicitly (`python -u`, `stdbuf -oL <cmd>`).
+- **Upstream hops may coalesce small frames.** Chunks travel bash → agent → worker (gRPC) → WS → CDN → client. Any of those hops is allowed to combine small frames under light load, so a short command may arrive as one chunk even if its output was produced incrementally. Real workloads (builds, installs, servers) produce enough output that streaming is visible in practice.
+
+See `sdks/typescript/examples/stream-demo.ts` / `sdks/python/examples/stream_demo.py` for a ~6-second apt-install simulation that prints per-chunk arrival timestamps — a good way to eyeball streaming behavior against your deployment.
+
<Note>
- Python does not support `exec.attach()`, streaming callbacks, `maxRunAfterDisconnect`, or the `ExecSession` object. For streaming in Python, use the [WebSocket binary protocol](/reference/api#websocket-binary-protocol) directly.
+ Per-call `cwd`, `env`, and `timeout` are intentionally not supported in v1. Use inline shell syntax (`cd /x && cmd`, `FOO=bar cmd`) — the shell state carries across calls. Use `exec.background()` for fire-and-forget processes.
</Note>
## Managing Sessions
@@ -172,11 +264,13 @@ for s in sessions:
</CodeGroup>
-### Attach to Running Session (TypeScript only)
+### Attach to Running Session
Reconnect to a running exec session to resume streaming output:
-```typescript
+<CodeGroup>
+
+```typescript TypeScript
const session = await sandbox.exec.attach(sessionId, {
onStdout: (data) => process.stdout.write(data),
onStderr: (data) => process.stderr.write(data),
@@ -185,6 +279,18 @@ const session = await sandbox.exec.attach(sessionId, {
});
```
+```python Python
+session = await sandbox.exec.attach(
+ session_id,
+ on_stdout=lambda b: print(b.decode(), end=""),
+ on_stderr=lambda b: print(b.decode(), end=""),
+ on_exit=lambda code: print(f"Exited: {code}"),
+ on_scrollback_end=lambda: print("--- live output ---"),
+)
+```
+
+</CodeGroup>
+
On attach, the server replays the scrollback buffer (historical output), sends a scrollback-end marker, then streams live output.
### Kill a Session
diff --git a/examples/python/validate_all_features.py b/examples/python/validate_all_features.py
index 35d0c5f1..2a8d9513 100644
--- a/examples/python/validate_all_features.py
+++ b/examples/python/validate_all_features.py
@@ -123,22 +123,24 @@ async def main():
# ─── 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(
+ # start() returns an ExecSession with streaming + done future (matches TS SDK).
+ sess = 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)
+ ok(f"start session: {sess.session_id}") if sess.session_id else fail(f"start: {sess.session_id}")
+ await sess.done
+ await sess.close()
# 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"])
+ long_sess = await sb.exec.start("sleep", args=["300"])
await asyncio.sleep(0.5)
- await sb.exec.kill(long_id)
+ await long_sess.kill()
+ await long_sess.close()
ok("kill session")
print()
diff --git a/sdks/python/examples/stream_demo.py b/sdks/python/examples/stream_demo.py
new file mode 100644
index 00000000..7035c183
--- /dev/null
+++ b/sdks/python/examples/stream_demo.py
@@ -0,0 +1,101 @@
+"""stream_demo.py — simulates apt-install-style output over ~6 seconds
+via shell.run(), printing each chunk with its arrival timestamp so you
+can see exactly how streaming feels in practice.
+
+Usage:
+ python sdks/python/examples/stream_demo.py
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import time
+
+from opencomputer import Sandbox
+
+API_URL = os.environ.get("OPENCOMPUTER_API_URL", "https://app.opencomputer.dev")
+API_KEY = os.environ.get("OPENCOMPUTER_API_KEY", "opensandbox-dev")
+
+# Pseudo-apt output. Uses /bin/echo (external, flushes on exit) rather
+# than bash builtins so glibc block-buffering doesn't hide the streaming.
+APT_SIM = r"""
+/bin/echo "Reading package lists..."
+sleep 0.3
+/bin/echo "Building dependency tree..."
+sleep 0.2
+/bin/echo "Reading state information..."
+sleep 0.4
+/bin/echo "The following NEW packages will be installed:"
+/bin/echo " libfoo1 libfoo-dev pkg-a pkg-b pkg-c"
+sleep 0.3
+/bin/echo "0 upgraded, 5 newly installed, 0 to remove and 0 not upgraded."
+/bin/echo "Need to get 4,321 kB of archives."
+/bin/echo "After this operation, 12.3 MB of additional disk space will be used."
+sleep 0.4
+for i in 1 2 3 4 5; do
+ /bin/echo "Get:$i http://deb.example.com/debian bookworm/main amd64 pkg-$i"
+ sleep 0.2
+done
+/bin/echo "Fetched 4,321 kB in 1s (4,321 kB/s)"
+sleep 0.3
+for i in 1 2 3 4 5; do
+ /bin/echo "Selecting previously unselected package pkg-$i."
+ /bin/echo "Unpacking pkg-$i (1.0-$i) ..."
+ sleep 0.15
+ /bin/echo "Setting up pkg-$i (1.0-$i) ..."
+ sleep 0.15
+done
+/bin/echo "W: Could not fetch http://example.com/deprecated — ignoring" >&2
+/bin/echo "Processing triggers for libc-bin (2.36-9+deb12u3) ..."
+sleep 0.4
+/bin/echo "Processing triggers for man-db (2.11.2-2) ..."
+sleep 0.5
+/bin/echo "done."
+"""
+
+
+async def main() -> None:
+ print(f"API: {API_URL}")
+ sb = await Sandbox.create(api_url=API_URL, api_key=API_KEY, template="base")
+ print(f"sandbox: {sb.sandbox_id}")
+
+ t0 = time.monotonic()
+ out_count = 0
+ err_count = 0
+ last_t = t0
+
+ try:
+ sh = await sb.exec.shell()
+
+ def on_out(b: bytes) -> None:
+ nonlocal out_count, last_t
+ out_count += 1
+ now = time.monotonic()
+ gap = now - last_t
+ last_t = now
+ # Show dt-since-start and gap-since-last-chunk.
+ print(f"[+{now - t0:5.2f}s Δ{gap:4.2f}s OUT] {b.decode().rstrip()}")
+
+ def on_err(b: bytes) -> None:
+ nonlocal err_count, last_t
+ err_count += 1
+ now = time.monotonic()
+ gap = now - last_t
+ last_t = now
+ print(f"[+{now - t0:5.2f}s Δ{gap:4.2f}s ERR] {b.decode().rstrip()}")
+
+ print("--- starting simulated apt-install ---")
+ r = await sh.run(APT_SIM, on_stdout=on_out, on_stderr=on_err)
+ total = time.monotonic() - t0
+ print("--- done ---")
+ print(f"exit={r.exit_code} total_wall={total:.2f}s "
+ f"stdout_chunks={out_count} stderr_chunks={err_count}")
+ print(f"stdout_bytes={len(r.stdout)} stderr_bytes={len(r.stderr)}")
+ await sh.close()
+ finally:
+ await sb.kill()
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/sdks/python/examples/test_exec.py b/sdks/python/examples/test_exec.py
index ba93176f..5b681d14 100644
--- a/sdks/python/examples/test_exec.py
+++ b/sdks/python/examples/test_exec.py
@@ -86,7 +86,8 @@ async def main():
# 8. exec.start() + list + kill
print("\n--- 8. exec.start('sleep 60') + list + kill ---")
- session_id = await sandbox.exec.start("sleep", args=["60"])
+ session = await sandbox.exec.start("sleep", args=["60"])
+ session_id = session.session_id
print(f" session: {session_id}")
sessions = await sandbox.exec.list()
diff --git a/sdks/python/examples/test_shell.py b/sdks/python/examples/test_shell.py
new file mode 100644
index 00000000..9933932d
--- /dev/null
+++ b/sdks/python/examples/test_shell.py
@@ -0,0 +1,222 @@
+"""test_shell.py — End-to-end test for exec.shell() (stateful shell sessions).
+
+Usage:
+ cd sdks/python
+ python examples/test_shell.py
+
+Environment:
+ OPENCOMPUTER_API_URL (default: http://localhost:8080)
+ OPENCOMPUTER_API_KEY (default: opensandbox-dev)
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+
+from opencomputer import Sandbox, ShellBusyError, ShellClosedError
+
+
+API_URL = os.environ.get("OPENCOMPUTER_API_URL", "http://localhost:8080")
+API_KEY = os.environ.get("OPENCOMPUTER_API_KEY", "opensandbox-dev")
+
+passed = 0
+failed = 0
+
+
+def check(cond: bool, msg: str) -> None:
+ global passed, failed
+ if cond:
+ passed += 1
+ print(f" ✓ {msg}")
+ else:
+ failed += 1
+ print(f" ✗ {msg}")
+
+
+async def main() -> None:
+ print("=== OpenSandbox Python Shell API Test ===\n")
+ print(f"API: {API_URL}")
+
+ print("\n--- 1. Creating sandbox ---")
+ sandbox = await Sandbox.create(api_url=API_URL, api_key=API_KEY, template="base")
+ print(f" Sandbox: {sandbox.sandbox_id} ({sandbox.status})")
+ check(sandbox.status == "running", "sandbox is running")
+
+ try:
+ # 2. basic run + exit code
+ print("\n--- 2. shell.run('echo hello') ---")
+ sh = await sandbox.exec.shell()
+ r1 = await sh.run("echo hello")
+ print(f' stdout: "{r1.stdout.strip()}" exit={r1.exit_code}')
+ check(r1.exit_code == 0, "exit 0")
+ check(r1.stdout.strip() == "hello", "stdout matches")
+ check(r1.stderr == "", "stderr empty")
+
+ # 3. cwd persists
+ print("\n--- 3. cwd persists across run() calls ---")
+ await sh.run("cd /tmp")
+ pwd = await sh.run("pwd")
+ print(f' pwd: "{pwd.stdout.strip()}"')
+ check(pwd.stdout.strip() == "/tmp", "cwd persisted")
+
+ # 4. exported env persists
+ print("\n--- 4. exported env persists ---")
+ await sh.run("export MY_SHELL_VAR=persistence-works")
+ env_r = await sh.run("echo $MY_SHELL_VAR")
+ print(f' echo: "{env_r.stdout.strip()}"')
+ check(env_r.stdout.strip() == "persistence-works", "env persisted")
+
+ # 5. non-zero exit — subshell so it doesn't kill the outer shell
+ print("\n--- 5. non-zero exit code ---")
+ r_fail = await sh.run("( exit 7 )")
+ print(f" exit: {r_fail.exit_code}")
+ check(r_fail.exit_code == 7, f"exit 7 (got {r_fail.exit_code})")
+ r_fail2 = await sh.run("false && echo nope")
+ check(r_fail2.exit_code == 1, f"exit 1 from false (got {r_fail2.exit_code})")
+
+ # 6. stderr vs stdout separation
+ print("\n--- 6. stderr separated from stdout ---")
+ r_err = await sh.run("echo to-out; echo to-err >&2")
+ print(f' stdout="{r_err.stdout.strip()}" stderr="{r_err.stderr.strip()}"')
+ check(r_err.stdout.strip() == "to-out", "stdout is to-out")
+ check(r_err.stderr.strip() == "to-err", "stderr is to-err")
+ check("__OC_" not in r_err.stderr, "sentinel token hidden from returned stderr")
+
+ # 7. streaming callbacks — print live so interleaving is visible,
+ # then assert chunks were spaced out in time (not buffered to the end).
+ print("\n--- 7. streaming callbacks ---")
+ import time
+ out_chunks: list[bytes] = []
+ err_chunks: list[bytes] = []
+ out_times: list[float] = []
+ err_times: list[float] = []
+ t0 = time.monotonic()
+
+ def on_out(b: bytes) -> None:
+ out_chunks.append(b)
+ out_times.append(time.monotonic())
+ print(f" [+{time.monotonic() - t0:5.2f}s OUT] {b!r}")
+
+ def on_err(b: bytes) -> None:
+ err_chunks.append(b)
+ err_times.append(time.monotonic())
+ print(f" [+{time.monotonic() - t0:5.2f}s ERR] {b!r}")
+
+ # Use /bin/echo (external) rather than bash's builtin — the builtin
+ # goes through glibc stdio which block-buffers when stdout is a pipe,
+ # so output lands in one chunk at the end. Each /bin/echo is a fresh
+ # process that flushes on exit, making the streaming observable.
+ r_stream = await sh.run(
+ "for i in 1 2 3; do /bin/echo stdout-$i; /bin/echo stderr-$i >&2; sleep 0.2; done",
+ on_stdout=on_out,
+ on_stderr=on_err,
+ )
+ joined_out = b"".join(out_chunks).decode()
+ joined_err = b"".join(err_chunks).decode()
+ check("stdout-1" in joined_out and "stdout-3" in joined_out, "stdout stream callbacks fired")
+ check("stderr-1" in joined_err and "stderr-3" in joined_err, "stderr stream callbacks fired")
+ check("__OC_" not in joined_err, "sentinel token hidden from on_stderr")
+ check(r_stream.exit_code == 0, "streaming run exits 0")
+ # Command sleeps 0.2s × 3 = 0.6s. Ideally chunks stream as they are
+ # produced. In practice, frames may be coalesced by upstream proxies
+ # (CF/ALB) or gRPC flow control, so a single-chunk delivery is legal
+ # — we log the span for visibility but don't fail on it.
+ stdout_span = (out_times[-1] - out_times[0]) if len(out_times) >= 2 else 0.0
+ print(f" (stdout span across {len(out_times)} chunks: {stdout_span:.2f}s)")
+
+ # 8. concurrent run rejects
+ print("\n--- 8. concurrent run rejects ---")
+ slow_task = asyncio.create_task(sh.run("sleep 0.3; echo done"))
+ await asyncio.sleep(0.05)
+ busy_err: Exception | None = None
+ try:
+ await sh.run("echo should-not-run")
+ except Exception as e:
+ busy_err = e
+ check(isinstance(busy_err, ShellBusyError), "got ShellBusyError on concurrent run")
+ slow_r = await slow_task
+ check(slow_r.stdout.strip() == "done", "original run still completes")
+
+ # 9. shell functions persist
+ print("\n--- 9. shell functions persist ---")
+ await sh.run("greet() { echo hi-$1; }")
+ fn_r = await sh.run("greet world")
+ check(fn_r.stdout.strip() == "hi-world", "defined function callable in later run")
+
+ # 10. close
+ print("\n--- 10. close ---")
+ await sh.close()
+ closed_err: Exception | None = None
+ try:
+ await sh.run("echo after-close")
+ except Exception as e:
+ closed_err = e
+ check(isinstance(closed_err, ShellClosedError), "run after close rejects with ShellClosedError")
+
+ # 11. shell with cwd/env at construction
+ print("\n--- 11. shell(cwd=..., env=...) initial state ---")
+ sh2 = await sandbox.exec.shell(cwd="/etc", env={"SHELL_INIT_VAR": "from-init"})
+ r11a = await sh2.run("pwd")
+ check(r11a.stdout.strip() == "/etc", "initial cwd honored")
+ r11b = await sh2.run("echo $SHELL_INIT_VAR")
+ check(r11b.stdout.strip() == "from-init", "initial env honored")
+ await sh2.close()
+
+ # 12. terminal-tab semantic: `exit` in user command closes the shell
+ print("\n--- 12. exit N closes the shell (terminal-tab semantic) ---")
+ sh_exit = await sandbox.exec.shell()
+ exit_err: Exception | None = None
+ try:
+ await sh_exit.run("exit 42")
+ except Exception as e:
+ exit_err = e
+ check(isinstance(exit_err, ShellClosedError), "exit 42 rejects the pending run with ShellClosedError")
+ after_exit_err: Exception | None = None
+ try:
+ await sh_exit.run("echo after")
+ except Exception as e:
+ after_exit_err = e
+ check(isinstance(after_exit_err, ShellClosedError), "subsequent run rejects once shell is closed")
+
+ # 13. reattach to an open shell by sessionId
+ print("\n--- 13. reattach_shell revisits an open shell ---")
+ sh_a = await sandbox.exec.shell()
+ await sh_a.run("cd /tmp")
+ await sh_a.run("export REATTACH_VAR=round-trip")
+ reattach_id = sh_a.session_id
+ # Drop the reference without closing — server-side bash keeps running.
+ sh_b = await sandbox.exec.reattach_shell(reattach_id)
+ check(sh_b.session_id == reattach_id, "reattached shell has the same sessionId")
+ r_pwd = await sh_b.run("pwd")
+ check(r_pwd.stdout.strip() == "/tmp", f'reattach preserves cwd (got "{r_pwd.stdout.strip()}")')
+ r_env2 = await sh_b.run("echo $REATTACH_VAR")
+ check(r_env2.stdout.strip() == "round-trip", f'reattach preserves env (got "{r_env2.stdout.strip()}")')
+ await sh_b.close()
+
+ # 14. exec.background alias
+ print("\n--- 14. exec.background alias ---")
+ bg_exit = {"code": -999}
+
+ def on_bg_exit(code: int) -> None:
+ bg_exit["code"] = code
+
+ bg_sess = await sandbox.exec.background(
+ "sh", args=["-c", "echo bg-ok; sleep 0.2"], on_exit=on_bg_exit
+ )
+ await bg_sess.done
+ await bg_sess.close()
+ check(bg_exit["code"] == 0, f"exec.background returns exit code (got {bg_exit['code']})")
+
+ finally:
+ print("\n--- Killing sandbox ---")
+ await sandbox.kill()
+ check(sandbox.status == "stopped", "sandbox stopped")
+
+ print(f"\n=== Results: {passed} passed, {failed} failed ===")
+ if failed > 0:
+ raise SystemExit(1)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/sdks/python/opencomputer/__init__.py b/sdks/python/opencomputer/__init__.py
index abccfd8a..80d8015c 100644
--- a/sdks/python/opencomputer/__init__.py
+++ b/sdks/python/opencomputer/__init__.py
@@ -3,9 +3,10 @@
from opencomputer.sandbox import Sandbox
from opencomputer.agent import Agent, AgentEvent, AgentSession, AgentSessionInfo
from opencomputer.filesystem import Filesystem
-from opencomputer.exec import Exec, ProcessResult, ExecSessionInfo
+from opencomputer.exec import Exec, ProcessResult, ExecSession, ExecSessionInfo
from opencomputer.image import Image
from opencomputer.pty import Pty, PtySession
+from opencomputer.shell import Shell, ShellBusyError, ShellClosedError
from opencomputer.template import Template
from opencomputer.project import SecretStore
from opencomputer.snapshot import Snapshots
@@ -31,10 +32,14 @@ __all__ = [
"Filesystem",
"Exec",
"ProcessResult",
+ "ExecSession",
"ExecSessionInfo",
"Image",
"Pty",
"PtySession",
+ "Shell",
+ "ShellBusyError",
+ "ShellClosedError",
"Template",
"SecretStore",
"Snapshots",
diff --git a/sdks/python/opencomputer/exec.py b/sdks/python/opencomputer/exec.py
index 6cc78c46..8ec25e36 100644
--- a/sdks/python/opencomputer/exec.py
+++ b/sdks/python/opencomputer/exec.py
@@ -2,10 +2,13 @@
from __future__ import annotations
-from dataclasses import dataclass
-from typing import Any
+import asyncio
+from dataclasses import dataclass, field
+from typing import Any, Callable
+from urllib.parse import quote
import httpx
+import websockets
@dataclass
@@ -31,6 +34,53 @@ class ExecSessionInfo:
attached_clients: int
+@dataclass
+class ExecSession:
+ """A live exec session attached over WebSocket.
+
+ Mirrors the TypeScript SDK: `done` resolves with the exit code, and
+ `send_stdin` / `kill` / `close` provide the same control surface.
+ """
+
+ session_id: str
+ sandbox_id: str
+ _ws: Any = field(repr=False, default=None)
+ _exit_future: asyncio.Future = field(repr=False, default=None) # type: ignore[assignment]
+ _reader_task: asyncio.Task | None = field(repr=False, default=None)
+ _kill_fn: Callable[[str, int], Any] | None = field(repr=False, default=None)
+
+ @property
+ def done(self) -> asyncio.Future:
+ """Future resolving to the process exit code."""
+ return self._exit_future
+
+ async def send_stdin(self, data: str | bytes) -> None:
+ """Write to the process stdin. No-op if the connection is closed."""
+ if self._ws is None:
+ return
+ payload = data.encode() if isinstance(data, str) else data
+ try:
+ await self._ws.send(b"\x00" + payload)
+ except Exception:
+ pass
+
+ async def kill(self, signal: int = 9) -> None:
+ """Kill the underlying process."""
+ if self._kill_fn is None:
+ return
+ await self._kill_fn(self.session_id, signal)
+
+ async def close(self) -> None:
+ """Detach from the session. Does not kill the process."""
+ if self._ws is not None:
+ try:
+ await self._ws.close()
+ except Exception:
+ pass
+ if self._reader_task is not None and not self._reader_task.done():
+ self._reader_task.cancel()
+
+
class Exec:
"""Session-based command execution for a sandbox."""
@@ -40,11 +90,13 @@ class Exec:
sandbox_id: str,
connect_url: str,
token: str,
+ api_key: str = "",
):
self._client = client
self._sandbox_id = sandbox_id
self._connect_url = connect_url
self._token = token
+ self._api_key = api_key
async def run(
self,
@@ -84,11 +136,16 @@ class Exec:
env: dict[str, str] | None = None,
cwd: str | None = None,
timeout: int | None = None,
- ) -> str:
- """Start a long-running command and return the session ID.
+ max_run_after_disconnect: int | None = None,
+ on_stdout: Callable[[bytes], None] | None = None,
+ on_stderr: Callable[[bytes], None] | None = None,
+ on_exit: Callable[[int], None] | None = None,
+ on_scrollback_end: Callable[[], None] | None = None,
+ ) -> ExecSession:
+ """Start a long-running command and attach for streaming I/O.
- Unlike `run()`, this does not wait for completion. Use `list()` to
- check session status, or `kill()` to stop it.
+ Returns an `ExecSession` with `done` (future resolving to exit code),
+ `send_stdin`, `kill`, and `close`. Mirrors the TypeScript SDK.
"""
body: dict[str, Any] = {"cmd": command}
if args:
@@ -99,13 +156,200 @@ class Exec:
body["cwd"] = cwd
if timeout is not None:
body["timeout"] = timeout
+ if max_run_after_disconnect is not None:
+ body["maxRunAfterDisconnect"] = max_run_after_disconnect
resp = await self._client.post(
f"/sandboxes/{self._sandbox_id}/exec",
json=body,
)
resp.raise_for_status()
- return resp.json()["sessionID"]
+ session_id = resp.json()["sessionID"]
+
+ return await self.attach(
+ session_id,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ on_exit=on_exit,
+ on_scrollback_end=on_scrollback_end,
+ )
+
+ async def background(
+ self,
+ command: str,
+ args: list[str] | None = None,
+ env: dict[str, str] | None = None,
+ cwd: str | None = None,
+ timeout: int | None = None,
+ max_run_after_disconnect: int | None = None,
+ on_stdout: Callable[[bytes], None] | None = None,
+ on_stderr: Callable[[bytes], None] | None = None,
+ on_exit: Callable[[int], None] | None = None,
+ ) -> ExecSession:
+ """Alias for `start`. Use when the intent is "run in the background
+ and observe" rather than the more ambiguous "start".
+ """
+ return await self.start(
+ command,
+ args=args,
+ env=env,
+ cwd=cwd,
+ timeout=timeout,
+ max_run_after_disconnect=max_run_after_disconnect,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ on_exit=on_exit,
+ )
+
+ async def attach(
+ self,
+ session_id: str,
+ on_stdout: Callable[[bytes], None] | None = None,
+ on_stderr: Callable[[bytes], None] | None = None,
+ on_exit: Callable[[int], None] | None = None,
+ on_scrollback_end: Callable[[], None] | None = None,
+ ) -> ExecSession:
+ """Attach to an existing exec session over WebSocket and route output."""
+ ws_base = self._connect_url.replace("http://", "ws://").replace("https://", "wss://")
+ if self._token:
+ auth = f"?token={quote(self._token)}"
+ elif self._api_key:
+ auth = f"?api_key={quote(self._api_key)}"
+ else:
+ auth = ""
+ ws_url = f"{ws_base}/sandboxes/{self._sandbox_id}/exec/{session_id}{auth}"
+
+ ws = await websockets.connect(ws_url)
+ loop = asyncio.get_event_loop()
+ exit_future: asyncio.Future = loop.create_future()
+ got_exit = False
+
+ async def reader() -> None:
+ nonlocal got_exit
+ try:
+ async for msg in ws:
+ if not isinstance(msg, (bytes, bytearray)) or len(msg) < 1:
+ continue
+ stream_id = msg[0]
+ payload = bytes(msg[1:])
+ if stream_id == 0x01:
+ if on_stdout:
+ on_stdout(payload)
+ elif stream_id == 0x02:
+ if on_stderr:
+ on_stderr(payload)
+ elif stream_id == 0x03:
+ code = int.from_bytes(payload[:4], "big", signed=True) if len(payload) >= 4 else 0
+ got_exit = True
+ if on_exit:
+ on_exit(code)
+ if not exit_future.done():
+ exit_future.set_result(code)
+ elif stream_id == 0x04:
+ if on_scrollback_end:
+ on_scrollback_end()
+ except (websockets.ConnectionClosed, asyncio.CancelledError):
+ pass
+ except Exception:
+ pass
+ finally:
+ if not got_exit and not exit_future.done():
+ if on_exit:
+ on_exit(-1)
+ exit_future.set_result(-1)
+
+ task = asyncio.create_task(reader())
+
+ return ExecSession(
+ session_id=session_id,
+ sandbox_id=self._sandbox_id,
+ _ws=ws,
+ _exit_future=exit_future,
+ _reader_task=task,
+ _kill_fn=self.kill,
+ )
+
+ async def shell(
+ self,
+ cwd: str | None = None,
+ env: dict[str, str] | None = None,
+ ):
+ """Open a stateful shell session.
+
+ Subsequent `.run()` calls share the same bash process, so cwd,
+ exported env vars, and shell functions persist — the ergonomics of
+ a terminal tab. Foreground-only: concurrent `.run()` rejects. If
+ the user command calls `exit`, the shell closes (same as closing a
+ terminal tab) and subsequent `.run()` rejects.
+ """
+ # Late import to avoid circularity.
+ from opencomputer.shell import Shell
+
+ shell_ref: dict[str, Any] = {}
+
+ def _on_stdout(chunk: bytes) -> None:
+ sh = shell_ref.get("s")
+ if sh is not None:
+ sh._on_stdout(chunk)
+
+ def _on_stderr(chunk: bytes) -> None:
+ sh = shell_ref.get("s")
+ if sh is not None:
+ sh._on_stderr(chunk)
+
+ def _on_scrollback_end() -> None:
+ sh = shell_ref.get("s")
+ if sh is not None:
+ sh._on_scrollback_end()
+
+ session = await self.start(
+ "bash",
+ args=["--noprofile", "--norc", "+m"],
+ env=env,
+ cwd=cwd,
+ on_stdout=_on_stdout,
+ on_stderr=_on_stderr,
+ on_scrollback_end=_on_scrollback_end,
+ )
+ shell = Shell(session)
+ shell_ref["s"] = shell
+ return shell
+
+ async def reattach_shell(self, session_id: str):
+ """Re-attach to a shell session opened earlier via `shell()`.
+
+ Useful for revisiting a long-lived terminal tab from a different
+ process invocation. Assumes the shell is idle; if another client
+ has a run in flight, output interleaves and results are undefined.
+ """
+ from opencomputer.shell import Shell
+
+ shell_ref: dict[str, Any] = {}
+
+ def _on_stdout(chunk: bytes) -> None:
+ sh = shell_ref.get("s")
+ if sh is not None:
+ sh._on_stdout(chunk)
+
+ def _on_stderr(chunk: bytes) -> None:
+ sh = shell_ref.get("s")
+ if sh is not None:
+ sh._on_stderr(chunk)
+
+ def _on_scrollback_end() -> None:
+ sh = shell_ref.get("s")
+ if sh is not None:
+ sh._on_scrollback_end()
+
+ session = await self.attach(
+ session_id,
+ on_stdout=_on_stdout,
+ on_stderr=_on_stderr,
+ on_scrollback_end=_on_scrollback_end,
+ )
+ shell = Shell(session)
+ shell_ref["s"] = shell
+ return shell
async def list(self) -> list[ExecSessionInfo]:
"""List all exec sessions for this sandbox."""
diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.py
index 0888944a..dfcd4ce7 100644
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@ -271,7 +271,26 @@ class Sandbox:
@property
def exec(self) -> Exec:
"""Access session-based command execution."""
- return Exec(self._ops_client, self.sandbox_id, self._connect_url, self._token)
+ # Pair URL + credential: direct-worker URL uses the sandbox JWT,
+ # control-plane fallback uses the API key. The control-plane routes
+ # live under `/api/…`; worker routes don't — so add the prefix only
+ # when falling back.
+ if self._connect_url and self._token:
+ exec_url, exec_token, exec_key = self._connect_url, self._token, ""
+ else:
+ api_base = (
+ self._api_url
+ if self._api_url.endswith("/api")
+ else f"{self._api_url}/api"
+ )
+ exec_url, exec_token, exec_key = api_base, "", self._api_key
+ return Exec(
+ self._ops_client,
+ self.sandbox_id,
+ exec_url,
+ exec_token,
+ api_key=exec_key,
+ )
@property
def commands(self) -> Exec:
diff --git a/sdks/python/opencomputer/shell.py b/sdks/python/opencomputer/shell.py
new file mode 100644
index 00000000..5428508f
--- /dev/null
+++ b/sdks/python/opencomputer/shell.py
@@ -0,0 +1,275 @@
+"""Stateful shell sessions for a sandbox — the ergonomics of a terminal tab.
+
+See the TypeScript SDK's `Shell` for the companion implementation. The two
+SDKs share the same sentinel protocol: bash is run with `--noprofile
+--norc`, commands are piped via stdin, and each command is framed by
+per-call DONE/EXIT markers (stdout + stderr respectively) so we can resolve
+only after both pipes have drained.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import uuid
+from typing import Callable
+
+from opencomputer.exec import ExecSession, ProcessResult
+
+
+class ShellBusyError(Exception):
+ """Raised when `shell.run()` is called while another run is in flight."""
+
+ def __init__(self) -> None:
+ super().__init__(
+ "shell is already running a command; shell.run is foreground-only"
+ )
+
+
+class ShellClosedError(Exception):
+ """Raised when `shell.run()` is called after the shell has exited.
+
+ This also fires if the user command calls `exit` — same as closing a
+ terminal tab.
+ """
+
+
+class Shell:
+ """A long-lived bash process with state preserved across `.run()` calls."""
+
+ def __init__(self, session: ExecSession):
+ self._session = session
+ self.session_id = session.session_id
+ self._state = "idle" # idle | running | closed
+ self._token = ""
+ self._stdout_done_marker = ""
+ self._stderr_exit_prefix = ""
+ self._stdout_buf = ""
+ self._stderr_buf = ""
+ self._stdout_scan_idx = 0
+ self._stderr_scan_idx = 0
+ self._stdout_done_idx: int | None = None
+ self._stderr_exit_code: int | None = None
+ self._stderr_exit_idx: int | None = None
+ self._current_on_stdout: Callable[[bytes], None] | None = None
+ self._current_on_stderr: Callable[[bytes], None] | None = None
+ self._current_future: asyncio.Future | None = None
+ # Drop inbound chunks until the server sends `0x04` (scrollback_end).
+ # Without this, reattaching to a shell with prior runs would feed
+ # old sentinels into the parser.
+ self._scrollback_done = False
+
+ # If the bash process exits while a run is pending, fail that run.
+ def _on_session_done(fut: asyncio.Future) -> None:
+ prev = self._state
+ self._state = "closed"
+ if self._current_future is not None and not self._current_future.done():
+ try:
+ code = fut.result() if not fut.cancelled() else -1
+ except Exception:
+ code = -1
+ if prev != "idle":
+ self._current_future.set_exception(
+ ShellClosedError(f"bash exited with code {code}")
+ )
+
+ session.done.add_done_callback(_on_session_done)
+
+ def _on_scrollback_end(self) -> None:
+ self._scrollback_done = True
+
+ def _on_stdout(self, chunk: bytes) -> None:
+ if not self._scrollback_done:
+ return
+ if self._state != "running":
+ return
+ self._stdout_buf += chunk.decode("utf-8", errors="replace")
+ self._scan_stdout()
+
+ def _on_stderr(self, chunk: bytes) -> None:
+ if not self._scrollback_done:
+ return
+ if self._state != "running":
+ return
+ self._stderr_buf += chunk.decode("utf-8", errors="replace")
+ self._scan_stderr()
+
+ def _scan_stdout(self) -> None:
+ if self._current_future is None or self._stdout_done_idx is not None:
+ return
+
+ marker = self._stdout_done_marker
+ idx = self._stdout_buf.find(marker, self._stdout_scan_idx)
+
+ if idx == -1:
+ hold = len(marker) - 1
+ safe = max(self._stdout_scan_idx, len(self._stdout_buf) - hold)
+ if safe > self._stdout_scan_idx and self._current_on_stdout is not None:
+ chunk = self._stdout_buf[self._stdout_scan_idx : safe]
+ self._current_on_stdout(chunk.encode("utf-8"))
+ if safe > self._stdout_scan_idx:
+ self._stdout_scan_idx = safe
+ return
+
+ if idx > self._stdout_scan_idx and self._current_on_stdout is not None:
+ chunk = self._stdout_buf[self._stdout_scan_idx : idx]
+ self._current_on_stdout(chunk.encode("utf-8"))
+ if idx > self._stdout_scan_idx:
+ self._stdout_scan_idx = idx
+
+ self._stdout_done_idx = idx
+ self._try_complete()
+
+ def _scan_stderr(self) -> None:
+ if self._current_future is None or self._stderr_exit_code is not None:
+ return
+
+ prefix = self._stderr_exit_prefix
+ idx = self._stderr_buf.find(prefix, self._stderr_scan_idx)
+
+ if idx == -1:
+ hold = len(prefix) - 1
+ safe = max(self._stderr_scan_idx, len(self._stderr_buf) - hold)
+ if safe > self._stderr_scan_idx and self._current_on_stderr is not None:
+ chunk = self._stderr_buf[self._stderr_scan_idx : safe]
+ self._current_on_stderr(chunk.encode("utf-8"))
+ if safe > self._stderr_scan_idx:
+ self._stderr_scan_idx = safe
+ return
+
+ if idx > self._stderr_scan_idx and self._current_on_stderr is not None:
+ chunk = self._stderr_buf[self._stderr_scan_idx : idx]
+ self._current_on_stderr(chunk.encode("utf-8"))
+ if idx > self._stderr_scan_idx:
+ self._stderr_scan_idx = idx
+
+ after_prefix = idx + len(prefix)
+ close_idx = self._stderr_buf.find("__", after_prefix)
+ if close_idx == -1:
+ return # wait for more bytes
+
+ exit_str = self._stderr_buf[after_prefix:close_idx]
+ try:
+ exit_code = int(exit_str)
+ except ValueError:
+ fut = self._current_future
+ self._state = "closed"
+ self._current_future = None
+ if fut is not None and not fut.done():
+ fut.set_exception(ShellClosedError(f"corrupt sentinel: {exit_str!r}"))
+ return
+
+ self._stderr_exit_code = exit_code
+ self._stderr_exit_idx = idx
+ self._try_complete()
+
+ def _try_complete(self) -> None:
+ fut = self._current_future
+ if fut is None:
+ return
+ if self._stdout_done_idx is None or self._stderr_exit_code is None:
+ return
+
+ result = ProcessResult(
+ exit_code=self._stderr_exit_code,
+ stdout=self._stdout_buf[: self._stdout_done_idx],
+ stderr=self._stderr_buf[
+ : self._stderr_exit_idx
+ if self._stderr_exit_idx is not None
+ else len(self._stderr_buf)
+ ],
+ )
+
+ self._current_future = None
+ self._current_on_stdout = None
+ self._current_on_stderr = None
+ self._stdout_buf = ""
+ self._stderr_buf = ""
+ self._stdout_scan_idx = 0
+ self._stderr_scan_idx = 0
+ self._stdout_done_idx = None
+ self._stderr_exit_code = None
+ self._stderr_exit_idx = None
+ self._token = ""
+ self._stdout_done_marker = ""
+ self._stderr_exit_prefix = ""
+ if self._state != "closed":
+ self._state = "idle"
+
+ if not fut.done():
+ fut.set_result(result)
+
+ async def run(
+ self,
+ cmd: str,
+ on_stdout: Callable[[bytes], None] | None = None,
+ on_stderr: Callable[[bytes], None] | None = None,
+ ) -> ProcessResult:
+ """Run a command inside the shell and wait for it to complete.
+
+ Per-call cwd/env/timeout are intentionally not supported in v1 — use
+ inline shell syntax (`cd /x && cmd`, `FOO=bar cmd`). Timeouts will
+ land once we have a "signal foreground job" primitive.
+ """
+ if self._state == "closed":
+ raise ShellClosedError("shell is closed")
+ if self._state == "running":
+ raise ShellBusyError()
+
+ token = uuid.uuid4().hex
+ self._token = token
+ self._stdout_done_marker = f"\n__OC_{token}_DONE__\n"
+ self._stderr_exit_prefix = f"\n__OC_{token}_EXIT_"
+
+ inner = cmd.strip() or ":"
+ # `{ cmd\n}` groups so `$?` captures the user's exit. Newline before
+ # `}` is required — `{ cmd\n; }` is a bash syntax error. DONE goes
+ # to stdout, EXIT to stderr; we resolve only when both are seen to
+ # avoid a race where the stderr sentinel arrives before the user's
+ # stdout is drained (stdout/stderr are read on separate goroutines
+ # on the agent, so wire ordering isn't guaranteed).
+ wrapped = (
+ f"{{ {inner}\n}} ; __oc_ec=$? ; "
+ f"printf '\\n__OC_%s_DONE__\\n' '{token}' ; "
+ f"printf '\\n__OC_%s_EXIT_%d__\\n' '{token}' \"$__oc_ec\" >&2\n"
+ )
+
+ self._state = "running"
+ self._stdout_buf = ""
+ self._stderr_buf = ""
+ self._stdout_scan_idx = 0
+ self._stderr_scan_idx = 0
+ self._stdout_done_idx = None
+ self._stderr_exit_code = None
+ self._stderr_exit_idx = None
+ self._current_on_stdout = on_stdout
+ self._current_on_stderr = on_stderr
+
+ loop = asyncio.get_event_loop()
+ self._current_future = loop.create_future()
+
+ try:
+ await self._session.send_stdin(wrapped)
+ except Exception:
+ self._state = "closed"
+ fut = self._current_future
+ self._current_future = None
+ if fut is not None and not fut.done():
+ fut.cancel()
+ raise
+
+ return await self._current_future
+
+ async def close(self) -> None:
+ """Write `exit` to bash and wait for it to terminate."""
+ if self._state == "closed":
+ return
+ self._state = "closed"
+ try:
+ await self._session.send_stdin("exit\n")
+ except Exception:
+ pass
+ try:
+ await self._session.done
+ except Exception:
+ pass
+ await self._session.close()
diff --git a/sdks/typescript/examples/stream-demo.ts b/sdks/typescript/examples/stream-demo.ts
new file mode 100644
index 00000000..d3952827
--- /dev/null
+++ b/sdks/typescript/examples/stream-demo.ts
@@ -0,0 +1,109 @@
+/**
+ * stream-demo.ts — simulates apt-install-style output over ~6 seconds via
+ * shell.run(), printing each chunk with its arrival timestamp so you can
+ * see exactly how streaming feels in practice.
+ *
+ * Usage:
+ * cd sdks/typescript
+ * npx tsx examples/stream-demo.ts
+ */
+
+import { Sandbox } from "../src/index.js";
+
+const API_URL = process.env.OPENCOMPUTER_API_URL || "https://app.opencomputer.dev";
+const API_KEY = process.env.OPENCOMPUTER_API_KEY || "opensandbox-dev";
+
+// Pseudo-apt output. Uses /bin/echo (external, flushes on exit) rather
+// than bash builtins so glibc block-buffering doesn't hide the streaming.
+const APT_SIM = String.raw`
+/bin/echo "Reading package lists..."
+sleep 0.3
+/bin/echo "Building dependency tree..."
+sleep 0.2
+/bin/echo "Reading state information..."
+sleep 0.4
+/bin/echo "The following NEW packages will be installed:"
+/bin/echo " libfoo1 libfoo-dev pkg-a pkg-b pkg-c"
+sleep 0.3
+/bin/echo "0 upgraded, 5 newly installed, 0 to remove and 0 not upgraded."
+/bin/echo "Need to get 4,321 kB of archives."
+/bin/echo "After this operation, 12.3 MB of additional disk space will be used."
+sleep 0.4
+for i in 1 2 3 4 5; do
+ /bin/echo "Get:$i http://deb.example.com/debian bookworm/main amd64 pkg-$i"
+ sleep 0.2
+done
+/bin/echo "Fetched 4,321 kB in 1s (4,321 kB/s)"
+sleep 0.3
+for i in 1 2 3 4 5; do
+ /bin/echo "Selecting previously unselected package pkg-$i."
+ /bin/echo "Unpacking pkg-$i (1.0-$i) ..."
+ sleep 0.15
+ /bin/echo "Setting up pkg-$i (1.0-$i) ..."
+ sleep 0.15
+done
+/bin/echo "W: Could not fetch http://example.com/deprecated — ignoring" >&2
+/bin/echo "Processing triggers for libc-bin (2.36-9+deb12u3) ..."
+sleep 0.4
+/bin/echo "Processing triggers for man-db (2.11.2-2) ..."
+sleep 0.5
+/bin/echo "done."
+`;
+
+async function main() {
+ console.log(`API: ${API_URL}`);
+ const sandbox = await Sandbox.create({
+ apiUrl: API_URL,
+ apiKey: API_KEY,
+ template: "base",
+ });
+ console.log(`sandbox: ${sandbox.sandboxId}`);
+
+ const decoder = new TextDecoder();
+ const t0 = Date.now();
+ let outCount = 0;
+ let errCount = 0;
+ let lastT = t0;
+
+ const fmt = (n: number) => (n / 1000).toFixed(2).padStart(5, " ");
+
+ try {
+ const sh = await sandbox.exec.shell();
+
+ const onStdout = (b: Uint8Array) => {
+ outCount++;
+ const now = Date.now();
+ const gap = now - lastT;
+ lastT = now;
+ const text = decoder.decode(b).replace(/\n+$/, "");
+ console.log(`[+${fmt(now - t0)}s Δ${fmt(gap)}s OUT] ${text}`);
+ };
+
+ const onStderr = (b: Uint8Array) => {
+ errCount++;
+ const now = Date.now();
+ const gap = now - lastT;
+ lastT = now;
+ const text = decoder.decode(b).replace(/\n+$/, "");
+ console.log(`[+${fmt(now - t0)}s Δ${fmt(gap)}s ERR] ${text}`);
+ };
+
+ console.log("--- starting simulated apt-install ---");
+ const r = await sh.run(APT_SIM, { onStdout, onStderr });
+ const total = (Date.now() - t0) / 1000;
+ console.log("--- done ---");
+ console.log(
+ `exit=${r.exitCode} total_wall=${total.toFixed(2)}s ` +
+ `stdout_chunks=${outCount} stderr_chunks=${errCount}`,
+ );
+ console.log(`stdout_bytes=${r.stdout.length} stderr_bytes=${r.stderr.length}`);
+ await sh.close();
+ } finally {
+ await sandbox.kill();
+ }
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/sdks/typescript/examples/test-shell.ts b/sdks/typescript/examples/test-shell.ts
new file mode 100644
index 00000000..7338d705
--- /dev/null
+++ b/sdks/typescript/examples/test-shell.ts
@@ -0,0 +1,231 @@
+/**
+ * test-shell.ts — End-to-end test for exec.shell() (stateful shell sessions)
+ *
+ * Usage:
+ * cd sdks/typescript
+ * npx tsx examples/test-shell.ts
+ *
+ * Environment:
+ * OPENCOMPUTER_API_URL (default: http://localhost:8080)
+ * OPENCOMPUTER_API_KEY (default: opensandbox-dev)
+ */
+
+import { Sandbox, ShellBusyError, ShellClosedError } from "../src/index.js";
+
+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();
+let passed = 0;
+let failed = 0;
+
+function assert(condition: boolean, msg: string) {
+ if (condition) {
+ passed++;
+ console.log(` ✓ ${msg}`);
+ } else {
+ failed++;
+ console.log(` ✗ ${msg}`);
+ }
+}
+
+async function main() {
+ console.log("=== OpenSandbox Shell API Test ===\n");
+ console.log(`API: ${API_URL}`);
+
+ console.log("\n--- 1. Creating sandbox ---");
+ const sandbox = await Sandbox.create({
+ apiUrl: API_URL,
+ apiKey: API_KEY,
+ template: "base",
+ });
+ console.log(` Sandbox: ${sandbox.sandboxId} (${sandbox.status})`);
+ assert(sandbox.status === "running", "sandbox is running");
+
+ // 2. basic run + exit code
+ console.log("\n--- 2. shell.run('echo hello') ---");
+ const sh = await sandbox.exec.shell();
+ const r1 = await sh.run("echo hello");
+ console.log(` stdout: "${r1.stdout.trim()}" exit=${r1.exitCode}`);
+ assert(r1.exitCode === 0, "exit 0");
+ assert(r1.stdout.trim() === "hello", "stdout matches");
+ assert(r1.stderr === "", "stderr empty");
+
+ // 3. cwd persists across calls
+ console.log("\n--- 3. cwd persists across run() calls ---");
+ await sh.run("cd /tmp");
+ const pwd = await sh.run("pwd");
+ console.log(` pwd: "${pwd.stdout.trim()}"`);
+ assert(pwd.stdout.trim() === "/tmp", "cwd persisted");
+
+ // 4. exported env persists
+ console.log("\n--- 4. exported env persists ---");
+ await sh.run("export MY_SHELL_VAR=persistence-works");
+ const envR = await sh.run("echo $MY_SHELL_VAR");
+ console.log(` echo: "${envR.stdout.trim()}"`);
+ assert(envR.stdout.trim() === "persistence-works", "env persisted");
+
+ // 5. non-zero exit — subshell so it doesn't kill the outer shell
+ console.log("\n--- 5. non-zero exit code ---");
+ const rFail = await sh.run("( exit 7 )");
+ console.log(` exit: ${rFail.exitCode}`);
+ assert(rFail.exitCode === 7, `exit 7 (got ${rFail.exitCode})`);
+ const rFail2 = await sh.run("false && echo nope");
+ assert(rFail2.exitCode === 1, `exit 1 from false (got ${rFail2.exitCode})`);
+
+ // 6. stderr vs stdout separation
+ console.log("\n--- 6. stderr separated from stdout ---");
+ const rErr = await sh.run("echo to-out; echo to-err >&2");
+ console.log(` stdout="${rErr.stdout.trim()}" stderr="${rErr.stderr.trim()}"`);
+ assert(rErr.stdout.trim() === "to-out", "stdout is to-out");
+ assert(rErr.stderr.trim() === "to-err", "stderr is to-err");
+
+ // 7. streaming callbacks — print live so interleaving is visible, then
+ // assert the chunks were spaced out in time (not buffered to the end).
+ console.log("\n--- 7. streaming callbacks ---");
+ const outChunks: string[] = [];
+ const errChunks: string[] = [];
+ const outTimes: number[] = [];
+ const errTimes: number[] = [];
+ const t0 = Date.now();
+ const stamp = () => ((Date.now() - t0) / 1000).toFixed(2).padStart(5, " ");
+ // Use /bin/echo (external) rather than bash's builtin — the builtin
+ // goes through glibc stdio which block-buffers when stdout is a pipe,
+ // so output lands in one chunk at the end. Each /bin/echo is a fresh
+ // process that flushes on exit, making the streaming observable.
+ const rStream = await sh.run(
+ "for i in 1 2 3; do /bin/echo stdout-$i; /bin/echo stderr-$i >&2; sleep 0.2; done",
+ {
+ onStdout: (b) => {
+ const s = decoder.decode(b);
+ outChunks.push(s);
+ outTimes.push(Date.now());
+ process.stdout.write(` [+${stamp()}s OUT] ${JSON.stringify(s)}\n`);
+ },
+ onStderr: (b) => {
+ const s = decoder.decode(b);
+ errChunks.push(s);
+ errTimes.push(Date.now());
+ process.stdout.write(` [+${stamp()}s ERR] ${JSON.stringify(s)}\n`);
+ },
+ },
+ );
+ const joinedOut = outChunks.join("");
+ const joinedErr = errChunks.join("");
+ assert(joinedOut.includes("stdout-1") && joinedOut.includes("stdout-3"), "stdout stream callbacks fired");
+ assert(joinedErr.includes("stderr-1") && joinedErr.includes("stderr-3"), "stderr stream callbacks fired");
+ assert(!joinedErr.includes("__OC_"), "sentinel token hidden from onStderr");
+ assert(!rStream.stderr.includes("__OC_"), "sentinel token hidden from returned stderr");
+ // Command sleeps 0.2s × 3 = 0.6s. Ideally chunks stream as they are
+ // produced. In practice, frames may be coalesced by upstream proxies
+ // (CF/ALB) or gRPC flow control, so a single-chunk delivery is legal —
+ // we log the span for visibility but don't fail on it.
+ const stdoutSpanMs = outTimes.length >= 2 ? outTimes[outTimes.length - 1] - outTimes[0] : 0;
+ console.log(` (stdout span across ${outTimes.length} chunks: ${stdoutSpanMs}ms)`);
+
+ // 8. concurrent run rejects
+ console.log("\n--- 8. concurrent run rejects ---");
+ const slowP = sh.run("sleep 0.3; echo done");
+ let busyErr: unknown;
+ try {
+ await sh.run("echo should-not-run");
+ } catch (e) {
+ busyErr = e;
+ }
+ assert(busyErr instanceof ShellBusyError, "got ShellBusyError on concurrent run");
+ const slowR = await slowP;
+ assert(slowR.stdout.trim() === "done", "original run still completes");
+
+ // 9. shell.run with multi-line cmd
+ console.log("\n--- 9. multi-line cmd ---");
+ const multiR = await sh.run("echo a\necho b\necho c");
+ const lines = multiR.stdout.trim().split("\n");
+ assert(lines.length === 3 && lines[0] === "a" && lines[2] === "c", "multi-line executes in order");
+
+ // 10. shell.run with a function defined earlier
+ console.log("\n--- 10. shell functions persist ---");
+ await sh.run("greet() { echo hi-$1; }");
+ const fnR = await sh.run("greet world");
+ assert(fnR.stdout.trim() === "hi-world", "defined function callable in later run");
+
+ // 11. close
+ console.log("\n--- 11. close ---");
+ await sh.close();
+ let closedErr: unknown;
+ try {
+ await sh.run("echo after-close");
+ } catch (e) {
+ closedErr = e;
+ }
+ assert(closedErr instanceof ShellClosedError, "run after close rejects with ShellClosedError");
+
+ // 12. shell with cwd/env at construction
+ console.log("\n--- 12. shell({ cwd, env }) initial state ---");
+ const sh2 = await sandbox.exec.shell({
+ cwd: "/etc",
+ env: { SHELL_INIT_VAR: "from-init" },
+ });
+ const r12a = await sh2.run("pwd");
+ assert(r12a.stdout.trim() === "/etc", "initial cwd honored");
+ const r12b = await sh2.run("echo $SHELL_INIT_VAR");
+ assert(r12b.stdout.trim() === "from-init", "initial env honored");
+ await sh2.close();
+
+ // 13. terminal-tab semantic: `exit` in user command closes the shell
+ console.log("\n--- 13. exit N closes the shell (terminal-tab semantic) ---");
+ const shExit = await sandbox.exec.shell();
+ let exitErr: unknown;
+ try {
+ await shExit.run("exit 42");
+ } catch (e) {
+ exitErr = e;
+ }
+ assert(exitErr instanceof ShellClosedError, "exit 42 rejects the pending run with ShellClosedError");
+ let afterExitErr: unknown;
+ try {
+ await shExit.run("echo after");
+ } catch (e) {
+ afterExitErr = e;
+ }
+ assert(afterExitErr instanceof ShellClosedError, "subsequent run rejects once shell is closed");
+
+ // 14. reattach to an open shell by sessionId
+ console.log("\n--- 14. reattachShell revisits an open shell ---");
+ const shA = await sandbox.exec.shell();
+ await shA.run("cd /tmp");
+ await shA.run("export REATTACH_VAR=round-trip");
+ const reattachId = shA.sessionId;
+ // Drop the reference without closing — server-side bash keeps running.
+ const shB = await sandbox.exec.reattachShell(reattachId);
+ assert(shB.sessionId === reattachId, "reattached shell has the same sessionId");
+ const rPwd = await shB.run("pwd");
+ assert(rPwd.stdout.trim() === "/tmp", `reattach preserves cwd (got "${rPwd.stdout.trim()}")`);
+ const rEnv = await shB.run("echo $REATTACH_VAR");
+ assert(rEnv.stdout.trim() === "round-trip", `reattach preserves env (got "${rEnv.stdout.trim()}")`);
+ await shB.close();
+
+ // 15. shell alongside exec.background
+ console.log("\n--- 15. exec.background alias ---");
+ let bgExitCode = -999;
+ const bgSession = await sandbox.exec.background("sh", {
+ args: ["-c", "echo bg-ok; sleep 0.2"],
+ onExit: (c) => {
+ bgExitCode = c;
+ },
+ });
+ await bgSession.done;
+ assert(bgExitCode === 0, `exec.background returns exit code (got ${bgExitCode})`);
+
+ // Cleanup
+ console.log("\n--- 14. Killing sandbox ---");
+ await sandbox.kill();
+ assert(sandbox.status === "stopped", "sandbox stopped");
+
+ console.log(`\n=== Results: ${passed} passed, ${failed} failed ===`);
+ if (failed > 0) process.exit(1);
+}
+
+main().catch((err) => {
+ console.error("\nTest failed:", err);
+ process.exit(1);
+});
diff --git a/sdks/typescript/src/exec.ts b/sdks/typescript/src/exec.ts
index 6aedf0de..50535134 100644
--- a/sdks/typescript/src/exec.ts
+++ b/sdks/typescript/src/exec.ts
@@ -1,3 +1,5 @@
+import { ShellImpl, type Shell, type ShellOpts } from "./shell.js";
+
export interface ProcessResult {
exitCode: number;
stdout: string;
@@ -19,6 +21,7 @@ export interface ExecStartOpts {
onStdout?: (data: Uint8Array) => void;
onStderr?: (data: Uint8Array) => void;
onExit?: (exitCode: number) => void;
+ onScrollbackEnd?: () => void;
}
export interface ExecAttachOpts {
@@ -92,6 +95,7 @@ export class Exec {
onStdout: opts.onStdout,
onStderr: opts.onStderr,
onExit: opts.onExit,
+ onScrollbackEnd: opts.onScrollbackEnd,
});
}
@@ -112,9 +116,23 @@ export class Exec {
ws.binaryType = "arraybuffer";
let gotExit = false;
+ let opened = false;
let resolveDone: (code: number) => void;
const done = new Promise<number>((resolve) => { resolveDone = resolve; });
+ await new Promise<void>((resolve, reject) => {
+ ws.onopen = () => {
+ opened = true;
+ resolve();
+ };
+ ws.onerror = () => {
+ if (!opened) reject(new Error(`WebSocket connection failed: ${wsEndpoint}`));
+ };
+ ws.onclose = () => {
+ if (!opened) reject(new Error(`WebSocket closed before opening: ${wsEndpoint}`));
+ };
+ });
+
ws.onmessage = (event) => {
const buf = new Uint8Array(event.data as ArrayBuffer);
if (buf.length < 1) return;
@@ -155,10 +173,7 @@ export class Exec {
};
ws.onerror = () => {
- if (!gotExit) {
- opts.onExit?.(-1);
- resolveDone(-1);
- }
+ // Post-open errors are followed by onclose, which handles exit.
};
const exec = this;
@@ -213,6 +228,59 @@ export class Exec {
}
}
+ /**
+ * Alias for {@link start}. Use when the intent is "run this command in the
+ * background and observe it" rather than the more ambiguous "start". Same
+ * options, same return type.
+ */
+ async background(command: string, opts: ExecStartOpts = {}): Promise<ExecSession> {
+ return this.start(command, opts);
+ }
+
+ /**
+ * Open a stateful shell session. Subsequent `.run()` calls share the same
+ * bash process, so `cwd`, exported env vars, and shell functions persist
+ * across calls — the ergonomics of a terminal tab.
+ *
+ * Backed by a long-running exec session running `bash --noprofile --norc`.
+ * Foreground-only: concurrent `.run()` rejects. Use `exec.background()` for
+ * fire-and-forget processes. If the user command calls `exit`, the shell
+ * closes (same as closing a terminal tab) and subsequent `.run()` rejects.
+ */
+ async shell(opts: ShellOpts = {}): Promise<Shell> {
+ let impl: ShellImpl | null = null;
+ const session = await this.start("bash", {
+ args: ["--noprofile", "--norc", "+m"],
+ env: opts.env,
+ cwd: opts.cwd,
+ onStdout: (chunk) => impl?.onStdoutChunk(chunk),
+ onStderr: (chunk) => impl?.onStderrChunk(chunk),
+ onScrollbackEnd: () => impl?.onScrollbackEnd(),
+ });
+ impl = new ShellImpl(session);
+ return impl;
+ }
+
+ /**
+ * Re-attach to a shell session that was previously opened by `shell()` and
+ * whose sessionId you've kept. Useful for revisiting a long-lived terminal
+ * tab from a different process invocation.
+ *
+ * Assumes the shell is idle (no in-flight `.run()` from another client).
+ * If another client has a run in flight, output will interleave and the
+ * results are undefined — coordinate at the application level.
+ */
+ async reattachShell(sessionId: string): Promise<Shell> {
+ let impl: ShellImpl | null = null;
+ const session = await this.attach(sessionId, {
+ onStdout: (chunk) => impl?.onStdoutChunk(chunk),
+ onStderr: (chunk) => impl?.onStderrChunk(chunk),
+ onScrollbackEnd: () => impl?.onScrollbackEnd(),
+ });
+ impl = new ShellImpl(session);
+ return impl;
+ }
+
async run(command: string, opts: RunOpts = {}): Promise<ProcessResult> {
const body: Record<string, unknown> = {
cmd: "sh",
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index bd0bc801..e18372b5 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -2,6 +2,7 @@ export { Sandbox, type SandboxOpts, type CheckpointInfo, type PatchInfo, type Pa
export { Agent, type AgentEvent, type AgentConfig, type AgentStartOpts, type AgentSession, type McpServerConfig } from "./agent.js";
export { Filesystem, type EntryInfo } from "./filesystem.js";
export { Exec, type ProcessResult, type RunOpts, type ExecSession, type ExecSessionInfo, type ExecStartOpts, type ExecAttachOpts } from "./exec.js";
+export { type Shell, type ShellOpts, type ShellRunOpts, ShellBusyError, ShellClosedError } from "./shell.js";
export { Pty, type PtySession, type PtyOpts } from "./pty.js";
export { Templates, type TemplateInfo } from "./template.js";
export { SecretStore, type SecretStoreInfo, type SecretEntryInfo, type SecretStoreOpts, type CreateSecretStoreOpts, type UpdateSecretStoreOpts } from "./project.js";
diff --git a/sdks/typescript/src/shell.ts b/sdks/typescript/src/shell.ts
new file mode 100644
index 00000000..3c965855
--- /dev/null
+++ b/sdks/typescript/src/shell.ts
@@ -0,0 +1,291 @@
+import type { ExecSession, ProcessResult } from "./exec.js";
+
+export interface ShellOpts {
+ cwd?: string;
+ env?: Record<string, string>;
+}
+
+export interface ShellRunOpts {
+ onStdout?: (data: Uint8Array) => void;
+ onStderr?: (data: Uint8Array) => void;
+}
+
+export interface Shell {
+ readonly sessionId: string;
+ /**
+ * Run a command inside the shell and wait for it to complete.
+ *
+ * State set by previous calls (cwd, exported variables, shell functions)
+ * persists into this call. Rejects with `ShellBusyError` if another run is
+ * in flight, or `ShellClosedError` if the shell has exited (including when
+ * the user command calls `exit` — same as closing a terminal tab).
+ *
+ * Per-call `cwd`/`env`/`timeout` are intentionally not supported in v1 —
+ * use shell syntax inline (`cd /x && cmd`, `FOO=bar cmd`). Timeouts will
+ * land once we have a "signal foreground job" primitive.
+ */
+ run(cmd: string, opts?: ShellRunOpts): Promise<ProcessResult>;
+ /**
+ * Write `exit` to the shell and wait for bash to terminate.
+ */
+ close(): Promise<void>;
+}
+
+export class ShellBusyError extends Error {
+ constructor() {
+ super("shell is already running a command; shell.run is foreground-only");
+ this.name = "ShellBusyError";
+ }
+}
+
+export class ShellClosedError extends Error {
+ constructor(reason?: string) {
+ super(reason ? `shell is closed: ${reason}` : "shell is closed");
+ this.name = "ShellClosedError";
+ }
+}
+
+type State = "idle" | "running" | "closed";
+
+interface PendingRun {
+ token: string;
+ stdoutDoneMarker: string; // "\n__OC_<TOK>_DONE__\n"
+ stderrExitPrefix: string; // "\n__OC_<TOK>_EXIT_"
+ stdoutBuf: string;
+ stderrBuf: string;
+ stdoutScanIdx: number; // bytes emitted to onStdout
+ stderrScanIdx: number; // bytes emitted to onStderr
+ stdoutDoneIdx: number | null; // index of DONE marker in stdoutBuf, once found
+ stderrExitCode: number | null; // parsed exit code, once EXIT sentinel found
+ stderrExitIdx: number | null; // index of EXIT sentinel start in stderrBuf
+ onStdout?: (data: Uint8Array) => void;
+ onStderr?: (data: Uint8Array) => void;
+ resolve: (r: ProcessResult) => void;
+ reject: (e: Error) => void;
+}
+
+const encoder = new TextEncoder();
+
+/**
+ * Hex-ish 128-bit token; `crypto.randomUUID` is Node 18+ / browser standard.
+ * Fallback uses `Math.random` only if the global `crypto` is absent.
+ */
+function newToken(): string {
+ const g = globalThis as { crypto?: { randomUUID?: () => string } };
+ if (g.crypto?.randomUUID) return g.crypto.randomUUID().replace(/-/g, "");
+ let s = "";
+ for (let i = 0; i < 32; i++) s += Math.floor(Math.random() * 16).toString(16);
+ return s;
+}
+
+export class ShellImpl implements Shell {
+ readonly sessionId: string;
+ private session: ExecSession;
+ private state: State = "idle";
+ private pending: PendingRun | null = null;
+ private stdoutDecoder = new TextDecoder("utf-8", { fatal: false });
+ private stderrDecoder = new TextDecoder("utf-8", { fatal: false });
+ // Chunks arriving before scrollback_end (0x04) are historical replay of
+ // the session's prior output. Drop them — our sentinel protocol only
+ // matches per-call tokens, but the caller's onStdout/onStderr callbacks
+ // should not see stale data either.
+ private scrollbackDone = false;
+
+ constructor(session: ExecSession) {
+ this.session = session;
+ this.sessionId = session.sessionId;
+
+ // If bash exits while a run is pending, fail the pending run.
+ this.session.done.then((exitCode) => {
+ const prev = this.state;
+ this.state = "closed";
+ if (this.pending) {
+ const p = this.pending;
+ this.pending = null;
+ if (prev !== "idle") {
+ p.reject(new ShellClosedError(`bash exited with code ${exitCode}`));
+ }
+ }
+ });
+ }
+
+ onScrollbackEnd(): void {
+ this.scrollbackDone = true;
+ }
+
+ onStdoutChunk(chunk: Uint8Array): void {
+ if (!this.scrollbackDone) return;
+ const p = this.pending;
+ if (!p) return;
+ p.stdoutBuf += this.stdoutDecoder.decode(chunk, { stream: true });
+ this.scanStdout();
+ }
+
+ onStderrChunk(chunk: Uint8Array): void {
+ if (!this.scrollbackDone) return;
+ const p = this.pending;
+ if (!p) return;
+ p.stderrBuf += this.stderrDecoder.decode(chunk, { stream: true });
+ this.scanStderr();
+ }
+
+ /** Extract user stdout up to the DONE marker; emit incremental chunks. */
+ private scanStdout(): void {
+ const p = this.pending;
+ if (!p || p.stdoutDoneIdx !== null) return;
+
+ const idx = p.stdoutBuf.indexOf(p.stdoutDoneMarker, p.stdoutScanIdx);
+
+ if (idx === -1) {
+ // Hold back a tail that could be a partial marker.
+ const hold = p.stdoutDoneMarker.length - 1;
+ const safe = Math.max(p.stdoutScanIdx, p.stdoutBuf.length - hold);
+ if (safe > p.stdoutScanIdx) {
+ const chunk = p.stdoutBuf.slice(p.stdoutScanIdx, safe);
+ p.onStdout?.(encoder.encode(chunk));
+ p.stdoutScanIdx = safe;
+ }
+ return;
+ }
+
+ // Emit any un-emitted bytes before the marker.
+ if (idx > p.stdoutScanIdx) {
+ const chunk = p.stdoutBuf.slice(p.stdoutScanIdx, idx);
+ p.onStdout?.(encoder.encode(chunk));
+ p.stdoutScanIdx = idx;
+ }
+
+ p.stdoutDoneIdx = idx;
+ this.tryComplete();
+ }
+
+ /** Extract user stderr up to the EXIT sentinel; parse the exit code. */
+ private scanStderr(): void {
+ const p = this.pending;
+ if (!p || p.stderrExitCode !== null) return;
+
+ const idx = p.stderrBuf.indexOf(p.stderrExitPrefix, p.stderrScanIdx);
+
+ if (idx === -1) {
+ const hold = p.stderrExitPrefix.length - 1;
+ const safe = Math.max(p.stderrScanIdx, p.stderrBuf.length - hold);
+ if (safe > p.stderrScanIdx) {
+ const chunk = p.stderrBuf.slice(p.stderrScanIdx, safe);
+ p.onStderr?.(encoder.encode(chunk));
+ p.stderrScanIdx = safe;
+ }
+ return;
+ }
+
+ if (idx > p.stderrScanIdx) {
+ const chunk = p.stderrBuf.slice(p.stderrScanIdx, idx);
+ p.onStderr?.(encoder.encode(chunk));
+ p.stderrScanIdx = idx;
+ }
+
+ const afterPrefix = idx + p.stderrExitPrefix.length;
+ const closeIdx = p.stderrBuf.indexOf("__", afterPrefix);
+ if (closeIdx === -1) return; // wait for more bytes
+
+ const exitStr = p.stderrBuf.slice(afterPrefix, closeIdx);
+ const exitCode = parseInt(exitStr, 10);
+ if (!Number.isFinite(exitCode)) {
+ this.state = "closed";
+ this.pending = null;
+ p.reject(new ShellClosedError(`corrupt sentinel: "${exitStr}"`));
+ return;
+ }
+
+ p.stderrExitCode = exitCode;
+ p.stderrExitIdx = idx;
+ this.tryComplete();
+ }
+
+ /** Resolve once both markers are in — guarantees both pipes are drained. */
+ private tryComplete(): void {
+ const p = this.pending;
+ if (!p) return;
+ if (p.stdoutDoneIdx === null || p.stderrExitCode === null) return;
+
+ const result: ProcessResult = {
+ exitCode: p.stderrExitCode,
+ stdout: p.stdoutBuf.slice(0, p.stdoutDoneIdx),
+ stderr: p.stderrBuf.slice(0, p.stderrExitIdx ?? p.stderrBuf.length),
+ };
+
+ this.pending = null;
+ if (this.state !== "closed") this.state = "idle";
+ p.resolve(result);
+ }
+
+ async run(cmd: string, opts: ShellRunOpts = {}): Promise<ProcessResult> {
+ if (this.state === "closed") throw new ShellClosedError();
+ if (this.state === "running") throw new ShellBusyError();
+
+ const token = newToken();
+ const stdoutDoneMarker = `\n__OC_${token}_DONE__\n`;
+ const stderrExitPrefix = `\n__OC_${token}_EXIT_`;
+
+ // `{ cmd\n}` groups the user command so `$?` captures its exit. The
+ // newline before `}` is required — `{ cmd\n; }` is a bash syntax error.
+ //
+ // Two markers, one per stream: DONE to stdout, EXIT to stderr. We
+ // resolve only when both are seen, which prevents a race where the
+ // stderr sentinel arrives before the user's stdout is drained (the
+ // agent reads stdout and stderr on separate goroutines, so wire
+ // ordering isn't guaranteed). Empty command becomes `:` (POSIX no-op).
+ const inner = cmd.trim() === "" ? ":" : cmd;
+ const wrapped =
+ `{ ${inner}\n} ; __oc_ec=$? ; ` +
+ `printf '\\n__OC_%s_DONE__\\n' '${token}' ; ` +
+ `printf '\\n__OC_%s_EXIT_%d__\\n' '${token}' "$__oc_ec" >&2\n`;
+
+ this.state = "running";
+ const run: PendingRun = {
+ token,
+ stdoutDoneMarker,
+ stderrExitPrefix,
+ stdoutBuf: "",
+ stderrBuf: "",
+ stdoutScanIdx: 0,
+ stderrScanIdx: 0,
+ stdoutDoneIdx: null,
+ stderrExitCode: null,
+ stderrExitIdx: null,
+ onStdout: opts.onStdout,
+ onStderr: opts.onStderr,
+ resolve: () => {},
+ reject: () => {},
+ };
+ const promise = new Promise<ProcessResult>((resolve, reject) => {
+ run.resolve = resolve;
+ run.reject = reject;
+ });
+ this.pending = run;
+
+ try {
+ this.session.sendStdin(wrapped);
+ } catch (err) {
+ this.pending = null;
+ this.state = "closed";
+ throw err;
+ }
+
+ return promise;
+ }
+
+ async close(): Promise<void> {
+ if (this.state === "closed") return;
+ this.state = "closed";
+ try {
+ this.session.sendStdin("exit\n");
+ } catch {
+ // session already dead
+ }
+ try {
+ await this.session.done;
+ } finally {
+ this.session.close();
+ }
+ }
+}