Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(sdk-python): keep code-interpreter output fragments together in Execution.text
Jackmeson1c19a4233a844
diff --git a/docs/examples/code-interpreter.md b/docs/examples/code-interpreter.mdindex dec8ee265..5c8f15eea 100644--- a/docs/examples/code-interpreter.md+++ b/docs/examples/code-interpreter.md@@ -44,6 +44,8 @@ uv run python examples/code-interpreter/main.pyThe script creates a Sandbox + CodeInterpreter, runs a Python code snippet and prints stdout/result, then terminates the remote instance. Cleanup is attempted in a `finally` block even if interpreter setup or code execution raises an exception.+For `Execution` objects returned by the synchronous and asynchronous Python code-interpreter adapters, `execution.text` joins stdout fragments without inserting separators, so `"Loading"` followed by `"...done\n"` produces `"Loading...done"`. Formatted stdout and stderr retain the existing display normalization: CR/CRLF line endings become `\n` and trailing newlines are stripped; raw log messages and command-execution formatting are unchanged. The private formatting flag is not serialized: reconstructing an `Execution` from `model_dump()` or `model_dump_json()` output restores the default line formatting.+## Environment variables| Variable | Default | Description |diff --git a/sdks/code-interpreter/python/src/code_interpreter/adapters/code_adapter.py b/sdks/code-interpreter/python/src/code_interpreter/adapters/code_adapter.pyindex 07a8ac49c..30d8f9098 100644--- a/sdks/code-interpreter/python/src/code_interpreter/adapters/code_adapter.py+++ b/sdks/code-interpreter/python/src/code_interpreter/adapters/code_adapter.py@@ -316,6 +316,7 @@ class CodesAdapter(Codes):result=[],error=None,)+ execution._is_code_execution = True# Use SSE client for streaming responses (read timeout disabled)client = await self._get_sse_client()diff --git a/sdks/code-interpreter/python/src/code_interpreter/sync/adapters/code_adapter.py b/sdks/code-interpreter/python/src/code_interpreter/sync/adapters/code_adapter.pyindex 424c6b216..e6abfb50d 100644--- a/sdks/code-interpreter/python/src/code_interpreter/sync/adapters/code_adapter.py+++ b/sdks/code-interpreter/python/src/code_interpreter/sync/adapters/code_adapter.py@@ -310,6 +310,7 @@ class CodesAdapterSync(CodesSync):url = self._get_execd_url(self.RUN_CODE_PATH)execution = Execution(id=None, execution_count=None, result=[], error=None)+ execution._is_code_execution = Truedispatcher = ExecutionEventDispatcherSync(execution, handlers)with self._sse_client.stream("POST", url, json=api_request) as response:diff --git a/sdks/code-interpreter/python/tests/test_code_service_adapter_streaming.py b/sdks/code-interpreter/python/tests/test_code_service_adapter_streaming.pyindex a9d5a5e36..bd77ebc19 100644--- a/sdks/code-interpreter/python/tests/test_code_service_adapter_streaming.py+++ b/sdks/code-interpreter/python/tests/test_code_service_adapter_streaming.py@@ -21,6 +21,7 @@ from datetime import timedeltaimport httpximport pytestfrom opensandbox.config import ConnectionConfig+from opensandbox.config.connection_sync import ConnectionConfigSyncfrom opensandbox.exceptions import (InvalidArgumentException,SandboxApiException,@@ -33,6 +34,96 @@ from code_interpreter.adapters.converter.code_execution_converter import (CodeExecutionConverter,)from code_interpreter.models.code import CodeContext, SupportedLanguage+from code_interpreter.sync.adapters.code_adapter import CodesAdapterSync+++ params=[+ pytest.param((["Loading", "...done\n"], "Loading...done"), id="partial-line"),+ pytest.param(([".", ".", "."], "..."), id="progress-dots"),+ pytest.param((["first\n", "second\n"], "first\nsecond"), id="terminated-lines"),+ pytest.param((["first\n", "\n", "last\n"], "first\n\nlast"), id="blank-line"),+ pytest.param((["\n"], ""), id="only-blank-line"),+ pytest.param((["first\r", "last\r"], "first\nlast"), id="carriage-returns"),+ pytest.param((["first\r\n", "last\r\n"], "first\nlast"), id="crlf-lines"),+ pytest.param((["first\r", "\n", "last\r", "\n"], "first\nlast"), id="split-crlf"),+ pytest.param((["first\n", "last"], "first\nlast"), id="unterminated-final-fragment"),+ pytest.param((["", "Loading", "", "...done\n", ""], "Loading...done"), id="empty-fragments"),+ pytest.param(([], ""), id="no-output"),+ ]+)+def stream_fragments(request: pytest.FixtureRequest) -> tuple[list[str], str]:+ return request.param+++def _fragment_response(+ request: httpx.Request, stream: str, fragments: list[str]+) -> httpx.Response:+ """Replay synthetic stream events, without requiring execd or Jupyter."""+ assert request.url.path == "/code"+ events = [+ {"type": "init", "text": "exec-fragments", "timestamp": 0},+ *[+ {"type": stream, "text": text, "timestamp": index}+ for index, text in enumerate(fragments, start=1)+ ],+ {"type": "execution_complete", "timestamp": len(fragments) + 1},+ ]+ return httpx.Response(+ 200,+ headers={"Content-Type": "text/event-stream"},+ content="".join(f"data: {json.dumps(event)}\n\n" for event in events),+ request=request,+ )++[email protected]("stream", ["stdout", "stderr"])+async def test_run_code_preserves_stream_fragments(+ stream: str, stream_fragments: tuple[list[str], str]+) -> None:+ fragments, expected = stream_fragments+ transport = httpx.MockTransport(+ lambda request: _fragment_response(request, stream, fragments)+ )+ cfg = ConnectionConfig(protocol="http", transport=transport)+ adapter = CodesAdapter(SandboxEndpoint(endpoint="localhost:44772"), cfg)++ execution = await adapter.run("print('synthetic stream')")++ assert execution.id == "exec-fragments"+ assert execution.complete is not None+ assert [message.text for message in getattr(execution.logs, stream)] == fragments+ if stream == "stdout":+ assert execution.text == expected+ assert str(execution) == expected+ else:+ assert execution.text == ""+ assert str(execution) == (f"[stderr]\n{expected}" if fragments else "")++[email protected]("stream", ["stdout", "stderr"])+def test_sync_run_code_preserves_stream_fragments(+ stream: str, stream_fragments: tuple[list[str], str]+) -> None:+ fragments, expected = stream_fragments+ transport = httpx.MockTransport(+ lambda request: _fragment_response(request, stream, fragments)+ )+ cfg = ConnectionConfigSync(protocol="http", transport=transport)+ adapter = CodesAdapterSync(SandboxEndpoint(endpoint="localhost:44772"), cfg)++ execution = adapter.run("print('synthetic stream')")++ assert execution.id == "exec-fragments"+ assert execution.complete is not None+ assert [message.text for message in getattr(execution.logs, stream)] == fragments+ if stream == "stdout":+ assert execution.text == expected+ assert str(execution) == expected+ else:+ assert execution.text == ""+ assert str(execution) == (f"[stderr]\n{expected}" if fragments else "")class _SseTransport(httpx.AsyncBaseTransport):diff --git a/sdks/sandbox/python/src/opensandbox/models/execd.py b/sdks/sandbox/python/src/opensandbox/models/execd.pyindex cc5c04d75..e966a26b0 100644--- a/sdks/sandbox/python/src/opensandbox/models/execd.py+++ b/sdks/sandbox/python/src/opensandbox/models/execd.py@@ -23,7 +23,7 @@ from collections.abc import Awaitable, Callablefrom datetime import datetime, timedeltafrom typing import Any-from pydantic import BaseModel, ConfigDict, Field, model_validator+from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, model_validatorclass OutputMessage(BaseModel):@@ -119,13 +119,21 @@ class ExecutionLogs(BaseModel):self.stderr.append(message)-def _format_output_messages(messages: list[OutputMessage]) -> str:- """Format both legacy line events and events carrying their own line endings."""+def _format_output_messages(+ messages: list[OutputMessage], *, preserve_fragments: bool = False+) -> str:+ """Format command lines or code fragments, normalizing line endings for display."""parts: list[str] = []last_char = ""for message in messages:text = message.text- if text and last_char and last_char not in "\r\n" and text[0] not in "\r\n":+ if (+ not preserve_fragments+ and text+ and last_char+ and last_char not in "\r\n"+ and text[0] not in "\r\n"+ ):parts.append("\n")parts.append(text)if text:@@ -171,6 +179,8 @@ class Execution(BaseModel):for all execution-related data that is exposed to users."""+ _is_code_execution: bool = PrivateAttr(default=False)+id: str | None = Field(default=None, description="Unique execution identifier")execution_count: int | None = Field(default=None,@@ -208,7 +218,9 @@ class Execution(BaseModel):"""chunks: list[str] = []- stdout_text = _format_output_messages(self.logs.stdout)+ stdout_text = _format_output_messages(+ self.logs.stdout, preserve_fragments=self._is_code_execution+ )if stdout_text:chunks.append(stdout_text)@@ -226,7 +238,9 @@ class Execution(BaseModel):parts.append(self.text)if self.logs.stderr:- stderr_text = _format_output_messages(self.logs.stderr)+ stderr_text = _format_output_messages(+ self.logs.stderr, preserve_fragments=self._is_code_execution+ )parts.append(f"[stderr]\n{stderr_text}")if self.error: