sandbox-ai-sdk 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sandbox_ai_sdk-0.1.0/.gitignore +15 -0
- sandbox_ai_sdk-0.1.0/LICENSE +202 -0
- sandbox_ai_sdk-0.1.0/PKG-INFO +135 -0
- sandbox_ai_sdk-0.1.0/README.md +112 -0
- sandbox_ai_sdk-0.1.0/pyproject.toml +39 -0
- sandbox_ai_sdk-0.1.0/src/sandbox_ai/__init__.py +15 -0
- sandbox_ai_sdk-0.1.0/src/sandbox_ai/client.py +279 -0
- sandbox_ai_sdk-0.1.0/src/sandbox_ai/errors.py +49 -0
- sandbox_ai_sdk-0.1.0/src/sandbox_ai/models.py +113 -0
- sandbox_ai_sdk-0.1.0/src/sandbox_ai/py.typed +0 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sandbox-ai-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for Sandbox AI: propose changes to business systems and read the decision
|
|
5
|
+
Author: Sandbox AI
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Requires-Dist: httpx>=0.27
|
|
21
|
+
Requires-Dist: pydantic>=2.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# sandbox-ai-sdk
|
|
25
|
+
|
|
26
|
+
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.
|
|
27
|
+
|
|
28
|
+
> **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.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
pip install sandbox-ai-sdk
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Or `uv add sandbox-ai-sdk`. The import is `sandbox_ai`.
|
|
37
|
+
|
|
38
|
+
## Quick start
|
|
39
|
+
|
|
40
|
+
1. In the Sandbox AI dashboard, open **Agents**, add your agent and create a key. Copy it: you only see it once.
|
|
41
|
+
2. Give the client the key and your gateway's address, as arguments or as environment variables. Both are required:
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
export SANDBOX_AI_API_KEY=sbx_...
|
|
45
|
+
export SANDBOX_AI_BASE_URL=https://your-gateway.example.com
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
3. Propose a change:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from sandbox_ai import Client
|
|
52
|
+
|
|
53
|
+
client = Client() # reads SANDBOX_AI_API_KEY and SANDBOX_AI_BASE_URL
|
|
54
|
+
# or: Client(api_key="sbx_...", base_url="https://your-gateway.example.com")
|
|
55
|
+
|
|
56
|
+
decision = client.propose_change(
|
|
57
|
+
"salesforce", # system
|
|
58
|
+
"account", # object
|
|
59
|
+
"001-SAMPLE-0142", # record_id: None to create a record
|
|
60
|
+
{"OwnerId": "005-SAMPLE-MARCUS"},
|
|
61
|
+
reason="Customer asked to work with Marcus", # shown to approvers
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
if decision.status == "needs_approval":
|
|
65
|
+
# A person decides. Check again later.
|
|
66
|
+
decision = client.get_decision(decision.change_id)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
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.
|
|
70
|
+
|
|
71
|
+
## What the status means
|
|
72
|
+
|
|
73
|
+
| `decision.status` | What happened | What the agent should do |
|
|
74
|
+
| --- | --- | --- |
|
|
75
|
+
| `applied` | Every field was written and confirmed | Carry on |
|
|
76
|
+
| `needs_approval` | A rule sent it to a person | Call `get_decision` later |
|
|
77
|
+
| `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 |
|
|
78
|
+
| `blocked`, `rejected`, `expired` | Nothing was written | Read `decision.message` or `field.message` for why |
|
|
79
|
+
| `conflict` | The record changed since Sandbox AI read it | Read the record again, then propose again |
|
|
80
|
+
| `error` | The system refused the change | Read `field.message` |
|
|
81
|
+
| `observed` | The connection is watch-only, so nothing was written | Keep writing through your existing path |
|
|
82
|
+
|
|
83
|
+
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`.
|
|
84
|
+
|
|
85
|
+
`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.
|
|
86
|
+
|
|
87
|
+
## Errors
|
|
88
|
+
|
|
89
|
+
Everything raises `SandboxAIError`, with:
|
|
90
|
+
|
|
91
|
+
- `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`, `timeout`, `network_error` and `unexpected_response`.
|
|
92
|
+
- `message`: plain words, safe to show to people and to agents.
|
|
93
|
+
- `status`: the HTTP status, when there was one.
|
|
94
|
+
- `retry_after`: whole seconds to wait, from the `Retry-After` header, after `rate_limited`. `None` if the gateway didn't say.
|
|
95
|
+
- `details`: the extra context the gateway sent, such as which fields failed an `invalid_request`. `None` if it sent none.
|
|
96
|
+
- `idempotency_key`: the key to retry with, after `propose_change` failed in a way that may have left the change made. `None` otherwise.
|
|
97
|
+
|
|
98
|
+
### Retrying a change safely
|
|
99
|
+
|
|
100
|
+
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:
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from sandbox_ai import Client, SandboxAIError
|
|
104
|
+
|
|
105
|
+
client = Client()
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
decision = client.propose_change("salesforce", "account", None, {"Name": "Acme"})
|
|
109
|
+
except SandboxAIError as error:
|
|
110
|
+
if not error.idempotency_key:
|
|
111
|
+
raise
|
|
112
|
+
decision = client.propose_change(
|
|
113
|
+
"salesforce", "account", None, {"Name": "Acme"}, idempotency_key=error.idempotency_key
|
|
114
|
+
)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
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.
|
|
118
|
+
|
|
119
|
+
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.
|
|
120
|
+
|
|
121
|
+
The API key never appears in errors, logs or `repr(client)`.
|
|
122
|
+
|
|
123
|
+
## Settings
|
|
124
|
+
|
|
125
|
+
| Argument | Environment variable | Default |
|
|
126
|
+
| --- | --- | --- |
|
|
127
|
+
| `api_key` | `SANDBOX_AI_API_KEY` | required |
|
|
128
|
+
| `base_url` | `SANDBOX_AI_BASE_URL` | required: the address of your Sandbox AI gateway |
|
|
129
|
+
| `timeout` | | 10 seconds |
|
|
130
|
+
|
|
131
|
+
A blank or whitespace-only `api_key` or `base_url` argument counts as not given, so the client falls back to `SANDBOX_AI_API_KEY` or `SANDBOX_AI_BASE_URL`.
|
|
132
|
+
|
|
133
|
+
## License
|
|
134
|
+
|
|
135
|
+
Apache-2.0. The full license text is in the LICENSE file included in the package.
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# sandbox-ai-sdk
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
> **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.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
pip install sandbox-ai-sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or `uv add sandbox-ai-sdk`. The import is `sandbox_ai`.
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
1. In the Sandbox AI dashboard, open **Agents**, add your agent and create a key. Copy it: you only see it once.
|
|
18
|
+
2. Give the client the key and your gateway's address, as arguments or as environment variables. Both are required:
|
|
19
|
+
|
|
20
|
+
```
|
|
21
|
+
export SANDBOX_AI_API_KEY=sbx_...
|
|
22
|
+
export SANDBOX_AI_BASE_URL=https://your-gateway.example.com
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
3. Propose a change:
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from sandbox_ai import Client
|
|
29
|
+
|
|
30
|
+
client = Client() # reads SANDBOX_AI_API_KEY and SANDBOX_AI_BASE_URL
|
|
31
|
+
# or: Client(api_key="sbx_...", base_url="https://your-gateway.example.com")
|
|
32
|
+
|
|
33
|
+
decision = client.propose_change(
|
|
34
|
+
"salesforce", # system
|
|
35
|
+
"account", # object
|
|
36
|
+
"001-SAMPLE-0142", # record_id: None to create a record
|
|
37
|
+
{"OwnerId": "005-SAMPLE-MARCUS"},
|
|
38
|
+
reason="Customer asked to work with Marcus", # shown to approvers
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
if decision.status == "needs_approval":
|
|
42
|
+
# A person decides. Check again later.
|
|
43
|
+
decision = client.get_decision(decision.change_id)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
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.
|
|
47
|
+
|
|
48
|
+
## What the status means
|
|
49
|
+
|
|
50
|
+
| `decision.status` | What happened | What the agent should do |
|
|
51
|
+
| --- | --- | --- |
|
|
52
|
+
| `applied` | Every field was written and confirmed | Carry on |
|
|
53
|
+
| `needs_approval` | A rule sent it to a person | Call `get_decision` later |
|
|
54
|
+
| `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 |
|
|
55
|
+
| `blocked`, `rejected`, `expired` | Nothing was written | Read `decision.message` or `field.message` for why |
|
|
56
|
+
| `conflict` | The record changed since Sandbox AI read it | Read the record again, then propose again |
|
|
57
|
+
| `error` | The system refused the change | Read `field.message` |
|
|
58
|
+
| `observed` | The connection is watch-only, so nothing was written | Keep writing through your existing path |
|
|
59
|
+
|
|
60
|
+
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`.
|
|
61
|
+
|
|
62
|
+
`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.
|
|
63
|
+
|
|
64
|
+
## Errors
|
|
65
|
+
|
|
66
|
+
Everything raises `SandboxAIError`, with:
|
|
67
|
+
|
|
68
|
+
- `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`, `timeout`, `network_error` and `unexpected_response`.
|
|
69
|
+
- `message`: plain words, safe to show to people and to agents.
|
|
70
|
+
- `status`: the HTTP status, when there was one.
|
|
71
|
+
- `retry_after`: whole seconds to wait, from the `Retry-After` header, after `rate_limited`. `None` if the gateway didn't say.
|
|
72
|
+
- `details`: the extra context the gateway sent, such as which fields failed an `invalid_request`. `None` if it sent none.
|
|
73
|
+
- `idempotency_key`: the key to retry with, after `propose_change` failed in a way that may have left the change made. `None` otherwise.
|
|
74
|
+
|
|
75
|
+
### Retrying a change safely
|
|
76
|
+
|
|
77
|
+
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:
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from sandbox_ai import Client, SandboxAIError
|
|
81
|
+
|
|
82
|
+
client = Client()
|
|
83
|
+
|
|
84
|
+
try:
|
|
85
|
+
decision = client.propose_change("salesforce", "account", None, {"Name": "Acme"})
|
|
86
|
+
except SandboxAIError as error:
|
|
87
|
+
if not error.idempotency_key:
|
|
88
|
+
raise
|
|
89
|
+
decision = client.propose_change(
|
|
90
|
+
"salesforce", "account", None, {"Name": "Acme"}, idempotency_key=error.idempotency_key
|
|
91
|
+
)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
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.
|
|
95
|
+
|
|
96
|
+
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.
|
|
97
|
+
|
|
98
|
+
The API key never appears in errors, logs or `repr(client)`.
|
|
99
|
+
|
|
100
|
+
## Settings
|
|
101
|
+
|
|
102
|
+
| Argument | Environment variable | Default |
|
|
103
|
+
| --- | --- | --- |
|
|
104
|
+
| `api_key` | `SANDBOX_AI_API_KEY` | required |
|
|
105
|
+
| `base_url` | `SANDBOX_AI_BASE_URL` | required: the address of your Sandbox AI gateway |
|
|
106
|
+
| `timeout` | | 10 seconds |
|
|
107
|
+
|
|
108
|
+
A blank or whitespace-only `api_key` or `base_url` argument counts as not given, so the client falls back to `SANDBOX_AI_API_KEY` or `SANDBOX_AI_BASE_URL`.
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
Apache-2.0. The full license text is in the LICENSE file included in the package.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "sandbox-ai-sdk"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Python client for Sandbox AI: propose changes to business systems and read the decision"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "Sandbox AI" }]
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
dependencies = ["httpx>=0.27", "pydantic>=2.9"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 3 - Alpha",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
17
|
+
"Programming Language :: Python :: 3.11",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Programming Language :: Python :: 3.14",
|
|
21
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[build-system]
|
|
26
|
+
requires = ["hatchling>=1.27"]
|
|
27
|
+
build-backend = "hatchling.build"
|
|
28
|
+
|
|
29
|
+
[tool.hatch.build.targets.wheel]
|
|
30
|
+
packages = ["src/sandbox_ai"]
|
|
31
|
+
|
|
32
|
+
# The tests (they need the repo's contracts/ folder) and the developer notes stay out of the
|
|
33
|
+
# sdist. Hatchling always adds the nearest .gitignore to an sdist, so that one stays in.
|
|
34
|
+
[tool.hatch.build.targets.sdist]
|
|
35
|
+
exclude = ["/tests", "/DEVELOPING.md"]
|
|
36
|
+
|
|
37
|
+
[tool.ruff]
|
|
38
|
+
extend = "../../pyproject.toml"
|
|
39
|
+
target-version = "py311"
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Sandbox AI for Python: propose changes to business systems and read the decision."""
|
|
2
|
+
|
|
3
|
+
from .client import Client, __version__
|
|
4
|
+
from .errors import SandboxAIError
|
|
5
|
+
from .models import Approval, Decision, FieldDecision, Preview
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"Approval",
|
|
9
|
+
"Client",
|
|
10
|
+
"Decision",
|
|
11
|
+
"FieldDecision",
|
|
12
|
+
"Preview",
|
|
13
|
+
"SandboxAIError",
|
|
14
|
+
"__version__",
|
|
15
|
+
]
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""A thin client for the Sandbox AI gateway API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import uuid
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from types import TracebackType
|
|
9
|
+
from typing import Any
|
|
10
|
+
from urllib.parse import quote
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
from pydantic import ValidationError
|
|
14
|
+
|
|
15
|
+
from .errors import SandboxAIError
|
|
16
|
+
from .models import Decision, _ChangeDetail
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
|
19
|
+
|
|
20
|
+
# The connection never opened, so the gateway can't have seen the request: it was refused,
|
|
21
|
+
# timed out while connecting, or never got a connection from the pool. Every other failure
|
|
22
|
+
# may have happened after it arrived.
|
|
23
|
+
_NOT_SENT = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout, httpx.UnsupportedProtocol)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _gateway_address(address: str) -> str:
|
|
27
|
+
"""The address without a trailing slash, once it's a full http or https URL with a host.
|
|
28
|
+
|
|
29
|
+
It can't carry credentials, which httpx would send as Basic auth instead of the key, or a
|
|
30
|
+
query string or fragment, which would end up inside every request's path.
|
|
31
|
+
"""
|
|
32
|
+
try:
|
|
33
|
+
url = httpx.URL(address)
|
|
34
|
+
except httpx.InvalidURL:
|
|
35
|
+
url = None
|
|
36
|
+
if (
|
|
37
|
+
url is None
|
|
38
|
+
or url.scheme not in ("http", "https")
|
|
39
|
+
or not url.host
|
|
40
|
+
or url.userinfo
|
|
41
|
+
or url.query
|
|
42
|
+
or url.fragment
|
|
43
|
+
):
|
|
44
|
+
# Never repeat the address: it could be a key pasted into the wrong setting.
|
|
45
|
+
raise SandboxAIError(
|
|
46
|
+
"The gateway address isn't valid. Pass base_url=... or set SANDBOX_AI_BASE_URL to "
|
|
47
|
+
"the full address, like https://your-gateway.example.com.",
|
|
48
|
+
code="invalid_base_url",
|
|
49
|
+
)
|
|
50
|
+
return address.rstrip("/")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _mask(key: str) -> str:
|
|
54
|
+
"""Only the last four characters, the way the dashboard shows a key."""
|
|
55
|
+
return f"…{key[-4:]}" if len(key) > 8 else "…"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Client:
|
|
59
|
+
"""Proposes changes to Sandbox AI and reads the decisions.
|
|
60
|
+
|
|
61
|
+
The API key identifies the agent, so the gateway knows who is asking. It's read from
|
|
62
|
+
`api_key` or the SANDBOX_AI_API_KEY environment variable, and is never printed. The
|
|
63
|
+
gateway's address comes from `base_url` or SANDBOX_AI_BASE_URL. Both are required.
|
|
64
|
+
|
|
65
|
+
Example::
|
|
66
|
+
|
|
67
|
+
client = Client(api_key="sbx_...", base_url="https://gateway.example")
|
|
68
|
+
decision = client.propose_change(
|
|
69
|
+
"salesforce", "account", "001-SAMPLE-0142", {"OwnerId": "005-SAMPLE"}
|
|
70
|
+
)
|
|
71
|
+
decision.status # "needs_approval"
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
def __init__(
|
|
75
|
+
self,
|
|
76
|
+
api_key: str | None = None,
|
|
77
|
+
*,
|
|
78
|
+
base_url: str | None = None,
|
|
79
|
+
timeout: float = 10.0,
|
|
80
|
+
) -> None:
|
|
81
|
+
# A blank value counts as not given, and stray spaces from a pasted config are dropped.
|
|
82
|
+
key = (api_key or "").strip() or os.environ.get("SANDBOX_AI_API_KEY", "").strip()
|
|
83
|
+
if not key:
|
|
84
|
+
raise SandboxAIError(
|
|
85
|
+
"No API key. Pass api_key=... or set SANDBOX_AI_API_KEY. "
|
|
86
|
+
"Create a key for your agent in the Sandbox AI dashboard.",
|
|
87
|
+
code="missing_api_key",
|
|
88
|
+
)
|
|
89
|
+
# A key goes in a header, which can't hold spaces, line breaks or non-ASCII characters.
|
|
90
|
+
# Never repeat it: the error could end up in a log.
|
|
91
|
+
if not (key.isascii() and key.isprintable()) or any(c.isspace() for c in key):
|
|
92
|
+
raise SandboxAIError(
|
|
93
|
+
"This doesn't look like a Sandbox AI API key.", code="invalid_api_key"
|
|
94
|
+
)
|
|
95
|
+
address = (base_url or "").strip() or os.environ.get("SANDBOX_AI_BASE_URL", "").strip()
|
|
96
|
+
if not address:
|
|
97
|
+
raise SandboxAIError(
|
|
98
|
+
"No gateway address. Pass base_url=... or set SANDBOX_AI_BASE_URL to the "
|
|
99
|
+
"address of your Sandbox AI gateway.",
|
|
100
|
+
code="missing_base_url",
|
|
101
|
+
)
|
|
102
|
+
self._key = key
|
|
103
|
+
self.base_url = _gateway_address(address)
|
|
104
|
+
self.timeout = timeout
|
|
105
|
+
self._http = httpx.Client(base_url=self.base_url, timeout=timeout)
|
|
106
|
+
|
|
107
|
+
def __repr__(self) -> str:
|
|
108
|
+
return f"Client(base_url={self.base_url!r}, api_key={_mask(self._key)!r})"
|
|
109
|
+
|
|
110
|
+
def __enter__(self) -> Client:
|
|
111
|
+
return self
|
|
112
|
+
|
|
113
|
+
def __exit__(
|
|
114
|
+
self,
|
|
115
|
+
exc_type: type[BaseException] | None,
|
|
116
|
+
exc: BaseException | None,
|
|
117
|
+
tb: TracebackType | None,
|
|
118
|
+
) -> None:
|
|
119
|
+
self.close()
|
|
120
|
+
|
|
121
|
+
def close(self) -> None:
|
|
122
|
+
"""Closes the connection pool. Also happens when used as a context manager."""
|
|
123
|
+
self._http.close()
|
|
124
|
+
|
|
125
|
+
def propose_change(
|
|
126
|
+
self,
|
|
127
|
+
system: str,
|
|
128
|
+
object: str,
|
|
129
|
+
record_id: str | None,
|
|
130
|
+
fields: Mapping[str, Any],
|
|
131
|
+
reason: str | None = None,
|
|
132
|
+
*,
|
|
133
|
+
idempotency_key: str | None = None,
|
|
134
|
+
) -> Decision:
|
|
135
|
+
"""Proposes a change to one record and returns Sandbox AI's decision.
|
|
136
|
+
|
|
137
|
+
An update when `record_id` is set, a create when it's None. `fields` maps field
|
|
138
|
+
names to new values. `reason` is shown to approvers, so say why in plain words.
|
|
139
|
+
|
|
140
|
+
Each call sends an idempotency key: yours, or one the SDK makes. If the call times
|
|
141
|
+
out, the connection drops after sending, or the gateway answers with a 5xx or
|
|
142
|
+
something the SDK can't read, the change may already have been made. The
|
|
143
|
+
SandboxAIError then carries the key as `idempotency_key`, and names it in its
|
|
144
|
+
message. Pass it to the same call within 24 hours: the gateway returns the first
|
|
145
|
+
decision instead of making a second change. Keys belong to the API key that sent
|
|
146
|
+
them, so another agent's key never matches yours.
|
|
147
|
+
"""
|
|
148
|
+
if not fields:
|
|
149
|
+
raise ValueError("fields needs at least one field to change.")
|
|
150
|
+
body: dict[str, Any] = {
|
|
151
|
+
"system": system,
|
|
152
|
+
"object": object,
|
|
153
|
+
"action": "create" if record_id is None else "update",
|
|
154
|
+
"fields": dict(fields),
|
|
155
|
+
}
|
|
156
|
+
if record_id is not None:
|
|
157
|
+
body["record_id"] = record_id
|
|
158
|
+
if reason is not None:
|
|
159
|
+
body["reason"] = reason
|
|
160
|
+
key = idempotency_key or str(uuid.uuid4())
|
|
161
|
+
data = self._request("POST", "/v1/changes", json=body, idempotency_key=key)
|
|
162
|
+
return self._parse(Decision, data, idempotency_key=key)
|
|
163
|
+
|
|
164
|
+
def get_decision(self, change_id: str) -> Decision:
|
|
165
|
+
"""The latest decision for a change, for example after a person approved it.
|
|
166
|
+
|
|
167
|
+
It only reads, so after a timeout, simply call it again.
|
|
168
|
+
"""
|
|
169
|
+
data = self._request("GET", f"/v1/changes/{quote(change_id, safe='')}")
|
|
170
|
+
return self._parse(_ChangeDetail, data).decision
|
|
171
|
+
|
|
172
|
+
def _request(
|
|
173
|
+
self,
|
|
174
|
+
method: str,
|
|
175
|
+
path: str,
|
|
176
|
+
*,
|
|
177
|
+
json: Any = None,
|
|
178
|
+
idempotency_key: str | None = None,
|
|
179
|
+
) -> Any:
|
|
180
|
+
headers = {
|
|
181
|
+
"Authorization": f"Bearer {self._key}",
|
|
182
|
+
"User-Agent": f"sandbox-ai-python/{__version__}",
|
|
183
|
+
}
|
|
184
|
+
if idempotency_key is not None:
|
|
185
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
186
|
+
try:
|
|
187
|
+
response = self._http.request(method, path, json=json, headers=headers)
|
|
188
|
+
# Before TimeoutException: a connect or pool timeout is one, but nothing was sent.
|
|
189
|
+
except _NOT_SENT:
|
|
190
|
+
raise self._unreachable() from None
|
|
191
|
+
except httpx.TimeoutException:
|
|
192
|
+
said = f"Sandbox AI didn't answer within {self.timeout:g} seconds."
|
|
193
|
+
if idempotency_key is None:
|
|
194
|
+
said += " Try again."
|
|
195
|
+
raise _failed(said, idempotency_key, code="timeout") from None
|
|
196
|
+
except httpx.HTTPError:
|
|
197
|
+
if idempotency_key is None:
|
|
198
|
+
raise self._unreachable() from None
|
|
199
|
+
raise _failed(
|
|
200
|
+
f"The connection to Sandbox AI at {self.base_url} dropped before it answered.",
|
|
201
|
+
idempotency_key,
|
|
202
|
+
code="network_error",
|
|
203
|
+
) from None
|
|
204
|
+
if response.is_error:
|
|
205
|
+
raise _error_from(response, idempotency_key)
|
|
206
|
+
try:
|
|
207
|
+
return response.json()
|
|
208
|
+
except ValueError:
|
|
209
|
+
raise _failed(
|
|
210
|
+
"Sandbox AI sent an answer that isn't JSON.",
|
|
211
|
+
idempotency_key,
|
|
212
|
+
code="unexpected_response",
|
|
213
|
+
status=response.status_code,
|
|
214
|
+
) from None
|
|
215
|
+
|
|
216
|
+
def _unreachable(self) -> SandboxAIError:
|
|
217
|
+
return SandboxAIError(
|
|
218
|
+
f"Couldn't reach Sandbox AI at {self.base_url}. Check the address and your connection.",
|
|
219
|
+
code="network_error",
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
@staticmethod
|
|
223
|
+
def _parse(model: type[Any], data: Any, *, idempotency_key: str | None = None) -> Any:
|
|
224
|
+
try:
|
|
225
|
+
return model.model_validate(data)
|
|
226
|
+
except ValidationError:
|
|
227
|
+
raise _failed(
|
|
228
|
+
"Sandbox AI sent an answer this version of the SDK doesn't understand. "
|
|
229
|
+
"Update the sandbox-ai-sdk package.",
|
|
230
|
+
idempotency_key,
|
|
231
|
+
code="unexpected_response",
|
|
232
|
+
) from None
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _failed(said: str, key: str | None, **error: Any) -> SandboxAIError:
|
|
236
|
+
"""`key` is set when a change may have gone through: the only safe retry reuses it."""
|
|
237
|
+
if key is None:
|
|
238
|
+
return SandboxAIError(said, **error)
|
|
239
|
+
return SandboxAIError(
|
|
240
|
+
f"{said.rstrip('. ')}. The change may already have been made. "
|
|
241
|
+
f"Retry with idempotency_key={key!r} so it isn't made twice.",
|
|
242
|
+
idempotency_key=key,
|
|
243
|
+
**error,
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _error_from(response: httpx.Response, key: str | None) -> SandboxAIError:
|
|
248
|
+
"""The contract's error body, or a plain description when there isn't one.
|
|
249
|
+
|
|
250
|
+
A 4xx means the gateway refused the request. After a 5xx, the change may have been made.
|
|
251
|
+
"""
|
|
252
|
+
code, message = (
|
|
253
|
+
"unexpected_response",
|
|
254
|
+
f"Sandbox AI answered with status {response.status_code}.",
|
|
255
|
+
)
|
|
256
|
+
details: dict[str, Any] | None = None
|
|
257
|
+
try:
|
|
258
|
+
body = response.json()
|
|
259
|
+
error = body.get("error") if isinstance(body, dict) else None
|
|
260
|
+
if (
|
|
261
|
+
isinstance(error, dict)
|
|
262
|
+
and isinstance(error.get("code"), str)
|
|
263
|
+
and isinstance(error.get("message"), str)
|
|
264
|
+
):
|
|
265
|
+
code, message = error["code"], error["message"]
|
|
266
|
+
if isinstance(error.get("details"), dict):
|
|
267
|
+
details = error["details"]
|
|
268
|
+
except ValueError:
|
|
269
|
+
pass
|
|
270
|
+
# Whole seconds, as the contract declares. An HTTP date or anything else reads as None.
|
|
271
|
+
retry_after = response.headers.get("Retry-After", "").strip()
|
|
272
|
+
return _failed(
|
|
273
|
+
message,
|
|
274
|
+
key if response.is_server_error else None,
|
|
275
|
+
code=code,
|
|
276
|
+
status=response.status_code,
|
|
277
|
+
retry_after=int(retry_after) if retry_after.isdecimal() else None,
|
|
278
|
+
details=details,
|
|
279
|
+
)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""The one error the SDK raises."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SandboxAIError(Exception):
|
|
9
|
+
"""A request to Sandbox AI that didn't work.
|
|
10
|
+
|
|
11
|
+
`code` is the API contract's error code, such as "agent_paused" or "invalid_request",
|
|
12
|
+
or one of the SDK's own: "missing_api_key", "invalid_api_key", "missing_base_url",
|
|
13
|
+
"invalid_base_url", "timeout", "network_error" and "unexpected_response". `message` is
|
|
14
|
+
plain words, safe to show to people and to agents. It never contains the API key.
|
|
15
|
+
|
|
16
|
+
`details` is the extra context the gateway sent, if any, such as which fields failed
|
|
17
|
+
an "invalid_request".
|
|
18
|
+
|
|
19
|
+
`idempotency_key` is set when propose_change failed after the request may have reached
|
|
20
|
+
the gateway: a "timeout", a "network_error" after sending, a 5xx, or an answer the SDK
|
|
21
|
+
couldn't read. The change may already have been made, so retry with this key and the
|
|
22
|
+
gateway returns the first decision instead of making it twice.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
message: str,
|
|
28
|
+
*,
|
|
29
|
+
code: str,
|
|
30
|
+
status: int | None = None,
|
|
31
|
+
retry_after: int | None = None,
|
|
32
|
+
idempotency_key: str | None = None,
|
|
33
|
+
details: dict[str, Any] | None = None,
|
|
34
|
+
) -> None:
|
|
35
|
+
super().__init__(message)
|
|
36
|
+
self.message = message
|
|
37
|
+
self.code = code
|
|
38
|
+
self.status = status
|
|
39
|
+
#: Whole seconds to wait before retrying, from Retry-After (rate_limited).
|
|
40
|
+
self.retry_after = retry_after
|
|
41
|
+
#: The key to retry with. None if nothing was sent, and on every other error.
|
|
42
|
+
self.idempotency_key = idempotency_key
|
|
43
|
+
#: Extra context from the gateway, as it sent it. None if it sent none.
|
|
44
|
+
self.details = details
|
|
45
|
+
|
|
46
|
+
def __repr__(self) -> str:
|
|
47
|
+
return (
|
|
48
|
+
f"SandboxAIError(code={self.code!r}, status={self.status!r}, message={self.message!r})"
|
|
49
|
+
)
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""What the gateway sends back, as typed models.
|
|
2
|
+
|
|
3
|
+
These mirror contracts/schemas/decision.json. Tests compare them with the schema, so a
|
|
4
|
+
contract change that this SDK doesn't handle fails CI.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from typing import Any, Literal
|
|
11
|
+
|
|
12
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
13
|
+
|
|
14
|
+
Status = Literal[
|
|
15
|
+
"applied",
|
|
16
|
+
"partially_applied",
|
|
17
|
+
"needs_approval",
|
|
18
|
+
"blocked",
|
|
19
|
+
"rejected",
|
|
20
|
+
"expired",
|
|
21
|
+
"conflict",
|
|
22
|
+
"error",
|
|
23
|
+
"observed",
|
|
24
|
+
]
|
|
25
|
+
Mode = Literal["watch", "enforce"]
|
|
26
|
+
Outcome = Literal["allow", "needs_approval", "blocked"]
|
|
27
|
+
ApprovalState = Literal["pending", "approved", "rejected", "expired", "escalated"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _Model(BaseModel):
|
|
31
|
+
# Fields added to the contract later don't break this version of the SDK.
|
|
32
|
+
model_config = ConfigDict(extra="ignore", frozen=True)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class FieldDecision(_Model):
|
|
36
|
+
"""What happened to one field."""
|
|
37
|
+
|
|
38
|
+
field: str
|
|
39
|
+
label: str | None = None
|
|
40
|
+
before: Any = None
|
|
41
|
+
after: Any = None
|
|
42
|
+
outcome: Outcome
|
|
43
|
+
rule_ids: list[str] = Field(default_factory=list)
|
|
44
|
+
message: str | None = None
|
|
45
|
+
written: bool = False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Preview(_Model):
|
|
49
|
+
"""What the gateway read before deciding."""
|
|
50
|
+
|
|
51
|
+
simulated: bool | None = None
|
|
52
|
+
record_version: str | None = None
|
|
53
|
+
record_label: str | None = None
|
|
54
|
+
warnings: list[str] = Field(default_factory=list)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Approval(_Model):
|
|
58
|
+
"""The request for a person's decision, when a rule asked for one.
|
|
59
|
+
|
|
60
|
+
`state` "pending" and "escalated" both mean it's still waiting. While it waits, anyone in
|
|
61
|
+
`approvers` can decide, and the first decision wins. `group_ids` lists every group it has
|
|
62
|
+
reached, in order, and the last one has it now.
|
|
63
|
+
|
|
64
|
+
Exactly one deadline is set while it waits: `escalates_at` if that group has a backup
|
|
65
|
+
group, otherwise `expires_at`. Both keep their last values once it's final.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
id: str
|
|
69
|
+
approvers: list[str]
|
|
70
|
+
group_id: str
|
|
71
|
+
group_ids: list[str]
|
|
72
|
+
state: ApprovalState
|
|
73
|
+
requested_at: datetime
|
|
74
|
+
escalates_at: datetime | None = None
|
|
75
|
+
expires_at: datetime | None = None
|
|
76
|
+
escalated_at: datetime | None = None
|
|
77
|
+
decided_by: str | None = None
|
|
78
|
+
decided_at: datetime | None = None
|
|
79
|
+
comment: str | None = None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Decision(_Model):
|
|
83
|
+
"""Sandbox AI's answer for a proposed change, decided per field.
|
|
84
|
+
|
|
85
|
+
`status` says where it stands: "applied", "needs_approval" (wait for a person, then
|
|
86
|
+
call get_decision again), "blocked", "rejected", "expired", "conflict", "error",
|
|
87
|
+
"partially_applied", or "observed" when the connection is watch-only and nothing was
|
|
88
|
+
written.
|
|
89
|
+
|
|
90
|
+
`message` and `rule_ids` say why for the change as a whole. They're always set when
|
|
91
|
+
there are no fields, as for a delete, which is always blocked, in watch-only too.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
change_id: str
|
|
95
|
+
status: Status
|
|
96
|
+
mode: Mode
|
|
97
|
+
fields: list[FieldDecision]
|
|
98
|
+
message: str | None = None
|
|
99
|
+
rule_ids: list[str] = Field(default_factory=list)
|
|
100
|
+
preview: Preview | None = None
|
|
101
|
+
approval: Approval | None = None
|
|
102
|
+
decided_at: datetime | None = None
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def written(self) -> bool:
|
|
106
|
+
"""True if at least one field was written to the system."""
|
|
107
|
+
return any(f.written for f in self.fields)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class _ChangeDetail(_Model):
|
|
111
|
+
"""GET /v1/changes/{id}. The SDK only needs the decision from it."""
|
|
112
|
+
|
|
113
|
+
decision: Decision
|
|
File without changes
|