Secure, Fast, and Extensible Sandbox runtime for AI agents.
#
# Copyright 2026 The OpenSandbox Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Isolated session adapter implementation (async).
Adapter for /v1/isolated/* endpoints using direct httpx + SSE streaming.
"""
import json
import logging
import httpx
from opensandbox._httpx import build_async_redirect_client_options
from opensandbox.adapters.converter.event_node import EventNode
from opensandbox.adapters.converter.exception_converter import ExceptionConverter
from opensandbox.adapters.converter.execution_event_dispatcher import (
ExecutionEventDispatcher,
)
from opensandbox.adapters.converter.response_handler import (
build_api_exception_from_httpx,
)
from opensandbox.adapters.isolated_filesystem_adapter import IsolatedFilesystemAdapter
from opensandbox.adapters.sse import aiter_sse_events
from opensandbox.config import ConnectionConfig
from opensandbox.exceptions import InvalidArgumentException
from opensandbox.models.execd import Execution, ExecutionHandlers
from opensandbox.models.isolated import (
CreateIsolatedSessionRequest,
IsolatedBackgroundRun,
IsolatedCapabilities,
IsolatedRunLogs,
IsolatedRunOpts,
IsolatedRunStatus,
IsolatedSessionInfo,
IsolatedSessionState,
IsolatedSessionSummary,
)
from opensandbox.models.sandboxes import SandboxEndpoint
from opensandbox.services.filesystem import Filesystem
from opensandbox.services.isolated import (
IsolationService,
IsolationServiceMixin,
IsolationSession,
)
from opensandbox.transport import streaming_transport
logger = logging.getLogger(__name__)
TAIL_CURSOR_HEADER = "EXECD-ISOLATED-TAIL-CURSOR"
def _decode_sse_event_data(data: str) -> EventNode | None:
if not data.strip():
return None
try:
event_dict = json.loads(data)
return EventNode(**event_dict)
except Exception as e:
logger.error(f"Failed to parse SSE event data: {data}", exc_info=e)
return None
def _infer_exit_code(execution: Execution) -> int | None:
if execution.error is not None:
# Prefer the authoritative error.exit_code; fall back to parsing evalue
# for servers that predate it.
if execution.error.exit_code is not None:
return execution.error.exit_code
try:
return int(execution.error.value)
except (TypeError, ValueError):
return None
if execution.complete is not None:
return 0
return None
# Creation-parameter fields execd may echo back in GET /v1/isolated/session/{id}.
# Older execd builds omit them; when absent we leave the corresponding field as
# None so the returned handle/state remains usable via session_id for
# run/get/delete/files.
#
# NOTE: ``idle_timeout_seconds`` uses ``is not None`` (not falsy) checks
# because 0 is a valid, meaningful configuration value ("no idle timeout").
_ECHO_FIELDS = (
"profile",
"workspace",
"overlays",
"extra_writable",
"binds",
"share_net",
"env_passthrough",
"uid",
"gid",
"uid_mode",
"idle_timeout_seconds",
)
def _forward_echo_fields(state: dict, payload: dict) -> None:
"""Copy creation-parameter echo fields from ``state`` into ``payload``.
Only fields present and non-null are forwarded; absent/null fields fall
back to the model defaults (``None``). ``0`` is preserved (e.g. for
``idle_timeout_seconds``).
"""
for key in _ECHO_FIELDS:
if key in state and state[key] is not None:
payload[key] = state[key]
def _build_attach_info(session_id: str, state: dict) -> IsolatedSessionInfo:
"""Build an :class:`IsolatedSessionInfo` from a ``GET`` session state payload.
Only fields actually returned by execd are forwarded; missing fields fall
back to the model defaults (``None``). ``session_id`` comes from the
caller because the endpoint identifies the session by path, not payload.
"""
payload: dict = {"session_id": session_id}
created_at = state.get("created_at")
if created_at is not None:
payload["created_at"] = created_at
_forward_echo_fields(state, payload)
return IsolatedSessionInfo(**payload)
def _build_session_state(state: dict) -> IsolatedSessionState:
"""Build an :class:`IsolatedSessionState` from a ``GET`` session state payload.
Preserves the required ``status`` field and the runtime timestamps
(``created_at``, ``last_run_at``, ``idle_remaining_seconds``), and
forwards the same creation-parameter echo fields as
:func:`_build_attach_info` when execd includes them.
"""
payload: dict = {"status": state["status"]}
for key in ("created_at", "last_run_at", "idle_remaining_seconds"):
if key in state and state[key] is not None:
payload[key] = state[key]
_forward_echo_fields(state, payload)
return IsolatedSessionState(**payload)
class IsolationSessionHandle(IsolationSession):
"""Async handle to a single isolated session."""
def __init__(self, info: IsolatedSessionInfo, adapter: "IsolatedSessionsAdapter"):
self._info = info
self._adapter = adapter
self._files: Filesystem | None = None
@property
def session_id(self) -> str:
return self._info.session_id
@property
def info(self) -> IsolatedSessionInfo:
return self._info
@property
def files(self) -> Filesystem:
if self._files is None:
self._files = IsolatedFilesystemAdapter(
self._adapter.connection_config,
self._adapter.execd_endpoint,
self._info.session_id,
)
return self._files
async def run(
self,
code: str,
*,
opts: IsolatedRunOpts | None = None,
handlers: ExecutionHandlers | None = None,
) -> Execution:
return await self._adapter._run(
self._info.session_id, code, opts=opts, handlers=handlers
)
async def run_background(
self,
code: str,
*,
opts: IsolatedRunOpts | None = None,
) -> IsolatedBackgroundRun:
return await self._adapter._run_background(
self._info.session_id, code, opts=opts
)
async def run_status(self, run_id: str) -> IsolatedRunStatus:
return await self._adapter._run_status(self._info.session_id, run_id)
async def run_logs(self, run_id: str, cursor: int = 0) -> IsolatedRunLogs:
return await self._adapter._run_logs(
self._info.session_id, run_id, cursor=cursor
)
async def get(self) -> IsolatedSessionState:
return await self._adapter._get(self._info.session_id)
async def delete(self) -> None:
return await self._adapter._delete(self._info.session_id)
class IsolatedSessionsAdapter(IsolationServiceMixin, IsolationService):
"""Async adapter for isolated session endpoints (/v1/isolated/*).
``run_once``/``session`` are inherited from :class:`IsolationServiceMixin`.
"""
CREATE_PATH = "/v1/isolated/session"
SESSION_PATH = "/v1/isolated/session/{session_id}"
RUN_PATH = "/v1/isolated/session/{session_id}/run"
RUN_STATUS_PATH = "/v1/isolated/session/{session_id}/runs/{run_id}"
RUN_LOGS_PATH = "/v1/isolated/session/{session_id}/runs/{run_id}/logs"
SESSIONS_PATH = "/v1/isolated/sessions"
CAPABILITIES_PATH = "/v1/isolated/capabilities"
def __init__(
self,
connection_config: ConnectionConfig,
execd_endpoint: SandboxEndpoint,
) -> None:
self.connection_config = connection_config
self.execd_endpoint = execd_endpoint
protocol = self.connection_config.protocol
base_url = f"{protocol}://{self.execd_endpoint.endpoint}"
timeout_seconds = self.connection_config.request_timeout.total_seconds()
timeout = httpx.Timeout(timeout_seconds)
headers = self.execd_endpoint.build_request_headers(self.connection_config)
self._httpx_client = httpx.AsyncClient(
base_url=base_url,
headers=headers,
timeout=timeout,
transport=self.connection_config.transport,
**build_async_redirect_client_options(self.connection_config, base_url),
)
sse_headers = {
**headers,
"Accept": "text/event-stream",
"Cache-Control": "no-cache",
}
# SSE bootstraps keep only the wake-timeout retry: a non-idempotent
# status opt-in would cause duplicate execution on a resent SSE POST.
self._sse_client = httpx.AsyncClient(
headers=sse_headers,
timeout=httpx.Timeout(
connect=timeout_seconds,
read=None,
write=timeout_seconds,
pool=None,
),
transport=streaming_transport(self.connection_config.transport),
**build_async_redirect_client_options(self.connection_config, base_url),
)
def _get_url(self, path: str) -> str:
protocol = self.connection_config.protocol
return f"{protocol}://{self.execd_endpoint.endpoint}{path}"
async def create(
self, request: CreateIsolatedSessionRequest
) -> IsolationSessionHandle:
try:
url = self._get_url(self.CREATE_PATH)
body = request.model_dump(exclude_none=True)
response = await self._httpx_client.post(url, json=body)
if response.status_code not in (200, 201):
raise build_api_exception_from_httpx(
response, "create isolated session"
)
data = response.json()
info = IsolatedSessionInfo(**data)
return IsolationSessionHandle(info, self)
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e
async def attach(self, session_id: str) -> IsolationSessionHandle:
if not (session_id and session_id.strip()):
raise InvalidArgumentException("session_id cannot be empty")
try:
url = self._get_url(self.SESSION_PATH.format(session_id=session_id))
response = await self._httpx_client.get(url)
if response.status_code != 200:
raise build_api_exception_from_httpx(
response, "attach isolated session"
)
info = _build_attach_info(session_id, response.json())
return IsolationSessionHandle(info, self)
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e
async def _get(self, session_id: str) -> IsolatedSessionState:
if not (session_id and session_id.strip()):
raise InvalidArgumentException("session_id cannot be empty")
try:
url = self._get_url(self.SESSION_PATH.format(session_id=session_id))
response = await self._httpx_client.get(url)
if response.status_code != 200:
raise build_api_exception_from_httpx(
response, "get isolated session"
)
return _build_session_state(response.json())
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e
async def _run(
self,
session_id: str,
code: str,
*,
opts: IsolatedRunOpts | None = None,
handlers: ExecutionHandlers | None = None,
) -> Execution:
if not (session_id and session_id.strip()):
raise InvalidArgumentException("session_id cannot be empty")
if not (code and code.strip()):
raise InvalidArgumentException("code cannot be empty")
opts = opts or IsolatedRunOpts()
json_body: dict = {"code": code}
if opts.envs:
json_body["envs"] = opts.envs
if opts.timeout_seconds is not None:
json_body["timeout_seconds"] = opts.timeout_seconds
url = self._get_url(self.RUN_PATH.format(session_id=session_id))
try:
execution = Execution(id=None, execution_count=None, result=[], error=None)
client = self._sse_client
async with client.stream("POST", url, json=json_body) as response:
if response.status_code != 200:
await response.aread()
raise build_api_exception_from_httpx(
response, "run in isolated session"
)
dispatcher = ExecutionEventDispatcher(execution, handlers)
async for event in aiter_sse_events(response):
event_node = _decode_sse_event_data(event.data)
if event_node is None:
continue
await dispatcher.dispatch(event_node)
execution.exit_code = _infer_exit_code(execution)
return execution
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e
async def _run_background(
self,
session_id: str,
code: str,
*,
opts: IsolatedRunOpts | None = None,
) -> IsolatedBackgroundRun:
if not (session_id and session_id.strip()):
raise InvalidArgumentException("session_id cannot be empty")
if not (code and code.strip()):
raise InvalidArgumentException("code cannot be empty")
opts = opts or IsolatedRunOpts()
json_body: dict = {"code": code, "background": True}
if opts.envs:
json_body["envs"] = opts.envs
# timeout_seconds is foreground-only and deliberately not sent.
url = self._get_url(self.RUN_PATH.format(session_id=session_id))
try:
response = await self._httpx_client.post(url, json=json_body)
if response.status_code != 202:
raise build_api_exception_from_httpx(
response, "run background in isolated session"
)
return IsolatedBackgroundRun(**response.json())
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e
async def _run_status(
self, session_id: str, run_id: str
) -> IsolatedRunStatus:
if not (session_id and session_id.strip()):
raise InvalidArgumentException("session_id cannot be empty")
if not (run_id and run_id.strip()):
raise InvalidArgumentException("run_id cannot be empty")
try:
url = self._get_url(
self.RUN_STATUS_PATH.format(session_id=session_id, run_id=run_id)
)
response = await self._httpx_client.get(url)
if response.status_code != 200:
raise build_api_exception_from_httpx(
response, "get isolated run status"
)
return IsolatedRunStatus(**response.json())
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e
async def _run_logs(
self,
session_id: str,
run_id: str,
*,
cursor: int = 0,
) -> IsolatedRunLogs:
if not (session_id and session_id.strip()):
raise InvalidArgumentException("session_id cannot be empty")
if not (run_id and run_id.strip()):
raise InvalidArgumentException("run_id cannot be empty")
if cursor < 0:
raise InvalidArgumentException("cursor cannot be negative")
try:
url = self._get_url(
self.RUN_LOGS_PATH.format(session_id=session_id, run_id=run_id)
)
params = {"cursor": cursor} if cursor else None
response = await self._httpx_client.get(url, params=params)
if response.status_code != 200:
raise build_api_exception_from_httpx(
response, "get isolated run logs"
)
next_cursor = response.headers.get(TAIL_CURSOR_HEADER)
if next_cursor is not None:
try:
cursor_value = int(next_cursor)
except (TypeError, ValueError):
cursor_value = cursor + len(response.content)
else:
cursor_value = cursor + len(response.content)
return IsolatedRunLogs(text=response.text, cursor=cursor_value)
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e
async def _delete(self, session_id: str) -> None:
if not (session_id and session_id.strip()):
raise InvalidArgumentException("session_id cannot be empty")
try:
url = self._get_url(self.SESSION_PATH.format(session_id=session_id))
response = await self._httpx_client.delete(url)
if response.status_code not in (200, 204):
raise build_api_exception_from_httpx(
response, "delete isolated session"
)
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e
async def list(self) -> list[IsolatedSessionSummary]:
try:
url = self._get_url(self.SESSIONS_PATH)
response = await self._httpx_client.get(url)
if response.status_code != 200:
raise build_api_exception_from_httpx(
response, "list isolated sessions"
)
data = response.json()
return [
IsolatedSessionSummary(**item) for item in data.get("sessions", [])
]
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e
async def capabilities(self) -> IsolatedCapabilities:
try:
url = self._get_url(self.CAPABILITIES_PATH)
response = await self._httpx_client.get(url)
if response.status_code != 200:
raise build_api_exception_from_httpx(
response, "get capabilities"
)
data = response.json()
return IsolatedCapabilities(**data)
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e