diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0579562..3826ed9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,12 @@ jobs: - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 with: python-version: ${{ matrix.python }} - - run: pip install -e ".[dev]" + # The LangChain and OpenAI Agents integrations need Python 3.11 or later; on 3.10 the SDK is + # tested without them (their tests skip) and the type check runs on the later versions. + - if: matrix.python == '3.10' + run: pip install -e ".[dev]" + - if: matrix.python != '3.10' + run: pip install -e ".[dev,langchain,openai-agents]" - run: pytest - - run: mypy src tests + - if: matrix.python != '3.10' + run: mypy src tests diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 84e9e03..25e0ab7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,9 +1,10 @@ # Copyright 2026 Neural Inverse # SPDX-License-Identifier: Apache-2.0 -# Publishes sandscale to PyPI when a v* tag is pushed, through PyPI trusted publishing (OIDC): -# no PyPI token is stored anywhere. PyPI trusts this repository, this workflow file (release.yml) -# and the environment `pypi`. Attestations (PEP 740) are attached automatically. +# Publishes sandscale to PyPI when a v* tag is pushed. Until a trusted publisher (OIDC) is +# registered on PyPI, the upload uses the project's API token, the secret PYPI_API_TOKEN of the +# environment `pypi` (never printed, never in this repository); attestations (PEP 740) need +# trusted publishing and are off until then. # See RELEASING.md for the one-time setup. name: release @@ -28,7 +29,7 @@ jobs: have="$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")" test "$want" = "$have" || { echo "tag $GITHUB_REF_NAME but pyproject.toml is $have"; exit 1; } grep -q "VERSION = \"$want\"" src/sandscale/_version.py || { echo "_version.py does not carry $want"; exit 1; } - - run: pip install -e ".[dev]" + - run: pip install -e ".[dev,langchain,openai-agents]" - run: pytest - run: mypy src tests - run: python -m build @@ -42,10 +43,16 @@ jobs: runs-on: ubuntu-latest environment: pypi permissions: - id-token: write # PyPI trusted publishing + id-token: write # kept for PyPI trusted publishing once it is set up on PyPI steps: - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: name: dist path: dist/ - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1 + with: + # An API token of the project (environment secret of `pypi`), until a trusted publisher + # is registered on PyPI. PEP 740 attestations need trusted publishing, so they are off. + password: ${{ secrets.PYPI_API_TOKEN }} + attestations: false + print-hash: true diff --git a/CHANGELOG.md b/CHANGELOG.md index 906f4de..a5fbcdb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ # Changelog -## 1.0.0 - 2026-11-18 +## 1.0.0 - 2026-11-29 First public release of sandscale under the Apache-2.0 licence: sandboxes (create, run with live output, logs, files, pause, resume, snapshot, stop, list), ports, preview links and SSH, diff --git a/README.md b/README.md index 0f5372c..7a2d949 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,6 @@ hands back the server's answer, including its error code and message. pip install sandscale ``` -Documentation: https://sandscale.dev/docs. Source and issues: https://github.com/sandscale/sandscale-python. Licensed under Apache-2.0. - ## Quick start ```python @@ -24,6 +22,9 @@ from sandscale import Sandscale with Sandscale() as sandscale: # SANDSCALE_API_KEY from the environment box = sandscale.sandboxes.create(template="builtin:python", timeout_seconds=600) + # BUILTIN_TEMPLATES lists the built-ins: base (default), python, node, go, go_postgres (Go with PostgreSQL 17 + # running on 127.0.0.1:5432, TEST_DATABASE_URL set), minimal. The default image has + # Python 3 with pip, Node.js with npm, git, curl, a C compiler, jq and unzip (docs/sandbox/images.md). try: run = sandscale.sandboxes.run( box.id, @@ -58,10 +59,10 @@ One account works in every Sandscale region. Pass `region="us"` or `region="eu"` |---|---| | none | `https://api.sandscale.dev`, the front door: it routes to the request's region, US by default | | `"us"` | `https://api.us.sandscale.dev` | -| `"eu"` | `https://api.eu.sandscale.dev` (when Sandscale opens in eu1) | +| `"eu"` | `https://api.sandscale.dev` with `region=eu1`: the front door sends the call to the EU region with your own credential. The EU regional host (`api.eu.sandscale.dev`) does not accept a global API key or sign-in token, so the SDK never calls it directly | A region id such as `us1` names the same region. `region_urls` sets origins explicitly. -Against another `base_url` (a self-hosted Keystone) a region is looked up in that server's +Against another `base_url` (a self-hosted Sandscale) a region is looked up in that server's public region list (`GET /api/v1/regions`). Models carry the `region` they were read from; pass it to later calls on them. Lists without a @@ -72,12 +73,19 @@ says, per region, the next cursor or the error that region answered. | Area | Methods | |---|---| +| `sandboxes` | `create`, `get`, `list`, `run` (live stdout and stderr, exit code), `logs`, `write_file`, `read_file`, `list_files`, `pause`, `resume`, `snapshot`, `list_snapshots`, `stop`, `attach_volume`, `list_attachments`, `commit_volume`, `detach_volume`, `restore_cache`, `save_cache` | +| `volumes` | `create`, `get`, `list`, `delete` | +| `caches` | `list`, `delete` | +| `workspaces` | `list`, `get`, `start`, `stop`, `connect_info` | +| `build_hosts` | `list_pools`, `list`, `get`, `start` (take a lease of a pool), `stop` (release it), `connect_info`, `ssh_certificate` | | `sandboxes` | `create` (`network`, `image`, `runtime`, `environment_id`), `get`, `list`, `run` (live stdout and stderr, exit code), `logs`, `write_file`, `read_file`, `list_files`, `pause`, `resume`, `snapshot`, `list_snapshots`, `stop`, `expose_port`, `list_ports`, `close_port`, `create_preview_link`, `list_preview_links`, `revoke_preview_link`, `ssh_info`, `ssh_certificate` | | `snapshots` | `list` (with quota usage), `get`, `delete` | | `templates` | `create`, `list`, `get`, `delete`, `build_status` | | `policy` | `get`, `set` | | `webhooks` | `list`, `create`, `delete`, `verify` (also `verify_webhook_signature`) | | `traces` | `list`, `get`, `get_export`, `set_export`, `delete_export`, `test_export` | +| `execute`, `search`, `tasks`, `code_policy` | code mode (below): `tasks.get`, `tasks.wait`, `code_policy.get`, `code_policy.set` | +| `api` | the typed API (below): every operation as `api..(**args)` | | `objects` | buckets (`create_bucket`, `list_buckets`, `get_bucket`, `update_bucket`, `delete_bucket`), lifecycle, policy, access keys, `limits` | | `workspaces` | `list`, `get`, `start`, `stop`, `connect_info`, `create`, `update`, `delete`, `rebuild`, `open_link`, `list_backups`, `create_backup`, `verify_backup`, `list_apps`, `share_app` | | `build_hosts` | `list_pools`, `list`, `get`, `start` (take a lease of a pool), `stop` (release it), `connect_info`, `ssh_certificate`, `renew`, `kill`, `list_runs`, `get_run`, `list_artifacts`, `get_artifact`, `download_artifact`, `delete_artifact`, `list_caches`, `list_pool_caches`, `purge_pool_cache` | @@ -94,9 +102,24 @@ the organization's DLP rules. The server may redact it, or end the stream with server that answers with the finished result instead gets the callbacks the final output once. `sandboxes.create(vault_env=[VaultEnvRef("DB_PASSWORD", "secret/data/db", "password")])` puts -Keystone Vault values in the sandbox's environment. The server reads them as you and gives them +Sandscale Vault values in the sandbox's environment. The server reads them as you and gives them to the sandbox only. +Persistent volumes keep a directory between sandboxes, in versions. +`attach_volume(sandbox_id, volume_id, mount_path, mode="rw")` mounts one (read-write by one +sandbox at a time, else 409 `volume_writer_attached`; `mode="ro"` is never written back), +`commit_volume` writes the next version and `detach_volume(..., commit=False)` drops +uncommitted changes (a read-write attachment commits first by default). Dependency caches are +keyed by the server from the lockfile it reads in the sandbox and shared within the organization +only: + +```python +r = sandscale.sandboxes.restore_cache(box.id, ecosystem="pip", lockfile="/workspace/requirements.txt") +if not r.hit: + sandscale.sandboxes.run(box.id, "pip install -r /workspace/requirements.txt") + sandscale.sandboxes.save_cache(box.id, ecosystem="pip", lockfile="/workspace/requirements.txt") +``` + ## More examples Every call takes `region=` like the first ones. The server decides what you may do; the SDK @@ -140,7 +163,7 @@ hook = sandscale.webhooks.create(url="https://example.com/hooks/sandscale", even signing_secret = hook.secret # shown once: store it in your secret manager, never print it # In your receiver: pass the raw body exactly as received. -ok = verify_webhook_signature(request.headers.get("X-Keystone-Signature"), raw_body, signing_secret) +ok = verify_webhook_signature(request.headers.get("X-Sandscale-Signature"), raw_body, signing_secret) ``` The signature is `sha256=` and the hex HMAC-SHA256 of the raw body under the secret; the check @@ -193,7 +216,7 @@ print(sandscale.agent_cloud.get_task(task.id).state) sandscale.agent_cloud.cancel_task(task.id) ``` -These are Keystone's lead routes (never the device agent). They need a signed-in person's +These are Sandscale's lead routes (never the device agent). They need a signed-in person's `token`; an API key is refused with 403 `person_required`. ### Account @@ -216,14 +239,121 @@ Plan changes, overage and personal API keys need a signed-in person's token. Sec shows once (webhook signing secret, `secret_access_key`, API key `key`) are fields excluded from `repr` and from `raw`; the SDK never logs or prints them. +## Agent frameworks + +**LangChain.** `pip install "sandscale[langchain]"`. `SandscaleSandbox` is a Deep Agents sandbox +backend (its file tools and `execute` run in the sandbox; paths are absolute), and `SandscaleToolkit` +gives any LangChain agent `sandscale_run`, `sandscale_write_file` and `sandscale_read_file`: + +```python +from deepagents import create_deep_agent +from sandscale.integrations.langchain import SandscaleSandbox, SandscaleToolkit + +with SandscaleSandbox.create(template="builtin:python", timeout_seconds=900) as backend: + agent = create_deep_agent(model="anthropic:claude-sonnet-4-6", backend=backend) + +with SandscaleToolkit.create(template="builtin:node") as toolkit: + tools = toolkit.get_tools() +``` + +**OpenAI Agents SDK.** `pip install "sandscale[openai-agents]"`. `SandscaleSandboxClient` runs a +`SandboxAgent`'s workspace in a sandbox (root `/workspace`; saved workspaces are tar archives; an +exposed port is published as a public preview link, Pro and up): + +```python +from agents.run import RunConfig +from agents.sandbox import SandboxRunConfig +from sandscale.integrations.openai_agents import SandscaleSandboxClient, SandscaleSandboxClientOptions + +config = RunConfig(sandbox=SandboxRunConfig( + client=SandscaleSandboxClient(), + options=SandscaleSandboxClientOptions(template="builtin:python", timeout_seconds=900), +)) +``` + +A sandbox an adapter started is stopped when it closes; one you pass in is left running. Both wait out +rate limits (429) and move files as streamed transfers (`sandboxes.upload` and `sandboxes.download`, +up to 1 GiB). Full scripts: `examples/langchain_deep_agent.py`, `examples/openai_agents_sandbox.py`. + +## For agents + +```python +c = sandscale.capabilities() # plan, limits, templates, regions, vCPU-hour balance and its reset time +box = sandscale.sandboxes.create(template="builtin:base", idempotency_key="job-42") # a retry never makes a second box +proc = sandscale.sandboxes.start_process(box.id, "python -m http.server 8000") +sandscale.sandboxes.wait_for_port(box.id, 8000) +log = sandscale.sandboxes.process_logs(box.id, proc.process_id, offset=0) # log.next_offset continues +sandscale.sandboxes.kill_process(box.id, proc.process_id) +text = sandscale.sandboxes.read_text(box.id, "/workspace/out.txt") +``` + +A refused call raises an error whose `details` carry the next step the server names (the templates to start, +the plan that lifts a limit, when the allowance renews). + +## Code mode + +`execute` runs a TypeScript or JavaScript script on the server against your typed API, as you: one +request instead of one per call. The script sees `sandscale..(args)` and +`vault.ref("store/name#field")`, may `await` and `return`, and its return value is `task.result`. + +```python +task = sandscale.execute(""" + const box = await sandscale.sandbox.create({ template: "builtin:python" }); + console.log("started", box.id); + return box.id; +""") +print(task.state, task.result, [line.text for line in task.console]) +``` + +The server answers within `wait_seconds` (at most 30); after a 202 the SDK reads the task again +(`poll_interval`, `timeout`) until it succeeded or failed. A failed task raises `TaskFailedError` +(its `code` is the task's: `script_error`, `syntax_error`, `time_limit` and so on; `task.error` +has the script `line` and `column` and the `api_error` that ended it, with its `next` step); +`raise_on_failure=False` returns it instead. A `timeout` that passes first raises +`TaskTimeoutError` while the task keeps running on the server. + +A call the Organization's ask-first policy names waits for a person: `execute` returns the task in +state `awaiting_approval` with `pending_approval` (`request_id`, `operation`, `seq`), unless +`wait_for_approval=True`. Read it later with `sandscale.tasks.get(task_id, wait_seconds=30)` or +`sandscale.tasks.wait(task_id)`; reading an approved task resumes it. Only the person who started a +task reads it (anyone else gets `NotFoundError`). + +```python +found = sandscale.search('return api.find("snapshot a sandbox", 5)') # the typed API as data +print(found.result) +sandscale.code_policy.get().ask_first # e.g. ["destructive"] +sandscale.code_policy.set(["sandbox_terminate", "writes"]) # needs sandboxes:write +``` + +## Typed API + +`sandscale.api..(**args)` calls any operation of the typed API (the same +functions a code mode script calls) directly from Python. It is built at import from the generated +operation table; names work in camelCase and snake_case (`api.auditLogs.auditEventsList` and +`api.audit_logs.audit_events_list`), and `api.call("sandbox_snapshot_create", {...})` takes the +operation name. + +```python +snap = sandscale.api.sandbox.snapshot_create(id=box.id, label="before", region="us") +events = sandscale.api.audit_logs.audit_events_list(from_="2026-11-01", limit=50) # from_ for from +sandscale.api.sandbox.instances_ports_delete(id=box.id, port=8080, confirm=True) +``` + +Arguments are the operation's parameter names; one the operation does not take, or a missing +required one, raises `ApiArgumentError` before any request. Organization path parameters are filled +from the client's `org_id`. An operation that deletes, ends or changes billing needs `confirm=True` +(never sent); without it the SDK raises `SandscaleError` with code `confirmation_required` and sends +nothing. A write takes `idempotency_key` (sent as `Idempotency-Key`, so it is retried like a read). +Answers are the server's JSON as is; refusals are the usual errors below. + ## Errors Every API error is a `SandscaleError` with the server's `status`, `code`, `message`, `request_id` and `details`: `InvalidRequestError` (400, 413, 422), `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), -`LimitExceededError` (402 or a quota or limit code) and its `RateLimitError` (429, with +`LimitExceededError` (402 or a quota or limit code, including `lease_duration_limit`, `lease_vcpu_limit`, `lease_concurrent_limit`, `lab_host_limit`, `vault_secret_limit` and `vault_store_limit`, whose `details` carry `plan` and the limit hit) and its `RateLimitError` (429, with `retry_after`), `EntitlementError` (`not_entitled`, `payment_required`, `entitlement_*`, -`plan_*`, `*_not_in_plan`), `RegionError` (`wrong_region` with `region`, `region_*`), `KillSwitchError` +`plan_*`, `*_not_in_plan`; `lease_not_in_plan` now means a misconfigured plan), `RegionError` (`wrong_region` with `region`, `region_*`), `KillSwitchError` (`kill_switch_*`), `ServerError` (5xx; `retryable` for 502, 503 and 504) with `ServiceUnavailableError` (any 503, with `retry_after`; also `entitlement_unavailable`) and `SandboxWakingError` (503 `sandbox_waking`: the sandbox is resuming, retry after `retry_after`), and `APIConnectionError` (no answer). @@ -241,7 +371,8 @@ never retried. Calls that change something are sent once. - **Cross-region credentials.** Until the global plane syncs API keys and sign-in sessions to every region, a credential of one region is refused in another with `wrong_region` (`RegionError`, with `region`). -- **Vault environment on sandboxes** needs a server that supports `vault_env`. A server from before it ignores the +- **Vault environment on sandboxes** needs a server with `vault_env` + (docs/sandbox/vault-env.md in the Sandscale documentation). A server from before it ignores the field. - Synchronous client only; an asyncio client is a follow-up. @@ -252,5 +383,5 @@ pip install -e ".[dev]" && pytest # unit tests against a local mock server, ro SANDSCALE_API_KEY=... pytest # also the integration test (starts and stops one sandbox) ``` -`tests/test_routes.py` fails when the server stops mounting a route this SDK calls (checked against the -server route inventory when the tests run inside the Keystone source tree, skipped elsewhere) or when the SDK calls a route it does not list. +`tests/test_routes.py` fails when the server stops mounting a route this SDK calls (the route +inventory of the Sandscale repository) or when the SDK calls a route it does not list. diff --git a/RELEASING.md b/RELEASING.md index 09c0a15..185747f 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -9,9 +9,11 @@ tree. Do not commit here directly; changes go through Keystone and are synced on A release is a `v*` tag on `main`. `.github/workflows/release.yml` checks that the tag equals `pyproject.toml` and `_version.py`, runs pytest and mypy, builds the sdist and wheel, then the -`publish` job uploads them with `pypa/gh-action-pypi-publish` using **PyPI trusted publishing**: -GitHub's OIDC token is exchanged for a short-lived upload token, so no PyPI token exists in this -repository. PEP 740 attestations are attached automatically. +`publish` job uploads them with `pypa/gh-action-pypi-publish`. Today it uses the project's PyPI API +token, stored only as the secret `PYPI_API_TOKEN` of the GitHub environment `pypi` (never in this +repository, never printed). When a trusted publisher is registered (below), drop the `password` +input and turn `attestations` back on: GitHub's OIDC token is then exchanged for a short-lived +upload token and PEP 740 attestations are attached. ## One-time owner setup diff --git a/examples/langchain_deep_agent.py b/examples/langchain_deep_agent.py new file mode 100644 index 0000000..c47fd89 --- /dev/null +++ b/examples/langchain_deep_agent.py @@ -0,0 +1,17 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""A LangChain Deep Agent whose file tools and shell run in a Sandscale sandbox. + + pip install "sandscale[langchain]" langchain-anthropic + export SANDSCALE_API_KEY=... ANTHROPIC_API_KEY=... + python examples/langchain_deep_agent.py +""" + +from deepagents import create_deep_agent + +from sandscale.integrations.langchain import SandscaleSandbox + +with SandscaleSandbox.create(template="builtin:python", timeout_seconds=900) as backend: + agent = create_deep_agent(model="anthropic:claude-sonnet-4-6", backend=backend) + result = agent.invoke({"messages": [{"role": "user", "content": "Write fib.py printing the first 20 Fibonacci numbers, run it and show the output."}]}) + print(result["messages"][-1].content) diff --git a/examples/openai_agents_sandbox.py b/examples/openai_agents_sandbox.py new file mode 100644 index 0000000..e70ce75 --- /dev/null +++ b/examples/openai_agents_sandbox.py @@ -0,0 +1,35 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""An OpenAI Agents SDK SandboxAgent that works in a Sandscale sandbox. + + pip install "sandscale[openai-agents]" + export SANDSCALE_API_KEY=... OPENAI_API_KEY=... + python examples/openai_agents_sandbox.py +""" + +import asyncio + +from agents import Runner +from agents.run import RunConfig +from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig + +from sandscale.integrations.openai_agents import SandscaleSandboxClient, SandscaleSandboxClientOptions + + +async def main() -> None: + agent = SandboxAgent( + name="builder", + instructions="Work in the workspace. Write the code, run it and report what it printed.", + default_manifest=Manifest(), + ) + config = RunConfig( + sandbox=SandboxRunConfig( + client=SandscaleSandboxClient(), + options=SandscaleSandboxClientOptions(template="builtin:python", timeout_seconds=900), + ) + ) + result = await Runner.run(agent, "Write primes.py printing the primes below 50 and run it.", run_config=config) + print(result.final_output) + + +asyncio.run(main()) diff --git a/pyproject.toml b/pyproject.toml index 9860a1f..0d406e5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,7 +19,7 @@ dependencies = [ ] keywords = ["sandscale", "sandbox", "ai", "agents", "code-execution"] classifiers = [ - "Development Status :: 5 - Production/Stable", + "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python :: 3", "Typing :: Typed", @@ -32,6 +32,15 @@ Source = "https://github.com/sandscale/sandscale-python" Changelog = "https://github.com/sandscale/sandscale-python/blob/main/CHANGELOG.md" [project.optional-dependencies] +# sandscale.integrations.langchain: a Deep Agents sandbox backend and a LangChain toolkit. +langchain = [ + "deepagents>=0.7", + "langchain-core>=1.0", +] +# sandscale.integrations.openai_agents: a sandbox client for the OpenAI Agents SDK's SandboxAgent. +openai-agents = [ + "openai-agents>=0.26", +] dev = [ "pytest>=7.0", "mypy>=1.13", @@ -52,3 +61,13 @@ testpaths = ["tests"] [tool.mypy] strict = true + +# The live LangChain suite is an optional test dependency (langchain-tests), not installed for the +# type check. +[[tool.mypy.overrides]] +module = ["langchain_tests.*"] +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = ["test_integrations_live", "tests.test_integrations_live"] +warn_unused_ignores = false diff --git a/src/sandscale/__init__.py b/src/sandscale/__init__.py index ef111cf..db8cc26 100644 --- a/src/sandscale/__init__.py +++ b/src/sandscale/__init__.py @@ -21,18 +21,45 @@ import httpx from ._account import Account +from ._api import Api, ApiArgumentError, ApiFunction, ApiNamespace +from ._code import ( + ApiErrorInfo, + CodePolicy, + CodePolicyService, + ConsoleLine, + PendingApproval, + SearchResult, + Task, + TaskError, + TaskFailedError, + Tasks, + TaskTimeoutError, + execute as _execute, + search as _search, +) +from ._call import call as _call, operations +from ._capabilities import Capabilities, capabilities as _capabilities +from ._builtin import BUILTIN_TEMPLATES from ._admin import Policy, Snapshots, Templates, Traces, Webhooks, verify_webhook_signature from ._compute import AgentCloud, LabHosts from ._objects import Objects -from ._services import BuildHosts, Sandboxes, Workspaces +from ._services import BuildHosts, Caches, ProcessInfo, ProcessLogs, ProcessStart, Sandboxes, Volumes, Workspaces from ._transport import DEFAULT_BASE_URL, SANDSCALE_REGION_URLS, TokenSource, Transport from ._version import VERSION from .errors import ( + AccountExistsError, APIConnectionError, AuthenticationError, ConfigurationError, ConflictError, EntitlementError, + FairUseLimit, + LimitInfo, + PlanRefusal, + FreeAlreadyClaimedError, + FreeDailyLimitError, + FreeMonthlyLimitError, + FreeNewAccountLimitError, InvalidRequestError, KillSwitchError, LimitExceededError, @@ -46,6 +73,13 @@ ServiceUnavailableError, ) from .admin_models import ( + CodeModeUsage, + DailyUsage, + GithubLinkStart, + Identity, + PeriodUsage, + RampUsage, + UsageLimits, TraceCost, NoncurrentVersionExpiration, BucketUsage, @@ -97,10 +131,14 @@ TraceSummary, Usage, Webhook, + WebhookDelivery, WorkspaceApp, WorkspaceBackup, ) from .models import ( + DependencyCache, + CacheResult, + ActivityDay, ConnectInfo, FileEntry, Lease, @@ -110,11 +148,15 @@ Pool, RegionPage, RunEnd, + RunOutput, RunResult, Sandbox, + SandboxActivity, Snapshot, SSHCertificate, VaultEnvRef, + Volume, + VolumeAttachment, Workspace, WorkspaceBuild, ) @@ -159,6 +201,10 @@ def __init__( http_client=http_client, ) self.sandboxes = Sandboxes(self.transport) + #: Persistent volumes; attach them with ``sandboxes.attach_volume``. + self.volumes = Volumes(self.transport) + #: Dependency caches; restore and save them with ``sandboxes.restore_cache`` and ``save_cache``. + self.caches = Caches(self.transport) self.workspaces = Workspaces(self.transport) self.build_hosts = BuildHosts(self.transport, self.workspaces) self.snapshots = Snapshots(self.transport) @@ -170,6 +216,76 @@ def __init__( self.lab_hosts = LabHosts(self.transport) self.agent_cloud = AgentCloud(self.transport) self.account = Account(self.transport) + #: Code mode tasks (``execute`` starts one). + self.tasks = Tasks(self.transport) + #: What a code mode script must ask a person about first. + self.code_policy = CodePolicyService(self.transport) + self._api: Optional[Api] = None + + @property + def api(self) -> Api: + """The typed Sandscale API, ``api..(**args)``: every operation a code mode + script can call, called directly from Python as this client.""" + if self._api is None: + self._api = Api(self.transport) + return self._api + + def execute( + self, + code: str, + *, + wait_seconds: float = 30, + poll_interval: float = 1.0, + timeout: Optional[float] = None, + wait_for_approval: bool = False, + raise_on_failure: bool = True, + idempotency_key: Optional[str] = None, + ) -> Task: + """Runs a TypeScript or JavaScript script on the server against your typed API (code mode) and + returns its task once it succeeded or failed. + + The script sees ``sandscale..(args)`` and ``vault.ref(...)``, may ``await`` and + ``return``; its return value is ``task.result``. The server answers within ``wait_seconds`` + (at most 30) or the SDK reads the task again until it ends. A task that waits on a person's + approval is returned in state ``awaiting_approval`` unless ``wait_for_approval``. A failed + task raises :class:`TaskFailedError` (``raise_on_failure=False`` returns it instead); + ``timeout`` (seconds, default none) raises :class:`TaskTimeoutError` with the task still + running on the server.""" + return _execute( + self.transport, + self.tasks, + code, + wait_seconds=wait_seconds, + poll_interval=poll_interval, + timeout=timeout, + wait_for_approval=wait_for_approval, + raise_on_failure=raise_on_failure, + idempotency_key=idempotency_key, + ) + + def search(self, code: str) -> SearchResult: + """Runs a script against the typed API as data (``api.namespaces[ns].functions[fn]``, + ``api.find("words", limit)``) and returns what it returned. A script failure raises + :class:`InvalidRequestError` (422) with ``details`` ``{line, column}``.""" + return _search(self.transport, code) + + def call( + self, + operation: str, + args: Optional[Mapping[str, Any]] = None, + *, + region: Optional[str] = None, + idempotency_key: Optional[str] = None, + ) -> Any: + """Runs any operation of the Sandscale API by its catalogue name (``operations()`` lists them with their + arguments), for what the typed methods do not cover. The server decides everything else.""" + return _call(self.transport, operation, args, region=region, idempotency_key=idempotency_key) + + def capabilities(self, *, region: Optional[str] = None) -> Capabilities: + """What this account can do here now: the plan, its limits (vCPU, memory, concurrent boxes, time to + live, network modes), the templates that start and what is in them, the regions and the vCPU-hour + balance with the time it resets. The server decides every figure.""" + return _capabilities(self.transport, region) def close(self) -> None: self.transport.close() @@ -182,8 +298,46 @@ def __exit__(self, *exc: Any) -> None: __all__ = [ + "Api", + "ApiArgumentError", + "ApiErrorInfo", + "ApiFunction", + "ApiNamespace", + "CodePolicy", + "CodePolicyService", + "ConsoleLine", + "PendingApproval", + "SearchResult", + "Task", + "TaskError", + "TaskFailedError", + "TaskTimeoutError", + "Tasks", + "operations", + "AccountExistsError", + "Capabilities", + "ProcessInfo", + "ProcessLogs", + "ProcessStart", + "CodeModeUsage", + "DailyUsage", + "FairUseLimit", + "LimitInfo", + "PlanRefusal", + "FreeAlreadyClaimedError", + "FreeDailyLimitError", + "FreeMonthlyLimitError", + "FreeNewAccountLimitError", + "GithubLinkStart", + "Identity", + "PeriodUsage", + "RampUsage", + "UsageLimits", "Sandscale", + "BUILTIN_TEMPLATES", "Sandboxes", + "Volumes", + "Caches", "Workspaces", "BuildHosts", "Transport", @@ -204,6 +358,8 @@ def __exit__(self, *exc: Any) -> None: "RateLimitError", "RegionError", "ServerError", + "DependencyCache", + "CacheResult", "ConnectInfo", "FileEntry", "Lease", @@ -213,11 +369,16 @@ def __exit__(self, *exc: Any) -> None: "Pool", "RegionPage", "RunEnd", + "RunOutput", "RunResult", "Sandbox", "Snapshot", + "SandboxActivity", + "ActivityDay", "SSHCertificate", "VaultEnvRef", + "Volume", + "VolumeAttachment", "Workspace", "WorkspaceBuild", "Account", @@ -283,6 +444,7 @@ def __exit__(self, *exc: Any) -> None: "TraceSummary", "Usage", "Webhook", + "WebhookDelivery", "WorkspaceApp", "WorkspaceBackup", ] diff --git a/src/sandscale/_account.py b/src/sandscale/_account.py index 3dba9df..53ea802 100644 --- a/src/sandscale/_account.py +++ b/src/sandscale/_account.py @@ -8,7 +8,7 @@ from typing import Any, Optional, Sequence, Union from ._transport import Transport, seg -from .admin_models import ApiKey, ApiKeyLimits, ApiKeyList, Billing, Checkout, CreatedApiKey, PlanState, RegionInfo, Usage +from .admin_models import ApiKey, ApiKeyLimits, ApiKeyList, Billing, Checkout, CreatedApiKey, GithubLinkStart, Identity, PlanState, RegionInfo, Usage Raw = dict[str, Any] @@ -40,7 +40,14 @@ def change_plan( seats: Optional[int] = None, region: Optional[str] = None, ) -> PlanState: - """Changes a live subscription: an upgrade applies now, a downgrade at the period end.""" + """Changes a live subscription: an upgrade or more seats is charged first and applies only when + the payment succeeds, a downgrade or fewer seats at the period end. + + Refused 402 ``payment_declined``, ``payment_authentication_required`` or + ``payment_method_required`` (nothing changed; the error body names ``next_step`` and, for + authentication, ``hosted_invoice_url``), and 409 ``charge_in_progress``, + ``charge_not_applied`` or ``pending_change``. + """ raw = self._t.request( "POST", f"/api/v1/orgs/{self._org()}/sandscale/billing/plan", @@ -57,7 +64,7 @@ def set_overage(self, enabled: bool, *, region: Optional[str] = None) -> PlanSta return PlanState.from_raw(raw.get("state") if isinstance(raw.get("state"), dict) else raw) def cancel_pending_plan_change(self, *, region: Optional[str] = None) -> PlanState: - """Withdraws a waiting downgrade.""" + """Withdraws a waiting downgrade or seat decrease.""" raw = self._t.request("DELETE", f"/api/v1/orgs/{self._org()}/sandscale/billing/plan/pending", region=region) body: Raw = raw if isinstance(raw, dict) else {} state = body.get("state") @@ -85,6 +92,22 @@ def usage(self, *, region: Optional[str] = None) -> Usage: """The month's usage across every region.""" return Usage.from_raw(self._t.request("GET", "/api/v1/sandscale/usage", region=region)) + def identity(self, *, region: Optional[str] = None) -> Identity: + """What your login linked: a GitHub account and a verified card lift the new-account ramp.""" + return Identity.from_raw(self._t.request("GET", "/api/v1/sandscale/identity", region=region)) + + def github_start(self, *, region: Optional[str] = None) -> GithubLinkStart: + """Starts linking a GitHub account (a person signed in, not an API key). Send the person to + ``authorize_url``; GitHub returns them with a code that :meth:`github_complete` finishes with ``state``. + A GitHub account another Sandscale login holds is refused ``account_exists``.""" + return GithubLinkStart.from_raw(self._t.request("POST", "/api/v1/sandscale/identity/github/start", region=region)) + + def github_complete(self, code: str, state: str, *, region: Optional[str] = None) -> Identity: + """Finishes a GitHub link with the code GitHub returned and the ``state`` :meth:`github_start` gave.""" + return Identity.from_raw( + self._t.request("POST", "/api/v1/sandscale/identity/github/complete", json_body={"code": code, "state": state}, region=region) + ) + def regions(self) -> list[RegionInfo]: """The regions the server lists (public).""" raw = self._t.request("GET", "/api/v1/regions") diff --git a/src/sandscale/_admin.py b/src/sandscale/_admin.py index 878b8ee..a265d15 100644 --- a/src/sandscale/_admin.py +++ b/src/sandscale/_admin.py @@ -6,8 +6,9 @@ import hashlib import hmac +import time from datetime import datetime -from typing import Any, Mapping, Optional, Sequence, Union +from typing import Any, List, Mapping, Optional, Sequence, Union from ._services import list_across_regions from ._transport import Transport, seg @@ -23,6 +24,7 @@ TraceExportTest, TraceSummary, Webhook, + WebhookDelivery, ) from .models import ListResult, RegionPage, Snapshot @@ -99,7 +101,8 @@ def list(self, *, region: Optional[str] = None) -> ListResult[Template]: def one(r: Optional[str]) -> tuple[list[Template], RegionPage]: raw = self._t.request("GET", "/api/v1/sandbox/templates", region=r) page = RegionPage(region=r, has_more=bool(raw.get("has_more")), next_cursor=raw.get("next_cursor")) - return [Template.from_raw(x, r) for x in raw.get("data") or []], page + builtin = [Template.from_builtin(x, r) for x in raw.get("builtin") or []] + return builtin + [Template.from_raw(x, r) for x in raw.get("data") or []], page return list_across_regions(self._t, region, one) @@ -165,21 +168,50 @@ def set( return SandboxPolicy.from_raw(raw, self._t.region_of(region)) -def verify_webhook_signature(signature: Optional[str], body: Union[bytes, str], secret: str) -> bool: - """True when ``signature`` (the ``X-Keystone-Signature`` header, ``sha256=``) is the - HMAC-SHA256 of the raw request ``body`` under the webhook's secret. Pass the body exactly as - received, before any JSON parsing. The comparison is constant time; a missing or malformed - header is False. (Current signing carries no timestamp.)""" - if not signature or not secret or not signature.startswith("sha256="): +def verify_webhook_signature( + signature: Optional[str], + body: Union[bytes, str], + secret: str, + *, + tolerance_seconds: float = 300.0, + now: Optional[float] = None, +) -> bool: + """True when ``signature`` (the ``X-Sandscale-Signature`` header of a delivery, + ``t=,v1=.">``) matches the raw request ``body`` + under the webhook's ``secret`` and its timestamp is within the tolerance (default 5 minutes). + Pass the body exactly as received, before any JSON parsing. During a secret rotation's overlap + the header carries two ``v1`` values and either may match, so verify with the secret you hold. + The comparison is constant time; a missing, malformed or stale header is False. Also drop a + repeated ``X-Sandscale-Event-Id`` to refuse a replay inside the tolerance.""" + if not signature or not secret: + return False + t = "" + sigs: list[str] = [] + for part in signature.split(","): + k, sep, v = part.partition("=") + if not sep: + continue + k, v = k.strip(), v.strip().lower() + if k == "t": + t = v + elif k == "v1": + sigs.append(v) + if not (t.isascii() and t.isdigit() and len(t) <= 15) or not sigs: + return False + if abs((time.time() if now is None else now) - int(t)) > tolerance_seconds: return False - given = signature[len("sha256=") :].strip().lower() data = body.encode() if isinstance(body, str) else body - expected = hmac.new(secret.encode(), data, hashlib.sha256).hexdigest() - return hmac.compare_digest(given.encode(), expected.encode()) + expected = hmac.new(secret.encode(), t.encode() + b"." + data, hashlib.sha256).hexdigest() + ok = False + for given in sigs: + if hmac.compare_digest(given.encode(), expected.encode()): + ok = True + return ok class Webhooks: - """Webhook endpoints for sandbox events.""" + """Signed webhooks for your compute events (sandboxes, workspaces, tasks, leases, approvals, + usage and billing).""" def __init__(self, t: Transport) -> None: self._t = t @@ -195,18 +227,68 @@ def create( self, *, url: str, - events: Optional[Sequence[str]] = None, - secret: Optional[str] = None, + events: Sequence[str], + lease_lead_seconds: Optional[int] = None, region: Optional[str] = None, ) -> CreatedWebhook: - """Registers an endpoint. The signing secret is shown once, on the returned object.""" - body = _body({"url": url, "events": list(events) if events is not None else None, "secret": secret}) + """Registers an https endpoint for event types (see :meth:`event_types`). The signing + secret is shown once, on the returned object.""" + body = _body({"url": url, "events": list(events), "lease_lead_seconds": lease_lead_seconds}) raw = self._t.request("POST", "/api/v1/sandbox/webhooks", region=region, json_body=body) return CreatedWebhook.from_raw(raw, self._t.region_of(region)) + def get(self, webhook_id: str, *, region: Optional[str] = None) -> Webhook: + raw = self._t.request("GET", f"/api/v1/sandbox/webhooks/{seg(webhook_id)}", region=region) + return Webhook.from_raw(raw, self._t.region_of(region)) + def delete(self, webhook_id: str, *, region: Optional[str] = None) -> None: self._t.request("DELETE", f"/api/v1/sandbox/webhooks/{seg(webhook_id)}", region=region) + def rotate_secret( + self, webhook_id: str, *, overlap_seconds: Optional[int] = None, region: Optional[str] = None + ) -> CreatedWebhook: + """Replaces the signing secret; the previous one keeps signing for ``overlap_seconds`` + (default 24 h, at most 7 days, 0 ends it at once). The new secret is shown once.""" + body = None if overlap_seconds is None else {"overlap_seconds": overlap_seconds} + raw = self._t.request( + "POST", f"/api/v1/sandbox/webhooks/{seg(webhook_id)}/rotate-secret", region=region, json_body=body + ) + return CreatedWebhook.from_raw(raw, self._t.region_of(region)) + + def test(self, webhook_id: str, *, region: Optional[str] = None) -> WebhookDelivery: + """Queues one ``webhook.test`` delivery; follow it with :meth:`list_deliveries`.""" + raw = self._t.request("POST", f"/api/v1/sandbox/webhooks/{seg(webhook_id)}/test", region=region) + return WebhookDelivery.from_raw(raw, self._t.region_of(region)) + + def list_deliveries( + self, + webhook_id: str, + *, + before: Optional[str] = None, + limit: Optional[int] = None, + region: Optional[str] = None, + ) -> tuple[List[WebhookDelivery], Optional[str]]: + """The delivery log, newest first, and the ``before`` value of the next page (or None).""" + raw = self._t.request( + "GET", + f"/api/v1/sandbox/webhooks/{seg(webhook_id)}/deliveries", + region=region, + query={"before": before, "limit": limit}, + ) + r = self._t.region_of(region) + return [WebhookDelivery.from_raw(d, r) for d in raw.get("deliveries") or []], raw.get("next_before") or None + + def redeliver(self, webhook_id: str, delivery_id: str, *, region: Optional[str] = None) -> WebhookDelivery: + """Sends a delivery's event again, signed afresh (at most 10 a minute per endpoint).""" + raw = self._t.request( + "POST", f"/api/v1/sandbox/webhooks/{seg(webhook_id)}/deliveries/{seg(delivery_id)}/redeliver", region=region + ) + return WebhookDelivery.from_raw(raw, self._t.region_of(region)) + + def event_types(self, *, region: Optional[str] = None) -> List[Raw]: + raw = self._t.request("GET", "/api/v1/sandbox/webhooks/event-types", region=region) + return list(raw.get("event_types") or []) + def _iso(value: Union[datetime, str, None]) -> Optional[str]: return value.isoformat() if isinstance(value, datetime) else value @@ -253,7 +335,7 @@ def set_export( enabled: Optional[bool] = None, region: Optional[str] = None, ) -> TraceExport: - """Creates or replaces the export. ``headers`` are stored in Keystone Vault and never answered; + """Creates or replaces the export. ``headers`` are stored in Sandscale Vault and never answered; omit them to keep the stored ones, ``{}`` removes them.""" body = _body({"protocol": protocol, "endpoint": endpoint, "headers": dict(headers) if headers is not None else None, "enabled": enabled}) raw = self._t.request("PUT", "/api/v1/sandbox/trace-export", region=region, json_body=body) diff --git a/src/sandscale/_api.py b/src/sandscale/_api.py new file mode 100644 index 0000000..347c4a5 --- /dev/null +++ b/src/sandscale/_api.py @@ -0,0 +1,291 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""The typed Sandscale API: ``Sandscale.api..(**args)``. + +Built at import from the generated operation table (``_api_gen.OPERATIONS``, the same functions +a code mode script calls as ``sandscale..(args)``); there is no code per +operation. Every call goes through the client's transport, so regions, retries and errors behave +like the rest of the SDK. The server decides every call; the SDK only checks the shape of the +arguments and the confirm rule before sending.""" + +from __future__ import annotations + +import keyword +import re +from typing import Any, Dict, Iterator, List, Mapping, Optional +from urllib.parse import quote + +from ._api_gen import OPERATIONS +from ._transport import Transport +from .errors import ConfigurationError, SandscaleError + +Operation = Dict[str, Any] + +_BODY_METHODS = {"POST", "PUT", "PATCH"} +#: Arguments of every typed call that are never sent as a parameter. +_RESERVED = ("confirm", "idempotency_key") +_PATH_HOLE = re.compile(r"\{([A-Za-z_][A-Za-z0-9_]*)(\.\.\.)?\}") + + +class ApiArgumentError(ConfigurationError, TypeError): + """A typed API call named an argument the operation does not take, left out a required one or + gave one of the wrong kind. Raised before any request.""" + + +def snake_case(name: str) -> str: + """``snapshotCreate`` to ``snapshot_create``, ``auditLogs`` to ``audit_logs``.""" + name = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name) + return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name).lower() + + +def _segment(value: Any, *, name: str, many: bool) -> str: + if isinstance(value, bool) or not isinstance(value, (str, int)): + raise ApiArgumentError(f"path argument {name} must be a string or an integer") + text = str(value) + parts = text.split("/") if many else [text] + for part in parts: + if part in ("", ".", ".."): + raise ApiArgumentError(f"path argument {name} has an empty, '.' or '..' segment") + return "/".join(quote(p, safe="") for p in parts) + + +def _argument_name(op: Operation, given: str) -> Optional[str]: + """The parameter a keyword names: its own name, or the name with a trailing underscore when the + name is a Python keyword (``from_`` for ``from``).""" + names = {p["name"] for p in op["params"]} + if given in names: + return given + if given.endswith("_") and given[:-1] in names and keyword.iskeyword(given[:-1]): + return given[:-1] + return None + + +def build_request(op: Operation, args: Mapping[str, Any], org_id: Optional[str]) -> Dict[str, Any]: + """The request one call of ``op`` sends: method, path, query, JSON body and region. Raises + :class:`ApiArgumentError` for an unknown, missing or malformed argument.""" + values: Dict[str, Any] = {} + for given, value in args.items(): + name = _argument_name(op, given) + if name is None: + known = ", ".join(sorted(p["name"] for p in op["params"])) or "none" + raise ApiArgumentError(f"{op['ns']}.{op['fn']} takes no argument {given!r} (it takes: {known})") + if name in values: + raise ApiArgumentError(f"{op['ns']}.{op['fn']} got argument {name!r} twice") + values[name] = value + + path_values: Dict[str, Any] = {} + query: Dict[str, Any] = {} + body: Dict[str, Any] = {} + whole: Any = None + has_whole = False + region: Optional[str] = None + for p in op["params"]: + name, where = p["name"], p["in"] + value = values.get(name) + if value is None and p.get("from") == "org": + if not org_id: + raise ConfigurationError( + f"{op['ns']}.{op['fn']} needs an organization: pass {name}, or org_id to the client, or set SANDSCALE_ORG_ID" + ) + value = org_id + if value is None: + if p.get("required") or where == "path": + raise ApiArgumentError(f"{op['ns']}.{op['fn']} needs argument {name!r}") + continue + wire = p.get("wire") or name + if where == "path": + path_values[name] = value + elif where == "query": + query[wire] = value + elif where == "query_all": + if not isinstance(value, Mapping): + raise ApiArgumentError(f"argument {name} of {op['ns']}.{op['fn']} must be a mapping of query parameters") + for k, v in value.items(): + query[str(k)] = v + elif where == "body": + body[wire] = value + elif where == "whole": + whole, has_whole = value, True + elif where == "region": + if not isinstance(value, str): + raise ApiArgumentError("region must be a string") + region = value + else: # pragma: no cover - a generator change the SDK does not know yet + raise ApiArgumentError(f"{op['ns']}.{op['fn']}: parameter {name} is sent in {where!r}, which this SDK does not know") + query.update(op.get("fixed_query") or {}) + + def fill(m: "re.Match[str]") -> str: + name, many = m.group(1), bool(m.group(2)) + return _segment(path_values[name], name=name, many=many) + + path = _PATH_HOLE.sub(fill, op["path"]) + + json_body: Any = None + if has_whole: + if body: + if not isinstance(whole, Mapping): + raise ApiArgumentError(f"{op['ns']}.{op['fn']}: the body must be a mapping when body fields are also given") + json_body = {**whole, **body} + else: + json_body = whole + elif body: + json_body = body + if json_body is None and op["method"] in _BODY_METHODS: + json_body = {} + return { + "method": op["method"], + "path": path, + "query": {k: _query_value(v) for k, v in query.items()}, + "json_body": json_body, + "region": region, + } + + +def _query_value(value: Any) -> Any: + if isinstance(value, bool): + return "true" if value else "false" + return value + + +class ApiFunction: + """One operation of the typed API, bound to a client.""" + + def __init__(self, transport: Transport, op: Operation) -> None: + self._t = transport + self.operation: Operation = op + self.__name__ = op["fn"] + self.__qualname__ = f"{op['ns']}.{op['fn']}" + params = ", ".join( + f"{p['name']}{'' if p.get('required') or (p['in'] == 'path' and p.get('from') != 'org') else '?'} ({p['in']})" + for p in op["params"] + ) or "no arguments" + flags = [] + if op.get("mutates"): + flags.append("changes something: idempotency_key=... makes it safe to retry") + if op.get("confirm"): + flags.append("deletes, ends or changes billing: needs confirm=True") + self.__doc__ = f"{op['method']} {op['path']} (operation {op['op']}). Arguments: {params}." + ( + " " + "; ".join(flags) + "." if flags else "" + ) + + def __repr__(self) -> str: + return f"" + + def __call__( + self, + _args: Optional[Mapping[str, Any]] = None, + /, + *, + confirm: bool = False, + idempotency_key: Optional[str] = None, + **kwargs: Any, + ) -> Any: + op = self.operation + args: Dict[str, Any] = dict(_args or {}) + # The arguments may also come as one mapping, the way a script calls them. + if "confirm" in args: + confirm = bool(args.pop("confirm")) or confirm + if "idempotency_key" in args: + idempotency_key = args.pop("idempotency_key") or idempotency_key + for k, v in kwargs.items(): + if k in args: + raise ApiArgumentError(f"{self.__qualname__} got argument {k!r} twice") + args[k] = v + if op.get("confirm") and confirm is not True: + raise SandscaleError( + 0, + "confirmation_required", + f"{self.__qualname__} ({op['op']}) deletes, ends or changes billing: call it again with confirm=True", + details={"operation": op["op"], "next": {"confirm": True}}, + ) + if idempotency_key is not None: + if not op.get("mutates"): + raise ApiArgumentError(f"{self.__qualname__} changes nothing: idempotency_key applies to writes only") + if not isinstance(idempotency_key, str) or not idempotency_key: + raise ApiArgumentError("idempotency_key must be a non-empty string") + req = build_request(op, args, self._t.org_id) + return self._t.request( + req["method"], + req["path"], + region=req["region"], + query=req["query"] or None, + json_body=req["json_body"], + idempotency_key=idempotency_key, + ) + + +class ApiNamespace: + """The functions of one namespace; each under its camelCase name and its snake_case name.""" + + def __init__(self, name: str, functions: Mapping[str, ApiFunction]) -> None: + self._name = name + self._functions: Dict[str, ApiFunction] = {} + for fn, f in functions.items(): + for alias in {fn, snake_case(fn)}: + self._functions[alias] = f + setattr(self, alias, f) + + def __getattr__(self, name: str) -> ApiFunction: + # Only reached for a name that is not set: say which names exist. + if name.startswith("__"): + raise AttributeError(name) + known = ", ".join(sorted({f.__name__ for f in self._functions.values()})) + raise AttributeError(f"the typed API has no function {self._name}.{name} (it has: {known})") + + def __iter__(self) -> Iterator[ApiFunction]: + seen: List[int] = [] + for f in self._functions.values(): + if id(f) not in seen: + seen.append(id(f)) + yield f + + def __repr__(self) -> str: + return f"" + + +class Api: + """``Sandscale.api``: every operation of the typed API, as ``api..(**args)``. + + Namespaces and functions answer to their camelCase names (``api.auditLogs.auditEventsList``) + and their snake_case names (``api.audit_logs.audit_events_list``). Arguments are the + operation's parameter names; a Python keyword takes a trailing underscore (``from_``). An + operation that deletes, ends or changes billing needs ``confirm=True``; a write takes + ``idempotency_key``. Path parameters naming the organization are filled from the client's + ``org_id`` when left out. Answers are the server's JSON, as is.""" + + def __init__(self, transport: Transport, operations: Optional[List[Operation]] = None) -> None: + self._t = transport + ops = OPERATIONS if operations is None else operations + by_ns: Dict[str, Dict[str, ApiFunction]] = {} + self._by_op: Dict[str, ApiFunction] = {} + for op in ops: + f = ApiFunction(transport, op) + by_ns.setdefault(op["ns"], {})[op["fn"]] = f + self._by_op[op["op"]] = f + self._namespaces: Dict[str, ApiNamespace] = {} + for ns, functions in by_ns.items(): + namespace = ApiNamespace(ns, functions) + for alias in {ns, snake_case(ns)}: + self._namespaces[alias] = namespace + setattr(self, alias, namespace) + + def __getattr__(self, name: str) -> ApiNamespace: + if name.startswith("__"): + raise AttributeError(name) + raise AttributeError(f"the typed API has no namespace {name} (it has: {', '.join(self.namespaces())})") + + def namespaces(self) -> List[str]: + """The namespaces, by their camelCase names.""" + return sorted({n._name for n in self._namespaces.values()}) + + def operations(self) -> List[Operation]: + """The operation table the API is built from.""" + return [f.operation for f in self._by_op.values()] + + def call(self, operation: str, args: Optional[Mapping[str, Any]] = None, **kwargs: Any) -> Any: + """Calls an operation by its operation name (``sandbox_terminate``), as the remote MCP's + ``sandscale_call`` names it.""" + f = self._by_op.get(operation) + if f is None: + raise ApiArgumentError(f"the typed API has no operation {operation!r}") + return f(args, **kwargs) diff --git a/src/sandscale/_api_gen.py b/src/sandscale/_api_gen.py new file mode 100644 index 0000000..c90259e --- /dev/null +++ b/src/sandscale/_api_gen.py @@ -0,0 +1,353 @@ +# Code generated by cmd/toolcatalog-gen. DO NOT EDIT. +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""The typed Sandscale API's operations (the functions code mode scripts call), from the tool catalogue.""" + +import json as _json + +OPERATIONS = _json.loads(r'''[ +{"ns":"access","fn":"invitationCreate","op":"invitation_create","method":"POST","path":"/api/v1/users/invitations","params":[{"name":"display_name","in":"body"},{"name":"email","in":"body","required":true},{"name":"invited_by_user_id","in":"body"},{"name":"organization_id","in":"body","required":true}],"mutates":true}, +{"ns":"access","fn":"invitationRevoke","op":"invitation_revoke","method":"POST","path":"/api/v1/users/invitations/{id}/revoke","params":[{"name":"id","in":"path","required":true},{"name":"body","in":"whole"}],"mutates":true,"confirm":true}, +{"ns":"access","fn":"invitationsList","op":"invitations_list","method":"GET","path":"/api/v1/users/invitations","params":[{"name":"after","in":"query"},{"name":"limit","in":"query"},{"name":"organization_id","in":"query"},{"name":"status","in":"query"}]}, +{"ns":"access","fn":"memberRemove","op":"member_remove","method":"DELETE","path":"/api/v1/organizations/{id}/members/{user_id}","params":[{"name":"id","in":"path","from":"org"},{"name":"user_id","in":"path","required":true}],"mutates":true,"confirm":true}, +{"ns":"access","fn":"membersList","op":"members_list","method":"GET","path":"/api/v1/organizations/{id}/members","params":[{"name":"id","in":"path","from":"org"},{"name":"limit","in":"query"},{"name":"offset","in":"query"}]}, +{"ns":"access","fn":"orgApiKeysDelete","op":"org_api_keys_delete","method":"DELETE","path":"/api/v1/organizations/{id}/api-keys/{key_id}","params":[{"name":"id","in":"path","from":"org"},{"name":"key_id","in":"path","required":true}],"mutates":true,"confirm":true}, +{"ns":"access","fn":"orgApiKeysList","op":"org_api_keys_list","method":"GET","path":"/api/v1/organizations/{id}/api-keys","params":[{"name":"id","in":"path","from":"org"}]}, +{"ns":"access","fn":"orgApiKeysScopeReportGet","op":"org_api_keys_scope_report_get","method":"GET","path":"/api/v1/organizations/{id}/api-keys/scope-report","params":[{"name":"id","in":"path","from":"org"}]}, +{"ns":"access","fn":"orgMembersCreate","op":"org_members_create","method":"POST","path":"/api/v1/organizations/{id}/members","params":[{"name":"id","in":"path","from":"org"},{"name":"user_id","in":"body","required":true}],"mutates":true}, +{"ns":"access","fn":"usersInvitationsResend","op":"users_invitations_resend","method":"POST","path":"/api/v1/users/invitations/{id}/resend","params":[{"name":"id","in":"path","required":true},{"name":"body","in":"whole"}],"mutates":true}, +{"ns":"auditLogs","fn":"auditEventsList","op":"audit_events_list","method":"GET","path":"/api/v1/audit-logs","params":[{"name":"action","in":"query"},{"name":"action_prefix","in":"query"},{"name":"from","in":"query"},{"name":"include_read_only","in":"query"},{"name":"limit","in":"query"},{"name":"offset","in":"query"},{"name":"outcome","in":"query"},{"name":"project_id","in":"query"},{"name":"resource_type","in":"query"},{"name":"to","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"auditEventsQuery","op":"audit_events_query","method":"GET","path":"/api/v1/audit-logs/query","params":[{"name":"from","in":"query"},{"name":"query","in":"query"},{"name":"to","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"chainLanesList","op":"audit_logs_chain_lanes_list","method":"GET","path":"/api/v1/audit-logs/chain-lanes","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"coldSegmentsList","op":"audit_logs_cold_segments_list","method":"GET","path":"/api/v1/audit-logs/cold-segments","params":[{"name":"organization_id","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"endpointActivityGet","op":"audit_logs_endpoint_activity_get","method":"GET","path":"/api/v1/audit-logs/endpoint-activity","params":[{"name":"category","in":"query"},{"name":"device_id","in":"query"},{"name":"limit","in":"query"},{"name":"offset","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"exportsGet","op":"audit_logs_exports_get","method":"GET","path":"/api/v1/audit-logs/exports/{exportID}","params":[{"name":"exportID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"exportsList","op":"audit_logs_exports_list","method":"GET","path":"/api/v1/audit-logs/exports","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"merkleCheckpointsList","op":"audit_logs_merkle_checkpoints_list","method":"GET","path":"/api/v1/audit-logs/merkle/checkpoints","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"merkleCheckpointsVerifyGet","op":"audit_logs_merkle_checkpoints_verify_get","method":"GET","path":"/api/v1/audit-logs/merkle/checkpoints/{seq}/verify","params":[{"name":"seq","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"organizationGet","op":"audit_logs_organization_get","method":"GET","path":"/api/v1/audit-logs/organization","params":[{"name":"account","in":"query"},{"name":"action","in":"query"},{"name":"action_prefix","in":"query"},{"name":"before","in":"query"},{"name":"include_read_only","in":"query"},{"name":"limit","in":"query"},{"name":"outcome","in":"query"},{"name":"resource_type","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"retentionGet","op":"audit_logs_retention_get","method":"GET","path":"/api/v1/audit-logs/retention","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"sessionsList","op":"audit_logs_sessions_list","method":"GET","path":"/api/v1/audit-logs/sessions","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"sessionsReplayGet","op":"audit_logs_sessions_replay_get","method":"GET","path":"/api/v1/audit-logs/sessions/{id}/replay","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"storageStatsList","op":"audit_logs_storage_stats_list","method":"GET","path":"/api/v1/audit-logs/storage-stats","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"tieringGet","op":"audit_logs_tiering_get","method":"GET","path":"/api/v1/audit-logs/tiering","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"verificationsGet","op":"audit_logs_verifications_get","method":"GET","path":"/api/v1/audit-logs/verifications/{id}","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"verificationsList","op":"audit_logs_verifications_list","method":"GET","path":"/api/v1/audit-logs/verifications","params":[{"name":"limit","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"auditLogs","fn":"verifyGet","op":"audit_logs_verify_get","method":"GET","path":"/api/v1/audit-logs/verify","params":[{"name":"from","in":"query"},{"name":"to","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"billing","fn":"paymentMethodCheckoutGet","op":"billing_payment_method_checkout_get","method":"GET","path":"/api/v1/orgs/{orgID}/billing/payment-method/checkout/{checkoutID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"checkoutID","in":"path","required":true}]}, +{"ns":"billing","fn":"planGet","op":"plan_get","method":"GET","path":"/api/v1/orgs/{orgID}/billing","params":[{"name":"orgID","in":"path","from":"org"}]}, +{"ns":"billing","fn":"profileGet","op":"billing_profile_get","method":"GET","path":"/api/v1/orgs/{orgID}/billing/profile","params":[{"name":"orgID","in":"path","from":"org"}]}, +{"ns":"billing","fn":"sandscaleBillingGet","op":"sandscale_billing_get","method":"GET","path":"/api/v1/orgs/{orgID}/sandscale/billing","params":[{"name":"orgID","in":"path","from":"org"}]}, +{"ns":"billing","fn":"sandscaleBillingPortal","op":"sandscale_billing_portal","method":"POST","path":"/api/v1/orgs/{orgID}/sandscale/billing/portal","params":[{"name":"orgID","in":"path","from":"org"}],"mutates":true}, +{"ns":"billing","fn":"sandscaleCheckoutStart","op":"sandscale_checkout_start","method":"POST","path":"/api/v1/orgs/{orgID}/sandscale/billing/checkout","params":[{"name":"orgID","in":"path","from":"org"},{"name":"interval","in":"body","required":true},{"name":"plan","in":"body","required":true},{"name":"seats","in":"body"}],"mutates":true}, +{"ns":"billing","fn":"sandscaleSpendCapsGet","op":"sandscale_spend_caps_get","method":"GET","path":"/api/v1/orgs/{orgID}/sandscale/spend-caps/{capID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"capID","in":"path","required":true}]}, +{"ns":"billing","fn":"sandscaleSpendCapsList","op":"sandscale_spend_caps_list","method":"GET","path":"/api/v1/orgs/{orgID}/sandscale/spend-caps","params":[{"name":"orgID","in":"path","from":"org"}]}, +{"ns":"billing","fn":"sandscaleUsageGet","op":"sandscale_usage_get","method":"GET","path":"/api/v1/sandscale/usage","params":[]}, +{"ns":"billing","fn":"standingGet","op":"billing_standing_get","method":"GET","path":"/api/v1/orgs/{orgID}/billing/standing","params":[{"name":"orgID","in":"path","from":"org"}]}, +{"ns":"billing","fn":"usageGet","op":"usage_get","method":"GET","path":"/api/v1/orgs/{orgID}/billing/usage","params":[{"name":"orgID","in":"path","from":"org"},{"name":"month","in":"query"}]}, +{"ns":"invitations","fn":"accept","op":"invitations_accept","method":"POST","path":"/api/v1/invitations/{token}/accept","params":[{"name":"token","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"killSwitch","fn":"sandboxKillSwitchGet","op":"sandbox_kill_switch_get","method":"GET","path":"/api/v1/sandbox/kill-switch","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"objects","fn":"deleteAccessKey","op":"objects_delete_access_key","method":"POST","path":"/api/v1/svc/objects/DeleteAccessKey","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"objects","fn":"deleteBucketLifecycle","op":"objects_delete_bucket_lifecycle","method":"POST","path":"/api/v1/svc/objects/DeleteBucketLifecycle","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"objects","fn":"deleteBucketPolicy","op":"objects_delete_bucket_policy","method":"POST","path":"/api/v1/svc/objects/DeleteBucketPolicy","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"objects","fn":"describeObjectsLimits","op":"objects_describe_objects_limits","method":"POST","path":"/api/v1/svc/objects/DescribeObjectsLimits","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"objects","fn":"describeObjectsService","op":"objects_describe_objects_service","method":"POST","path":"/api/v1/svc/objects/DescribeObjectsService","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"objects","fn":"getBucketLifecycle","op":"objects_get_bucket_lifecycle","method":"POST","path":"/api/v1/svc/objects/GetBucketLifecycle","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"objects","fn":"getBucketPolicy","op":"objects_get_bucket_policy","method":"POST","path":"/api/v1/svc/objects/GetBucketPolicy","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"objects","fn":"putBucketLifecycle","op":"objects_put_bucket_lifecycle","method":"POST","path":"/api/v1/svc/objects/PutBucketLifecycle","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"objects","fn":"putBucketPolicy","op":"objects_put_bucket_policy","method":"POST","path":"/api/v1/svc/objects/PutBucketPolicy","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"objects","fn":"storageAccessKeyCreate","op":"storage_access_key_create","method":"POST","path":"/api/v1/svc/objects/CreateAccessKey","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"objects","fn":"storageAccessKeysList","op":"storage_access_keys_list","method":"POST","path":"/api/v1/svc/objects/ListAccessKeys","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"objects","fn":"storageBucketCreate","op":"storage_bucket_create","method":"POST","path":"/api/v1/svc/objects/CreateBucket","params":[{"name":"ContentClass","in":"body"},{"name":"DataEvents","in":"body"},{"name":"Name","in":"body","required":true},{"name":"ObjectLock","in":"body"},{"name":"Versioning","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"objects","fn":"storageBucketDelete","op":"storage_bucket_delete","method":"POST","path":"/api/v1/svc/objects/DeleteBucket","params":[{"name":"Name","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"objects","fn":"storageBucketDescribe","op":"storage_bucket_describe","method":"POST","path":"/api/v1/svc/objects/DescribeBucket","params":[{"name":"Name","in":"body","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"objects","fn":"storageBucketsList","op":"storage_buckets_list","method":"POST","path":"/api/v1/svc/objects/ListBuckets","params":[{"name":"MaxResults","in":"body"},{"name":"NextToken","in":"body"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"objects","fn":"updateAccessKey","op":"objects_update_access_key","method":"POST","path":"/api/v1/svc/objects/UpdateAccessKey","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"objects","fn":"updateBucket","op":"objects_update_bucket","method":"POST","path":"/api/v1/svc/objects/UpdateBucket","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"orgs","fn":"invitationsDelete","op":"invitations_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/invitations/{invID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"invID","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"orgs","fn":"quotasAlertsList","op":"quotas_alerts_list","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/alerts","params":[{"name":"orgID","in":"path","from":"org"},{"name":"unacked_only","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"orgs","fn":"quotasForecastGet","op":"quotas_forecast_get","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/{quotaID}/forecast","params":[{"name":"orgID","in":"path","from":"org"},{"name":"quotaID","in":"path","required":true},{"name":"lookback_days","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"orgs","fn":"quotasGet","op":"quotas_get","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/{quotaID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"quotaID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"orgs","fn":"quotasList","op":"quotas_list","method":"GET","path":"/api/v1/orgs/{orgID}/quotas","params":[{"name":"orgID","in":"path","from":"org"},{"name":"active_only","in":"query"},{"name":"resource_type","in":"query"},{"name":"scope","in":"query"},{"name":"user_id","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"orgs","fn":"quotasPoolsList","op":"quotas_pools_list","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/pools","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"orgs","fn":"quotasReportGet","op":"quotas_report_get","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/report","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"orgs","fn":"quotasRequestsList","op":"quotas_requests_list","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/requests","params":[{"name":"orgID","in":"path","from":"org"},{"name":"status","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"orgs","fn":"quotasUsageGet","op":"quotas_usage_get","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/{quotaID}/usage","params":[{"name":"orgID","in":"path","from":"org"},{"name":"quotaID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"profile","fn":"accountInvitationsAccept","op":"account_invitations_accept","method":"POST","path":"/api/v1/account/invitations/accept","params":[{"name":"body","in":"whole"}],"mutates":true}, +{"ns":"profile","fn":"accountInvitationsList","op":"account_invitations_list","method":"GET","path":"/api/v1/account/invitations","params":[]}, +{"ns":"profile","fn":"accountInvitationsLookup","op":"account_invitations_lookup","method":"POST","path":"/api/v1/account/invitations/lookup","params":[{"name":"body","in":"whole"}],"mutates":true}, +{"ns":"profile","fn":"myApiKeyDelete","op":"my_api_key_delete","method":"DELETE","path":"/api/v1/account/api-keys/{id}","params":[{"name":"id","in":"path","required":true}],"mutates":true,"confirm":true}, +{"ns":"profile","fn":"myApiKeysList","op":"my_api_keys_list","method":"GET","path":"/api/v1/account/api-keys","params":[]}, +{"ns":"profile","fn":"organizationsList","op":"organizations_list","method":"GET","path":"/api/v1/account/organizations","params":[]}, +{"ns":"profileActivity","fn":"meUsageGet","op":"me_usage_get","method":"GET","path":"/api/v1/me/usage","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"regions","fn":"list","op":"regions_list","method":"GET","path":"/api/v1/regions","params":[]}, +{"ns":"sandbox","fn":"activityGet","op":"sandbox_activity_get","method":"GET","path":"/api/v1/sandbox/activity","params":[{"name":"days","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"artifactsApprove","op":"sandbox_artifacts_approve","method":"POST","path":"/api/v1/sandbox/artifacts/{id}/approve","params":[{"name":"id","in":"path","required":true},{"name":"target_path","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"artifactsList","op":"sandbox_artifacts_list","method":"GET","path":"/api/v1/sandbox/artifacts","params":[{"name":"run_id","in":"query"},{"name":"status","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"artifactsReject","op":"sandbox_artifacts_reject","method":"POST","path":"/api/v1/sandbox/artifacts/{id}/reject","params":[{"name":"id","in":"path","required":true},{"name":"reason","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"batchesCreate","op":"sandbox_batches_create","method":"POST","path":"/api/v1/sandbox/batches","params":[{"name":"command","in":"body"},{"name":"count","in":"body","required":true},{"name":"cpu_count","in":"body"},{"name":"disk_mb","in":"body"},{"name":"image","in":"body"},{"name":"labels","in":"body"},{"name":"mem_mb","in":"body"},{"name":"metadata","in":"body"},{"name":"name","in":"body"},{"name":"network","in":"body"},{"name":"priority","in":"body"},{"name":"template_id","in":"body"},{"name":"ttl_seconds","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"batchesGet","op":"sandbox_batches_get","method":"GET","path":"/api/v1/sandbox/batches/{batchID}","params":[{"name":"batchID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"cachesDelete","op":"sandbox_caches_delete","method":"DELETE","path":"/api/v1/sandbox/caches/{cacheId}","params":[{"name":"cacheId","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"sandbox","fn":"cachesList","op":"sandbox_caches_list","method":"GET","path":"/api/v1/sandbox/caches","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"create","op":"sandbox_create","method":"POST","path":"/api/v1/sandbox/instances","params":[{"name":"command","in":"body"},{"name":"cpu_count","in":"body"},{"name":"disk_mb","in":"body"},{"name":"env","in":"body"},{"name":"environment_id","in":"body"},{"name":"image","in":"body"},{"name":"labels","in":"body"},{"name":"mem_mb","in":"body"},{"name":"metadata","in":"body"},{"name":"name","in":"body"},{"name":"network","in":"body"},{"name":"priority","in":"body"},{"name":"queue","in":"body"},{"name":"runtime","in":"body"},{"name":"snapshot_id","in":"body"},{"name":"template_id","in":"body"},{"name":"ttl_seconds","in":"body"},{"name":"vault_env","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"docsList","op":"sandbox_docs_list","method":"GET","path":"/api/v1/sandbox/docs","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"exec","op":"sandbox_exec","method":"POST","path":"/api/v1/sandbox/instances/{id}/exec","params":[{"name":"id","in":"path","required":true},{"name":"command","in":"body","required":true},{"name":"env","in":"body"},{"name":"stdin","in":"body"},{"name":"timeout_sec","in":"body"},{"name":"wait","in":"body"},{"name":"workdir","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"fileRead","op":"sandbox_file_read","method":"GET","path":"/api/v1/sandbox/instances/{id}/files","params":[{"name":"id","in":"path","required":true},{"name":"path","in":"query","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"fileWrite","op":"sandbox_file_write","method":"PUT","path":"/api/v1/sandbox/instances/{id}/files","params":[{"name":"id","in":"path","required":true},{"name":"content","in":"body","required":true},{"name":"mode","in":"body"},{"name":"path","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"get","op":"sandbox_get","method":"GET","path":"/api/v1/sandbox/instances/{id}","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"instancesCachesRestore","op":"sandbox_instances_caches_restore","method":"POST","path":"/api/v1/sandbox/instances/{id}/caches/restore","params":[{"name":"id","in":"path","required":true},{"name":"ecosystem","in":"body","required":true},{"name":"lockfile","in":"body","required":true},{"name":"path","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"instancesCachesSave","op":"sandbox_instances_caches_save","method":"POST","path":"/api/v1/sandbox/instances/{id}/caches/save","params":[{"name":"id","in":"path","required":true},{"name":"ecosystem","in":"body","required":true},{"name":"lockfile","in":"body","required":true},{"name":"path","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"instancesKeepAwake","op":"sandbox_instances_keep_awake","method":"POST","path":"/api/v1/sandbox/instances/{id}/keep-awake","params":[{"name":"id","in":"path","required":true},{"name":"reason","in":"body"},{"name":"ttl_seconds","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"instancesMetricsList","op":"sandbox_instances_metrics_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/metrics","params":[{"name":"id","in":"path","required":true},{"name":"start","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"instancesPortsDelete","op":"sandbox_instances_ports_delete","method":"DELETE","path":"/api/v1/sandbox/instances/{id}/ports/{port}","params":[{"name":"id","in":"path","required":true},{"name":"port","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"sandbox","fn":"instancesPortsList","op":"sandbox_instances_ports_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/ports","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"instancesPortsPreviewLinks","op":"sandbox_instances_ports_preview_links","method":"POST","path":"/api/v1/sandbox/instances/{id}/ports/{port}/preview-links","params":[{"name":"id","in":"path","required":true},{"name":"port","in":"path","required":true},{"name":"ttl_seconds","in":"body"},{"name":"visibility","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"instancesPrepare","op":"sandbox_instances_prepare","method":"POST","path":"/api/v1/sandbox/instances/{id}/prepare","params":[{"name":"id","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"instancesPreviewLinksDelete","op":"sandbox_instances_preview_links_delete","method":"DELETE","path":"/api/v1/sandbox/instances/{id}/preview-links/{linkId}","params":[{"name":"id","in":"path","required":true},{"name":"linkId","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"sandbox","fn":"instancesPreviewLinksList","op":"sandbox_instances_preview_links_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/preview-links","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"instancesProjectChangesList","op":"sandbox_instances_project_changes_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/project/changes","params":[{"name":"id","in":"path","required":true},{"name":"dir","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"instancesSnapshotsList","op":"sandbox_instances_snapshots_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/snapshots","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"instancesSshCertificate","op":"sandbox_instances_ssh_certificate","method":"POST","path":"/api/v1/sandbox/instances/{id}/ssh/certificate","params":[{"name":"id","in":"path","required":true},{"name":"public_key","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"instancesSshGet","op":"sandbox_instances_ssh_get","method":"GET","path":"/api/v1/sandbox/instances/{id}/ssh","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"instancesVolumesCommit","op":"sandbox_instances_volumes_commit","method":"POST","path":"/api/v1/sandbox/instances/{id}/volumes/{volumeId}/commit","params":[{"name":"id","in":"path","required":true},{"name":"volumeId","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"instancesVolumesCreate","op":"sandbox_instances_volumes_create","method":"POST","path":"/api/v1/sandbox/instances/{id}/volumes","params":[{"name":"id","in":"path","required":true},{"name":"mode","in":"body","required":true},{"name":"mount_path","in":"body","required":true},{"name":"volume_id","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"instancesVolumesDelete","op":"sandbox_instances_volumes_delete","method":"DELETE","path":"/api/v1/sandbox/instances/{id}/volumes/{volumeId}","params":[{"name":"id","in":"path","required":true},{"name":"volumeId","in":"path","required":true},{"name":"commit","in":"query"},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"sandbox","fn":"instancesVolumesList","op":"sandbox_instances_volumes_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/volumes","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"jobsInput","op":"sandbox_jobs_input","method":"POST","path":"/api/v1/sandbox/jobs/{id}/input","params":[{"name":"id","in":"path","required":true},{"name":"data","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"jobsPtyResize","op":"sandbox_jobs_pty_resize","method":"POST","path":"/api/v1/sandbox/jobs/{id}/pty/resize","params":[{"name":"id","in":"path","required":true},{"name":"cols","in":"body","required":true},{"name":"rows","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"launchOptions","op":"sandbox_launch_options","method":"GET","path":"/api/v1/sandbox/launch-options","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"list","op":"sandbox_list","method":"GET","path":"/api/v1/sandbox/instances","params":[{"name":"cursor","in":"query"},{"name":"limit","in":"query"},{"name":"project_id","in":"query"},{"name":"status","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"openapiYamlGet","op":"sandbox_openapi_yaml_get","method":"GET","path":"/api/v1/sandbox/openapi.yaml","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"orgsBillingUsageGet","op":"sandbox_orgs_billing_usage_get","method":"GET","path":"/api/v1/sandbox/orgs/{id}/billing/usage","params":[{"name":"id","in":"path","from":"org"},{"name":"end","in":"query","required":true},{"name":"start","in":"query","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"pause","op":"sandbox_pause","method":"POST","path":"/api/v1/sandbox/instances/{id}/pause","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"policyGet","op":"sandbox_policy_get","method":"GET","path":"/api/v1/sandbox/policy","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"policyPortExposureGet","op":"sandbox_policy_port_exposure_get","method":"GET","path":"/api/v1/sandbox/policy/port-exposure","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"policyPortExposureSet","op":"sandbox_policy_port_exposure_set","method":"PUT","path":"/api/v1/sandbox/policy/port-exposure","params":[{"name":"allowed_ports","in":"body","required":true},{"name":"default_ttl_seconds","in":"body","required":true},{"name":"max_open_per_sandbox","in":"body","required":true},{"name":"max_ttl_seconds","in":"body","required":true},{"name":"mode","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"policySet","op":"sandbox_policy_set","method":"PUT","path":"/api/v1/sandbox/policy","params":[{"name":"allowed_providers","in":"body"},{"name":"egress_allowlist","in":"body"},{"name":"egress_presets","in":"body"},{"name":"max_concurrent","in":"body"},{"name":"max_cpu","in":"body"},{"name":"max_cpu_cores_per_user","in":"body"},{"name":"max_disk_mb","in":"body"},{"name":"max_exec_time_sec","in":"body"},{"name":"max_mem_mb","in":"body"},{"name":"max_memory_gb_per_user","in":"body"},{"name":"max_workspaces_per_user","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"policySnapshotsList","op":"sandbox_policy_snapshots_list","method":"GET","path":"/api/v1/sandbox/policy/snapshots","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"policySnapshotsSet","op":"sandbox_policy_snapshots_set","method":"PUT","path":"/api/v1/sandbox/policy/snapshots","params":[{"name":"enabled","in":"body","required":true},{"name":"max_snapshot_bytes","in":"body","required":true},{"name":"max_snapshots","in":"body","required":true},{"name":"max_total_bytes","in":"body","required":true},{"name":"retention_days","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"policySshGet","op":"sandbox_policy_ssh_get","method":"GET","path":"/api/v1/sandbox/policy/ssh","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"policySshSet","op":"sandbox_policy_ssh_set","method":"PUT","path":"/api/v1/sandbox/policy/ssh","params":[{"name":"cert_ttl_seconds","in":"body","required":true},{"name":"enabled","in":"body","required":true},{"name":"max_session_seconds","in":"body","required":true},{"name":"mode","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"policyStorageGet","op":"sandbox_policy_storage_get","method":"GET","path":"/api/v1/sandbox/policy/storage","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"policyStorageSet","op":"sandbox_policy_storage_set","method":"PUT","path":"/api/v1/sandbox/policy/storage","params":[{"name":"cache_ttl_days","in":"body","required":true},{"name":"caches_enabled","in":"body","required":true},{"name":"max_cache_entry_bytes","in":"body","required":true},{"name":"max_cache_total_bytes","in":"body","required":true},{"name":"max_volume_bytes","in":"body","required":true},{"name":"max_volumes","in":"body","required":true},{"name":"volumes_enabled","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"policyWarmPoolGet","op":"sandbox_policy_warm_pool_get","method":"GET","path":"/api/v1/sandbox/policy/warm-pool","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"policyWarmPoolSet","op":"sandbox_policy_warm_pool_set","method":"PUT","path":"/api/v1/sandbox/policy/warm-pool","params":[{"name":"pools","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"portExpose","op":"sandbox_port_expose","method":"POST","path":"/api/v1/sandbox/instances/{id}/ports","params":[{"name":"id","in":"path","required":true},{"name":"port","in":"body","required":true},{"name":"protocol","in":"body"},{"name":"ttl_seconds","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"queueDelete","op":"sandbox_queue_delete","method":"DELETE","path":"/api/v1/sandbox/queue/{entryID}","params":[{"name":"entryID","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"sandbox","fn":"queueGet","op":"sandbox_queue_get","method":"GET","path":"/api/v1/sandbox/queue/{entryID}","params":[{"name":"entryID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"queueList","op":"sandbox_queue_list","method":"GET","path":"/api/v1/sandbox/queue","params":[{"name":"limit","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"quotaGet","op":"sandbox_quota_get","method":"GET","path":"/api/v1/sandbox/quota","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"resume","op":"sandbox_resume","method":"POST","path":"/api/v1/sandbox/instances/{id}/resume","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"runGet","op":"sandbox_run_get","method":"GET","path":"/api/v1/sandbox/runs/{id}","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"runOutput","op":"sandbox_run_output","method":"GET","path":"/api/v1/sandbox/runs/{id}/output","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"runsDelete","op":"sandbox_runs_delete","method":"DELETE","path":"/api/v1/sandbox/runs/{id}","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"sandbox","fn":"runsList","op":"sandbox_runs_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/runs","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"runsListAll","op":"sandbox_runs_list_all","method":"GET","path":"/api/v1/sandbox/runs","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"snapshotCreate","op":"sandbox_snapshot_create","method":"POST","path":"/api/v1/sandbox/instances/{id}/snapshot","params":[{"name":"id","in":"path","required":true},{"name":"label","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"snapshotDelete","op":"sandbox_snapshot_delete","method":"DELETE","path":"/api/v1/sandbox/snapshots/{snapshotId}","params":[{"name":"snapshotId","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"sandbox","fn":"snapshotsGet","op":"sandbox_snapshots_get","method":"GET","path":"/api/v1/sandbox/snapshots/{snapshotId}","params":[{"name":"snapshotId","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"snapshotsList","op":"sandbox_snapshots_list","method":"GET","path":"/api/v1/sandbox/snapshots","params":[{"name":"limit","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"templatesBuildStatusGet","op":"sandbox_templates_build_status_get","method":"GET","path":"/api/v1/sandbox/templates/{id}/build-status","params":[{"name":"id","in":"path","required":true},{"name":"watch","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"templatesCreate","op":"sandbox_templates_create","method":"POST","path":"/api/v1/sandbox/templates","params":[{"name":"cpu_count","in":"body"},{"name":"disk_size_mb","in":"body"},{"name":"image","in":"body"},{"name":"mem_size_mb","in":"body"},{"name":"name","in":"body","required":true},{"name":"registry_auth","in":"body"},{"name":"snapshot_id","in":"body"},{"name":"version","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"templatesDelete","op":"sandbox_templates_delete","method":"DELETE","path":"/api/v1/sandbox/templates/{id}","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"sandbox","fn":"templatesGet","op":"sandbox_templates_get","method":"GET","path":"/api/v1/sandbox/templates/{id}","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"templatesList","op":"sandbox_templates_list","method":"GET","path":"/api/v1/sandbox/templates","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"terminate","op":"sandbox_terminate","method":"DELETE","path":"/api/v1/sandbox/instances/{id}","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"sandbox","fn":"traceExportDelete","op":"sandbox_trace_export_delete","method":"DELETE","path":"/api/v1/sandbox/trace-export","params":[{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"sandbox","fn":"traceExportGet","op":"sandbox_trace_export_get","method":"GET","path":"/api/v1/sandbox/trace-export","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"traceExportSet","op":"sandbox_trace_export_set","method":"PUT","path":"/api/v1/sandbox/trace-export","params":[{"name":"enabled","in":"body"},{"name":"endpoint","in":"body","required":true},{"name":"headers","in":"body"},{"name":"protocol","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"traceExportTest","op":"sandbox_trace_export_test","method":"POST","path":"/api/v1/sandbox/trace-export/test","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"tracesGet","op":"sandbox_traces_get","method":"GET","path":"/api/v1/sandbox/traces/{traceId}","params":[{"name":"traceId","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"tracesList","op":"sandbox_traces_list","method":"GET","path":"/api/v1/sandbox/traces","params":[{"name":"cursor","in":"query"},{"name":"from","in":"query"},{"name":"limit","in":"query"},{"name":"sandbox_id","in":"query"},{"name":"to","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"volumesCreate","op":"sandbox_volumes_create","method":"POST","path":"/api/v1/sandbox/volumes","params":[{"name":"max_bytes","in":"body"},{"name":"name","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"volumesDelete","op":"sandbox_volumes_delete","method":"DELETE","path":"/api/v1/sandbox/volumes/{volumeId}","params":[{"name":"volumeId","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"sandbox","fn":"volumesGet","op":"sandbox_volumes_get","method":"GET","path":"/api/v1/sandbox/volumes/{volumeId}","params":[{"name":"volumeId","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"volumesList","op":"sandbox_volumes_list","method":"GET","path":"/api/v1/sandbox/volumes","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"webhooksCreate","op":"sandbox_webhooks_create","method":"POST","path":"/api/v1/sandbox/webhooks","params":[{"name":"events","in":"body","required":true},{"name":"lease_lead_seconds","in":"body"},{"name":"url","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"webhooksDelete","op":"sandbox_webhooks_delete","method":"DELETE","path":"/api/v1/sandbox/webhooks/{id}","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"sandbox","fn":"webhooksDeliveriesList","op":"sandbox_webhooks_deliveries_list","method":"GET","path":"/api/v1/sandbox/webhooks/{id}/deliveries","params":[{"name":"id","in":"path","required":true},{"name":"before","in":"query"},{"name":"limit","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"webhooksDeliveriesRedeliver","op":"sandbox_webhooks_deliveries_redeliver","method":"POST","path":"/api/v1/sandbox/webhooks/{id}/deliveries/{deliveryId}/redeliver","params":[{"name":"id","in":"path","required":true},{"name":"deliveryId","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"webhooksEventTypesList","op":"sandbox_webhooks_event_types_list","method":"GET","path":"/api/v1/sandbox/webhooks/event-types","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"webhooksGet","op":"sandbox_webhooks_get","method":"GET","path":"/api/v1/sandbox/webhooks/{id}","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"webhooksList","op":"sandbox_webhooks_list","method":"GET","path":"/api/v1/sandbox/webhooks","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"sandbox","fn":"webhooksRotateSecret","op":"sandbox_webhooks_rotate_secret","method":"POST","path":"/api/v1/sandbox/webhooks/{id}/rotate-secret","params":[{"name":"id","in":"path","required":true},{"name":"overlap_seconds","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"webhooksTest","op":"sandbox_webhooks_test","method":"POST","path":"/api/v1/sandbox/webhooks/{id}/test","params":[{"name":"id","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"sandbox","fn":"workersList","op":"sandbox_workers_list","method":"GET","path":"/api/v1/sandbox/workers","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"session","fn":"entitlementsGet","op":"entitlements_get","method":"GET","path":"/api/v1/account/entitlement","params":[]}, +{"ns":"session","fn":"myPermissions","op":"my_permissions","method":"GET","path":"/api/v1/me/permissions","params":[{"name":"node","in":"query"}]}, +{"ns":"session","fn":"whoami","op":"whoami","method":"GET","path":"/api/v1/users/me","params":[]}, +{"ns":"vault","fn":"mountsList","op":"vault_mounts_list","method":"GET","path":"/api/v1/vault/sys/mounts","params":[{"name":"region","in":"region"}],"regional":true}, +{"ns":"vault","fn":"secretMetadataGet","op":"vault_secret_metadata_get","method":"GET","path":"/api/v1/vault/{mount}/metadata/{path...}","params":[{"name":"mount","in":"path","required":true},{"name":"path","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"vault","fn":"secretNamesList","op":"vault_secret_names_list","method":"GET","path":"/api/v1/vault/{mount}/metadata/{path...}","fixed_query":{"list":"true"},"params":[{"name":"mount","in":"path","required":true},{"name":"path","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentAccountsAllowedUsersSet","op":"agent_accounts_allowed_users_set","method":"PUT","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}/allowed-users","params":[{"name":"orgID","in":"path","from":"org"},{"name":"accountID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"agentAccountsBindingsCreate","op":"agent_accounts_bindings_create","method":"POST","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}/bindings","params":[{"name":"orgID","in":"path","from":"org"},{"name":"accountID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"agentAccountsBindingsDelete","op":"agent_accounts_bindings_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}/bindings/{bindingID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"accountID","in":"path","required":true},{"name":"bindingID","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"agentAccountsBindingsList","op":"agent_accounts_bindings_list","method":"GET","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}/bindings","params":[{"name":"orgID","in":"path","from":"org"},{"name":"accountID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentAccountsCreate","op":"agent_accounts_create","method":"POST","path":"/api/v1/orgs/{orgID}/agent-accounts","params":[{"name":"orgID","in":"path","from":"org"},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"agentAccountsDelete","op":"agent_accounts_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"accountID","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"agentAccountsGet","op":"agent_accounts_get","method":"GET","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"accountID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentAccountsList","op":"agent_accounts_list","method":"GET","path":"/api/v1/orgs/{orgID}/agent-accounts","params":[{"name":"orgID","in":"path","from":"org"},{"name":"include_deleted","in":"query"},{"name":"scope","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentAccountsOwnerSet","op":"agent_accounts_owner_set","method":"PUT","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}/owner","params":[{"name":"orgID","in":"path","from":"org"},{"name":"accountID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"agentAccountsUpdate","op":"agent_accounts_update","method":"PATCH","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"accountID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"agentAccountsUsageGetAll","op":"agent_accounts_usage_get_all","method":"GET","path":"/api/v1/orgs/{orgID}/agent-accounts/usage","params":[{"name":"orgID","in":"path","from":"org"},{"name":"days","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentAccountsUsageGetByAccountId","op":"agent_accounts_usage_get_by_account_id","method":"GET","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}/usage","params":[{"name":"orgID","in":"path","from":"org"},{"name":"accountID","in":"path","required":true},{"name":"days","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentAccountsWorkspacesList","op":"agent_accounts_workspaces_list","method":"GET","path":"/api/v1/orgs/{orgID}/agent-accounts/workspaces","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentConfigGet","op":"workspaces_agent_config_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/agent/config","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"name","in":"query"},{"name":"type","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentConfigSet","op":"workspaces_agent_config_set","method":"PUT","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/agent/config","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"agentGet","op":"workspaces_agent_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/agent","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentLeadGrantsList","op":"agent_lead_grants_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads","params":[{"name":"orgID","in":"path","from":"org"},{"name":"state","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentLeadTaskDispatch","op":"agent_lead_task_dispatch","method":"POST","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks","params":[{"name":"orgID","in":"path","from":"org"},{"name":"grantID","in":"path","required":true},{"name":"access","in":"body"},{"name":"account_id","in":"body"},{"name":"brief","in":"body","required":true},{"name":"budget_micros","in":"body"},{"name":"connection_id","in":"body"},{"name":"credential_source","in":"body"},{"name":"cwd","in":"body"},{"name":"engine","in":"body"},{"name":"governance_mode","in":"body"},{"name":"lease_id","in":"body"},{"name":"max_runtime_seconds","in":"body"},{"name":"mode","in":"body"},{"name":"pool_id","in":"body"},{"name":"ref","in":"body"},{"name":"repository","in":"body"},{"name":"target","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"agentLeadTaskReport","op":"agent_lead_task_report","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks/{leadTaskID}/report","params":[{"name":"orgID","in":"path","from":"org"},{"name":"grantID","in":"path","required":true},{"name":"leadTaskID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentLeadTaskStop","op":"agent_lead_task_stop","method":"POST","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks/{leadTaskID}/stop","params":[{"name":"orgID","in":"path","from":"org"},{"name":"grantID","in":"path","required":true},{"name":"leadTaskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"agentLeadTasksList","op":"agent_lead_tasks_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks","params":[{"name":"orgID","in":"path","from":"org"},{"name":"grantID","in":"path","required":true},{"name":"limit","in":"query"},{"name":"state","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentLogsList","op":"workspaces_agent_logs_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/agent/logs","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentTaskCancel","op":"agent_task_cancel","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/cancel","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"agentTaskDiff","op":"agent_task_diff","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/diff","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentTaskGet","op":"agent_task_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentTaskLog","op":"agent_task_log","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/log","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"limit","in":"query"},{"name":"offset","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentTaskOpenBranch","op":"agent_task_open_branch","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/branch","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"agentTaskStart","op":"agent_task_start","method":"POST","path":"/api/v1/orgs/{orgID}/build/tasks","params":[{"name":"orgID","in":"path","from":"org"},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"agentTasksList","op":"agent_tasks_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/tasks","params":[{"name":"orgID","in":"path","from":"org"},{"name":"cursor","in":"query"},{"name":"engine","in":"query"},{"name":"limit","in":"query"},{"name":"pool_id","in":"query"},{"name":"scope","in":"query"},{"name":"since","in":"query"},{"name":"state","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"agentWorkersList","op":"agent_workers_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/workers","params":[{"name":"orgID","in":"path","from":"org"},{"name":"lead_grant_id","in":"query"},{"name":"scope","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"appsList","op":"workspaces_apps_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/apps","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"appsShareUpdate","op":"workspaces_apps_share_update","method":"PATCH","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/apps/{slug}/share","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"slug","in":"path","required":true},{"name":"share_level","in":"body","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"backupCapability","op":"workspace_backup_capability","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backup-capability","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"backupCreate","op":"workspace_backup_create","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backups","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"type","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"backupDelete","op":"workspace_backup_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/backups/{backupID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"backupID","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"backupGet","op":"workspace_backup_get","method":"GET","path":"/api/v1/orgs/{orgID}/backups/{backupID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"backupID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"backupRestore","op":"workspace_backup_restore","method":"POST","path":"/api/v1/orgs/{orgID}/backups/{backupID}/restore","params":[{"name":"orgID","in":"path","from":"org"},{"name":"backupID","in":"path","required":true},{"name":"workspace_id","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"backupScheduleCreate","op":"workspace_backup_schedule_create","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backup-schedule","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"frequency","in":"body","required":true},{"name":"retention_policy","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"backupScheduleGet","op":"workspace_backup_schedule_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backup-schedule","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"backupSchedulesDelete","op":"backup_schedules_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/backup-schedules/{id}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"backupSchedulesSet","op":"backup_schedules_set","method":"PUT","path":"/api/v1/orgs/{orgID}/backup-schedules/{id}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"backupStatsList","op":"workspaces_backup_stats_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backup-stats","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"backupVerify","op":"workspace_backup_verify","method":"POST","path":"/api/v1/orgs/{orgID}/backups/{backupID}/verify","params":[{"name":"orgID","in":"path","from":"org"},{"name":"backupID","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"backupsList","op":"workspace_backups_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backups","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"backupsRestorePoints","op":"backups_restore_points","method":"POST","path":"/api/v1/orgs/{orgID}/backups/{backupID}/restore-points","params":[{"name":"orgID","in":"path","from":"org"},{"name":"backupID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"backupsVerifyAll","op":"workspaces_backups_verify_all","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backups/verify-all","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildDevicePoliciesList","op":"build_device_policies_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/device-policies","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildDevicePoliciesSet","op":"build_device_policies_set","method":"PUT","path":"/api/v1/orgs/{orgID}/build/device-policies/{class}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"class","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildDevicesList","op":"build_devices_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/devices","params":[{"name":"orgID","in":"path","from":"org"},{"name":"class","in":"query"},{"name":"host_id","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildEngineProfilesEgressSet","op":"build_engine_profiles_egress_set","method":"PUT","path":"/api/v1/orgs/{orgID}/build/engine-profiles/{engine}/egress","params":[{"name":"orgID","in":"path","from":"org"},{"name":"engine","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildEngineProfilesList","op":"build_engine_profiles_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/engine-profiles","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildGovernanceGet","op":"build_governance_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/governance","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildGovernanceSet","op":"build_governance_set","method":"PUT","path":"/api/v1/orgs/{orgID}/build/governance","params":[{"name":"orgID","in":"path","from":"org"},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLabHostsDevicesList","op":"build_lab_hosts_devices_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/lab-hosts/{hostID}/devices","params":[{"name":"orgID","in":"path","from":"org"},{"name":"hostID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLabHostsEnrolmentTokensCreate","op":"build_lab_hosts_enrolment_tokens_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/lab-hosts/enrolment-tokens","params":[{"name":"orgID","in":"path","from":"org"},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLabHostsEnrolmentTokensDelete","op":"build_lab_hosts_enrolment_tokens_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/build/lab-hosts/enrolment-tokens/{tokenID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"tokenID","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"buildLabHostsEnrolmentTokensList","op":"build_lab_hosts_enrolment_tokens_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/lab-hosts/enrolment-tokens","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLabHostsGet","op":"build_lab_hosts_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/lab-hosts/{hostID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"hostID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLabHostsList","op":"build_lab_hosts_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/lab-hosts","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLabHostsReleaseClaims","op":"build_lab_hosts_release_claims","method":"POST","path":"/api/v1/orgs/{orgID}/build/lab-hosts/{hostID}/release-claims","params":[{"name":"orgID","in":"path","from":"org"},{"name":"hostID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLabHostsRevoke","op":"build_lab_hosts_revoke","method":"POST","path":"/api/v1/orgs/{orgID}/build/lab-hosts/{hostID}/revoke","params":[{"name":"orgID","in":"path","from":"org"},{"name":"hostID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"buildLabHostsUpdate","op":"build_lab_hosts_update","method":"PATCH","path":"/api/v1/orgs/{orgID}/build/lab-hosts/{hostID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"hostID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeadsGet","op":"build_leads_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"grantID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeadsTasksGet","op":"build_leads_tasks_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks/{leadTaskID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"grantID","in":"path","required":true},{"name":"leadTaskID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeadsTasksLogGet","op":"build_leads_tasks_log_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks/{leadTaskID}/log","params":[{"name":"orgID","in":"path","from":"org"},{"name":"grantID","in":"path","required":true},{"name":"leadTaskID","in":"path","required":true},{"name":"limit","in":"query"},{"name":"offset","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeadsTasksMove","op":"build_leads_tasks_move","method":"POST","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks/{leadTaskID}/move","params":[{"name":"orgID","in":"path","from":"org"},{"name":"grantID","in":"path","required":true},{"name":"leadTaskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeadsTasksRetry","op":"build_leads_tasks_retry","method":"POST","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks/{leadTaskID}/retry","params":[{"name":"orgID","in":"path","from":"org"},{"name":"grantID","in":"path","required":true},{"name":"leadTaskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeadsUsageGet","op":"build_leads_usage_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/usage","params":[{"name":"orgID","in":"path","from":"org"},{"name":"grantID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeadsWorkersList","op":"build_leads_workers_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/workers","params":[{"name":"orgID","in":"path","from":"org"},{"name":"grantID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeaseCreate","op":"build_lease_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}/leases","params":[{"name":"orgID","in":"path","from":"org"},{"name":"poolID","in":"path","required":true},{"name":"devices","in":"body"},{"name":"purpose","in":"body"},{"name":"repo","in":"body"},{"name":"size","in":"body"},{"name":"ttl_seconds","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeaseGet","op":"build_lease_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeaseRelease","op":"build_lease_release","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/release","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeaseRenew","op":"build_lease_renew","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/renew","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesArtifactsContentGet","op":"build_leases_artifacts_content_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/artifacts/{artifactID}/content","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"artifactID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesArtifactsCreate","op":"build_leases_artifacts_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/artifacts","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"name","in":"query"},{"name":"run_id","in":"query"},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesArtifactsDelete","op":"build_leases_artifacts_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/artifacts/{artifactID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"artifactID","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesArtifactsGet","op":"build_leases_artifacts_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/artifacts/{artifactID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"artifactID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesArtifactsList","op":"build_leases_artifacts_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/artifacts","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesCachesEntriesSet","op":"build_leases_caches_entries_set","method":"PUT","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/caches/{cacheName}/entries","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"cacheName","in":"path","required":true},{"name":"key","in":"query"},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesCachesList","op":"build_leases_caches_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/caches","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesCachesRestoreGet","op":"build_leases_caches_restore_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/caches/{cacheName}/restore","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"cacheName","in":"path","required":true},{"name":"key","in":"query"},{"name":"prefix","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesEngineSigninsCreate","op":"build_leases_engine_signins_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/engine-signins","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesEngineSigninsDelete","op":"build_leases_engine_signins_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/engine-signins/{signinID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"signinID","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesEngineSigninsGet","op":"build_leases_engine_signins_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/engine-signins/{signinID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"signinID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesKill","op":"build_leases_kill","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/kill","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesList","op":"build_leases_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases","params":[{"name":"orgID","in":"path","from":"org"},{"name":"limit","in":"query"},{"name":"scope","in":"query"},{"name":"state","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesRunsComplete","op":"build_leases_runs_complete","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/runs/{runID}/complete","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"runID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesRunsCreate","op":"build_leases_runs_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/runs","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesRunsGet","op":"build_leases_runs_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/runs/{runID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"runID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesRunsList","op":"build_leases_runs_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/runs","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesRunsLogGet","op":"build_leases_runs_log_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/runs/{runID}/log","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"runID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesRunsLogSet","op":"build_leases_runs_log_set","method":"PUT","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/runs/{runID}/log","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"runID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesSshCertificate","op":"build_leases_ssh_certificate","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/ssh/certificate","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesSshGet","op":"build_leases_ssh_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/ssh","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesSync","op":"build_leases_sync","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/sync","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesTasksChangesList","op":"build_leases_tasks_changes_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/changes","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesTasksCreate","op":"build_leases_tasks_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesTasksFileGet","op":"build_leases_tasks_file_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/file","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"path","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesTasksFilesList","op":"build_leases_tasks_files_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/files","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"path","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesTasksHandback","op":"build_leases_tasks_handback","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/handback","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesTasksKeepLease","op":"build_leases_tasks_keep_lease","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/keep-lease","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLeasesTasksList","op":"build_leases_tasks_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesTasksLiveDiffGet","op":"build_leases_tasks_live_diff_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/live/diff","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesTasksLiveEventsList","op":"build_leases_tasks_live_events_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/live/events","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"after","in":"query"},{"name":"limit","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesTasksLiveGet","op":"build_leases_tasks_live_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/live","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"after","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildLeasesTasksTakeover","op":"build_leases_tasks_takeover","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/takeover","params":[{"name":"orgID","in":"path","from":"org"},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildLoginWipesList","op":"build_login_wipes_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/login-wipes","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildPoolsCachesDelete","op":"build_pools_caches_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}/caches/{cacheName}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"poolID","in":"path","required":true},{"name":"cacheName","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"buildPoolsCachesList","op":"build_pools_caches_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}/caches","params":[{"name":"orgID","in":"path","from":"org"},{"name":"poolID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildPoolsCreate","op":"build_pools_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/pools","params":[{"name":"orgID","in":"path","from":"org"},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildPoolsDelete","op":"build_pools_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"poolID","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"buildPoolsEnginesList","op":"build_pools_engines_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}/engines","params":[{"name":"orgID","in":"path","from":"org"},{"name":"poolID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildPoolsGet","op":"build_pools_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"poolID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildPoolsList","op":"build_pools_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/pools","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildPoolsUpdate","op":"build_pools_update","method":"PATCH","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"poolID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildQuotasList","op":"build_quotas_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/quotas","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildTaskCostsList","op":"build_task_costs_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/task-costs","params":[{"name":"orgID","in":"path","from":"org"},{"name":"scope","in":"query"},{"name":"since","in":"query"},{"name":"until","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildTaskCredentialsDelete","op":"build_task_credentials_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/build/task-credentials/{vendor}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"vendor","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"buildTaskCredentialsList","op":"build_task_credentials_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/task-credentials","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildTaskCredentialsSet","op":"build_task_credentials_set","method":"PUT","path":"/api/v1/orgs/{orgID}/build/task-credentials/{vendor}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"vendor","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"buildTaskEnginesList","op":"build_task_engines_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/task-engines","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildUsageGet","op":"build_usage_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/usage","params":[{"name":"orgID","in":"path","from":"org"},{"name":"scope","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildsGet","op":"workspaces_builds_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/builds/{buildID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"buildID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildsList","op":"workspace_builds_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/builds","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"limit","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"buildsLogsList","op":"workspaces_builds_logs_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/builds/{buildID}/logs","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"buildID","in":"path","required":true},{"name":"after","in":"query"},{"name":"limit","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"create","op":"workspace_create","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces","params":[{"name":"orgID","in":"path","from":"org"},{"name":"autostart","in":"body"},{"name":"autostart_schedule","in":"body"},{"name":"idle_timeout_seconds","in":"body"},{"name":"name","in":"body","required":true},{"name":"parameters","in":"body"},{"name":"template_id","in":"body","required":true},{"name":"template_version_id","in":"body"},{"name":"ttl_seconds","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"delete","op":"workspace_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"exec","op":"workspace_exec","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/exec","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"command","in":"body","required":true},{"name":"env","in":"body"},{"name":"stdin","in":"body"},{"name":"timeout_sec","in":"body"},{"name":"workdir","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"get","op":"workspace_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"gitCredentialsDelete","op":"workspaces_git_credentials_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/git-credentials/{host}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"host","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"gitCredentialsList","op":"workspaces_git_credentials_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/git-credentials","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"gitCredentialsSet","op":"workspaces_git_credentials_set","method":"PUT","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/git-credentials/{host}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"host","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"guest","op":"workspaces_guest","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/guest","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"guestDelete","op":"workspaces_guest_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/guest","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"mutates":true,"confirm":true,"regional":true}, +{"ns":"workspaces","fn":"invitationsList","op":"workspaces_invitations_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/invitations","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"invite","op":"workspaces_invite","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/invite","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"lifecyclePolicyGet","op":"workspaces_lifecycle_policy_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/lifecycle-policy","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"lifecyclePolicySet","op":"workspaces_lifecycle_policy_set","method":"PUT","path":"/api/v1/orgs/{orgID}/workspaces/lifecycle-policy","params":[{"name":"orgID","in":"path","from":"org"},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"list","op":"workspace_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces","params":[{"name":"orgID","in":"path","from":"org"},{"name":"all","in":"query"},{"name":"cursor","in":"query"},{"name":"limit","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"metricsDashboardGet","op":"workspaces_metrics_dashboard_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/metrics/dashboard","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"metricsDefinitionsList","op":"workspaces_metrics_definitions_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/metrics/definitions","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"metricsLatestGet","op":"workspaces_metrics_latest_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/metrics/latest","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"metricsList","op":"workspaces_metrics_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/metrics","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"openGet","op":"workspaces_open_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/open","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"ide","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"permissionsList","op":"workspaces_permissions_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/permissions","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"policyGet","op":"workspaces_policy_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/policy","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"policySet","op":"workspaces_policy_set","method":"PUT","path":"/api/v1/orgs/{orgID}/workspaces/policy","params":[{"name":"orgID","in":"path","from":"org"},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"rebuild","op":"workspace_rebuild","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/rebuild","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"parameters","in":"body"},{"name":"template_version_id","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"restorePointsList","op":"workspaces_restore_points_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/restore-points","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"share","op":"workspaces_share","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/share","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"sharesList","op":"workspaces_shares_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/shares","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"sshCertificate","op":"workspaces_ssh_certificate","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/ssh/certificate","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"sshGet","op":"workspaces_ssh_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/ssh","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"sshHostCaGet","op":"workspaces_ssh_host_ca_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/ssh-host-ca","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"start","op":"workspace_start","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/start","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"stop","op":"workspace_stop","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/stop","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"templateLaunchOptions","op":"workspace_template_launch_options","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/launch","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"version","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"templatesAccessGet","op":"templates_access_get","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/access","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"templatesBuiltinsList","op":"templates_builtins_list","method":"GET","path":"/api/v1/orgs/{orgID}/templates/builtins","params":[{"name":"orgID","in":"path","from":"org"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"templatesGet","op":"templates_get","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"templatesList","op":"workspace_templates_list","method":"GET","path":"/api/v1/orgs/{orgID}/templates","params":[{"name":"orgID","in":"path","from":"org"},{"name":"cursor","in":"query"},{"name":"include_deleted","in":"query"},{"name":"limit","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"templatesPermissionsList","op":"templates_permissions_list","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/permissions","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"templatesStatsList","op":"templates_stats_list","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/stats","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"templatesVersionsGet","op":"templates_versions_get","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/versions/{vid}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"vid","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"templatesVersionsList","op":"templates_versions_list","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/versions","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"include_archived","in":"query"},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"templatesVersionsParametersList","op":"templates_versions_parameters_list","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/versions/{vid}/parameters","params":[{"name":"orgID","in":"path","from":"org"},{"name":"id","in":"path","required":true},{"name":"vid","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"terminalAvailabilityGet","op":"workspaces_terminal_availability_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/terminal/availability","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"terminalTickets","op":"workspaces_terminal_tickets","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/terminal/tickets","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"tokens","op":"workspaces_tokens","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/tokens","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"mutates":true,"regional":true}, +{"ns":"workspaces","fn":"tokensList","op":"workspaces_tokens_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/tokens","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"regional":true}, +{"ns":"workspaces","fn":"update","op":"workspace_update","method":"PATCH","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}","params":[{"name":"orgID","in":"path","from":"org"},{"name":"wsID","in":"path","required":true},{"name":"autostart","in":"body"},{"name":"autostart_schedule","in":"body"},{"name":"idle_timeout_seconds","in":"body"},{"name":"ttl_seconds","in":"body"},{"name":"region","in":"region"}],"mutates":true,"regional":true} +]''') diff --git a/src/sandscale/_builtin.py b/src/sandscale/_builtin.py new file mode 100644 index 0000000..37b328a --- /dev/null +++ b/src/sandscale/_builtin.py @@ -0,0 +1,20 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""The built-in sandbox templates every Sandscale organization can start. + +``base`` is the default image: Python 3 with pip, Node.js with npm, git, curl, a C compiler, jq and +unzip. ``python`` and ``node`` are that same image; ``go`` adds the Go toolchain; ``go_postgres`` is +``go`` plus PostgreSQL 17 running on 127.0.0.1:5432 at boot (``TEST_DATABASE_URL`` set; a test database, +not durable); ``minimal`` is bare Alpine (a shell and busybox). Use them as ``sandscale.sandboxes.create(template=BUILTIN_TEMPLATES["go"])``. +""" + +from __future__ import annotations + +BUILTIN_TEMPLATES = { + "base": "builtin:base", + "python": "builtin:python", + "node": "builtin:node", + "go": "builtin:go", + "go_postgres": "builtin:go-postgres", + "minimal": "builtin:minimal", +} diff --git a/src/sandscale/_call.py b/src/sandscale/_call.py new file mode 100644 index 0000000..f996d94 --- /dev/null +++ b/src/sandscale/_call.py @@ -0,0 +1,80 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""Run any operation of the Sandscale API by its catalogue name: ``Sandscale.call``.""" + +from __future__ import annotations + +from typing import Any, Dict, List, Mapping, Optional + +from ._operations_gen import OPERATIONS +from ._transport import Transport, seg +from .errors import SandscaleError + +_BY_NAME: Dict[str, Dict[str, Any]] = {o["name"]: o for o in OPERATIONS} + + +def operations() -> List[Dict[str, Any]]: + """The operations ``call`` can run: every JSON operation of the Sandscale API.""" + return list(OPERATIONS) + + +def call( + t: Transport, + operation: str, + args: Optional[Mapping[str, Any]] = None, + *, + region: Optional[str] = None, + idempotency_key: Optional[str] = None, +) -> Any: + """Runs one operation by its catalogue name. The request is built from the generated operation table; the + server decides everything else, so a call the plan or the permissions do not allow is refused with the + server's own code.""" + args = dict(args or {}) + op = _BY_NAME.get(operation) + if op is None: + raise SandscaleError(400, "unknown_operation", f"there is no operation {operation!r}") + known = {p["name"] for p in op["params"]} + unknown = sorted(k for k in args if k not in known) + if unknown: + raise SandscaleError(400, "invalid_arguments", f"{operation} has no argument {', '.join(unknown)}") + path = op["path"] + query: Dict[str, Any] = dict(op.get("fixed_query") or {}) + body: Optional[Dict[str, Any]] = None + whole: Any = None + for p in op["params"]: + v = args.get(p["name"]) + if p.get("org"): + v = t.require_org() + if v is None: + if p.get("required") and p["in"] != "region": + raise SandscaleError(400, "invalid_arguments", f"{p['name']} is required") + continue + wire = p.get("wire") or p["name"] + kind = p["in"] + if kind == "path": + rest = "{" + p["name"] + "...}" in path + piece = "/".join(seg(s) for s in str(v).strip("/").split("/")) if rest else seg(str(v)) + path = path.replace("{" + p["name"] + "...}", piece).replace("{" + p["name"] + "}", piece) + elif kind == "query": + if isinstance(v, (dict, list)): + raise SandscaleError(400, "invalid_arguments", f"{p['name']} must be a string, number or boolean") + query[wire] = v + elif kind == "query_all": + for k, qv in dict(v).items(): + if isinstance(qv, (dict, list)): + raise SandscaleError(400, "invalid_arguments", f"{p['name']}.{k} must be a string, number or boolean") + query[k] = qv + elif kind == "body": + body = body or {} + body[wire] = v + elif kind == "whole": + whole = v + elif kind == "region": + region = str(v) + if "{" in path: + raise SandscaleError(400, "invalid_arguments", f"{operation} needs all of its path arguments") + write = op["method"] not in ("GET", "HEAD") + payload = whole if whole is not None else body + if payload is None and write and op["method"] != "DELETE": + payload = {} + return t.request(op["method"], path, region=region, query=query, json_body=payload, idempotency_key=idempotency_key) diff --git a/src/sandscale/_capabilities.py b/src/sandscale/_capabilities.py new file mode 100644 index 0000000..7f6d937 --- /dev/null +++ b/src/sandscale/_capabilities.py @@ -0,0 +1,177 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""What the caller can do here now: ``Sandscale.capabilities()``.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional + +from ._transport import Transport +from .errors import SandscaleError + +Raw = Dict[str, Any] + + +@dataclass +class Plan: + code: str + name: Optional[str] = None + upgradable: Optional[bool] = None + + +@dataclass +class Limits: + max_vcpu_per_box: Optional[int] = None + max_mem_mb: Optional[int] = None + max_concurrent_boxes: Optional[int] = None + running_boxes: Optional[int] = None + max_ttl_seconds: Optional[int] = None + default_ttl_seconds: Optional[int] = None + default_vcpu: Optional[int] = None + default_mem_mb: Optional[int] = None + #: The network modes ``create`` accepts now. + network: List[str] = field(default_factory=list) + #: Modes that exist but are not available, with the reason. + network_unavailable: Dict[str, str] = field(default_factory=dict) + + +@dataclass +class TemplateOption: + id: str + startable: bool + contains: Optional[str] = None + reason: Optional[str] = None + + +@dataclass +class RegionOption: + id: str + status: Optional[str] = None + + +@dataclass +class UsageBalance: + """The vCPU-hour balance. ``resets_at`` is the end of the window the server counts in (never computed + here). ``available`` is False, with ``code`` and ``reason``, when the caller may not read it.""" + + available: bool + vcpu_hours_used: Optional[float] = None + #: A number, or ``"unlimited"`` when the plan has no cap. + vcpu_hours_included: Any = None + vcpu_hours_remaining: Optional[float] = None + resets_at: Optional[str] = None + window_start: Optional[str] = None + month: Optional[str] = None + daily_cap_reached: bool = False + retry_at: Optional[str] = None + code: Optional[str] = None + reason: Optional[str] = None + + +@dataclass +class Capabilities: + plan: Plan + limits: Limits + templates: List[TemplateOption] + features: Dict[str, bool] + regions: List[RegionOption] + usage: UsageBalance + #: Set when no sandbox can start now whatever is chosen: ``{"code": ..., "reason": ...}``. + cannot_start: Optional[Dict[str, str]] = None + + +def _num(v: Any) -> Optional[int]: + if isinstance(v, bool): + return None + if isinstance(v, int): + return v + return int(v) if isinstance(v, float) and v.is_integer() else None + + +def _str(v: Any) -> Optional[str]: + return v if isinstance(v, str) and v != "" else None + + +def _obj(v: Any) -> Raw: + return v if isinstance(v, dict) else {} + + +def _list(v: Any) -> List[Raw]: + return [e for e in v if isinstance(e, dict)] if isinstance(v, list) else [] + + +def capabilities(t: Transport, region: Optional[str] = None) -> Capabilities: + """Reads launch options, quota, usage and regions and returns one answer. Usage needs billing:read and the + region list may be down: each is reported as missing instead of failing the call.""" + opts = t.request("GET", "/api/v1/sandbox/launch-options", region=region) or {} + quota = t.request("GET", "/api/v1/sandbox/quota", region=region) or {} + try: + usage = _usage(t.request("GET", "/api/v1/sandscale/usage", region=region) or {}) + except SandscaleError as e: + usage = UsageBalance(available=False, code=e.code or "unavailable", reason=e.message or "the usage could not be read") + try: + regions_raw = t.request("GET", "/api/v1/regions", region=region) or {} + except SandscaleError: + regions_raw = {} + size, ttl = _obj(opts.get("size")), _obj(opts.get("ttl")) + limits = Limits( + max_vcpu_per_box=_num(size.get("max_cpu")), + max_mem_mb=_num(size.get("max_mem_mb")), + max_concurrent_boxes=_num(quota.get("max_instances")), + running_boxes=_num(quota.get("active_instances")), + max_ttl_seconds=_num(ttl.get("max_seconds")), + default_ttl_seconds=_num(ttl.get("default_seconds")), + default_vcpu=_num(size.get("default_cpu")), + default_mem_mb=_num(size.get("default_mem_mb")), + ) + for o in _list(_obj(opts.get("network")).get("options")): + value = _str(o.get("value")) + if not value: + continue + if o.get("available") is True: + limits.network.append(value) + else: + limits.network_unavailable[value] = _str(o.get("reason")) or "not available" + out = Capabilities( + plan=Plan(code=_str(quota.get("plan")) or "", name=_str(quota.get("plan_name")), + upgradable=quota.get("plan_upgradable") if isinstance(quota.get("plan_upgradable"), bool) else None), + limits=limits, + templates=[ + TemplateOption(id=str(t_.get("id") or ""), startable=t_.get("startable") is True, + contains=_str(t_.get("description")), reason=_str(t_.get("reason"))) + for t_ in _list(opts.get("templates")) + ], + features={k: _obj(v).get("available") is True for k, v in _obj(opts.get("features")).items()}, + regions=[ + RegionOption(id=_str(r.get("id")) or _str(r.get("region")) or _str(r.get("name")) or "", status=_str(r.get("status"))) + for r in _list(_obj(regions_raw).get("regions")) + ], + usage=usage, + ) + out.regions = [r for r in out.regions if r.id] + if opts.get("can_start") is False: + r = _obj(opts.get("refusal")) + out.cannot_start = {"code": _str(r.get("code")) or "", "reason": _str(r.get("message")) or ""} + return out + + +def _usage(u: Raw) -> UsageBalance: + included = _num(_obj(u.get("limits")).get("vcpu_seconds")) + used = _num(u.get("vcpu_seconds_used")) or 0 + left = _num(u.get("vcpu_seconds_left")) + period, daily = _obj(u.get("period")), _obj(u.get("daily")) + capped = included is not None and included >= 0 + out = UsageBalance( + available=True, + vcpu_hours_used=used / 3600, + vcpu_hours_included=included / 3600 if included is not None and included >= 0 else "unlimited", + vcpu_hours_remaining=left / 3600 if capped and left is not None and left >= 0 else None, + resets_at=_str(period.get("resets_at")), + window_start=_str(period.get("starts_at")), + month=_str(u.get("month")), + ) + if daily.get("at_cap") is True: + out.daily_cap_reached = True + out.retry_at = _str(daily.get("retry_at")) + return out diff --git a/src/sandscale/_code.py b/src/sandscale/_code.py new file mode 100644 index 0000000..38e393a --- /dev/null +++ b/src/sandscale/_code.py @@ -0,0 +1,340 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""Code mode: ``Sandscale.execute``, ``Sandscale.tasks``, ``Sandscale.search`` and +``Sandscale.code_policy`` (docs/architecture/sandscale-code-mode-contract.md). + +A script runs on the server against the caller's typed API (``sandscale..(args)``) +as the caller; the SDK only sends it and reads the task back. The server decides every call the +script makes, the operations that wait for a person's approval and every limit.""" + +from __future__ import annotations + +import time +from dataclasses import dataclass, field +from datetime import datetime +from typing import Any, Dict, List, Optional, Sequence + +from ._transport import Transport, seg +from .errors import SandscaleError, _when + +Raw = Dict[str, Any] + +#: The most a request may ask the server to hold an answer (the contract's ``wait_seconds``). +MAX_WAIT_SECONDS = 30 + +#: A task in one of these states will not change any more. +FINAL_STATES = ("succeeded", "failed") + + +@dataclass +class ConsoleLine: + level: str + text: str + + +@dataclass +class ApiErrorInfo: + """The API refusal that ended a script (``error.api_error``): the same code, message and next + step a direct call would have raised.""" + + code: str + message: str + status: Optional[int] = None + next: Any = None + retry_after_seconds: Optional[float] = None + + +@dataclass +class TaskError: + """Why a task failed: ``script_error``, ``syntax_error``, ``time_limit``, ``cpu_limit``, + ``memory_limit``, ``journal_divergence``, ``approval_rejected``, ``approval_expired``, + ``worker_lost`` or ``worker_failed``, with the script position when there is one.""" + + code: str + message: str + line: Optional[int] = None + column: Optional[int] = None + api_error: Optional[ApiErrorInfo] = None + + +@dataclass +class PendingApproval: + """The call a task waits on a person to approve.""" + + request_id: str + operation: Optional[str] = None + seq: Optional[int] = None + + +@dataclass +class Task: + """One execute run. ``state`` is ``running``, ``awaiting_approval``, ``succeeded`` or ``failed``.""" + + task_id: str + state: str + run_id: Optional[str] = None + segments: Optional[int] = None + script_sha256: Optional[str] = None + #: The script's return value (any JSON), when it succeeded. + result: Any = None + console: List[ConsoleLine] = field(default_factory=list) + #: True when the server cut the console or the result to its size limit. + truncated: bool = False + error: Optional[TaskError] = None + pending_approval: Optional[PendingApproval] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + finished_at: Optional[datetime] = None + #: The answer as the server sent it. + raw: Raw = field(default_factory=dict, repr=False) + + @property + def done(self) -> bool: + return self.state in FINAL_STATES + + @property + def succeeded(self) -> bool: + return self.state == "succeeded" + + @classmethod + def from_raw(cls, raw: Raw) -> "Task": + err = raw.get("error") if isinstance(raw.get("error"), dict) else None + pending = raw.get("pending_approval") if isinstance(raw.get("pending_approval"), dict) else None + return cls( + task_id=str(raw.get("task_id") or ""), + state=str(raw.get("state") or ""), + run_id=raw.get("run_id"), + segments=_int(raw.get("segments")), + script_sha256=raw.get("script_sha256"), + result=raw.get("result"), + console=_console(raw.get("console")), + truncated=bool(raw.get("truncated")), + error=_task_error(err) if err is not None else None, + pending_approval=( + PendingApproval( + request_id=str(pending.get("request_id") or ""), + operation=pending.get("operation"), + seq=_int(pending.get("seq")), + ) + if pending is not None + else None + ), + created_at=_when(raw.get("created_at")), + updated_at=_when(raw.get("updated_at")), + finished_at=_when(raw.get("finished_at")), + raw=raw, + ) + + +@dataclass +class SearchResult: + """What a search script returned, with its console.""" + + result: Any = None + console: List[ConsoleLine] = field(default_factory=list) + truncated: bool = False + + +@dataclass +class CodePolicy: + """The operations (or the classes ``destructive`` and ``writes``) a script must ask a person + about before it calls them.""" + + ask_first: List[str] = field(default_factory=list) + + +class TaskFailedError(SandscaleError): + """A code mode task ended ``failed``. ``code`` is the task's error code; ``task`` is the whole + task (console included) and ``details`` the task's ``error`` object, ``api_error`` included.""" + + def __init__(self, task: Task) -> None: + err = task.error + super().__init__( + 0, + err.code if err else "task_failed", + err.message if err else f"task {task.task_id} failed", + details=task.raw.get("error"), + ) + self.task = task + + +class TaskTimeoutError(SandscaleError): + """The task did not finish within the SDK's ``timeout``. It keeps running on the server; + ``task`` is the last state read, and ``Sandscale.tasks.wait(task.task_id)`` picks it up.""" + + def __init__(self, task: Task, timeout: float) -> None: + super().__init__(0, "task_timeout", f"task {task.task_id} is still {task.state} after {timeout:g} s") + self.task = task + + +def _int(value: Any) -> Optional[int]: + return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None + + +def _console(value: Any) -> List[ConsoleLine]: + if not isinstance(value, list): + return [] + return [ + ConsoleLine(level=str(c.get("level") or "log"), text=str(c.get("text") or "")) + for c in value + if isinstance(c, dict) + ] + + +def _task_error(err: Raw) -> TaskError: + api = err.get("api_error") if isinstance(err.get("api_error"), dict) else None + retry = api.get("retry_after_seconds") if api is not None else None + return TaskError( + code=str(err.get("code") or "task_failed"), + message=str(err.get("message") or ""), + line=_int(err.get("line")), + column=_int(err.get("column")), + api_error=( + ApiErrorInfo( + code=str(api.get("code") or ""), + message=str(api.get("message") or ""), + status=_int(api.get("status")), + next=api.get("next"), + retry_after_seconds=float(retry) if isinstance(retry, (int, float)) and not isinstance(retry, bool) else None, + ) + if api is not None + else None + ), + ) + + +def _wait(value: float) -> int: + return max(0, min(MAX_WAIT_SECONDS, int(value))) + + +def _request_timeout(wait_seconds: int) -> Optional[float]: + """A held answer may take ``wait_seconds``: the request's own timeout leaves room for it.""" + return float(wait_seconds) + 30.0 if wait_seconds > 0 else None + + +class Tasks: + """``Sandscale.tasks``: read and wait for code mode tasks. Only the person who started a task + reads it; any other id is ``NotFoundError``.""" + + def __init__(self, transport: Transport) -> None: + self._t = transport + + def get(self, task_id: str, *, wait_seconds: float = 0) -> Task: + """The task. With ``wait_seconds`` (at most 30) the server holds the answer until the task + changes or the time passes. Reading a task whose approval a person gave resumes it.""" + wait = _wait(wait_seconds) + raw = self._t.request( + "GET", + f"/api/v1/sandbox/code/tasks/{seg(task_id)}", + query={"wait_seconds": wait} if wait else None, + timeout=_request_timeout(wait), + ) + return Task.from_raw(raw or {}) + + def wait( + self, + task_id: str, + *, + wait_seconds: float = MAX_WAIT_SECONDS, + poll_interval: float = 1.0, + timeout: Optional[float] = None, + wait_for_approval: bool = False, + raise_on_failure: bool = True, + ) -> Task: + """Reads the task until it succeeded or failed. A task awaiting a person's approval is + returned as it is unless ``wait_for_approval``. Raises :class:`TaskFailedError` for a + failed task (unless ``raise_on_failure`` is False) and :class:`TaskTimeoutError` when + ``timeout`` seconds pass first.""" + return self._follow( + self.get(task_id), + wait_seconds=wait_seconds, + poll_interval=poll_interval, + timeout=timeout, + wait_for_approval=wait_for_approval, + raise_on_failure=raise_on_failure, + ) + + def _follow( + self, + task: Task, + *, + wait_seconds: float, + poll_interval: float, + timeout: Optional[float], + wait_for_approval: bool, + raise_on_failure: bool, + ) -> Task: + deadline = None if timeout is None else time.monotonic() + timeout + while not task.done: + if task.state == "awaiting_approval" and not wait_for_approval: + return task + wait = _wait(wait_seconds) + if deadline is not None: + left = deadline - time.monotonic() + if left <= 0: + raise TaskTimeoutError(task, float(timeout or 0)) + wait = min(wait, _wait(left)) + if poll_interval > 0: + self._t.sleep(poll_interval) + task = self.get(task.task_id, wait_seconds=wait) + if task.state == "failed" and raise_on_failure: + raise TaskFailedError(task) + return task + + +class CodePolicyService: + """``Sandscale.code_policy``: what a script must ask a person about first.""" + + def __init__(self, transport: Transport) -> None: + self._t = transport + + def get(self) -> CodePolicy: + raw = self._t.request("GET", "/api/v1/sandbox/code/policy") or {} + return CodePolicy(ask_first=[str(x) for x in raw.get("ask_first") or []]) + + def set(self, ask_first: Sequence[str]) -> CodePolicy: + """Replaces the list: operation names (``sandbox_terminate``) or the classes ``destructive`` + and ``writes``. Needs ``sandboxes:write``.""" + if isinstance(ask_first, str): + raise TypeError("ask_first is a list of operation names or classes, not one string") + raw = self._t.request("PUT", "/api/v1/sandbox/code/policy", json_body={"ask_first": list(ask_first)}) or {} + return CodePolicy(ask_first=[str(x) for x in raw.get("ask_first") or []]) + + +def execute( + transport: Transport, + tasks: Tasks, + code: str, + *, + wait_seconds: float = MAX_WAIT_SECONDS, + poll_interval: float = 1.0, + timeout: Optional[float] = None, + wait_for_approval: bool = False, + raise_on_failure: bool = True, + idempotency_key: Optional[str] = None, +) -> Task: + if not isinstance(code, str) or not code.strip(): + raise TypeError("code is the script's text") + wait = _wait(wait_seconds) + raw = transport.request( + "POST", + "/api/v1/sandbox/code/tasks", + json_body={"code": code, "wait_seconds": wait}, + timeout=_request_timeout(wait), + idempotency_key=idempotency_key, + ) + return tasks._follow( + Task.from_raw(raw or {}), + wait_seconds=wait_seconds, + poll_interval=poll_interval, + timeout=timeout, + wait_for_approval=wait_for_approval, + raise_on_failure=raise_on_failure, + ) + + +def search(transport: Transport, code: str) -> SearchResult: + if not isinstance(code, str) or not code.strip(): + raise TypeError("code is the script's text") + raw = transport.request("POST", "/api/v1/sandbox/code/search", json_body={"code": code}) or {} + return SearchResult(result=raw.get("result"), console=_console(raw.get("console")), truncated=bool(raw.get("truncated"))) diff --git a/src/sandscale/_compute.py b/src/sandscale/_compute.py index 3239c85..a23ea6f 100644 --- a/src/sandscale/_compute.py +++ b/src/sandscale/_compute.py @@ -46,7 +46,7 @@ def revoke(self, host_id: str, *, reason: Optional[str] = None, region: Optional class AgentCloud: - """Agent Cloud tasks: background coding-agent tasks, through Keystone's lead routes (never + """Agent Cloud tasks: background coding-agent tasks, through Sandscale's lead routes (never the device agent). These routes need a signed-in person's token; an API key is refused with 403 ``person_required``. ``grant_id`` defaults to ``current``, the caller's one active lead grant.""" diff --git a/src/sandscale/_operations_gen.py b/src/sandscale/_operations_gen.py new file mode 100644 index 0000000..b5b8fb1 --- /dev/null +++ b/src/sandscale/_operations_gen.py @@ -0,0 +1,355 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""Generated by go run ./cmd/toolcatalog-gen from the tool catalogue. Do not edit by hand. + +Every JSON operation of the Sandscale API and how to build its request, for Sandscale.call(operation, ...).""" + +import json +from typing import Any, Dict, List + +OPERATIONS: List[Dict[str, Any]] = json.loads(r'''[ + {"name":"my_api_keys_list","method":"GET","path":"/api/v1/account/api-keys","region":"global","params":[],"changes":false,"confirm":false}, + {"name":"my_api_key_delete","method":"DELETE","path":"/api/v1/account/api-keys/{id}","region":"global","params":[{"name":"id","in":"path","required":true}],"changes":true,"confirm":true}, + {"name":"entitlements_get","method":"GET","path":"/api/v1/account/entitlement","region":"plane","params":[],"changes":false,"confirm":false}, + {"name":"account_invitations_list","method":"GET","path":"/api/v1/account/invitations","region":"global","params":[],"changes":false,"confirm":false}, + {"name":"account_invitations_accept","method":"POST","path":"/api/v1/account/invitations/accept","region":"global","params":[{"name":"body","in":"whole"}],"changes":true,"confirm":false}, + {"name":"account_invitations_lookup","method":"POST","path":"/api/v1/account/invitations/lookup","region":"global","params":[{"name":"body","in":"whole"}],"changes":true,"confirm":false}, + {"name":"organizations_list","method":"GET","path":"/api/v1/account/organizations","region":"global","params":[],"changes":false,"confirm":false}, + {"name":"audit_events_list","method":"GET","path":"/api/v1/audit-logs","region":"regional","params":[{"name":"action","in":"query"},{"name":"action_prefix","in":"query"},{"name":"from","in":"query"},{"name":"include_read_only","in":"query"},{"name":"limit","in":"query"},{"name":"offset","in":"query"},{"name":"outcome","in":"query"},{"name":"project_id","in":"query"},{"name":"resource_type","in":"query"},{"name":"to","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_chain_lanes_list","method":"GET","path":"/api/v1/audit-logs/chain-lanes","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_cold_segments_list","method":"GET","path":"/api/v1/audit-logs/cold-segments","region":"regional","params":[{"name":"organization_id","in":"query","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_endpoint_activity_get","method":"GET","path":"/api/v1/audit-logs/endpoint-activity","region":"regional","params":[{"name":"category","in":"query"},{"name":"device_id","in":"query"},{"name":"limit","in":"query"},{"name":"offset","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_exports_list","method":"GET","path":"/api/v1/audit-logs/exports","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_exports_get","method":"GET","path":"/api/v1/audit-logs/exports/{exportID}","region":"regional","params":[{"name":"exportID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_merkle_checkpoints_list","method":"GET","path":"/api/v1/audit-logs/merkle/checkpoints","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_merkle_checkpoints_verify_get","method":"GET","path":"/api/v1/audit-logs/merkle/checkpoints/{seq}/verify","region":"regional","params":[{"name":"seq","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_organization_get","method":"GET","path":"/api/v1/audit-logs/organization","region":"regional","params":[{"name":"account","in":"query"},{"name":"action","in":"query"},{"name":"action_prefix","in":"query"},{"name":"before","in":"query"},{"name":"include_read_only","in":"query"},{"name":"limit","in":"query"},{"name":"outcome","in":"query"},{"name":"resource_type","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_events_query","method":"GET","path":"/api/v1/audit-logs/query","region":"regional","params":[{"name":"from","in":"query"},{"name":"query","in":"query"},{"name":"to","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_retention_get","method":"GET","path":"/api/v1/audit-logs/retention","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_sessions_list","method":"GET","path":"/api/v1/audit-logs/sessions","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_sessions_replay_get","method":"GET","path":"/api/v1/audit-logs/sessions/{id}/replay","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_storage_stats_list","method":"GET","path":"/api/v1/audit-logs/storage-stats","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_tiering_get","method":"GET","path":"/api/v1/audit-logs/tiering","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_verifications_list","method":"GET","path":"/api/v1/audit-logs/verifications","region":"regional","params":[{"name":"limit","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_verifications_get","method":"GET","path":"/api/v1/audit-logs/verifications/{id}","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"audit_logs_verify_get","method":"GET","path":"/api/v1/audit-logs/verify","region":"regional","params":[{"name":"from","in":"query"},{"name":"to","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"invitations_accept","method":"POST","path":"/api/v1/invitations/{token}/accept","region":"regional","params":[{"name":"token","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"my_permissions","method":"GET","path":"/api/v1/me/permissions","region":"plane","params":[{"name":"node","in":"query"}],"changes":false,"confirm":false}, + {"name":"me_usage_get","method":"GET","path":"/api/v1/me/usage","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"org_api_keys_list","method":"GET","path":"/api/v1/organizations/{id}/api-keys","region":"global","params":[{"name":"id","in":"path","org":true}],"changes":false,"confirm":false}, + {"name":"org_api_keys_scope_report_get","method":"GET","path":"/api/v1/organizations/{id}/api-keys/scope-report","region":"global","params":[{"name":"id","in":"path","org":true}],"changes":false,"confirm":false}, + {"name":"org_api_keys_delete","method":"DELETE","path":"/api/v1/organizations/{id}/api-keys/{key_id}","region":"global","params":[{"name":"id","in":"path","org":true},{"name":"key_id","in":"path","required":true}],"changes":true,"confirm":true}, + {"name":"members_list","method":"GET","path":"/api/v1/organizations/{id}/members","region":"global","params":[{"name":"id","in":"path","org":true},{"name":"limit","in":"query"},{"name":"offset","in":"query"}],"changes":false,"confirm":false}, + {"name":"org_members_create","method":"POST","path":"/api/v1/organizations/{id}/members","region":"global","params":[{"name":"id","in":"path","org":true},{"name":"user_id","in":"body","required":true}],"changes":true,"confirm":false}, + {"name":"member_remove","method":"DELETE","path":"/api/v1/organizations/{id}/members/{user_id}","region":"global","params":[{"name":"id","in":"path","org":true},{"name":"user_id","in":"path","required":true}],"changes":true,"confirm":true}, + {"name":"agent_accounts_list","method":"GET","path":"/api/v1/orgs/{orgID}/agent-accounts","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"include_deleted","in":"query"},{"name":"scope","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_accounts_create","method":"POST","path":"/api/v1/orgs/{orgID}/agent-accounts","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"agent_accounts_usage_get_all","method":"GET","path":"/api/v1/orgs/{orgID}/agent-accounts/usage","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"days","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_accounts_workspaces_list","method":"GET","path":"/api/v1/orgs/{orgID}/agent-accounts/workspaces","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_accounts_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"accountID","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"agent_accounts_get","method":"GET","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"accountID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_accounts_update","method":"PATCH","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"accountID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"agent_accounts_allowed_users_set","method":"PUT","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}/allowed-users","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"accountID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"agent_accounts_bindings_list","method":"GET","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}/bindings","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"accountID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_accounts_bindings_create","method":"POST","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}/bindings","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"accountID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"agent_accounts_bindings_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}/bindings/{bindingID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"accountID","in":"path","required":true},{"name":"bindingID","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"agent_accounts_owner_set","method":"PUT","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}/owner","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"accountID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"agent_accounts_usage_get_by_account_id","method":"GET","path":"/api/v1/orgs/{orgID}/agent-accounts/{accountID}/usage","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"accountID","in":"path","required":true},{"name":"days","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"backup_schedules_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/backup-schedules/{id}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"backup_schedules_set","method":"PUT","path":"/api/v1/orgs/{orgID}/backup-schedules/{id}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspace_backup_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/backups/{backupID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"backupID","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"workspace_backup_get","method":"GET","path":"/api/v1/orgs/{orgID}/backups/{backupID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"backupID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_backup_restore","method":"POST","path":"/api/v1/orgs/{orgID}/backups/{backupID}/restore","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"backupID","in":"path","required":true},{"name":"workspace_id","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"backups_restore_points","method":"POST","path":"/api/v1/orgs/{orgID}/backups/{backupID}/restore-points","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"backupID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspace_backup_verify","method":"POST","path":"/api/v1/orgs/{orgID}/backups/{backupID}/verify","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"backupID","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"plan_get","method":"GET","path":"/api/v1/orgs/{orgID}/billing","region":"global","params":[{"name":"orgID","in":"path","org":true}],"changes":false,"confirm":false}, + {"name":"billing_payment_method_checkout_get","method":"GET","path":"/api/v1/orgs/{orgID}/billing/payment-method/checkout/{checkoutID}","region":"global","params":[{"name":"orgID","in":"path","org":true},{"name":"checkoutID","in":"path","required":true}],"changes":false,"confirm":false}, + {"name":"billing_profile_get","method":"GET","path":"/api/v1/orgs/{orgID}/billing/profile","region":"global","params":[{"name":"orgID","in":"path","org":true}],"changes":false,"confirm":false}, + {"name":"billing_standing_get","method":"GET","path":"/api/v1/orgs/{orgID}/billing/standing","region":"global","params":[{"name":"orgID","in":"path","org":true}],"changes":false,"confirm":false}, + {"name":"usage_get","method":"GET","path":"/api/v1/orgs/{orgID}/billing/usage","region":"global","params":[{"name":"orgID","in":"path","org":true},{"name":"month","in":"query"}],"changes":false,"confirm":false}, + {"name":"build_device_policies_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/device-policies","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_device_policies_set","method":"PUT","path":"/api/v1/orgs/{orgID}/build/device-policies/{class}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"class","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_devices_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/devices","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"class","in":"query"},{"name":"host_id","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_engine_profiles_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/engine-profiles","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_engine_profiles_egress_set","method":"PUT","path":"/api/v1/orgs/{orgID}/build/engine-profiles/{engine}/egress","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"engine","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_governance_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/governance","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_governance_set","method":"PUT","path":"/api/v1/orgs/{orgID}/build/governance","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_lab_hosts_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/lab-hosts","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_lab_hosts_enrolment_tokens_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/lab-hosts/enrolment-tokens","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_lab_hosts_enrolment_tokens_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/lab-hosts/enrolment-tokens","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_lab_hosts_enrolment_tokens_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/build/lab-hosts/enrolment-tokens/{tokenID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"tokenID","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"build_lab_hosts_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/lab-hosts/{hostID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"hostID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_lab_hosts_update","method":"PATCH","path":"/api/v1/orgs/{orgID}/build/lab-hosts/{hostID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"hostID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_lab_hosts_devices_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/lab-hosts/{hostID}/devices","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"hostID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_lab_hosts_release_claims","method":"POST","path":"/api/v1/orgs/{orgID}/build/lab-hosts/{hostID}/release-claims","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"hostID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_lab_hosts_revoke","method":"POST","path":"/api/v1/orgs/{orgID}/build/lab-hosts/{hostID}/revoke","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"hostID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"agent_lead_grants_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"state","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leads_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"grantID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_lead_tasks_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"grantID","in":"path","required":true},{"name":"limit","in":"query"},{"name":"state","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_lead_task_dispatch","method":"POST","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"grantID","in":"path","required":true},{"name":"access","in":"body"},{"name":"account_id","in":"body"},{"name":"brief","in":"body","required":true},{"name":"budget_micros","in":"body"},{"name":"connection_id","in":"body"},{"name":"credential_source","in":"body"},{"name":"cwd","in":"body"},{"name":"engine","in":"body"},{"name":"governance_mode","in":"body"},{"name":"lease_id","in":"body"},{"name":"max_runtime_seconds","in":"body"},{"name":"mode","in":"body"},{"name":"pool_id","in":"body"},{"name":"ref","in":"body"},{"name":"repository","in":"body"},{"name":"target","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_leads_tasks_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks/{leadTaskID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"grantID","in":"path","required":true},{"name":"leadTaskID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leads_tasks_log_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks/{leadTaskID}/log","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"grantID","in":"path","required":true},{"name":"leadTaskID","in":"path","required":true},{"name":"limit","in":"query"},{"name":"offset","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leads_tasks_move","method":"POST","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks/{leadTaskID}/move","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"grantID","in":"path","required":true},{"name":"leadTaskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"agent_lead_task_report","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks/{leadTaskID}/report","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"grantID","in":"path","required":true},{"name":"leadTaskID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leads_tasks_retry","method":"POST","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks/{leadTaskID}/retry","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"grantID","in":"path","required":true},{"name":"leadTaskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"agent_lead_task_stop","method":"POST","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/tasks/{leadTaskID}/stop","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"grantID","in":"path","required":true},{"name":"leadTaskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"build_leads_usage_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/usage","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"grantID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leads_workers_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leads/{grantID}/workers","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"grantID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"limit","in":"query"},{"name":"scope","in":"query"},{"name":"state","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_lease_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_artifacts_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/artifacts","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_artifacts_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/artifacts","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"name","in":"query"},{"name":"run_id","in":"query"},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_leases_artifacts_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/artifacts/{artifactID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"artifactID","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"build_leases_artifacts_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/artifacts/{artifactID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"artifactID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_artifacts_content_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/artifacts/{artifactID}/content","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"artifactID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_caches_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/caches","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_caches_entries_set","method":"PUT","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/caches/{cacheName}/entries","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"cacheName","in":"path","required":true},{"name":"key","in":"query"},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_leases_caches_restore_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/caches/{cacheName}/restore","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"cacheName","in":"path","required":true},{"name":"key","in":"query"},{"name":"prefix","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_engine_signins_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/engine-signins","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_leases_engine_signins_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/engine-signins/{signinID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"signinID","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"build_leases_engine_signins_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/engine-signins/{signinID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"signinID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_kill","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/kill","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"build_lease_release","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/release","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"build_lease_renew","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/renew","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_leases_runs_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/runs","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_runs_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/runs","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_leases_runs_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/runs/{runID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"runID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_runs_complete","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/runs/{runID}/complete","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"runID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_leases_runs_log_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/runs/{runID}/log","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"runID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_runs_log_set","method":"PUT","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/runs/{runID}/log","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"runID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_leases_ssh_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/ssh","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_ssh_certificate","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/ssh/certificate","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_leases_sync","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/sync","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_leases_tasks_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_tasks_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"agent_task_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_task_open_branch","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/branch","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"agent_task_cancel","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/cancel","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"build_leases_tasks_changes_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/changes","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_task_diff","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/diff","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_tasks_file_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/file","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"path","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_tasks_files_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/files","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"path","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_tasks_handback","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/handback","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_leases_tasks_keep_lease","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/keep-lease","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_leases_tasks_live_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/live","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"after","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_tasks_live_diff_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/live/diff","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_tasks_live_events_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/live/events","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"after","in":"query"},{"name":"limit","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_task_log","method":"GET","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/log","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"limit","in":"query"},{"name":"offset","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_leases_tasks_takeover","method":"POST","path":"/api/v1/orgs/{orgID}/build/leases/{leaseID}/tasks/{taskID}/takeover","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"leaseID","in":"path","required":true},{"name":"taskID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_login_wipes_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/login-wipes","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_pools_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/pools","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_pools_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/pools","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_pools_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"poolID","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"build_pools_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"poolID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_pools_update","method":"PATCH","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"poolID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_pools_caches_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}/caches","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"poolID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_pools_caches_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}/caches/{cacheName}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"poolID","in":"path","required":true},{"name":"cacheName","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"build_pools_engines_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}/engines","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"poolID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_lease_create","method":"POST","path":"/api/v1/orgs/{orgID}/build/pools/{poolID}/leases","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"poolID","in":"path","required":true},{"name":"devices","in":"body"},{"name":"purpose","in":"body"},{"name":"repo","in":"body"},{"name":"size","in":"body"},{"name":"ttl_seconds","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_quotas_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/quotas","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_task_costs_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/task-costs","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"scope","in":"query"},{"name":"since","in":"query"},{"name":"until","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_task_credentials_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/task-credentials","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"build_task_credentials_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/build/task-credentials/{vendor}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"vendor","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"build_task_credentials_set","method":"PUT","path":"/api/v1/orgs/{orgID}/build/task-credentials/{vendor}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"vendor","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_task_engines_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/task-engines","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_tasks_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/tasks","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"cursor","in":"query"},{"name":"engine","in":"query"},{"name":"limit","in":"query"},{"name":"pool_id","in":"query"},{"name":"scope","in":"query"},{"name":"since","in":"query"},{"name":"state","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_task_start","method":"POST","path":"/api/v1/orgs/{orgID}/build/tasks","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"build_usage_get","method":"GET","path":"/api/v1/orgs/{orgID}/build/usage","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"scope","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"agent_workers_list","method":"GET","path":"/api/v1/orgs/{orgID}/build/workers","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"lead_grant_id","in":"query"},{"name":"scope","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"invitations_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/invitations/{invID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"invID","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"quotas_list","method":"GET","path":"/api/v1/orgs/{orgID}/quotas","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"active_only","in":"query"},{"name":"resource_type","in":"query"},{"name":"scope","in":"query"},{"name":"user_id","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"quotas_alerts_list","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/alerts","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"unacked_only","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"quotas_pools_list","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/pools","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"quotas_report_get","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/report","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"quotas_requests_list","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/requests","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"status","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"quotas_get","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/{quotaID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"quotaID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"quotas_forecast_get","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/{quotaID}/forecast","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"quotaID","in":"path","required":true},{"name":"lookback_days","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"quotas_usage_get","method":"GET","path":"/api/v1/orgs/{orgID}/quotas/{quotaID}/usage","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"quotaID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandscale_billing_get","method":"GET","path":"/api/v1/orgs/{orgID}/sandscale/billing","region":"global","params":[{"name":"orgID","in":"path","org":true}],"changes":false,"confirm":false}, + {"name":"sandscale_checkout_start","method":"POST","path":"/api/v1/orgs/{orgID}/sandscale/billing/checkout","region":"global","params":[{"name":"orgID","in":"path","org":true},{"name":"interval","in":"body","required":true},{"name":"plan","in":"body","required":true},{"name":"seats","in":"body"}],"changes":true,"confirm":false}, + {"name":"sandscale_billing_portal","method":"POST","path":"/api/v1/orgs/{orgID}/sandscale/billing/portal","region":"global","params":[{"name":"orgID","in":"path","org":true}],"changes":true,"confirm":false}, + {"name":"sandscale_spend_caps_list","method":"GET","path":"/api/v1/orgs/{orgID}/sandscale/spend-caps","region":"global","params":[{"name":"orgID","in":"path","org":true}],"changes":false,"confirm":false}, + {"name":"sandscale_spend_caps_get","method":"GET","path":"/api/v1/orgs/{orgID}/sandscale/spend-caps/{capID}","region":"global","params":[{"name":"orgID","in":"path","org":true},{"name":"capID","in":"path","required":true}],"changes":false,"confirm":false}, + {"name":"workspace_templates_list","method":"GET","path":"/api/v1/orgs/{orgID}/templates","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"cursor","in":"query"},{"name":"include_deleted","in":"query"},{"name":"limit","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"templates_builtins_list","method":"GET","path":"/api/v1/orgs/{orgID}/templates/builtins","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"templates_get","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"templates_access_get","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/access","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_template_launch_options","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/launch","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"version","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"templates_permissions_list","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/permissions","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"templates_stats_list","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/stats","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"templates_versions_list","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/versions","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"include_archived","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"templates_versions_get","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/versions/{vid}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"vid","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"templates_versions_parameters_list","method":"GET","path":"/api/v1/orgs/{orgID}/templates/{id}/versions/{vid}/parameters","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"vid","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"all","in":"query"},{"name":"cursor","in":"query"},{"name":"limit","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_create","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"autostart","in":"body"},{"name":"autostart_schedule","in":"body"},{"name":"idle_timeout_seconds","in":"body"},{"name":"name","in":"body","required":true},{"name":"parameters","in":"body"},{"name":"template_id","in":"body","required":true},{"name":"template_version_id","in":"body"},{"name":"ttl_seconds","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_lifecycle_policy_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/lifecycle-policy","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_lifecycle_policy_set","method":"PUT","path":"/api/v1/orgs/{orgID}/workspaces/lifecycle-policy","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_policy_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/policy","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_policy_set","method":"PUT","path":"/api/v1/orgs/{orgID}/workspaces/policy","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_ssh_host_ca_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/ssh-host-ca","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_backup_capability","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backup-capability","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_backup_schedule_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backup-schedule","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_backup_schedule_create","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backup-schedule","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"frequency","in":"body","required":true},{"name":"retention_policy","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_backup_stats_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backup-stats","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_backups_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backups","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_backup_create","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backups","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"type","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_backups_verify_all","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{id}/backups/verify-all","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_metrics_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/metrics","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_metrics_dashboard_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/metrics/dashboard","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_metrics_definitions_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/metrics/definitions","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_metrics_latest_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/metrics/latest","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_restore_points_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{id}/restore-points","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"workspace_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_update","method":"PATCH","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"autostart","in":"body"},{"name":"autostart_schedule","in":"body"},{"name":"idle_timeout_seconds","in":"body"},{"name":"ttl_seconds","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_agent_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/agent","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_agent_config_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/agent/config","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"name","in":"query"},{"name":"type","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_agent_config_set","method":"PUT","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/agent/config","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_agent_logs_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/agent/logs","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_apps_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/apps","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_apps_share_update","method":"PATCH","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/apps/{slug}/share","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"slug","in":"path","required":true},{"name":"share_level","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspace_builds_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/builds","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"limit","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_builds_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/builds/{buildID}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"buildID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_builds_logs_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/builds/{buildID}/logs","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"buildID","in":"path","required":true},{"name":"after","in":"query"},{"name":"limit","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_exec","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/exec","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"command","in":"body","required":true},{"name":"env","in":"body"},{"name":"stdin","in":"body"},{"name":"timeout_sec","in":"body"},{"name":"workdir","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_git_credentials_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/git-credentials","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_git_credentials_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/git-credentials/{host}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"host","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"workspaces_git_credentials_set","method":"PUT","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/git-credentials/{host}","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"host","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_guest_delete","method":"DELETE","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/guest","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"workspaces_guest","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/guest","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_invitations_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/invitations","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_invite","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/invite","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_open_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/open","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"ide","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_permissions_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/permissions","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspace_rebuild","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/rebuild","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"parameters","in":"body"},{"name":"template_version_id","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_share","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/share","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_shares_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/shares","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_ssh_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/ssh","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_ssh_certificate","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/ssh/certificate","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspace_start","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/start","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspace_stop","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/stop","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_terminal_availability_get","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/terminal/availability","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_terminal_tickets","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/terminal/tickets","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"workspaces_tokens_list","method":"GET","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/tokens","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"workspaces_tokens","method":"POST","path":"/api/v1/orgs/{orgID}/workspaces/{wsID}/tokens","region":"regional","params":[{"name":"orgID","in":"path","org":true},{"name":"wsID","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"regions_list","method":"GET","path":"/api/v1/regions","region":"plane","params":[],"changes":false,"confirm":false}, + {"name":"sandbox_activity_get","method":"GET","path":"/api/v1/sandbox/activity","region":"regional","params":[{"name":"days","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_artifacts_list","method":"GET","path":"/api/v1/sandbox/artifacts","region":"regional","params":[{"name":"run_id","in":"query"},{"name":"status","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_artifacts_approve","method":"POST","path":"/api/v1/sandbox/artifacts/{id}/approve","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"target_path","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_artifacts_reject","method":"POST","path":"/api/v1/sandbox/artifacts/{id}/reject","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"reason","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_batches_create","method":"POST","path":"/api/v1/sandbox/batches","region":"regional","params":[{"name":"command","in":"body"},{"name":"count","in":"body","required":true},{"name":"cpu_count","in":"body"},{"name":"disk_mb","in":"body"},{"name":"image","in":"body"},{"name":"labels","in":"body"},{"name":"mem_mb","in":"body"},{"name":"metadata","in":"body"},{"name":"name","in":"body"},{"name":"network","in":"body"},{"name":"priority","in":"body"},{"name":"template_id","in":"body"},{"name":"ttl_seconds","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_batches_get","method":"GET","path":"/api/v1/sandbox/batches/{batchID}","region":"regional","params":[{"name":"batchID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_caches_list","method":"GET","path":"/api/v1/sandbox/caches","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_caches_delete","method":"DELETE","path":"/api/v1/sandbox/caches/{cacheId}","region":"regional","params":[{"name":"cacheId","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"sandbox_docs_list","method":"GET","path":"/api/v1/sandbox/docs","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_list","method":"GET","path":"/api/v1/sandbox/instances","region":"regional","params":[{"name":"cursor","in":"query"},{"name":"limit","in":"query"},{"name":"project_id","in":"query"},{"name":"status","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_create","method":"POST","path":"/api/v1/sandbox/instances","region":"regional","params":[{"name":"command","in":"body"},{"name":"cpu_count","in":"body"},{"name":"disk_mb","in":"body"},{"name":"env","in":"body"},{"name":"environment_id","in":"body"},{"name":"image","in":"body"},{"name":"labels","in":"body"},{"name":"mem_mb","in":"body"},{"name":"metadata","in":"body"},{"name":"name","in":"body"},{"name":"network","in":"body"},{"name":"priority","in":"body"},{"name":"queue","in":"body"},{"name":"runtime","in":"body"},{"name":"snapshot_id","in":"body"},{"name":"template_id","in":"body"},{"name":"ttl_seconds","in":"body"},{"name":"vault_env","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_terminate","method":"DELETE","path":"/api/v1/sandbox/instances/{id}","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"sandbox_get","method":"GET","path":"/api/v1/sandbox/instances/{id}","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_instances_caches_restore","method":"POST","path":"/api/v1/sandbox/instances/{id}/caches/restore","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"ecosystem","in":"body","required":true},{"name":"lockfile","in":"body","required":true},{"name":"path","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_instances_caches_save","method":"POST","path":"/api/v1/sandbox/instances/{id}/caches/save","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"ecosystem","in":"body","required":true},{"name":"lockfile","in":"body","required":true},{"name":"path","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_exec","method":"POST","path":"/api/v1/sandbox/instances/{id}/exec","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"command","in":"body","required":true},{"name":"env","in":"body"},{"name":"stdin","in":"body"},{"name":"timeout_sec","in":"body"},{"name":"wait","in":"body"},{"name":"workdir","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_file_read","method":"GET","path":"/api/v1/sandbox/instances/{id}/files","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"path","in":"query","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_file_write","method":"PUT","path":"/api/v1/sandbox/instances/{id}/files","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"content","in":"body","required":true},{"name":"mode","in":"body"},{"name":"path","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_instances_keep_awake","method":"POST","path":"/api/v1/sandbox/instances/{id}/keep-awake","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"reason","in":"body"},{"name":"ttl_seconds","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_instances_metrics_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/metrics","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"start","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_pause","method":"POST","path":"/api/v1/sandbox/instances/{id}/pause","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_instances_ports_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/ports","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_port_expose","method":"POST","path":"/api/v1/sandbox/instances/{id}/ports","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"port","in":"body","required":true},{"name":"protocol","in":"body"},{"name":"ttl_seconds","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_instances_ports_delete","method":"DELETE","path":"/api/v1/sandbox/instances/{id}/ports/{port}","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"port","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"sandbox_instances_ports_preview_links","method":"POST","path":"/api/v1/sandbox/instances/{id}/ports/{port}/preview-links","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"port","in":"path","required":true},{"name":"ttl_seconds","in":"body"},{"name":"visibility","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_instances_prepare","method":"POST","path":"/api/v1/sandbox/instances/{id}/prepare","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_instances_preview_links_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/preview-links","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_instances_preview_links_delete","method":"DELETE","path":"/api/v1/sandbox/instances/{id}/preview-links/{linkId}","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"linkId","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"sandbox_instances_project_changes_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/project/changes","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"dir","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_resume","method":"POST","path":"/api/v1/sandbox/instances/{id}/resume","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_runs_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/runs","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_snapshot_create","method":"POST","path":"/api/v1/sandbox/instances/{id}/snapshot","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"label","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_instances_snapshots_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/snapshots","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_instances_ssh_get","method":"GET","path":"/api/v1/sandbox/instances/{id}/ssh","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_instances_ssh_certificate","method":"POST","path":"/api/v1/sandbox/instances/{id}/ssh/certificate","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"public_key","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_instances_volumes_list","method":"GET","path":"/api/v1/sandbox/instances/{id}/volumes","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_instances_volumes_create","method":"POST","path":"/api/v1/sandbox/instances/{id}/volumes","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"mode","in":"body","required":true},{"name":"mount_path","in":"body","required":true},{"name":"volume_id","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_instances_volumes_delete","method":"DELETE","path":"/api/v1/sandbox/instances/{id}/volumes/{volumeId}","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"volumeId","in":"path","required":true},{"name":"commit","in":"query"},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"sandbox_instances_volumes_commit","method":"POST","path":"/api/v1/sandbox/instances/{id}/volumes/{volumeId}/commit","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"volumeId","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_jobs_input","method":"POST","path":"/api/v1/sandbox/jobs/{id}/input","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"data","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_jobs_pty_resize","method":"POST","path":"/api/v1/sandbox/jobs/{id}/pty/resize","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"cols","in":"body","required":true},{"name":"rows","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_kill_switch_get","method":"GET","path":"/api/v1/sandbox/kill-switch","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_launch_options","method":"GET","path":"/api/v1/sandbox/launch-options","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_openapi_yaml_get","method":"GET","path":"/api/v1/sandbox/openapi.yaml","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_orgs_billing_usage_get","method":"GET","path":"/api/v1/sandbox/orgs/{id}/billing/usage","region":"regional","params":[{"name":"id","in":"path","org":true},{"name":"end","in":"query","required":true},{"name":"start","in":"query","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_policy_get","method":"GET","path":"/api/v1/sandbox/policy","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_policy_set","method":"PUT","path":"/api/v1/sandbox/policy","region":"regional","params":[{"name":"allowed_providers","in":"body"},{"name":"egress_allowlist","in":"body"},{"name":"egress_presets","in":"body"},{"name":"max_concurrent","in":"body"},{"name":"max_cpu","in":"body"},{"name":"max_cpu_cores_per_user","in":"body"},{"name":"max_disk_mb","in":"body"},{"name":"max_exec_time_sec","in":"body"},{"name":"max_mem_mb","in":"body"},{"name":"max_memory_gb_per_user","in":"body"},{"name":"max_workspaces_per_user","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_policy_port_exposure_get","method":"GET","path":"/api/v1/sandbox/policy/port-exposure","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_policy_port_exposure_set","method":"PUT","path":"/api/v1/sandbox/policy/port-exposure","region":"regional","params":[{"name":"allowed_ports","in":"body","required":true},{"name":"default_ttl_seconds","in":"body","required":true},{"name":"max_open_per_sandbox","in":"body","required":true},{"name":"max_ttl_seconds","in":"body","required":true},{"name":"mode","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_policy_snapshots_list","method":"GET","path":"/api/v1/sandbox/policy/snapshots","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_policy_snapshots_set","method":"PUT","path":"/api/v1/sandbox/policy/snapshots","region":"regional","params":[{"name":"enabled","in":"body","required":true},{"name":"max_snapshot_bytes","in":"body","required":true},{"name":"max_snapshots","in":"body","required":true},{"name":"max_total_bytes","in":"body","required":true},{"name":"retention_days","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_policy_ssh_get","method":"GET","path":"/api/v1/sandbox/policy/ssh","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_policy_ssh_set","method":"PUT","path":"/api/v1/sandbox/policy/ssh","region":"regional","params":[{"name":"cert_ttl_seconds","in":"body","required":true},{"name":"enabled","in":"body","required":true},{"name":"max_session_seconds","in":"body","required":true},{"name":"mode","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_policy_storage_get","method":"GET","path":"/api/v1/sandbox/policy/storage","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_policy_storage_set","method":"PUT","path":"/api/v1/sandbox/policy/storage","region":"regional","params":[{"name":"cache_ttl_days","in":"body","required":true},{"name":"caches_enabled","in":"body","required":true},{"name":"max_cache_entry_bytes","in":"body","required":true},{"name":"max_cache_total_bytes","in":"body","required":true},{"name":"max_volume_bytes","in":"body","required":true},{"name":"max_volumes","in":"body","required":true},{"name":"volumes_enabled","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_policy_warm_pool_get","method":"GET","path":"/api/v1/sandbox/policy/warm-pool","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_policy_warm_pool_set","method":"PUT","path":"/api/v1/sandbox/policy/warm-pool","region":"regional","params":[{"name":"pools","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_queue_list","method":"GET","path":"/api/v1/sandbox/queue","region":"regional","params":[{"name":"limit","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_queue_delete","method":"DELETE","path":"/api/v1/sandbox/queue/{entryID}","region":"regional","params":[{"name":"entryID","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"sandbox_queue_get","method":"GET","path":"/api/v1/sandbox/queue/{entryID}","region":"regional","params":[{"name":"entryID","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_quota_get","method":"GET","path":"/api/v1/sandbox/quota","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_runs_list_all","method":"GET","path":"/api/v1/sandbox/runs","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_runs_delete","method":"DELETE","path":"/api/v1/sandbox/runs/{id}","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"sandbox_run_get","method":"GET","path":"/api/v1/sandbox/runs/{id}","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_run_output","method":"GET","path":"/api/v1/sandbox/runs/{id}/output","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_snapshots_list","method":"GET","path":"/api/v1/sandbox/snapshots","region":"regional","params":[{"name":"limit","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_snapshot_delete","method":"DELETE","path":"/api/v1/sandbox/snapshots/{snapshotId}","region":"regional","params":[{"name":"snapshotId","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"sandbox_snapshots_get","method":"GET","path":"/api/v1/sandbox/snapshots/{snapshotId}","region":"regional","params":[{"name":"snapshotId","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_templates_list","method":"GET","path":"/api/v1/sandbox/templates","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_templates_create","method":"POST","path":"/api/v1/sandbox/templates","region":"regional","params":[{"name":"cpu_count","in":"body"},{"name":"disk_size_mb","in":"body"},{"name":"image","in":"body"},{"name":"mem_size_mb","in":"body"},{"name":"name","in":"body","required":true},{"name":"registry_auth","in":"body"},{"name":"snapshot_id","in":"body"},{"name":"version","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_templates_delete","method":"DELETE","path":"/api/v1/sandbox/templates/{id}","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"sandbox_templates_get","method":"GET","path":"/api/v1/sandbox/templates/{id}","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_templates_build_status_get","method":"GET","path":"/api/v1/sandbox/templates/{id}/build-status","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"watch","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_trace_export_delete","method":"DELETE","path":"/api/v1/sandbox/trace-export","region":"regional","params":[{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"sandbox_trace_export_get","method":"GET","path":"/api/v1/sandbox/trace-export","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_trace_export_set","method":"PUT","path":"/api/v1/sandbox/trace-export","region":"regional","params":[{"name":"enabled","in":"body"},{"name":"endpoint","in":"body","required":true},{"name":"headers","in":"body"},{"name":"protocol","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_trace_export_test","method":"POST","path":"/api/v1/sandbox/trace-export/test","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_traces_list","method":"GET","path":"/api/v1/sandbox/traces","region":"regional","params":[{"name":"cursor","in":"query"},{"name":"from","in":"query"},{"name":"limit","in":"query"},{"name":"sandbox_id","in":"query"},{"name":"to","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_traces_get","method":"GET","path":"/api/v1/sandbox/traces/{traceId}","region":"regional","params":[{"name":"traceId","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_volumes_list","method":"GET","path":"/api/v1/sandbox/volumes","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_volumes_create","method":"POST","path":"/api/v1/sandbox/volumes","region":"regional","params":[{"name":"max_bytes","in":"body"},{"name":"name","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_volumes_delete","method":"DELETE","path":"/api/v1/sandbox/volumes/{volumeId}","region":"regional","params":[{"name":"volumeId","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"sandbox_volumes_get","method":"GET","path":"/api/v1/sandbox/volumes/{volumeId}","region":"regional","params":[{"name":"volumeId","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_webhooks_list","method":"GET","path":"/api/v1/sandbox/webhooks","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_webhooks_create","method":"POST","path":"/api/v1/sandbox/webhooks","region":"regional","params":[{"name":"events","in":"body","required":true},{"name":"lease_lead_seconds","in":"body"},{"name":"url","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_webhooks_event_types_list","method":"GET","path":"/api/v1/sandbox/webhooks/event-types","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_webhooks_delete","method":"DELETE","path":"/api/v1/sandbox/webhooks/{id}","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"sandbox_webhooks_get","method":"GET","path":"/api/v1/sandbox/webhooks/{id}","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_webhooks_deliveries_list","method":"GET","path":"/api/v1/sandbox/webhooks/{id}/deliveries","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"before","in":"query"},{"name":"limit","in":"query"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandbox_webhooks_deliveries_redeliver","method":"POST","path":"/api/v1/sandbox/webhooks/{id}/deliveries/{deliveryId}/redeliver","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"deliveryId","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_webhooks_rotate_secret","method":"POST","path":"/api/v1/sandbox/webhooks/{id}/rotate-secret","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"overlap_seconds","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_webhooks_test","method":"POST","path":"/api/v1/sandbox/webhooks/{id}/test","region":"regional","params":[{"name":"id","in":"path","required":true},{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"sandbox_workers_list","method":"GET","path":"/api/v1/sandbox/workers","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"sandscale_usage_get","method":"GET","path":"/api/v1/sandscale/usage","region":"global","params":[],"changes":false,"confirm":false}, + {"name":"storage_access_key_create","method":"POST","path":"/api/v1/svc/objects/CreateAccessKey","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"storage_bucket_create","method":"POST","path":"/api/v1/svc/objects/CreateBucket","region":"regional","params":[{"name":"ContentClass","in":"body"},{"name":"DataEvents","in":"body"},{"name":"Name","in":"body","required":true},{"name":"ObjectLock","in":"body"},{"name":"Versioning","in":"body"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"objects_delete_access_key","method":"POST","path":"/api/v1/svc/objects/DeleteAccessKey","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"storage_bucket_delete","method":"POST","path":"/api/v1/svc/objects/DeleteBucket","region":"regional","params":[{"name":"Name","in":"body","required":true},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"objects_delete_bucket_lifecycle","method":"POST","path":"/api/v1/svc/objects/DeleteBucketLifecycle","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"objects_delete_bucket_policy","method":"POST","path":"/api/v1/svc/objects/DeleteBucketPolicy","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":true}, + {"name":"storage_bucket_describe","method":"POST","path":"/api/v1/svc/objects/DescribeBucket","region":"regional","params":[{"name":"Name","in":"body","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"objects_describe_objects_limits","method":"POST","path":"/api/v1/svc/objects/DescribeObjectsLimits","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"objects_describe_objects_service","method":"POST","path":"/api/v1/svc/objects/DescribeObjectsService","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"objects_get_bucket_lifecycle","method":"POST","path":"/api/v1/svc/objects/GetBucketLifecycle","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"objects_get_bucket_policy","method":"POST","path":"/api/v1/svc/objects/GetBucketPolicy","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"storage_access_keys_list","method":"POST","path":"/api/v1/svc/objects/ListAccessKeys","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"storage_buckets_list","method":"POST","path":"/api/v1/svc/objects/ListBuckets","region":"regional","params":[{"name":"MaxResults","in":"body"},{"name":"NextToken","in":"body"},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"objects_put_bucket_lifecycle","method":"POST","path":"/api/v1/svc/objects/PutBucketLifecycle","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"objects_put_bucket_policy","method":"POST","path":"/api/v1/svc/objects/PutBucketPolicy","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"objects_update_access_key","method":"POST","path":"/api/v1/svc/objects/UpdateAccessKey","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"objects_update_bucket","method":"POST","path":"/api/v1/svc/objects/UpdateBucket","region":"regional","params":[{"name":"body","in":"whole"},{"name":"region","in":"region"}],"changes":true,"confirm":false}, + {"name":"invitations_list","method":"GET","path":"/api/v1/users/invitations","region":"global","params":[{"name":"after","in":"query"},{"name":"limit","in":"query"},{"name":"organization_id","in":"query","org":true},{"name":"status","in":"query"}],"changes":false,"confirm":false}, + {"name":"invitation_create","method":"POST","path":"/api/v1/users/invitations","region":"global","params":[{"name":"display_name","in":"body"},{"name":"email","in":"body","required":true},{"name":"invited_by_user_id","in":"body"},{"name":"organization_id","in":"body","required":true,"org":true}],"changes":true,"confirm":false}, + {"name":"users_invitations_resend","method":"POST","path":"/api/v1/users/invitations/{id}/resend","region":"global","params":[{"name":"id","in":"path","required":true},{"name":"body","in":"whole"}],"changes":true,"confirm":false}, + {"name":"invitation_revoke","method":"POST","path":"/api/v1/users/invitations/{id}/revoke","region":"global","params":[{"name":"id","in":"path","required":true},{"name":"body","in":"whole"}],"changes":true,"confirm":true}, + {"name":"whoami","method":"GET","path":"/api/v1/users/me","region":"plane","params":[],"changes":false,"confirm":false}, + {"name":"vault_mounts_list","method":"GET","path":"/api/v1/vault/sys/mounts","region":"regional","params":[{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"vault_secret_metadata_get","method":"GET","path":"/api/v1/vault/{mount}/metadata/{path...}","region":"regional","params":[{"name":"mount","in":"path","required":true},{"name":"path","in":"path","required":true},{"name":"region","in":"region"}],"changes":false,"confirm":false}, + {"name":"vault_secret_names_list","method":"GET","path":"/api/v1/vault/{mount}/metadata/{path...}","region":"regional","params":[{"name":"mount","in":"path","required":true},{"name":"path","in":"path","required":true},{"name":"region","in":"region"}],"fixed_query":{"list":"true"},"changes":false,"confirm":false} +]''') diff --git a/src/sandscale/_processes.py b/src/sandscale/_processes.py new file mode 100644 index 0000000..4d59219 --- /dev/null +++ b/src/sandscale/_processes.py @@ -0,0 +1,40 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""The shell scripts behind background processes (``Sandboxes.start_process`` and friends). + +They run through the exec route, so they work on every image that has ``sh`` (BusyBox included). +The remote MCP's ``sandbox_process`` runs the same text (a test keeps the copies identical).""" + +PROCESS_START_SCRIPT = r'''set -u; d=/tmp/.ws-procs/$1; mkdir -p "$d" || exit 1 +if [ -n "$2" ]; then cd "$2" || { echo "cannot enter $2" >&2; exit 1; }; fi +printf '%s' "$3" > "$d/cmd"; rm -f "$d/exit" "$d/pid" +S=; command -v setsid >/dev/null 2>&1 && S=setsid +( $S sh -c 'echo $$ > "$1"; exec sh -c "$2"' sh "$d/pid" "$3" > "$d/log" 2>&1 < /dev/null; echo $? > "$d/exit" ) > /dev/null 2>&1 & +i=0; while [ ! -s "$d/pid" ] && [ "$i" -lt 30 ]; do i=$((i+1)); sleep 1; done +cat "$d/pid"''' + +PROCESS_LIST_SCRIPT = r'''for d in /tmp/.ws-procs/*/; do [ -d "$d" ] || continue; d=${d%/}; id=${d##*/} +pid=$(cat "$d/pid" 2>/dev/null); code= +if [ -f "$d/exit" ]; then st=exited; code=$(cat "$d/exit") +elif [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then st=running +else st=lost; fi +printf '%s\t%s\t%s\t%s\t%s\n' "$id" "$st" "$code" "$pid" "$(head -c 120 "$d/cmd" 2>/dev/null | tr '\n' ' ')" +done''' + +PROCESS_LOGS_SCRIPT = r'''d=/tmp/.ws-procs/$1; f=$d/log; [ -f "$f" ] || { echo "no process $1" >&2; exit 2; } +wc -c < "$f" +pid=$(cat "$d/pid" 2>/dev/null) +if [ -f "$d/exit" ]; then echo "exited $(cat "$d/exit")"; elif [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then echo running; else echo lost; fi +if [ "$2" -ge 0 ]; then tail -c +"$(($2 + 1))" "$f" | head -c "$3"; else tail -c "$3" "$f"; fi''' + +PROCESS_KILL_SCRIPT = r'''d=/tmp/.ws-procs/$1; [ -d "$d" ] || { echo "no process $1" >&2; exit 2; } +pid=$(cat "$d/pid" 2>/dev/null); [ -n "$pid" ] || { echo "not started" >&2; exit 2; } +kill -s "$2" -- "-$pid" 2>/dev/null || kill -s "$2" "$pid" 2>/dev/null || { echo "not running"; exit 0; } +echo signalled''' + +PROCESS_WAIT_PORT_SCRIPT = r'''hex=$(printf '%04X' "$1"); i=0 +while [ "$i" -lt "$2" ]; do + if grep -qi ":$hex [0-9A-F:]* 0A " /proc/net/tcp /proc/net/tcp6 2>/dev/null; then echo ready; exit 0; fi + i=$((i+1)); sleep 1 +done +echo timeout; exit 1''' diff --git a/src/sandscale/_services.py b/src/sandscale/_services.py index 516c304..ebe46cf 100644 --- a/src/sandscale/_services.py +++ b/src/sandscale/_services.py @@ -1,14 +1,23 @@ # Copyright 2026 Neural Inverse # SPDX-License-Identifier: Apache-2.0 -"""Sandboxes, workspaces and build hosts.""" +"""Sandboxes, volumes, caches, workspaces and build hosts.""" from __future__ import annotations import base64 +from dataclasses import dataclass import json +import secrets import time from typing import Any, Callable, Iterator, List, Mapping, Optional, Sequence, TypeVar, Union +from ._processes import ( + PROCESS_KILL_SCRIPT, + PROCESS_LIST_SCRIPT, + PROCESS_LOGS_SCRIPT, + PROCESS_START_SCRIPT, + PROCESS_WAIT_PORT_SCRIPT, +) from ._transport import Transport, seg from .errors import SandboxWakingError, SandscaleError, ServerError from .admin_models import ( @@ -26,6 +35,8 @@ WorkspaceBackup, ) from .models import ( + DependencyCache, + CacheResult, ConnectInfo, FileEntry, Lease, @@ -35,11 +46,15 @@ Pool, RegionPage, RunEnd, + RunOutput, RunResult, Sandbox, + SandboxActivity, Snapshot, SSHCertificate, VaultEnvRef, + Volume, + VolumeAttachment, Workspace, WorkspaceBuild, parse_time, @@ -91,6 +106,40 @@ def _b64(data: Union[bytes, str]) -> str: return base64.b64encode(data.encode() if isinstance(data, str) else data).decode("ascii") +@dataclass +class ProcessStart: + """A background process of a sandbox, just started (``Sandboxes.start_process``).""" + + process_id: str + pid: int + + +@dataclass +class ProcessInfo: + """A background process of a sandbox: state is ``running``, ``exited`` (with ``exit_code``) or ``lost``.""" + + process_id: str + state: str + command: str + exit_code: Optional[int] = None + + +@dataclass +class ProcessLogs: + """A read of a background process's output (``Sandboxes.process_logs``).""" + + process_id: str + state: str + text: str + #: Pass as ``offset`` to read on from here. + next_offset: int + log_bytes: int + exit_code: Optional[int] = None + + +#: How long one streamed file transfer may take (the server bounds it at 30 minutes). +_TRANSFER_TIMEOUT = 1800.0 + class Sandboxes: def __init__(self, t: Transport) -> None: self._t = t @@ -114,15 +163,22 @@ def create( image: Optional[str] = None, runtime: Optional[str] = None, environment_id: Optional[str] = None, + idempotency_key: Optional[str] = None, region: Optional[str] = None, ) -> Sandbox: """Starts a sandbox. Limits, entitlement and policy are decided by the server. - ``vault_env`` names Keystone Vault values for the sandbox's environment + ``idempotency_key`` makes the start safe to retry: the same key starts one sandbox (the + server stores it per organization), and a connection error or a 429, 502, 503 or 504 is + retried automatically. + + ``vault_env`` names Sandscale Vault values for the sandbox's environment (``VaultEnvRef(name, path, field)`` or a mapping with those keys). The server reads each as the caller and hands it to the sandbox only: values never pass through the SDK. - ``network`` is the network mode (``none``, or ``allowlist`` where the plan has network), + ``network`` is the network mode (``none``, ``allowlist`` for the organization's hosts, or + ``full`` for any public host on ports 80 and 443 on Pro and higher; ``capabilities()`` + says which the organization can use now), ``image`` an OCI image pinned by digest (``name@sha256:...``) on a worker that runs images of its own, ``runtime`` ``firecracker`` (or another runtime where allowed) and ``environment_id`` a cloud environment the launch options list.""" @@ -145,7 +201,7 @@ def create( "environment_id": environment_id, } body = {k: v for k, v in fields.items() if v is not None} - raw = self._t.request("POST", "/api/v1/sandbox/instances", region=region, json_body=body) + raw = self._t.request("POST", "/api/v1/sandbox/instances", region=region, json_body=body, idempotency_key=idempotency_key) return Sandbox.from_raw(raw, self._t.region_of(region)) def get(self, sandbox_id: str, *, region: Optional[str] = None) -> Sandbox: @@ -171,6 +227,12 @@ def one(r: Optional[str]) -> tuple[list[Sandbox], RegionPage]: return list_across_regions(self._t, region, one) + def activity(self, *, days: Optional[int] = None, region: Optional[str] = None) -> SandboxActivity: + """Your own commands (one per exec) per UTC day for the last ``days`` days ending today + (1 to 371, 365 by default), in one region. Other people's commands are never counted.""" + raw = self._t.request("GET", "/api/v1/sandbox/activity", region=region, query={"days": days}) + return SandboxActivity.from_raw(raw, self._t.region_of(region)) + def stop(self, sandbox_id: str, *, region: Optional[str] = None) -> None: """Stops the sandbox and releases it.""" self._t.request("DELETE", f"/api/v1/sandbox/instances/{seg(sandbox_id)}", region=region) @@ -229,7 +291,7 @@ def snapshot(self, sandbox_id: str, *, label: Optional[str] = None, region: Opti def list_snapshots(self, sandbox_id: str, *, region: Optional[str] = None) -> List[Snapshot]: raw = self._t.request("GET", f"/api/v1/sandbox/instances/{seg(sandbox_id)}/snapshots", region=region) - # The server answers {"snapshots": [...]}. + # The server answers {"snapshots": [...]} (internal/sandboxapi/snapshots.go). return [Snapshot.from_raw(s, self._t.region_of(region)) for s in raw.get("snapshots") or []] def run( @@ -294,6 +356,15 @@ def run( final = self._t.request("GET", f"/api/v1/sandbox/runs/{seg(run_id)}", region=region) return _run_result({**final, "run_id": run_id}, out["stdout"], out["stderr"], True) + def run_output(self, run_id: str, *, region: Optional[str] = None) -> RunOutput: + """Reads the output of a run started without waiting (``wait: False``), once it ended. + + ``finished`` False: still running, read again later; ``output_available`` False with + ``reason`` ``"not_kept"``: no output is kept (a waited run's went to its caller, or the + retention in ``output_expires_at`` passed).""" + raw = self._t.request("GET", f"/api/v1/sandbox/runs/{seg(run_id)}/output", region=region) + return RunOutput.from_raw(raw) + def logs( self, sandbox_id: str, @@ -359,6 +430,118 @@ def read_file(self, sandbox_id: str, path: str, *, region: Optional[str] = None) raise SandscaleError(400, "not_a_file", f"{path} is not a regular file") return base64.b64decode(raw.get("content") or "") + def upload( + self, sandbox_id: str, path: str, data: Union[bytes, str], *, mode: Optional[str] = None, region: Optional[str] = None + ) -> None: + """Writes a file as a streamed transfer (raw bytes, up to the server's transfer bound, 1 GiB + by default), for files too large for ``write_file``. The file appears only once every byte + arrived.""" + payload = data.encode("utf-8") if isinstance(data, str) else bytes(data) + self._t.request_raw( + "PUT", + f"/api/v1/sandbox/instances/{seg(sandbox_id)}/files", + region=region, + query={"path": path, "mode": mode}, + body=payload, + timeout=_TRANSFER_TIMEOUT, + ) + + def download(self, sandbox_id: str, path: str, *, region: Optional[str] = None) -> bytes: + """Reads a file as a streamed transfer (raw bytes, up to the server's transfer bound).""" + return self._t.request_raw( + "GET", + f"/api/v1/sandbox/instances/{seg(sandbox_id)}/files", + region=region, + query={"path": path, "raw": 1}, + timeout=_TRANSFER_TIMEOUT, + ) + + def read_text(self, sandbox_id: str, path: str, *, region: Optional[str] = None) -> str: + """Reads a UTF-8 text file as a string (a file that is not valid UTF-8 raises UnicodeDecodeError).""" + return self.read_file(sandbox_id, path, region=region).decode("utf-8") + + def start_process( + self, + sandbox_id: str, + command: str, + *, + workdir: Optional[str] = None, + env: Optional[Mapping[str, str]] = None, + region: Optional[str] = None, + ) -> "ProcessStart": + """Starts a shell line in the background and returns at once with its ``process_id``. + + Read its output with :meth:`process_logs`, stop it with :meth:`kill_process`, wait for a port + with :meth:`wait_for_port`. The process, its log and its exit code live in the sandbox.""" + process_id = "p" + secrets.token_hex(4) + out = self._shell(sandbox_id, PROCESS_START_SCRIPT, [process_id, workdir or "", command], region, env) + digits = out.strip() + return ProcessStart(process_id=process_id, pid=int(digits) if digits.isdigit() else 0) + + def list_processes(self, sandbox_id: str, *, region: Optional[str] = None) -> List["ProcessInfo"]: + """The sandbox's background processes with their state (running, exited with an exit code, or lost).""" + out = self._shell(sandbox_id, PROCESS_LIST_SCRIPT, [], region) + procs: List[ProcessInfo] = [] + for line in out.split("\n"): + f = line.split("\t") + if len(f) < 5: + continue + procs.append( + ProcessInfo(process_id=f[0], state=f[1], command="\t".join(f[4:]), exit_code=int(f[2]) if f[2] != "" else None) + ) + return procs + + def process_logs( + self, + sandbox_id: str, + process_id: str, + *, + offset: Optional[int] = None, + tail_bytes: int = 8192, + region: Optional[str] = None, + ) -> "ProcessLogs": + """Reads a process's output. With ``offset`` it reads from that byte and ``next_offset`` is where + to continue; without it, the last ``tail_bytes`` (at most 65536).""" + limit = min(max(tail_bytes, 1), 65536) + start = -1 if offset is None else offset + out = self._shell(sandbox_id, PROCESS_LOGS_SCRIPT, [process_id, str(start), str(limit)], region) + size_line, _, rest = out.partition("\n") + state_line, _, text = rest.partition("\n") + state = state_line.strip() + exit_code: Optional[int] = None + if state.startswith("exited "): + exit_code = int(state[len("exited ") :]) + state = "exited" + size = int(size_line) if size_line.strip().isdigit() else 0 + return ProcessLogs( + process_id=process_id, + state=state, + text=text, + next_offset=size if start < 0 else start + len(text), + log_bytes=size, + exit_code=exit_code, + ) + + def kill_process(self, sandbox_id: str, process_id: str, *, force: bool = False, region: Optional[str] = None) -> bool: + """Stops a background process (SIGTERM, or SIGKILL with ``force``). False when it was not running.""" + out = self._shell(sandbox_id, PROCESS_KILL_SCRIPT, [process_id, "KILL" if force else "TERM"], region) + return out.strip() == "signalled" + + def wait_for_port(self, sandbox_id: str, port: int, *, timeout: int = 30, region: Optional[str] = None) -> bool: + """Waits until a TCP port listens in the sandbox (default 30 s, at most 120). Whether it did.""" + wait = min(max(timeout, 1), 120) + result = self.run(sandbox_id, ["sh", "-c", PROCESS_WAIT_PORT_SCRIPT, "sh", str(port), str(wait)], timeout=wait + 15, region=region) + return result.exit_code == 0 and result.stdout.strip() == "ready" + + def _shell( + self, sandbox_id: str, script: str, args: List[str], region: Optional[str], env: Optional[Mapping[str, str]] = None + ) -> str: + result = self.run(sandbox_id, ["sh", "-c", script, "sh", *args], env=env, timeout=60, region=region) + if result.exit_code != 0: + first = (result.stderr.strip().splitlines() or [""])[0] + raise SandscaleError(422, "process_failed", f"{first or 'the command failed'} (exit {result.exit_code})") + return result.stdout + def list_files(self, sandbox_id: str, path: str, *, region: Optional[str] = None) -> List[FileEntry]: raw = self._files(sandbox_id, path, region) if raw.get("type") != "dir": @@ -369,12 +552,79 @@ def list_files(self, sandbox_id: str, path: str, *, region: Optional[str] = None for e in raw.get("entries") or [] ] + def attach_volume( + self, + sandbox_id: str, + volume_id: str, + mount_path: str, + *, + mode: str = "rw", + region: Optional[str] = None, + ) -> VolumeAttachment: + """Attaches a persistent volume at ``mount_path`` (``mode`` ``"rw"`` or ``"ro"``). One + sandbox at a time may hold a volume read-write (409 volume_writer_attached otherwise).""" + body = {"volume_id": volume_id, "mount_path": mount_path, "mode": mode} + raw = self._t.request( + "POST", f"/api/v1/sandbox/instances/{seg(sandbox_id)}/volumes", region=region, json_body=body + ) + return VolumeAttachment.from_raw(raw) + + def list_attachments(self, sandbox_id: str, *, region: Optional[str] = None) -> List[VolumeAttachment]: + """The volumes attached to the sandbox.""" + raw = self._t.request("GET", f"/api/v1/sandbox/instances/{seg(sandbox_id)}/volumes", region=region) + return [VolumeAttachment.from_raw(a) for a in raw.get("data") or []] + + def commit_volume(self, sandbox_id: str, volume_id: str, *, region: Optional[str] = None) -> Volume: + """Writes a read-write attachment's contents back as the volume's next version (409 + volume_read_only for a read-only attachment).""" + raw = self._t.request( + "POST", f"/api/v1/sandbox/instances/{seg(sandbox_id)}/volumes/{seg(volume_id)}/commit", region=region + ) + return Volume.from_raw(raw, self._t.region_of(region)) + + def detach_volume( + self, sandbox_id: str, volume_id: str, *, commit: bool = True, region: Optional[str] = None + ) -> None: + """Detaches a volume; a read-write attachment is committed first unless ``commit=False``.""" + self._t.request( + "DELETE", + f"/api/v1/sandbox/instances/{seg(sandbox_id)}/volumes/{seg(volume_id)}", + region=region, + query={"commit": None if commit else "false"}, + ) + + def restore_cache( + self, sandbox_id: str, *, ecosystem: str, lockfile: str, path: Optional[str] = None, region: Optional[str] = None + ) -> CacheResult: + """Restores the organization's dependency cache for ``lockfile`` into the sandbox. The + server reads the lockfile in the sandbox and computes the key; ``hit`` says whether one + was restored. ``ecosystem`` is npm, pip, cargo or gomod.""" + raw = self._t.request( + "POST", + f"/api/v1/sandbox/instances/{seg(sandbox_id)}/caches/restore", + region=region, + json_body=_cache_body(ecosystem, lockfile, path), + ) + return CacheResult.from_raw(raw) + + def save_cache( + self, sandbox_id: str, *, ecosystem: str, lockfile: str, path: Optional[str] = None, region: Optional[str] = None + ) -> CacheResult: + """Saves the sandbox's dependency directory as the lockfile's cache; an existing entry is + never overwritten (``exists``).""" + raw = self._t.request( + "POST", + f"/api/v1/sandbox/instances/{seg(sandbox_id)}/caches/save", + region=region, + json_body=_cache_body(ecosystem, lockfile, path), + ) + return CacheResult.from_raw(raw) # --- ports, preview links, SSH --------------------------------------------------------- def expose_port( self, sandbox_id: str, port: int, *, ttl_seconds: Optional[int] = None, region: Optional[str] = None ) -> PortExposure: - """Opens a TCP port of the running sandbox to you alone, through Keystone.""" + """Opens a TCP port of the running sandbox to you alone, through Sandscale.""" body: Raw = {"port": port} if ttl_seconds is not None: body["ttl_seconds"] = ttl_seconds @@ -439,6 +689,13 @@ def _files(self, sandbox_id: str, path: str, region: Optional[str]) -> Raw: return raw +def _cache_body(ecosystem: str, lockfile: str, path: Optional[str]) -> Raw: + body: Raw = {"ecosystem": ecosystem, "lockfile": lockfile} + if path is not None: + body["path"] = path + return body + + def _vault_ref(ref: Union[VaultEnvRef, Mapping[str, str]]) -> dict[str, str]: if isinstance(ref, VaultEnvRef): return {"name": ref.name, "path": ref.path, "field": ref.field} @@ -455,6 +712,7 @@ def _run_result(raw: Raw, stdout: str, stderr: str, streamed: bool) -> RunResult duration_ms=int(raw.get("duration_ms") or 0), oom_killed=raw.get("oom_killed") is True or raw.get("status") == "oom_killed", timed_out=raw.get("timed_out") is True or raw.get("status") == "timed_out", + error=(raw.get("error") or None) if isinstance(raw.get("error"), str) else None, streamed=streamed, ) @@ -467,6 +725,59 @@ def _json_object(text: str) -> Raw: return value if isinstance(value, dict) else {} +class Volumes: + """Persistent volumes of the organization; attach one with ``sandboxes.attach_volume``.""" + + def __init__(self, t: Transport) -> None: + self._t = t + + def create(self, name: str, *, max_bytes: Optional[int] = None, region: Optional[str] = None) -> Volume: + """Creates an empty volume. Quota and size limits are decided by the server.""" + body: Raw = {"name": name} + if max_bytes is not None: + body["max_bytes"] = max_bytes + raw = self._t.request("POST", "/api/v1/sandbox/volumes", region=region, json_body=body) + return Volume.from_raw(raw, self._t.region_of(region)) + + def get(self, volume_id: str, *, region: Optional[str] = None) -> Volume: + raw = self._t.request("GET", f"/api/v1/sandbox/volumes/{seg(volume_id)}", region=region) + return Volume.from_raw(raw, self._t.region_of(region)) + + def list(self, *, region: Optional[str] = None) -> ListResult[Volume]: + """Lists volumes: of one region when one is named, else of every live region.""" + + def one(r: Optional[str]) -> tuple[list[Volume], RegionPage]: + raw = self._t.request("GET", "/api/v1/sandbox/volumes", region=r) + return [Volume.from_raw(v, r) for v in raw.get("data") or []], RegionPage(region=r) + + return list_across_regions(self._t, region, one) + + def delete(self, volume_id: str, *, region: Optional[str] = None) -> None: + """Deletes a volume (409 volume_in_use while it is attached).""" + self._t.request("DELETE", f"/api/v1/sandbox/volumes/{seg(volume_id)}", region=region) + + +class Caches: + """Dependency caches of the organization; restore and save them with + ``sandboxes.restore_cache`` and ``sandboxes.save_cache``. Keys are computed by the server + from the lockfile, and caches are shared within the organization only.""" + + def __init__(self, t: Transport) -> None: + self._t = t + + def list(self, *, region: Optional[str] = None) -> ListResult[DependencyCache]: + """Lists cache entries: of one region when one is named, else of every live region.""" + + def one(r: Optional[str]) -> tuple[list[DependencyCache], RegionPage]: + raw = self._t.request("GET", "/api/v1/sandbox/caches", region=r) + return [DependencyCache.from_raw(c, r) for c in raw.get("data") or []], RegionPage(region=r) + + return list_across_regions(self._t, region, one) + + def delete(self, cache_id: str, *, region: Optional[str] = None) -> None: + self._t.request("DELETE", f"/api/v1/sandbox/caches/{seg(cache_id)}", region=region) + + class Workspaces: def __init__(self, t: Transport) -> None: self._t = t diff --git a/src/sandscale/_transport.py b/src/sandscale/_transport.py index 5e2aeb6..0edbc67 100644 --- a/src/sandscale/_transport.py +++ b/src/sandscale/_transport.py @@ -11,7 +11,7 @@ import re import time from types import MappingProxyType -from typing import Any, Callable, Iterator, Mapping, Optional, Union +from typing import Any, Callable, Dict, Iterator, Mapping, Optional, Union from urllib.parse import urlsplit import httpx @@ -28,12 +28,23 @@ ) DEFAULT_BASE_URL = "https://api.sandscale.dev" -#: Sandscale's regional APIs ; api.sandscale.dev routes to the request's region, +#: Sandscale's regional APIs (decision 12); api.sandscale.dev routes to the request's region, #: US by default. SANDSCALE_REGION_URLS: Mapping[str, str] = MappingProxyType( {"us": "https://api.us.sandscale.dev", "eu": "https://api.eu.sandscale.dev"} ) _FRONT_DOOR_HOST = "api.sandscale.dev" +#: Regions the front door forwards to: the global plane serves us1 itself, so a call for another +#: region goes to api.sandscale.dev with ``region=`` and the global plane sends it on. A +#: regional host does not accept a global API key or sign-in token (regional cells create no API +#: keys; docs/cloud/multi-region.md 19.2). +_REGIONAL_COMPUTE_PATHS = ( + re.compile(r"^/api/v1/sandbox/instances(/|$)"), + re.compile(r"^/api/v1/orgs/[^/]+/workspaces(/|$)"), + re.compile(r"^/api/v1/orgs/[^/]+/build/leases(/|$)"), + re.compile(r"^/api/v1/orgs/[^/]+/build/pools/[^/]+/leases(/|$)"), +) +_FORWARDED_REGION_IDS: Mapping[str, str] = MappingProxyType({"eu": "eu1"}) def _sandscale_region(region: str) -> str: @@ -118,11 +129,34 @@ def require_org(self) -> str: def region_of(self, region: Optional[str]) -> Optional[str]: return region if region is not None else self.region + def forwarded_region(self, region: Optional[str]) -> Optional[str]: + """The cell id a call names in its ``region`` query when the front door forwards it + (``eu`` is ``eu1``), else None.""" + if region is None or not self._sandscale or region in self._region_urls: + return None + return _FORWARDED_REGION_IDS.get(_sandscale_region(region)) + + def _forward_params(self, region: Optional[str], path: str, params: Dict[str, Any]) -> None: + """Adds ``region=`` for a region the front door forwards, and refuses (before any + request) a route that is served in the US only: objects, templates, policy, webhooks, + snapshots, traces, lab hosts, agent tasks and the rest would run there, in the wrong region.""" + forwarded = self.forwarded_region(region) + if forwarded is None: + return + if not any(p.match(path) for p in _REGIONAL_COMPUTE_PATHS): + raise RegionError( + 0, + "region_unsupported", + f"{path} is served in the US only; region {region} applies to sandboxes, workspaces and build leases. " + "Omit region (or use us) for this call", + ) + params.setdefault("region", forwarded) + def origin_for(self, region: Optional[str]) -> str: """The API origin of a region. Explicit ``region_urls`` win. On Sandscale (the front door api.sandscale.dev) a region is one of Sandscale's regional APIs, ``us`` and ``eu`` - (a region id such as ``us1`` names the same), with no lookup. Against - another base URL (a self-hosted Keystone) the region is looked up in the server's public + (decision 12; a region id such as ``us1`` names the same), with no lookup. Against + another base URL (a self-hosted Sandscale) the region is looked up in the server's public region list (GET /api/v1/regions): an exact id, or the one live region whose id is the name followed by digits.""" if region is None: @@ -134,7 +168,7 @@ def origin_for(self, region: Optional[str]) -> str: if url is None: names = " or ".join(SANDSCALE_REGION_URLS) raise RegionError(0, "region_unknown", f"Sandscale has no region {region}; use {names}") - return url + return self.base_url if _sandscale_region(region) in _FORWARDED_REGION_IDS else url entries = self._region_list() matches = [r for r in entries if r["id"] == region] if not matches: @@ -196,19 +230,43 @@ def request( query: Optional[Mapping[str, Any]] = None, json_body: Any = None, timeout: Optional[float] = None, + idempotency_key: Optional[str] = None, ) -> Any: - """Sends one request and returns the parsed JSON (None for an empty body).""" - resp = self._call(method, path, region=region, query=query, json_body=json_body, timeout=timeout) + """Sends one request and returns the parsed JSON (None for an empty body). + + ``idempotency_key`` is sent as ``Idempotency-Key``: the server runs the write once however + often it is sent, so a write with a key is retried like a read.""" + resp = self._call( + method, path, region=region, query=query, json_body=json_body, timeout=timeout, idempotency_key=idempotency_key + ) return resp.json() if resp.content else None def request_bytes(self, method: str, path: str, *, region: Optional[str] = None) -> bytes: """Sends one request and returns the response body unparsed (a download).""" return self._call(method, path, region=region, query=None, json_body=None, timeout=None).content + def request_raw( + self, + method: str, + path: str, + *, + region: Optional[str] = None, + query: Optional[Mapping[str, Any]] = None, + body: Optional[bytes] = None, + timeout: Optional[float] = None, + ) -> bytes: + """Sends raw bytes (``application/octet-stream``) and returns the raw answer: a streamed + file transfer.""" + return self._call( + method, path, region=region, query=query, json_body=None, timeout=timeout, raw_body=body, + accept="application/octet-stream", + ).content + def stream_lines(self, path: str, *, region: Optional[str], query: Mapping[str, Any]) -> Iterator[str]: """Opens a Server-Sent Events stream and yields its lines.""" origin = self.origin_for(self.region_of(region)) params = {k: v for k, v in query.items() if v is not None} + self._forward_params(self.region_of(region), path, params) headers = self._headers("text/event-stream") try: with self._http.stream( @@ -240,15 +298,25 @@ def _call( query: Optional[Mapping[str, Any]], json_body: Any, timeout: Optional[float], + idempotency_key: Optional[str] = None, + raw_body: Optional[bytes] = None, + accept: str = "application/json", ) -> httpx.Response: url = f"{self.origin_for(self.region_of(region))}{path}" params = {k: v for k, v in (query or {}).items() if v is not None} - headers = self._headers("application/json") + self._forward_params(self.region_of(region), path, params) + headers = self._headers(accept) + if idempotency_key: + headers["Idempotency-Key"] = idempotency_key content: Optional[bytes] = None if json_body is not None: headers["Content-Type"] = "application/json" content = json.dumps(json_body).encode() - retries = self._max_retries if method in _SAFE_METHODS else 0 + elif raw_body is not None: + headers["Content-Type"] = "application/octet-stream" + content = raw_body + # A write with an idempotency key is retried like a read: the server runs it once. + retries = self._max_retries if method in _SAFE_METHODS or idempotency_key else 0 attempt = 0 while True: error: SandscaleError diff --git a/src/sandscale/_version.py b/src/sandscale/_version.py index 3beaa6a..9943edb 100644 --- a/src/sandscale/_version.py +++ b/src/sandscale/_version.py @@ -1,5 +1,5 @@ # Copyright 2026 Neural Inverse # SPDX-License-Identifier: Apache-2.0 -"""The SDK version.""" +"""The SDK's version (sdk/VERSION; written by sdk/scripts/set-version.mjs).""" VERSION = "1.0.0" diff --git a/src/sandscale/admin_models.py b/src/sandscale/admin_models.py index bca8aba..fa115e3 100644 --- a/src/sandscale/admin_models.py +++ b/src/sandscale/admin_models.py @@ -233,6 +233,29 @@ class Template: created_at: Optional[datetime] = None region: Optional[str] = None raw: Raw = field(default_factory=dict) + #: True for a built-in template (``builtin:go``): every organization has it; it is not a row. + builtin: bool = False + #: For a built-in template: whether it can be started here now, why not, and what it runs. + startable: Optional[bool] = None + reason: Optional[str] = None + description: Optional[str] = None + + @classmethod + def from_builtin(cls, raw: Raw, region: Optional[str]) -> "Template": + startable = raw.get("startable") is True + return cls( + id=str(raw.get("id")), + name=str(raw.get("name") or ""), + version="builtin", + status="ready" if startable else "unavailable", + image=_s(raw, "image"), + region=region, + raw=raw, + builtin=True, + startable=startable, + reason=_s(raw, "reason"), + description=_s(raw, "description"), + ) @classmethod def from_raw(cls, raw: Raw, region: Optional[str]) -> "Template": @@ -308,6 +331,9 @@ class Webhook: url: str = "" events: list[str] = field(default_factory=list) active: bool = True + secret_version: int = 1 + previous_secret_expires_at: Optional[datetime] = None + lease_lead_seconds: Optional[int] = None created_at: Optional[datetime] = None updated_at: Optional[datetime] = None region: Optional[str] = None @@ -318,12 +344,64 @@ def from_raw(cls, raw: Raw, region: Optional[str]) -> "Webhook": return cls(**_webhook_fields(raw, region)) +@dataclass(kw_only=True) +class WebhookDelivery: + """One delivery of an event to a webhook endpoint (status: pending, delivering, delivered, + failed or refused).""" + + id: str + webhook_id: str = "" + event_id: str = "" + event_type: str = "" + resource_type: str = "" + resource_id: str = "" + status: str = "" + attempts: int = 0 + max_attempts: int = 0 + response_status: Optional[int] = None + last_error: Optional[str] = None + next_attempt_at: Optional[datetime] = None + last_attempt_at: Optional[datetime] = None + delivered_at: Optional[datetime] = None + redelivery_of: Optional[str] = None + created_at: Optional[datetime] = None + region: Optional[str] = None + raw: Raw = field(default_factory=dict) + + @classmethod + def from_raw(cls, raw: Raw, region: Optional[str]) -> "WebhookDelivery": + code = raw.get("response_status") + return cls( + id=str(raw.get("id")), + webhook_id=str(raw.get("webhook_id") or ""), + event_id=str(raw.get("event_id") or ""), + event_type=str(raw.get("event_type") or ""), + resource_type=str(raw.get("resource_type") or ""), + resource_id=str(raw.get("resource_id") or ""), + status=str(raw.get("status") or ""), + attempts=_i(raw, "attempts"), + max_attempts=_i(raw, "max_attempts"), + response_status=int(code) if isinstance(code, int) else None, + last_error=_s(raw, "last_error"), + next_attempt_at=parse_time(raw.get("next_attempt_at")), + last_attempt_at=parse_time(raw.get("last_attempt_at")), + delivered_at=parse_time(raw.get("delivered_at")), + redelivery_of=_s(raw, "redelivery_of"), + created_at=parse_time(raw.get("created_at")), + region=region, + raw=raw, + ) + + def _webhook_fields(raw: Raw, region: Optional[str]) -> dict[str, Any]: return { "id": str(raw.get("id")), "url": str(raw.get("url") or ""), "events": _l(raw, "events"), "active": raw.get("active") is not False, + "secret_version": _i(raw, "secret_version", 1), + "previous_secret_expires_at": parse_time(raw.get("previous_secret_expires_at")), + "lease_lead_seconds": raw.get("lease_lead_seconds") if isinstance(raw.get("lease_lead_seconds"), int) else None, "created_at": parse_time(raw.get("created_at")), "updated_at": parse_time(raw.get("updated_at")), "region": region, @@ -1110,10 +1188,41 @@ class PlanOffer: max_concurrent_boxes: int = 0 max_vcpu_per_box: int = 0 network_egress: bool = False + #: Longest build or lab host lease, in hours; never 0 (Free 1, Pro 4, Team 12, Enterprise custom). max_lease_hours: int = 0 + #: Open build or lab host leases at once; -1 is unlimited. + max_concurrent_leases: int = 0 + #: Most vCPUs one lease may take. + max_vcpu_per_lease: int = 0 + #: Network a lease gets: ``registry`` (package registries only) or ``full``. + lease_network: str = "" + #: Lab hosts the organization may register; -1 is unlimited (per seat when ``lab_hosts_per_seat``). + max_lab_hosts: int = 0 + lab_hosts_per_seat: bool = False + #: Vault key/value stores the organization may create; -1 is unlimited. + max_vault_stores: int = 0 + #: Vault secrets the organization may keep; -1 is unlimited. + max_vault_secrets: int = 0 object_storage_gb: int = 0 overage_allowed: bool = False overage_minor_per_vcpu_hour: int = 0 + #: What a box's network is: ``allowlist`` (Free) or ``open``. + network_mode: str = "" + #: What a vCPU is: ``shared`` (a fair share on a busy host, never above the box's own) or ``dedicated``. + vcpu_kind: str = "" + #: A new paid subscription starts with overage on and this customer spend cap (dollars per period; 0: none). + overage_default_on: bool = False + default_spend_cap_usd: int = 0 + #: The longest a sandbox lives, in hours; -1 is unlimited. + max_session_hours: int = 0 + #: A box may burst to this many times its base vCPUs (0: no burst). + burst_multiplier: int = 0 + #: Workspaces the organization may hold; -1 is unlimited. + max_workspaces: int = 0 + #: A sandbox's port may have a public preview link. + public_previews: bool = False + #: How long the audit log is kept searchable, in days. + audit_retention_days: int = 0 features: list[str] = field(default_factory=list) raw: Raw = field(default_factory=dict) @@ -1131,9 +1240,25 @@ def from_raw(cls, raw: Raw) -> "PlanOffer": max_vcpu_per_box=_i(raw, "max_vcpu_per_box"), network_egress=_b(raw, "network_egress"), max_lease_hours=_i(raw, "max_lease_hours"), + max_concurrent_leases=_i(raw, "max_concurrent_leases"), + max_vcpu_per_lease=_i(raw, "max_vcpu_per_lease"), + lease_network=str(raw.get("lease_network") or ""), + max_lab_hosts=_i(raw, "max_lab_hosts"), + lab_hosts_per_seat=_b(raw, "lab_hosts_per_seat"), + max_vault_stores=_i(raw, "max_vault_stores"), + max_vault_secrets=_i(raw, "max_vault_secrets"), object_storage_gb=_i(raw, "object_storage_gb"), overage_allowed=_b(raw, "overage_allowed"), overage_minor_per_vcpu_hour=_i(raw, "overage_minor_per_vcpu_hour"), + network_mode=str(raw.get("network_mode") or ""), + vcpu_kind=str(raw.get("vcpu_kind") or ""), + overage_default_on=_b(raw, "overage_default_on"), + default_spend_cap_usd=_i(raw, "default_spend_cap_usd"), + max_session_hours=_i(raw, "max_session_hours"), + burst_multiplier=_i(raw, "burst_multiplier"), + max_workspaces=_i(raw, "max_workspaces"), + public_previews=_b(raw, "public_previews"), + audit_retention_days=_i(raw, "audit_retention_days"), features=_l(raw, "features"), raw=raw, ) @@ -1151,6 +1276,10 @@ class PlanState: pending_plan: Optional[str] = None pending_interval: Optional[str] = None pending_effective_at: Optional[datetime] = None + #: Seats that take effect at ``pending_effective_at`` (a seat decrease waits for the period end). + pending_seats: Optional[int] = None + #: The subscription has no card for its renewal. + payment_method_missing: bool = False raw: Raw = field(default_factory=dict) @classmethod @@ -1166,14 +1295,30 @@ def from_raw(cls, raw: Raw) -> "PlanState": pending_plan=_s(raw, "pending_plan"), pending_interval=_s(raw, "pending_interval"), pending_effective_at=parse_time(raw.get("pending_effective_at")), + pending_seats=raw["pending_seats"] if isinstance(raw.get("pending_seats"), int) and not isinstance(raw.get("pending_seats"), bool) else None, + payment_method_missing=_b(raw, "payment_method_missing"), raw=raw, ) @dataclass(kw_only=True) class CreditBalance: + """The credit balance of the usage window. + + ``month`` is the UTC calendar month the usage window starts in. The window itself is + ``period_start`` to ``period_end`` (``resets_at`` is the same moment as ``period_end``): + ``period_kind`` is ``billing_period`` (a paid plan's Stripe period, or a monthly slice of a + yearly one), ``signup_anniversary`` (the Free plan month from one sign-up anniversary to the + next) or ``calendar_month``. ``allowance_prorated`` is true when the included credits are + pro rata because the plan or seats changed in the window, or the window was cut short. + """ + month: str = "" resets_at: Optional[datetime] = None + period_start: Optional[datetime] = None + period_end: Optional[datetime] = None + period_kind: str = "" + allowance_prorated: bool = False included_vcpu_hours: str = "" used_vcpu_hours: str = "" remaining_vcpu_hours: str = "" @@ -1185,6 +1330,10 @@ def from_raw(cls, raw: Raw) -> "CreditBalance": return cls( month=str(raw.get("month") or ""), resets_at=parse_time(raw.get("resets_at")), + period_start=parse_time(raw.get("period_start")), + period_end=parse_time(raw.get("period_end")), + period_kind=str(raw.get("period_kind") or ""), + allowance_prorated=_b(raw, "allowance_prorated"), included_vcpu_hours=str(raw.get("included_vcpu_hours") or ""), used_vcpu_hours=str(raw.get("used_vcpu_hours") or ""), remaining_vcpu_hours=str(raw.get("remaining_vcpu_hours") or ""), @@ -1201,6 +1350,14 @@ class Billing: offer: PlanOffer balance: CreditBalance plans: list[PlanOffer] = field(default_factory=list) + #: Paid seats taken, pending invitations included. + seats_in_use: int = 0 + #: Members suspended because the paid seats fell below the members (``user_id``, ``email``, + #: ``display_name``, ``suspended_at``); restored automatically when seats are bought. + suspended_members: list[Raw] = field(default_factory=list) + #: The seat or plan charge being collected before it applies (``id``, ``kind``, ``status`` + #: ``charging`` or ``authentication_required``, ``hosted_invoice_url``, ...), or None. + open_charge: Optional[Raw] = None raw: Raw = field(default_factory=dict) @classmethod @@ -1210,6 +1367,9 @@ def from_raw(cls, raw: Raw) -> "Billing": offer=PlanOffer.from_raw(_obj(raw, "offer")), balance=CreditBalance.from_raw(_obj(raw, "balance")), plans=[PlanOffer.from_raw(p) for p in raw.get("plans") or [] if isinstance(p, dict)], + seats_in_use=_i(raw, "seats_in_use"), + suspended_members=[m for m in raw.get("suspended_members") or [] if isinstance(m, dict)], + open_charge=raw["open_charge"] if isinstance(raw.get("open_charge"), dict) else None, raw=raw, ) @@ -1238,6 +1398,157 @@ def from_raw(cls, raw: Raw) -> "Checkout": ) +@dataclass(kw_only=True) +class DailyUsage: + """The rolling 24-hour cap of a plan that has one (Free). ``at_cap``: running boxes are paused and + starts refused until ``retry_at``.""" + + window_seconds: int = 0 + used_vcpu_seconds: int = 0 + limit_vcpu_seconds: int = 0 + left_vcpu_seconds: int = 0 + at_cap: bool = False + retry_at: Optional[datetime] = None + + @classmethod + def from_raw(cls, raw: Raw) -> "DailyUsage": + return cls( + window_seconds=_i(raw, "window_seconds"), + used_vcpu_seconds=_i(raw, "used_vcpu_seconds"), + limit_vcpu_seconds=_i(raw, "limit_vcpu_seconds"), + left_vcpu_seconds=_i(raw, "left_vcpu_seconds"), + at_cap=_b(raw, "at_cap"), + retry_at=parse_time(raw.get("retry_at")), + ) + + +@dataclass(kw_only=True) +class PeriodUsage: + """The allowance's billing period (the organization's own anniversary).""" + + starts_at: Optional[datetime] = None + resets_at: Optional[datetime] = None + used_vcpu_seconds: int = 0 + limit_vcpu_seconds: int = 0 + left_vcpu_seconds: int = 0 + + @classmethod + def from_raw(cls, raw: Raw) -> "PeriodUsage": + return cls( + starts_at=parse_time(raw.get("starts_at")), + resets_at=parse_time(raw.get("resets_at")), + used_vcpu_seconds=_i(raw, "used_vcpu_seconds"), + limit_vcpu_seconds=_i(raw, "limit_vcpu_seconds"), + left_vcpu_seconds=_i(raw, "left_vcpu_seconds"), + ) + + +@dataclass(kw_only=True) +class RampUsage: + """The new-account ramp of the Free plan. ``lift_with`` are the signals that lift it now + (``github_account``, ``card``, ``operator_approval``); empty when it is not active.""" + + active: bool = False + ends_at: Optional[datetime] = None + max_boxes: int = 0 + daily_vcpu_seconds: int = 0 + trust_signals: list[str] = field(default_factory=list) + lift_with: list[str] = field(default_factory=list) + + @classmethod + def from_raw(cls, raw: Raw) -> "RampUsage": + return cls( + active=_b(raw, "active"), + ends_at=parse_time(raw.get("ends_at")), + max_boxes=_i(raw, "max_boxes"), + daily_vcpu_seconds=_i(raw, "daily_vcpu_seconds"), + trust_signals=_l(raw, "trust_signals"), + lift_with=_l(raw, "lift_with"), + ) + + +@dataclass(kw_only=True) +class UsageLimits: + """The plan's limits as the usage answer carries them (vCPU-seconds where named so; -1 is unlimited).""" + + plan: str = "" + max_boxes: int = 0 + vcpu_seconds: int = 0 + gpus: bool = False + fair_use: bool = False + daily_vcpu_seconds: int = 0 + ramp_days: int = 0 + ramp_max_boxes: int = 0 + ramp_daily_vcpu_seconds: int = 0 + trust_github_min_age_days: int = 0 + + @classmethod + def from_raw(cls, raw: Raw) -> "UsageLimits": + return cls( + plan=str(raw.get("plan") or ""), + max_boxes=_i(raw, "max_boxes"), + vcpu_seconds=_i(raw, "vcpu_seconds"), + gpus=_b(raw, "gpus"), + fair_use=_b(raw, "fair_use"), + daily_vcpu_seconds=_i(raw, "daily_vcpu_seconds"), + ramp_days=_i(raw, "ramp_days"), + ramp_max_boxes=_i(raw, "ramp_max_boxes"), + ramp_daily_vcpu_seconds=_i(raw, "ramp_daily_vcpu_seconds"), + trust_github_min_age_days=_i(raw, "trust_github_min_age_days"), + ) + + +@dataclass(kw_only=True) +class Identity: + """What a login linked (``GET /api/v1/sandscale/identity``).""" + + github_linked: bool = False + github_linked_at: Optional[datetime] = None + #: The linked account is older than the plan's age: it lifts the new-account ramp. + github_account_old_enough: bool = False + card_verified: bool = False + #: ``account_exists`` when the last card was refused because another login holds it. + card_refusal: Optional[str] = None + raw: Raw = field(default_factory=dict) + + @classmethod + def from_raw(cls, raw: Raw) -> "Identity": + return cls( + github_linked=_b(raw, "github_linked"), + github_linked_at=parse_time(raw.get("github_linked_at")), + github_account_old_enough=_b(raw, "github_account_old_enough"), + card_verified=_b(raw, "card_verified"), + card_refusal=_s(raw, "card_refusal") or None, + raw=raw, + ) + + +@dataclass(kw_only=True) +class GithubLinkStart: + """A started GitHub link: send the person to ``authorize_url``, then ``github_complete`` with the code and ``state``.""" + + authorize_url: str = "" + state: str = "" + expires_at: Optional[datetime] = None + + @classmethod + def from_raw(cls, raw: Raw) -> "GithubLinkStart": + return cls(authorize_url=str(raw.get("authorize_url") or ""), state=str(raw.get("state") or ""), expires_at=parse_time(raw.get("expires_at"))) + + +@dataclass(kw_only=True) +class CodeModeUsage: + """Code mode runs (scripts and searches) and the vCPU-seconds they were charged: each run's CPU + time rounded up to the whole second.""" + + runs: int = 0 + vcpu_seconds: int = 0 + + @classmethod + def from_raw(cls, raw: Raw) -> "CodeModeUsage": + return cls(runs=_i(raw, "runs"), vcpu_seconds=_i(raw, "vcpu_seconds")) + + @dataclass(kw_only=True) class Usage: month: str = "" @@ -1245,12 +1556,28 @@ class Usage: vcpu_seconds_left: int = 0 running_boxes: int = 0 running_by_region: dict[str, int] = field(default_factory=dict) + limits: Optional[UsageLimits] = None + #: Set when the organization has a daily cap. + daily: Optional[DailyUsage] = None + #: Set for the Free plan. + period: Optional[PeriodUsage] = None + ramp: Optional[RampUsage] = None + #: ``held``, ``unclaimed`` or ``held_by_another`` (a start is refused ``free_already_claimed``); Free only. + free_claim: Optional[str] = None + #: Code mode runs of the same window; their vCPU-seconds are part of ``vcpu_seconds_used``. + code_mode: Optional[CodeModeUsage] = None raw: Raw = field(default_factory=dict) @classmethod def from_raw(cls, raw: Raw) -> "Usage": by = _obj(raw, "running_by_region") return cls( + limits=UsageLimits.from_raw(_obj(raw, "limits")) if raw.get("limits") else None, + daily=DailyUsage.from_raw(_obj(raw, "daily")) if raw.get("daily") else None, + period=PeriodUsage.from_raw(_obj(raw, "period")) if raw.get("period") else None, + ramp=RampUsage.from_raw(_obj(raw, "ramp")) if raw.get("ramp") else None, + free_claim=_s(_obj(raw, "free"), "claim"), + code_mode=CodeModeUsage.from_raw(_obj(raw, "code_mode")) if raw.get("code_mode") else None, month=str(raw.get("month") or ""), vcpu_seconds_used=_i(raw, "vcpu_seconds_used"), vcpu_seconds_left=_i(raw, "vcpu_seconds_left"), diff --git a/src/sandscale/errors.py b/src/sandscale/errors.py index 62fdf14..f3fba97 100644 --- a/src/sandscale/errors.py +++ b/src/sandscale/errors.py @@ -14,6 +14,8 @@ import json import re import time +from dataclasses import dataclass, field +from datetime import datetime from typing import Any, Mapping, Optional @@ -74,17 +76,153 @@ class ConflictError(SandscaleError): """409: the resource is not in a state that allows the call (paused, ended, busy).""" +@dataclass(frozen=True) +class LimitInfo: + """What a 402 limit answer names in its details: the plan, which limit refused and, when the + server sent them, the value in use and the largest the plan allows (``max_*``).""" + + plan: Optional[str] = None + limit: Optional[str] = None + used: Optional[int] = None + max: Optional[int] = None + + +@dataclass(frozen=True) +class PlanRefusal: + """What a ``feature_not_in_plan`` answer names: the feature, the lowest plan that includes it + and the sentences the server wrote for the customer. Every field is the server's, as sent.""" + + #: The price book feature, e.g. ``sandscale.sso``. + feature: Optional[str] = None + #: The feature's name, e.g. ``Single sign-on``. + feature_title: Optional[str] = None + #: What the feature gives, one sentence. + gives: Optional[str] = None + #: The lowest plan that includes it, e.g. ``team``. + plan: Optional[str] = None + #: How the customer reads that plan, e.g. ``Team``. + plan_name: Optional[str] = None + + class LimitExceededError(SandscaleError): """A plan, quota or usage limit refused the call (402, or a quota or limit code).""" + #: The plan and limit the answer names (402 limit codes), as sent; empty when it named none. + limit_info: LimitInfo = LimitInfo() + + +def _when(value: Any) -> Optional[datetime]: + if not isinstance(value, str): + return None + try: + return datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return None + + +def _n(value: Any) -> Optional[int]: + return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None + + +@dataclass(frozen=True) +class FairUseLimit: + """The ledger's refusal as the server sent it (``limit`` in the answer of a refused start).""" + + #: ``daily_vcpu_hours``, ``vcpu_hours``, ``free_plan``, ``ramp_boxes`` or ``ramp_daily_vcpu_hours``. + limit: Optional[str] = None + plan: Optional[str] = None + allowed: Optional[int] = None + used: Optional[int] = None + allowed_vcpu_seconds: Optional[int] = None + used_vcpu_seconds: Optional[int] = None + #: When the rolling 24-hour cap next has room. + retry_at: Optional[datetime] = None + #: When the Free allowance renews (the organization's billing anniversary). + resets_at: Optional[datetime] = None + #: When the new-account ramp ends by itself. + ramp_ends_at: Optional[datetime] = None + #: Trust signals that lift the ramp now: ``github_account``, ``card``, ``operator_approval``. + lift: tuple[str, ...] = field(default_factory=tuple) + + @classmethod + def from_raw(cls, raw: Optional[Mapping[str, Any]]) -> "FairUseLimit": + r = raw or {} + lift = r.get("lift") + return cls( + limit=r["limit"] if isinstance(r.get("limit"), str) else None, + plan=r["plan"] if isinstance(r.get("plan"), str) else None, + allowed=_n(r.get("allowed")), + used=_n(r.get("used")), + allowed_vcpu_seconds=_n(r.get("allowed_vcpu_seconds")), + used_vcpu_seconds=_n(r.get("used_vcpu_seconds")), + retry_at=_when(r.get("retry_at")), + resets_at=_when(r.get("resets_at")), + ramp_ends_at=_when(r.get("ramp_ends_at")), + lift=tuple(x for x in lift if isinstance(x, str)) if isinstance(lift, list) else (), + ) + + +class _FreeLimit(LimitExceededError): + """Base of the Free fair-use refusals: ``fair_use`` is the ledger's refusal as sent.""" + + def __init__(self, status: int, code: str, message: str, *, limit: Optional[Mapping[str, Any]] = None, **extra: Any) -> None: + super().__init__(status, code, message, **extra) + self.fair_use = FairUseLimit.from_raw(limit) + + +class FreeDailyLimitError(_FreeLimit): + """429 ``free_daily_limit``: the Free plan's vCPU-hours of the last 24 hours are used. Running boxes are + paused (nothing is deleted); starts and resumes work again at ``retry_at``.""" + + @property + def retry_at(self) -> Optional[datetime]: + return self.fair_use.retry_at + + +class FreeMonthlyLimitError(_FreeLimit): + """402 ``free_monthly_limit``: the Free allowance of this billing period is used; it renews at ``resets_at``.""" + + @property + def resets_at(self) -> Optional[datetime]: + return self.fair_use.resets_at + + +class FreeNewAccountLimitError(_FreeLimit): + """429 ``free_new_account_limit``: a new account's boxes or daily vCPU-hours are capped. ``lift`` names the + trust signals that lift it now, ``ramp_ends_at`` is when it ends by itself, ``retry_at`` is set for the daily cap.""" + + @property + def lift(self) -> tuple[str, ...]: + return self.fair_use.lift + + @property + def ramp_ends_at(self) -> Optional[datetime]: + return self.fair_use.ramp_ends_at + + @property + def retry_at(self) -> Optional[datetime]: + return self.fair_use.retry_at + class RateLimitError(LimitExceededError): """429: too many requests; retry after ``retry_after`` seconds.""" +class FreeAlreadyClaimedError(PermissionDeniedError): + """403 ``free_already_claimed``: another organization of your login holds the Free plan.""" + + +class AccountExistsError(ConflictError): + """409 ``account_exists``: one person has one Sandscale login; sign in to your existing account. The + server gives the same answer whichever of the address, a GitHub account or a card matched.""" + + class EntitlementError(SandscaleError): """The organization's plan does not include this, or payment is required.""" + #: For ``feature_not_in_plan``: the feature and the plan that includes it, as the server sent them. + plan_refusal: PlanRefusal = PlanRefusal() + class RegionError(SandscaleError): """The call went to a region that cannot serve it (wrong region, region unavailable).""" @@ -134,10 +272,21 @@ def __init__(self, message: str) -> None: } +_FAIR_USE: dict[str, type[SandscaleError]] = { + "free_daily_limit": FreeDailyLimitError, + "free_monthly_limit": FreeMonthlyLimitError, + "free_new_account_limit": FreeNewAccountLimitError, + "free_already_claimed": FreeAlreadyClaimedError, + "account_exists": AccountExistsError, +} + + def error_for(status: int, code: str, message: str, **extra: Any) -> SandscaleError: """Sorts a server answer into its error class.""" cls: type[SandscaleError] - if _KILL_SWITCH.search(code): + if code in _FAIR_USE: + cls = _FAIR_USE[code] + elif _KILL_SWITCH.search(code): cls = KillSwitchError elif code == "wrong_region" or code.startswith("region_"): cls = RegionError @@ -159,11 +308,20 @@ def error_for(status: int, code: str, message: str, **extra: Any) -> SandscaleEr cls = ServerError else: cls = SandscaleError - return cls(status, code, message, **extra) + if not issubclass(cls, _FreeLimit): + extra.pop("limit", None) + plan_refusal = extra.pop("plan_refusal", None) + limit_info = extra.pop("limit_info", None) + err = cls(status, code, message, **extra) + if isinstance(err, EntitlementError) and plan_refusal is not None: + err.plan_refusal = plan_refusal + if isinstance(err, LimitExceededError) and limit_info is not None: + err.limit_info = limit_info + return err def parse_error(status: int, reason: str, text: str, headers: Mapping[str, str]) -> SandscaleError: - """Reads Keystone's error envelope ``{"error": {"code", "message", "request_id", + """Reads Sandscale's error envelope ``{"error": {"code", "message", "request_id", "detail" | "details"}}``; the ``wrong_region`` answer also carries ``code`` and ``region`` at the top level.""" code = f"http_{status}" @@ -187,6 +345,32 @@ def parse_error(status: int, reason: str, text: str, headers: Mapping[str, str]) for key in ("detail", "details"): if err.get(key) is not None: extra["details"] = err[key] + limit = body.get("limit") + if limit is None and isinstance(extra.get("details"), dict): + limit = extra["details"].get("limit") + if isinstance(limit, dict): + extra["limit"] = limit + det = extra["details"] if isinstance(extra.get("details"), dict) else {} + + def pick(key: str) -> Any: + return err.get(key) if err.get(key) is not None else det.get(key) + + def as_text(value: Any) -> Optional[str]: + return value if isinstance(value, str) and value != "" else None + + refusal = PlanRefusal( + feature=as_text(pick("feature")), + feature_title=as_text(pick("feature_title")), + gives=as_text(pick("gives")), + plan=as_text(pick("plan")), + plan_name=as_text(pick("plan_name")), + ) + if refusal != PlanRefusal(): + extra["plan_refusal"] = refusal + max_key = next((k for k, v in det.items() if k.startswith("max_") and isinstance(v, (int, float)) and not isinstance(v, bool)), None) + info = LimitInfo(plan=as_text(det.get("plan")), limit=as_text(det.get("limit")) or as_text(det.get("field")), used=_n(det.get("used")), max=_n(det[max_key]) if max_key else None) + if info != LimitInfo(): + extra["limit_info"] = info region = err.get("region") or body.get("region") or body.get("home_region") if isinstance(region, str): extra["region"] = region diff --git a/src/sandscale/integrations/__init__.py b/src/sandscale/integrations/__init__.py new file mode 100644 index 0000000..a86e00c --- /dev/null +++ b/src/sandscale/integrations/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""Adapters that let agent frameworks run their code in Sandscale sandboxes. + +- ``sandscale.integrations.langchain``: a LangChain Deep Agents sandbox backend + (``SandscaleSandbox``) and a LangChain toolkit (``SandscaleToolkit``). Install + ``sandscale[langchain]``. +- ``sandscale.integrations.openai_agents``: a sandbox client for the OpenAI Agents SDK's + ``SandboxAgent`` (``SandscaleSandboxClient``). Install ``sandscale[openai-agents]``. + +Each adapter only calls the Sandscale SDK: the server decides plans, limits and policy as for +any other caller, and the API key never enters the sandbox. +""" diff --git a/src/sandscale/integrations/langchain.py b/src/sandscale/integrations/langchain.py new file mode 100644 index 0000000..f98887f --- /dev/null +++ b/src/sandscale/integrations/langchain.py @@ -0,0 +1,243 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""LangChain adapters for Sandscale (``pip install "sandscale[langchain]"``). + +``SandscaleSandbox`` is a Deep Agents sandbox backend: Deep Agents' file tools (ls, read, write, +edit, glob, grep) and ``execute`` run in a Sandscale sandbox:: + + from deepagents import create_deep_agent + from sandscale.integrations.langchain import SandscaleSandbox + + with SandscaleSandbox.create(template="builtin:python") as backend: + agent = create_deep_agent(model="...", backend=backend) + +``SandscaleToolkit`` gives any LangChain agent three tools over one sandbox: run a command, write +a file and read a file:: + + from sandscale.integrations.langchain import SandscaleToolkit + + with SandscaleToolkit.create(template="builtin:node") as toolkit: + tools = toolkit.get_tools() +""" + +from __future__ import annotations + +import posixpath +import time +from typing import Any, Callable, Optional, TypeVar + +from .. import Sandscale +from ..errors import RateLimitError, SandscaleError +from ..models import Sandbox + +try: + from deepagents.backends.protocol import ExecuteResponse, FileDownloadResponse, FileUploadResponse + from deepagents.backends.sandbox import BaseSandbox +except ImportError as e: # pragma: no cover - exercised only without the extra + raise ImportError('sandscale.integrations.langchain needs Deep Agents: pip install "sandscale[langchain]"') from e + +from langchain_core.tools import BaseTool, BaseToolkit, StructuredTool + +#: Commands run below this directory unless they change it; it is the sandbox's workspace. +WORKSPACE = "/workspace" +#: The default timeout of one command, in seconds. +DEFAULT_TIMEOUT = 300 +#: The toolkit's tools cut output longer than this for the model (the server bounds a command's +#: output itself; the Deep Agents backend passes it whole, because its file tools read through it). +MAX_OUTPUT = 100_000 + +T = TypeVar("T") + + +def _rate_limited_retry(call: Callable[[], T]) -> T: + """Runs ``call``, waiting out up to 5 rate limit refusals (429): a refused request never ran, so + sending it again cannot run it twice.""" + for attempt in range(6): + try: + return call() + except RateLimitError as e: + if attempt == 5: + raise + time.sleep(min(e.retry_after, 30.0) if e.retry_after > 0 else 0.5 * 2**attempt) + raise AssertionError("unreachable") + + +def _file_error(e: SandscaleError) -> str: + """The Deep Agents error code of a refused file operation an agent can act on.""" + if e.status == 404 or e.code in ("not_found", "file_not_found"): + return "file_not_found" + if e.status == 403: + return "permission_denied" + if e.code in ("not_a_file", "is_directory"): + return "is_directory" + return "invalid_path" + + +def _absolute(path: str) -> str: + return path if path.startswith("/") else posixpath.join(WORKSPACE, path) + + +class _Box: + """One sandbox and the client that reaches it; ``owned`` boxes are stopped on close.""" + + def __init__(self, client: Sandscale, sandbox_id: str, region: Optional[str], owned: bool, owns_client: bool) -> None: + self.client, self.sandbox_id, self.region, self.owned, self.owns_client = client, sandbox_id, region, owned, owns_client + + @classmethod + def start(cls, client: Optional[Sandscale], create: dict[str, Any]) -> "_Box": + owns_client = client is None + c = client or Sandscale() + box: Sandbox = _rate_limited_retry(lambda: c.sandboxes.create(**create)) + return cls(c, box.id, box.region, owned=True, owns_client=owns_client) + + def run(self, command: str, timeout: Optional[int]) -> tuple[str, int, bool]: + run = _rate_limited_retry( + lambda: self.client.sandboxes.run( + self.sandbox_id, command, workdir=WORKSPACE, timeout=timeout or DEFAULT_TIMEOUT, region=self.region + ) + ) + output = run.stdout + if run.stderr: + output = f"{output}\n{run.stderr}" if output else run.stderr + if run.error: + output = f"{output}\n{run.error}" if output else run.error + return output, run.exit_code, False + + def close(self) -> None: + try: + if self.owned: + self.client.sandboxes.stop(self.sandbox_id, region=self.region) + finally: + if self.owns_client: + self.client.close() + + +class SandscaleSandbox(BaseSandbox): + """A Deep Agents sandbox backend over one Sandscale sandbox. + + Pass an existing sandbox (``SandscaleSandbox(client, sandbox_id)``, left running on close) or + start one with ``SandscaleSandbox.create(**create_kwargs)`` (stopped on close; the keyword + arguments are ``Sandscale().sandboxes.create``'s, for example ``template``, ``network`` and + ``timeout_seconds``). Paths are absolute, as Deep Agents gives them; a relative one is ``invalid_path``. + """ + + def __init__(self, client: Sandscale, sandbox_id: str, *, region: Optional[str] = None) -> None: + self._box = _Box(client, sandbox_id, region, owned=False, owns_client=False) + + @classmethod + def create(cls, *, client: Optional[Sandscale] = None, **create_kwargs: Any) -> "SandscaleSandbox": + self = cls.__new__(cls) + self._box = _Box.start(client, create_kwargs) + return self + + @property + def id(self) -> str: + return self._box.sandbox_id + + def execute(self, command: str, *, timeout: Optional[int] = None) -> ExecuteResponse: + output, exit_code, truncated = self._box.run(command, timeout) + return ExecuteResponse(output=output, exit_code=exit_code, truncated=truncated) + + def upload_files(self, files: list[tuple[str, bytes]]) -> list[FileUploadResponse]: + out: list[FileUploadResponse] = [] + for path, content in files: + if not path.startswith("/"): + out.append(FileUploadResponse(path=path, error="invalid_path")) + continue + try: + _rate_limited_retry( + lambda: self._box.client.sandboxes.upload(self.id, path, content, region=self._box.region) + ) + out.append(FileUploadResponse(path=path, error=None)) + except SandscaleError as e: + if e.status >= 500 or e.status == 0: + raise + out.append(FileUploadResponse(path=path, error=_file_error(e))) + return out + + def download_files(self, paths: list[str]) -> list[FileDownloadResponse]: + out: list[FileDownloadResponse] = [] + for path in paths: + if not path.startswith("/"): + out.append(FileDownloadResponse(path=path, content=None, error="invalid_path")) + continue + try: + data = _rate_limited_retry( + lambda: self._box.client.sandboxes.download(self.id, path, region=self._box.region) + ) + out.append(FileDownloadResponse(path=path, content=data, error=None)) + except SandscaleError as e: + if e.status >= 500 or e.status == 0: + raise + out.append(FileDownloadResponse(path=path, content=None, error=_file_error(e))) + return out + + def close(self) -> None: + """Stops the sandbox if this backend started it.""" + self._box.close() + + def __enter__(self) -> "SandscaleSandbox": + return self + + def __exit__(self, *exc: object) -> None: + self.close() + + +class SandscaleToolkit(BaseToolkit): + """LangChain tools over one Sandscale sandbox: ``sandscale_run``, ``sandscale_write_file`` and + ``sandscale_read_file``. Build it on an existing sandbox (``SandscaleToolkit.on(client, + sandbox_id)``) or start one (``SandscaleToolkit.create(**create_kwargs)``, stopped on close).""" + + model_config = {"arbitrary_types_allowed": True} + + box: Any = None + + @classmethod + def on(cls, client: Sandscale, sandbox_id: str, *, region: Optional[str] = None) -> "SandscaleToolkit": + return cls(box=_Box(client, sandbox_id, region, owned=False, owns_client=False)) + + @classmethod + def create(cls, *, client: Optional[Sandscale] = None, **create_kwargs: Any) -> "SandscaleToolkit": + return cls(box=_Box.start(client, create_kwargs)) + + @property + def sandbox_id(self) -> str: + return str(self.box.sandbox_id) + + def get_tools(self) -> list[BaseTool]: + box: _Box = self.box + + def sandscale_run(command: str, timeout_seconds: int = DEFAULT_TIMEOUT) -> str: + """Run a shell command in the sandbox (working directory /workspace) and return its exit code and output.""" + output, exit_code, _ = box.run(command, timeout_seconds) + truncated = len(output) > MAX_OUTPUT + if truncated: + output = output[:MAX_OUTPUT] + return f"exit code {exit_code}" + (" (output truncated)" if truncated else "") + (f"\n{output}" if output else "") + + def sandscale_write_file(path: str, content: str) -> str: + """Write a UTF-8 text file in the sandbox; a relative path is under /workspace.""" + box.client.sandboxes.upload(box.sandbox_id, _absolute(path), content, region=box.region) + return f"wrote {len(content.encode('utf-8'))} bytes to {_absolute(path)}" + + def sandscale_read_file(path: str) -> str: + """Read a UTF-8 text file from the sandbox; a relative path is under /workspace.""" + data: bytes = box.client.sandboxes.download(box.sandbox_id, _absolute(path), region=box.region) + text: str = data.decode("utf-8", errors="replace") + return text if len(text) <= MAX_OUTPUT else text[:MAX_OUTPUT] + "\n[truncated]" + + return [ + StructuredTool.from_function(sandscale_run), + StructuredTool.from_function(sandscale_write_file), + StructuredTool.from_function(sandscale_read_file), + ] + + def close(self) -> None: + """Stops the sandbox if this toolkit started it.""" + self.box.close() + + def __enter__(self) -> "SandscaleToolkit": + return self + + def __exit__(self, *exc: object) -> None: + self.close() diff --git a/src/sandscale/integrations/openai_agents.py b/src/sandscale/integrations/openai_agents.py new file mode 100644 index 0000000..f2b4c56 --- /dev/null +++ b/src/sandscale/integrations/openai_agents.py @@ -0,0 +1,381 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""A Sandscale sandbox client for the OpenAI Agents SDK (``pip install "sandscale[openai-agents]"``). + +A ``SandboxAgent`` runs its shell and file tools in a Sandscale sandbox (a Firecracker microVM):: + + from agents import Runner + from agents.run import RunConfig + from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig + from sandscale.integrations.openai_agents import SandscaleSandboxClient, SandscaleSandboxClientOptions + + agent = SandboxAgent(name="builder", instructions="...", default_manifest=Manifest()) + result = await Runner.run(agent, "Build it", run_config=RunConfig(sandbox=SandboxRunConfig( + client=SandscaleSandboxClient(), + options=SandscaleSandboxClientOptions(template="builtin:python", timeout_seconds=1800), + ))) + +The workspace root is ``/workspace``. Saved workspaces are tar archives of it (``persist_workspace``); +an exposed port is published as a public preview link (Sandscale Pro and up, on a cell with a preview +domain). Sandbox-local users are not supported: commands run as the sandbox's user. +""" + +from __future__ import annotations + +import asyncio +import io +import math +import time +import uuid +from pathlib import Path +from typing import Any, Callable, Literal, Optional, TypeVar +from urllib.parse import urlsplit + +from .. import Sandscale +from ..errors import RateLimitError, SandscaleError + +try: + from agents.sandbox.errors import ( + ConfigurationError, + ErrorCode, + ExecTimeoutError, + ExecTransportError, + ExposedPortUnavailableError, + WorkspaceArchiveReadError, + WorkspaceArchiveWriteError, + WorkspaceReadNotFoundError, + ) + from agents.sandbox.manifest import Manifest + from agents.sandbox.session import SandboxSession, SandboxSessionState + from agents.sandbox.session.base_sandbox_session import BaseSandboxSession + from agents.sandbox.session.manager import Instrumentation + from agents.sandbox.session.runtime_helpers import RESOLVE_WORKSPACE_PATH_HELPER, RuntimeHelperScript + from agents.sandbox.session.sandbox_client import BaseSandboxClient, BaseSandboxClientOptions + from agents.sandbox.snapshot import SnapshotBase, SnapshotSpec, resolve_snapshot + from agents.sandbox.types import ExecResult, ExposedPortEndpoint, User + from agents.sandbox.workspace_paths import sandbox_path_str +except ImportError as e: # pragma: no cover - exercised only without the extra + raise ImportError( + 'sandscale.integrations.openai_agents needs the OpenAI Agents SDK: pip install "sandscale[openai-agents]"' + ) from e + +#: The sandbox's workspace, the manifest root of every Sandscale session. +WORKSPACE_ROOT = "/workspace" +_DEFAULT_MANIFEST_ROOT = str(Manifest.model_fields["root"].default) +#: The default timeout of one command when the SDK gives none, in seconds. +DEFAULT_EXEC_TIMEOUT = 300 + +T = TypeVar("T") + + +def _rate_limited_retry(call: Callable[[], T]) -> T: + """Runs ``call``, waiting out up to 5 rate limit refusals (429): a refused request never ran, so + sending it again cannot run it twice.""" + for attempt in range(6): + try: + return call() + except RateLimitError as e: + if attempt == 5: + raise + time.sleep(min(e.retry_after, 30.0) if e.retry_after > 0 else 0.5 * 2**attempt) + raise AssertionError("unreachable") + + +def _manifest(manifest: Optional[Manifest]) -> Manifest: + if manifest is None: + return Manifest(root=WORKSPACE_ROOT) + if manifest.root == _DEFAULT_MANIFEST_ROOT: + return manifest.model_copy(update={"root": WORKSPACE_ROOT}) + return manifest + + +def _retryable(e: BaseException) -> Optional[bool]: + if isinstance(e, SandscaleError): + return e.status in (0, 408, 425, 429, 500, 502, 503, 504) + return None + + +class SandscaleSandboxClientOptions(BaseSandboxClientOptions): + """How a session's sandbox is started: the fields of ``Sandscale().sandboxes.create``.""" + + type: Literal["sandscale"] = "sandscale" + template: Optional[str] = None + cpu_count: Optional[int] = None + memory_mb: Optional[int] = None + disk_mb: Optional[int] = None + timeout_seconds: Optional[int] = None + network: Optional[str] = None + env: Optional[dict[str, str]] = None + region: Optional[str] = None + exposed_ports: tuple[int, ...] = () + + +class SandscaleSandboxSessionState(SandboxSessionState): + """Serializable state of a Sandscale session: the sandbox it runs in and how to start another.""" + + type: Literal["sandscale"] = "sandscale" + sandbox_id: str = "" + region: Optional[str] = None + template: Optional[str] = None + cpu_count: Optional[int] = None + memory_mb: Optional[int] = None + disk_mb: Optional[int] = None + timeout_seconds: Optional[int] = None + network: Optional[str] = None + env: Optional[dict[str, str]] = None + + +class SandscaleSandboxSession(BaseSandboxSession): + """A sandbox session backed by one Sandscale sandbox.""" + + state: SandscaleSandboxSessionState + + def __init__(self, *, state: SandscaleSandboxSessionState, client: Sandscale) -> None: + self.state = state + self._client = client + + # --- backend lifecycle ----------------------------------------------------------------- + + async def _ensure_sandbox(self) -> str: + if not self.state.sandbox_id: + fields = { + "template": self.state.template, + "cpu_count": self.state.cpu_count, + "memory_mb": self.state.memory_mb, + "disk_mb": self.state.disk_mb, + "timeout_seconds": self.state.timeout_seconds, + "network": self.state.network, + "env": self.state.env, + "region": self.state.region, + "labels": {"openai-agents-session": self.state.session_id.hex}, + } + # One key per start, so a retried request starts one sandbox and a resume after the + # sandbox ended starts a new one. + key = f"openai-agents-{uuid.uuid4().hex}" + given: dict[str, Any] = {k: v for k, v in fields.items() if v is not None} + box = await asyncio.to_thread( + _rate_limited_retry, lambda: self._client.sandboxes.create(idempotency_key=key, **given) + ) + self.state.sandbox_id, self.state.region = box.id, box.region + self.state.workspace_root_ready = False + return self.state.sandbox_id + + async def running(self) -> bool: + if not self.state.sandbox_id: + return False + try: + box = await asyncio.to_thread(_rate_limited_retry, lambda: self._client.sandboxes.get(self.state.sandbox_id, region=self.state.region)) + except SandscaleError: + return False + return box.status == "running" + + async def shutdown(self) -> None: + """Stops the sandbox (best effort: a sandbox already gone is not an error).""" + if not self.state.sandbox_id: + return + try: + await asyncio.to_thread(_rate_limited_retry, lambda: self._client.sandboxes.stop(self.state.sandbox_id, region=self.state.region)) + except SandscaleError as e: + if e.status not in (404, 409, 410): + raise + + # --- commands ---------------------------------------------------------------------------- + + def supports_pty(self) -> bool: + return False + + def _reject_user(self, op: Literal["exec", "read", "write"], user: str | User) -> None: + name = user.name if isinstance(user, User) else user + raise ConfigurationError( + message=f"SandscaleSandboxSession does not support sandbox-local users; `{op}` must be called without `user`", + error_code=ErrorCode.SANDBOX_CONFIG_INVALID, + op=op, + context={"backend": "sandscale", "user": name}, + ) + + def _prepare_exec_command(self, *command: str | Path, shell: bool | list[str], user: str | User | None) -> list[str]: + if user is not None: + self._reject_user("exec", user) + return super()._prepare_exec_command(*command, shell=shell, user=user) + + async def _exec_internal(self, *command: str | Path, timeout: float | None = None) -> ExecResult: + argv = [str(part) for part in command] + if not argv: + return ExecResult(stdout=b"", stderr=b"", exit_code=0) + sandbox_id = await self._ensure_sandbox() + seconds = max(1, math.ceil(timeout)) if timeout else DEFAULT_EXEC_TIMEOUT + try: + run = await asyncio.to_thread(_rate_limited_retry, lambda: self._client.sandboxes.run(sandbox_id, + argv, + workdir=self.state.manifest.root, + timeout=seconds, + region=self.state.region,)) + except SandscaleError as e: + raise ExecTransportError( + command=argv, context={"backend": "sandscale", "sandbox_id": sandbox_id}, cause=e, retryable=_retryable(e) + ) from e + if run.timed_out: + raise ExecTimeoutError(command=argv, timeout_s=timeout, context={"backend": "sandscale", "sandbox_id": sandbox_id}) + stderr = run.stderr if not run.error else f"{run.stderr}\n{run.error}" if run.stderr else run.error + return ExecResult(stdout=run.stdout.encode("utf-8"), stderr=stderr.encode("utf-8"), exit_code=run.exit_code) + + # --- files ------------------------------------------------------------------------------- + + async def _validate_path_access(self, path: Path | str, *, for_write: bool = False) -> Path: + return await self._validate_remote_path_access(path, for_write=for_write) + + def _runtime_helpers(self) -> tuple[RuntimeHelperScript, ...]: + return (RESOLVE_WORKSPACE_PATH_HELPER,) + + async def read(self, path: Path, *, user: str | User | None = None) -> io.IOBase: + if user is not None: + self._reject_user("read", user) + normalized = await self._validate_path_access(path) + sandbox_id = await self._ensure_sandbox() + try: + data = await asyncio.to_thread(_rate_limited_retry, lambda: self._client.sandboxes.download(sandbox_id, sandbox_path_str(normalized), region=self.state.region)) + except SandscaleError as e: + if e.status == 404 or e.code in ("not_found", "file_not_found"): + raise WorkspaceReadNotFoundError(path=normalized) from None + raise WorkspaceArchiveReadError(path=normalized, cause=e, retryable=_retryable(e)) from e + return io.BytesIO(data) + + async def write(self, path: Path, data: io.IOBase, *, user: str | User | None = None) -> None: + if user is not None: + self._reject_user("write", user) + normalized = await self._validate_path_access(path, for_write=True) + payload = data.read() + if isinstance(payload, str): + payload = payload.encode("utf-8") + sandbox_id = await self._ensure_sandbox() + try: + await asyncio.to_thread(_rate_limited_retry, lambda: self._client.sandboxes.upload(sandbox_id, sandbox_path_str(normalized), bytes(payload), region=self.state.region)) + except SandscaleError as e: + raise WorkspaceArchiveWriteError(path=normalized, cause=e, retryable=_retryable(e)) from e + + # --- saved workspaces ---------------------------------------------------------------------- + + def _archive_path(self) -> str: + return f"/tmp/openai-agents-{self.state.session_id.hex}.tar" + + async def persist_workspace(self) -> io.IOBase: + root = self._workspace_root_path() + sandbox_id = await self._ensure_sandbox() + archive = self._archive_path() + excludes = [f"--exclude=./{p.as_posix()}" for p in sorted(self._persist_workspace_skip_relpaths(), key=lambda p: p.as_posix())] + result = await self.exec("tar", "cf", archive, "--no-wildcards", *excludes, "-C", root.as_posix(), ".", shell=False) + if not result.ok(): + raise WorkspaceArchiveReadError(path=root, context={"backend": "sandscale", "stderr": result.stderr[-500:].decode("utf-8", "replace")}) + try: + data = await asyncio.to_thread(_rate_limited_retry, lambda: self._client.sandboxes.download(sandbox_id, archive, region=self.state.region)) + except SandscaleError as e: + raise WorkspaceArchiveReadError(path=root, cause=e, retryable=_retryable(e)) from e + finally: + await self.exec("rm", "-f", archive, shell=False) + return io.BytesIO(data) + + async def hydrate_workspace(self, data: io.IOBase) -> None: + root = self._workspace_root_path() + raw = data.read() + if isinstance(raw, str): + raw = raw.encode("utf-8") + sandbox_id = await self._ensure_sandbox() + archive = self._archive_path() + try: + await asyncio.to_thread(_rate_limited_retry, lambda: self._client.sandboxes.upload(sandbox_id, archive, bytes(raw), region=self.state.region)) + except SandscaleError as e: + raise WorkspaceArchiveWriteError(path=root, cause=e, retryable=_retryable(e)) from e + try: + await self.mkdir(root, parents=True) + result = await self.exec("tar", "xf", archive, "-C", root.as_posix(), "--no-same-owner", shell=False) + if not result.ok(): + raise WorkspaceArchiveWriteError(path=root, context={"backend": "sandscale", "stderr": result.stderr[-500:].decode("utf-8", "replace")}) + finally: + await self.exec("rm", "-f", archive, shell=False) + + # --- ports --------------------------------------------------------------------------------- + + async def _resolve_exposed_port(self, port: int) -> ExposedPortEndpoint: + sandbox_id = await self._ensure_sandbox() + try: + exposure = await asyncio.to_thread(_rate_limited_retry, lambda: self._client.sandboxes.expose_port(sandbox_id, port, region=self.state.region)) + link = await asyncio.to_thread(_rate_limited_retry, lambda: self._client.sandboxes.create_preview_link(sandbox_id, exposure.id, visibility="public", region=self.state.region)) + except SandscaleError as e: + raise ExposedPortUnavailableError( + port=port, + exposed_ports=self.state.exposed_ports, + reason="backend_unavailable", + context={"backend": "sandscale", "sandbox_id": sandbox_id, "code": e.code}, + cause=e, + retryable=_retryable(e), + ) from e + parsed = urlsplit(link.url) + if not parsed.hostname: + raise ExposedPortUnavailableError( + port=port, exposed_ports=self.state.exposed_ports, reason="backend_unavailable", context={"backend": "sandscale"} + ) + tls = parsed.scheme == "https" + return ExposedPortEndpoint(host=parsed.hostname, port=parsed.port or (443 if tls else 80), tls=tls) + + +class SandscaleSandboxClient(BaseSandboxClient[SandscaleSandboxClientOptions]): + """Starts, resumes and stops Sandscale sandboxes for the OpenAI Agents SDK. + + ``client`` is a ``Sandscale`` client (default: one from ``$SANDSCALE_API_KEY``).""" + + backend_id = "sandscale" + + def __init__(self, client: Optional[Sandscale] = None, *, instrumentation: Optional[Instrumentation] = None) -> None: + super().__init__() + self._client = client or Sandscale() + self._instrumentation = instrumentation if instrumentation is not None else Instrumentation() + + async def create( + self, + *, + snapshot: SnapshotSpec | SnapshotBase | None = None, + manifest: Manifest | None = None, + options: SandscaleSandboxClientOptions, + ) -> SandboxSession: + resolved = self._validate_manifest_for_create(_manifest(manifest)) + session_id = uuid.uuid4() + state = SandscaleSandboxSessionState( + session_id=session_id, + manifest=resolved, + snapshot=resolve_snapshot(snapshot, str(session_id)), + exposed_ports=options.exposed_ports, + region=options.region, + template=options.template, + cpu_count=options.cpu_count, + memory_mb=options.memory_mb, + disk_mb=options.disk_mb, + timeout_seconds=options.timeout_seconds, + network=options.network, + env=dict(options.env) if options.env else None, + ) + inner = SandscaleSandboxSession(state=state, client=self._client) + await inner._ensure_sandbox() + return self._wrap_session(inner, instrumentation=self._instrumentation) + + async def delete(self, session: SandboxSession) -> SandboxSession: + inner = session._inner + if not isinstance(inner, SandscaleSandboxSession): + raise TypeError("SandscaleSandboxClient.delete expects a SandscaleSandboxSession") + await inner.shutdown() + return session + + async def resume(self, state: SandboxSessionState) -> SandboxSession: + if not isinstance(state, SandscaleSandboxSessionState): + raise TypeError("SandscaleSandboxClient.resume expects a SandscaleSandboxSessionState") + inner = SandscaleSandboxSession(state=state, client=self._client) + reconnected = await inner.running() + if not reconnected: + # The sandbox ended (its time to live, a stop): start a new one; the snapshot restores it. + state.sandbox_id = "" + state.workspace_root_ready = False + await inner._ensure_sandbox() + inner._set_start_state_preserved(reconnected) + return self._wrap_session(inner, instrumentation=self._instrumentation) + + def deserialize_session_state(self, payload: dict[str, object]) -> SandboxSessionState: + return self._deserialize_session_state_payload(payload, SandscaleSandboxSessionState) diff --git a/src/sandscale/models.py b/src/sandscale/models.py index 7c9b2c8..e32ea44 100644 --- a/src/sandscale/models.py +++ b/src/sandscale/models.py @@ -58,9 +58,16 @@ class Sandbox: memory_mb: Optional[int] = None timeout_seconds: Optional[int] = None status_reason: Optional[str] = None + end_reason: Optional[str] = None + end_summary: Optional[str] = None created_at: Optional[datetime] = None can_pause: Optional[bool] = None can_resume: Optional[bool] = None + #: What it was started from: a built-in template (``builtin:go``), the organization + #: template's id, or ``builtin:base``. + template: Optional[str] = None + #: The image it runs, pinned by digest; None for the workers' default image. + image: Optional[str] = None @classmethod def from_raw(cls, raw: Raw, region: Optional[str]) -> "Sandbox": @@ -76,9 +83,13 @@ def from_raw(cls, raw: Raw, region: Optional[str]) -> "Sandbox": memory_mb=raw.get("mem_mb"), timeout_seconds=raw.get("ttl_seconds"), status_reason=_str(raw, "status_reason"), + end_reason=_str(raw, "end_reason"), + end_summary=_str(raw, "end_summary"), created_at=parse_time(raw.get("created_at")), can_pause=suspend.get("can_pause") if suspend else None, can_resume=suspend.get("can_resume") if suspend else None, + template=_str(raw, "template"), + image=_str(raw, "image"), ) @@ -91,6 +102,9 @@ class RunResult: duration_ms: int = 0 oom_killed: bool = False timed_out: bool = False + #: Why the sandbox could not run the command at all (``exit_code`` is then -1); a command + #: that ran and failed has none. + error: Optional[str] = None #: True when the output callbacks received live output; False when they got it at the end. streamed: bool = False @@ -119,9 +133,51 @@ def from_raw(cls, run_id: str, raw: Raw) -> "RunEnd": ) +@dataclass +class RunOutput: + """A run's kept output (``Sandboxes.run_output``).""" + + run_id: str + raw: Raw + instance_id: str = "" + status: str = "" + exit_code: Optional[int] = None + finished: bool = False + oom_killed: bool = False + timed_out: bool = False + output_available: bool = False + stdout: str = "" + stderr: str = "" + #: Why the sandbox could not run the command, or why its output was withheld. + error: Optional[str] = None + output_expires_at: Optional[datetime] = None + #: ``"running"`` or ``"not_kept"`` when there is no output. + reason: Optional[str] = None + + @classmethod + def from_raw(cls, raw: Raw) -> "RunOutput": + code = raw.get("exit_code") + return cls( + run_id=str(raw.get("run_id") or ""), + raw=raw, + instance_id=str(raw.get("instance_id") or ""), + status=str(raw.get("status") or ""), + exit_code=code if isinstance(code, int) and not isinstance(code, bool) else None, + finished=raw.get("finished") is True, + oom_killed=raw.get("oom_killed") is True, + timed_out=raw.get("timed_out") is True, + output_available=raw.get("output_available") is True, + stdout=str(raw.get("stdout") or ""), + stderr=str(raw.get("stderr") or ""), + error=_str(raw, "error"), + output_expires_at=parse_time(raw.get("output_expires_at")), + reason=_str(raw, "reason"), + ) + + @dataclass(frozen=True) class VaultEnvRef: - """One Keystone Vault value of a sandbox's environment: variable ``name`` gets ``field`` of + """One Sandscale Vault value of a sandbox's environment: variable ``name`` gets ``field`` of the secret at ``path``.""" name: str @@ -144,6 +200,39 @@ class FileEntry: size: Optional[int] = None +@dataclass +class ActivityDay: + """One UTC day (``YYYY-MM-DD``) with at least one of your commands.""" + + date: str + count: int + + +@dataclass +class SandboxActivity: + """Your own sandbox commands per UTC day (``sandboxes.activity``): ``from_`` and ``to`` are the + first and last day counted (``to`` is today), ``days`` the days with a command, oldest first.""" + + from_: str + to: str + total: int + days: list[ActivityDay] + raw: Raw + region: Optional[str] = None + + @classmethod + def from_raw(cls, raw: Raw, region: Optional[str]) -> "SandboxActivity": + days = [d for d in raw.get("days") or [] if isinstance(d, Mapping)] + return cls( + from_=str(raw.get("from") or ""), + to=str(raw.get("to") or ""), + total=int(raw.get("total") or 0), + days=[ActivityDay(date=str(d.get("date") or ""), count=int(d.get("count") or 0)) for d in days], + raw=raw, + region=region, + ) + + @dataclass class Snapshot: id: str @@ -173,6 +262,149 @@ def from_raw(cls, raw: Raw, region: Optional[str]) -> "Snapshot": ) +@dataclass +class Volume: + """A persistent volume: versioned contents kept between sandboxes, in one region.""" + + id: str + name: str + status: str + raw: Raw + region: Optional[str] = None + #: The committed version (0 for an empty volume). + version: int = 0 + size_bytes: int = 0 + max_bytes: int = 0 + sha256: Optional[str] = None + created_by: Optional[str] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + #: The sandbox holding the read-write attachment, when one does. + writer_instance_id: Optional[str] = None + #: How many read-only attachments there are. + readers: int = 0 + + @classmethod + def from_raw(cls, raw: Raw, region: Optional[str]) -> "Volume": + return cls( + id=str(raw.get("id")), + name=str(raw.get("name") or ""), + status=str(raw.get("status") or ""), + raw=raw, + region=region, + version=int(raw.get("version") or 0), + size_bytes=int(raw.get("size_bytes") or 0), + max_bytes=int(raw.get("max_bytes") or 0), + sha256=_str(raw, "sha256"), + created_by=_str(raw, "created_by"), + created_at=parse_time(raw.get("created_at")), + updated_at=parse_time(raw.get("updated_at")), + writer_instance_id=_str(raw, "writer_instance_id"), + readers=int(raw.get("readers") or 0), + ) + + +@dataclass +class VolumeAttachment: + """A volume attached to a sandbox.""" + + id: str + volume_id: str + volume_name: str + instance_id: str + mode: str # "rw" or "ro" + mount_path: str + raw: Raw + #: The volume version the attachment started from. + base_version: int = 0 + attached_by: Optional[str] = None + attached_at: Optional[datetime] = None + + @classmethod + def from_raw(cls, raw: Raw) -> "VolumeAttachment": + return cls( + id=str(raw.get("id") or ""), + volume_id=str(raw.get("volume_id") or ""), + volume_name=str(raw.get("volume_name") or ""), + instance_id=str(raw.get("instance_id") or ""), + mode=str(raw.get("mode") or ""), + mount_path=str(raw.get("mount_path") or ""), + raw=raw, + base_version=int(raw.get("base_version") or 0), + attached_by=_str(raw, "attached_by"), + attached_at=parse_time(raw.get("attached_at")), + ) + + +@dataclass +class CacheResult: + """The answer of a cache restore or save. The server computed ``key`` from the lockfile.""" + + key: str + ecosystem: str + path: str + raw: Raw + cache_id: Optional[str] = None + #: Restore: a cache entry was found and unpacked. + hit: bool = False + #: Save: a new entry was written. + saved: bool = False + #: An entry for the key exists (a save never overwrites it). + exists: bool = False + size_bytes: int = 0 + + @classmethod + def from_raw(cls, raw: Raw) -> "CacheResult": + return cls( + key=str(raw.get("key") or ""), + ecosystem=str(raw.get("ecosystem") or ""), + path=str(raw.get("path") or ""), + raw=raw, + cache_id=_str(raw, "cache_id"), + hit=raw.get("hit") is True, + saved=raw.get("saved") is True, + exists=raw.get("exists") is True, + size_bytes=int(raw.get("size_bytes") or 0), + ) + + +@dataclass +class DependencyCache: + """A dependency cache entry of the organization.""" + + id: str + ecosystem: str + key: str + status: str + raw: Raw + region: Optional[str] = None + lockfile_name: Optional[str] = None + path: Optional[str] = None + size_bytes: int = 0 + created_by: Optional[str] = None + created_at: Optional[datetime] = None + last_used_at: Optional[datetime] = None + expires_at: Optional[datetime] = None + + @classmethod + def from_raw(cls, raw: Raw, region: Optional[str]) -> "DependencyCache": + return cls( + id=str(raw.get("id")), + ecosystem=str(raw.get("ecosystem") or ""), + key=str(raw.get("key") or ""), + status=str(raw.get("status") or ""), + raw=raw, + region=region, + lockfile_name=_str(raw, "lockfile_name"), + path=_str(raw, "path"), + size_bytes=int(raw.get("size_bytes") or 0), + created_by=_str(raw, "created_by"), + created_at=parse_time(raw.get("created_at")), + last_used_at=parse_time(raw.get("last_used_at")), + expires_at=parse_time(raw.get("expires_at")), + ) + + @dataclass class Workspace: id: str diff --git a/tests/mock_server.py b/tests/mock_server.py index dddd922..70af22c 100644 --- a/tests/mock_server.py +++ b/tests/mock_server.py @@ -43,6 +43,13 @@ def json(self, status: int, body: Any = None, headers: Optional[dict[str, str]] self._h.end_headers() self._h.wfile.write(data) + def raw(self, status: int, data: bytes) -> None: + self._h.send_response(status) + self._h.send_header("Content-Type", "application/octet-stream") + self._h.send_header("Content-Length", str(len(data))) + self._h.end_headers() + self._h.wfile.write(data) + def sse(self, events: list[tuple[str, Any]], end: bool = True) -> None: self._h.send_response(200) self._h.send_header("Content-Type", "text/event-stream") @@ -71,7 +78,7 @@ def log_message(self, *args: Any) -> None: def _handle(self) -> None: length = int(self.headers.get("Content-Length") or 0) - body = self.rfile.read(length).decode() if length else "" + body = self.rfile.read(length).decode("utf-8" if "json" in (self.headers.get("Content-Type") or "") else "latin-1") if length else "" url = urlsplit(self.path) method = self.command found = next((r for r in mock._routes if r[0] == method and r[2].fullmatch(url.path)), None) diff --git a/tests/test_agent.py b/tests/test_agent.py new file mode 100644 index 0000000..28a6ed7 --- /dev/null +++ b/tests/test_agent.py @@ -0,0 +1,149 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""Agent experience: capabilities, idempotent create, text files and background processes.""" + +from __future__ import annotations + +import base64 +import json +import socket +import subprocess +import time +from typing import Any, Iterator + +import pytest + +from sandscale import Sandscale, ServerError + +from .mock_server import MockServer, Reply, Recorded + +ORG = "org-1" + + +@pytest.fixture() +def api() -> Iterator[MockServer]: + server = MockServer() + yield server + server.stop() + + +def make(api: MockServer, **kw: Any) -> Sandscale: + c = Sandscale(**{"api_key": "ssk_test", "base_url": api.url, "org_id": ORG, **kw}) + c.transport.sleep = lambda _s: None + return c + + +def test_capabilities_merge_the_server_answers_and_take_the_reset_from_the_server(api: MockServer) -> None: + api.json("GET", "/api/v1/sandbox/launch-options", 200, { + "can_start": True, + "templates": [ + {"id": "builtin:base", "startable": True, "description": "Python 3, Node.js"}, + {"id": "builtin:python", "startable": False, "reason": "not available here"}, + ], + "size": {"max_cpu": 4, "max_mem_mb": 8192, "default_cpu": 1, "default_mem_mb": 512}, + "ttl": {"default_seconds": 3600, "max_seconds": 86400}, + "network": {"options": [{"value": "none", "available": True}, {"value": "allowlist", "available": False, "reason": "turn on a preset first"}]}, + "features": {"snapshots": {"available": True}, "ssh": {"available": False}}, + }) + api.json("GET", "/api/v1/sandbox/quota", 200, {"active_instances": 1, "max_instances": 5, "plan": "pro", "plan_name": "Pro", "plan_upgradable": True}) + api.json("GET", "/api/v1/sandscale/usage", 200, { + "limits": {"vcpu_seconds": 720000}, "vcpu_seconds_used": 36000, "vcpu_seconds_left": 684000, "month": "2026-11", + "period": {"starts_at": "2026-11-07T00:00:00Z", "resets_at": "2026-12-07T00:00:00Z"}, + }) + api.json("GET", "/api/v1/regions", 200, {"regions": [{"id": "us1", "status": "live"}, {"id": "eu1", "status": "live"}]}) + c = make(api).capabilities() + assert (c.plan.code, c.plan.name, c.plan.upgradable) == ("pro", "Pro", True) + assert (c.limits.max_vcpu_per_box, c.limits.max_mem_mb, c.limits.max_concurrent_boxes, c.limits.running_boxes) == (4, 8192, 5, 1) + assert c.limits.network == ["none"] and c.limits.network_unavailable == {"allowlist": "turn on a preset first"} + assert [(t.id, t.startable) for t in c.templates] == [("builtin:base", True), ("builtin:python", False)] + assert c.features == {"snapshots": True, "ssh": False} + u = c.usage + assert (u.available, u.vcpu_hours_used, u.vcpu_hours_included, u.vcpu_hours_remaining) == (True, 10, 200, 190) + assert (u.resets_at, u.window_start) == ("2026-12-07T00:00:00Z", "2026-11-07T00:00:00Z") + assert [r.id for r in c.regions] == ["us1", "eu1"] + + +def test_capabilities_report_usage_unavailable_without_billing_read(api: MockServer) -> None: + api.json("GET", "/api/v1/sandbox/launch-options", 200, {"can_start": False, "refusal": {"code": "quota_exceeded", "message": "full"}, "templates": []}) + api.json("GET", "/api/v1/sandbox/quota", 200, {"plan": "free"}) + api.json("GET", "/api/v1/sandscale/usage", 403, {"error": {"code": "forbidden", "message": "billing:read is required"}}) + c = make(api).capabilities() + assert (c.usage.available, c.usage.code, c.usage.reason) == (False, "forbidden", "billing:read is required") + assert c.cannot_start == {"code": "quota_exceeded", "reason": "full"} + assert c.regions == [] + + +def test_create_with_a_key_sends_it_and_retries(api: MockServer) -> None: + calls = {"n": 0} + + def handler(_req: Recorded, reply: Reply) -> None: + calls["n"] += 1 + if calls["n"] == 1: + reply.json(503, {"error": {"code": "service_unavailable", "message": "retry"}}) + else: + reply.json(201, {"id": "sb-1", "status": "running", "created_at": "2026-11-19T00:00:00Z"}) + + api.on("POST", "/api/v1/sandbox/instances", handler) + box = make(api).sandboxes.create(idempotency_key="agent-retry-0001", network="none") + assert box.id == "sb-1" and calls["n"] == 2 + assert [r.headers.get("idempotency-key") for r in api.requests] == ["agent-retry-0001", "agent-retry-0001"] + assert api.requests[0].json() == {"network": "none"} + + +def test_create_without_a_key_is_not_retried(api: MockServer) -> None: + api.json("POST", "/api/v1/sandbox/instances", 503, {"error": {"code": "service_unavailable", "message": "retry"}}) + with pytest.raises(ServerError): + make(api).sandboxes.create() + assert len(api.requests) == 1 and "idempotency-key" not in api.requests[0].headers + + +def test_refusal_detail_is_on_the_error(api: MockServer) -> None: + api.json("POST", "/api/v1/sandbox/instances", 400, {"error": {"code": "template_unavailable", "message": "x", "detail": {"retryable": False, "available_templates": ["builtin:base"]}}}) + with pytest.raises(Exception) as e: + make(api).sandboxes.create(template="builtin:python") + assert e.value.code == "template_unavailable" # type: ignore[attr-defined] + assert e.value.details == {"retryable": False, "available_templates": ["builtin:base"]} # type: ignore[attr-defined] + + +def test_read_text(api: MockServer) -> None: + api.json("GET", "/api/v1/sandbox/instances/{}/files", 200, {"type": "file", "content": base64.b64encode("héllo\n".encode()).decode()}) + assert make(api).sandboxes.read_text("sb-1", "/workspace/a.txt") == "héllo\n" + + +def test_background_processes_run_the_scripts(api: MockServer) -> None: + def exec_locally(req: Recorded, reply: Reply) -> None: + argv = json.loads(req.body)["command"] + r = subprocess.run(argv, capture_output=True, text=True) + reply.json(200, {"run_id": "r", "exit_code": r.returncode, "stdout": r.stdout, "stderr": r.stderr, "duration_ms": 1}) + + api.on("POST", "/api/v1/sandbox/instances/{}/exec", exec_locally) + box = make(api).sandboxes + started = box.start_process("sb-1", "echo first; sleep 1; echo second; exit 3") + pid = started.process_id + logs = box.process_logs("sb-1", pid) + for _ in range(50): + if logs.state == "exited": + break + time.sleep(0.2) + logs = box.process_logs("sb-1", pid) + assert (logs.state, logs.exit_code, logs.text) == ("exited", 3, "first\nsecond\n") + rest = box.process_logs("sb-1", pid, offset=6) + assert (rest.text, rest.next_offset) == ("second\n", 13) + mine = [p for p in box.list_processes("sb-1") if p.process_id == pid] + assert len(mine) == 1 and (mine[0].state, mine[0].exit_code) == ("exited", 3) + + sleeper = box.start_process("sb-1", "sleep 300").process_id + assert box.process_logs("sb-1", sleeper).state == "running" + assert box.kill_process("sb-1", sleeper) is True + for _ in range(50): + if box.process_logs("sb-1", sleeper).state == "exited": + break + time.sleep(0.1) + assert box.process_logs("sb-1", sleeper).state == "exited" + + with socket.socket() as srv: + srv.bind(("127.0.0.1", 0)) + srv.listen() + port = srv.getsockname()[1] + assert box.wait_for_port("sb-1", port, timeout=3) is True + assert box.wait_for_port("sb-1", port, timeout=2) is False diff --git a/tests/test_call.py b/tests/test_call.py new file mode 100644 index 0000000..08a5677 --- /dev/null +++ b/tests/test_call.py @@ -0,0 +1,65 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""Sandscale.call: any operation by its catalogue name, from the generated operation table.""" + +from __future__ import annotations + +from typing import Any, Iterator + +import pytest + +import sandscale +from sandscale import Sandscale, SandscaleError + +from .mock_server import MockServer + + +@pytest.fixture() +def api() -> Iterator[MockServer]: + server = MockServer() + yield server + server.stop() + + +def make(api: MockServer, **kw: Any) -> Sandscale: + return Sandscale(**{"api_key": "ssk_test", "base_url": api.url, "org_id": "org-1", **kw}) + + +def test_operations_are_the_sandscale_scope() -> None: + ops = {o["name"]: o for o in sandscale.operations()} + assert "sandbox_create" in ops and "workspace_create" in ops and "models_catalog_get" not in ops + assert ops["sandbox_terminate"]["confirm"] is True + + +def test_builds_path_query_body_and_organization(api: MockServer) -> None: + api.json("POST", "/api/v1/sandbox/instances", 201, {"id": "sb-1"}) + api.json("GET", "/api/v1/sandbox/instances/{}", 200, {"id": "sb-1"}) + api.json("GET", "/api/v1/sandbox/instances", 200, {"data": []}) + api.json("GET", "/api/v1/orgs/{}/workspaces/{}", 200, {"id": "ws-1"}) + c = make(api) + assert c.call("sandbox_create", {"template_id": "builtin:base", "ttl_seconds": 600}, idempotency_key="ax-call-0001") == {"id": "sb-1"} + assert api.requests[0].json() == {"template_id": "builtin:base", "ttl_seconds": 600} + assert api.requests[0].headers["idempotency-key"] == "ax-call-0001" + c.call("sandbox_get", {"id": "a/b c"}) + assert api.requests[1].path == "/api/v1/sandbox/instances/a%2Fb%20c" + c.call("sandbox_list", {"status": "running", "limit": 5}) + assert api.requests[2].query == {"status": "running", "limit": "5"} + c.call("workspace_get", {"wsID": "ws-1"}) + assert api.requests[3].path == "/api/v1/orgs/org-1/workspaces/ws-1" + + +def test_refuses_unknown_before_any_request(api: MockServer) -> None: + c = make(api) + for op, args, code in [("models_catalog_get", {}, "unknown_operation"), ("sandbox_get", {"id": "x", "nope": 1}, "invalid_arguments"), + ("sandbox_get", {}, "invalid_arguments")]: + with pytest.raises(SandscaleError) as e: + c.call(op, args) + assert e.value.code == code + assert api.requests == [] + + +def test_server_refusal_is_carried(api: MockServer) -> None: + api.json("POST", "/api/v1/sandbox/instances", 402, {"error": {"code": "vcpu_per_box_limit", "message": "too big", "detail": {"plan_limit": {"upgrade_to": "pro"}}}}) + with pytest.raises(SandscaleError) as e: + make(api).call("sandbox_create", {"cpu_count": 99}) + assert e.value.code == "vcpu_per_box_limit" and e.value.details == {"plan_limit": {"upgrade_to": "pro"}} diff --git a/tests/test_client.py b/tests/test_client.py index 54b43b6..de7d4ce 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -310,6 +310,49 @@ def test_stop_pause_resume_snapshot(api: MockServer, sleeps: list[float]) -> Non assert [s.id for s in c.sandboxes.list_snapshots("sb-1")] == ["sn-1"] +def test_volumes(api: MockServer, sleeps: list[float]) -> None: + vol = { + "id": "vol-1", "name": "deps", "region": "us-east-1", "status": "ready", "version": 2, "size_bytes": 10, + "max_bytes": 1024, "created_by": "u", "writer_instance_id": "sb-1", "readers": 1, + } + api.json("POST", "/api/v1/sandbox/volumes", 201, vol) + api.json("POST", "/api/v1/sandbox/instances/{}/volumes", 201, { + "id": "att-1", "volume_id": "vol-1", "volume_name": "deps", "instance_id": "sb-1", "mode": "ro", + "mount_path": "/data/deps", "base_version": 2, "attached_by": "u", + }) + api.json("POST", "/api/v1/sandbox/instances/{}/volumes/{}/commit", 200, {**vol, "version": 3}) + api.on("DELETE", "/api/v1/sandbox/instances/{}/volumes/{}", lambda _r, reply: reply.json(204)) + c = make(api, sleeps) + v = c.volumes.create("deps", max_bytes=1024) + assert (v.id, v.version, v.max_bytes, v.writer_instance_id, v.readers) == ("vol-1", 2, 1024, "sb-1", 1) + assert api.requests[0].json() == {"name": "deps", "max_bytes": 1024} + a = c.sandboxes.attach_volume("sb-1", "vol-1", "/data/deps", mode="ro") + assert (a.id, a.mode, a.base_version) == ("att-1", "ro", 2) + assert api.requests[1].json() == {"volume_id": "vol-1", "mount_path": "/data/deps", "mode": "ro"} + c.sandboxes.attach_volume("sb-1", "vol-1", "/data/deps") + assert api.requests[2].json()["mode"] == "rw" + assert c.sandboxes.commit_volume("sb-1", "vol-1").version == 3 + c.sandboxes.detach_volume("sb-1", "vol-1") + c.sandboxes.detach_volume("sb-1", "vol-1", commit=False) + assert [r.query for r in api.requests[4:]] == [{}, {"commit": "false"}] + + +def test_caches(api: MockServer, sleeps: list[float]) -> None: + api.json("POST", "/api/v1/sandbox/instances/{}/caches/restore", 200, { + "cache_id": "c-1", "key": "k", "ecosystem": "npm", "path": "/root/.npm", "hit": True, "saved": False, "exists": True, "size_bytes": 5, + }) + api.json("POST", "/api/v1/sandbox/instances/{}/caches/save", 200, { + "key": "k", "ecosystem": "npm", "path": "/root/.npm", "hit": False, "saved": False, "exists": True, "size_bytes": 5, + }) + c = make(api, sleeps) + r = c.sandboxes.restore_cache("sb-1", ecosystem="npm", lockfile="/workspace/package-lock.json") + assert (r.cache_id, r.hit, r.size_bytes) == ("c-1", True, 5) + assert api.requests[0].json() == {"ecosystem": "npm", "lockfile": "/workspace/package-lock.json"} + r = c.sandboxes.save_cache("sb-1", ecosystem="npm", lockfile="/workspace/package-lock.json", path="/root/.npm") + assert (r.saved, r.exists) == (False, True) + assert api.requests[1].json() == {"ecosystem": "npm", "lockfile": "/workspace/package-lock.json", "path": "/root/.npm"} + + def test_files(api: MockServer, sleeps: list[float]) -> None: api.json("PUT", "/api/v1/sandbox/instances/{}/files", 200, {}) @@ -376,6 +419,25 @@ def test_run_reads_the_run_without_a_result_in_done(api: MockServer, sleeps: lis assert (res.run_id, res.exit_code, res.timed_out, res.duration_ms, res.streamed) == ("r3", 124, True, 9, True) +def test_run_output_and_command_errors(api: MockServer, sleeps: list[float]) -> None: + api.json( + "GET", + "/api/v1/sandbox/runs/{}/output", + 200, + {"run_id": "r4", "instance_id": "sb-1", "status": "failed", "exit_code": 127, "finished": True, + "output_available": True, "stdout": "", "stderr": "command not found: go\n", + "output_expires_at": "2026-11-23T10:00:00Z"}, + ) + out = make(api, sleeps).sandboxes.run_output("r4") + assert api.requests[0].route == "GET /api/v1/sandbox/runs/{}/output" + assert (out.run_id, out.exit_code, out.finished, out.output_available, out.stderr, out.reason) == ( + "r4", 127, True, True, "command not found: go\n", None) + assert out.output_expires_at is not None + api.json("POST", "/api/v1/sandbox/instances/{}/exec", 200, {"run_id": "r5", "exit_code": -1, "stdout": "", "stderr": "", "error": "the sandbox could not run the command"}) + res = make(api, sleeps).sandboxes.run("sb-1", ["true"]) + assert (res.exit_code, res.error) == (-1, "the sandbox could not run the command") + + def test_run_with_a_result_answer_delivers_it_once(api: MockServer, sleeps: list[float]) -> None: api.json("POST", "/api/v1/sandbox/instances/{}/exec", 200, {"run_id": "a", "exit_code": 0, "stdout": "x", "stderr": ""}) out: list[str] = [] @@ -469,7 +531,7 @@ def test_build_hosts_lab_and_certificate(api: MockServer, sleeps: list[float]) - assert (got.serial, got.principals, got.ssh) == ("1", ["nib-1"], {"user": "nib-1"}) -# --- Sandscale regions ------------------------------------------------------ +# --- Sandscale regions (decision 12) ------------------------------------------------------ def _recording(urls: list[str]) -> httpx.Client: @@ -478,21 +540,22 @@ def handler(request: httpx.Request) -> httpx.Response: if request.url.path == "/api/v1/regions": return httpx.Response( 200, - json={"regions": [{"id": "us1", "status": "live", "api_url": "https://api.us1.region.example.test"}, {"id": "eu1", "status": "coming_soon"}]}, + json={"regions": [{"id": "us1", "status": "live", "api_url": "https://api.us1.keystone.neuralinverse.io"}, {"id": "eu1", "status": "coming_soon"}]}, ) return httpx.Response(200, json={"data": [], "id": "sb", "status": "running"}) return httpx.Client(transport=httpx.MockTransport(handler)) -def test_sandscale_regions_use_their_own_hosts() -> None: +def test_sandscale_us_is_direct_and_eu_goes_through_the_global_api() -> None: urls: list[str] = [] c = Sandscale(api_key="k", http_client=_recording(urls)) c.sandboxes.get("sb", region="eu") c.sandboxes.get("sb", region="us1") c.sandboxes.get("sb") + # A regional cell takes no global API key: the global plane forwards to eu1 (region=eu1). assert urls == [ - "https://api.eu.sandscale.dev/api/v1/sandbox/instances/sb", + "https://api.sandscale.dev/api/v1/sandbox/instances/sb?region=eu1", "https://api.us.sandscale.dev/api/v1/sandbox/instances/sb", "https://api.sandscale.dev/api/v1/sandbox/instances/sb", ] @@ -501,12 +564,29 @@ def test_sandscale_regions_use_their_own_hosts() -> None: assert info.value.code == "region_unknown" +def test_sandscale_refuses_a_us_only_route_for_eu_before_any_request() -> None: + urls: list[str] = [] + c = Sandscale(api_key="k", http_client=_recording(urls)) + with pytest.raises(RegionError) as info: + c.templates.get("t1", region="eu") + assert info.value.code == "region_unsupported" + assert urls == [] + c.templates.get("t1") + c.templates.get("t1", region="us") + assert urls == [ + "https://api.sandscale.dev/api/v1/sandbox/templates/t1", + "https://api.us.sandscale.dev/api/v1/sandbox/templates/t1", + ] + c.sandboxes.get("sb", region="eu") + assert urls[-1] == "https://api.sandscale.dev/api/v1/sandbox/instances/sb?region=eu1" + + def test_sandscale_lists_live_regions_through_their_hosts() -> None: urls: list[str] = [] result = Sandscale(api_key="k", http_client=_recording(urls)).sandboxes.list() assert [p.region for p in result.pages] == ["us"] assert urls == ["https://api.sandscale.dev/api/v1/regions", "https://api.us.sandscale.dev/api/v1/sandbox/instances"] - assert not any("region.example.test" in u for u in urls) + assert not any("keystone.neuralinverse.io" in u for u in urls) def test_wrong_region_stays_typed() -> None: @@ -515,3 +595,46 @@ def test_wrong_region_stays_typed() -> None: with pytest.raises(RegionError) as info: Sandscale(api_key="k", http_client=client).sandboxes.get("sb", region="us") assert info.value.region == "eu1" + + +# --- Free fair-use refusals --------------------------------------------------------------- + + +def test_free_daily_limit_carries_retry_at(api: MockServer, sleeps: list[float]) -> None: + from sandscale import FreeDailyLimitError + + body = { + "error": {"code": "free_daily_limit", "message": "cap"}, + "limit": {"limit": "daily_vcpu_hours", "allowed": 15, "used": 15, "allowed_vcpu_seconds": 54000, "plan": "free", "retry_at": "2026-11-19T10:01:00Z"}, + } + api.json("POST", "/api/v1/sandbox/instances", 429, body, {"Retry-After": "60"}) + with pytest.raises(FreeDailyLimitError) as info: + make(api, sleeps).sandboxes.create(template="builtin:base") + err = info.value + assert isinstance(err, LimitExceededError) + assert err.retry_at is not None and err.retry_at.isoformat() == "2026-11-19T10:01:00+00:00" + assert (err.fair_use.limit, err.fair_use.allowed, err.fair_use.allowed_vcpu_seconds, err.fair_use.plan) == ("daily_vcpu_hours", 15, 54000, "free") + + +def test_free_limit_under_details_and_ramp_lift(api: MockServer, sleeps: list[float]) -> None: + from sandscale import FreeMonthlyLimitError, FreeNewAccountLimitError + + api.json("POST", "/api/v1/sandbox/instances", 402, {"error": {"code": "free_monthly_limit", "message": "used", "details": {"limit": {"resets_at": "2026-11-30T12:00:00Z"}}}}) + with pytest.raises(FreeMonthlyLimitError) as m: + make(api, sleeps).sandboxes.create(template="builtin:base") + assert m.value.resets_at is not None and m.value.resets_at.day == 30 + api.json("POST", "/api/v1/sandbox/instances", 429, {"error": {"code": "free_new_account_limit", "message": "new"}, "limit": {"limit": "ramp_boxes", "ramp_ends_at": "2026-11-25T00:00:00Z", "lift": ["github_account", "card", "operator_approval"]}}) + with pytest.raises(FreeNewAccountLimitError) as r: + make(api, sleeps).sandboxes.create(template="builtin:base") + assert r.value.lift == ("github_account", "card", "operator_approval") and r.value.ramp_ends_at is not None + + +def test_free_already_claimed_and_account_exists(api: MockServer, sleeps: list[float]) -> None: + from sandscale import AccountExistsError, FreeAlreadyClaimedError + + api.json("POST", "/api/v1/sandbox/instances", 403, error_body("free_already_claimed", "another organization holds Free")) + with pytest.raises(FreeAlreadyClaimedError): + make(api, sleeps).sandboxes.create(template="builtin:base") + api.json("POST", "/api/v1/sandbox/instances", 409, error_body("account_exists", "sign in")) + with pytest.raises(AccountExistsError): + make(api, sleeps).sandboxes.create(template="builtin:base") diff --git a/tests/test_code_mode.py b/tests/test_code_mode.py new file mode 100644 index 0000000..fa17726 --- /dev/null +++ b/tests/test_code_mode.py @@ -0,0 +1,336 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""The typed API client and code mode: execute, tasks, search and the ask-first policy.""" + +from __future__ import annotations + +import json +from typing import Any, Iterator + +import pytest + +from sandscale import ( + ApiArgumentError, + ConfigurationError, + InvalidRequestError, + NotFoundError, + Sandscale, + SandscaleError, + TaskFailedError, + TaskTimeoutError, +) +from sandscale._api import Api, build_request, snake_case +from sandscale._api_gen import OPERATIONS + +from .mock_server import MockServer, Recorded, Reply, error_body + +ORG = "org-1" + +#: The code mode routes (docs/architecture/sandscale-code-mode-contract.md). Not in test_routes.py's +#: ROUTES until the server mounts them. +CODE_ROUTES = [ + "POST /api/v1/sandbox/code/tasks", + "GET /api/v1/sandbox/code/tasks/{}", + "POST /api/v1/sandbox/code/search", + "GET /api/v1/sandbox/code/policy", + "PUT /api/v1/sandbox/code/policy", +] + + +@pytest.fixture() +def api() -> Iterator[MockServer]: + server = MockServer() + yield server + server.stop() + + +def make(api: MockServer, **kw: Any) -> Sandscale: + c = Sandscale(**{"api_key": "ssk_test", "base_url": api.url, "org_id": ORG, **kw}) + c.transport.sleep = lambda _s: None + return c + + +def op(ns: str, fn: str) -> dict[str, Any]: + return next(o for o in OPERATIONS if o["ns"] == ns and o["fn"] == fn) + + +# The typed API --------------------------------------------------------------------------------- + + +def test_every_operation_is_reachable_by_camel_and_snake_names() -> None: + a = Api(Sandscale(api_key="k", base_url="http://127.0.0.1:1").transport) + for o in OPERATIONS: + camel = getattr(getattr(a, o["ns"]), o["fn"]) + snake = getattr(getattr(a, snake_case(o["ns"])), snake_case(o["fn"])) + assert camel is snake and camel.operation is o + assert a.auditLogs is a.audit_logs + assert a.sandbox.snapshotCreate is a.sandbox.snapshot_create + # No two functions of a namespace share a name, in either spelling, and no name hides a method. + for ns in {o["ns"] for o in OPERATIONS}: + fns = [o["fn"] for o in OPERATIONS if o["ns"] == ns] + names = fns + [snake_case(f) for f in fns if snake_case(f) != f] + assert len(names) == len(set(names)), ns + assert not {snake_case(o["ns"]) for o in OPERATIONS} & {"call", "namespaces", "operations"} + + +def test_unknown_namespace_or_function_names_what_exists(api: MockServer) -> None: + c = make(api) + with pytest.raises(AttributeError, match="no namespace"): + c.api.nope + with pytest.raises(AttributeError, match="no function sandbox.nope"): + c.api.sandbox.nope + + +def test_typed_call_maps_path_query_body_and_region(api: MockServer) -> None: + api.json("POST", "/api/v1/sandbox/instances/{}/snapshot", 201, {"snapshot_id": "s1"}) + api.json("GET", "/api/v1/audit-logs", 200, {"events": []}) + api.json("GET", "/api/v1/orgs/{}/billing/usage", 200, {"usage": 1}) + c = make(api, region_urls={"eu": api.url}) + + assert c.api.sandbox.snapshot_create(id="sb/1", label="before", region="eu") == {"snapshot_id": "s1"} + rec = api.requests[-1] + assert rec.path == "/api/v1/sandbox/instances/sb%2F1/snapshot" + assert rec.json() == {"label": "before"} + assert "idempotency-key" not in rec.headers + + c.api.auditLogs.auditEventsList(from_="2026-11-01", limit=5, include_read_only=True) + rec = api.requests[-1] + assert rec.query == {"from": "2026-11-01", "limit": "5", "include_read_only": "true"} + assert rec.body == "" + + # The organization fills from the client; a given one wins. + c.api.billing.usage_get(month="2026-11") + assert api.requests[-1].path == f"/api/v1/orgs/{ORG}/billing/usage" + assert api.requests[-1].query == {"month": "2026-11"} + c.api.billing.usage_get({"orgID": "org-2"}) + assert api.requests[-1].path == "/api/v1/orgs/org-2/billing/usage" + + +def test_build_request_whole_body_fixed_query_and_many_segment_path() -> None: + req = build_request(op("vault", "secretNamesList"), {"mount": "kv", "path": "team/a b"}, None) + assert req["path"] == "/api/v1/vault/kv/metadata/team/a%20b" + assert req["query"] == {"list": "true"} + with pytest.raises(ApiArgumentError, match="segment"): + build_request(op("vault", "secretNamesList"), {"mount": "kv", "path": "a/../b"}, None) + with pytest.raises(ApiArgumentError): + build_request(op("vault", "secretNamesList"), {"mount": "..", "path": "a"}, None) + + req = build_request(op("objects", "putBucketPolicy"), {"body": {"Name": "b", "Policy": "{}"}}, None) + assert req["json_body"] == {"Name": "b", "Policy": "{}"} and req["method"] == "POST" + # A write with no arguments still sends a JSON object. + req = build_request(op("objects", "describeObjectsLimits"), {}, None) + assert req["json_body"] == {} + + synthetic = { + "ns": "x", "fn": "y", "op": "x_y", "method": "GET", "path": "/api/v1/x", + "params": [{"name": "filter", "in": "query_all"}, {"name": "max", "in": "query", "wire": "limit"}], + } + req = build_request(synthetic, {"filter": {"a": "1", "b": False}, "max": 3}, None) + assert req["query"] == {"a": "1", "b": "false", "limit": 3} and req["json_body"] is None + + +def test_unknown_or_missing_arguments_are_refused_before_any_request(api: MockServer) -> None: + c = make(api) + with pytest.raises(ApiArgumentError, match="takes no argument 'nope'"): + c.api.sandbox.snapshot_create(id="x", nope=1) + with pytest.raises(ApiArgumentError, match="needs argument 'id'"): + c.api.sandbox.snapshot_create(label="x") + with pytest.raises(TypeError): # ApiArgumentError is a TypeError too + c.api.sandbox.snapshot_create(id="x", nope=1) + with pytest.raises(ApiArgumentError, match="writes only"): + c.api.auditLogs.auditEventsList(idempotency_key="k") + no_org = make(api, org_id=None) + no_org.transport.org_id = None + with pytest.raises(ConfigurationError, match="needs an organization"): + no_org.api.billing.usageGet() + assert api.requests == [] + + +def test_confirm_is_required_and_never_sent(api: MockServer) -> None: + api.json("DELETE", "/api/v1/sandbox/instances/{}/ports/{}", 204) + c = make(api) + assert op("sandbox", "instancesPortsDelete").get("confirm") + with pytest.raises(SandscaleError) as e: + c.api.sandbox.instances_ports_delete(id="sb", port=8080) + assert e.value.code == "confirmation_required" and e.value.status == 0 + assert e.value.details["operation"] == "sandbox_instances_ports_delete" + assert api.requests == [] + + c.api.sandbox.instances_ports_delete(id="sb", port=8080, confirm=True) + rec = api.requests[-1] + assert rec.path == "/api/v1/sandbox/instances/sb/ports/8080" + assert rec.query == {} and rec.body == "" + + # A confirm in the arguments mapping (the way a script passes it) is stripped too. + api.json("POST", "/api/v1/svc/objects/DeleteBucket", 200, {}) + c.api.objects.storage_bucket_delete({"Name": "b", "confirm": True}) + assert api.requests[-1].json() == {"Name": "b"} + + +def test_idempotency_key_on_a_write_is_the_header_and_retries(api: MockServer) -> None: + calls = {"n": 0} + + def flaky(_req: Recorded, reply: Reply) -> None: + calls["n"] += 1 + if calls["n"] == 1: + reply.json(503, error_body("unavailable", "try again")) + else: + reply.json(201, {"id": "sb"}) + + api.on("POST", "/api/v1/sandbox/instances/{}/snapshot", flaky) + c = make(api) + assert c.api.sandbox.snapshotCreate(id="sb", idempotency_key="job-42") == {"id": "sb"} + assert [r.headers.get("idempotency-key") for r in api.requests] == ["job-42", "job-42"] + + +def test_typed_call_errors_are_the_sdk_errors(api: MockServer) -> None: + api.json("POST", "/api/v1/sandbox/instances/{}/snapshot", 402, error_body("plan_limit", "upgrade", detail={"next": {"plan": "pro"}})) + c = make(api) + with pytest.raises(SandscaleError) as e: + c.api.sandbox.snapshot_create(id="sb") + assert e.value.status == 402 and e.value.code == "plan_limit" + assert e.value.details == {"next": {"plan": "pro"}} + + +def test_call_by_operation_name(api: MockServer) -> None: + api.json("POST", "/api/v1/sandbox/instances/{}/snapshot", 201, {"ok": True}) + c = make(api) + assert c.api.call("sandbox_snapshot_create", {"id": "sb"}) == {"ok": True} + with pytest.raises(ApiArgumentError): + c.api.call("no_such_operation") + + +# Code mode ------------------------------------------------------------------------------------- + + +def task(state: str, **extra: Any) -> dict[str, Any]: + return { + "task_id": "t-1", "state": state, "run_id": "r-1", "segments": 1, "script_sha256": "ab", + "console": [], "truncated": False, "created_at": "2026-11-18T10:00:00Z", "updated_at": "2026-11-18T10:00:01Z", + **extra, + } + + +def test_execute_answered_at_once(api: MockServer) -> None: + api.json("POST", "/api/v1/sandbox/code/tasks", 200, task( + "succeeded", result={"n": 2}, console=[{"level": "log", "text": "hi"}], finished_at="2026-11-18T10:00:02Z")) + c = make(api) + t = c.execute("return 1 + 1") + assert t.succeeded and t.result == {"n": 2} and t.console[0].text == "hi" + assert t.finished_at is not None and t.finished_at.year == 2026 + assert [r.route for r in api.requests] == ["POST /api/v1/sandbox/code/tasks"] + assert api.requests[0].json() == {"code": "return 1 + 1", "wait_seconds": 30} + + +def test_execute_202_then_polls_until_succeeded(api: MockServer) -> None: + api.json("POST", "/api/v1/sandbox/code/tasks", 202, task("running")) + states = iter([task("running"), task("succeeded", result=[1, 2])]) + api.on("GET", "/api/v1/sandbox/code/tasks/{}", lambda _r, reply: reply.json(200, next(states))) + c = make(api) + t = c.execute("return [1, 2]", wait_seconds=5, idempotency_key="run-1") + assert t.state == "succeeded" and t.result == [1, 2] + assert [r.route for r in api.requests] == [ + "POST /api/v1/sandbox/code/tasks", "GET /api/v1/sandbox/code/tasks/{}", "GET /api/v1/sandbox/code/tasks/{}", + ] + assert api.requests[0].headers["idempotency-key"] == "run-1" + assert api.requests[0].json()["wait_seconds"] == 5 + assert api.requests[1].path == "/api/v1/sandbox/code/tasks/t-1" + assert api.requests[1].query == {"wait_seconds": "5"} + + +def test_failed_task_raises_with_the_api_error(api: MockServer) -> None: + err = { + "code": "script_error", "message": "plan limit", "line": 3, "column": 7, + "api_error": {"code": "plan_limit", "message": "upgrade", "status": 402, "next": {"plan": "pro"}, "retry_after_seconds": 0}, + } + api.json("POST", "/api/v1/sandbox/code/tasks", 200, task("failed", error=err, console=[{"level": "error", "text": "x"}])) + c = make(api) + with pytest.raises(TaskFailedError) as e: + c.execute("await sandscale.sandbox.create({})") + assert e.value.code == "script_error" and e.value.details == err + t = e.value.task + assert t.error is not None and (t.error.line, t.error.column) == (3, 7) + assert t.error.api_error is not None and t.error.api_error.status == 402 and t.error.api_error.next == {"plan": "pro"} + assert t.console[0].level == "error" + + t = c.execute("x", raise_on_failure=False) + assert t.state == "failed" and t.error is not None and t.error.code == "script_error" + + +def test_awaiting_approval_is_returned_unless_waited_for(api: MockServer) -> None: + pending = task("awaiting_approval", pending_approval={"request_id": "ap-1", "operation": "sandbox_terminate", "seq": 4}) + api.json("POST", "/api/v1/sandbox/code/tasks", 202, pending) + c = make(api) + t = c.execute("await sandscale.sandbox.terminate({id: 'x'})") + assert t.state == "awaiting_approval" and not t.done + assert t.pending_approval is not None + assert (t.pending_approval.request_id, t.pending_approval.operation, t.pending_approval.seq) == ("ap-1", "sandbox_terminate", 4) + assert len(api.requests) == 1 + + states = iter([pending, task("succeeded", result="done")]) + api.on("GET", "/api/v1/sandbox/code/tasks/{}", lambda _r, reply: reply.json(200, next(states))) + t = c.execute("...", wait_for_approval=True) + assert t.state == "succeeded" and t.result == "done" + + +def test_timeout_raises_with_the_running_task(api: MockServer) -> None: + api.json("POST", "/api/v1/sandbox/code/tasks", 202, task("running")) + api.json("GET", "/api/v1/sandbox/code/tasks/{}", 200, task("running")) + c = make(api) + with pytest.raises(TaskTimeoutError) as e: + c.execute("while (true) {}", timeout=0) + assert e.value.task.state == "running" and e.value.code == "task_timeout" + + +def test_tasks_get_wait_and_404(api: MockServer) -> None: + api.json("GET", "/api/v1/sandbox/code/tasks/{}", 200, task("succeeded", result=1)) + c = make(api) + t = c.tasks.get("t-1") + assert t.task_id == "t-1" and t.result == 1 and api.requests[-1].query == {} + c.tasks.get("t-1", wait_seconds=99) + assert api.requests[-1].query == {"wait_seconds": "30"} + assert c.tasks.wait("t-1").result == 1 + + api.json("GET", "/api/v1/sandbox/code/tasks/{}", 404, error_body("not_found", "no such task")) + with pytest.raises(NotFoundError) as e: + c.tasks.get("someone-elses") + assert e.value.code == "not_found" + + +def test_search(api: MockServer) -> None: + api.json("POST", "/api/v1/sandbox/code/search", 200, {"result": [{"operation": "sandbox_create"}], "console": [], "truncated": False}) + c = make(api) + r = c.search("return api.find('start a sandbox', 3)") + assert r.result == [{"operation": "sandbox_create"}] and r.console == [] and not r.truncated + assert api.requests[-1].json() == {"code": "return api.find('start a sandbox', 3)"} + + api.json("POST", "/api/v1/sandbox/code/search", 422, error_body("syntax_error", "unexpected token", detail={"line": 1, "column": 4})) + with pytest.raises(InvalidRequestError) as e: + c.search("return (") + assert e.value.code == "syntax_error" and e.value.details == {"line": 1, "column": 4} + + +def test_code_policy(api: MockServer) -> None: + api.json("GET", "/api/v1/sandbox/code/policy", 200, {"ask_first": ["destructive"]}) + api.on("PUT", "/api/v1/sandbox/code/policy", lambda req, reply: reply.json(200, json.loads(req.body))) + c = make(api) + assert c.code_policy.get().ask_first == ["destructive"] + assert c.code_policy.set(["sandbox_terminate", "writes"]).ask_first == ["sandbox_terminate", "writes"] + assert api.requests[-1].json() == {"ask_first": ["sandbox_terminate", "writes"]} + with pytest.raises(TypeError): + c.code_policy.set("writes") + + +def test_code_mode_calls_exactly_the_contract_routes(api: MockServer) -> None: + api.json("POST", "/api/v1/sandbox/code/tasks", 202, task("running")) + api.json("GET", "/api/v1/sandbox/code/tasks/{}", 200, task("succeeded")) + api.json("POST", "/api/v1/sandbox/code/search", 200, {"result": None}) + api.json("GET", "/api/v1/sandbox/code/policy", 200, {"ask_first": []}) + api.json("PUT", "/api/v1/sandbox/code/policy", 200, {"ask_first": []}) + c = make(api) + c.execute("1") + c.tasks.get("t-1") + c.search("1") + c.code_policy.get() + c.code_policy.set([]) + assert sorted({r.route for r in api.requests}) == sorted(CODE_ROUTES) diff --git a/tests/test_integrations.py b/tests/test_integrations.py new file mode 100644 index 0000000..662ffea --- /dev/null +++ b/tests/test_integrations.py @@ -0,0 +1,206 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""The framework adapters (sandscale.integrations) against the mock API: each maps its framework's +calls onto the Sandscale routes and its errors onto the framework's.""" + +from __future__ import annotations + +import asyncio +import base64 +import io +import json +from pathlib import Path +from typing import Any, Iterator + +import pytest + +from sandscale import Sandscale + +from .mock_server import MockServer, Recorded, Reply, error_body + +ORG = "00000000-0000-4000-8000-000000000001" +BOX = {"id": "sb-1", "status": "running", "cpu_count": 2, "mem_mb": 2048} + + +@pytest.fixture() +def api() -> Iterator[MockServer]: + server = MockServer() + server.json("POST", "/api/v1/sandbox/instances", 201, BOX) + server.json("GET", "/api/v1/sandbox/instances/{}", 200, BOX) + server.json("DELETE", "/api/v1/sandbox/instances/{}", 204) + yield server + server.stop() + + +def client(api: MockServer) -> Sandscale: + c = Sandscale(api_key="ssk_test", base_url=api.url, org_id=ORG) + c.transport.sleep = lambda _s: None + return c + + +def files(store: dict[str, bytes]) -> Any: + """The streamed file routes: raw bytes in (PUT, octet-stream) and out (GET with raw=1).""" + + def handler(req: Recorded, reply: Reply) -> None: + path = req.query["path"] + if req.method == "PUT": + assert req.headers["content-type"] == "application/octet-stream" + store[path] = req.body.encode("latin-1") + reply.json(200, {}) + return + assert req.query.get("raw") == "1" + if path not in store: + reply.json(404, error_body("not_found", "no such file")) + return + reply.raw(200, store[path]) + + return handler + + +# --- LangChain ---------------------------------------------------------------------------------- + + +def test_langchain_backend_execute_and_files(api: MockServer) -> None: + pytest.importorskip("deepagents") + from sandscale.integrations.langchain import SandscaleSandbox + + store: dict[str, bytes] = {} + api.on("PUT", "/api/v1/sandbox/instances/{}/files", files(store)) + api.on("GET", "/api/v1/sandbox/instances/{}/files", files(store)) + api.json("POST", "/api/v1/sandbox/instances/{}/exec", 200, {"run_id": "r1", "exit_code": 2, "stdout": "out", "stderr": "err"}) + + with SandscaleSandbox.create(client=client(api), template="builtin:python", timeout_seconds=600) as sb: + assert sb.id == "sb-1" + res = sb.execute("make test", timeout=30) + assert (res.output, res.exit_code, res.truncated) == ("out\nerr", 2, False) + exec_req = next(r for r in api.requests if r.route.endswith("/exec")) + assert exec_req.json() == {"command": ["sh", "-c", "make test"], "timeout_sec": 30, "workdir": "/workspace"} + + up = sb.upload_files([("/workspace/notes.txt", b"hi"), ("/workspace/a/b.bin", b"\x00\x01"), ("rel.txt", b"x")]) + assert [(u.path, u.error) for u in up] == [("/workspace/notes.txt", None), ("/workspace/a/b.bin", None), ("rel.txt", "invalid_path")] + assert store == {"/workspace/notes.txt": b"hi", "/workspace/a/b.bin": b"\x00\x01"} + + down = sb.download_files(["/workspace/notes.txt", "/workspace/missing.txt"]) + assert (down[0].content, down[0].error) == (b"hi", None) + assert (down[1].content, down[1].error) == (None, "file_not_found") + create = next(r for r in api.requests if r.route == "POST /api/v1/sandbox/instances") + assert create.json() == {"template_id": "builtin:python", "ttl_seconds": 600} + assert api.requests[-1].route == "DELETE /api/v1/sandbox/instances/{}" + + +def test_langchain_backend_on_an_existing_sandbox_leaves_it_running(api: MockServer) -> None: + pytest.importorskip("deepagents") + from sandscale.integrations.langchain import SandscaleSandbox + + SandscaleSandbox(client(api), "sb-9").close() + assert not any(r.method == "DELETE" for r in api.requests) + + +def test_langchain_backend_raises_server_errors(api: MockServer) -> None: + pytest.importorskip("deepagents") + from sandscale.errors import SandscaleError + from sandscale.integrations.langchain import SandscaleSandbox + + api.json("PUT", "/api/v1/sandbox/instances/{}/files", 503, error_body("dlp_unavailable", "down")) + with pytest.raises(SandscaleError): + SandscaleSandbox(client(api), "sb-1").upload_files([("/workspace/x", b"y")]) + + +def test_langchain_toolkit(api: MockServer) -> None: + pytest.importorskip("langchain_core") + from sandscale.integrations.langchain import SandscaleToolkit + + store: dict[str, bytes] = {} + api.on("PUT", "/api/v1/sandbox/instances/{}/files", files(store)) + api.on("GET", "/api/v1/sandbox/instances/{}/files", files(store)) + api.json("POST", "/api/v1/sandbox/instances/{}/exec", 200, {"run_id": "r1", "exit_code": 0, "stdout": "ok", "stderr": ""}) + + toolkit = SandscaleToolkit.on(client(api), "sb-1") + tools = {t.name: t for t in toolkit.get_tools()} + assert set(tools) == {"sandscale_run", "sandscale_write_file", "sandscale_read_file"} + assert tools["sandscale_run"].invoke({"command": "echo ok"}) == "exit code 0\nok" + assert tools["sandscale_write_file"].invoke({"path": "app.py", "content": "print(1)"}) == "wrote 8 bytes to /workspace/app.py" + assert tools["sandscale_read_file"].invoke({"path": "app.py"}) == "print(1)" + toolkit.close() + assert not any(r.method == "DELETE" for r in api.requests) + + +# --- OpenAI Agents SDK -------------------------------------------------------------------------- + + +def test_openai_agents_session(api: MockServer) -> None: + pytest.importorskip("agents.sandbox") + from agents.sandbox.errors import WorkspaceReadNotFoundError + from sandscale.integrations.openai_agents import ( + SandscaleSandboxClient, + SandscaleSandboxClientOptions, + SandscaleSandboxSession, + SandscaleSandboxSessionState, + ) + + store: dict[str, bytes] = {} + api.on("PUT", "/api/v1/sandbox/instances/{}/files", files(store)) + api.on("GET", "/api/v1/sandbox/instances/{}/files", files(store)) + api.json("POST", "/api/v1/sandbox/instances/{}/exec", 200, {"run_id": "r1", "exit_code": 0, "stdout": "hello\n", "stderr": ""}) + + async def scenario() -> None: + sc = SandscaleSandboxClient(client(api)) + session = await sc.create(options=SandscaleSandboxClientOptions(template="builtin:node", timeout_seconds=900)) + inner = session._inner + assert isinstance(inner, SandscaleSandboxSession) + assert inner.state.sandbox_id == "sb-1" and inner.state.manifest.root == "/workspace" + create = next(r for r in api.requests if r.route == "POST /api/v1/sandbox/instances") + body = create.json() + assert body["template_id"] == "builtin:node" and body["ttl_seconds"] == 900 + assert create.headers.get("idempotency-key", "").startswith("openai-agents-") + + res = await inner._exec_internal("echo", "hello", timeout=10) + assert (res.stdout, res.exit_code) == (b"hello\n", 0) + exec_req = [r for r in api.requests if r.route.endswith("/exec")][-1] + assert exec_req.json() == {"command": ["echo", "hello"], "timeout_sec": 10, "workdir": "/workspace"} + + assert await inner.running() + state = sc.deserialize_session_state(json.loads(inner.state.model_dump_json())) + assert isinstance(state, SandscaleSandboxSessionState) and state.sandbox_id == "sb-1" + + store["/workspace/missing-check"] = b"x" + await sc.delete(session) + assert api.requests[-1].route == "DELETE /api/v1/sandbox/instances/{}" + + asyncio.run(scenario()) + + +def test_openai_agents_read_maps_not_found(api: MockServer) -> None: + pytest.importorskip("agents.sandbox") + from agents.sandbox.errors import WorkspaceReadNotFoundError + from agents.sandbox.manifest import Manifest + from agents.sandbox.snapshot import resolve_snapshot + from sandscale.integrations.openai_agents import SandscaleSandboxSession, SandscaleSandboxSessionState + + api.json("GET", "/api/v1/sandbox/instances/{}/files", 404, error_body("not_found", "no such file")) + state = SandscaleSandboxSessionState( + manifest=Manifest(root="/workspace"), snapshot=resolve_snapshot(None, "s"), sandbox_id="sb-1" + ) + session = SandscaleSandboxSession(state=state, client=client(api)) + + async def read_missing() -> None: + # Skip the in-sandbox path check (it runs a helper through exec, which the mock does not). + async def no_check(path: Path | str, *, for_write: bool = False) -> Path: + return Path(path) + + session._validate_path_access = no_check # type: ignore[method-assign] + with pytest.raises(WorkspaceReadNotFoundError): + await session.read(Path("/workspace/nope.txt")) + + asyncio.run(read_missing()) + + +def test_openai_agents_shutdown_tolerates_an_ended_sandbox(api: MockServer) -> None: + pytest.importorskip("agents.sandbox") + from agents.sandbox.manifest import Manifest + from agents.sandbox.snapshot import resolve_snapshot + from sandscale.integrations.openai_agents import SandscaleSandboxSession, SandscaleSandboxSessionState + + api.json("DELETE", "/api/v1/sandbox/instances/{}", 404, error_body("not_found", "gone")) + state = SandscaleSandboxSessionState(manifest=Manifest(root="/workspace"), snapshot=resolve_snapshot(None, "s"), sandbox_id="sb-1") + asyncio.run(SandscaleSandboxSession(state=state, client=client(api)).shutdown()) diff --git a/tests/test_integrations_live.py b/tests/test_integrations_live.py new file mode 100644 index 0000000..ae0ec25 --- /dev/null +++ b/tests/test_integrations_live.py @@ -0,0 +1,103 @@ +# Copyright 2026 Neural Inverse +# SPDX-License-Identifier: Apache-2.0 +"""The framework adapters against the real Sandscale API, only when SANDSCALE_API_KEY is set. Each +test starts small sandboxes with a short time to live (they end by themselves if a stop is refused). +SANDSCALE_BASE_URL, SANDSCALE_ORG_ID and SANDSCALE_REGION are honoured. Nothing secret is printed.""" + +from __future__ import annotations + +import asyncio +import io +import os +from collections.abc import Iterator +from pathlib import Path + +import pytest + +from sandscale import Sandscale +from sandscale.errors import SandscaleError + +pytestmark = pytest.mark.skipif(not os.environ.get("SANDSCALE_API_KEY"), reason="SANDSCALE_API_KEY is not set") + +TTL = 300 +REGION = os.environ.get("SANDSCALE_REGION") or None + + +def _stop_quietly(close: object) -> None: + """A key without sandboxes:manage cannot stop a box: the box then ends at its time to live.""" + try: + close() # type: ignore[operator] + except SandscaleError as e: + if e.status != 403: + raise + + +try: + from langchain_tests.integration_tests import SandboxIntegrationTests +except ImportError: # pragma: no cover + SandboxIntegrationTests = None # type: ignore[assignment,misc] + + +if SandboxIntegrationTests is not None: + + class TestSandscaleSandboxStandard(SandboxIntegrationTests): # type: ignore[misc,valid-type] + """LangChain's standard sandbox suite (file tools and execute) on a real sandbox.""" + + # langchain-tests 1.2.0 still expects relative glob paths and a refused overwrite; Deep Agents + # 0.7 returns absolute glob paths and overwrites by design (its own local backend does the same). + for _name in [n for n in dir(SandboxIntegrationTests) if n.startswith("test_") and ("glob" in n or "write_existing" in n)]: + locals()[_name] = pytest.mark.xfail(reason="langchain-tests 1.2.0 and Deep Agents 0.7 disagree", strict=False)( + getattr(SandboxIntegrationTests, _name) + ) + + @pytest.fixture(scope="class") + def sandbox(self) -> Iterator[object]: + from sandscale.integrations.langchain import SandscaleSandbox + + backend = SandscaleSandbox.create(template="builtin:python", timeout_seconds=TTL, region=REGION) + try: + yield backend + finally: + _stop_quietly(backend.close) + + +def test_langchain_toolkit_live() -> None: + pytest.importorskip("langchain_core") + from sandscale.integrations.langchain import SandscaleToolkit + + toolkit = SandscaleToolkit.create(template="builtin:python", timeout_seconds=TTL, region=REGION) + try: + tools = {t.name: t for t in toolkit.get_tools()} + assert "wrote" in tools["sandscale_write_file"].invoke({"path": "hello.py", "content": "print(6 * 7)"}) + assert tools["sandscale_read_file"].invoke({"path": "hello.py"}) == "print(6 * 7)" + assert tools["sandscale_run"].invoke({"command": "python3 hello.py"}) == "exit code 0\n42\n" + finally: + _stop_quietly(toolkit.close) + + +def test_openai_agents_session_live() -> None: + pytest.importorskip("agents.sandbox") + from sandscale.integrations.openai_agents import SandscaleSandboxClient, SandscaleSandboxClientOptions + + async def scenario() -> None: + sc = SandscaleSandboxClient(Sandscale(region=REGION)) + session = await sc.create(options=SandscaleSandboxClientOptions(template="builtin:python", timeout_seconds=TTL, region=REGION)) + try: + await session.start() + res = await session.exec("echo", "hello from sandscale", shell=False) + assert res.ok() and res.stdout.decode().strip() == "hello from sandscale" + await session.write(Path("notes/a.txt"), io.BytesIO(b"one")) + assert (await session.read(Path("notes/a.txt"))).read() == b"one" + archive = (await session.persist_workspace()).read() + assert len(archive) > 0 + await session.exec("rm", "-rf", "notes", shell=False) + await session.hydrate_workspace(io.BytesIO(archive)) + assert (await session.read(Path("notes/a.txt"))).read() == b"one" + finally: + try: + await sc.delete(session) + except SandscaleError as e: + if e.status != 403: + raise + + asyncio.run(scenario()) diff --git a/tests/test_parity.py b/tests/test_parity.py index 4d84af1..a64cfd0 100644 --- a/tests/test_parity.py +++ b/tests/test_parity.py @@ -16,6 +16,7 @@ DefaultRetention, EntitlementError, LifecycleRule, + LimitExceededError, NoncurrentVersionExpiration, NotFoundError, PermissionDeniedError, @@ -141,6 +142,25 @@ def test_templates(api: MockServer, c: Sandscale) -> None: assert (st.status, st.progress_percent) == ("building", 50) +def test_builtin_templates_and_sandbox_template(api: MockServer, c: Sandscale) -> None: + api.json( + "GET", + "/api/v1/sandbox/templates", + 200, + {"data": [], "has_more": False, "builtin": [ + {"id": "builtin:base", "name": "base", "description": "Python and Node", "startable": True}, + {"id": "builtin:go", "name": "go", "image": "sandscale-go@sha256:1", "description": "Go", "startable": False, "reason": "not here"}, + ]}, + ) + api.json("GET", "/api/v1/sandbox/instances/{}", 200, {"id": "sb-1", "status": "running", "template": "builtin:go", "image": "sandscale-go@sha256:1"}) + got = c.templates.list().data + assert [(t.id, t.builtin, t.startable, t.status) for t in got] == [ + ("builtin:base", True, True, "ready"), ("builtin:go", True, False, "unavailable")] + assert (got[1].image, got[1].reason, got[1].description) == ("sandscale-go@sha256:1", "not here", "Go") + sb = c.sandboxes.get("sb-1") + assert (sb.template, sb.image) == ("builtin:go", "sandscale-go@sha256:1") + + def test_policy(api: MockServer, c: Sandscale) -> None: pol = {"max_concurrent": 5, "max_exec_time_sec": 60, "max_mem_mb": 1024, "max_cpu": 2, "max_disk_mb": None, "egress_allowlist": ["pypi.org"], "allowed_providers": [], "egress_presets": ["npm"], "hibernation": "default"} @@ -158,8 +178,15 @@ def test_policy(api: MockServer, c: Sandscale) -> None: # --- webhooks -------------------------------------------------------------------------------- +NOW = 1_800_000_000.0 + + +def v1(body: bytes, secret: str, t: int = int(NOW)) -> str: + return "v1=" + hmac.new(secret.encode(), str(t).encode() + b"." + body, hashlib.sha256).hexdigest() + + def sign(body: bytes, secret: str) -> str: - return "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest() + return f"t={int(NOW)},{v1(body, secret)}" def test_webhooks_and_secret_is_hidden(api: MockServer, c: Sandscale) -> None: @@ -179,22 +206,50 @@ def test_webhooks_and_secret_is_hidden(api: MockServer, c: Sandscale) -> None: def test_verify_webhook_signature() -> None: - body = b'{"id":"d1","type":"run.completed"}' + body = b'{"id":"d1","type":"sandbox.created"}' good = sign(body, "s3cret") - assert verify_webhook_signature(good, body, "s3cret") - assert verify_webhook_signature(good, body.decode(), "s3cret") - assert not verify_webhook_signature(good, body + b" ", "s3cret") # tampered body - assert not verify_webhook_signature(good, body, "other") # wrong secret - assert not verify_webhook_signature(good.replace("sha256=", "sha1="), body, "s3cret") # malformed - assert not verify_webhook_signature("sha256=zz", body, "s3cret") - assert not verify_webhook_signature("", body, "s3cret") - assert not verify_webhook_signature(None, body, "s3cret") - assert not verify_webhook_signature(good, body, "") + assert verify_webhook_signature(good, body, "s3cret", now=NOW) + assert verify_webhook_signature(good, body.decode(), "s3cret", now=NOW) + # during a rotation's overlap the header carries a second v1; either secret verifies + both = f"t={int(NOW)},{v1(body, 'new')},{v1(body, 'old')}" + assert verify_webhook_signature(both, body, "old", now=NOW) and verify_webhook_signature(both, body, "new", now=NOW) + assert not verify_webhook_signature(good, body + b" ", "s3cret", now=NOW) # tampered body + assert not verify_webhook_signature(good, body, "other", now=NOW) # wrong secret + assert not verify_webhook_signature(good, body, "s3cret", now=NOW + 301) # stale + assert not verify_webhook_signature(good, body, "s3cret", now=NOW - 301) # from the future + assert not verify_webhook_signature(f"t={int(NOW) - 1000},{v1(body, 's3cret')}", body, "s3cret", now=NOW) # replayed timestamp + assert not verify_webhook_signature("sha256=abcd", body, "s3cret", now=NOW) # the old format + assert not verify_webhook_signature(f"t={int(NOW)},v1=zz", body, "s3cret", now=NOW) + assert not verify_webhook_signature(v1(body, "s3cret"), body, "s3cret", now=NOW) # no timestamp + assert not verify_webhook_signature("", body, "s3cret", now=NOW) + assert not verify_webhook_signature(None, body, "s3cret", now=NOW) + assert not verify_webhook_signature(good, body, "", now=NOW) + + +def test_rotate_test_deliveries_redeliver_and_event_types(api: MockServer, c: Sandscale) -> None: + wh = {"id": "w1", "url": "https://h.test/x", "events": ["sandbox.created"], "active": True} + d = {"id": "d1", "webhook_id": "w1", "event_id": "e1", "event_type": "sandbox.created", "status": "delivered", "attempts": 1, "max_attempts": 8, "response_status": 200} + api.json("GET", "/api/v1/sandbox/webhooks/{}", 200, {**wh, "secret_version": 1, "lease_lead_seconds": 900}) + api.json("POST", "/api/v1/sandbox/webhooks/{}/rotate-secret", 200, {**wh, "secret_version": 2, "secret": "whsec_two", "secret_shown_once": True}) + api.json("POST", "/api/v1/sandbox/webhooks/{}/test", 202, {**d, "status": "pending"}) + api.json("GET", "/api/v1/sandbox/webhooks/{}/deliveries", 200, {"deliveries": [d], "next_before": "2026-11-18T00:00:00Z"}) + api.json("POST", "/api/v1/sandbox/webhooks/{}/deliveries/{}/redeliver", 202, {**d, "id": "d2", "redelivery_of": "d1", "status": "pending"}) + api.json("GET", "/api/v1/sandbox/webhooks/event-types", 200, {"event_types": [{"type": "sandbox.created"}]}) + got = c.webhooks.get("w1") + assert got.secret_version == 1 and got.lease_lead_seconds == 900 + rotated = c.webhooks.rotate_secret("w1", overlap_seconds=60) + assert last(api).json() == {"overlap_seconds": 60} + assert rotated.secret == "whsec_two" and "whsec_two" not in repr(rotated) and rotated.secret_version == 2 + assert c.webhooks.test("w1").status == "pending" + items, nxt = c.webhooks.list_deliveries("w1", limit=5) + assert items[0].event_type == "sandbox.created" and items[0].response_status == 200 and nxt == "2026-11-18T00:00:00Z" + assert c.webhooks.redeliver("w1", "d1").redelivery_of == "d1" + assert len(c.webhooks.event_types()) == 1 def test_verify_is_on_the_service(c: Sandscale) -> None: body = b"{}" - assert c.webhooks.verify(sign(body, "k"), body, "k") + assert c.webhooks.verify(sign(body, "k"), body, "k", now=NOW) # --- traces ---------------------------------------------------------------------------------- @@ -203,6 +258,19 @@ def test_verify_is_on_the_service(c: Sandscale) -> None: TID = "4bf92f3577b34da6a3ce929d0e0e4736" +def test_sandbox_activity(api: MockServer, c: Sandscale) -> None: + api.json( + "GET", + "/api/v1/sandbox/activity", + 200, + {"from": "2025-11-24", "to": "2026-11-23", "total": 5, "days": [{"date": "2026-11-20", "count": 2}, {"date": "2026-11-23", "count": 3}]}, + ) + a = c.sandboxes.activity(days=30) + assert last(api).query["days"] == "30" + assert (a.from_, a.to, a.total) == ("2025-11-24", "2026-11-23", 5) + assert [(d.date, d.count) for d in a.days] == [("2026-11-20", 2), ("2026-11-23", 3)] + + def test_traces(api: MockServer, c: Sandscale) -> None: summary = {"trace_id": TID, "start_time": "2026-11-18T00:00:00Z", "end_time": "2026-11-18T00:00:02Z", "duration_ms": 2000, "spans": 2, "errors": 0, "sandboxes": ["sb"], "vcpu_hours": 0.5, "usd": 0.01, "status": "ok"} @@ -411,18 +479,22 @@ def test_agent_cloud_tasks(api: MockServer, c: Sandscale) -> None: def test_billing_usage_regions(api: MockServer, c: Sandscale) -> None: - offer = {"plan": "pro", "name": "Pro", "monthly_minor": 2500, "included_vcpu_hours": 750, "overage_allowed": True, "features": ["workspaces"]} + offer = {"plan": "pro", "name": "Pro", "monthly_minor": 2500, "included_vcpu_hours": 1500, "overage_allowed": True, "features": ["workspaces"]} state = {"plan": "pro", "interval": "month", "paid_seats": 1, "overage_enabled": False, "cancel_at_period_end": False, "pending_plan": "free"} - api.json("GET", "/api/v1/orgs/{}/sandscale/billing", 200, {"state": state, "offer": offer, "balance": {"month": "2026-11", "used_vcpu_hours": "1.5"}, "plans": [offer]}) + api.json("GET", "/api/v1/orgs/{}/sandscale/billing", 200, {"state": state, "offer": offer, "balance": {"month": "2026-11", "resets_at": "2026-12-18T09:30:00Z", "period_start": "2026-11-18T09:30:00Z", "period_end": "2026-12-18T09:30:00Z", "period_kind": "billing_period", "allowance_prorated": True, "used_vcpu_hours": "1.5"}, "plans": [offer]}) api.json("POST", "/api/v1/orgs/{}/sandscale/billing/plan", 200, {"state": {**state, "plan": "team"}, "offer": offer}) api.json("PUT", "/api/v1/orgs/{}/sandscale/billing/overage", 200, {"state": {**state, "overage_enabled": True}, "offer": offer}) api.json("DELETE", "/api/v1/orgs/{}/sandscale/billing/plan/pending", 200, {"state": {**state, "pending_plan": None}}) api.json("POST", "/api/v1/orgs/{}/sandscale/billing/checkout", 201, {"id": "cs", "url": "https://pay.test/cs", "plan": "pro", "interval": "month", "seats": 1}) - api.json("GET", "/api/v1/sandscale/usage", 200, {"month": "2026-11", "vcpu_seconds_used": 10, "vcpu_seconds_left": 90, "running_boxes": 2, "running_by_region": {"us1": 2}}) + api.json("GET", "/api/v1/sandscale/usage", 200, {"month": "2026-11", "vcpu_seconds_used": 10, "vcpu_seconds_left": 90, "running_boxes": 2, "running_by_region": {"us1": 2}, "code_mode": {"runs": 7, "vcpu_seconds": 12}}) api.json("GET", "/api/v1/regions", 200, {"regions": [{"id": "us1", "status": "live", "api_url": "https://api.us.sandscale.dev"}]}) b = c.account.billing() assert last(api).path == f"/api/v1/orgs/{ORG}/sandscale/billing" assert (b.state.plan, b.state.pending_plan, b.offer.monthly_minor, b.balance.used_vcpu_hours, len(b.plans)) == ("pro", "free", 2500, "1.5", 1) + assert (b.balance.month, b.balance.period_kind, b.balance.allowance_prorated) == ("2026-11", "billing_period", True) + assert b.balance.period_start is not None and (b.balance.period_start.month, b.balance.period_start.day) == (11, 18) + assert b.balance.period_end is not None and (b.balance.period_end.month, b.balance.period_end.day) == (12, 18) + assert b.balance.resets_at == b.balance.period_end assert c.account.change_plan(plan="team", interval="month", seats=3).plan == "team" assert last(api).json() == {"plan": "team", "interval": "month", "seats": 3} assert c.account.set_overage(True).overage_enabled is True and last(api).json() == {"enabled": True} @@ -431,6 +503,7 @@ def test_billing_usage_regions(api: MockServer, c: Sandscale) -> None: assert co.url == "https://pay.test/cs" and last(api).json() == {"plan": "pro", "interval": "month"} u = c.account.usage() assert (u.vcpu_seconds_used, u.running_by_region) == (10, {"us1": 2}) + assert u.code_mode is not None and (u.code_mode.runs, u.code_mode.vcpu_seconds) == (7, 12) assert c.account.regions()[0].id == "us1" @@ -483,6 +556,39 @@ def test_not_in_plan_is_entitlement(api: MockServer, c: Sandscale, code: str) -> assert e.value.code == code +def test_feature_not_in_plan_carries_the_plan_the_server_named(api: MockServer, c: Sandscale) -> None: + api.json( + "POST", + "/api/v1/sandbox/instances", + 403, + {"error": {"code": "feature_not_in_plan", "message": "Workspaces are on the Pro plan.", "feature": "sandscale.workspaces", "feature_title": "Workspaces", "gives": "Long-lived environments.", "plan": "pro", "plan_name": "Pro"}}, + ) + with pytest.raises(EntitlementError) as e: + c.sandboxes.create() + r = e.value.plan_refusal + assert (r.feature, r.feature_title, r.gives, r.plan, r.plan_name) == ("sandscale.workspaces", "Workspaces", "Long-lived environments.", "pro", "Pro") + # Build Hosts carries the same fields in details. + from sandscale.errors import parse_error + + body = '{"error": {"code": "feature_not_in_plan", "message": "m", "details": {"field": "backend", "feature": "sandscale.byoc", "plan": "enterprise", "plan_name": "Enterprise"}}}' + err = parse_error(403, "Forbidden", body, {}) + assert isinstance(err, EntitlementError) and err.plan_refusal.plan == "enterprise" and err.plan_refusal.feature == "sandscale.byoc" + # An answer that names nothing leaves it empty. + api.json("POST", "/api/v1/sandbox/instances", 403, error_body("network_not_in_plan", "upgrade")) + with pytest.raises(EntitlementError) as e2: + c.sandboxes.create() + assert e2.value.plan_refusal.plan is None + + +def test_402_limit_codes_expose_plan_limit_and_value(api: MockServer, c: Sandscale) -> None: + from sandscale.errors import parse_error, LimitExceededError + + body = '{"error": {"code": "lease_vcpu_limit", "message": "m", "details": {"plan": "free", "max_vcpus": 2, "vcpus": 4}}}' + err = parse_error(402, "Payment Required", body, {}) + assert isinstance(err, LimitExceededError) + assert err.limit_info.plan == "free" and err.limit_info.max == 2 + + def test_entitlement_unavailable_is_retryable_unavailable(api: MockServer, c: Sandscale) -> None: api.json("POST", "/api/v1/sandbox/instances", 503, error_body("entitlement_unavailable", "stale")) with pytest.raises(ServiceUnavailableError) as e: @@ -538,3 +644,63 @@ def test_prepare_never_raises_for_a_waking_sandbox(api: MockServer, c: Sandscale api.json("POST", "/api/v1/sandbox/instances/{}/prepare", 503, error_body("sandbox_waking", "resuming")) c.sandboxes.prepare("sb") assert len(api.requests) == 1 + + +def test_usage_fair_use_fields_and_identity(api: MockServer, c: Sandscale) -> None: + api.json( + "GET", + "/api/v1/sandscale/usage", + 200, + { + "month": "2026-11", "vcpu_seconds_used": 10, "vcpu_seconds_left": 90, "running_boxes": 0, "running_by_region": {}, + "limits": {"plan": "free", "max_boxes": 2, "vcpu_seconds": 540000, "gpus": False, "fair_use": True, "daily_vcpu_seconds": 54000, "ramp_days": 7, "ramp_max_boxes": 1, "ramp_daily_vcpu_seconds": 18000, "trust_github_min_age_days": 90}, + "daily": {"window_seconds": 86400, "used_vcpu_seconds": 54000, "limit_vcpu_seconds": 54000, "left_vcpu_seconds": 0, "at_cap": True, "retry_at": "2026-11-19T10:01:00Z"}, + "period": {"starts_at": "2026-10-31T12:00:00Z", "resets_at": "2026-11-30T12:00:00Z", "used_vcpu_seconds": 10, "limit_vcpu_seconds": 540000, "left_vcpu_seconds": 539990}, + "ramp": {"active": True, "ends_at": "2026-11-25T00:00:00Z", "max_boxes": 1, "daily_vcpu_seconds": 18000, "trust_signals": [], "lift_with": ["github_account", "card", "operator_approval"]}, + "free": {"claim": "held"}, + }, + ) + api.json("GET", "/api/v1/sandscale/identity", 200, {"github_linked": True, "github_account_old_enough": False, "card_verified": False, "card_refusal": "account_exists"}) + api.json("POST", "/api/v1/sandscale/identity/github/start", 200, {"authorize_url": "https://github.com/login/oauth/authorize?x=1", "state": "s1", "expires_at": "2026-11-18T00:10:00Z"}) + api.json("POST", "/api/v1/sandscale/identity/github/complete", 200, {"github_linked": True, "github_account_old_enough": True, "card_verified": False, "card_refusal": ""}) + u = c.account.usage() + assert u.limits is not None and (u.limits.fair_use, u.limits.daily_vcpu_seconds, u.limits.ramp_max_boxes) == (True, 54000, 1) + assert u.daily is not None and (u.daily.at_cap, u.daily.left_vcpu_seconds) == (True, 0) and u.daily.retry_at is not None + assert u.period is not None and u.period.left_vcpu_seconds == 539990 and u.period.resets_at is not None + assert u.ramp is not None and u.ramp.active and u.ramp.lift_with == ["github_account", "card", "operator_approval"] + assert u.free_claim == "held" + i = c.account.identity() + assert (i.github_linked, i.github_account_old_enough, i.card_refusal) == (True, False, "account_exists") + assert c.account.github_start().state == "s1" + done = c.account.github_complete("code", "s1") + assert done.github_account_old_enough and last(api).json() == {"code": "code", "state": "s1"} and done.card_refusal is None + + +def test_plan_offer_lease_and_vault_fields(api: MockServer, c: Sandscale) -> None: + offer = {"plan": "free", "name": "Free", "max_lease_hours": 1, "max_concurrent_leases": 1, "max_vcpu_per_lease": 2, "lease_network": "registry", "max_lab_hosts": -1, "lab_hosts_per_seat": True, "max_vault_stores": 1, "max_vault_secrets": -1} + api.json("GET", "/api/v1/orgs/{}/sandscale/billing", 200, {"state": {"plan": "free"}, "offer": offer, "balance": {}, "plans": [offer]}) + o = c.account.billing().offer + assert (o.max_lease_hours, o.max_concurrent_leases, o.max_vcpu_per_lease, o.lease_network) == (1, 1, 2, "registry") + assert (o.max_lab_hosts, o.lab_hosts_per_seat, o.max_vault_stores, o.max_vault_secrets) == (-1, True, 1, -1) + + +@pytest.mark.parametrize( + "code,details", + [ + ("lease_duration_limit", {"field": "duration_seconds", "max_seconds": 3600, "plan": "free", "max_lease_hours": 1}), + ("lease_vcpu_limit", {"plan": "free", "max_vcpus": 2, "vcpus": 4}), + ("lease_concurrent_limit", {"plan": "free", "max_concurrent_leases": 1, "open_leases": 1}), + ("lab_host_limit", {"plan": "free", "max_lab_hosts": 1, "lab_hosts": 1}), + ("vault_secret_limit", None), + ("vault_store_limit", None), + ], +) +def test_lease_and_vault_limits_are_limit_errors(api: MockServer, c: Sandscale, code: str, details: Any) -> None: + api.json("POST", "/api/v1/sandbox/instances", 402, error_body(code, "Upgrade the plan", **({"details": details} if details else {}))) + with pytest.raises(LimitExceededError) as e: + c.sandboxes.create() + assert not isinstance(e.value, EntitlementError) and e.value.code == code and e.value.status == 402 + assert not getattr(e.value, "retryable", False) + if details: + assert e.value.details == details + assert len(api.requests) == 1 diff --git a/tests/test_routes.py b/tests/test_routes.py index e037375..ea526c8 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,12 +1,11 @@ # Copyright 2026 Neural Inverse # SPDX-License-Identifier: Apache-2.0 -"""The routes this SDK calls. The test fails when the SDK calls a route not listed here and, when -SANDSCALE_ROUTE_INVENTORY names the server's route inventory files (colon separated; the source -repository sets it), when the server stops mounting one of them.""" +"""The routes this SDK calls. The test fails when the server stops mounting one of them (the +route inventory of the Keystone repository, which cmd/server's contract test proves matches the +live router), or when the SDK calls a route not listed here.""" from __future__ import annotations -import os import re from pathlib import Path from typing import Iterator @@ -19,8 +18,14 @@ ROUTES = [ "GET /api/v1/regions", + "POST /api/v1/sandbox/code/tasks", + "GET /api/v1/sandbox/code/tasks/{}", + "POST /api/v1/sandbox/code/search", + "GET /api/v1/sandbox/code/policy", + "PUT /api/v1/sandbox/code/policy", "POST /api/v1/sandbox/instances", "GET /api/v1/sandbox/instances", + "GET /api/v1/sandbox/activity", "GET /api/v1/sandbox/instances/{}", "DELETE /api/v1/sandbox/instances/{}", "POST /api/v1/sandbox/instances/{}/pause", @@ -34,6 +39,18 @@ "GET /api/v1/sandbox/instances/{}/logs", "PUT /api/v1/sandbox/instances/{}/files", "GET /api/v1/sandbox/instances/{}/files", + "POST /api/v1/sandbox/volumes", + "GET /api/v1/sandbox/volumes", + "GET /api/v1/sandbox/volumes/{}", + "DELETE /api/v1/sandbox/volumes/{}", + "POST /api/v1/sandbox/instances/{}/volumes", + "GET /api/v1/sandbox/instances/{}/volumes", + "POST /api/v1/sandbox/instances/{}/volumes/{}/commit", + "DELETE /api/v1/sandbox/instances/{}/volumes/{}", + "POST /api/v1/sandbox/instances/{}/caches/restore", + "POST /api/v1/sandbox/instances/{}/caches/save", + "GET /api/v1/sandbox/caches", + "DELETE /api/v1/sandbox/caches/{}", "GET /api/v1/orgs/{}/workspaces", "GET /api/v1/orgs/{}/workspaces/{}", "POST /api/v1/orgs/{}/workspaces/{}/start", @@ -65,7 +82,13 @@ "PUT /api/v1/sandbox/policy", "GET /api/v1/sandbox/webhooks", "POST /api/v1/sandbox/webhooks", + "GET /api/v1/sandbox/webhooks/{}", + "GET /api/v1/sandbox/webhooks/event-types", "DELETE /api/v1/sandbox/webhooks/{}", + "POST /api/v1/sandbox/webhooks/{}/rotate-secret", + "POST /api/v1/sandbox/webhooks/{}/test", + "GET /api/v1/sandbox/webhooks/{}/deliveries", + "POST /api/v1/sandbox/webhooks/{}/deliveries/{}/redeliver", "GET /api/v1/sandbox/traces", "GET /api/v1/sandbox/traces/{}", "GET /api/v1/sandbox/trace-export", @@ -122,25 +145,29 @@ "DELETE /api/v1/orgs/{}/sandscale/billing/plan/pending", "POST /api/v1/orgs/{}/sandscale/billing/checkout", "GET /api/v1/sandscale/usage", + "GET /api/v1/sandscale/identity", + "POST /api/v1/sandscale/identity/github/start", + "POST /api/v1/sandscale/identity/github/complete", "GET /api/v1/account/api-keys", "POST /api/v1/account/api-keys", "POST /api/v1/account/api-keys/{}/rotate", "DELETE /api/v1/account/api-keys/{}", ] -#: The server's route inventory files, colon separated. The source repository sets -#: SANDSCALE_ROUTE_INVENTORY; without it the contract check is skipped. -INVENTORY_FILES = [Path(p) for p in os.environ.get("SANDSCALE_ROUTE_INVENTORY", "").split(":") if p] +INVENTORY = Path(__file__).resolve().parents[4] / "modules/access/internal/routes/testdata/routes.txt" +#: The routes of every mux with their product line (cmd/server's contract test): it also lists +#: routes the first inventory has not caught up with (the run trace routes). +PRODUCT_LINE_INVENTORY = Path(__file__).resolve().parents[4] / "cmd/server/testdata/product_line_routes.txt" -@pytest.mark.skipif(not INVENTORY_FILES or not all(p.exists() for p in INVENTORY_FILES), reason="SANDSCALE_ROUTE_INVENTORY is not set") +@pytest.mark.skipif(not INVENTORY.exists(), reason="the route inventory is only in the Keystone repository") def test_server_mounts_every_route() -> None: - mounted: set[str] = set() - for inventory in INVENTORY_FILES: - for line in inventory.read_text().splitlines(): - m = re.match(r"^(?:\S+ )?((?:GET|POST|PUT|PATCH|DELETE) /\S*)", line) - if m: - mounted.add(re.sub(r"\{[^}/]*\}", "{}", m.group(1))) + mounted = {re.sub(r"\{[^}/]*\}", "{}", line.strip()) for line in INVENTORY.read_text().splitlines() if line.strip()} + if PRODUCT_LINE_INVENTORY.exists(): + for line in PRODUCT_LINE_INVENTORY.read_text().splitlines(): + parts = line.split("\t")[0].split(" ") + if len(parts) == 3: + mounted.add(re.sub(r"\{[^}/]*\}", "{}", f"{parts[1]} {parts[2]}")) missing = [r for r in ROUTES if r not in mounted] assert missing == [], f"routes the SDK calls that the server no longer mounts: {missing}" @@ -149,11 +176,31 @@ def test_server_mounts_every_route() -> None: def api() -> Iterator[MockServer]: server = MockServer() lease = {"id": "l", "pool_id": "p", "state": "active", "workspace_id": "w"} + volume = {"id": "v", "name": "deps", "status": "ready", "version": 1, "size_bytes": 0, "max_bytes": 1, "readers": 0} for route in ROUTES: method, pattern = route.split(" ") def handler(_req: Recorded, reply: Reply, route: str = route, method: str = method) -> None: - if route == "GET /api/v1/regions": + if route.startswith(("POST /api/v1/sandbox/code/tasks", "GET /api/v1/sandbox/code/tasks")): + reply.json(200, {"task_id": "t", "state": "succeeded", "result": 1, "console": []}) + return + if route == "POST /api/v1/sandbox/code/search": + reply.json(200, {"result": [], "console": [], "truncated": False}) + return + if route.endswith("/code/policy"): + reply.json(200, {"ask_first": []}) + return + if method == "DELETE" and ("/volumes" in route or "/caches" in route): + reply.json(204) + elif method == "GET" and route.endswith(("/volumes", "/caches")): + reply.json(200, {"data": []}) + elif "/caches/" in route: + reply.json(200, {"key": "k", "ecosystem": "npm", "path": "/root/.npm", "hit": False, "saved": False, "exists": False, "size_bytes": 0}) + elif route == "POST /api/v1/sandbox/instances/{}/volumes": + reply.json(201, {"id": "a", "volume_id": "v", "instance_id": "x", "mode": "rw", "mount_path": "/data", "base_version": 0}) + elif "/volumes" in route: + reply.json(201 if route == "POST /api/v1/sandbox/volumes" else 200, volume) + elif route == "GET /api/v1/regions": reply.json(200, {"regions": [{"id": "us1", "status": "live", "api_url": server.url}]}) elif route.endswith("/logs"): reply.sse([("done", {})]) @@ -202,6 +249,7 @@ def test_sdk_calls_exactly_the_listed_routes(api: MockServer) -> None: s = c.sandboxes s.create(region="us") s.list() + s.activity() s.get("x") s.stop("x") s.pause("x") @@ -215,6 +263,18 @@ def test_sdk_calls_exactly_the_listed_routes(api: MockServer) -> None: list(s.logs("x", "r")) s.write_file("x", "/workspace/a", "a") s.read_file("x", "/workspace/a") + s.attach_volume("x", "v", "/data") + s.list_attachments("x") + s.commit_volume("x", "v") + s.detach_volume("x", "v", commit=False) + s.restore_cache("x", ecosystem="npm", lockfile="/workspace/package-lock.json") + s.save_cache("x", ecosystem="npm", lockfile="/workspace/package-lock.json") + c.volumes.create("deps", max_bytes=1) + c.volumes.list() + c.volumes.get("v") + c.volumes.delete("v") + c.caches.list() + c.caches.delete("c") w = c.workspaces w.list() w.get("w") @@ -248,8 +308,19 @@ def test_sdk_calls_exactly_the_listed_routes(api: MockServer) -> None: c.policy.get() c.policy.set(max_cpu=1) c.webhooks.list() - c.webhooks.create(url="https://h.test/x") + c.webhooks.create(url="https://h.test/x", events=["sandbox.created"]) + c.webhooks.event_types() + c.webhooks.get("w") c.webhooks.delete("w") + c.webhooks.rotate_secret("w") + c.webhooks.test("w") + c.webhooks.list_deliveries("w") + c.webhooks.redeliver("w", "d") + c.execute("return 1") + c.tasks.get("t") + c.search('return api.find("box")') + c.code_policy.get() + c.code_policy.set([]) c.traces.list() c.traces.get("a" * 32) c.traces.get_export() @@ -308,6 +379,9 @@ def test_sdk_calls_exactly_the_listed_routes(api: MockServer) -> None: a.cancel_pending_plan_change() a.checkout(plan="pro", interval="month") a.usage() + a.identity() + a.github_start() + a.github_complete("c", "s") a.regions() a.list_api_keys() a.create_api_key(name="n", expires_at="2027-01-01T00:00:00Z")