terrarium-python 0.1.1__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.
@@ -0,0 +1,34 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
11
+
12
+ # terrarium session logs and scratch (root only — must not swallow web/app/api/logs/)
13
+ /logs/
14
+ notes.md
15
+
16
+ # Next.js web console
17
+ web/node_modules/
18
+ web/.next/
19
+ web/next-env.d.ts
20
+ web/*.tsbuildinfo
21
+ .env
22
+
23
+ # Rust
24
+ warden/target/
25
+
26
+ # Jekyll docs site
27
+ docs/_site/
28
+ docs/.jekyll-cache/
29
+ docs/.jekyll-metadata
30
+ docs/vendor/
31
+
32
+ # Tooling caches
33
+ .ruff_cache/
34
+ .serena/
@@ -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,397 @@
1
+ Metadata-Version: 2.4
2
+ Name: terrarium-python
3
+ Version: 0.1.1
4
+ Summary: Async Python client for the Terrarium orchestrator API — manage sandboxed Claude agents and sessions (Claude-Agent-SDK-aligned).
5
+ Project-URL: Homepage, https://oaisp.github.io/terrarium/
6
+ Project-URL: Documentation, https://oaisp.github.io/terrarium/sdk/
7
+ Project-URL: Source, https://github.com/OAISP/terrarium
8
+ Project-URL: Issues, https://github.com/OAISP/terrarium/issues
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: httpx>=0.27
18
+ Description-Content-Type: text/markdown
19
+
20
+ # terrarium-python
21
+
22
+ Python client for the **Terrarium** orchestrator API — create and drive sandboxed Claude
23
+ agents over HTTP. The surface mirrors the [Claude Agent SDK](https://github.com/anthropics/claude-agent-sdk-python)
24
+ (`query`, `TerrariumOptions`, typed messages, `can_use_tool`) with extra parameters for
25
+ Terrarium's own features. Like the Claude Agent SDK, it is **async-only** and its sole
26
+ dependency is `httpx`.
27
+
28
+ ```bash
29
+ pip install terrarium-python
30
+ ```
31
+
32
+ ## Quickstart
33
+
34
+ ```python
35
+ import asyncio
36
+ from terrarium import TerrariumClient, TerrariumOptions, AssistantMessage, TextBlock
37
+
38
+ async def main():
39
+ async with TerrariumClient("https://terrarium-api.example.com", token="…") as client:
40
+ async with client.session(options=TerrariumOptions(model="claude-haiku-4-5")) as s:
41
+ async for msg in s.receive_response("What is 7 × 6?"):
42
+ if isinstance(msg, AssistantMessage):
43
+ for block in msg.content:
44
+ if isinstance(block, TextBlock):
45
+ print(block.text)
46
+
47
+ asyncio.run(main())
48
+ ```
49
+
50
+ One-shot, exactly like `claude_agent_sdk.query`:
51
+
52
+ ```python
53
+ from terrarium import query, TerrariumOptions
54
+
55
+ async for msg in query(prompt="Summarise the repo", options=TerrariumOptions(model="opus")):
56
+ print(msg)
57
+ ```
58
+
59
+ ## Mental model
60
+
61
+ | Concept | What it is | Lifetime |
62
+ |---|---|---|
63
+ | **Client** | a connection to one orchestrator (`base_url` + bearer `token`) | your process |
64
+ | **Agent** | a *reusable, stored config* — model, persona, egress, allowed tools | persistent; `client.agents` |
65
+ | **Session** | one *running conversation* in a fresh sandbox; inherits an agent's config (or takes an inline one) | ephemeral by default, or durable (see below) |
66
+ | **Client tool** | a tool whose handler runs in **your** process, callable by the sandboxed agent | per-session |
67
+ | **Egress profile** | a named Warden allow/deny bundle controlling what the sandbox can reach | persistent; `client.egress_profiles` |
68
+
69
+ `TerrariumOptions` is a superset of the Claude SDK's `ClaudeAgentOptions`: the Claude fields
70
+ (`model`, `system_prompt`, `allowed_tools`, `builtin_tools`, `permission_mode`, `max_turns`,
71
+ `max_budget_usd`, `mcp_servers`, `agents`, `thinking`, `effort`, `fallback_model`, `max_thinking_tokens`,
72
+ `betas`, `setting_sources`, `env`, `skills`, `can_use_tool`) plus Terrarium extras (`system_mode`,
73
+ `tools`, `approval`, `interactive`, `environments`, `memory_scope`, `agent_id`, `title`). It
74
+ exposes the **same configurability as the console** (a parity test enforces this). Only fields you
75
+ set are sent — everything else is the orchestrator default.
76
+
77
+ ### Choosing the agent's built-in tools
78
+
79
+ Two distinct knobs (both Claude-SDK-aligned):
80
+
81
+ - **`builtin_tools`** — the **availability** allowlist: the base set of built-in tools the agent
82
+ may use. `None` = all defaults; a list = *only* those; `[]` = none.
83
+ - **`allowed_tools`** — the **auto-approve** list: which available tools skip the permission
84
+ *prompt*. Only matters for `interactive` / gated sessions (under the default `bypassPermissions`
85
+ it's a no-op — everything's already approved).
86
+
87
+ ```python
88
+ # a read-only research agent — it simply doesn't have Bash/Write/etc.
89
+ TerrariumOptions(model="haiku", builtin_tools=["Read", "Grep", "Glob", "WebSearch"])
90
+ ```
91
+
92
+ ### Trimming the default Claude harness
93
+
94
+ A fresh Claude Code session ships a lot of harness by default: ~30 built-in tools
95
+ (`Task`, `Workflow`, `CronCreate`, …), a dozen built-in skills / slash commands
96
+ (`code-review`, `deep-research`, `verify`, …) and a roster of built-in subagents. Three
97
+ knobs strip it down:
98
+
99
+ - **`builtin_tools`** — the tool availability allowlist (above). Leaving `Task` out removes
100
+ the whole subagent system; leaving `Skill` out removes skill *invocation*.
101
+ - **`skills`** — the skill filter: `[]` hides **every** skill, including the CLI's built-ins
102
+ (this is the "bare harness" setting — `False` only skips mounting your `skills/` dir, the
103
+ CLI defaults still load); `["code-review"]` enables only the named ones; `"all"` / `True`
104
+ enables everything discovered. `skills=[]` also pins `setting_sources` empty (the Claude
105
+ SDK would otherwise re-enable `user`+`project` settings for skill discovery); pass
106
+ `setting_sources` yourself to override.
107
+
108
+ > **Don't judge the filter by the init event.** The CLI's `system/init` message reports
109
+ > every skill/slash command it *discovered on disk*, unfiltered — that's inventory
110
+ > metadata, not what the model sees. The filter applies to the model's context (the
111
+ > skill listing is absent from the actual API request) and to invocation (the Skill tool
112
+ > rejects unlisted skills). The `Skill` tool itself is availability, i.e. `builtin_tools`.
113
+ - **`agents`** — programmatically *define* subagents, instead of / on top of the built-in
114
+ roster. Takes `terrarium.AgentDefinition` (field-for-field the Claude Agent SDK's, so
115
+ ported code drops in unchanged) or an equivalent plain dict.
116
+
117
+ ```python
118
+ # a minimal, no-frills agent: 4 tools, zero skills, no subagents
119
+ TerrariumOptions(
120
+ builtin_tools=["Read", "Grep", "Glob", "Bash"],
121
+ skills=[],
122
+ )
123
+
124
+ # or: bespoke subagents only, with a single curated skill
125
+ from terrarium import AgentDefinition
126
+ TerrariumOptions(
127
+ skills=["code-review"],
128
+ agents={"triager": AgentDefinition(description="Triage failing tests",
129
+ prompt="You triage…",
130
+ tools=["Read", "Grep", "Bash"], maxTurns=10)},
131
+ )
132
+ ```
133
+
134
+ The same stripped setup is available as the one-click **`bare`** template:
135
+
136
+ ```python
137
+ agent = await client.agents.create(name="minimal", template="bare")
138
+ ```
139
+
140
+ `system_prompt` also accepts the Claude SDK's preset form —
141
+ `{"type": "preset", "preset": "claude_code"}` maps to the `claude_code` persona (`append`
142
+ has no Terrarium equivalent and is refused rather than silently dropped).
143
+
144
+ ## Recipes
145
+
146
+ ### Reusable agent + sessions
147
+
148
+ Create the config once; open as many sessions against it as you like.
149
+
150
+ ```python
151
+ agent = await client.agents.create(
152
+ name="Researcher", model="sonnet", system_mode="assistant",
153
+ thinking={"type": "adaptive"}, allowed_tools=["WebSearch", "Read", "Bash"],
154
+ )
155
+ async with client.session(options=TerrariumOptions(agent_id=agent["id"])) as s:
156
+ async for msg in s.receive_response("Summarize the latest on X."):
157
+ print(msg)
158
+ ```
159
+
160
+ ### Custom tools with your application context
161
+
162
+ Define tools whose handlers run in **your** process — with your database, auth, secrets,
163
+ whatever — and the sandboxed agent can call them. Mirrors the Claude Agent SDK's `@tool`,
164
+ except the handler executes client-side: the agent's tool **input** crosses out, your handler
165
+ runs here, and only the **result** you return crosses back in. Your code and state never enter
166
+ the sandbox.
167
+
168
+ ```python
169
+ from terrarium import query, TerrariumOptions, tool
170
+
171
+ @tool("get_user", "Look up a user by id", {"id": {"type": "string"}})
172
+ async def get_user(args):
173
+ return await db.users.find(args["id"]) # runs in YOUR process, with YOUR context
174
+
175
+ async for msg in query(prompt="What's user 42's plan tier?",
176
+ options=TerrariumOptions(model="sonnet", tools=[get_user])):
177
+ print(msg)
178
+ ```
179
+
180
+ Only the schemas (`name`, `description`, `input_schema`) travel to the orchestrator; the
181
+ handlers stay local and are invoked automatically when the agent calls the tool (return a
182
+ string, or `{"content": ..., "is_error": bool}`). This is the sandbox-safe equivalent of the
183
+ Claude SDK's in-process MCP tools — and it works the same whether the session is inline or
184
+ bound to an `agent_id`.
185
+
186
+ #### Vision: returning images (screenshots / computer-use)
187
+
188
+ A client tool's `content` may be a **list of Anthropic content blocks**, so it can return *pixels*
189
+ to the agent — not just words. This is how you build screenshot / computer-use tooling: the screen
190
+ lives on your host, the tool grabs it, and the hosted agent reasons over the image directly (one
191
+ agent, one context — no separate vision loop).
192
+
193
+ ```python
194
+ import base64
195
+
196
+ @tool("screenshot", "Capture the screen and return the image.", {})
197
+ async def screenshot(args):
198
+ png = take_screenshot() # your host-side capture → bytes
199
+ return {"content": [{
200
+ "type": "image",
201
+ "source": {"type": "base64", "media_type": "image/png",
202
+ "data": base64.b64encode(png).decode()},
203
+ }]}
204
+ ```
205
+
206
+ Image content blocks work the same on a **user turn** — pass a block list to
207
+ `receive_response` / `ask` / `send`:
208
+
209
+ ```python
210
+ await s.ask([{"type": "text", "text": "What's on my screen?"},
211
+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64}}])
212
+ ```
213
+
214
+ ### Long-running / durable sessions
215
+
216
+ By default a session is **ephemeral** — `async with` deletes it on exit. For a session that
217
+ outlives the block (a persistent assistant, a scheduled job), pass `ephemeral=False`, then
218
+ reattach later with `client.attach(id)`:
219
+
220
+ ```python
221
+ # start it, do a turn, leave it running
222
+ async with client.session(options=opts, ephemeral=False) as s:
223
+ sid = s.id
224
+ async for _ in s.receive_response("Boot up and remember you are my ops assistant."):
225
+ pass
226
+
227
+ # … hours later, in another process …
228
+ async with client.attach(sid, tools=[get_user]) as s: # attach() never deletes
229
+ async for msg in s.receive_response("Any alerts overnight?"):
230
+ print(msg)
231
+ ```
232
+
233
+ `attach()` re-registers client-tool handlers via `tools=[…]` (the schemas were already sent at
234
+ creation). See [`examples/long_running.py`](../examples/long_running.py).
235
+
236
+ **Resume vs. replay.** `attach()` **resumes** by default: it reads the session's durable
237
+ `resume_cursor` and starts the stream there, so the next turn yields only new events. This is
238
+ what makes reattaching safe after *your* process restarts — without it the handle would replay
239
+ the log, and a replayed `client_tool_call` re-runs its handler here in your process, firing real
240
+ side effects a second time and posting stale results back to the agent.
241
+
242
+ The cursor is the seq of the last turn boundary, derived from the orchestrator's log/registry —
243
+ so it survives an orchestrator restart too. It deliberately lags rather than leads: mid-turn, the
244
+ tail replays, which is correct because a `client_tool_call` after the cursor is still waiting on
245
+ an answer.
246
+
247
+ ```python
248
+ async with client.attach(sid, tools=[get_user]) as s: # resume (default)
249
+ ...
250
+ async with client.attach(sid, replay=True) as s: # full history from seq 0
251
+ ...
252
+ ```
253
+
254
+ Use `replay=True` only to rebuild state from the whole log, and only with idempotent tools (or
255
+ none registered). Attaching to a **terminated** session raises — read its log via
256
+ `client.sessions.events(sid)` instead.
257
+
258
+ ### Structured memory (retrieval, not a folder)
259
+
260
+ The sandbox's `/memory` is an FS volume — no retrieval, and on k8s its RWO PVC can't multi-attach
261
+ (concurrent sessions of one agent fork). `terrarium.memory` offers memory as **client tools** over
262
+ a real store instead: the agent calls `memory_search` / `memory_write` / `memory_get`, the handlers
263
+ run in your process, and concurrent sessions share one store (no fork). The reference
264
+ `SqliteMemory` is stdlib-only (FTS5, LIKE fallback); implement `MemoryStore` for pgvector/etc.
265
+
266
+ ```python
267
+ from terrarium import TerrariumClient, TerrariumOptions
268
+ from terrarium.memory import SqliteMemory, memory_tools
269
+
270
+ store = SqliteMemory("assistant.db") # durable across sessions/processes
271
+ opts = TerrariumOptions(agent_id=agent_id, tools=memory_tools(store))
272
+ # the agent can now memory_write facts and memory_search them on later turns / sessions
273
+ ```
274
+
275
+ ### Egress profiles
276
+
277
+ A named set of **firewall rules** controlling what a sandbox can reach. It's applied to an
278
+ agent by attaching an **environment** that references it (there is no direct per-agent egress
279
+ pin; see below). Instantiate a built-in preset (`anthropic-only`, `developer`, `python`,
280
+ `node`, `data-science`, `web-audit` — `await client.egress_profiles.presets()`), or build
281
+ rules directly:
282
+
283
+ ```python
284
+ prof = await client.egress_profiles.create(
285
+ name="internal-git", mode="enforce",
286
+ rules=[
287
+ {"action": "allow", "dest": "github.com"}, # domain, ports 80/443
288
+ {"action": "allow", "dest": "10.20.0.0/16", "ports": [443, 5432]}, # internal CIDR + DB port
289
+ {"action": "deny", "dest": "telemetry.example.com"},
290
+ {"action": "inspect", "dest": "registry.npmjs.org"}, # TLS-terminate + scan
291
+ ],
292
+ # resolve an internal name to a fixed IP when your DNS server (not the sandbox) knows it
293
+ hosts=[{"host": "git.internal.example", "ip": "10.1.20.200"}],
294
+ )
295
+ ```
296
+
297
+ Each rule is `{"action": "allow"|"deny"|"inspect", "dest": <domain|ip|cidr>, "ports": [..],
298
+ "enabled": true, "note": ".."}`. `ports` (allow/inspect) lifts the default 80/443 wall for
299
+ that destination; `deny` is dest-only. Private ranges are denied unless an allow/inspect rule
300
+ covers them; the cloud-metadata IP is a hard floor.
301
+
302
+ ### Environments — the per-agent egress + secret-scoping mechanism
303
+
304
+ Operator **secrets** are injected by Warden at the network boundary (the value never enters
305
+ the sandbox). By default *every* enabled secret is injected into *every* agent's Warden —
306
+ so any agent that can reach the scoped host can use the token. **Environments** fix that: an
307
+ environment groups a set of secrets and, optionally, an egress profile; an agent attaches to
308
+ one or more and then receives **only** those environments' secrets, under the egress merged
309
+ from their profiles. Environments are the single way to scope an agent's egress and secrets.
310
+
311
+ ```python
312
+ # an operator secret (value lives in the vault + Warden, never the sandbox)
313
+ await client.secrets.put("gh", scopes=["api.github.com"], value=os.environ["GH_TOKEN"])
314
+ # bundle it with a matching egress profile
315
+ gh_prof = await client.egress_profiles.create(preset="developer", name="gh-egress")
316
+ env = await client.environments.create(name="github", secrets=["gh"], egress_profile=gh_prof["id"])
317
+ # only agents attached to this environment get the GitHub token injected + this egress
318
+ agent = await client.agents.create(name="pr-bot", environments=[env["id"]])
319
+ ```
320
+
321
+ Need egress with no injected credential? Create an environment with an egress profile and no
322
+ secrets (`secrets=[]`) and attach it. An agent with **no** environments receives no operator
323
+ secrets under the global egress policy. Attaching multiple
324
+ environments unions their secrets; their egress profiles merge (enforce wins over monitor;
325
+ allowed hosts union — attaching can only widen reach, never narrow it). Referenced environments
326
+ and profiles must be detached before deletion; dangling references fail closed at resolution.
327
+ `client.environments.{list, create, update, delete}` and `client.secrets.{list, put, delete}`.
328
+
329
+ ### Interactive agents (questions + permission gating)
330
+
331
+ An agent created with `interactive=True` can pause to ask the operator structured questions
332
+ (`question` events) or for tool approval (`permission` events, when `approval` is set). Resolve
333
+ both with one Claude-SDK-style `can_use_tool` callback (sync **or** async):
334
+
335
+ ```python
336
+ from terrarium import TerrariumOptions, PermissionResultAllow, PermissionResultDeny
337
+
338
+ async def can_use_tool(tool, tool_input, ctx):
339
+ if tool == "AskUserQuestion":
340
+ qs = tool_input["questions"]
341
+ return PermissionResultAllow(updated_input={"answers": {q["question"]: q["options"][0]["label"] for q in qs}})
342
+ if tool == "Bash":
343
+ return PermissionResultDeny(message="no shell")
344
+ return PermissionResultAllow() # or .always to remember for the session
345
+
346
+ opts = TerrariumOptions(interactive=True, approval="all", can_use_tool=can_use_tool)
347
+ async for msg in query(prompt="Design me a portfolio", options=opts, client=client):
348
+ print(msg)
349
+ ```
350
+
351
+ Or resolve manually while streaming: on a `QuestionMessage` call `await s.answer(question_id, {...})`;
352
+ on a `PermissionMessage` call `await s.decide(request_id, "allow"|"always"|"deny")`.
353
+
354
+ > **Divergence from the Claude Agent SDK:** persistence here is a Terrarium convenience —
355
+ > `PermissionResultAllow(always=True)` (or `decide(..., "always")`) remembers the decision for
356
+ > the session. The upstream SDK instead expresses this via `updated_permissions=[...]` on the
357
+ > result and has a `PermissionResultDeny(interrupt=...)` field; Terrarium models neither. If you
358
+ > are porting a Claude-SDK `can_use_tool` that returns `updated_permissions`, switch it to
359
+ > `always=True` here.
360
+
361
+ ### Raw event stream
362
+
363
+ `receive_response()` yields typed, coalesced messages. For the underlying per-event stream
364
+ (token deltas, status, rewind points) use `ask()`:
365
+
366
+ ```python
367
+ async for ev in s.ask("now dig deeper"):
368
+ print(ev["type"], ev.get("text", ""))
369
+ ```
370
+
371
+ ## Message shape
372
+
373
+ `receive_response()` yields the Claude-Agent-SDK message types — `AssistantMessage` (with
374
+ `.content` blocks: `TextBlock` / `ThinkingBlock` / `ToolUseBlock`), `UserMessage`
375
+ (`ToolResultBlock`), `ResultMessage`, plus `SystemMessage` / `QuestionMessage` /
376
+ `PermissionMessage`. A turn's consecutive assistant blocks (text + tool_uses) are **coalesced
377
+ into one multi-block `AssistantMessage`**, just like the real Claude Agent SDK. (Need the raw
378
+ events instead? Use `ask()`.)
379
+
380
+ ## API surface
381
+
382
+ ```
383
+ client.agents.{create, list, get, update, delete}
384
+ client.sessions.{create, get, list, delete, send, interrupt, answer, decide,
385
+ set_model, set_permission_mode, stream}
386
+ client.schedules.{create, list, update, delete}
387
+ client.tokens.{create, list, delete}
388
+ client.egress_profiles.{list, presets, create, update, delete}
389
+ client.secrets.{list, put, delete}
390
+ client.environments.{list, create, update, delete}
391
+ client.{session, attach, health, fleet, templates}
392
+
393
+ Session.{connect, ask, run, query, receive_response, interrupt, answer, decide,
394
+ set_model, set_permission_mode, rewind, upload_file, verify_egress, summary, close}
395
+ ```
396
+
397
+ The `terra-cli` command bridges this async SDK via `asyncio.run`.