SandboxPython SDKTypes and errors

Types and errors

Every type here is a dataclass or enum you import from tangle_sandbox. Errors are SandboxError with a platform code; Error codes lists every code.

from tangle_sandbox import SandboxError
 
try:
    box.exec("true")
except SandboxError as error:
    print(error.code, error.status, error.retryable, error.next_step)

Status

SandboxStatus is a string enum: PENDING, PROVISIONING, RUNNING, STOPPED, FAILED, EXPIRED, DELETED. Values are the lowercase strings the API returns (box.status.value == "running"). Pass members, not strings, to wait_for and ListSandboxOptions.

Create options

TypeFields
CreateSandboxOptionsSee the field table
BackendConfigtype, profile: dict, model: dict. An unknown type raises ValueError
BackendTypeopencode, claude-code, kimi-code, codex, amp, factory-droids, pi, prime, hermes, openclaw, nanoclaw, acp, cursor, cli-base
GitConfigurl, ref, depth, sparse, auth: GitAuth
GitAuthtoken
SandboxResourcescpu_cores, memory_mb, disk_gb, accelerator: SandboxAccelerator
SandboxAcceleratorkind (for example nvidia-l4), count, memory_mb
StorageConfigtype (s3, gcs or r2), bucket, region, endpoint, credentials, prefix. The API requires credentials
EgressPolicymode (open, strict or blocked), allow_domains, include_implicit_domains
DriverConfigtype="tangle", enable_criu (accepted, no effect)
ConfidentialConfigtee, attestation_nonce; import from tangle_sandbox.types; only the [tangle] client reads it
ListSandboxOptionsstatus, limit, offset
WaitForOptionstimeout_ms=120000, poll_interval_ms=2000

BackendType lists what the SDK accepts. The coding agents the service runs today come from GET /v1/backends; the service refuses one it cannot run with HARNESS_UNAVAILABLE.

Sandbox details

TypeFields
SandboxInfoid, status, name, connection, metadata, created_at, started_at, last_activity_at, expires_at, error, egress_policy, egress_policy_source
SandboxConnectionruntime_url, host_url, auth_token, auth_token_expires_at, ssh, web_terminal_url
SSHCredentialshost, port, username
UsageInfocompute_minutes, active_sandboxes, total_sandboxes, period_start, period_end
SubscriptionInfoplan, status, credits_available_usd, credits_used_usd, monthly_balance_usd, max_concurrent_sandboxes, overage_allowed, limits, current_period_end
SecretInfoname, created_at, updated_at, host, header, reason
SandboxEnvironmentAn environment id and the runtimes a create with it may name
Team, TeamMember, TeamInvitationSee Teams
CreateTeamOptions, InviteTeamMemberOptionsname, org_id; email, role, ttl_hours

Commands and agents

TypeFields
ExecOptionscwd, env, timeout_ms, session_id (accepted, not sent)
ExecResultexit_code, stdout, stderr (empty; stderr is merged into stdout)
PromptOptionssession_id, backend, timeout_ms, context
PromptResultsuccess, response, error, trace_id, duration_ms, usage
TokenUsageinput_tokens, output_tokens
SandboxEventtype, data, id
SearchOptionsglob, cwd, max_results, ignore_case, context
SearchMatchpath, line, column, text, before, after

Git, snapshots and network

TypeFields
GitStatusis_repo, branch, head, is_dirty, ahead, behind, staged, modified, untracked
GitCommitsha, short_sha, message, author, email, date
GitBranchname, current, upstream, commit
GitDifffiles, additions, deletions, raw
SnapshotOptionstags, storage
SnapshotResultsnapshot_id, created_at, size_bytes, tags
SnapshotInfosnapshot_id, sandbox_id, created_at, tags, paths, size_bytes
EgressDenialhost, rejected_by, count, last_at
MAX_EGRESS_DENIALS_LIMIT50

Batches

TypeFields
BatchRunRequesttasks, backends, timeout_ms=300000, execution_class="simulation", persistent=False, reuse_key, lifecycle, grace_ms, git
BatchTaskid, message, context, timeout_ms
BatchBackendid, type, profile, model, server
BatchBackendModel, BatchBackendServer, BatchLifecycleModel, server and lifecycle settings for a backend or a persistent batch
BatchResulttotal_tasks, total_backends, total_executions, total_success, total_failure, total_retries, success_rate, results, cleanup
BatchTaskResulttask_id, backend_id, backend_type, success, duration_ms, retries, result_summary, error
BatchCleanupBatchReleaseCleanup, BatchPersistentCleanup or BatchGraceCleanup; mode is release, persistent or grace

