Metadata-Version: 2.5
Name: sandbox-ai-sdk
Version: 0.1.1
Summary: Python client for Sandbox AI: propose changes to business systems and read the decision
Author: Sandbox AI
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic>=2.9
Description-Content-Type: text/markdown

# sandbox-ai-sdk

The Python client for Sandbox AI. An agent proposes a change to a record in a business system, such as Salesforce or ServiceNow, and gets back what Sandbox AI decided for each field: applied, held for a person's approval, or blocked by a rule. Built on `httpx` and Pydantic. Python 3.11 and later.

> **Alpha.** This is an early release, and the API may change before 1.0. It needs access to a Sandbox AI gateway: an agent key and the gateway's address.

## Install

```
pip install sandbox-ai-sdk
```

Or `uv add sandbox-ai-sdk`. The import is `sandbox_ai`.

## Quick start

1. In the Sandbox AI dashboard, open **Agents**, add your agent and create a key. Copy it: you only see it once.
2. Give the client the key and your gateway's address, as arguments or as environment variables. Both are required:

   ```
   export SANDBOX_AI_API_KEY=sbx_...
   export SANDBOX_AI_BASE_URL=https://your-gateway.example.com
   ```

3. Propose a change:

```python
from sandbox_ai import Client

client = Client()  # reads SANDBOX_AI_API_KEY and SANDBOX_AI_BASE_URL
# or: Client(api_key="sbx_...", base_url="https://your-gateway.example.com")

decision = client.propose_change(
    "salesforce",  # system
    "account",  # object
    "001-SAMPLE-0142",  # record_id: None to create a record
    {"OwnerId": "005-SAMPLE-MARCUS"},
    reason="Customer asked to work with Marcus",  # shown to approvers
)

if decision.status == "needs_approval":
    # A person decides. Check again later.
    decision = client.get_decision(decision.change_id)
```

The key identifies the agent, so there's no agent id to pass. Use the client as a context manager (`with Client(...) as client:`) or call `client.close()` when done.

## What the status means

| `decision.status` | What happened | What the agent should do |
| --- | --- | --- |
| `applied` | Every field was written and confirmed | Carry on |
| `needs_approval` | A rule sent it to a person | Call `get_decision` later |
| `partially_applied` | Some fields were written. The rest were blocked by rules, declined by the approver, or not decided in time | Check `decision.fields`, and `decision.approval.comment` for what the approver said when there was an approval |
| `blocked`, `rejected`, `expired` | Nothing was written | Read `decision.message` or `field.message` for why |
| `conflict` | The record changed since Sandbox AI read it | Read the record again, then propose again |
| `error` | The system refused the change | Read `field.message` |
| `observed` | The connection is watch-only, so nothing was written | Keep writing through your existing path |

Each item in `decision.fields` has the field, `before`, `after`, the `outcome` (`allow`, `needs_approval` or `blocked`), the `rule_ids` that decided it, and whether it was `written`.

`decision.message` and `decision.rule_ids` say why for the change as a whole. A delete has no fields and is always `blocked`, in watch-only too, so those two are always set for one.

## Errors

`Client()` raises `SandboxAIError` when a setting is missing or invalid, and so does a request that fails. (`propose_change` with an empty `fields` raises `ValueError` instead, before anything is sent.) The error has:

- `code`: the API's error code, such as `unauthorized`, `agent_paused`, `invalid_request`, `unknown_system` or `rate_limited`. The SDK adds its own: `missing_api_key`, `invalid_api_key`, `missing_base_url`, `invalid_base_url`, `insecure_base_url`, `key_in_base_url`, `timeout`, `network_error` and `unexpected_response`.
- `message`: plain words, safe to show to people and to agents.
- `status`: the HTTP status, when there was one.
- `retry_after`: whole seconds to wait, from the `Retry-After` header, after `rate_limited`. `None` if the gateway didn't say.
- `details`: the extra context the gateway sent, such as which fields failed an `invalid_request`. `None` if it sent none.
- `idempotency_key`: the key to retry with, after `propose_change` failed in a way that may have left the change made. `None` otherwise.

### Retrying a change safely

