specstream-claude-browser 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- specstream_claude_browser-0.1.0/.gitignore +69 -0
- specstream_claude_browser-0.1.0/CHANGELOG.md +5 -0
- specstream_claude_browser-0.1.0/LICENSE +24 -0
- specstream_claude_browser-0.1.0/PKG-INFO +129 -0
- specstream_claude_browser-0.1.0/README.md +100 -0
- specstream_claude_browser-0.1.0/examples/heading.py +21 -0
- specstream_claude_browser-0.1.0/pyproject.toml +55 -0
- specstream_claude_browser-0.1.0/specstream_claude_browser/__init__.py +7 -0
- specstream_claude_browser-0.1.0/specstream_claude_browser/_client.py +140 -0
- specstream_claude_browser-0.1.0/specstream_claude_browser/_driver.py +421 -0
- specstream_claude_browser-0.1.0/specstream_claude_browser/py.typed +0 -0
- specstream_claude_browser-0.1.0/tests/test_specstream_claude_browser.py +250 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
.venv/
|
|
3
|
+
__pycache__/
|
|
4
|
+
*.py[cod]
|
|
5
|
+
.pytest_cache/
|
|
6
|
+
.mypy_cache/
|
|
7
|
+
.ruff_cache/
|
|
8
|
+
.coverage
|
|
9
|
+
coverage/
|
|
10
|
+
|
|
11
|
+
# Node/frontend
|
|
12
|
+
node_modules/
|
|
13
|
+
build/
|
|
14
|
+
dist/
|
|
15
|
+
playwright-report/
|
|
16
|
+
test-results/
|
|
17
|
+
.react-router/
|
|
18
|
+
|
|
19
|
+
# Runtime/output
|
|
20
|
+
site-*/
|
|
21
|
+
*.log
|
|
22
|
+
*.dump
|
|
23
|
+
/exports/*
|
|
24
|
+
/growth/email/out/
|
|
25
|
+
screenshots/
|
|
26
|
+
|
|
27
|
+
# Secrets
|
|
28
|
+
.env
|
|
29
|
+
.env.*
|
|
30
|
+
!.env.example
|
|
31
|
+
*.pem
|
|
32
|
+
*.key
|
|
33
|
+
|
|
34
|
+
# Editors/OS
|
|
35
|
+
.DS_Store
|
|
36
|
+
.idea/
|
|
37
|
+
.vscode/
|
|
38
|
+
|
|
39
|
+
# Isolated engine verification state
|
|
40
|
+
.engine-local/
|
|
41
|
+
|
|
42
|
+
# Isolated product-hardening verification state
|
|
43
|
+
.hardening-local/
|
|
44
|
+
|
|
45
|
+
# Isolated product-maturation verification state (short Unix socket paths)
|
|
46
|
+
/.maturation-local/
|
|
47
|
+
/.t/
|
|
48
|
+
|
|
49
|
+
.runtime/
|
|
50
|
+
/design/brand/street-world/specstream-street-world.zip
|
|
51
|
+
|
|
52
|
+
/artifacts/launch-validation/
|
|
53
|
+
|
|
54
|
+
/artifacts/launch-package/
|
|
55
|
+
|
|
56
|
+
# Website build output read by the pages (page dates from git)
|
|
57
|
+
apps/website/src/data/lastmod.generated.json
|
|
58
|
+
plugins/openai/ui/harness/harness.js
|
|
59
|
+
apps/workspace/dist-chatgpt/
|
|
60
|
+
marketing/native/*/
|
|
61
|
+
marketing/native/START-HERE.html
|
|
62
|
+
|
|
63
|
+
# the crew board and its runs (ops/crew.py): a database and job scripts, not source
|
|
64
|
+
/var/crew/
|
|
65
|
+
|
|
66
|
+
# Work trees of parallel helpers: full copies of the repo. Searches and git must not walk them
|
|
67
|
+
# (Nov 12: 50 copies inside the repo kept the /home disk at 100% busy).
|
|
68
|
+
.claude/worktrees/
|
|
69
|
+
listings/highlevel/video/*.mp4
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
BSD 2-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, SpecStream SAS
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
16
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
17
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
18
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
19
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
20
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
21
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
22
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
23
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
24
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: specstream-claude-browser
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A driver for the browser toolset of the Claude SDK that runs on SpecStream browser sessions.
|
|
5
|
+
Project-URL: Homepage, https://specstream.ai
|
|
6
|
+
Project-URL: Documentation, https://specstream.ai/docs/api
|
|
7
|
+
Project-URL: Repository, https://github.com/specstream/specstream-tools/tree/main/packages/specstream-claude-browser
|
|
8
|
+
Project-URL: Issues, https://github.com/specstream/specstream-tools/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/specstream/specstream-tools/blob/main/packages/specstream-claude-browser/CHANGELOG.md
|
|
10
|
+
Project-URL: Pricing, https://specstream.ai/pricing
|
|
11
|
+
Author-email: SpecStream <support@specstream.ai>
|
|
12
|
+
License-Expression: BSD-2-Clause
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Keywords: agents,anthropic,browser-sessions,browser-toolset,browser-use,claude,specstream
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Browsers
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Requires-Dist: anthropic<3,>=2.8
|
|
25
|
+
Requires-Dist: httpx2<3,>=2
|
|
26
|
+
Provides-Extra: test
|
|
27
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# specstream-claude-browser
|
|
31
|
+
|
|
32
|
+
A driver for the [browser toolset of the Claude SDK](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk) that runs on [SpecStream](https://specstream.ai) browser sessions. Claude navigates, reads and acts in a real browser that SpecStream hosts. You run no browser yourself.
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install specstream-claude-browser
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Quick start
|
|
39
|
+
|
|
40
|
+
A free account comes with $2 of credit and needs no card: [specstream.ai](https://specstream.ai/signup).
|
|
41
|
+
|
|
42
|
+
Set `ANTHROPIC_API_KEY`, `SPECSTREAM_API_KEY`, and `CLAUDE_MODEL` to a model the browser toolset supports (the Claude page above lists them). Create a SpecStream key under Agents & API at https://specstream.ai/workspace.
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import os
|
|
46
|
+
|
|
47
|
+
from anthropic import Anthropic
|
|
48
|
+
from specstream_claude_browser import SpecStreamBrowser
|
|
49
|
+
|
|
50
|
+
client = Anthropic()
|
|
51
|
+
with SpecStreamBrowser() as browser:
|
|
52
|
+
runner = client.beta.messages.tool_runner(
|
|
53
|
+
model=os.environ["CLAUDE_MODEL"], # a model the browser toolset supports
|
|
54
|
+
max_tokens=1024,
|
|
55
|
+
tools=[browser],
|
|
56
|
+
messages=[{"role": "user", "content": "Open example.com and tell me its heading."}],
|
|
57
|
+
)
|
|
58
|
+
for message in runner:
|
|
59
|
+
print(message)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The session opens at the first call and ends when the `with` block ends. A toolset that Claude never calls opens no session.
|
|
63
|
+
|
|
64
|
+
## What it costs
|
|
65
|
+
|
|
66
|
+
A session costs $0.10 an hour, charged by the second, plus $1 per 1,000 steps. One member call is one step, with three exceptions: `key` is one step for each key press, `form_input` on a text field or a select is two steps, and a refused call is none.
|
|
67
|
+
|
|
68
|
+
## Members
|
|
69
|
+
|
|
70
|
+
| Member | How it runs |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `navigate` | Opens the URL. `back`, `forward` and `reload` work. The HTTP status is not reported. |
|
|
73
|
+
| `screenshot` | A PNG of the viewport. One image pixel is one CSS pixel. |
|
|
74
|
+
| `read_page` | The page's accessibility snapshot. Each element carries a ref, such as `[ref=e12]`. |
|
|
75
|
+
| `get_page_text` | The page's text. |
|
|
76
|
+
| `find` | The snapshot lines that contain the words of the query. It matches text, not a description. |
|
|
77
|
+
| `left_click`, `double_click`, `right_click`, `middle_click`, `hover` | By ref, with the pointer. `left_click` also takes a coordinate, and then clicks the element at that point by script. |
|
|
78
|
+
| `scroll`, `scroll_to` | `scroll` moves the scrollable box under the point. `scroll_to` brings a ref into view. |
|
|
79
|
+
| `type` | Inserts text into the field that has the focus. |
|
|
80
|
+
| `key` | Keys and chords as Claude writes them (`ctrl+a`, `Return`). |
|
|
81
|
+
| `form_input` | Fills a text field, chooses an option of a select, or sets a checkbox, by ref. |
|
|
82
|
+
| `wait` | Waits up to 60 seconds. |
|
|
83
|
+
| `read_console`, `read_network` | The page's console messages and network requests. |
|
|
84
|
+
| `javascript_exec` | Runs a script in the page. Served only when you pass `confirm`. |
|
|
85
|
+
|
|
86
|
+
Not served, and sent to the API as disabled: `zoom`, `left_click_drag`, `left_mouse_down`, `left_mouse_up`, `mouse_move`, `hold_key`, `file_upload`, `new_tab`, `switch_tab`, `list_tabs` and `close_tab`. The driver follows one page and reports it as one tab.
|
|
87
|
+
|
|
88
|
+
## Options
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
SpecStreamBrowser(
|
|
92
|
+
api_key=None, # default: the SPECSTREAM_API_KEY environment variable
|
|
93
|
+
session_id=None, # drive a session that is already open, and leave it open at close()
|
|
94
|
+
timeout_s=900, # the longest the session lasts, 60 to 3600 seconds
|
|
95
|
+
idle_timeout_s=300, # the session ends after this long without a step, 10 to 600 seconds
|
|
96
|
+
allowed_domains=None, # hosts the session may open, such as ["example.com", "*.example.com"]
|
|
97
|
+
block_media=False, # do not load images, video and fonts
|
|
98
|
+
url_policy=..., # the toolset's own options are passed through:
|
|
99
|
+
confirm=..., # url_policy, confirm, configs, file_policy, tool_configs
|
|
100
|
+
)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`browser.session_id` is the session's id once it is open. `browser.live_url` is a page that shows the browser's screen as it changes.
|
|
104
|
+
|
|
105
|
+
## Run it safely
|
|
106
|
+
|
|
107
|
+
Claude's next action depends on the pages it reads, and a page can try to steer it. Before you run the driver on anything that matters, read [Run the toolset safely](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#run-the-toolset-safely) and do these two things:
|
|
108
|
+
|
|
109
|
+
- Pass `allowed_domains`. The session itself then refuses every other host, also for links a page opens. A `url_policy` checks only the URLs Claude navigates to.
|
|
110
|
+
- Pass `confirm` for calls that have an effect, and leave `javascript_exec` off unless the task needs it.
|
|
111
|
+
|
|
112
|
+
SpecStream sessions never open private addresses, and they do not open sites that opted out.
|
|
113
|
+
|
|
114
|
+
## Errors
|
|
115
|
+
|
|
116
|
+
A step that fails reaches Claude as an error result with SpecStream's own message, and the run continues. That includes a key that SpecStream refuses. A missing key raises `SpecStreamError` when you create the toolset. `close()` does not raise: if the release call fails, the session ends at its idle wait.
|
|
117
|
+
|
|
118
|
+
## Tests
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
pip install -e ".[test]"
|
|
122
|
+
pytest -q
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
The tests script the SpecStream API. They need no key and no network.
|
|
126
|
+
|
|
127
|
+
## License
|
|
128
|
+
|
|
129
|
+
BSD-2-Clause.
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# specstream-claude-browser
|
|
2
|
+
|
|
3
|
+
A driver for the [browser toolset of the Claude SDK](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk) that runs on [SpecStream](https://specstream.ai) browser sessions. Claude navigates, reads and acts in a real browser that SpecStream hosts. You run no browser yourself.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install specstream-claude-browser
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Quick start
|
|
10
|
+
|
|
11
|
+
A free account comes with $2 of credit and needs no card: [specstream.ai](https://specstream.ai/signup).
|
|
12
|
+
|
|
13
|
+
Set `ANTHROPIC_API_KEY`, `SPECSTREAM_API_KEY`, and `CLAUDE_MODEL` to a model the browser toolset supports (the Claude page above lists them). Create a SpecStream key under Agents & API at https://specstream.ai/workspace.
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import os
|
|
17
|
+
|
|
18
|
+
from anthropic import Anthropic
|
|
19
|
+
from specstream_claude_browser import SpecStreamBrowser
|
|
20
|
+
|
|
21
|
+
client = Anthropic()
|
|
22
|
+
with SpecStreamBrowser() as browser:
|
|
23
|
+
runner = client.beta.messages.tool_runner(
|
|
24
|
+
model=os.environ["CLAUDE_MODEL"], # a model the browser toolset supports
|
|
25
|
+
max_tokens=1024,
|
|
26
|
+
tools=[browser],
|
|
27
|
+
messages=[{"role": "user", "content": "Open example.com and tell me its heading."}],
|
|
28
|
+
)
|
|
29
|
+
for message in runner:
|
|
30
|
+
print(message)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The session opens at the first call and ends when the `with` block ends. A toolset that Claude never calls opens no session.
|
|
34
|
+
|
|
35
|
+
## What it costs
|
|
36
|
+
|
|
37
|
+
A session costs $0.10 an hour, charged by the second, plus $1 per 1,000 steps. One member call is one step, with three exceptions: `key` is one step for each key press, `form_input` on a text field or a select is two steps, and a refused call is none.
|
|
38
|
+
|
|
39
|
+
## Members
|
|
40
|
+
|
|
41
|
+
| Member | How it runs |
|
|
42
|
+
| --- | --- |
|
|
43
|
+
| `navigate` | Opens the URL. `back`, `forward` and `reload` work. The HTTP status is not reported. |
|
|
44
|
+
| `screenshot` | A PNG of the viewport. One image pixel is one CSS pixel. |
|
|
45
|
+
| `read_page` | The page's accessibility snapshot. Each element carries a ref, such as `[ref=e12]`. |
|
|
46
|
+
| `get_page_text` | The page's text. |
|
|
47
|
+
| `find` | The snapshot lines that contain the words of the query. It matches text, not a description. |
|
|
48
|
+
| `left_click`, `double_click`, `right_click`, `middle_click`, `hover` | By ref, with the pointer. `left_click` also takes a coordinate, and then clicks the element at that point by script. |
|
|
49
|
+
| `scroll`, `scroll_to` | `scroll` moves the scrollable box under the point. `scroll_to` brings a ref into view. |
|
|
50
|
+
| `type` | Inserts text into the field that has the focus. |
|
|
51
|
+
| `key` | Keys and chords as Claude writes them (`ctrl+a`, `Return`). |
|
|
52
|
+
| `form_input` | Fills a text field, chooses an option of a select, or sets a checkbox, by ref. |
|
|
53
|
+
| `wait` | Waits up to 60 seconds. |
|
|
54
|
+
| `read_console`, `read_network` | The page's console messages and network requests. |
|
|
55
|
+
| `javascript_exec` | Runs a script in the page. Served only when you pass `confirm`. |
|
|
56
|
+
|
|
57
|
+
Not served, and sent to the API as disabled: `zoom`, `left_click_drag`, `left_mouse_down`, `left_mouse_up`, `mouse_move`, `hold_key`, `file_upload`, `new_tab`, `switch_tab`, `list_tabs` and `close_tab`. The driver follows one page and reports it as one tab.
|
|
58
|
+
|
|
59
|
+
## Options
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
SpecStreamBrowser(
|
|
63
|
+
api_key=None, # default: the SPECSTREAM_API_KEY environment variable
|
|
64
|
+
session_id=None, # drive a session that is already open, and leave it open at close()
|
|
65
|
+
timeout_s=900, # the longest the session lasts, 60 to 3600 seconds
|
|
66
|
+
idle_timeout_s=300, # the session ends after this long without a step, 10 to 600 seconds
|
|
67
|
+
allowed_domains=None, # hosts the session may open, such as ["example.com", "*.example.com"]
|
|
68
|
+
block_media=False, # do not load images, video and fonts
|
|
69
|
+
url_policy=..., # the toolset's own options are passed through:
|
|
70
|
+
confirm=..., # url_policy, confirm, configs, file_policy, tool_configs
|
|
71
|
+
)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`browser.session_id` is the session's id once it is open. `browser.live_url` is a page that shows the browser's screen as it changes.
|
|
75
|
+
|
|
76
|
+
## Run it safely
|
|
77
|
+
|
|
78
|
+
Claude's next action depends on the pages it reads, and a page can try to steer it. Before you run the driver on anything that matters, read [Run the toolset safely](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#run-the-toolset-safely) and do these two things:
|
|
79
|
+
|
|
80
|
+
- Pass `allowed_domains`. The session itself then refuses every other host, also for links a page opens. A `url_policy` checks only the URLs Claude navigates to.
|
|
81
|
+
- Pass `confirm` for calls that have an effect, and leave `javascript_exec` off unless the task needs it.
|
|
82
|
+
|
|
83
|
+
SpecStream sessions never open private addresses, and they do not open sites that opted out.
|
|
84
|
+
|
|
85
|
+
## Errors
|
|
86
|
+
|
|
87
|
+
A step that fails reaches Claude as an error result with SpecStream's own message, and the run continues. That includes a key that SpecStream refuses. A missing key raises `SpecStreamError` when you create the toolset. `close()` does not raise: if the release call fails, the session ends at its idle wait.
|
|
88
|
+
|
|
89
|
+
## Tests
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
pip install -e ".[test]"
|
|
93
|
+
pytest -q
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The tests script the SpecStream API. They need no key and no network.
|
|
97
|
+
|
|
98
|
+
## License
|
|
99
|
+
|
|
100
|
+
BSD-2-Clause.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Ask Claude for a page's heading. Needs ANTHROPIC_API_KEY, SPECSTREAM_API_KEY and CLAUDE_MODEL.
|
|
2
|
+
|
|
3
|
+
A run opens one SpecStream browser session ($0.10 an hour by the second, plus $1 per 1,000 steps).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
from anthropic import Anthropic
|
|
9
|
+
|
|
10
|
+
from specstream_claude_browser import SpecStreamBrowser
|
|
11
|
+
|
|
12
|
+
client = Anthropic()
|
|
13
|
+
with SpecStreamBrowser(allowed_domains=["example.com"]) as browser:
|
|
14
|
+
runner = client.beta.messages.tool_runner(
|
|
15
|
+
model=os.environ["CLAUDE_MODEL"], # a model the browser toolset supports
|
|
16
|
+
max_tokens=1024,
|
|
17
|
+
tools=[browser],
|
|
18
|
+
messages=[{"role": "user", "content": "Open example.com and tell me its heading."}],
|
|
19
|
+
)
|
|
20
|
+
for message in runner:
|
|
21
|
+
print(message)
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "specstream-claude-browser"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "A driver for the browser toolset of the Claude SDK that runs on SpecStream browser sessions."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = "BSD-2-Clause"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [{ name = "SpecStream", email = "support@specstream.ai" }]
|
|
10
|
+
keywords = ["claude", "anthropic", "browser-use", "browser-toolset", "specstream", "browser-sessions", "agents"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 4 - Beta",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
17
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
18
|
+
"Topic :: Internet :: WWW/HTTP :: Browsers",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
# httpx2 is the HTTP client the anthropic package itself installs, so the driver adds no package of its own.
|
|
22
|
+
dependencies = ["anthropic>=2.8,<3", "httpx2>=2,<3"]
|
|
23
|
+
|
|
24
|
+
[project.optional-dependencies]
|
|
25
|
+
test = ["pytest>=8"]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://specstream.ai"
|
|
29
|
+
Documentation = "https://specstream.ai/docs/api"
|
|
30
|
+
Repository = "https://github.com/specstream/specstream-tools/tree/main/packages/specstream-claude-browser"
|
|
31
|
+
Issues = "https://github.com/specstream/specstream-tools/issues"
|
|
32
|
+
Changelog = "https://github.com/specstream/specstream-tools/blob/main/packages/specstream-claude-browser/CHANGELOG.md"
|
|
33
|
+
Pricing = "https://specstream.ai/pricing"
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["hatchling>=1.27,<2"]
|
|
37
|
+
build-backend = "hatchling.build"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["specstream_claude_browser"]
|
|
41
|
+
|
|
42
|
+
[tool.hatch.build.targets.sdist]
|
|
43
|
+
include = ["specstream_claude_browser", "examples", "tests", "README.md", "CHANGELOG.md", "LICENSE"]
|
|
44
|
+
|
|
45
|
+
[tool.ruff]
|
|
46
|
+
line-length = 120
|
|
47
|
+
|
|
48
|
+
[tool.ruff.lint]
|
|
49
|
+
select = ["E", "F", "I", "W"]
|
|
50
|
+
|
|
51
|
+
[tool.ruff.lint.per-file-ignores]
|
|
52
|
+
"tests/*" = ["E501"]
|
|
53
|
+
|
|
54
|
+
[tool.pytest.ini_options]
|
|
55
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""A driver for the browser toolset of the Claude SDK that runs on SpecStream browser sessions."""
|
|
2
|
+
|
|
3
|
+
from specstream_claude_browser._client import BASE_URL, SessionClient, SpecStreamError
|
|
4
|
+
from specstream_claude_browser._driver import TAB_ID, SpecStreamBrowser
|
|
5
|
+
|
|
6
|
+
__all__ = ["BASE_URL", "TAB_ID", "SessionClient", "SpecStreamBrowser", "SpecStreamError"]
|
|
7
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""The three SpecStream browser-session calls the driver needs: open a session, send it one step, end it."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
from urllib.parse import quote
|
|
8
|
+
|
|
9
|
+
import httpx2 as httpx
|
|
10
|
+
|
|
11
|
+
BASE_URL = "https://api.specstream.ai"
|
|
12
|
+
USER_AGENT = "specstream-claude-browser/0.1.0"
|
|
13
|
+
# Above the API's own wait for one step (120 s), so the API's answer arrives before this client gives up.
|
|
14
|
+
REQUEST_TIMEOUT_S = 150.0
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SpecStreamError(Exception):
|
|
18
|
+
"""SpecStream refused a call, or answered with something this driver cannot read."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class StepResult:
|
|
23
|
+
"""The answer to one step: the tool's text and image, the page after it, and the tool's own error."""
|
|
24
|
+
|
|
25
|
+
text: str = ""
|
|
26
|
+
image_data: str | None = None
|
|
27
|
+
image_media_type: str | None = None
|
|
28
|
+
url: str | None = None
|
|
29
|
+
title: str | None = None
|
|
30
|
+
error: str | None = None
|
|
31
|
+
raw: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SessionClient:
|
|
35
|
+
"""Calls /v1/browser/sessions with an API key. `transport` replaces the network, for tests."""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
api_key: str,
|
|
40
|
+
*,
|
|
41
|
+
base_url: str = BASE_URL,
|
|
42
|
+
transport: httpx.BaseTransport | None = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
if not api_key or not api_key.strip():
|
|
45
|
+
raise SpecStreamError(
|
|
46
|
+
"No SpecStream API key. Pass api_key=..., or set SPECSTREAM_API_KEY. "
|
|
47
|
+
"Create a key under Agents & API at https://specstream.ai/workspace."
|
|
48
|
+
)
|
|
49
|
+
token = api_key.strip()
|
|
50
|
+
self._http = httpx.Client(
|
|
51
|
+
base_url=base_url.rstrip("/"),
|
|
52
|
+
timeout=REQUEST_TIMEOUT_S,
|
|
53
|
+
transport=transport,
|
|
54
|
+
headers={
|
|
55
|
+
"Authorization": token if token.lower().startswith("bearer ") else f"Bearer {token}",
|
|
56
|
+
"Accept": "application/json",
|
|
57
|
+
"User-Agent": USER_AGENT,
|
|
58
|
+
},
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
def open(
|
|
62
|
+
self,
|
|
63
|
+
*,
|
|
64
|
+
timeout_s: int,
|
|
65
|
+
idle_timeout_s: int,
|
|
66
|
+
allowed_domains: list[str] | None = None,
|
|
67
|
+
block_media: bool = False,
|
|
68
|
+
) -> dict[str, Any]:
|
|
69
|
+
"""Opens a session. keep_alive is true because the driver sends one step at a time, with no
|
|
70
|
+
client connected between steps: without it the session would end at once."""
|
|
71
|
+
body: dict[str, Any] = {
|
|
72
|
+
"timeout_s": timeout_s,
|
|
73
|
+
"idle_timeout_s": idle_timeout_s,
|
|
74
|
+
"keep_alive": True,
|
|
75
|
+
"metadata": {"client": "claude-browser-toolset"},
|
|
76
|
+
}
|
|
77
|
+
if allowed_domains:
|
|
78
|
+
body["allowed_domains"] = list(allowed_domains)
|
|
79
|
+
if block_media:
|
|
80
|
+
body["block_media"] = True
|
|
81
|
+
return self._request("POST", "/v1/browser/sessions", body)
|
|
82
|
+
|
|
83
|
+
def step(self, session_id: str, tool: str, arguments: dict[str, Any] | None = None) -> StepResult:
|
|
84
|
+
"""One step: a Playwright MCP tool name with its arguments, or browser_read for the page's text."""
|
|
85
|
+
data = self._request("POST", f"{self._path(session_id)}/actions", {"tool": tool, "arguments": arguments or {}})
|
|
86
|
+
texts: list[str] = []
|
|
87
|
+
image_data = image_media_type = None
|
|
88
|
+
for part in data.get("result") or []:
|
|
89
|
+
if not isinstance(part, dict):
|
|
90
|
+
continue
|
|
91
|
+
if part.get("type") == "text" and isinstance(part.get("text"), str):
|
|
92
|
+
texts.append(part["text"])
|
|
93
|
+
elif part.get("type") == "image" and isinstance(part.get("data"), str) and image_data is None:
|
|
94
|
+
image_data, image_media_type = part["data"], part.get("mime_type")
|
|
95
|
+
error = data.get("error")
|
|
96
|
+
message = None
|
|
97
|
+
if isinstance(error, dict):
|
|
98
|
+
message = str(error.get("message") or error.get("code") or "The step failed.")
|
|
99
|
+
if error.get("reason"):
|
|
100
|
+
message = f"{message} ({error['reason']})"
|
|
101
|
+
return StepResult(
|
|
102
|
+
text="\n".join(texts),
|
|
103
|
+
image_data=image_data,
|
|
104
|
+
image_media_type=image_media_type,
|
|
105
|
+
url=data.get("url") if isinstance(data.get("url"), str) else None,
|
|
106
|
+
title=data.get("title") if isinstance(data.get("title"), str) else None,
|
|
107
|
+
error=message,
|
|
108
|
+
raw=data,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
def release(self, session_id: str) -> dict[str, Any]:
|
|
112
|
+
"""Ends the session, so that its time stops being charged."""
|
|
113
|
+
return self._request("POST", f"{self._path(session_id)}/release", {})
|
|
114
|
+
|
|
115
|
+
def close(self) -> None:
|
|
116
|
+
self._http.close()
|
|
117
|
+
|
|
118
|
+
@staticmethod
|
|
119
|
+
def _path(session_id: str) -> str:
|
|
120
|
+
return f"/v1/browser/sessions/{quote(session_id, safe='')}"
|
|
121
|
+
|
|
122
|
+
def _request(self, method: str, path: str, body: dict[str, Any]) -> dict[str, Any]:
|
|
123
|
+
try:
|
|
124
|
+
response = self._http.request(method, path, json=body)
|
|
125
|
+
except httpx.HTTPError as exc:
|
|
126
|
+
raise SpecStreamError(f"Could not reach SpecStream: {exc.__class__.__name__}") from exc
|
|
127
|
+
try:
|
|
128
|
+
payload = response.json()
|
|
129
|
+
except ValueError:
|
|
130
|
+
payload = None
|
|
131
|
+
if response.status_code >= 400:
|
|
132
|
+
error = payload.get("error") if isinstance(payload, dict) else None
|
|
133
|
+
message = error.get("message") if isinstance(error, dict) else error
|
|
134
|
+
if not isinstance(message, str) or not message:
|
|
135
|
+
message = response.text[:300] or response.reason_phrase
|
|
136
|
+
raise SpecStreamError(f"SpecStream answered {response.status_code}: {message}")
|
|
137
|
+
data = payload.get("data") if isinstance(payload, dict) else None
|
|
138
|
+
if not isinstance(data, dict):
|
|
139
|
+
raise SpecStreamError("SpecStream answered without data.")
|
|
140
|
+
return data
|
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
"""SpecStreamBrowser: the members of the Claude browser toolset, each sent as one step of a SpecStream session.
|
|
2
|
+
|
|
3
|
+
A session takes Playwright MCP's tools, which address an element by the ref its snapshot gives it. So
|
|
4
|
+
`read_page` returns that snapshot, and the members that act on an element take a ref target. The few
|
|
5
|
+
members that take a coordinate (`left_click` at a point, `scroll`) run as a script in the page.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import httpx2 as httpx
|
|
16
|
+
from anthropic.tools import ToolError
|
|
17
|
+
from anthropic.tools.browser import (
|
|
18
|
+
BetaAbstractBrowserToolset20260801,
|
|
19
|
+
BetaBrowserNavigateResult,
|
|
20
|
+
BetaBrowserState,
|
|
21
|
+
BetaScreenshotResult,
|
|
22
|
+
BetaToolsetCallContext,
|
|
23
|
+
TabMissingError,
|
|
24
|
+
)
|
|
25
|
+
from anthropic.types.beta import (
|
|
26
|
+
BetaBrowserDoubleClickInput,
|
|
27
|
+
BetaBrowserFindInput,
|
|
28
|
+
BetaBrowserFormInputInput,
|
|
29
|
+
BetaBrowserGetPageTextInput,
|
|
30
|
+
BetaBrowserHoverInput,
|
|
31
|
+
BetaBrowserJavascriptExecInput,
|
|
32
|
+
BetaBrowserKeyInput,
|
|
33
|
+
BetaBrowserLeftClickInput,
|
|
34
|
+
BetaBrowserMiddleClickInput,
|
|
35
|
+
BetaBrowserNavigateInput,
|
|
36
|
+
BetaBrowserReadConsoleInput,
|
|
37
|
+
BetaBrowserReadNetworkInput,
|
|
38
|
+
BetaBrowserReadPageInput,
|
|
39
|
+
BetaBrowserRightClickInput,
|
|
40
|
+
BetaBrowserScreenshotInput,
|
|
41
|
+
BetaBrowserScrollInput,
|
|
42
|
+
BetaBrowserScrollToInput,
|
|
43
|
+
BetaBrowserStateTabEntryParam,
|
|
44
|
+
BetaBrowserTypeInput,
|
|
45
|
+
BetaBrowserWaitInput,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
from specstream_claude_browser._client import BASE_URL, SessionClient, SpecStreamError, StepResult
|
|
49
|
+
|
|
50
|
+
# A session has one page the driver follows, so the report always names this one tab.
|
|
51
|
+
TAB_ID = "tab-1"
|
|
52
|
+
# The API's own bounds for a session's length and for its idle wait, in seconds.
|
|
53
|
+
TIMEOUT_MIN_S, TIMEOUT_MAX_S = 60, 3600
|
|
54
|
+
IDLE_MIN_S, IDLE_MAX_S = 10, 600
|
|
55
|
+
# One wheel tick, in CSS pixels.
|
|
56
|
+
SCROLL_TICK_PX = 100
|
|
57
|
+
# The longest wait one step may ask for, in seconds: below the API's own wait for a step.
|
|
58
|
+
WAIT_MAX_S = 60.0
|
|
59
|
+
|
|
60
|
+
REF_ONLY = "This browser addresses elements by ref. Call read_page and pass a ref target."
|
|
61
|
+
|
|
62
|
+
_MODIFIERS = {
|
|
63
|
+
"ctrl": "Control",
|
|
64
|
+
"control": "Control",
|
|
65
|
+
"cmd": "Meta",
|
|
66
|
+
"command": "Meta",
|
|
67
|
+
"meta": "Meta",
|
|
68
|
+
"super": "Meta",
|
|
69
|
+
"win": "Meta",
|
|
70
|
+
"alt": "Alt",
|
|
71
|
+
"option": "Alt",
|
|
72
|
+
"shift": "Shift",
|
|
73
|
+
}
|
|
74
|
+
_KEYS = {
|
|
75
|
+
"return": "Enter",
|
|
76
|
+
"enter": "Enter",
|
|
77
|
+
"backspace": "Backspace",
|
|
78
|
+
"delete": "Delete",
|
|
79
|
+
"del": "Delete",
|
|
80
|
+
"escape": "Escape",
|
|
81
|
+
"esc": "Escape",
|
|
82
|
+
"tab": "Tab",
|
|
83
|
+
"space": "Space",
|
|
84
|
+
"up": "ArrowUp",
|
|
85
|
+
"down": "ArrowDown",
|
|
86
|
+
"left": "ArrowLeft",
|
|
87
|
+
"right": "ArrowRight",
|
|
88
|
+
"arrowup": "ArrowUp",
|
|
89
|
+
"arrowdown": "ArrowDown",
|
|
90
|
+
"arrowleft": "ArrowLeft",
|
|
91
|
+
"arrowright": "ArrowRight",
|
|
92
|
+
"page_up": "PageUp",
|
|
93
|
+
"pageup": "PageUp",
|
|
94
|
+
"prior": "PageUp",
|
|
95
|
+
"page_down": "PageDown",
|
|
96
|
+
"pagedown": "PageDown",
|
|
97
|
+
"next": "PageDown",
|
|
98
|
+
"home": "Home",
|
|
99
|
+
"end": "End",
|
|
100
|
+
"insert": "Insert",
|
|
101
|
+
}
|
|
102
|
+
_RESULT_SECTION = re.compile(r"^### Result\s*\n(.*?)(?=^### |\Z)", re.MULTILINE | re.DOTALL)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def playwright_key(chord: str) -> str:
|
|
106
|
+
"""One key or chord as Claude writes it ("ctrl+a", "Return") in Playwright's spelling ("Control+a", "Enter")."""
|
|
107
|
+
if chord == "+":
|
|
108
|
+
return chord
|
|
109
|
+
parts = chord.split("+")
|
|
110
|
+
if chord.endswith("++"): # a chord that ends in the plus key itself, such as "ctrl++"
|
|
111
|
+
parts = [*chord[:-2].split("+"), "+"]
|
|
112
|
+
out: list[str] = []
|
|
113
|
+
for index, part in enumerate(parts):
|
|
114
|
+
last = index == len(parts) - 1
|
|
115
|
+
low = part.lower()
|
|
116
|
+
if not last and low in _MODIFIERS:
|
|
117
|
+
out.append(_MODIFIERS[low])
|
|
118
|
+
elif low in _KEYS:
|
|
119
|
+
out.append(_KEYS[low])
|
|
120
|
+
elif low in _MODIFIERS:
|
|
121
|
+
out.append(_MODIFIERS[low])
|
|
122
|
+
elif re.fullmatch(r"f\d{1,2}", low):
|
|
123
|
+
out.append(low.upper())
|
|
124
|
+
else:
|
|
125
|
+
out.append(part)
|
|
126
|
+
return "+".join(out)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _modifiers(chord: str | None) -> list[str]:
|
|
130
|
+
if not chord:
|
|
131
|
+
return []
|
|
132
|
+
names: list[str] = []
|
|
133
|
+
for part in chord.split("+"):
|
|
134
|
+
name = _MODIFIERS.get(part.strip().lower())
|
|
135
|
+
if name is None:
|
|
136
|
+
raise ToolError(f"Unknown modifier {part!r}. Use ctrl, shift, alt or cmd.")
|
|
137
|
+
if name not in names:
|
|
138
|
+
names.append(name)
|
|
139
|
+
return names
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _evaluated(text: str) -> str:
|
|
143
|
+
"""The value a browser_evaluate step returned, without the sections Playwright MCP writes around it."""
|
|
144
|
+
match = _RESULT_SECTION.search(text)
|
|
145
|
+
return (match.group(1) if match else text).strip()
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class SpecStreamBrowser(BetaAbstractBrowserToolset20260801):
|
|
149
|
+
"""The Claude browser toolset on a SpecStream browser session.
|
|
150
|
+
|
|
151
|
+
The session opens at the first call and ends at `close()` (or at the end of the `with` block), so
|
|
152
|
+
a toolset that is never called costs nothing. Time is charged by the second and each step once.
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
api_key: A SpecStream API key. Default: the SPECSTREAM_API_KEY environment variable.
|
|
156
|
+
session_id: Drive a session that is already open, and leave it open at `close()`.
|
|
157
|
+
timeout_s: The longest the session lasts, 60 to 3600 seconds.
|
|
158
|
+
idle_timeout_s: The session ends after this long without a step, 10 to 600 seconds.
|
|
159
|
+
allowed_domains: Hosts the session may open ("example.com", "*.example.com"). The session
|
|
160
|
+
refuses every other host itself, in addition to any `url_policy` you pass.
|
|
161
|
+
block_media: Do not load images, video and fonts.
|
|
162
|
+
base_url: The API's address.
|
|
163
|
+
transport: Replaces the network, for tests.
|
|
164
|
+
**options: The toolset's own options: `url_policy`, `confirm`, `configs`, `file_policy`,
|
|
165
|
+
`tool_configs`. `javascript_exec` is served only when you pass `confirm`.
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
def __init__(
|
|
169
|
+
self,
|
|
170
|
+
*,
|
|
171
|
+
api_key: str | None = None,
|
|
172
|
+
session_id: str | None = None,
|
|
173
|
+
timeout_s: int = 900,
|
|
174
|
+
idle_timeout_s: int = 300,
|
|
175
|
+
allowed_domains: list[str] | None = None,
|
|
176
|
+
block_media: bool = False,
|
|
177
|
+
base_url: str = BASE_URL,
|
|
178
|
+
transport: httpx.BaseTransport | None = None,
|
|
179
|
+
**options: Any,
|
|
180
|
+
) -> None:
|
|
181
|
+
if not TIMEOUT_MIN_S <= timeout_s <= TIMEOUT_MAX_S:
|
|
182
|
+
raise ValueError(f"timeout_s must be {TIMEOUT_MIN_S} to {TIMEOUT_MAX_S} seconds.")
|
|
183
|
+
if not IDLE_MIN_S <= idle_timeout_s <= IDLE_MAX_S:
|
|
184
|
+
raise ValueError(f"idle_timeout_s must be {IDLE_MIN_S} to {IDLE_MAX_S} seconds.")
|
|
185
|
+
# The API serves javascript_exec only when it is switched on, and the SDK then asks for a confirm
|
|
186
|
+
# callable. So it is on with `confirm` and off without, and the few-line start works; a caller's
|
|
187
|
+
# own entry wins.
|
|
188
|
+
configs = dict(options.get("configs") or {})
|
|
189
|
+
configs.setdefault("javascript_exec", {"enabled": options.get("confirm") is not None})
|
|
190
|
+
options["configs"] = configs
|
|
191
|
+
super().__init__(**options)
|
|
192
|
+
self._client = SessionClient(
|
|
193
|
+
api_key if api_key is not None else os.environ.get("SPECSTREAM_API_KEY", ""),
|
|
194
|
+
base_url=base_url,
|
|
195
|
+
transport=transport,
|
|
196
|
+
)
|
|
197
|
+
self._open_options = {
|
|
198
|
+
"timeout_s": timeout_s,
|
|
199
|
+
"idle_timeout_s": idle_timeout_s,
|
|
200
|
+
"allowed_domains": allowed_domains,
|
|
201
|
+
"block_media": block_media,
|
|
202
|
+
}
|
|
203
|
+
self._session_id = session_id
|
|
204
|
+
self._owns_session = session_id is None
|
|
205
|
+
self._released = False
|
|
206
|
+
self._url = "about:blank"
|
|
207
|
+
self._title = ""
|
|
208
|
+
self.live_url: str | None = None
|
|
209
|
+
|
|
210
|
+
@property
|
|
211
|
+
def session_id(self) -> str | None:
|
|
212
|
+
"""The session's id once it is open."""
|
|
213
|
+
return self._session_id
|
|
214
|
+
|
|
215
|
+
# --- the session -----------------------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
def _session(self) -> str:
|
|
218
|
+
if self._session_id is None:
|
|
219
|
+
try:
|
|
220
|
+
session = self._client.open(**self._open_options)
|
|
221
|
+
except SpecStreamError as exc:
|
|
222
|
+
raise ToolError(str(exc)) from exc
|
|
223
|
+
self._session_id = str(session["id"])
|
|
224
|
+
live = session.get("live_url")
|
|
225
|
+
self.live_url = live if isinstance(live, str) else None
|
|
226
|
+
return self._session_id
|
|
227
|
+
|
|
228
|
+
def _step(self, tool: str, arguments: dict[str, Any] | None = None, *, tab_id: str | None = None) -> StepResult:
|
|
229
|
+
if tab_id is not None and tab_id != TAB_ID:
|
|
230
|
+
raise TabMissingError()
|
|
231
|
+
try:
|
|
232
|
+
result = self._client.step(self._session(), tool, arguments)
|
|
233
|
+
except SpecStreamError as exc:
|
|
234
|
+
raise ToolError(str(exc)) from exc
|
|
235
|
+
if result.url:
|
|
236
|
+
self._url = result.url
|
|
237
|
+
if result.title is not None:
|
|
238
|
+
self._title = result.title
|
|
239
|
+
if result.error:
|
|
240
|
+
raise ToolError(result.error)
|
|
241
|
+
return result
|
|
242
|
+
|
|
243
|
+
def _evaluate(self, function: str, *, tab_id: str | None, ref: str | None = None) -> str:
|
|
244
|
+
arguments: dict[str, Any] = {"function": function}
|
|
245
|
+
if ref is not None:
|
|
246
|
+
arguments["target"] = ref
|
|
247
|
+
arguments["element"] = "the target element"
|
|
248
|
+
return _evaluated(self._step("browser_evaluate", arguments, tab_id=tab_id).text)
|
|
249
|
+
|
|
250
|
+
def close(self) -> None:
|
|
251
|
+
super().close() # first, so no call is still using the browser when it ends
|
|
252
|
+
if self._session_id is not None and self._owns_session and not self._released:
|
|
253
|
+
self._released = True
|
|
254
|
+
try:
|
|
255
|
+
self._client.release(self._session_id)
|
|
256
|
+
except SpecStreamError:
|
|
257
|
+
# The session also ends by itself at its idle wait; closing must not raise in the host.
|
|
258
|
+
pass
|
|
259
|
+
self._client.close()
|
|
260
|
+
|
|
261
|
+
# --- the state report -------------------------------------------------------------------
|
|
262
|
+
|
|
263
|
+
def _browser_state(self, context: BetaToolsetCallContext) -> BetaBrowserState:
|
|
264
|
+
if self._session_id is None:
|
|
265
|
+
return BetaBrowserState(tabs=[], state_changes=[])
|
|
266
|
+
return BetaBrowserState(
|
|
267
|
+
tabs=[BetaBrowserStateTabEntryParam(tab_id=TAB_ID, title=self._title, url=self._url, active=True)],
|
|
268
|
+
state_changes=[],
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
# --- members ------------------------------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
def navigate(self, context: BetaToolsetCallContext, input: BetaBrowserNavigateInput) -> BetaBrowserNavigateResult:
|
|
274
|
+
word = input.url.strip().lower()
|
|
275
|
+
if word == "back":
|
|
276
|
+
self._step("browser_navigate_back", tab_id=input.tab_id)
|
|
277
|
+
elif word == "forward":
|
|
278
|
+
self._evaluate("() => { history.forward(); }", tab_id=input.tab_id)
|
|
279
|
+
elif word == "reload":
|
|
280
|
+
self._evaluate("() => { location.reload(); }", tab_id=input.tab_id)
|
|
281
|
+
else:
|
|
282
|
+
self._step("browser_navigate", {"url": input.url}, tab_id=input.tab_id)
|
|
283
|
+
return BetaBrowserNavigateResult(url=self._url, status=None, title=self._title or None)
|
|
284
|
+
|
|
285
|
+
def screenshot(self, context: BetaToolsetCallContext, input: BetaBrowserScreenshotInput) -> BetaScreenshotResult:
|
|
286
|
+
# scale=css: one image pixel is one CSS pixel, so a coordinate read off the image is a page coordinate.
|
|
287
|
+
result = self._step("browser_take_screenshot", {"type": "png", "scale": "css"}, tab_id=input.tab_id)
|
|
288
|
+
if not result.image_data:
|
|
289
|
+
raise ToolError("The browser returned no image.")
|
|
290
|
+
media_type = result.image_media_type if result.image_media_type in ("image/png", "image/jpeg") else "image/png"
|
|
291
|
+
return BetaScreenshotResult(data=result.image_data, media_type=media_type)
|
|
292
|
+
|
|
293
|
+
def _click(self, input: Any, **extra: Any) -> None:
|
|
294
|
+
target = input.target
|
|
295
|
+
if target.type != "ref":
|
|
296
|
+
raise ToolError(REF_ONLY)
|
|
297
|
+
arguments: dict[str, Any] = {"target": target.ref, "element": "the target element", **extra}
|
|
298
|
+
modifiers = _modifiers(input.modifiers)
|
|
299
|
+
if modifiers:
|
|
300
|
+
arguments["modifiers"] = modifiers
|
|
301
|
+
self._step("browser_click", arguments, tab_id=input.tab_id)
|
|
302
|
+
|
|
303
|
+
def left_click(self, context: BetaToolsetCallContext, input: BetaBrowserLeftClickInput) -> str | None:
|
|
304
|
+
target = input.target
|
|
305
|
+
if target.type == "ref":
|
|
306
|
+
self._click(input)
|
|
307
|
+
return None
|
|
308
|
+
if input.modifiers:
|
|
309
|
+
raise ToolError("A click at a coordinate takes no modifiers here. " + REF_ONLY)
|
|
310
|
+
# A session has no pointer tool, so a click at a point is the element under it, clicked by script.
|
|
311
|
+
found = self._evaluate(
|
|
312
|
+
f"() => {{ const el = document.elementFromPoint({int(target.x)}, {int(target.y)}); "
|
|
313
|
+
"if (!el) return false; el.click(); return true; }",
|
|
314
|
+
tab_id=input.tab_id,
|
|
315
|
+
)
|
|
316
|
+
if found == "false":
|
|
317
|
+
raise ToolError(f"No element at ({target.x}, {target.y}).")
|
|
318
|
+
return "Clicked the element at that point by script. A ref target from read_page clicks with the pointer."
|
|
319
|
+
|
|
320
|
+
def right_click(self, context: BetaToolsetCallContext, input: BetaBrowserRightClickInput) -> str | None:
|
|
321
|
+
self._click(input, button="right")
|
|
322
|
+
return None
|
|
323
|
+
|
|
324
|
+
def middle_click(self, context: BetaToolsetCallContext, input: BetaBrowserMiddleClickInput) -> str | None:
|
|
325
|
+
self._click(input, button="middle")
|
|
326
|
+
return None
|
|
327
|
+
|
|
328
|
+
def double_click(self, context: BetaToolsetCallContext, input: BetaBrowserDoubleClickInput) -> str | None:
|
|
329
|
+
self._click(input, doubleClick=True)
|
|
330
|
+
return None
|
|
331
|
+
|
|
332
|
+
def hover(self, context: BetaToolsetCallContext, input: BetaBrowserHoverInput) -> str | None:
|
|
333
|
+
if input.target.type != "ref":
|
|
334
|
+
raise ToolError(REF_ONLY)
|
|
335
|
+
self._step("browser_hover", {"target": input.target.ref, "element": "the target element"}, tab_id=input.tab_id)
|
|
336
|
+
return None
|
|
337
|
+
|
|
338
|
+
def scroll(self, context: BetaToolsetCallContext, input: BetaBrowserScrollInput) -> str | None:
|
|
339
|
+
amount = (input.scroll_amount or 3) * SCROLL_TICK_PX
|
|
340
|
+
dx, dy = {"up": (0, -amount), "down": (0, amount), "left": (-amount, 0), "right": (amount, 0)}[
|
|
341
|
+
input.scroll_direction
|
|
342
|
+
]
|
|
343
|
+
# Scrolls the nearest scrollable box under the point, or the page when there is none.
|
|
344
|
+
self._evaluate(
|
|
345
|
+
f"() => {{ let el = document.elementFromPoint({int(input.target.x)}, {int(input.target.y)}); "
|
|
346
|
+
"while (el && el !== document.documentElement) { const s = getComputedStyle(el); "
|
|
347
|
+
"const y = /(auto|scroll)/.test(s.overflowY) && el.scrollHeight > el.clientHeight; "
|
|
348
|
+
"const x = /(auto|scroll)/.test(s.overflowX) && el.scrollWidth > el.clientWidth; "
|
|
349
|
+
f"if (({dy} !== 0 && y) || ({dx} !== 0 && x)) {{ el.scrollBy({dx}, {dy}); return true; }} "
|
|
350
|
+
f"el = el.parentElement; }} window.scrollBy({dx}, {dy}); return true; }}",
|
|
351
|
+
tab_id=input.tab_id,
|
|
352
|
+
)
|
|
353
|
+
return None
|
|
354
|
+
|
|
355
|
+
def scroll_to(self, context: BetaToolsetCallContext, input: BetaBrowserScrollToInput) -> str | None:
|
|
356
|
+
self._evaluate(
|
|
357
|
+
"(element) => { element.scrollIntoView({block: 'center', inline: 'center'}); }",
|
|
358
|
+
tab_id=input.tab_id,
|
|
359
|
+
ref=input.target.ref,
|
|
360
|
+
)
|
|
361
|
+
return None
|
|
362
|
+
|
|
363
|
+
def type(self, context: BetaToolsetCallContext, input: BetaBrowserTypeInput) -> str | None:
|
|
364
|
+
# Types into the focused field: insertText fires the input events a page's own code listens for.
|
|
365
|
+
typed = self._evaluate(
|
|
366
|
+
f"() => document.execCommand('insertText', false, {json.dumps(input.text)})", tab_id=input.tab_id
|
|
367
|
+
)
|
|
368
|
+
if typed == "false":
|
|
369
|
+
raise ToolError("No editable field has the focus. Click a field first, or use form_input with its ref.")
|
|
370
|
+
return None
|
|
371
|
+
|
|
372
|
+
def key(self, context: BetaToolsetCallContext, input: BetaBrowserKeyInput) -> str | None:
|
|
373
|
+
chords = [playwright_key(chord) for chord in input.text.split()]
|
|
374
|
+
if not chords:
|
|
375
|
+
raise ToolError("No key to press.")
|
|
376
|
+
for _ in range(max(1, input.repeat or 1)):
|
|
377
|
+
for chord in chords:
|
|
378
|
+
self._step("browser_press_key", {"key": chord}, tab_id=input.tab_id)
|
|
379
|
+
return None
|
|
380
|
+
|
|
381
|
+
def form_input(self, context: BetaToolsetCallContext, input: BetaBrowserFormInputInput) -> str | None:
|
|
382
|
+
ref, value = input.target.ref, input.value
|
|
383
|
+
if isinstance(value, bool):
|
|
384
|
+
kind, text = "checkbox", "true" if value else "false"
|
|
385
|
+
else:
|
|
386
|
+
# A <select> takes the text of one of its options; every other field is filled as text.
|
|
387
|
+
tag = self._evaluate("(element) => element.tagName", tab_id=input.tab_id, ref=ref)
|
|
388
|
+
kind = "combobox" if "SELECT" in tag.upper() else "textbox"
|
|
389
|
+
text = str(int(value)) if isinstance(value, float) and value.is_integer() else str(value)
|
|
390
|
+
field = {"name": "the target field", "type": kind, "target": ref, "value": text}
|
|
391
|
+
self._step("browser_fill_form", {"fields": [field]}, tab_id=input.tab_id)
|
|
392
|
+
return None
|
|
393
|
+
|
|
394
|
+
def read_page(self, context: BetaToolsetCallContext, input: BetaBrowserReadPageInput) -> str:
|
|
395
|
+
arguments: dict[str, Any] = {}
|
|
396
|
+
if input.depth is not None:
|
|
397
|
+
arguments["depth"] = input.depth
|
|
398
|
+
if input.ref is not None:
|
|
399
|
+
arguments["target"] = input.ref
|
|
400
|
+
return self._step("browser_snapshot", arguments, tab_id=input.tab_id).text
|
|
401
|
+
|
|
402
|
+
def find(self, context: BetaToolsetCallContext, input: BetaBrowserFindInput) -> str:
|
|
403
|
+
# The session matches the words in the page's snapshot; it does not read a description.
|
|
404
|
+
return self._step("browser_find", {"text": input.query}, tab_id=input.tab_id).text
|
|
405
|
+
|
|
406
|
+
def get_page_text(self, context: BetaToolsetCallContext, input: BetaBrowserGetPageTextInput) -> str:
|
|
407
|
+
return self._step("browser_read", {"format": "text"}, tab_id=input.tab_id).text
|
|
408
|
+
|
|
409
|
+
def wait(self, context: BetaToolsetCallContext, input: BetaBrowserWaitInput) -> str | None:
|
|
410
|
+
seconds = min(max(float(input.duration), 0.0), WAIT_MAX_S)
|
|
411
|
+
self._step("browser_wait_for", {"time": seconds}, tab_id=input.tab_id)
|
|
412
|
+
return None
|
|
413
|
+
|
|
414
|
+
def read_console(self, context: BetaToolsetCallContext, input: BetaBrowserReadConsoleInput) -> str:
|
|
415
|
+
return self._step("browser_console_messages", {"level": "info"}, tab_id=input.tab_id).text
|
|
416
|
+
|
|
417
|
+
def read_network(self, context: BetaToolsetCallContext, input: BetaBrowserReadNetworkInput) -> str:
|
|
418
|
+
return self._step("browser_network_requests", {"static": False}, tab_id=input.tab_id).text
|
|
419
|
+
|
|
420
|
+
def javascript_exec(self, context: BetaToolsetCallContext, input: BetaBrowserJavascriptExecInput) -> str:
|
|
421
|
+
return self._evaluate(f"async () => await (0, eval)({json.dumps(input.text)})", tab_id=input.tab_id)
|
|
File without changes
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import httpx2 as httpx
|
|
7
|
+
import pytest
|
|
8
|
+
from anthropic.types.beta import BetaToolUseBlock
|
|
9
|
+
|
|
10
|
+
from specstream_claude_browser import TAB_ID, SpecStreamBrowser, SpecStreamError
|
|
11
|
+
from specstream_claude_browser._driver import playwright_key
|
|
12
|
+
|
|
13
|
+
SESSION = {"id": "bs_1", "status": "running", "live_url": "https://api.specstream.ai/v1/browser/sessions/bs_1/live"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Api:
|
|
17
|
+
def __init__(self, answers: dict[str, dict[str, Any]] | None = None, open_status: int = 201) -> None:
|
|
18
|
+
self.calls: list[tuple[str, str, dict[str, Any]]] = []
|
|
19
|
+
self.answers = answers or {}
|
|
20
|
+
self.open_status = open_status
|
|
21
|
+
|
|
22
|
+
def __call__(self, request: httpx.Request) -> httpx.Response:
|
|
23
|
+
body = json.loads(request.content or b"{}")
|
|
24
|
+
self.calls.append((request.method, request.url.path, body))
|
|
25
|
+
assert request.headers["authorization"] == "Bearer test-key"
|
|
26
|
+
if request.url.path == "/v1/browser/sessions":
|
|
27
|
+
if self.open_status >= 400:
|
|
28
|
+
return httpx.Response(self.open_status, json={"error": {"message": "The key is not valid."}})
|
|
29
|
+
return httpx.Response(201, json={"data": SESSION})
|
|
30
|
+
if request.url.path.endswith("/release"):
|
|
31
|
+
return httpx.Response(200, json={"data": {**SESSION, "status": "ended"}})
|
|
32
|
+
answer = {
|
|
33
|
+
"result": [],
|
|
34
|
+
"url": "https://example.com/",
|
|
35
|
+
"title": "Example Domain",
|
|
36
|
+
"took_ms": 5,
|
|
37
|
+
"price_usd": 0.001,
|
|
38
|
+
}
|
|
39
|
+
answer.update(self.answers.get(body["tool"], {}))
|
|
40
|
+
return httpx.Response(200, json={"data": answer})
|
|
41
|
+
|
|
42
|
+
def steps(self) -> list[tuple[str, dict[str, Any]]]:
|
|
43
|
+
return [(body["tool"], body["arguments"]) for _, path, body in self.calls if path.endswith("/actions")]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def browser(api: Api, **options: Any) -> SpecStreamBrowser:
|
|
47
|
+
return SpecStreamBrowser(api_key="test-key", transport=httpx.MockTransport(api), **options)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def call(toolset: SpecStreamBrowser, name: str, **input: Any) -> dict[str, Any]:
|
|
51
|
+
block = BetaToolUseBlock(
|
|
52
|
+
type="tool_use", id=f"toolu_{name}", name=name, input=input, toolset_name=toolset.toolset_name
|
|
53
|
+
)
|
|
54
|
+
return toolset.tool_result(block)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def texts(result: dict[str, Any]) -> str:
|
|
58
|
+
content = result["content"]
|
|
59
|
+
if isinstance(content, str):
|
|
60
|
+
return content
|
|
61
|
+
return "\n".join(str(part.get("text", "")) for part in content if part.get("type") == "text")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_the_tools_entry_serves_what_the_driver_implements_and_turns_the_rest_off() -> None:
|
|
65
|
+
api = Api()
|
|
66
|
+
with browser(api) as toolset:
|
|
67
|
+
entry = toolset.to_dict()
|
|
68
|
+
configs = entry["configs"]
|
|
69
|
+
for served in ("navigate", "screenshot", "left_click", "read_page", "get_page_text", "type", "key", "form_input"):
|
|
70
|
+
assert configs.get(served, {}).get("enabled", True) is not False, served
|
|
71
|
+
for off in ("javascript_exec", "new_tab", "switch_tab", "close_tab", "file_upload", "zoom", "left_click_drag"):
|
|
72
|
+
assert configs[off]["enabled"] is False, off
|
|
73
|
+
assert api.calls == [] # a toolset that is never called opens no session and costs nothing
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_navigate_opens_one_session_reports_the_page_and_close_releases_it() -> None:
|
|
77
|
+
api = Api()
|
|
78
|
+
with browser(api, allowed_domains=["example.com"]) as toolset:
|
|
79
|
+
result = call(toolset, "navigate", url="example.com")
|
|
80
|
+
assert not result.get("is_error")
|
|
81
|
+
assert "Navigated to https://example.com/" in texts(result)
|
|
82
|
+
assert "Example Domain" in texts(result)
|
|
83
|
+
call(toolset, "navigate", url="back")
|
|
84
|
+
assert toolset.session_id == "bs_1"
|
|
85
|
+
assert toolset.live_url == SESSION["live_url"]
|
|
86
|
+
method, path, body = api.calls[0]
|
|
87
|
+
assert (method, path) == ("POST", "/v1/browser/sessions")
|
|
88
|
+
assert body["keep_alive"] is True and body["allowed_domains"] == ["example.com"]
|
|
89
|
+
assert api.steps() == [("browser_navigate", {"url": "example.com"}), ("browser_navigate_back", {})]
|
|
90
|
+
assert [path for _, path, _ in api.calls].count("/v1/browser/sessions") == 1
|
|
91
|
+
assert api.calls[-1][1] == "/v1/browser/sessions/bs_1/release"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def test_the_state_report_names_the_one_tab_with_the_page_after_the_step() -> None:
|
|
95
|
+
api = Api()
|
|
96
|
+
with browser(api) as toolset:
|
|
97
|
+
result = call(toolset, "navigate", url="https://example.com")
|
|
98
|
+
state = [part for part in result["content"] if part.get("type") == "browser_state"]
|
|
99
|
+
assert len(state) == 1
|
|
100
|
+
(tab,) = state[0]["tabs"]
|
|
101
|
+
assert tab == {"tab_id": TAB_ID, "title": "Example Domain", "url": "https://example.com/", "active": True}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def test_screenshot_returns_the_image_the_session_took() -> None:
|
|
105
|
+
api = Api(
|
|
106
|
+
{"browser_take_screenshot": {"result": [{"type": "image", "data": "aGVsbG8=", "mime_type": "image/png"}]}}
|
|
107
|
+
)
|
|
108
|
+
with browser(api) as toolset:
|
|
109
|
+
result = call(toolset, "screenshot")
|
|
110
|
+
(image,) = [part for part in result["content"] if part.get("type") == "image"]
|
|
111
|
+
assert image["source"]["data"] == "aGVsbG8=" and image["source"]["media_type"] == "image/png"
|
|
112
|
+
assert api.steps() == [("browser_take_screenshot", {"type": "png", "scale": "css"})]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_clicks_by_ref_go_to_the_pointer_and_a_point_is_clicked_by_script() -> None:
|
|
116
|
+
api = Api({"browser_evaluate": {"result": [{"type": "text", "text": "### Result\ntrue\n### Page\n- Page URL: x"}]}})
|
|
117
|
+
with browser(api) as toolset:
|
|
118
|
+
assert not call(toolset, "left_click", target={"type": "ref", "ref": "e12"}, modifiers="ctrl+shift").get(
|
|
119
|
+
"is_error"
|
|
120
|
+
)
|
|
121
|
+
assert not call(toolset, "double_click", target={"type": "ref", "ref": "e3"}).get("is_error")
|
|
122
|
+
assert not call(toolset, "right_click", target={"type": "ref", "ref": "e3"}).get("is_error")
|
|
123
|
+
assert not call(toolset, "left_click", target={"type": "coordinate", "x": 10, "y": 20}).get("is_error")
|
|
124
|
+
refused = call(toolset, "hover", target={"type": "coordinate", "x": 1, "y": 2})
|
|
125
|
+
assert refused["is_error"] and "read_page" in texts(refused)
|
|
126
|
+
steps = api.steps()
|
|
127
|
+
assert steps[0] == (
|
|
128
|
+
"browser_click",
|
|
129
|
+
{"target": "e12", "element": "the target element", "modifiers": ["Control", "Shift"]},
|
|
130
|
+
)
|
|
131
|
+
assert steps[1][1]["doubleClick"] is True and steps[2][1]["button"] == "right"
|
|
132
|
+
assert steps[3][0] == "browser_evaluate" and "elementFromPoint(10, 20)" in steps[3][1]["function"]
|
|
133
|
+
assert len(steps) == 4 # the refused hover sent nothing
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_type_key_and_form_input_reach_the_page() -> None:
|
|
137
|
+
api = Api({"browser_evaluate": {"result": [{"type": "text", "text": '### Result\n"SELECT"\n'}]}})
|
|
138
|
+
with browser(api) as toolset:
|
|
139
|
+
assert not call(toolset, "type", text='say "hi"').get("is_error")
|
|
140
|
+
assert not call(toolset, "key", text="ctrl+a BackSpace", repeat=2).get("is_error")
|
|
141
|
+
assert not call(toolset, "form_input", target={"type": "ref", "ref": "e7"}, value=True).get("is_error")
|
|
142
|
+
assert not call(toolset, "form_input", target={"type": "ref", "ref": "e8"}, value="France").get("is_error")
|
|
143
|
+
steps = api.steps()
|
|
144
|
+
assert steps[0][0] == "browser_evaluate" and json.dumps('say "hi"') in steps[0][1]["function"]
|
|
145
|
+
assert [args["key"] for tool, args in steps if tool == "browser_press_key"] == ["Control+a", "Backspace"] * 2
|
|
146
|
+
fills = [args["fields"][0] for tool, args in steps if tool == "browser_fill_form"]
|
|
147
|
+
assert fills[0] == {"name": "the target field", "type": "checkbox", "target": "e7", "value": "true"}
|
|
148
|
+
assert fills[1] == {"name": "the target field", "type": "combobox", "target": "e8", "value": "France"}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def test_typing_with_no_focused_field_is_an_error_claude_can_act_on() -> None:
|
|
152
|
+
api = Api({"browser_evaluate": {"result": [{"type": "text", "text": "### Result\nfalse\n"}]}})
|
|
153
|
+
with browser(api) as toolset:
|
|
154
|
+
result = call(toolset, "type", text="hello")
|
|
155
|
+
assert result["is_error"] and "form_input" in texts(result)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def test_reading_members_return_the_sessions_text() -> None:
|
|
159
|
+
api = Api(
|
|
160
|
+
{
|
|
161
|
+
"browser_snapshot": {"result": [{"type": "text", "text": '- link "More information" [ref=e6]'}]},
|
|
162
|
+
"browser_read": {
|
|
163
|
+
"result": [{"type": "text", "text": "Example Domain\nThis domain is for use in examples."}]
|
|
164
|
+
},
|
|
165
|
+
"browser_find": {"result": [{"type": "text", "text": '- link "More information" [ref=e6]'}]},
|
|
166
|
+
}
|
|
167
|
+
)
|
|
168
|
+
with browser(api) as toolset:
|
|
169
|
+
assert "[ref=e6]" in texts(call(toolset, "read_page", depth=4))
|
|
170
|
+
assert "This domain is for use in examples." in texts(call(toolset, "get_page_text"))
|
|
171
|
+
assert "[ref=e6]" in texts(call(toolset, "find", query="More information"))
|
|
172
|
+
assert not call(toolset, "scroll", target={"type": "coordinate", "x": 5, "y": 5}, scroll_direction="down").get(
|
|
173
|
+
"is_error"
|
|
174
|
+
)
|
|
175
|
+
assert not call(toolset, "wait", duration=2).get("is_error")
|
|
176
|
+
steps = api.steps()
|
|
177
|
+
assert steps[0] == ("browser_snapshot", {"depth": 4})
|
|
178
|
+
assert steps[1] == ("browser_read", {"format": "text"})
|
|
179
|
+
assert steps[2] == ("browser_find", {"text": "More information"})
|
|
180
|
+
assert "scrollBy(0, 300)" in steps[3][1]["function"]
|
|
181
|
+
assert steps[4] == ("browser_wait_for", {"time": 2.0})
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def test_a_refused_page_and_an_unknown_tab_are_errors_and_the_run_goes_on() -> None:
|
|
185
|
+
blocked = {
|
|
186
|
+
"code": "blocked",
|
|
187
|
+
"reason": "outside_allowed_domains",
|
|
188
|
+
"message": "The host is outside allowed_domains.",
|
|
189
|
+
}
|
|
190
|
+
api = Api({"browser_navigate": {"error": blocked}})
|
|
191
|
+
with browser(api) as toolset:
|
|
192
|
+
refused = call(toolset, "navigate", url="https://other.example")
|
|
193
|
+
assert refused["is_error"] and "outside allowed_domains" in texts(refused)
|
|
194
|
+
missing = call(toolset, "get_page_text", tab_id="tab-9")
|
|
195
|
+
assert missing["is_error"]
|
|
196
|
+
assert not call(toolset, "get_page_text", tab_id=TAB_ID).get("is_error")
|
|
197
|
+
assert [tool for tool, _ in api.steps()] == ["browser_navigate", "browser_read"]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def test_a_refused_key_is_an_error_result_not_a_crash() -> None:
|
|
201
|
+
api = Api(open_status=401)
|
|
202
|
+
with browser(api) as toolset:
|
|
203
|
+
result = call(toolset, "navigate", url="https://example.com")
|
|
204
|
+
assert result["is_error"] and "401" in texts(result) and "The key is not valid." in texts(result)
|
|
205
|
+
assert "test-key" not in json.dumps(result)
|
|
206
|
+
assert len(api.calls) == 1 # no session was opened, so there is none to release
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def test_javascript_exec_is_served_only_with_a_confirm_callable() -> None:
|
|
210
|
+
api = Api({"browser_evaluate": {"result": [{"type": "text", "text": "### Result\n42\n"}]}})
|
|
211
|
+
with browser(api, confirm=lambda context: True) as toolset:
|
|
212
|
+
assert toolset.to_dict()["configs"].get("javascript_exec", {}).get("enabled", True) is not False
|
|
213
|
+
assert "42" in texts(call(toolset, "javascript_exec", text="6 * 7"))
|
|
214
|
+
assert json.dumps("6 * 7") in api.steps()[0][1]["function"]
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def test_a_session_that_was_handed_in_is_driven_and_left_open() -> None:
|
|
218
|
+
api = Api()
|
|
219
|
+
with browser(api, session_id="bs_mine") as toolset:
|
|
220
|
+
call(toolset, "get_page_text")
|
|
221
|
+
assert [path for _, path, _ in api.calls] == ["/v1/browser/sessions/bs_mine/actions"]
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def test_options_are_checked_before_anything_is_sent(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
225
|
+
monkeypatch.delenv("SPECSTREAM_API_KEY", raising=False)
|
|
226
|
+
with pytest.raises(SpecStreamError, match="SPECSTREAM_API_KEY"):
|
|
227
|
+
SpecStreamBrowser()
|
|
228
|
+
with pytest.raises(ValueError, match="timeout_s"):
|
|
229
|
+
SpecStreamBrowser(api_key="test-key", timeout_s=5)
|
|
230
|
+
with pytest.raises(ValueError, match="idle_timeout_s"):
|
|
231
|
+
SpecStreamBrowser(api_key="test-key", idle_timeout_s=5000)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@pytest.mark.parametrize(
|
|
235
|
+
("claude", "playwright"),
|
|
236
|
+
[
|
|
237
|
+
("ctrl+a", "Control+a"),
|
|
238
|
+
("cmd+shift+p", "Meta+Shift+p"),
|
|
239
|
+
("Return", "Enter"),
|
|
240
|
+
("BackSpace", "Backspace"),
|
|
241
|
+
("Page_Down", "PageDown"),
|
|
242
|
+
("alt+Left", "Alt+ArrowLeft"),
|
|
243
|
+
("f5", "F5"),
|
|
244
|
+
("shift", "Shift"),
|
|
245
|
+
("ctrl++", "Control++"),
|
|
246
|
+
("a", "a"),
|
|
247
|
+
],
|
|
248
|
+
)
|
|
249
|
+
def test_keys_are_spelled_as_playwright_names_them(claude: str, playwright: str) -> None:
|
|
250
|
+
assert playwright_key(claude) == playwright
|