Fleets

CreateSandboxFleetOptions, CreateSandboxFleetWithCoordinatorOptions, SandboxFleetMachineSpec, SandboxFleetPolicy, SandboxFleetWorkspace, ListSandboxFleetOptions, FleetExecDispatchOptions, FleetPromptDispatchOptions, FleetRetryPolicy, FleetDispatchResultBufferOptions, FleetDispatchResultBuffer, SandboxFleetDispatchResponse, SandboxFleetTraceBundle, SandboxFleetTraceExport, SandboxFleetIntelligenceEnvelope, CreateSandboxFleetTokenOptions and ReapExpiredSandboxFleetsOptions. Fleets and optional modules describes the fields you set.

Traces and reports

These are TypedDicts with the API’s camelCase keys.

TypeKeys
SandboxTraceBundletrace, intelligence
SandboxTraceExport, SandboxIntelligenceEnvelopeExport and analysis payloads
IntelligenceReportjobId, subject, mode, status, billing, result, error, createdAt, updatedAt, completedAt

Exported types that nothing returns

ProvisionEvent, ProvisionResult, ProvisionStep, ProvisionStatus and BuildProgressEvent are exported, but no method returns or yields them; Python has no provisioning progress stream. ImageSpec, ImageBuildResult and ImageBuildOptions belong to the image builder, whose build() the service refuses. SandboxClientConfig holds the client’s settings.

SandboxError

SandboxError(message, code=None, status=None, **details)
AttributeDescription
codePlatform error code, such as NOT_FOUND or CAPACITY_EXHAUSTED
statusHTTP status
retryableWhether sending the same request again can succeed
next_stepWhat to do about it
messageHuman-readable message
detailsCode-specific fields, also readable as attributes: timeout_ms, current_state, required_state, quota_type, failures, fields, resource_type, resource_id, capability, current, limit
retry_after_ms, eta_seconds, capacity_holdSet when the service refuses for capacity

Handle errors by code:

from tangle_sandbox import SandboxError
 
try:
    box = client.create()
except SandboxError as error:
    if error.code == "CAPACITY_EXHAUSTED" and error.retryable:
        print("retry in", error.retry_after_ms, "ms")
    else:
        raise

Aliases

Each alias is a SandboxError subclass for a group of codes, so isinstance checks work.

AliasCodeRaised for
ValidationErrorVALIDATION_ERRORHTTP 400
AuthErrorUNAUTHORIZEDHTTP 401
NotFoundErrorNOT_FOUNDHTTP 404
TimeoutErrorTIMEOUTHTTP 408 and client timeouts
StateErrorINVALID_STATEHTTP 409, and runtime calls on a sandbox that is not RUNNING
QuotaErrorQUOTA_EXCEEDEDHTTP 429 and quota codes
ServerErrorINTERNAL_ERRORHTTP 500 and above
CapabilityErrorUNSUPPORTEDCapability codes
PartialFailureErrorPARTIAL_FAILUREPartial-failure codes
NetworkErrorNETWORK_ERRORConnection failures and malformed stream data
BatchFailedErrorOPERATION_FAILEDrun_batch when the batch fails; a ServerError with a cleanup attribute

A bad key raises a SandboxError with an auth code; check code rather than expecting AuthError alone. tangle_sandbox.TimeoutError is not the built-in TimeoutError, and except TimeoutError with the built-in does not catch it.

Errors raised before a request

  • Sandbox("", url) raises AuthError("API key is required").
  • Sandbox(key, "") raises ValidationError("Base URL is required").
  • A runtime call on an instance whose cached status is not RUNNING raises StateError.

Errors that are not SandboxError

CallRaises
ImageBuilder.build()ValueError
export_trace, export_trace_bundleRuntimeError when your collector answers with an error
instance.intelligence(), fleet.intelligence()RuntimeError when there is no analysis
fleet.exec(), fleet.prompt()RuntimeError when the one machine fails
BackendConfig(type="unknown")ValueError
TangleSandboxClient streamingNotImplementedError
wait_for("running") timing outAttributeError; pass SandboxStatus.RUNNING

Next