Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(cli): preserve PTY error frames on abnormal close and surface kept sessions
高然733caf98d005
diff --git a/cli/README.md b/cli/README.mdindex 44ab9079e..b979719c6 100644--- a/cli/README.md+++ b/cli/README.md@@ -303,7 +303,7 @@ osb terminal <sandbox-id>osb terminal <sandbox-id> -w /workspace```-Requires an interactive TTY, and is supported on Unix, macOS, and Linux. If the connection drops while the shell is still running, the session is kept server-side so it can still be inspected; a clean exit tears the session down.+Requires an interactive TTY, and is supported on Unix, macOS, and Linux. If the connection drops while the shell is still running, the session is kept server-side and its id is printed so it can be inspected or removed via the execd API; a clean exit tears the session down.### Work with filesdiff --git a/cli/src/opensandbox_cli/commands/terminal.py b/cli/src/opensandbox_cli/commands/terminal.pyindex edd62cb5c..2d7fbf0e3 100644--- a/cli/src/opensandbox_cli/commands/terminal.py+++ b/cli/src/opensandbox_cli/commands/terminal.py@@ -196,6 +196,7 @@ async def stream_pty(*,stdin_read: ReadFn,stdout_write: WriteFn,+ error_write: WriteFn | None = None,send_lock: asyncio.Lock | None = None,) -> tuple[int | None, list[str]]:"""Relay frames; the exit code is ``None`` without an ``exit`` frame."""@@ -204,26 +205,36 @@ async def stream_pty(async def read_ws() -> None:nonlocal exit_code- async for message in ws:- if isinstance(message, bytes) and message:- kind, payload = message[0], message[1:]- if kind == BIN_REPLAY:- if len(payload) <= 8:+ try:+ async for message in ws:+ if isinstance(message, bytes) and message:+ kind, payload = message[0], message[1:]+ if kind == BIN_REPLAY:+ if len(payload) <= 8:+ continue+ payload = payload[8:]+ if payload and kind in (BIN_STDOUT, BIN_STDERR, BIN_REPLAY):+ stdout_write(payload)+ elif isinstance(message, str):+ try:+ frame = json.loads(message)+ except json.JSONDecodeError:continue- payload = payload[8:]- if payload and kind in (BIN_STDOUT, BIN_STDERR, BIN_REPLAY):- stdout_write(payload)- elif isinstance(message, str):- try:- frame = json.loads(message)- except json.JSONDecodeError:- continue- frame_type = frame.get("type")- if frame_type == "exit":- exit_code = int(frame.get("exit_code") or 0)- return- if frame_type == "error":- errors.append(str(frame.get("error") or "unknown error"))+ frame_type = frame.get("type")+ if frame_type == "exit":+ exit_code = int(frame.get("exit_code") or 0)+ return+ if frame_type == "error":+ message = str(frame.get("error") or "unknown error")+ errors.append(message)+ if error_write is not None:+ # The terminal is in raw mode: CRLF, not LF.+ error_write(message.encode() + b"\r\n")+ except websockets.ConnectionClosed:+ # Abnormal close: keep the collected exit state and errors so the+ # caller can surface them (e.g. execd's START_FAILED closes+ # without a WebSocket close frame).+ passstdin_task = asyncio.create_task(_pump_stdin(ws, send_lock or asyncio.Lock(), stdin_read)@@ -247,6 +258,7 @@ async def _connect_and_stream(stdin_read: ReadFn,stdout_write: WriteFn,get_size: SizeFn,+ error_write: WriteFn | None = None,) -> tuple[int | None, list[str]]:"""Connect to the PTY WebSocket, drive the relay loop, handle resize."""async with websockets.connect(ws_url, additional_headers=headers or None) as ws:@@ -287,6 +299,7 @@ async def _connect_and_stream(ws,stdin_read=stdin_read,stdout_write=stdout_write,+ error_write=error_write,send_lock=send_lock,)finally:@@ -341,7 +354,13 @@ def terminal()stdin_read, stdout_write, get_size, stdin_fd = _posix_tty_io()- error_write = sys.stderr.buffer.write++ def report_error(data: bytes) -> None:+ # CRLF line endings are added by the sender: the terminal is in raw+ # mode, where a bare LF does not return the carriage.+ sys.stderr.buffer.write(data)+ sys.stderr.buffer.flush()+exit_code: int | None = Noneerrors: list[str] = []teardown = False@@ -354,9 +373,10 @@ def terminal(stdin_read=stdin_read,stdout_write=stdout_write,get_size=get_size,+ error_write=report_error,))- teardown = exit_code is not None+ teardown = exit_code is not None or bool(errors)except websockets.InvalidStatus as exc:raise click.ClickException(f"The execd refused the terminal connection: {exc}"@@ -364,16 +384,21 @@ def terminal(except (OSError, websockets.WebSocketException) as exc:raise click.ClickException(f"Terminal connection failed: {exc}") from excfinally:- # A clean shell exit tears the session down; an interrupted connection- # leaves it running (shell alive, replay retained) for inspection.+ # Clean exit tears the session down, as does a reported failure (e.g.+ # START_FAILED: the shell never ran, so there is nothing to preserve).+ # A lost connection on a live shell is the one case worth keeping.if teardown:_delete_pty_session(http_base, headers, session_id, timeout=timeout)- for message in errors:- error_write(message.encode() + b"\n")- sys.stderr.buffer.flush()if exit_code is None:- raise click.ClickException(- "The terminal connection closed before the shell exited."+ if errors:+ raise click.ClickException("Shell startup failed: " + "; ".join(errors))+ sys.stderr.write(+ "Warning: the terminal connection closed before the shell exited.\n"+ f"The PTY session was kept on the sandbox: {session_id}\n"+ f" status: GET {http_base}/pty/{session_id}\n"+ f" remove: DELETE {http_base}/pty/{session_id}\n")+ sys.stderr.flush()+ raise click.ClickException("Terminal connection lost.")sys.exit(exit_code)diff --git a/cli/tests/test_commands.py b/cli/tests/test_commands.pyindex 7c6480342..48c0b8a08 100644--- a/cli/tests/test_commands.py+++ b/cli/tests/test_commands.py@@ -31,6 +31,7 @@ from pathlib import Pathfrom unittest.mock import MagicMock, patchimport pytest+import websocketsfrom click.testing import CliRunnerfrom opensandbox.exceptions import SandboxApiExceptionfrom opensandbox.models.diagnostics import DiagnosticContent, DiagnosticContext@@ -2705,9 +2706,26 @@ class TestTerminal:)assert result.exit_code == 1- assert "closed before the shell exited" in result.stderr+ assert "kept on the sandbox: sess-1" in result.stderr+ assert "DELETE http://execd.example:44772/pty/sess-1" in result.stderrdelete.assert_not_called()+ def test_startup_failure_deletes_session_and_reports_error(+ self, runner: CliRunner+ ) -> None:+ incoming = ['{"type":"error","code":"START_FAILED","error":"no such dir"}']++ result, _, _, delete, _, _ = _invoke_terminal(+ runner,+ ["terminal", "sbx-1"],+ incoming=incoming,+ )++ assert result.exit_code == 1+ assert "Shell startup failed" in result.stderr+ assert "no such dir" in result.stderr+ assert delete.call_args.args[2] == "sess-1"+def test_server_error_frames_are_reported_on_stderr(self, runner: CliRunner) -> None:@@ -2753,6 +2771,42 @@ class TestStdinReader:class TestStreamPTY:+ def test_abnormal_close_preserves_collected_error_frames(self) -> None:+ class _AbnormalCloseWS(_FakePTYWebSocket):+ async def __anext__(self) -> object:+ try:+ return await super().__anext__()+ except StopAsyncIteration:+ # execd closes without a WebSocket close frame on startup+ # failure; the error frame must not be lost.+ raise websockets.ConnectionClosedError(None, None) from None++ async def scenario():+ ws = _AbnormalCloseWS(+ [+ '{"type":"error","code":"START_FAILED","error":"no such dir"}',+ b"\x01partial",+ ]+ )++ async def stdin_read() -> bytes:+ return b""++ chunks = bytearray()+ streamed = bytearray()+ result = await stream_pty(+ ws,+ stdin_read=stdin_read,+ stdout_write=chunks.extend,+ error_write=streamed.extend,+ )+ return result, bytes(chunks), bytes(streamed)++ (exit_code, errors), written, streamed = asyncio.run(scenario())+ assert (exit_code, errors) == (None, ["no such dir"])+ assert written == b"partial"+ assert streamed == b"no such dir\r\n"+def test_error_frames_are_collected_and_exit_code_returned(self) -> None:async def scenario() -> tuple[int | None, list[str]]:ws = _FakePTYWebSocket(diff --git a/docs/cli/index.md b/docs/cli/index.mdindex 5a70731c6..61281b467 100644--- a/docs/cli/index.md+++ b/docs/cli/index.md@@ -279,6 +279,17 @@ osb command session run <sandbox-id> <session-id> -o raw -- sh -c 'echo $FOO'osb command session delete <sandbox-id> <session-id> -o json```+### Open an interactive terminal++`osb terminal` attaches your current terminal to a real PTY inside the sandbox (colors, `stty`, and resize all behave like a local shell). Exit the remote shell (or press Ctrl-D) to leave; the remote exit code becomes the command's exit code.++```bash+osb terminal <sandbox-id>+osb terminal <sandbox-id> -w /workspace+```++Requires an interactive TTY, and is supported on Unix, macOS, and Linux. If the connection drops while the shell is still running, the session is kept server-side and its id is printed so it can be inspected or removed via the execd API; a clean exit tears the session down.+### Work with files```bash@@ -397,6 +408,7 @@ The main command groups are:- `osb template`: golden-image template builds- `osb snapshot`: snapshot management- `osb command`: command execution and persistent sessions+- `osb terminal`: interactive PTY terminal into a sandbox- `osb file`: file and directory operations- `osb egress`: runtime egress policy- `osb credential-vault`: sandbox-local credentials and bindings