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.
#
"""
Sandbox-related data models.
Models for sandbox creation, configuration, status, and lifecycle management.
"""
import ipaddress
import re
from datetime import datetime
from typing import TYPE_CHECKING, Literal
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
if TYPE_CHECKING:
from opensandbox.config import ConnectionConfig
from opensandbox.config.connection_sync import ConnectionConfigSync
def _is_ip_or_cidr(value: str) -> bool:
"""Mirror the sidecar's netip-based target classification."""
try:
ipaddress.ip_address(value)
return True
except ValueError:
pass
if "/" in value and not value.partition("/")[2].isdigit():
return False
# netip.ParsePrefix rejects scoped prefixes ("fe80::1%eth0/64") even
# though Python's ipaddress accepts them; classify those as domains too.
if "/" in value and "%" in value:
return False
try:
ipaddress.ip_network(value, strict=False)
return True
except ValueError:
return False
class SandboxImageAuth(BaseModel):
"""
Authentication credentials for container registries.
"""
username: str = Field(description="Registry username")
password: str = Field(description="Registry password or access token")
@field_validator("username")
@classmethod
def username_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("Username cannot be blank")
return v
@field_validator("password")
@classmethod
def password_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("Password cannot be blank")
return v
class SandboxImageSpec(BaseModel):
"""
Specification for a sandbox container image.
Usage:
# Simple creation with just image
spec = SandboxImageSpec("python:3.11")
# With private registry auth
spec = SandboxImageSpec(
"my-registry.com/image:tag",
auth=SandboxImageAuth(username="user", password="pass")
)
"""
image: str = Field(
description="Image reference (e.g., 'ubuntu:22.04', 'python:3.11')"
)
auth: SandboxImageAuth | None = Field(
default=None, description="Authentication for private registries"
)
def __init__(
self,
image: str | None = None,
*,
auth: SandboxImageAuth | None = None,
**data: object,
) -> None:
"""
Initialize SandboxImageSpec.
Args:
image: Container image reference (positional or keyword)
auth: Optional authentication for private registries
"""
if image is not None:
data["image"] = image
if auth is not None:
data["auth"] = auth
super().__init__(**data)
@field_validator("image")
@classmethod
def image_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("Image cannot be blank")
return v
class PlatformSpec(BaseModel):
"""Runtime platform constraint for sandbox provisioning."""
os: Literal["linux", "windows"] = Field(
description="Target operating system for sandbox provisioning."
)
arch: Literal["amd64", "arm64"] = Field(
description="Target CPU architecture for sandbox provisioning."
)
class NetworkRule(BaseModel):
"""
Egress rule for matching network targets.
"""
action: Literal["allow", "deny"] = Field(
description='Whether to allow or deny matching targets. One of "allow" or "deny".'
)
target: str | None = Field(
default=None,
description=(
'FQDN, wildcard domain (e.g., "example.com", "*.example.com"), IP address, or CIDR. '
"May be omitted when `ports` is set; otherwise required."
),
)
ports: list[int] | None = Field(
default=None,
description=(
"Restricts this rule to specific TCP destination ports (1-65535, max 256, no "
"duplicates). Omitted target with ports set applies to all IPv4/IPv6 destinations; "
"a domain target with ports is rejected. TCP only."
),
min_length=1,
max_length=256,
)
@field_validator("target")
@classmethod
def target_must_not_be_empty(cls, v: str | None) -> str | None:
# Blank = omitted (sidecar read-back emits "target": ""); trim like
# the server does.
if v is None:
return None
v = v.strip()
return v or None
@field_validator("ports")
@classmethod
def ports_must_be_valid_tcp_ports(cls, v: list[int] | None) -> list[int] | None:
if v is None:
return v
seen: set[int] = set()
for port in v:
if port < 1 or port > 65535:
raise ValueError(f"Network rule port {port} out of range 1-65535")
if port in seen:
raise ValueError(f"Network rule has duplicate port {port}")
seen.add(port)
return v
@model_validator(mode="after")
def target_or_ports_required(self) -> "NetworkRule":
if self.target is None and not self.ports:
raise ValueError("Network rule requires target, ports, or both")
# Classify the trimmed target the way the sidecar does, so " 10.0.0.5"
# is an IP locally too instead of a misleading domain+ports error.
if self.ports and self.target is not None and not _is_ip_or_cidr(self.target.strip()):
raise ValueError("Network rule ports are not supported for domain targets")
return self
class NetworkPolicy(BaseModel):
"""
Egress network policy matching the sidecar `/policy` request body.
"""
default_action: Literal["allow", "deny"] | None = Field(
default="deny",
description='Default action when no rule matches. Defaults to "deny".',
alias="defaultAction",
)
egress: list[NetworkRule] | None = Field(
default=None,
description="List of egress rules evaluated in order.",
)
model_config = ConfigDict(populate_by_name=True)
class CredentialProxyConfig(BaseModel):
"""
Credential Vault proxy startup settings.
"""
enabled: bool = Field(
default=False,
description="Enable transparent MITM support required by Credential Vault injection.",
)
class LifecycleHook(BaseModel):
"""Command executed by execd before the user entrypoint starts."""
command: list[str] = Field(min_length=1)
timeout_seconds: int | None = Field(
default=None,
alias="timeoutSeconds",
description="Maximum execution time in seconds. The server validates the value and defaults to 60.",
)
@field_validator("command")
@classmethod
def command_must_not_be_blank(cls, value: list[str]) -> list[str]:
if not value[0].strip():
raise ValueError("Lifecycle hook command must not be empty")
return value
model_config = ConfigDict(populate_by_name=True, extra="forbid")
class PeriodicLifecycleHook(BaseModel):
"""Named command scheduled by execd while the sandbox is running."""
name: str = Field(min_length=1)
schedule: str = Field(min_length=1)
command: list[str] = Field(min_length=1)
timeout_seconds: int | None = Field(
default=None,
alias="timeoutSeconds",
description="Maximum execution time in seconds. The server validates the value and defaults to 60.",
)
@field_validator("name", "schedule")
@classmethod
def text_must_not_be_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("Periodic lifecycle hook fields must not be blank")
return value.strip()
@field_validator("command")
@classmethod
def command_must_not_be_blank(cls, value: list[str]) -> list[str]:
if not value[0].strip():
raise ValueError("Periodic lifecycle hook command must not be empty")
return value
model_config = ConfigDict(populate_by_name=True, extra="forbid")
class ActivityProbe(BaseModel):
"""
Application-declared activity probe (OSEP-0024 ``idlePolicy.activeProbe``).
The server issues ``GET {path}`` on ``{port}`` when the sandbox is
otherwise idle; ``200 {"active": true}`` counts as activity and resets
the idle clock, while ``{"active": false}``, any failure, or a timeout
records nothing.
"""
port: int = Field(
ge=1,
le=65535,
description="Sandbox port serving the probe endpoint.",
)
path: str = Field(
min_length=1,
max_length=512,
pattern=r"^/",
description=(
"Absolute HTTP path of the probe endpoint. Must not contain "
"whitespace or control characters."
),
)
timeout_seconds: int | None = Field(
default=None,
alias="timeoutSeconds",
ge=1,
le=10,
description=(
"Probe request budget in seconds. The server defaults to 2 when omitted."
),
)
@field_validator("path")
@classmethod
def path_must_not_contain_whitespace_or_control_chars(
cls, value: str
) -> str:
if any(ord(c) < 0x20 or c == "\x7f" or c.isspace() for c in value):
raise ValueError(
"Probe path must not contain whitespace or control characters"
)
return value
model_config = ConfigDict(populate_by_name=True, extra="forbid")
class IdlePolicy(BaseModel):
"""
Idle behavior declared by the sandbox (OSEP-0024).
With ``idle_timeout_seconds``, the sandbox is auto-paused after that many
seconds without ingress-observed activity (fast-sandbox backend only).
Without it, the policy is wake-only: the sandbox is never auto-paused,
but a (manually) paused sandbox wakes on access.
Omitting ``idlePolicy`` from :class:`SandboxLifecycle` preserves
non-automated behavior exactly: never auto-paused, never auto-woken.
"""
idle_timeout_seconds: int | None = Field(
default=None,
alias="idleTimeoutSeconds",
ge=30,
le=86400,
description=(
"Idle threshold X in seconds: the sandbox is auto-paused after X "
"continuously idle seconds. Must not exceed the server's "
"configured activity TTL (default 1800)."
),
)
on_idle: Literal["pause"] | None = Field(
default=None,
alias="onIdle",
description=(
"Action taken at the idle threshold. Required with, and only "
"valid with, idle_timeout_seconds. Only 'pause' exists today."
),
)
wake_on_access: bool = Field(
default=True,
alias="wakeOnAccess",
description=(
"Whether incoming traffic may wake the sandbox from Paused. "
"false keeps today's paused behavior (permanent 503 through the "
"gateway) and only the resume API restores the sandbox."
),
)
active_probe: ActivityProbe | None = Field(
default=None,
alias="activeProbe",
description=(
"Application-declared activity probe; relevant only with auto-pause."
),
)
@model_validator(mode="after")
def on_idle_requires_idle_timeout(self) -> "IdlePolicy":
if self.idle_timeout_seconds is None:
if self.on_idle is not None:
raise ValueError(
"onIdle must be omitted when idleTimeoutSeconds is omitted "
"(a policy without a timeout is wake-only)"
)
elif self.on_idle != "pause":
raise ValueError("onIdle must be 'pause' when idleTimeoutSeconds is set")
return self
model_config = ConfigDict(populate_by_name=True, extra="forbid")
class RenewalPolicy(BaseModel):
"""
Renew-on-access behavior (OSEP-0009): observed access moves the
expiration to ``max(now + extend_seconds, current)``. Control-plane
policy; supersedes the deprecated ``access.renew.extend.seconds``
extensions key.
"""
extend_seconds: int = Field(
alias="extendSeconds",
ge=300,
le=86400,
description=(
"Extension window X in seconds for each access-driven renewal: "
"the expiration is moved to max(now + X, current expiresAt)."
),
)
model_config = ConfigDict(populate_by_name=True, extra="forbid")
class SandboxLifecycle(BaseModel):
"""Optional lifecycle hooks applied when a sandbox is created."""
pre_start: LifecycleHook | None = Field(default=None, alias="preStart")
periodic: list[PeriodicLifecycleHook] | None = None
idle_policy: IdlePolicy | None = Field(
default=None,
alias="idlePolicy",
description=(
"Auto-pause and wake-on-access behavior (OSEP-0024). Control-plane "
"policy only: it never reaches the guest. Supported only by the "
"fast-sandbox backend."
),
)
renewal_policy: RenewalPolicy | None = Field(
default=None,
alias="renewalPolicy",
description=(
"Renew-on-access behavior (OSEP-0009). Control-plane policy; "
"supersedes the deprecated extensions['access.renew.extend.seconds'] key."
),
)
@model_validator(mode="after")
def periodic_names_must_be_unique(self) -> "SandboxLifecycle":
names = [hook.name for hook in self.periodic or []]
if len(names) != len(set(names)):
raise ValueError("Periodic lifecycle hook names must be unique")
return self
model_config = ConfigDict(populate_by_name=True, extra="forbid")
class InlineCredentialSource(BaseModel):
"""
Write-only inline credential material for Credential Vault.
"""
model_config = ConfigDict(extra="forbid")
value: str = Field(repr=False, description="Inline credential value.")
type: Literal["inline"] = Field(
default="inline",
description="Credential source type. Defaults to inline for the Python SDK.",
)
@field_validator("value")
@classmethod
def value_must_not_be_empty(cls, v: str) -> str:
if not v:
raise ValueError("Credential source value cannot be empty")
return v
class ExchangeCredentialSource(BaseModel):
"""
Exchange credential source (OSEP-0025): no local material; ``endpoint``
is configuration, not secret material.
"""
model_config = ConfigDict(extra="forbid")
type: Literal["exchange"] = Field(
default="exchange", description="Credential source type."
)
endpoint: str = Field(
description="Header-resolver endpoint (unix:///path or https://host[:port])."
)
@field_validator("endpoint")
@classmethod
def endpoint_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("Credential source endpoint cannot be blank")
return v
class Credential(BaseModel):
"""Sandbox-local Credential Vault credential."""
name: str = Field(description="Sandbox-local credential name.")
source: InlineCredentialSource | ExchangeCredentialSource | dict[str, str] = Field(
description="Write-only credential source (inline material or exchange endpoint)."
)
@field_validator("name")
@classmethod
def credential_name_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("Credential name cannot be blank")
return v
@model_validator(mode="after")
def normalize_source(self) -> "Credential":
if isinstance(self.source, dict):
if self.source.get("type", "inline") == "exchange":
self.source = ExchangeCredentialSource.model_validate(self.source)
else:
self.source = InlineCredentialSource.model_validate(self.source)
return self
class CredentialMatch(BaseModel):
"""Request match for a Credential Vault binding."""
schemes: list[Literal["https", "http"]] | None = Field(default=None)
ports: list[int] | None = Field(default=None, deprecated="Port is derived from scheme (https→443, http→80). Values other than 80 or 443 are rejected by the server.")
hosts: list[str] = Field(description="Exact FQDNs or leftmost-label wildcards.")
methods: list[str] | None = Field(default=None)
paths: list[str] | None = Field(default=None)
@field_validator("hosts")
@classmethod
def hosts_must_not_be_empty(cls, v: list[str]) -> list[str]:
if not v:
raise ValueError("Credential match hosts cannot be empty")
if any(not host.strip() for host in v):
raise ValueError("Credential match host cannot be blank")
return v
class CustomHeaderEntry(BaseModel):
"""Custom header injection entry."""
name: str
credential: str
class CredentialSubstitution(BaseModel):
"""Scoped placeholder substitution entry."""
credential: str
placeholder: str
in_: list[Literal["path", "query", "header", "body"]] = Field(alias="in")
model_config = ConfigDict(populate_by_name=True)
class CredentialAuth(BaseModel):
"""Credential Vault auth rule: ``type`` selects one of the five static
kinds; leaving it unset selects the typeless exchange form (OSEP-0025),
which sets only ``credential``."""
type: Literal["bearer", "basic", "apiKey", "customHeaders", "passthrough"] | None = (
None
)
credential: str | None = None
name: str | None = None
headers: list[CustomHeaderEntry] | None = None
substitutions: list[CredentialSubstitution] | None = None
@model_validator(mode="after")
def typeless_form_must_only_carry_credential(self) -> "CredentialAuth":
if self.type is not None:
return self
if not (self.credential or "").strip():
raise ValueError(
"CredentialAuth requires either a static 'type' or an"
" exchange 'credential' reference"
)
if self.name is not None or self.headers is not None or self.substitutions is not None:
raise ValueError(
"The typeless exchange auth form carries only 'credential';"
" 'name', 'headers', and 'substitutions' require a static 'type'"
)
return self
class CredentialBinding(BaseModel):
"""Sandbox-local Credential Vault binding."""
name: str
match: CredentialMatch | dict[str, object]
auth: CredentialAuth | dict[str, object]
@field_validator("name")
@classmethod
def binding_name_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("Credential binding name cannot be blank")
return v
@model_validator(mode="after")
def normalize_nested_models(self) -> "CredentialBinding":
if isinstance(self.match, dict):
self.match = CredentialMatch.model_validate(self.match)
if isinstance(self.auth, dict):
self.auth = CredentialAuth.model_validate(self.auth)
return self
class CredentialMetadata(BaseModel):
"""Sanitized credential metadata returned by Credential Vault."""
name: str
source_type: str = Field(
alias="sourceType",
description="Credential source kind (inline or exchange).",
)
revision: int
model_config = ConfigDict(populate_by_name=True)
class CredentialAuthMetadata(BaseModel):
"""Sanitized auth metadata: static kinds carry ``type`` (``name`` for
apiKey); the typeless form carries only ``credential``."""
type: str | None = None
name: str | None = None
credential: str | None = None
class CredentialBindingMetadata(BaseModel):
"""Sanitized binding metadata returned by Credential Vault."""
name: str
revision: int
match: CredentialMatch | None = None
auth: CredentialAuthMetadata | None = None
class CredentialVaultState(BaseModel):
"""Sanitized Credential Vault state."""
revision: int
credentials: list[CredentialMetadata]
bindings: list[CredentialBindingMetadata]
class CredentialListResponse(BaseModel):
"""Sanitized Credential Vault credential list response."""
revision: int
credentials: list[CredentialMetadata]
class CredentialBindingListResponse(BaseModel):
"""Sanitized Credential Vault binding list response."""
revision: int
bindings: list[CredentialBindingMetadata]
class CredentialMutationSet(BaseModel):
"""Atomic credential mutation set for Credential Vault patch."""
add: list[Credential | dict[str, object]] | None = None
replace: list[Credential | dict[str, object]] | None = None
delete: list[str] | None = None
class CredentialBindingMutationSet(BaseModel):
"""Atomic binding mutation set for Credential Vault patch."""
add: list[CredentialBinding | dict[str, object]] | None = None
replace: list[CredentialBinding | dict[str, object]] | None = None
delete: list[str] | None = None
class CredentialVaultPatchRequest(BaseModel):
"""Credential Vault patch request."""
expected_revision: int | None = Field(default=None, alias="expectedRevision")
credentials: CredentialMutationSet | dict[str, object] | None = None
bindings: CredentialBindingMutationSet | dict[str, object] | None = None
model_config = ConfigDict(populate_by_name=True)
# ============================================================================
# Volume Models
# ============================================================================
# Matches Unix absolute paths (/…) and Windows drive-letter paths (C:\ or C:/).
# Aligned with server-side pattern in server/opensandbox_server/api/schema.py.
_HOST_PATH_RE = re.compile(r"^(/|[A-Za-z]:[\\/])")
class Host(BaseModel):
"""
Host path bind mount backend.
Maps a directory on the host filesystem into the container.
Only available when the runtime supports host mounts.
"""
path: str = Field(description="Absolute path on the host filesystem to mount.")
@field_validator("path")
@classmethod
def path_must_be_absolute(cls, v: str) -> str:
if not _HOST_PATH_RE.match(v):
raise ValueError(
"Host path must be an absolute path starting with '/' "
"or a Windows drive letter (e.g. 'C:\\' or 'D:/')"
)
return v
class PVC(BaseModel):
"""
Platform-managed named volume backend.
Runtime-neutral abstraction for referencing a pre-existing named volume:
- Kubernetes: maps to a PersistentVolumeClaim in the same namespace.
- Docker: maps to a Docker named volume.
"""
claim_name: str = Field(
description=(
"Name of the platform volume. In Kubernetes this is the PVC name; "
"in Docker this is the named volume name."
),
alias="claimName",
)
create_if_not_exists: bool = Field(
default=True,
alias="createIfNotExists",
description="When true, auto-create the volume if it does not exist.",
)
delete_on_sandbox_termination: bool = Field(
default=False,
alias="deleteOnSandboxTermination",
description=(
"When true, the auto-created volume (Docker named volume or "
"Kubernetes PVC) is removed on sandbox deletion. Pre-existing "
"volumes are never removed."
),
)
storage_class: str | None = Field(
default=None,
alias="storageClass",
description=(
"Kubernetes StorageClass for auto-created PVCs. "
"Null means cluster default. Ignored for Docker."
),
)
storage: str | None = Field(
default=None,
description=(
"Storage capacity request for auto-created PVCs (e.g. '1Gi'). "
"Ignored for Docker."
),
)
access_modes: list[str] | None = Field(
default=None,
alias="accessModes",
description=(
"Access modes for auto-created PVCs (e.g. ['ReadWriteOnce']). "
"Ignored for Docker."
),
)
model_config = ConfigDict(populate_by_name=True)
@field_validator("claim_name")
@classmethod
def claim_name_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("PVC claim name cannot be blank")
return v
class OSSFS(BaseModel):
"""Alibaba Cloud OSS mount backend via ossfs."""
bucket: str = Field(description="OSS bucket name.")
endpoint: str = Field(
description="OSS endpoint (e.g., oss-cn-hangzhou.aliyuncs.com)."
)
version: Literal["1.0", "2.0"] = Field(
default="2.0",
description="ossfs major version used by runtime mount integration.",
)
options: list[str] | None = Field(
default=None,
description="Additional ossfs mount options.",
)
access_key_id: str | None = Field(
default=None,
alias="accessKeyId",
description="OSS access key ID for inline credentials mode.",
)
access_key_secret: str | None = Field(
default=None,
alias="accessKeySecret",
description="OSS access key secret for inline credentials mode.",
)
model_config = ConfigDict(populate_by_name=True)
@model_validator(mode="after")
def validate_inline_credentials(self) -> "OSSFS":
if not self.access_key_id or not self.access_key_secret:
raise ValueError(
"OSSFS inline credentials are required: accessKeyId and accessKeySecret."
)
return self
class Volume(BaseModel):
"""
Storage mount definition for a sandbox.
Each volume entry contains:
- A unique name identifier
- Exactly one backend (host, pvc, ossfs) with backend-specific fields
- Common mount settings (mount_path, read_only, sub_path)
Usage:
# Host path mount (read-write by default)
volume = Volume(
name="workdir",
host=Host(path="/data/opensandbox"),
mount_path="/mnt/work",
)
# PVC mount (read-only)
volume = Volume(
name="models",
pvc=PVC(claim_name="shared-models-pvc"),
mount_path="/mnt/models",
read_only=True,
)
"""
name: str = Field(
description="Unique identifier for the volume within the sandbox."
)
host: Host | None = Field(
default=None,
description="Host path bind mount backend.",
)
pvc: PVC | None = Field(
default=None,
description="Kubernetes PersistentVolumeClaim mount backend.",
)
ossfs: OSSFS | None = Field(
default=None,
description="OSSFS mount backend.",
)
mount_path: str = Field(
description="Absolute path inside the container where the volume is mounted.",
alias="mountPath",
)
read_only: bool = Field(
default=False,
description="If true, the volume is mounted as read-only. Defaults to false (read-write).",
alias="readOnly",
)
sub_path: str | None = Field(
default=None,
description="Optional subdirectory under the backend path to mount.",
alias="subPath",
)
model_config = ConfigDict(populate_by_name=True)
@field_validator("name")
@classmethod
def name_must_not_be_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("Volume name cannot be blank")
return v
@field_validator("mount_path")
@classmethod
def mount_path_must_be_absolute(cls, v: str) -> str:
if not v.startswith("/"):
raise ValueError("Mount path must be an absolute path starting with '/'")
return v
@model_validator(mode="after")
def validate_exactly_one_backend(self) -> "Volume":
"""Ensure exactly one backend (host, pvc, or ossfs) is specified."""
backends = [self.host, self.pvc, self.ossfs]
specified = [b for b in backends if b is not None]
if len(specified) == 0:
raise ValueError(
"Exactly one backend (host, pvc, ossfs) must be specified, but none was provided."
)
if len(specified) > 1:
raise ValueError(
"Exactly one backend (host, pvc, ossfs) must be specified, but multiple were provided."
)
return self
class SandboxStatus(BaseModel):
"""
Status information for a sandbox.
"""
state: str = Field(
description="Current state (e.g., RUNNING, PENDING, PAUSED, TERMINATED)"
)
reason: str | None = Field(
default=None, description="Short reason code for current state"
)
message: str | None = Field(
default=None, description="Human-readable status message"
)
last_transition_at: datetime | None = Field(
default=None,
description="Timestamp of last state transition",
alias="last_transition_at",
)
model_config = ConfigDict(populate_by_name=True)
class SandboxAllocation(BaseModel):
"""Current runtime-confirmed Pool allocation for a sandbox."""
mode: Literal["pool"] = Field(description="Confirmed allocation mode.")
pool_ref: str = Field(
description="Concrete Pool reference currently allocated to the sandbox."
)
state: Literal["allocated"] = Field(
description="Current confirmed allocation state."
)
class SnapshotStatus(BaseModel):
"""
Status information for a snapshot.
"""
state: str = Field(description="Current snapshot lifecycle state")
reason: str | None = Field(
default=None, description="Short reason code for current state"
)
message: str | None = Field(
default=None, description="Human-readable status message"
)
last_transition_at: datetime | None = Field(
default=None,
description="Timestamp of last state transition",
alias="last_transition_at",
)
model_config = ConfigDict(populate_by_name=True)
class SnapshotInfo(BaseModel):
"""
Detailed information about a snapshot instance.
"""
id: str = Field(description="Unique identifier of the snapshot")
sandbox_id: str = Field(
description="Source sandbox identifier used to create this snapshot",
alias="sandbox_id",
)
name: str | None = Field(default=None, description="Optional snapshot name")
status: SnapshotStatus = Field(description="Current status of the snapshot")
created_at: datetime = Field(description="Creation timestamp", alias="created_at")
model_config = ConfigDict(populate_by_name=True)
class SandboxInfo(BaseModel):
"""
Detailed information about a sandbox instance.
"""
id: str = Field(description="Unique identifier of the sandbox")
status: SandboxStatus = Field(description="Current status of the sandbox")
entrypoint: list[str] = Field(
description="Command line arguments used to start the sandbox"
)
expires_at: datetime | None = Field(
default=None,
description="Scheduled termination timestamp. Null means manual cleanup mode.",
alias="expires_at",
)
created_at: datetime = Field(description="Creation timestamp", alias="created_at")
image: SandboxImageSpec | None = Field(
default=None, description="Image specification used to create sandbox"
)
snapshot_id: str | None = Field(
default=None,
description="Snapshot identifier used to restore sandbox",
alias="snapshot_id",
)
platform: PlatformSpec | None = Field(
default=None, description="Effective platform used for sandbox provisioning."
)
allocation: SandboxAllocation | None = Field(
default=None,
description="Current runtime-confirmed Pool allocation, when available.",
)
metadata: dict[str, str] | None = Field(default=None, description="Custom metadata")
extensions: dict[str, str] | None = Field(
default=None, description="Opaque extension data returned by the server"
)
model_config = ConfigDict(populate_by_name=True)
class SandboxCreateResponse(BaseModel):
"""
Response returned when a sandbox is created.
"""
id: str = Field(description="Unique identifier of the newly created sandbox")
platform: PlatformSpec | None = Field(
default=None, description="Effective platform used for sandbox provisioning."
)
extensions: dict[str, str] | None = Field(
default=None, description="Opaque extension data returned by the server"
)
class CreateSnapshotRequest(BaseModel):
"""
Request returned when creating a snapshot.
"""
name: str | None = Field(default=None, description="Optional snapshot name")
class SandboxRenewResponse(BaseModel):
"""
Response returned when renewing a sandbox expiration time.
"""
expires_at: datetime = Field(
description="The new absolute expiration time in UTC (RFC 3339 format).",
alias="expires_at",
)
model_config = ConfigDict(populate_by_name=True)
class SandboxEndpoint(BaseModel):
"""
Connection endpoint information for a sandbox.
"""
endpoint: str = Field(description="Sandbox connection endpoint")
headers: dict[str, str] = Field(
default_factory=dict,
description="Headers that must be included on every request targeting this endpoint (e.g. when the server requires them for routing or auth). Empty if not required.",
)
origin: str | None = Field(
default=None,
description=(
"Origin of the sandbox taken from the server's "
"OPEN-SANDBOX-ORIGIN response header (see SandboxOrigin). "
"None when the server does not send it."
),
)
def build_request_headers(
self,
connection_config: "ConnectionConfig | ConnectionConfigSync",
) -> dict[str, str]:
"""
Default headers for execd-plane requests to this endpoint.
The API key is attached only when the client declared server-proxy
mode (``ConnectionConfig.use_server_proxy``): such requests pass the
server's auth gate. In direct mode execd performs no auth and the
key must never travel into the untrusted sandbox.
"""
headers = {
"User-Agent": connection_config.user_agent,
**connection_config.headers,
**self.headers,
}
if connection_config.use_server_proxy:
api_key = connection_config.get_api_key()
if api_key:
headers["OPEN-SANDBOX-API-KEY"] = api_key
return headers
class PaginationInfo(BaseModel):
"""
Pagination metadata.
"""
page: int = Field(description="Current page number (1-indexed)")
page_size: int = Field(description="Number of items per page", alias="page_size")
total_items: int = Field(
description="Total number of items across all pages", alias="total_items"
)
total_pages: int = Field(description="Total number of pages", alias="total_pages")
has_next_page: bool = Field(
description="True if there is a next page available", alias="has_next_page"
)
model_config = ConfigDict(populate_by_name=True)
class PagedSandboxInfos(BaseModel):
"""
A paginated list of sandbox information.
"""
sandbox_infos: list[SandboxInfo] = Field(
description="List of sandbox details for current page", alias="sandbox_infos"
)
pagination: PaginationInfo = Field(description="Pagination metadata")
model_config = ConfigDict(populate_by_name=True)
class PagedSnapshotInfos(BaseModel):
"""
A paginated list of snapshot information.
"""
snapshot_infos: list[SnapshotInfo] = Field(
description="List of snapshot details for current page", alias="snapshot_infos"
)
pagination: PaginationInfo = Field(description="Pagination metadata")
model_config = ConfigDict(populate_by_name=True)
class SandboxFilter(BaseModel):
"""
Filter criteria for listing sandboxes.
"""
states: list[str] | None = Field(
default=None, description="Filter by sandbox states"
)
metadata: dict[str, str] | None = Field(
default=None, description="Filter by metadata key-value pairs"
)
page_size: int | None = Field(
default=None, description="Number of items per page", alias="page_size"
)
page: int | None = Field(default=None, description="Page number (1-indexed)")
@field_validator("page_size")
@classmethod
def page_size_must_be_positive(cls, v: int | None) -> int | None:
if v is not None and v <= 0:
raise ValueError("Page size must be positive")
return v
@field_validator("page")
@classmethod
def page_must_be_non_negative(cls, v: int | None) -> int | None:
if v is not None and v < 0:
raise ValueError("Page must be non-negative")
return v
model_config = ConfigDict(populate_by_name=True)
class SnapshotFilter(BaseModel):
"""
Filter criteria for listing snapshots.
"""
sandbox_id: str | None = Field(
default=None,
description="Filter by source sandbox id",
alias="sandbox_id",
)
name: str | None = Field(
default=None, description="Filter by exact snapshot name"
)
states: list[str] | None = Field(
default=None, description="Filter by snapshot states"
)
page_size: int | None = Field(
default=None, description="Number of items per page", alias="page_size"
)
page: int | None = Field(default=None, description="Page number (1-indexed)")
@field_validator("page_size")
@classmethod
def snapshot_page_size_must_be_positive(cls, v: int | None) -> int | None:
if v is not None and v <= 0:
raise ValueError("Page size must be positive")
return v
@field_validator("page")
@classmethod
def snapshot_page_must_be_non_negative(cls, v: int | None) -> int | None:
if v is not None and v < 0:
raise ValueError("Page must be non-negative")
return v
model_config = ConfigDict(populate_by_name=True)
class SandboxMetrics(BaseModel):
"""
Real-time resource usage metrics for a sandbox.
"""
cpu_count: float = Field(
description="Number of CPU cores available/allocated", alias="cpu_count"
)
cpu_used_percentage: float = Field(
description="Current CPU usage as percentage (0.0 - 100.0)",
alias="cpu_used_percentage",
)
memory_total_in_mib: float = Field(
description="Total memory available in Mebibytes", alias="memory_total_in_mib"
)
memory_used_in_mib: float = Field(
description="Memory currently used in Mebibytes", alias="memory_used_in_mib"
)
timestamp: int = Field(
description="Timestamp of metric collection (Unix epoch milliseconds)"
)
model_config = ConfigDict(populate_by_name=True)
class SandboxState:
"""High-level lifecycle state of the sandbox.
This class provides constant string values for sandbox states.
Note that the sandbox service may introduce new states in future
versions; clients should handle unknown string values gracefully.
Common States:
PENDING (str): Sandbox is being provisioned.
RUNNING (str): Sandbox is running and ready to accept requests.
PAUSING (str): Sandbox is in the process of pausing.
PAUSED (str): Sandbox has been paused while retaining its state.
STOPPING (str): Sandbox is being terminated.
TERMINATED (str): Sandbox has been successfully terminated.
FAILED (str): Sandbox encountered a critical error.
UNKNOWN (str): State is unknown or unsupported by the current version.
State Transitions:
- Pending -> Running: After creation completes.
- Running -> Pausing: When pause is requested.
- Pausing -> Paused: After pause operation completes.
- Paused -> Running: When resume is requested.
- Running/Paused -> Stopping: When kill is requested or TTL expires.
- Stopping -> Terminated: After kill/timeout operation completes.
- Pending/Running/Paused -> Failed: On critical error.
"""
PENDING = "Pending"
RUNNING = "Running"
PAUSING = "Pausing"
PAUSED = "Paused"
STOPPING = "Stopping"
TERMINATED = "Terminated"
FAILED = "Failed"
UNKNOWN = "Unknown"
@classmethod
def values(cls) -> set[str]:
"""Returns a set of all known state values."""
return {
v for k, v in cls.__dict__.items() if k.isupper() and not k.startswith("_")
}
class SandboxOrigin:
"""Origin backing a sandbox.
The protocol defines a single origin value: ``template`` (reported by
the server via the ``OPEN-SANDBOX-ORIGIN`` response header, and set
locally when the sandbox was explicitly created from a template).
Anything else - including sandboxes created from an image or a snapshot
- carries no origin value.
Known values:
TEMPLATE (str): Runs on a fsb golden-image template (no sandbox-side
egress sidecar; egress policy goes through the lifecycle control
plane).
UNKNOWN (str): The origin could not be determined (create from an
image or snapshot, or an older server that does not send the
header).
The server may introduce new values in future versions; clients should
handle unknown string values gracefully.
"""
TEMPLATE = "template"
UNKNOWN = "unknown"
@classmethod
def values(cls) -> set[str]:
"""Returns a set of all known source values."""
return {
v for k, v in cls.__dict__.items() if k.isupper() and not k.startswith("_")
}