Every `propose_change` call sends an idempotency key: yours, or one the SDK makes. If the call times out waiting for an answer, the connection drops after sending, or the gateway answers with a 5xx or something the SDK can't read, the change may already have been made. Retry with the key from the error, within 24 hours, and the gateway returns the first decision instead of making the change twice:

```python
from sandbox_ai import Client, SandboxAIError

client = Client()

try:
    decision = client.propose_change("salesforce", "account", None, {"Name": "Acme"})
except SandboxAIError as error:
    if not error.idempotency_key:
        raise
    decision = client.propose_change(
        "salesforce", "account", None, {"Name": "Acme"}, idempotency_key=error.idempotency_key
    )
```

The error's message names the key too, so it's there for an agent reading the text. If the connection never opened, such as a refused connection, a connection that timed out before it opened, or a wrong address, nothing was sent: `idempotency_key` is `None` and the message says to check the address. A 4xx means the gateway refused the request, so it's `None` then too.

Keys belong to the API key that sent them, so another agent's key never matches yours. `get_decision` only reads, so after a timeout there's no key to think about: just call it again.

The API key never appears in errors, logs or `repr(client)`.

## Settings

| Argument | Environment variable | Default |
| --- | --- | --- |
| `api_key` | `SANDBOX_AI_API_KEY` | required |
| `base_url` | `SANDBOX_AI_BASE_URL` | required: the address of your Sandbox AI gateway |
| `timeout` | | 10 seconds |
| `allow_http` | `SANDBOX_AI_ALLOW_HTTP` | off: a plain `http://` address is refused with `insecure_base_url`, because it would send the key unencrypted, unless the gateway is local (`localhost`, a name under `.localhost`, a loopback address, `0.0.0.0` or `::`). Pass `allow_http=True` or set the variable to `1` to allow it on a network you trust |

An explicit `allow_http=True` or `allow_http=False` wins over the variable, and the variable only counts when it's exactly `1`.

A blank or whitespace-only `base_url` argument counts as not given, so the client falls back to `SANDBOX_AI_BASE_URL`. `api_key` is stricter: only leaving it out (or passing `None`) reads `SANDBOX_AI_API_KEY`. A blank or whitespace-only `api_key` raises `missing_api_key`, so an agent whose own key is missing never runs with another agent's key from the environment.

## Changes in 0.1.1

- **Plain http to a gateway that isn't local is refused**, with the new code `insecure_base_url`, because it would send the API key unencrypted. That includes `http://host.docker.internal`. `http://localhost`, a name under `.localhost` such as `http://app.localhost`, other loopback addresses, `http://0.0.0.0` and `http://[::]` still work. To allow plain http on a network you trust, pass `allow_http=True` or set `SANDBOX_AI_ALLOW_HTTP=1`.
- **Requests over plain http to a local address ignore the proxy settings in the environment**, such as `HTTP_PROXY` and `ALL_PROXY`, and go straight to that address. Local means `localhost`, a name under `.localhost`, a loopback address, `0.0.0.0` or `::`, the addresses plain http is allowed to without the opt-in. A name under `.localhost` is trusted by its name alone, so make sure it points at this machine. https addresses, and remote http you've allowed, use the proxy settings as before.
- **An address with your API key in it is refused**, with the new code `key_in_base_url`.
- **Addresses that can never work are refused when you create the `Client`**, with `invalid_base_url`: a `?` anywhere, a port outside 1 to 65535, or whitespace or a `%` in the host. Before, they failed on the first call.
- **An invalid internationalised host**, such as an `xn--` name that isn't valid punycode, is refused with `invalid_base_url` instead of raising an `idna` error.
- **A blank or whitespace-only `api_key` argument raises `missing_api_key`** instead of falling back to `SANDBOX_AI_API_KEY`. Leave `api_key` out to read the variable.
- **Error messages and `repr(client)` show `[redacted]`** in place of anything in the gateway address that looks like a key, in any case. `client.base_url` and httpx's own request log still show the address as given.
- If you run the MCP server with `uvx sandbox-ai-mcp`, run `uvx sandbox-ai-mcp@latest` once to pick up this update.

## License

Apache-2.0. The full license text is in the LICENSE file included in the package.
