topwater 0.1.0a4__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.
Files changed (74) hide show
  1. topwater-0.1.0a4/LICENSE +21 -0
  2. topwater-0.1.0a4/PKG-INFO +308 -0
  3. topwater-0.1.0a4/README.md +265 -0
  4. topwater-0.1.0a4/THIRD-PARTY-NOTICES.md +34 -0
  5. topwater-0.1.0a4/pyproject.toml +49 -0
  6. topwater-0.1.0a4/setup.cfg +4 -0
  7. topwater-0.1.0a4/src/topwater/__init__.py +53 -0
  8. topwater-0.1.0a4/src/topwater/_spec.py +318 -0
  9. topwater-0.1.0a4/src/topwater/api.py +330 -0
  10. topwater-0.1.0a4/src/topwater/arith.py +276 -0
  11. topwater-0.1.0a4/src/topwater/binder.py +266 -0
  12. topwater-0.1.0a4/src/topwater/bytetext.py +33 -0
  13. topwater-0.1.0a4/src/topwater/commands/__init__.py +1261 -0
  14. topwater-0.1.0a4/src/topwater/commands/archive.py +830 -0
  15. topwater-0.1.0a4/src/topwater/commands/awk.py +1468 -0
  16. topwater-0.1.0a4/src/topwater/commands/binary.py +215 -0
  17. topwater-0.1.0a4/src/topwater/commands/documents.py +34 -0
  18. topwater-0.1.0a4/src/topwater/commands/files.py +1007 -0
  19. topwater-0.1.0a4/src/topwater/commands/git.py +3692 -0
  20. topwater-0.1.0a4/src/topwater/commands/gitcore.py +784 -0
  21. topwater-0.1.0a4/src/topwater/commands/gitpack.py +242 -0
  22. topwater-0.1.0a4/src/topwater/commands/jq.py +1877 -0
  23. topwater-0.1.0a4/src/topwater/commands/more.py +1719 -0
  24. topwater-0.1.0a4/src/topwater/commands/net.py +824 -0
  25. topwater-0.1.0a4/src/topwater/commands/text.py +1677 -0
  26. topwater-0.1.0a4/src/topwater/containers.py +949 -0
  27. topwater-0.1.0a4/src/topwater/convert.py +629 -0
  28. topwater-0.1.0a4/src/topwater/host.py +425 -0
  29. topwater-0.1.0a4/src/topwater/integrations/__init__.py +38 -0
  30. topwater-0.1.0a4/src/topwater/integrations/claude_agent_sdk.py +30 -0
  31. topwater-0.1.0a4/src/topwater/integrations/crewai.py +26 -0
  32. topwater-0.1.0a4/src/topwater/integrations/google_adk.py +22 -0
  33. topwater-0.1.0a4/src/topwater/integrations/langchain.py +19 -0
  34. topwater-0.1.0a4/src/topwater/integrations/llamaindex.py +13 -0
  35. topwater-0.1.0a4/src/topwater/integrations/openai_agents.py +29 -0
  36. topwater-0.1.0a4/src/topwater/integrations/pydantic_ai.py +23 -0
  37. topwater-0.1.0a4/src/topwater/integrations/smolagents.py +27 -0
  38. topwater-0.1.0a4/src/topwater/mcp.py +149 -0
  39. topwater-0.1.0a4/src/topwater/parser.py +1277 -0
  40. topwater-0.1.0a4/src/topwater/py.typed +0 -0
  41. topwater-0.1.0a4/src/topwater/recording.py +602 -0
  42. topwater-0.1.0a4/src/topwater/shell.py +3381 -0
  43. topwater-0.1.0a4/src/topwater/snapshot.py +646 -0
  44. topwater-0.1.0a4/src/topwater/tools.py +343 -0
  45. topwater-0.1.0a4/src/topwater/vfs.py +932 -0
  46. topwater-0.1.0a4/src/topwater/web.py +400 -0
  47. topwater-0.1.0a4/src/topwater/webaccess.py +680 -0
  48. topwater-0.1.0a4/src/topwater.egg-info/PKG-INFO +308 -0
  49. topwater-0.1.0a4/src/topwater.egg-info/SOURCES.txt +72 -0
  50. topwater-0.1.0a4/src/topwater.egg-info/dependency_links.txt +1 -0
  51. topwater-0.1.0a4/src/topwater.egg-info/requires.txt +24 -0
  52. topwater-0.1.0a4/src/topwater.egg-info/top_level.txt +1 -0
  53. topwater-0.1.0a4/tests/test_agent_features.py +199 -0
  54. topwater-0.1.0a4/tests/test_api_command.py +288 -0
  55. topwater-0.1.0a4/tests/test_bug_pass.py +76 -0
  56. topwater-0.1.0a4/tests/test_command_spec.py +116 -0
  57. topwater-0.1.0a4/tests/test_containers.py +467 -0
  58. topwater-0.1.0a4/tests/test_corpus.py +48 -0
  59. topwater-0.1.0a4/tests/test_documents.py +496 -0
  60. topwater-0.1.0a4/tests/test_git.py +287 -0
  61. topwater-0.1.0a4/tests/test_host.py +96 -0
  62. topwater-0.1.0a4/tests/test_host_bridge.py +186 -0
  63. topwater-0.1.0a4/tests/test_integrations.py +304 -0
  64. topwater-0.1.0a4/tests/test_limits.py +200 -0
  65. topwater-0.1.0a4/tests/test_packaging.py +10 -0
  66. topwater-0.1.0a4/tests/test_permissions.py +165 -0
  67. topwater-0.1.0a4/tests/test_recordings.py +562 -0
  68. topwater-0.1.0a4/tests/test_review_fixes.py +19 -0
  69. topwater-0.1.0a4/tests/test_shell.py +185 -0
  70. topwater-0.1.0a4/tests/test_shell_language.py +148 -0
  71. topwater-0.1.0a4/tests/test_snapshots.py +484 -0
  72. topwater-0.1.0a4/tests/test_symlinks.py +152 -0
  73. topwater-0.1.0a4/tests/test_tool_commands.py +195 -0
  74. topwater-0.1.0a4/tests/test_web.py +701 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Grant Miller
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,308 @@
1
+ Metadata-Version: 2.4
2
+ Name: topwater
3
+ Version: 0.1.0a4
4
+ Summary: Give your agent one `bash` tool backed by a simulated Linux shell and your own Python tools.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/gr-ant/Topwater
7
+ Project-URL: Repository, https://github.com/gr-ant/Topwater
8
+ Project-URL: Issues, https://github.com/gr-ant/Topwater/issues
9
+ Keywords: agents,llm,tool-use,bash,shell,sandbox,simulation
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Software Development :: Libraries
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ License-File: THIRD-PARTY-NOTICES.md
26
+ Provides-Extra: langchain
27
+ Requires-Dist: langchain-core>=0.3; extra == "langchain"
28
+ Provides-Extra: llamaindex
29
+ Requires-Dist: llama-index-core>=0.12; extra == "llamaindex"
30
+ Provides-Extra: openai-agents
31
+ Requires-Dist: openai-agents>=0.26; extra == "openai-agents"
32
+ Provides-Extra: claude-agent-sdk
33
+ Requires-Dist: claude-agent-sdk>=0.2; extra == "claude-agent-sdk"
34
+ Provides-Extra: pydantic-ai
35
+ Requires-Dist: pydantic-ai-slim>=2.0; extra == "pydantic-ai"
36
+ Provides-Extra: crewai
37
+ Requires-Dist: crewai>=1.0; extra == "crewai"
38
+ Provides-Extra: smolagents
39
+ Requires-Dist: smolagents>=1.20; extra == "smolagents"
40
+ Provides-Extra: google-adk
41
+ Requires-Dist: google-adk>=2.0; extra == "google-adk"
42
+ Dynamic: license-file
43
+
44
+ # Topwater for Python
45
+
46
+ One `bash` tool for your LLM agent, backed by a simulated Linux machine that runs inside your Python process. Your
47
+ functions are commands on it. Python 3.10 or later, standard library only.
48
+
49
+ This page covers the Python API. The [main README](https://github.com/gr-ant/Topwater/blob/main/README.md) explains what Topwater is, and
50
+ [docs/](https://github.com/gr-ant/Topwater/blob/main/docs/README.md) is the reference; its samples are C#, and the names below are their Python equivalents.
51
+
52
+ - [Install](#install)
53
+ - [Quickstart](#quickstart)
54
+ - [Your programs](#your-programs)
55
+ - [Files and documents](#files-and-documents)
56
+ - [Snapshots and recordings](#snapshots-and-recordings)
57
+ - [Containers](#containers)
58
+ - [Agent frameworks](#agent-frameworks)
59
+ - [Where Python differs](#where-python-differs)
60
+ - [Development](#development)
61
+
62
+ ## Install
63
+
64
+ Not on PyPI yet. Install from the repository:
65
+
66
+ ```bash
67
+ pip install "git+https://github.com/gr-ant/Topwater#subdirectory=python"
68
+ ```
69
+
70
+ or, from a clone, `pip install ./python`.
71
+
72
+ ## Quickstart
73
+
74
+ `db` stands for your own data; the [main README](https://github.com/gr-ant/Topwater/blob/main/README.md#python) has a version that runs as it is.
75
+
76
+ ```python
77
+ import topwater
78
+ from topwater import Shell, command
79
+
80
+ class Tools:
81
+ @command("orders", description="List orders")
82
+ def orders(self, status: str | None = None, limit: int = 20):
83
+ return db.orders(status, limit)
84
+
85
+ shell = Shell().register(Tools())
86
+ output = shell.run("orders --status open | jq length").to_tool_output()
87
+ # inside async code: output = await topwater.execute_tool(shell, command)
88
+ ```
89
+
90
+ - **Tool definition for your model:** `topwater.TOOL_NAME`, `TOOL_DESCRIPTION`, `TOOL_INPUT_SCHEMA`. On a shell with
91
+ [web access](https://github.com/gr-ant/Topwater/blob/main/docs/web.md), use `topwater.tool_description(shell)`, which names the sites; the adapters do.
92
+ - **Limits**, all on by default:
93
+ `Shell(max_call_duration=120, max_file_system_bytes=128 << 20, max_string_bytes=32 << 20, ...)`. Option names are
94
+ the C# ones in snake_case, and `max_call_duration` is in seconds. `ShellResult.trailer` holds the note a limit adds.
95
+ - **`shell.run()`** wraps `asyncio.run`. Inside an event loop use `await shell.run_async()`.
96
+ - **Web terminal:** `python -m topwater.web --demo`, then open http://127.0.0.1:8000.
97
+
98
+ ## Your programs
99
+
100
+ ```python
101
+ from topwater import Shell, command, CommandContext
102
+
103
+ class Tools:
104
+ @command("count-lines")
105
+ def count_lines(self, ctx: CommandContext) -> int: # ctx gives stdin, stdout, the filesystem
106
+ ctx.print(len(ctx.stdin.splitlines()))
107
+ return 0 # an int is the exit code; lists, dicts and dataclasses print as JSON
108
+ ```
109
+
110
+ ```python
111
+ from topwater.tools import ToolResult, ToolSpec, register_tools # tools described by a JSON Schema
112
+ register_tools(shell, "crm", specs, lambda tool, arguments: ToolResult(call(tool, arguments))) # sync or async
113
+
114
+ from topwater.mcp import StdioMcpClient, mount_mcp # MCP servers
115
+ mount_mcp(shell, "files", StdioMcpClient(["npx", "-y", "@modelcontextprotocol/server-filesystem", "/data"]),
116
+ include=lambda name: not name.startswith("admin"))
117
+
118
+ from topwater.api import ApiEndpoint, register_api # authenticated HTTP APIs
119
+ register_api(shell, "api", {"jira": ApiEndpoint("https://acme.atlassian.net/rest/api/3",
120
+ auth=lambda: f"Bearer {secrets.get('jira')}", paths=["/issue/", "/search"])})
121
+
122
+ from topwater import WebPolicy # web access: curl and wget to the sites you list
123
+ shell.allow_web(WebPolicy(domains=["api.github.com", "*.wikipedia.org"]))
124
+
125
+ from topwater.host import bubblewrap, register_host_command # real host programs
126
+ duckdb = register_host_command(shell, "duckdb", launcher=bubblewrap()) # duckdb.close() removes its folder and the command
127
+ ```
128
+
129
+ All of these do real work when the agent calls them. [Your programs](https://github.com/gr-ant/Topwater/blob/main/docs/programs.md) says what each guarantees.
130
+
131
+ ## Files and documents
132
+
133
+ ```python
134
+ shell.fs.mkdir("/home/agent/data", parents=True)
135
+ shell.fs.write_text("/home/agent/data/config.json", text)
136
+ shell.fs.add_document("/home/agent/docs/policy.docx", "/real/path/policy.docx") # or bytes; also_markdown=True
137
+ text = topwater.convert.to_markdown(data, "report.xlsx")
138
+ ```
139
+
140
+ To give the built-in `git` an identity, write `/home/agent/.gitconfig` with `shell.fs.write_text`, or set
141
+ `GIT_AUTHOR_*` and `GIT_COMMITTER_*` in `shell.env` ([git](https://github.com/gr-ant/Topwater/blob/main/docs/machine.md#git)).
142
+
143
+ ## Snapshots and recordings
144
+
145
+ Machines and recordings are [`.topwater` files](https://github.com/gr-ant/Topwater/blob/main/docs/snapshots-and-recordings.md#the-file-format), the same in
146
+ every implementation.
147
+
148
+ ```python
149
+ from topwater import Shell, ShellSnapshot, Recording
150
+
151
+ before = shell.snapshot(); shell.run("rm -rf src"); shell.restore(before)
152
+ attempt = shell.fork() # shares nothing mutable; registered handlers are shared
153
+ shell.save("machine.topwater") # a path or a binary file
154
+ later = Shell.load("machine.topwater") # built-ins only (also bytes or a file); Shell() kwargs set the limits
155
+ shell.restore(ShellSnapshot.load("machine.topwater", shell)) # or load into a shell you configured, with its limits
156
+
157
+ with shell.start_recording(snapshot_every=10, metadata={"task": "..."}) as rec: # every run()/run_async() call
158
+ ... # rec.snapshot_now() keeps a checkpoint here
159
+ rec.save("run.topwater") # Shell.load() of it gives the machine after the last call
160
+ run = Recording.load("run.topwater", limits=shell) # also old .jsonl recordings and snapshot zips
161
+ run.calls[3].stdout, run.calls[3].files # what call 3 printed, the paths it added, changed or removed
162
+ probe = run.shell_at(3) # the machine after call 3: nearest checkpoint, then calls re-run
163
+ report = run.replay(run.create_shell(register_mine)) # report.matches, report.differences; normalize= to ignore times
164
+ ```
165
+
166
+ ## Containers
167
+
168
+ ```python
169
+ from topwater import containers # host code only: no shell command reaches it
170
+
171
+ ctx = containers.build_image(shell.snapshot(), "my-agent") # docker build; print(ctx.report) for what didn't carry over
172
+ containers.to_build_context(shell.snapshot()).write_to("build") # or write_tar(f); pure, no process
173
+ result = containers.from_container("web-1", containers.ImportOptions(paths=("/var/log", "/etc")))
174
+ shell = Shell(result.snapshot.user); shell.restore(result.snapshot)
175
+ ```
176
+
177
+ An exported image holds what the agent wrote: its files, scripts and `~/.bashrc`, with the session script it
178
+ sources. A shell in the image runs that content, so treat the image as untrusted and run it with the same care,
179
+ limits and isolation as the agent itself. See [Containers](https://github.com/gr-ant/Topwater/blob/main/docs/containers.md).
180
+
181
+ ## Agent frameworks
182
+
183
+ Each adapter is an extra. Until the package is on PyPI, name the repository:
184
+
185
+ ```bash
186
+ pip install "topwater[langchain] @ git+https://github.com/gr-ant/Topwater#subdirectory=python"
187
+ ```
188
+
189
+ The extras are `langchain`, `llamaindex`, `openai-agents`, `claude-agent-sdk`, `pydantic-ai`, `crewai`,
190
+ `smolagents` and `google-adk`.
191
+
192
+ Every adapter exposes `bash_tool(shell=None, description=None)`: a tool named `bash` with the standard description
193
+ and one `command` argument, as the framework's own tool type. Calls on one shell run one at a time, even from two
194
+ tools, and the shell keeps its state between calls. Sync tools work inside a running event loop (a notebook, an
195
+ async handler) too, though the loop waits for the call. Each module imports only its own framework;
196
+ `import topwater` imports none.
197
+
198
+ ```python
199
+ from langchain.agents import create_agent # LangChain, and LangGraph underneath
200
+ from topwater import Shell
201
+ from topwater.integrations.langchain import bash_tool
202
+
203
+ shell = Shell()
204
+ agent = create_agent(llm, tools=[bash_tool(shell)]) # or llm.bind_tools([bash_tool(shell)])
205
+ ```
206
+
207
+ ```python
208
+ from llama_index.core.agent.workflow import FunctionAgent
209
+ from topwater.integrations.llamaindex import bash_tool
210
+
211
+ agent = FunctionAgent(tools=[bash_tool(shell)], llm=llm)
212
+ ```
213
+
214
+ ```python
215
+ from agents import Agent # OpenAI Agents SDK
216
+ from topwater.integrations.openai_agents import bash_tool
217
+
218
+ agent = Agent(name="assistant", tools=[bash_tool(shell)])
219
+ ```
220
+
221
+ The Claude Agent SDK takes the tool through an in-process MCP server, so Claude sees it as `mcp__topwater__bash`.
222
+ Use `bash_options`, not `bash_tool` alone: it builds the whole safe setup. `tools=[]` turns off Claude Code's own
223
+ tools, its real `Bash` among them, and `setting_sources=[]` with `strict_mcp_config=True` keeps the developer's own
224
+ Claude Code settings, allow rules and MCP servers out of the agent. Other `ClaudeAgentOptions` arguments pass through:
225
+
226
+ ```python
227
+ from claude_agent_sdk import query
228
+ from topwater.integrations.claude_agent_sdk import bash_options
229
+
230
+ async for message in query(prompt="...", options=bash_options(shell, system_prompt="...")):
231
+ print(message)
232
+ ```
233
+
234
+ ```python
235
+ from pydantic_ai import Agent
236
+ from topwater.integrations.pydantic_ai import bash_tool
237
+
238
+ agent = Agent(model, tools=[bash_tool(shell)])
239
+ ```
240
+
241
+ ```python
242
+ from crewai import Agent
243
+ from topwater.integrations.crewai import bash_tool
244
+
245
+ agent = Agent(role="Analyst", goal="...", backstory="...", tools=[bash_tool(shell)])
246
+ ```
247
+
248
+ ```python
249
+ from smolagents import ToolCallingAgent
250
+ from topwater.integrations.smolagents import bash_tool
251
+
252
+ agent = ToolCallingAgent(tools=[bash_tool(shell)], model=model)
253
+ ```
254
+
255
+ ```python
256
+ from google.adk.agents import Agent
257
+ from topwater.integrations.google_adk import bash_tool
258
+
259
+ agent = Agent(name="assistant", model=model, tools=[bash_tool(shell)])
260
+ ```
261
+
262
+ Pydantic AI and Google ADK need Python 3.11 or later. CrewAI pins an older `openai` than the OpenAI Agents SDK
263
+ wants, so pip reports a conflict when both extras share an environment. AutoGen has no adapter: it is in maintenance
264
+ mode, and Microsoft points new projects to Microsoft Agent Framework.
265
+
266
+ ## Where Python differs
267
+
268
+ - **Not ported yet:** `bc`, the virtual clock and random seed ([deterministic
269
+ runs](https://github.com/gr-ant/Topwater/blob/main/docs/snapshots-and-recordings.md#deterministic-runs)), and replaying a recording as a test or on real bash
270
+ in Docker (`Topwater.Replay`).
271
+ - **Errors.** Snapshot load errors are `topwater.snapshot.SnapshotError` (a `ValueError`; C#'s `InvalidDataException`)
272
+ and `SnapshotVersionError` (C#'s `NotSupportedException`); a bad recording raises `RecordingError`, a
273
+ `SnapshotError`.
274
+ - **Clock.** Without a virtual clock or random seed, Python writes no `clock` or `random` and ignores them when
275
+ loading (after checking them). A recording's `start_time` and `random_seed` are kept and written back, never used,
276
+ so a replay here compares wall-clock output (pass `normalize=`). A call's `time` is the wall clock when it started.
277
+ - **Containers.** `topwater.containers` is synchronous (it shells out to the docker CLI, and an import runs
278
+ `session.sh` with `Shell.run`), so call it outside a running event loop. Names: `to_build_context`, `build_image`,
279
+ `from_container`, `from_image`, `from_tar(rootfs, ContainerConfig(user, working_dir, env), changes,
280
+ options)`, `docker_available()`; `ImportOptions(paths, include_binaries, restore_session,
281
+ limits)` where `limits` is a dict of `Shell()` arguments. Bad container data (a malformed archive, one over a limit,
282
+ a time or owner no snapshot can hold) raises `InvalidContainerData`, docker failures `ContainerError`. The export
283
+ quotes every name in `setup.sh`, leaves out account names starting with `-`, and refuses a base image name with a
284
+ line break.
285
+ - **MCP.** `topwater.mcp` is a small standard-library client for servers spoken to over stdio; `mount_mcp` accepts any
286
+ object with `list_tools()` and `call_tool(name, arguments)` returning MCP's dict shapes, so the official `mcp` SDK
287
+ adapts in a few lines.
288
+ - **APIs.** `register_api` takes a `transport` function `(method, url, headers, body, timeout, limit) -> (status,
289
+ reason, headers, body)` in place of an `HttpMessageHandler`. The default uses `urllib` with redirects disabled; a
290
+ transport you pass must not follow redirects either (it can't be checked).
291
+ - **Regular expressions.** The standard `re` module has no timeout, but it checks for signals while it backtracks. On
292
+ the main thread, a grep, sed, awk or `[[ =~ ]]` match runs under a one-shot `SIGALRM` for the time the call has
293
+ left, so one catastrophically backtracking match (`grep -E '(a+)+$'` on a long run of `a`s) stops at the call's time
294
+ limit. The alarm is set only around the match, and only when the host has no `SIGALRM` handler or interval timer of
295
+ its own; both are left as they were. In a worker thread, on Windows, or when the host uses `SIGALRM`, such a match
296
+ runs to completion and the time limit is checked between lines, records and steps.
297
+ - **Nesting and memory.** Nesting is bounded by Python's recursion limit instead of the .NET stack. Memory use has not
298
+ been measured; text is held as Python strings.
299
+
300
+ ## Development
301
+
302
+ ```bash
303
+ cd python && python -m pytest -q
304
+ ```
305
+
306
+ The shared cases live in [`../tests/corpus`](https://github.com/gr-ant/Topwater/blob/main/tests/corpus/README.md), recorded from real bash and GNU tools, and
307
+ run through `tests/test_corpus.py`. Known differences are in `../tests/corpus/skip/python.json`. Examples with a
308
+ real model are in `examples/`.
@@ -0,0 +1,265 @@
1
+ # Topwater for Python
2
+
3
+ One `bash` tool for your LLM agent, backed by a simulated Linux machine that runs inside your Python process. Your
4
+ functions are commands on it. Python 3.10 or later, standard library only.
5
+
6
+ This page covers the Python API. The [main README](https://github.com/gr-ant/Topwater/blob/main/README.md) explains what Topwater is, and
7
+ [docs/](https://github.com/gr-ant/Topwater/blob/main/docs/README.md) is the reference; its samples are C#, and the names below are their Python equivalents.
8
+
9
+ - [Install](#install)
10
+ - [Quickstart](#quickstart)
11
+ - [Your programs](#your-programs)
12
+ - [Files and documents](#files-and-documents)
13
+ - [Snapshots and recordings](#snapshots-and-recordings)
14
+ - [Containers](#containers)
15
+ - [Agent frameworks](#agent-frameworks)
16
+ - [Where Python differs](#where-python-differs)
17
+ - [Development](#development)
18
+
19
+ ## Install
20
+
21
+ Not on PyPI yet. Install from the repository:
22
+
23
+ ```bash
24
+ pip install "git+https://github.com/gr-ant/Topwater#subdirectory=python"
25
+ ```
26
+
27
+ or, from a clone, `pip install ./python`.
28
+
29
+ ## Quickstart
30
+
31
+ `db` stands for your own data; the [main README](https://github.com/gr-ant/Topwater/blob/main/README.md#python) has a version that runs as it is.
32
+
33
+ ```python
34
+ import topwater
35
+ from topwater import Shell, command
36
+
37
+ class Tools:
38
+ @command("orders", description="List orders")
39
+ def orders(self, status: str | None = None, limit: int = 20):
40
+ return db.orders(status, limit)
41
+
42
+ shell = Shell().register(Tools())
43
+ output = shell.run("orders --status open | jq length").to_tool_output()
44
+ # inside async code: output = await topwater.execute_tool(shell, command)
45
+ ```
46
+
47
+ - **Tool definition for your model:** `topwater.TOOL_NAME`, `TOOL_DESCRIPTION`, `TOOL_INPUT_SCHEMA`. On a shell with
48
+ [web access](https://github.com/gr-ant/Topwater/blob/main/docs/web.md), use `topwater.tool_description(shell)`, which names the sites; the adapters do.
49
+ - **Limits**, all on by default:
50
+ `Shell(max_call_duration=120, max_file_system_bytes=128 << 20, max_string_bytes=32 << 20, ...)`. Option names are
51
+ the C# ones in snake_case, and `max_call_duration` is in seconds. `ShellResult.trailer` holds the note a limit adds.
52
+ - **`shell.run()`** wraps `asyncio.run`. Inside an event loop use `await shell.run_async()`.
53
+ - **Web terminal:** `python -m topwater.web --demo`, then open http://127.0.0.1:8000.
54
+
55
+ ## Your programs
56
+
57
+ ```python
58
+ from topwater import Shell, command, CommandContext
59
+
60
+ class Tools:
61
+ @command("count-lines")
62
+ def count_lines(self, ctx: CommandContext) -> int: # ctx gives stdin, stdout, the filesystem
63
+ ctx.print(len(ctx.stdin.splitlines()))
64
+ return 0 # an int is the exit code; lists, dicts and dataclasses print as JSON
65
+ ```
66
+
67
+ ```python
68
+ from topwater.tools import ToolResult, ToolSpec, register_tools # tools described by a JSON Schema
69
+ register_tools(shell, "crm", specs, lambda tool, arguments: ToolResult(call(tool, arguments))) # sync or async
70
+
71
+ from topwater.mcp import StdioMcpClient, mount_mcp # MCP servers
72
+ mount_mcp(shell, "files", StdioMcpClient(["npx", "-y", "@modelcontextprotocol/server-filesystem", "/data"]),
73
+ include=lambda name: not name.startswith("admin"))
74
+
75
+ from topwater.api import ApiEndpoint, register_api # authenticated HTTP APIs
76
+ register_api(shell, "api", {"jira": ApiEndpoint("https://acme.atlassian.net/rest/api/3",
77
+ auth=lambda: f"Bearer {secrets.get('jira')}", paths=["/issue/", "/search"])})
78
+
79
+ from topwater import WebPolicy # web access: curl and wget to the sites you list
80
+ shell.allow_web(WebPolicy(domains=["api.github.com", "*.wikipedia.org"]))
81
+
82
+ from topwater.host import bubblewrap, register_host_command # real host programs
83
+ duckdb = register_host_command(shell, "duckdb", launcher=bubblewrap()) # duckdb.close() removes its folder and the command
84
+ ```
85
+
86
+ All of these do real work when the agent calls them. [Your programs](https://github.com/gr-ant/Topwater/blob/main/docs/programs.md) says what each guarantees.
87
+
88
+ ## Files and documents
89
+
90
+ ```python
91
+ shell.fs.mkdir("/home/agent/data", parents=True)
92
+ shell.fs.write_text("/home/agent/data/config.json", text)
93
+ shell.fs.add_document("/home/agent/docs/policy.docx", "/real/path/policy.docx") # or bytes; also_markdown=True
94
+ text = topwater.convert.to_markdown(data, "report.xlsx")
95
+ ```
96
+
97
+ To give the built-in `git` an identity, write `/home/agent/.gitconfig` with `shell.fs.write_text`, or set
98
+ `GIT_AUTHOR_*` and `GIT_COMMITTER_*` in `shell.env` ([git](https://github.com/gr-ant/Topwater/blob/main/docs/machine.md#git)).
99
+
100
+ ## Snapshots and recordings
101
+
102
+ Machines and recordings are [`.topwater` files](https://github.com/gr-ant/Topwater/blob/main/docs/snapshots-and-recordings.md#the-file-format), the same in
103
+ every implementation.
104
+
105
+ ```python
106
+ from topwater import Shell, ShellSnapshot, Recording
107
+
108
+ before = shell.snapshot(); shell.run("rm -rf src"); shell.restore(before)
109
+ attempt = shell.fork() # shares nothing mutable; registered handlers are shared
110
+ shell.save("machine.topwater") # a path or a binary file
111
+ later = Shell.load("machine.topwater") # built-ins only (also bytes or a file); Shell() kwargs set the limits
112
+ shell.restore(ShellSnapshot.load("machine.topwater", shell)) # or load into a shell you configured, with its limits
113
+
114
+ with shell.start_recording(snapshot_every=10, metadata={"task": "..."}) as rec: # every run()/run_async() call
115
+ ... # rec.snapshot_now() keeps a checkpoint here
116
+ rec.save("run.topwater") # Shell.load() of it gives the machine after the last call
117
+ run = Recording.load("run.topwater", limits=shell) # also old .jsonl recordings and snapshot zips
118
+ run.calls[3].stdout, run.calls[3].files # what call 3 printed, the paths it added, changed or removed
119
+ probe = run.shell_at(3) # the machine after call 3: nearest checkpoint, then calls re-run
120
+ report = run.replay(run.create_shell(register_mine)) # report.matches, report.differences; normalize= to ignore times
121
+ ```
122
+
123
+ ## Containers
124
+
125
+ ```python
126
+ from topwater import containers # host code only: no shell command reaches it
127
+
128
+ ctx = containers.build_image(shell.snapshot(), "my-agent") # docker build; print(ctx.report) for what didn't carry over
129
+ containers.to_build_context(shell.snapshot()).write_to("build") # or write_tar(f); pure, no process
130
+ result = containers.from_container("web-1", containers.ImportOptions(paths=("/var/log", "/etc")))
131
+ shell = Shell(result.snapshot.user); shell.restore(result.snapshot)
132
+ ```
133
+
134
+ An exported image holds what the agent wrote: its files, scripts and `~/.bashrc`, with the session script it
135
+ sources. A shell in the image runs that content, so treat the image as untrusted and run it with the same care,
136
+ limits and isolation as the agent itself. See [Containers](https://github.com/gr-ant/Topwater/blob/main/docs/containers.md).
137
+
138
+ ## Agent frameworks
139
+
140
+ Each adapter is an extra. Until the package is on PyPI, name the repository:
141
+
142
+ ```bash
143
+ pip install "topwater[langchain] @ git+https://github.com/gr-ant/Topwater#subdirectory=python"
144
+ ```
145
+
146
+ The extras are `langchain`, `llamaindex`, `openai-agents`, `claude-agent-sdk`, `pydantic-ai`, `crewai`,
147
+ `smolagents` and `google-adk`.
148
+
149
+ Every adapter exposes `bash_tool(shell=None, description=None)`: a tool named `bash` with the standard description
150
+ and one `command` argument, as the framework's own tool type. Calls on one shell run one at a time, even from two
151
+ tools, and the shell keeps its state between calls. Sync tools work inside a running event loop (a notebook, an
152
+ async handler) too, though the loop waits for the call. Each module imports only its own framework;
153
+ `import topwater` imports none.
154
+
155
+ ```python
156
+ from langchain.agents import create_agent # LangChain, and LangGraph underneath
157
+ from topwater import Shell
158
+ from topwater.integrations.langchain import bash_tool
159
+
160
+ shell = Shell()
161
+ agent = create_agent(llm, tools=[bash_tool(shell)]) # or llm.bind_tools([bash_tool(shell)])
162
+ ```
163
+
164
+ ```python
165
+ from llama_index.core.agent.workflow import FunctionAgent
166
+ from topwater.integrations.llamaindex import bash_tool
167
+
168
+ agent = FunctionAgent(tools=[bash_tool(shell)], llm=llm)
169
+ ```
170
+
171
+ ```python
172
+ from agents import Agent # OpenAI Agents SDK
173
+ from topwater.integrations.openai_agents import bash_tool
174
+
175
+ agent = Agent(name="assistant", tools=[bash_tool(shell)])
176
+ ```
177
+
178
+ The Claude Agent SDK takes the tool through an in-process MCP server, so Claude sees it as `mcp__topwater__bash`.
179
+ Use `bash_options`, not `bash_tool` alone: it builds the whole safe setup. `tools=[]` turns off Claude Code's own
180
+ tools, its real `Bash` among them, and `setting_sources=[]` with `strict_mcp_config=True` keeps the developer's own
181
+ Claude Code settings, allow rules and MCP servers out of the agent. Other `ClaudeAgentOptions` arguments pass through:
182
+
183
+ ```python
184
+ from claude_agent_sdk import query
185
+ from topwater.integrations.claude_agent_sdk import bash_options
186
+
187
+ async for message in query(prompt="...", options=bash_options(shell, system_prompt="...")):
188
+ print(message)
189
+ ```
190
+
191
+ ```python
192
+ from pydantic_ai import Agent
193
+ from topwater.integrations.pydantic_ai import bash_tool
194
+
195
+ agent = Agent(model, tools=[bash_tool(shell)])
196
+ ```
197
+
198
+ ```python
199
+ from crewai import Agent
200
+ from topwater.integrations.crewai import bash_tool
201
+
202
+ agent = Agent(role="Analyst", goal="...", backstory="...", tools=[bash_tool(shell)])
203
+ ```
204
+
205
+ ```python
206
+ from smolagents import ToolCallingAgent
207
+ from topwater.integrations.smolagents import bash_tool
208
+
209
+ agent = ToolCallingAgent(tools=[bash_tool(shell)], model=model)
210
+ ```
211
+
212
+ ```python
213
+ from google.adk.agents import Agent
214
+ from topwater.integrations.google_adk import bash_tool
215
+
216
+ agent = Agent(name="assistant", model=model, tools=[bash_tool(shell)])
217
+ ```
218
+
219
+ Pydantic AI and Google ADK need Python 3.11 or later. CrewAI pins an older `openai` than the OpenAI Agents SDK
220
+ wants, so pip reports a conflict when both extras share an environment. AutoGen has no adapter: it is in maintenance
221
+ mode, and Microsoft points new projects to Microsoft Agent Framework.
222
+
223
+ ## Where Python differs
224
+
225
+ - **Not ported yet:** `bc`, the virtual clock and random seed ([deterministic
226
+ runs](https://github.com/gr-ant/Topwater/blob/main/docs/snapshots-and-recordings.md#deterministic-runs)), and replaying a recording as a test or on real bash
227
+ in Docker (`Topwater.Replay`).
228
+ - **Errors.** Snapshot load errors are `topwater.snapshot.SnapshotError` (a `ValueError`; C#'s `InvalidDataException`)
229
+ and `SnapshotVersionError` (C#'s `NotSupportedException`); a bad recording raises `RecordingError`, a
230
+ `SnapshotError`.
231
+ - **Clock.** Without a virtual clock or random seed, Python writes no `clock` or `random` and ignores them when
232
+ loading (after checking them). A recording's `start_time` and `random_seed` are kept and written back, never used,
233
+ so a replay here compares wall-clock output (pass `normalize=`). A call's `time` is the wall clock when it started.
234
+ - **Containers.** `topwater.containers` is synchronous (it shells out to the docker CLI, and an import runs
235
+ `session.sh` with `Shell.run`), so call it outside a running event loop. Names: `to_build_context`, `build_image`,
236
+ `from_container`, `from_image`, `from_tar(rootfs, ContainerConfig(user, working_dir, env), changes,
237
+ options)`, `docker_available()`; `ImportOptions(paths, include_binaries, restore_session,
238
+ limits)` where `limits` is a dict of `Shell()` arguments. Bad container data (a malformed archive, one over a limit,
239
+ a time or owner no snapshot can hold) raises `InvalidContainerData`, docker failures `ContainerError`. The export
240
+ quotes every name in `setup.sh`, leaves out account names starting with `-`, and refuses a base image name with a
241
+ line break.
242
+ - **MCP.** `topwater.mcp` is a small standard-library client for servers spoken to over stdio; `mount_mcp` accepts any
243
+ object with `list_tools()` and `call_tool(name, arguments)` returning MCP's dict shapes, so the official `mcp` SDK
244
+ adapts in a few lines.
245
+ - **APIs.** `register_api` takes a `transport` function `(method, url, headers, body, timeout, limit) -> (status,
246
+ reason, headers, body)` in place of an `HttpMessageHandler`. The default uses `urllib` with redirects disabled; a
247
+ transport you pass must not follow redirects either (it can't be checked).
248
+ - **Regular expressions.** The standard `re` module has no timeout, but it checks for signals while it backtracks. On
249
+ the main thread, a grep, sed, awk or `[[ =~ ]]` match runs under a one-shot `SIGALRM` for the time the call has
250
+ left, so one catastrophically backtracking match (`grep -E '(a+)+$'` on a long run of `a`s) stops at the call's time
251
+ limit. The alarm is set only around the match, and only when the host has no `SIGALRM` handler or interval timer of
252
+ its own; both are left as they were. In a worker thread, on Windows, or when the host uses `SIGALRM`, such a match
253
+ runs to completion and the time limit is checked between lines, records and steps.
254
+ - **Nesting and memory.** Nesting is bounded by Python's recursion limit instead of the .NET stack. Memory use has not
255
+ been measured; text is held as Python strings.
256
+
257
+ ## Development
258
+
259
+ ```bash
260
+ cd python && python -m pytest -q
261
+ ```
262
+
263
+ The shared cases live in [`../tests/corpus`](https://github.com/gr-ant/Topwater/blob/main/tests/corpus/README.md), recorded from real bash and GNU tools, and
264
+ run through `tests/test_corpus.py`. Known differences are in `../tests/corpus/skip/python.json`. Examples with a
265
+ real model are in `examples/`.
@@ -0,0 +1,34 @@
1
+ # Third-party notices
2
+
3
+ Topwater is written from scratch (see the clean-room note in
4
+ [spec/README.md](https://github.com/gr-ant/Topwater/blob/main/spec/README.md)). The text below is the one place where
5
+ it reproduces material from another project.
6
+
7
+ ## jq
8
+
9
+ `jq --help` in Topwater prints the opening of jq 1.7.1's own help text (the usage lines, the description and the
10
+ example), kept in [spec/commands/jq.json](https://github.com/gr-ant/Topwater/blob/main/spec/commands/jq.json). jq is
11
+ distributed under the MIT license:
12
+
13
+ ```
14
+ Copyright (C) 2012 Stephen Dolan
15
+
16
+ Permission is hereby granted, free of charge, to any person obtaining
17
+ a copy of this software and associated documentation files (the
18
+ "Software"), to deal in the Software without restriction, including
19
+ without limitation the rights to use, copy, modify, merge, publish,
20
+ distribute, sublicense, and/or sell copies of the Software, and to
21
+ permit persons to whom the Software is furnished to do so, subject to
22
+ the following conditions:
23
+
24
+ The above copyright notice and this permission notice shall be
25
+ included in all copies or substantial portions of the Software.
26
+
27
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34
+ ```