e2b-claude-toolsets 0.0.2__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 (37) hide show
  1. e2b_claude_toolsets-0.0.2/.gitignore +29 -0
  2. e2b_claude_toolsets-0.0.2/LICENSE +201 -0
  3. e2b_claude_toolsets-0.0.2/PKG-INFO +148 -0
  4. e2b_claude_toolsets-0.0.2/README.md +135 -0
  5. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/__init__.py +23 -0
  6. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_async.py +26 -0
  7. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_async_browser.py +1023 -0
  8. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_async_cdp.py +231 -0
  9. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_async_computer.py +227 -0
  10. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_async_sandbox.py +123 -0
  11. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_browser.py +960 -0
  12. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_browser_state.py +347 -0
  13. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_cdp.py +305 -0
  14. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_computer.py +259 -0
  15. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_input.py +242 -0
  16. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_policy.py +69 -0
  17. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_runtime/THIRD_PARTY_LICENSES.txt +205 -0
  18. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_runtime/manifest.json +7 -0
  19. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_runtime/runtime.js +3076 -0
  20. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_sandbox.py +172 -0
  21. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_scripts.py +54 -0
  22. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_uploads.py +89 -0
  23. e2b_claude_toolsets-0.0.2/e2b_claude_toolsets/_viewer.py +243 -0
  24. e2b_claude_toolsets-0.0.2/hatch_build.py +28 -0
  25. e2b_claude_toolsets-0.0.2/pyproject.toml +41 -0
  26. e2b_claude_toolsets-0.0.2/tests/live/computer.py +73 -0
  27. e2b_claude_toolsets-0.0.2/tests/live/detach.py +99 -0
  28. e2b_claude_toolsets-0.0.2/tests/live/headless.py +47 -0
  29. e2b_claude_toolsets-0.0.2/tests/live/lifecycle.py +139 -0
  30. e2b_claude_toolsets-0.0.2/tests/live/security.py +134 -0
  31. e2b_claude_toolsets-0.0.2/tests/support.py +241 -0
  32. e2b_claude_toolsets-0.0.2/tests/test_async.py +538 -0
  33. e2b_claude_toolsets-0.0.2/tests/test_contracts.py +707 -0
  34. e2b_claude_toolsets-0.0.2/tests/test_parity.py +283 -0
  35. e2b_claude_toolsets-0.0.2/tests/test_review.py +215 -0
  36. e2b_claude_toolsets-0.0.2/tests/test_runtime.py +69 -0
  37. e2b_claude_toolsets-0.0.2/tests/test_viewer.py +146 -0
