Secure, Fast, and Extensible Sandbox runtime for AI agents.
#
# Copyright 2025 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.
#
"""
Execution model converter utilities.
Provides conversion functions between API models and domain models for execution-related operations,
similar to the Kotlin SDK ExecutionConverter.
This converter is designed to work with openapi-python-client generated models.
"""
from datetime import timedelta
from typing import Any
from opensandbox.api.execd.models.run_command_request import (
RunCommandRequest as ApiRunCommandRequest,
)
from opensandbox.exceptions import InvalidArgumentException
from opensandbox.models.execd import RunCommandOpts
class ExecutionConverter:
"""
Execution model converter utilities.
Provides static methods to convert between API models and domain models
for execution-related operations.
The API models are generated by openapi-python-client and use attrs.
"""
@staticmethod
def to_api_run_command_request(command: str | list[str], opts: RunCommandOpts) -> ApiRunCommandRequest:
"""Convert domain command + options to API RunCommandRequest."""
from opensandbox.api.execd.models.run_command_request_envs import (
RunCommandRequestEnvs,
)
from opensandbox.api.execd.types import UNSET
# Convert working_directory to cwd, handling None
cwd = UNSET
if opts.working_directory:
cwd = opts.working_directory
background = UNSET
if opts.background:
background = opts.background
timeout_milliseconds = UNSET
if opts.timeout is not None:
if opts.timeout < timedelta(0):
raise InvalidArgumentException("timeout must be positive")
# Round up using integer microseconds to preserve whole milliseconds exactly.
timeout_milliseconds = (opts.timeout // timedelta(microseconds=1) + 999) // 1000
uid = UNSET
if opts.uid is not None:
uid = opts.uid
gid = UNSET
if opts.gid is not None:
gid = opts.gid
envs = UNSET
if opts.envs is not None:
envs_payload = RunCommandRequestEnvs()
for key, value in opts.envs.items():
envs_payload[key] = value
envs = envs_payload
if not isinstance(command, (str, list)):
raise InvalidArgumentException("command must be shell text or an argv list")
if isinstance(command, list) and (
not command or not command[0]
or any(not isinstance(arg, str) or "\0" in arg for arg in command)
):
raise InvalidArgumentException("argv requires a non-empty executable and strings without NUL")
return ApiRunCommandRequest(
command=command if isinstance(command, str) else UNSET,
argv=command if isinstance(command, list) else UNSET,
background=background,
cwd=cwd, # Domain uses 'working_directory', API uses 'cwd'
timeout=timeout_milliseconds,
uid=uid,
gid=gid,
envs=envs,
# Note: handlers are not included in API request as they are for local processing
)
@staticmethod
def to_api_run_command_json(command: str | list[str], opts: RunCommandOpts) -> dict[str, Any]:
"""
Convert command + options to a plain JSON-serializable dict for httpx requests.
Centralizes the attrs/pydantic differences behind one callsite.
"""
api_request = ExecutionConverter.to_api_run_command_request(command, opts)
if hasattr(api_request, "to_dict"):
return api_request.to_dict()
# Fallback (shouldn't normally happen for openapi-python-client models).
return dict(getattr(api_request, "__dict__", {}))