@@ -0,0 +1,29 @@
1
+ # Local notes and experiments: never committed.
2
+ docs/raw/
3
+ experimental/
4
+
5
+ # Credentials.
6
+ .env
7
+ .env.*
8
+ !.env.example
9
+
10
+ # Dependencies and tool caches.
11
+ node_modules/
12
+ .venv/
13
+ .ruff_cache/
14
+ __pycache__/
15
+
16
+ # Build output and local run output: regenerate, don't commit.
17
+ dist/
18
+ *.egg-info/
19
+ results/
20
+
21
+ # Browser runtime assets, built from packages/claude-toolsets-runtime into both packages.
22
+ /packages/claude-toolsets-js/src/generated/
23
+ /packages/claude-toolsets-python/e2b_claude_toolsets/_runtime/
24
+
25
+ # Personal agent notes.
26
+ /AGENTS.md
27
+ CLAUDE.md
28
+ DECISIONS.md
29
+ EXECUTION_PLAN.md
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.5
2
+ Name: e2b-claude-toolsets
3
+ Version: 0.0.2
4
+ Summary: E2B browser and computer drivers for Anthropic toolsets
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.10
7
+ Requires-Dist: anthropic<2,>=1.12.0
8
+ Requires-Dist: e2b-desktop<3,>=2.6.0
9
+ Requires-Dist: e2b<3,>=2.51.0
10
+ Requires-Dist: httpx<1,>=0.28.1
11
+ Requires-Dist: websockets>=16.0
12
+ Description-Content-Type: text/markdown
13
+
14
+ # E2B Claude Toolsets for Python
15
+
16
+ Synchronous and native asyncio browser and computer drivers for Anthropic toolsets, on the standard E2B desktop. Both browser drivers implement all 31 browser actions; the four optional actions stay disabled by default. Both computer drivers implement 16 actions; computer zoom is unavailable.
17
+
18
+ ## Development
19
+
20
+ Developing from Git requires Python 3.10+, uv, pnpm and Bun 1.3.14; see the [repo README](https://github.com/e2b-dev/claude-toolsets#development).
21
+
22
+ ```sh
23
+ pnpm install # repo root: JS dependencies and the browser runtime
24
+ cd packages/claude-toolsets-python
25
+ uv sync --python 3.10
26
+ uv run python -m unittest discover -s tests -v
27
+ uv run ruff check
28
+ uv run ruff format --check
29
+ uv run ty check
30
+ uv build
31
+ ```
32
+
33
+ The Python build hook generates runtime assets from a Git checkout and includes them in both the wheel and sdist. Installing either built archive does not require Bun or Node.
34
+
35
+ The tests use the Anthropic SDK, local protocol fixtures and mocked E2B calls. They never create sandboxes or call a model. The protocol fixture does not execute DOM scripts. Run `pnpm setup:browsers` and `pnpm test:runtime` to execute both bridges against real local Chromium fixtures. Live E2B/model validation remains a separate step.
36
+
37
+ ## Examples
38
+
39
+ These commands create billable resources. They are manual examples, not offline tests. Set `E2B_API_KEY`; model examples also require `ANTHROPIC_API_KEY`. Set `ANTHROPIC_MODEL` to a model available to your account (the reference default is `claude-sonnet-5-5`). CLI login alone does not supply SDK credentials.
40
+
41
+ Run them from the repo root with this package's environment; the live tests run from this folder.
42
+
43
+ ```sh
44
+ uv run --project packages/claude-toolsets-python python examples/1-run.py "Read the latest E2B release"
45
+ uv run --project packages/claude-toolsets-python python examples/4-computer.py "Open a text editor and write a short note"
46
+ uv run --project packages/claude-toolsets-python python examples/2-exercise.py
47
+ uv run --project packages/claude-toolsets-python python examples/5-async-run.py
48
+ uv run --project packages/claude-toolsets-python python examples/5-async-run.py --computer
49
+ uv run --project packages/claude-toolsets-python python examples/6-async-exercise.py
50
+ cd packages/claude-toolsets-python
51
+ uv run python tests/live/detach.py # requires a snapshot-capable template; optional TEMPLATE override
52
+ uv run python tests/live/lifecycle.py # injected cleanup/interception failures; no model
53
+ uv run python tests/live/computer.py # all computer actions and input refusals; no model
54
+ ```
55
+
56
+ The exercise creates one desktop and a local HTML fixture, calls all 31 browser and 16 computer members through SDK dispatch, and cleans up the desktop. It uses no model API. An acknowledgment proves dispatch completed; only its explicit assertions check page behavior. The async exercise checks the form/upload/diagnostic workflow, native desktop text and screenshots, cancellation recovery and detach/reattach. It is a focused behavior check; the sync exercise dispatches every implemented action. The examples use a 600-second sandbox lifetime and explicit cleanup. Use a fresh, exclusive desktop for live view.
57
+
58
+ ## API and ownership
59
+
60
+ ```python
61
+ from e2b_claude_toolsets import E2BBrowserToolset, E2BComputerToolset, allow_hosts, live_view
62
+
63
+ with E2BBrowserToolset.create(allow_out=["example.com"], url_policy=allow_hosts(["example.com"])) as browser:
64
+ # Pass browser directly in Anthropic().beta.messages.tool_runner(tools=[browser], ...).
65
+ # The toolset owns this sandbox. Exiting closes Chrome and kills the sandbox.
66
+ sandbox = browser.sandbox
67
+ ```
68
+
69
+ `E2BBrowserToolset.create(sandbox=desktop, ...)` borrows the sandbox. On an `e2b_desktop` sandbox Chrome opens visibly on its screen, so it shows in the live view; pass `headless=True` to hide it, or `display=":1"` for another screen. An `AsyncSandbox` from `AsyncSandbox.connect()` carries no screen information, so pass `display=":0"` there to show Chrome on the desktop. It stops only Chrome it started, removes its own temporary directory, and closes its CDP connection. A pre-existing Chrome process stays running. Attach to one Chrome session exclusively; its caller remains responsible for the profile, egress and sandbox lifetime. When creating a sandbox, options include `api_key`, `template` (default `desktop`), `timeout` in seconds, `allow_out`, and `metadata`. Attached sandboxes must already have `allow_public_traffic=False` and `mask_request_host="localhost:${PORT}"`; creation-only options are refused when attaching.
70
+
71
+ `E2BComputerToolset.create(desktop, confirm=...)` borrows the desktop. It uses native screenshots/text and validated xdotool input. The SDK requires confirmation while `type`, `key` or `hold_key` is enabled. The computer example explicitly approves unattended input; an application should provide its intended approval behavior.
72
+
73
+ Sync and async toolsets preserve SDK `configs`, `confirm` and `tool_configs`; browser additionally accepts `url_policy` and `file_policy`. Omitted URL policy and explicit `None` have different SDK semantics. Unimplemented members are disabled by the SDK. The SDK owns input parsing, confirmation, action serialization and tool-result rendering. A toolset can serve multiple runner invocations; runners never close it. Use context managers or `finally: toolset.close()`.
74
+
75
+ `close()` marks a toolset closed, waits for accepted calls, then releases resources. Failed release keeps its resource record for retry. Startup failures clean up partial resources; `BrowserInitializationError.close()` and `ViewerInitializationError.view.stop()` allow retry after failed startup cleanup. Lost connections or expired sandboxes produce errors; sessions are never silently replaced and state-changing actions are never automatically replayed. A command timeout leaves the remote outcome uncertain. Sync interruption does not prove an already submitted remote operation stopped. On unexpected CDP loss, a separate cleanup thread attempts to stop Chrome started by this toolset through E2B's command API; the sandbox stays available until `close()`. A failed stop is reported and can be retried. Caller-owned Chrome stays running and its URL policy is no longer enforced after disconnection.
76
+
77
+ `live_view(desktop)` returns a context manager with `.url` and `.stop()`. It binds to loopback, uses a random capability path, validates host/origin, and proxies HTTP and WebSocket traffic with the traffic token kept in Python. Bodies and queues are bounded. Stopping closes local connections and the VNC stream it started; it never kills the desktop. Existing VNC streams are refused because Desktop SDK stream teardown is sandbox-wide. If stream teardown fails, retry `stop()`. Do not share the capability URL.
78
+
79
+ ## Async usage
80
+
81
+ ```python
82
+ from anthropic import AsyncAnthropic
83
+ from e2b_claude_toolsets import AsyncE2BBrowserToolset, allow_hosts
84
+
85
+ async def browse():
86
+ async with await AsyncE2BBrowserToolset.create(
87
+ allow_out=["example.com"], url_policy=allow_hosts(["example.com"]),
88
+ ) as browser, AsyncAnthropic() as client:
89
+ return await client.beta.messages.tool_runner(
90
+ model="claude-sonnet-5-5", max_tokens=1024, tools=[browser],
91
+ messages=[{"role": "user", "content": "Read https://example.com"}],
92
+ ).until_done()
93
+ ```
94
+
95
+ Use `await AsyncE2BBrowserToolset.create(...)` for asynchronous initialization, `await close()` and `await detach()`. It accepts the same options as the sync browser but requires `e2b.AsyncSandbox` when borrowing. URL policies and confirmation hooks can be plain or async callables. CDP, sandbox operations and waits use native async I/O; remote drivers are not sync calls wrapped in executor threads. Only bounded reads of host upload files use a thread to avoid blocking the event loop.
96
+
97
+ `await AsyncE2BComputerToolset.create(desktop, confirm=...)` borrows an `e2b.AsyncSandbox` with a running desktop, `DISPLAY=:0` and a fixed screen size. Desktop SDK 2.6.0 supplies only sync desktop startup/screenshot helpers. The async driver uses native async E2B commands/files for X11 input and screenshots. `examples/5-async-run.py --computer` boots the desktop with the sync helper before starting the event loop, then connects with `AsyncSandbox`; startup and final sandbox deletion stay outside that loop. It does not present a sync helper as an async API. `live_view` also remains a sync Desktop SDK helper; manage it outside the event loop if combining it with async actions.
98
+
99
+ Calls on one toolset are serialized by Anthropic SDK to preserve browser/desktop state; independent toolsets can overlap I/O in one event loop. Cancellation exits waits promptly and finishes key/button release before returning. An in-flight desktop input command is awaited up to its command timeout before release; local cancellation cannot establish that remote work stopped. Accepted actions are drained by `close()`, and cleanup completes even if the caller is cancelled again. Never automatically retry a state-changing operation after an uncertain outcome.
100
+
101
+ ## Optional browser actions
102
+
103
+ ```python
104
+ from anthropic.tools.browser import BetaLocalFilePolicy
105
+ from e2b_claude_toolsets import E2BBrowserToolset, UploadFile
106
+
107
+ with E2BBrowserToolset.create(
108
+ configs={name: {"enabled": True} for name in (
109
+ "file_upload", "javascript_exec", "read_console", "read_network",
110
+ )},
111
+ confirm=lambda context: True, # explicitly approves unattended execution in this demo
112
+ file_policy=BetaLocalFilePolicy(upload_document_ids=["report"]),
113
+ upload_documents={"report": UploadFile("report.txt", b"Hello")},
114
+ ) as browser:
115
+ pass # Hand browser to the runner; document_ids=["report"] uploads this file.
116
+ ```
117
+
118
+ The same configuration works on `AsyncE2BBrowserToolset.create`. The SDK validates file policy and asks for confirmation before upload or JavaScript execution. An application should provide its intended approval behavior. Host-path uploads require an explicitly allowed absolute path under `BetaLocalFilePolicy(upload_roots=[...])`; document IDs refer only to caller-provided `UploadFile` objects. Approved host files are opened without following the final symlink and their identity is checked again while reading. Files are bounded to 20 items/10 MiB per call and 50 MiB/100 staging directories per toolset. Staging stays until close after file selection because the page may read the bytes later; cleanup failure remains retryable. A timed-out or cancelled selection may have succeeded and is never repeated automatically.
119
+
120
+ `javascript_exec` evaluates in the page's main world and awaits promises; text is capped at 50,000 characters. Console and network readers consume the latest 100 records per tab since their last read. They may omit older/flooded diagnostics; network records include available status, duration and failure information, not response bodies. Page script execution has the page's authority and is not a trusted host-code executor. Upload path checks currently use POSIX file-open protections.
121
+
122
+ ## Detach before pause or fork
123
+
124
+ `detach()` / `await detach()` drains accepted calls, releases input, resolves queued interception commands, disables interception/auto-attach and closes CDP. It preserves the sandbox, Chrome, tabs, cookies and page state. Chrome/profile/download-directory ownership transfers to the caller; `close()` on the detached toolset is a no-op. A new toolset can attach to that Chrome. Give the model fresh browser state and references after attachment; old toolset refs/tab IDs are not a cross-instance identity contract.
125
+
126
+ Detach requires a borrowed sandbox, no active downloads and no staged uploads. Failed detach keeps cleanup handles so it can be retried or closed. Use `close()` when staged files are present. While detached, the toolset no longer applies URL policy; sandbox egress remains active. Pause/fork needs an E2B template with envd 0.5.0 or newer. Detach before taking a snapshot to avoid carrying paused Fetch requests into the resumed browser. Snapshot support is a template prerequisite, not a toolset guarantee.
127
+
128
+ ## Member coverage
129
+
130
+ | Driver | Implemented |
131
+ | --- | --- |
132
+ | Browser: navigation/capture | `navigate` (URL, back, forward, reload), `screenshot`, `zoom` |
133
+ | Browser: mouse | `left_click`, `right_click`, `middle_click`, `double_click`, `triple_click`, `hover`, `left_click_drag`, `left_mouse_down`, `left_mouse_up`, `mouse_move`, `scroll`, `scroll_to` |
134
+ | Browser: input/reading | `type`, `key`, `hold_key`, `form_input`, `read_page`, `find`, `get_page_text`, `wait` |
135
+ | Browser: optional | `file_upload`, `javascript_exec`, `read_console`, `read_network` (explicit opt-in) |
136
+ | Browser: tabs | `new_tab`, `list_tabs`, `switch_tab`, `close_tab` |
137
+ | Computer | `screenshot`, `cursor_position`, `mouse_move`, `left_click`, `right_click`, `middle_click`, `double_click`, `triple_click`, `left_mouse_down`, `left_mouse_up`, `left_click_drag`, `scroll`, `key`, `hold_key`, `type`, `wait` |
138
+
139
+ ## Boundaries and limits
140
+
141
+ - Browser viewport and computer screen: at least 200 a side and at most 2560×1440 pixels in total (larger screenshots are shrunk by the API and clicks miss), default 1280×800. Keep the desktop resolution fixed. Images are not resized. Coordinates are screenshot pixels; browser zoom returns a cropped/scaled region within the viewport size.
142
+ - Wait/hold operations are limited to 30 seconds. Computer and browser key repeats are limited to 100. Computer scroll accepts integers from 1 through 50 and refuses larger values before input; values are never silently rounded or capped. Browser scroll uses 1–10 wheel ticks. Input assumes a US keyboard layout.
143
+ - Browser DOM operations use the shared generated runtime from `packages/claude-toolsets-runtime/`, installed idempotently in an isolated world with JSON-encoded arguments. References are unique across documents/tabs and stale refs are refused. Cross-origin iframe contents and transformed iframe coordinates remain limitations. Dedicated workers are resumed and detached because their CDP targets do not support Fetch interception; URL-policy coverage of worker-originated requests is not guaranteed. Page text/images/titles are untrusted model input.
144
+ - Private CDP access, a fresh profile and scrubbed Chrome environment apply when the driver starts Chrome. Renderer sandboxing stays enabled. Egress is fixed at sandbox creation: a URL policy does not configure network egress.
145
+ - `allow_hosts` permits HTTP(S) hosts/subdomains and optional ports. Documents, redirects and selected local requests are intercepted; reserved local control ports are refused. This sample policy is not a DNS firewall. DNS aliases/rebinding and browser-internal/history edge cases need security review before sensitive browsing. Use restrictive sandbox egress too.
146
+ - Command replies and registered events have bounded storage. Interception decisions pipeline up to 96 pending commands, reserving capacity for actions and target setup; replies and 30-second timeouts are still checked. Errors for already canceled requests or vanished dialogs/targets are tolerated; unexpected errors or overflow of essential events close the connection and trigger the owned-Chrome stop attempt described above. Keep URL-policy callbacks fast. The latest 256 browser-state notifications and 100 download records are retained; older notifications/tracking records may be omitted under floods, but interception decisions are never dropped. Input sends use acknowledged round trips in both drivers. Optional console/network events have a 32-event queue budget so diagnostic floods leave room for URL protection; they may be dropped under pressure; these readers are bounded diagnostics, not complete audit logs.
147
+ - Downloads stay in the sandbox; the SDK controls whether their paths are disclosed. No download bytes are automatically added to the conversation or executed.
148
+ - If a borrowed Chrome disconnects with input held, release cannot be confirmed. Cleanup still releases independent local resources and reports that uncertainty instead of killing a caller-owned process or claiming success; release input manually or retry while the connection is usable.
@@ -0,0 +1,135 @@
1
+ # E2B Claude Toolsets for Python
2
+
3
+ Synchronous and native asyncio browser and computer drivers for Anthropic toolsets, on the standard E2B desktop. Both browser drivers implement all 31 browser actions; the four optional actions stay disabled by default. Both computer drivers implement 16 actions; computer zoom is unavailable.
4
+
5
+ ## Development
6
+
7
+ Developing from Git requires Python 3.10+, uv, pnpm and Bun 1.3.14; see the [repo README](https://github.com/e2b-dev/claude-toolsets#development).
8
+
9
+ ```sh
10
+ pnpm install # repo root: JS dependencies and the browser runtime
11
+ cd packages/claude-toolsets-python
12
+ uv sync --python 3.10
13
+ uv run python -m unittest discover -s tests -v
14
+ uv run ruff check
15
+ uv run ruff format --check
16
+ uv run ty check
17
+ uv build
18
+ ```
19
+
20
+ The Python build hook generates runtime assets from a Git checkout and includes them in both the wheel and sdist. Installing either built archive does not require Bun or Node.
21
+
22
+ The tests use the Anthropic SDK, local protocol fixtures and mocked E2B calls. They never create sandboxes or call a model. The protocol fixture does not execute DOM scripts. Run `pnpm setup:browsers` and `pnpm test:runtime` to execute both bridges against real local Chromium fixtures. Live E2B/model validation remains a separate step.
23
+
24
+ ## Examples
25
+
26
+ These commands create billable resources. They are manual examples, not offline tests. Set `E2B_API_KEY`; model examples also require `ANTHROPIC_API_KEY`. Set `ANTHROPIC_MODEL` to a model available to your account (the reference default is `claude-sonnet-5-5`). CLI login alone does not supply SDK credentials.
27
+
28
+ Run them from the repo root with this package's environment; the live tests run from this folder.
29
+
30
+ ```sh
31
+ uv run --project packages/claude-toolsets-python python examples/1-run.py "Read the latest E2B release"
32
+ uv run --project packages/claude-toolsets-python python examples/4-computer.py "Open a text editor and write a short note"
33
+ uv run --project packages/claude-toolsets-python python examples/2-exercise.py
34
+ uv run --project packages/claude-toolsets-python python examples/5-async-run.py
35
+ uv run --project packages/claude-toolsets-python python examples/5-async-run.py --computer
36
+ uv run --project packages/claude-toolsets-python python examples/6-async-exercise.py
37
+ cd packages/claude-toolsets-python
38
+ uv run python tests/live/detach.py # requires a snapshot-capable template; optional TEMPLATE override
39
+ uv run python tests/live/lifecycle.py # injected cleanup/interception failures; no model
40
+ uv run python tests/live/computer.py # all computer actions and input refusals; no model
41
+ ```
42
+
43
+ The exercise creates one desktop and a local HTML fixture, calls all 31 browser and 16 computer members through SDK dispatch, and cleans up the desktop. It uses no model API. An acknowledgment proves dispatch completed; only its explicit assertions check page behavior. The async exercise checks the form/upload/diagnostic workflow, native desktop text and screenshots, cancellation recovery and detach/reattach. It is a focused behavior check; the sync exercise dispatches every implemented action. The examples use a 600-second sandbox lifetime and explicit cleanup. Use a fresh, exclusive desktop for live view.
44
+
45
+ ## API and ownership
46
+
47
+ ```python
48
+ from e2b_claude_toolsets import E2BBrowserToolset, E2BComputerToolset, allow_hosts, live_view
49
+
50
+ with E2BBrowserToolset.create(allow_out=["example.com"], url_policy=allow_hosts(["example.com"])) as browser:
51
+ # Pass browser directly in Anthropic().beta.messages.tool_runner(tools=[browser], ...).
52
+ # The toolset owns this sandbox. Exiting closes Chrome and kills the sandbox.
53
+ sandbox = browser.sandbox
54
+ ```
55
+
56
+ `E2BBrowserToolset.create(sandbox=desktop, ...)` borrows the sandbox. On an `e2b_desktop` sandbox Chrome opens visibly on its screen, so it shows in the live view; pass `headless=True` to hide it, or `display=":1"` for another screen. An `AsyncSandbox` from `AsyncSandbox.connect()` carries no screen information, so pass `display=":0"` there to show Chrome on the desktop. It stops only Chrome it started, removes its own temporary directory, and closes its CDP connection. A pre-existing Chrome process stays running. Attach to one Chrome session exclusively; its caller remains responsible for the profile, egress and sandbox lifetime. When creating a sandbox, options include `api_key`, `template` (default `desktop`), `timeout` in seconds, `allow_out`, and `metadata`. Attached sandboxes must already have `allow_public_traffic=False` and `mask_request_host="localhost:${PORT}"`; creation-only options are refused when attaching.
57
+
58
+ `E2BComputerToolset.create(desktop, confirm=...)` borrows the desktop. It uses native screenshots/text and validated xdotool input. The SDK requires confirmation while `type`, `key` or `hold_key` is enabled. The computer example explicitly approves unattended input; an application should provide its intended approval behavior.
59
+
60
+ Sync and async toolsets preserve SDK `configs`, `confirm` and `tool_configs`; browser additionally accepts `url_policy` and `file_policy`. Omitted URL policy and explicit `None` have different SDK semantics. Unimplemented members are disabled by the SDK. The SDK owns input parsing, confirmation, action serialization and tool-result rendering. A toolset can serve multiple runner invocations; runners never close it. Use context managers or `finally: toolset.close()`.
61
+
62
+ `close()` marks a toolset closed, waits for accepted calls, then releases resources. Failed release keeps its resource record for retry. Startup failures clean up partial resources; `BrowserInitializationError.close()` and `ViewerInitializationError.view.stop()` allow retry after failed startup cleanup. Lost connections or expired sandboxes produce errors; sessions are never silently replaced and state-changing actions are never automatically replayed. A command timeout leaves the remote outcome uncertain. Sync interruption does not prove an already submitted remote operation stopped. On unexpected CDP loss, a separate cleanup thread attempts to stop Chrome started by this toolset through E2B's command API; the sandbox stays available until `close()`. A failed stop is reported and can be retried. Caller-owned Chrome stays running and its URL policy is no longer enforced after disconnection.
63
+
64
+ `live_view(desktop)` returns a context manager with `.url` and `.stop()`. It binds to loopback, uses a random capability path, validates host/origin, and proxies HTTP and WebSocket traffic with the traffic token kept in Python. Bodies and queues are bounded. Stopping closes local connections and the VNC stream it started; it never kills the desktop. Existing VNC streams are refused because Desktop SDK stream teardown is sandbox-wide. If stream teardown fails, retry `stop()`. Do not share the capability URL.
65
+
66
+ ## Async usage
67
+
68
+ ```python
69
+ from anthropic import AsyncAnthropic
70
+ from e2b_claude_toolsets import AsyncE2BBrowserToolset, allow_hosts
71
+
72
+ async def browse():
73
+ async with await AsyncE2BBrowserToolset.create(
74
+ allow_out=["example.com"], url_policy=allow_hosts(["example.com"]),
75
+ ) as browser, AsyncAnthropic() as client:
76
+ return await client.beta.messages.tool_runner(
77
+ model="claude-sonnet-5-5", max_tokens=1024, tools=[browser],
78
+ messages=[{"role": "user", "content": "Read https://example.com"}],
79
+ ).until_done()
80
+ ```
81
+
82
+ Use `await AsyncE2BBrowserToolset.create(...)` for asynchronous initialization, `await close()` and `await detach()`. It accepts the same options as the sync browser but requires `e2b.AsyncSandbox` when borrowing. URL policies and confirmation hooks can be plain or async callables. CDP, sandbox operations and waits use native async I/O; remote drivers are not sync calls wrapped in executor threads. Only bounded reads of host upload files use a thread to avoid blocking the event loop.
83
+
84
+ `await AsyncE2BComputerToolset.create(desktop, confirm=...)` borrows an `e2b.AsyncSandbox` with a running desktop, `DISPLAY=:0` and a fixed screen size. Desktop SDK 2.6.0 supplies only sync desktop startup/screenshot helpers. The async driver uses native async E2B commands/files for X11 input and screenshots. `examples/5-async-run.py --computer` boots the desktop with the sync helper before starting the event loop, then connects with `AsyncSandbox`; startup and final sandbox deletion stay outside that loop. It does not present a sync helper as an async API. `live_view` also remains a sync Desktop SDK helper; manage it outside the event loop if combining it with async actions.
85
+
86
+ Calls on one toolset are serialized by Anthropic SDK to preserve browser/desktop state; independent toolsets can overlap I/O in one event loop. Cancellation exits waits promptly and finishes key/button release before returning. An in-flight desktop input command is awaited up to its command timeout before release; local cancellation cannot establish that remote work stopped. Accepted actions are drained by `close()`, and cleanup completes even if the caller is cancelled again. Never automatically retry a state-changing operation after an uncertain outcome.
87
+
88
+ ## Optional browser actions
89
+
90
+ ```python
91
+ from anthropic.tools.browser import BetaLocalFilePolicy
92
+ from e2b_claude_toolsets import E2BBrowserToolset, UploadFile
93
+
94
+ with E2BBrowserToolset.create(
95
+ configs={name: {"enabled": True} for name in (
96
+ "file_upload", "javascript_exec", "read_console", "read_network",
97
+ )},
98
+ confirm=lambda context: True, # explicitly approves unattended execution in this demo
99
+ file_policy=BetaLocalFilePolicy(upload_document_ids=["report"]),
100
+ upload_documents={"report": UploadFile("report.txt", b"Hello")},
101
+ ) as browser:
102
+ pass # Hand browser to the runner; document_ids=["report"] uploads this file.
103
+ ```
104
+
105
+ The same configuration works on `AsyncE2BBrowserToolset.create`. The SDK validates file policy and asks for confirmation before upload or JavaScript execution. An application should provide its intended approval behavior. Host-path uploads require an explicitly allowed absolute path under `BetaLocalFilePolicy(upload_roots=[...])`; document IDs refer only to caller-provided `UploadFile` objects. Approved host files are opened without following the final symlink and their identity is checked again while reading. Files are bounded to 20 items/10 MiB per call and 50 MiB/100 staging directories per toolset. Staging stays until close after file selection because the page may read the bytes later; cleanup failure remains retryable. A timed-out or cancelled selection may have succeeded and is never repeated automatically.
106
+
107
+ `javascript_exec` evaluates in the page's main world and awaits promises; text is capped at 50,000 characters. Console and network readers consume the latest 100 records per tab since their last read. They may omit older/flooded diagnostics; network records include available status, duration and failure information, not response bodies. Page script execution has the page's authority and is not a trusted host-code executor. Upload path checks currently use POSIX file-open protections.
108
+
109
+ ## Detach before pause or fork
110
+
111
+ `detach()` / `await detach()` drains accepted calls, releases input, resolves queued interception commands, disables interception/auto-attach and closes CDP. It preserves the sandbox, Chrome, tabs, cookies and page state. Chrome/profile/download-directory ownership transfers to the caller; `close()` on the detached toolset is a no-op. A new toolset can attach to that Chrome. Give the model fresh browser state and references after attachment; old toolset refs/tab IDs are not a cross-instance identity contract.
112
+
113
+ Detach requires a borrowed sandbox, no active downloads and no staged uploads. Failed detach keeps cleanup handles so it can be retried or closed. Use `close()` when staged files are present. While detached, the toolset no longer applies URL policy; sandbox egress remains active. Pause/fork needs an E2B template with envd 0.5.0 or newer. Detach before taking a snapshot to avoid carrying paused Fetch requests into the resumed browser. Snapshot support is a template prerequisite, not a toolset guarantee.
114
+
115
+ ## Member coverage
116
+
117
+ | Driver | Implemented |
118
+ | --- | --- |
119
+ | Browser: navigation/capture | `navigate` (URL, back, forward, reload), `screenshot`, `zoom` |
120
+ | Browser: mouse | `left_click`, `right_click`, `middle_click`, `double_click`, `triple_click`, `hover`, `left_click_drag`, `left_mouse_down`, `left_mouse_up`, `mouse_move`, `scroll`, `scroll_to` |
121
+ | Browser: input/reading | `type`, `key`, `hold_key`, `form_input`, `read_page`, `find`, `get_page_text`, `wait` |
122
+ | Browser: optional | `file_upload`, `javascript_exec`, `read_console`, `read_network` (explicit opt-in) |
123
+ | Browser: tabs | `new_tab`, `list_tabs`, `switch_tab`, `close_tab` |
124
+ | Computer | `screenshot`, `cursor_position`, `mouse_move`, `left_click`, `right_click`, `middle_click`, `double_click`, `triple_click`, `left_mouse_down`, `left_mouse_up`, `left_click_drag`, `scroll`, `key`, `hold_key`, `type`, `wait` |
125
+
126
+ ## Boundaries and limits
127
+
128
+ - Browser viewport and computer screen: at least 200 a side and at most 2560×1440 pixels in total (larger screenshots are shrunk by the API and clicks miss), default 1280×800. Keep the desktop resolution fixed. Images are not resized. Coordinates are screenshot pixels; browser zoom returns a cropped/scaled region within the viewport size.
129
+ - Wait/hold operations are limited to 30 seconds. Computer and browser key repeats are limited to 100. Computer scroll accepts integers from 1 through 50 and refuses larger values before input; values are never silently rounded or capped. Browser scroll uses 1–10 wheel ticks. Input assumes a US keyboard layout.
130
+ - Browser DOM operations use the shared generated runtime from `packages/claude-toolsets-runtime/`, installed idempotently in an isolated world with JSON-encoded arguments. References are unique across documents/tabs and stale refs are refused. Cross-origin iframe contents and transformed iframe coordinates remain limitations. Dedicated workers are resumed and detached because their CDP targets do not support Fetch interception; URL-policy coverage of worker-originated requests is not guaranteed. Page text/images/titles are untrusted model input.
131
+ - Private CDP access, a fresh profile and scrubbed Chrome environment apply when the driver starts Chrome. Renderer sandboxing stays enabled. Egress is fixed at sandbox creation: a URL policy does not configure network egress.
132
+ - `allow_hosts` permits HTTP(S) hosts/subdomains and optional ports. Documents, redirects and selected local requests are intercepted; reserved local control ports are refused. This sample policy is not a DNS firewall. DNS aliases/rebinding and browser-internal/history edge cases need security review before sensitive browsing. Use restrictive sandbox egress too.
133
+ - Command replies and registered events have bounded storage. Interception decisions pipeline up to 96 pending commands, reserving capacity for actions and target setup; replies and 30-second timeouts are still checked. Errors for already canceled requests or vanished dialogs/targets are tolerated; unexpected errors or overflow of essential events close the connection and trigger the owned-Chrome stop attempt described above. Keep URL-policy callbacks fast. The latest 256 browser-state notifications and 100 download records are retained; older notifications/tracking records may be omitted under floods, but interception decisions are never dropped. Input sends use acknowledged round trips in both drivers. Optional console/network events have a 32-event queue budget so diagnostic floods leave room for URL protection; they may be dropped under pressure; these readers are bounded diagnostics, not complete audit logs.
134
+ - Downloads stay in the sandbox; the SDK controls whether their paths are disclosed. No download bytes are automatically added to the conversation or executed.
135
+ - If a borrowed Chrome disconnects with input held, release cannot be confirmed. Cleanup still releases independent local resources and reports that uncertainty instead of killing a caller-owned process or claiming success; release input manually or retry while the connection is usable.
@@ -0,0 +1,23 @@
1
+ """Sync and native asyncio E2B drivers for Anthropic browser and computer toolsets."""
2
+
3
+ from ._async_browser import AsyncBrowserInitializationError, AsyncE2BBrowserToolset
4
+ from ._async_computer import AsyncE2BComputerToolset
5
+ from ._browser import BrowserInitializationError, E2BBrowserToolset
6
+ from ._computer import E2BComputerToolset
7
+ from ._policy import allow_hosts
8
+ from ._uploads import UploadFile
9
+ from ._viewer import LiveView, ViewerInitializationError, live_view
10
+
11
+ __all__ = [
12
+ "E2BBrowserToolset",
13
+ "E2BComputerToolset",
14
+ "AsyncE2BBrowserToolset",
15
+ "AsyncE2BComputerToolset",
16
+ "AsyncBrowserInitializationError",
17
+ "BrowserInitializationError",
18
+ "LiveView",
19
+ "ViewerInitializationError",
20
+ "allow_hosts",
21
+ "live_view",
22
+ "UploadFile",
23
+ ]
@@ -0,0 +1,26 @@
1
+ """Finish bounded resource cleanup even if its caller is cancelled again."""
2
+
3
+ import asyncio
4
+ from collections.abc import Awaitable
5
+ from typing import TypeVar
6
+
7
+ T = TypeVar("T")
8
+
9
+
10
+ async def finish_cleanup(operation: Awaitable[T]) -> T:
11
+ task = asyncio.ensure_future(operation)
12
+ cancelled = None
13
+ while True:
14
+ try:
15
+ result = await asyncio.shield(task)
16
+ break
17
+ except asyncio.CancelledError as error:
18
+ if task.cancelled():
19
+ raise
20
+ cancelled = error
21
+ if task.done():
22
+ result = task.result()
23
+ break
24
+ if cancelled is not None:
25
+ raise cancelled
26
+ return result