specstream-claude-toolset 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.
@@ -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,6 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-13)
4
+
5
+ - First release. `SpecStreamBrowser` drives a SpecStream browser session for the Claude SDK's browser toolset (`BetaAbstractBrowserToolset20260801`): 27 members, with tabs, element references and dismissed dialogs reported to Claude.
6
+ - Tested with `anthropic` 2.8.0 and Playwright 1.65.
@@ -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,135 @@
1
+ Metadata-Version: 2.5
2
+ Name: specstream-claude-toolset
3
+ Version: 0.1.0
4
+ Summary: A SpecStream driver for the Claude SDK's browser toolset: Claude works in a real browser that SpecStream hosts, at $0.10 an hour.
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-toolset
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-toolset/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: ai-agents,anthropic,browser-toolset,browser-use,claude,headless-browser,playwright,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: playwright<2,>=1.45
26
+ Provides-Extra: test
27
+ Requires-Dist: pytest>=8; extra == 'test'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # SpecStream driver for the Claude browser toolset
31
+
32
+ `SpecStreamBrowser` is a driver for the browser toolset of the Claude SDK
33
+ ([Browser and computer use with the SDK toolsets](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk)).
34
+ Claude navigates, reads, clicks and types in a real browser that SpecStream hosts. You run no browser and no container.
35
+
36
+ A session costs $0.10 an hour, charged by the second. The driver opens it on Claude's first call and releases it on `close()`.
37
+
38
+ A free account comes with $2 of credit and needs no card: [specstream.ai](https://specstream.ai/signup).
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install "specstream-claude-toolset @ git+https://github.com/specstream/specstream-tools#subdirectory=packages/specstream-claude-toolset"
44
+ ```
45
+
46
+ The driver needs Python 3.10 or later, `anthropic` 2.8 or later and `playwright`. It connects Playwright to the hosted browser, so `playwright install` is not needed.
47
+
48
+ Set two keys and the model:
49
+
50
+ ```bash
51
+ export ANTHROPIC_API_KEY=... # https://platform.claude.com
52
+ export SPECSTREAM_API_KEY=... # https://specstream.ai/workspace
53
+ export ANTHROPIC_MODEL=... # a model that supports the browser toolset, listed on the page above
54
+ ```
55
+
56
+ ## Use
57
+
58
+ ```python
59
+ import os
60
+
61
+ from anthropic import Anthropic
62
+ from specstream_claude_toolset import SpecStreamBrowser
63
+
64
+ client = Anthropic()
65
+ with SpecStreamBrowser(allowed_domains=["example.com", "*.iana.org"]) as browser:
66
+ runner = client.beta.messages.tool_runner(
67
+ model=os.environ["ANTHROPIC_MODEL"],
68
+ max_tokens=1024,
69
+ tools=[browser],
70
+ messages=[{"role": "user", "content": "Open example.com and tell me its heading."}],
71
+ )
72
+ for message in runner:
73
+ print(message)
74
+ ```
75
+
76
+ Pass the driver itself as the `tools` entry. The runner never closes a toolset: the `with` block does, and that ends the session and its charge.
77
+
78
+ ## What Claude can do
79
+
80
+ The driver serves 27 members of `browser_toolset_20260801`:
81
+
82
+ | Group | Members |
83
+ | --- | --- |
84
+ | Navigation and capture | `navigate`, `screenshot`, `zoom` |
85
+ | Pointer | `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` |
86
+ | Keyboard and timing | `type`, `key`, `hold_key`, `wait` |
87
+ | Page reading | `read_page`, `find`, `get_page_text` |
88
+ | Forms | `form_input` |
89
+ | Tabs | `new_tab`, `list_tabs`, `switch_tab`, `close_tab` |
90
+
91
+ `javascript_exec`, `file_upload`, `read_console` and `read_network` are sent as disabled.
92
+
93
+ Clicks take a viewport coordinate or a reference such as `ref_4` from `read_page` or `find`. A reference stays the same until the tab navigates; after that the driver answers that it is stale, and Claude reads the page again. A tab that a page opens is reported to Claude, and so is a dialog the driver dismissed.
94
+
95
+ ## Options
96
+
97
+ | Option | Default | Sets |
98
+ | --- | --- | --- |
99
+ | `api_key` | `SPECSTREAM_API_KEY` | Your SpecStream API key |
100
+ | `allowed_domains` | every public host | Hosts the session may open, such as `example.com` or `*.example.com` |
101
+ | `timeout_s` | 300 | The most seconds the session runs (60 to 3,600) |
102
+ | `idle_timeout_s` | 60 | Seconds with no client before the session ends (10 to 600) |
103
+ | `viewport` | `(1280, 720)` | The size of the page and of every screenshot |
104
+ | `block_media` | `False` | `True` skips images, video, audio and fonts |
105
+ | `headless` | `True` | `False` runs the browser with a screen |
106
+ | `metadata` | none | Your own labels for the session |
107
+
108
+ The SDK's own options (`configs`, `confirm`, `url_policy`, `file_policy`, `tool_configs`) pass through unchanged.
109
+ `browser.session` holds the session as SpecStream answered it, with its `id` and `live_url`.
110
+
111
+ ## Safety
112
+
113
+ Read [Run the toolset safely](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#run-the-toolset-safely) before you point Claude at anything that matters.
114
+
115
+ - **Hosts.** The SDK's `url_policy` sees only `navigate` calls. `allowed_domains` is checked by SpecStream on the browser itself, so it also covers links Claude clicks, redirects and the requests a page makes. Set both when you can.
116
+ - **Schemes.** `navigate` opens `http` and `https` only. An address with no scheme gets `https://`.
117
+ - **The host.** The browser runs at SpecStream, not on your machine. It has no access to your files or your network, and it starts signed in to nothing.
118
+ - **Approval.** Pass `confirm` to ask a person before the calls you choose.
119
+
120
+ ## Errors
121
+
122
+ A browser error reaches Claude as one line, and the run goes on. A SpecStream refusal (no credit, a bad key, a session limit) reaches Claude with the API's own message. A missing key raises `SpecStreamError` when you construct the driver.
123
+
124
+ ## Tests
125
+
126
+ ```bash
127
+ pip install -e ".[test]"
128
+ pytest
129
+ ```
130
+
131
+ The tests script the SpecStream API, so they use no key and cost nothing. `tests/test_real_browser.py` drives a local Chromium and is skipped where Playwright has none.
132
+
133
+ ## License
134
+
135
+ BSD 2-Clause. See [LICENSE](LICENSE).
@@ -0,0 +1,106 @@
1
+ # SpecStream driver for the Claude browser toolset
2
+
3
+ `SpecStreamBrowser` is a driver for the browser toolset of the Claude SDK
4
+ ([Browser and computer use with the SDK toolsets](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk)).
5
+ Claude navigates, reads, clicks and types in a real browser that SpecStream hosts. You run no browser and no container.
6
+
7
+ A session costs $0.10 an hour, charged by the second. The driver opens it on Claude's first call and releases it on `close()`.
8
+
9
+ A free account comes with $2 of credit and needs no card: [specstream.ai](https://specstream.ai/signup).
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install "specstream-claude-toolset @ git+https://github.com/specstream/specstream-tools#subdirectory=packages/specstream-claude-toolset"
15
+ ```
16
+
17
+ The driver needs Python 3.10 or later, `anthropic` 2.8 or later and `playwright`. It connects Playwright to the hosted browser, so `playwright install` is not needed.
18
+
19
+ Set two keys and the model:
20
+
21
+ ```bash
22
+ export ANTHROPIC_API_KEY=... # https://platform.claude.com
23
+ export SPECSTREAM_API_KEY=... # https://specstream.ai/workspace
24
+ export ANTHROPIC_MODEL=... # a model that supports the browser toolset, listed on the page above
25
+ ```
26
+
27
+ ## Use
28
+
29
+ ```python
30
+ import os
31
+
32
+ from anthropic import Anthropic
33
+ from specstream_claude_toolset import SpecStreamBrowser
34
+
35
+ client = Anthropic()
36
+ with SpecStreamBrowser(allowed_domains=["example.com", "*.iana.org"]) as browser:
37
+ runner = client.beta.messages.tool_runner(
38
+ model=os.environ["ANTHROPIC_MODEL"],
39
+ max_tokens=1024,
40
+ tools=[browser],
41
+ messages=[{"role": "user", "content": "Open example.com and tell me its heading."}],
42
+ )
43
+ for message in runner:
44
+ print(message)
45
+ ```
46
+
47
+ Pass the driver itself as the `tools` entry. The runner never closes a toolset: the `with` block does, and that ends the session and its charge.
48
+
49
+ ## What Claude can do
50
+
51
+ The driver serves 27 members of `browser_toolset_20260801`:
52
+
53
+ | Group | Members |
54
+ | --- | --- |
55
+ | Navigation and capture | `navigate`, `screenshot`, `zoom` |
56
+ | Pointer | `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` |
57
+ | Keyboard and timing | `type`, `key`, `hold_key`, `wait` |
58
+ | Page reading | `read_page`, `find`, `get_page_text` |
59
+ | Forms | `form_input` |
60
+ | Tabs | `new_tab`, `list_tabs`, `switch_tab`, `close_tab` |
61
+
62
+ `javascript_exec`, `file_upload`, `read_console` and `read_network` are sent as disabled.
63
+
64
+ Clicks take a viewport coordinate or a reference such as `ref_4` from `read_page` or `find`. A reference stays the same until the tab navigates; after that the driver answers that it is stale, and Claude reads the page again. A tab that a page opens is reported to Claude, and so is a dialog the driver dismissed.
65
+
66
+ ## Options
67
+
68
+ | Option | Default | Sets |
69
+ | --- | --- | --- |
70
+ | `api_key` | `SPECSTREAM_API_KEY` | Your SpecStream API key |
71
+ | `allowed_domains` | every public host | Hosts the session may open, such as `example.com` or `*.example.com` |
72
+ | `timeout_s` | 300 | The most seconds the session runs (60 to 3,600) |
73
+ | `idle_timeout_s` | 60 | Seconds with no client before the session ends (10 to 600) |
74
+ | `viewport` | `(1280, 720)` | The size of the page and of every screenshot |
75
+ | `block_media` | `False` | `True` skips images, video, audio and fonts |
76
+ | `headless` | `True` | `False` runs the browser with a screen |
77
+ | `metadata` | none | Your own labels for the session |
78
+
79
+ The SDK's own options (`configs`, `confirm`, `url_policy`, `file_policy`, `tool_configs`) pass through unchanged.
80
+ `browser.session` holds the session as SpecStream answered it, with its `id` and `live_url`.
81
+
82
+ ## Safety
83
+
84
+ Read [Run the toolset safely](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#run-the-toolset-safely) before you point Claude at anything that matters.
85
+
86
+ - **Hosts.** The SDK's `url_policy` sees only `navigate` calls. `allowed_domains` is checked by SpecStream on the browser itself, so it also covers links Claude clicks, redirects and the requests a page makes. Set both when you can.
87
+ - **Schemes.** `navigate` opens `http` and `https` only. An address with no scheme gets `https://`.
88
+ - **The host.** The browser runs at SpecStream, not on your machine. It has no access to your files or your network, and it starts signed in to nothing.
89
+ - **Approval.** Pass `confirm` to ask a person before the calls you choose.
90
+
91
+ ## Errors
92
+
93
+ A browser error reaches Claude as one line, and the run goes on. A SpecStream refusal (no credit, a bad key, a session limit) reaches Claude with the API's own message. A missing key raises `SpecStreamError` when you construct the driver.
94
+
95
+ ## Tests
96
+
97
+ ```bash
98
+ pip install -e ".[test]"
99
+ pytest
100
+ ```
101
+
102
+ The tests script the SpecStream API, so they use no key and cost nothing. `tests/test_real_browser.py` drives a local Chromium and is skipped where Playwright has none.
103
+
104
+ ## License
105
+
106
+ BSD 2-Clause. See [LICENSE](LICENSE).
@@ -0,0 +1,32 @@
1
+ """Claude reads a page in a browser that SpecStream hosts.
2
+
3
+ Needs ANTHROPIC_API_KEY, SPECSTREAM_API_KEY and ANTHROPIC_MODEL (a model that supports the browser
4
+ toolset). The session costs $0.10 an hour, charged by the second,
5
+ and ends when the `with` block does.
6
+ """
7
+
8
+ import os
9
+
10
+ from anthropic import Anthropic
11
+
12
+ from specstream_claude_toolset import SpecStreamBrowser
13
+
14
+
15
+ def main() -> None:
16
+ client = Anthropic()
17
+ # The session opens only these hosts: links, redirects and page requests included.
18
+ with SpecStreamBrowser(allowed_domains=["example.com", "*.iana.org"]) as browser:
19
+ runner = client.beta.messages.tool_runner(
20
+ model=os.environ["ANTHROPIC_MODEL"],
21
+ max_tokens=1024,
22
+ tools=[browser],
23
+ messages=[{"role": "user", "content": "Open example.com and tell me its heading."}],
24
+ )
25
+ for message in runner:
26
+ for block in message.content:
27
+ if block.type == "text":
28
+ print(block.text)
29
+
30
+
31
+ if __name__ == "__main__":
32
+ main()
@@ -0,0 +1,55 @@
1
+ [project]
2
+ name = "specstream-claude-toolset"
3
+ version = "0.1.0"
4
+ description = "A SpecStream driver for the Claude SDK's browser toolset: Claude works in a real browser that SpecStream hosts, at $0.10 an hour."
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", "playwright", "headless-browser", "ai-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
+ dependencies = ["anthropic>=2.8,<3", "playwright>=1.45,<2"]
22
+
23
+ [project.optional-dependencies]
24
+ test = ["pytest>=8"]
25
+
26
+ [project.urls]
27
+ Homepage = "https://specstream.ai"
28
+ Documentation = "https://specstream.ai/docs/api"
29
+ Repository = "https://github.com/specstream/specstream-tools/tree/main/packages/specstream-claude-toolset"
30
+ Issues = "https://github.com/specstream/specstream-tools/issues"
31
+ Changelog = "https://github.com/specstream/specstream-tools/blob/main/packages/specstream-claude-toolset/CHANGELOG.md"
32
+ Pricing = "https://specstream.ai/pricing"
33
+
34
+ [build-system]
35
+ requires = ["hatchling>=1.27,<2"]
36
+ build-backend = "hatchling.build"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["specstream_claude_toolset"]
40
+
41
+ [tool.hatch.build.targets.sdist]
42
+ include = ["specstream_claude_toolset", "examples", "tests", "README.md", "CHANGELOG.md", "LICENSE"]
43
+
44
+ [tool.ruff]
45
+ line-length = 120
46
+
47
+ [tool.ruff.lint]
48
+ select = ["E", "F", "I", "W"]
49
+
50
+ [tool.ruff.lint.per-file-ignores]
51
+ "specstream_claude_toolset/_page.py" = ["E501"]
52
+ "tests/*" = ["E501"]
53
+
54
+ [tool.pytest.ini_options]
55
+ testpaths = ["tests"]
@@ -0,0 +1,7 @@
1
+ """A SpecStream driver for the Claude SDK's browser toolset."""
2
+
3
+ from ._session import SpecStreamError
4
+ from .browser import SpecStreamBrowser
5
+
6
+ __all__ = ["SpecStreamBrowser", "SpecStreamError"]
7
+ __version__ = "0.1.0"
@@ -0,0 +1,234 @@
1
+ """What the driver runs inside a page: the tagged element tree behind `read_page` and `find`, and the
2
+ key names Claude writes turned into the names Playwright presses."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from anthropic.tools import ToolError
7
+
8
+ READ_LIMIT = 50_000
9
+ TEXT_LIMIT = 100_000
10
+ FIND_LIMIT = 20
11
+
12
+ # Walks the DOM and returns {lines: [{depth, role, name, ref}]}. An element keeps its reference for
13
+ # the life of the document (window.__ssRefs), so a second read never renumbers one Claude holds; a
14
+ # navigation makes a new document, and the old references answer "stale".
15
+ TREE_SCRIPT = r"""
16
+ (opts) => {
17
+ const w = window;
18
+ if (!w.__ssRefs) { w.__ssRefs = new Map(); w.__ssRefOf = new WeakMap(); w.__ssNext = 1; }
19
+ const refOf = (el) => {
20
+ let ref = w.__ssRefOf.get(el);
21
+ if (!ref) { ref = 'ref_' + (w.__ssNext++); w.__ssRefOf.set(el, ref); w.__ssRefs.set(ref, el); }
22
+ return ref;
23
+ };
24
+ const INTERACTIVE = new Set(['a', 'button', 'input', 'select', 'textarea', 'summary', 'option']);
25
+ const ROLES = {a: 'link', button: 'button', select: 'combobox', textarea: 'textbox', img: 'image',
26
+ h1: 'heading', h2: 'heading', h3: 'heading', h4: 'heading', h5: 'heading', h6: 'heading',
27
+ nav: 'navigation', main: 'main', form: 'form', table: 'table', li: 'listitem', ul: 'list',
28
+ ol: 'list', summary: 'button', option: 'option', label: 'label', p: 'paragraph', td: 'cell',
29
+ th: 'columnheader', tr: 'row', iframe: 'iframe', dialog: 'dialog'};
30
+ const INPUTS = {checkbox: 'checkbox', radio: 'radio', button: 'button', submit: 'button',
31
+ reset: 'button', range: 'slider', search: 'searchbox', file: 'file input'};
32
+ const roleOf = (el) => {
33
+ const given = el.getAttribute('role');
34
+ if (given) return given;
35
+ const tag = el.tagName.toLowerCase();
36
+ if (tag === 'input') return INPUTS[(el.getAttribute('type') || 'text').toLowerCase()] || 'textbox';
37
+ return ROLES[tag] || null;
38
+ };
39
+ const interactive = (el) => {
40
+ const tag = el.tagName.toLowerCase();
41
+ if (tag === 'a') return el.hasAttribute('href');
42
+ if (INTERACTIVE.has(tag)) return true;
43
+ if (el.hasAttribute('onclick') || el.isContentEditable) return true;
44
+ const tab = el.getAttribute('tabindex');
45
+ if (tab !== null && tab !== '-1') return true;
46
+ const role = el.getAttribute('role');
47
+ return !!role && ['button', 'link', 'tab', 'menuitem', 'checkbox', 'radio', 'switch', 'option',
48
+ 'combobox', 'textbox', 'searchbox', 'slider'].includes(role);
49
+ };
50
+ const clean = (text) => (text || '').replace(/\s+/g, ' ').trim().slice(0, 120);
51
+ const ownText = (el) => {
52
+ let text = '';
53
+ for (const node of el.childNodes) if (node.nodeType === 3) text += node.nodeValue;
54
+ return clean(text);
55
+ };
56
+ const nameOf = (el, role) => {
57
+ const label = el.getAttribute('aria-label') || el.getAttribute('alt') || el.getAttribute('title');
58
+ if (label) return clean(label);
59
+ const tag = el.tagName.toLowerCase();
60
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') {
61
+ if (el.labels && el.labels.length) return clean(el.labels[0].innerText);
62
+ return clean(el.getAttribute('placeholder') || el.getAttribute('name') || el.value);
63
+ }
64
+ if (role === 'link' || role === 'button' || role === 'heading' || role === 'option' ||
65
+ role === 'tab' || role === 'menuitem' || role === 'label') return clean(el.innerText);
66
+ return ownText(el);
67
+ };
68
+ const shown = (el) => {
69
+ const style = getComputedStyle(el);
70
+ if (style.display === 'none' || style.visibility === 'hidden') return 'hidden';
71
+ const box = el.getBoundingClientRect();
72
+ if (box.width === 0 && box.height === 0) return 'empty';
73
+ const inView = box.bottom > 0 && box.right > 0 && box.top < innerHeight && box.left < innerWidth;
74
+ return inView ? 'view' : 'away';
75
+ };
76
+ const SKIP = new Set(['script', 'style', 'noscript', 'template', 'head', 'meta', 'link', 'svg', 'path']);
77
+ const lines = [];
78
+ const walk = (el, depth) => {
79
+ if (lines.length >= opts.maxLines) return;
80
+ const tag = el.tagName.toLowerCase();
81
+ if (SKIP.has(tag)) return;
82
+ const state = shown(el);
83
+ if (state === 'hidden') return;
84
+ let next = depth;
85
+ const role = roleOf(el);
86
+ const active = interactive(el);
87
+ const visible = state === 'view' || (opts.filter === 'all' && state !== 'empty');
88
+ if (visible && (opts.filter === 'interactive' ? active : (role || active))) {
89
+ const name = nameOf(el, role);
90
+ if (active || name || role === 'image' || role === 'iframe') {
91
+ if (depth <= opts.depth) {
92
+ const line = {depth, role: role || 'generic', name, ref: refOf(el)};
93
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') {
94
+ const type = (el.getAttribute('type') || '').toLowerCase();
95
+ if (type === 'checkbox' || type === 'radio') line.value = el.checked ? 'checked' : 'unchecked';
96
+ else if (type !== 'password') line.value = clean(el.value);
97
+ }
98
+ if (tag === 'a') line.href = (el.getAttribute('href') || '').slice(0, 200);
99
+ lines.push(line);
100
+ }
101
+ next = depth + 1;
102
+ }
103
+ }
104
+ if (next > opts.depth) return;
105
+ for (const child of el.children) walk(child, next);
106
+ if (el.shadowRoot) for (const child of el.shadowRoot.children) walk(child, next);
107
+ };
108
+ let root = document.body || document.documentElement;
109
+ if (opts.ref) {
110
+ root = w.__ssRefs.get(opts.ref);
111
+ if (!root || !root.isConnected) return {stale: true, lines: []};
112
+ }
113
+ if (root) walk(root, 1);
114
+ return {stale: false, lines};
115
+ }
116
+ """
117
+
118
+ ELEMENT_SCRIPT = (
119
+ "(ref) => { const el = window.__ssRefs && window.__ssRefs.get(ref); return el && el.isConnected ? el : null; }"
120
+ )
121
+
122
+ TEXT_SCRIPT = r"""
123
+ () => {
124
+ const main = document.querySelector('article, main, [role="main"]');
125
+ const pick = main && main.innerText && main.innerText.trim().length > 200 ? main : document.body;
126
+ return pick ? pick.innerText : '';
127
+ }
128
+ """
129
+
130
+ KIND_SCRIPT = "(el) => ({tag: el.tagName.toLowerCase(), type: (el.getAttribute('type') || '').toLowerCase()})"
131
+
132
+
133
+ def render(lines: list[dict]) -> str:
134
+ """The tagged format of `read_page` and `find`: `button "Search" [ref_4]`, indented by depth."""
135
+ out: list[str] = []
136
+ size = 0
137
+ for index, line in enumerate(lines):
138
+ text = " " * (max(int(line.get("depth", 1)), 1) - 1) + str(line.get("role") or "generic")
139
+ if line.get("name"):
140
+ text += ' "' + str(line["name"]).replace('"', "'") + '"'
141
+ if line.get("value"):
142
+ text += f" value={line['value']!r}"
143
+ if line.get("href"):
144
+ text += f" href={line['href']}"
145
+ text += f" [{line['ref']}]"
146
+ if size + len(text) + 1 > READ_LIMIT:
147
+ left = len(lines) - index
148
+ out.append(
149
+ f"(Cut at 50,000 characters: {left} more elements. Read again with a smaller depth, "
150
+ "or with the ref of the part you need.)"
151
+ )
152
+ break
153
+ out.append(text)
154
+ size += len(text) + 1
155
+ return "\n".join(out)
156
+
157
+
158
+ def _words(text: str) -> list[str]:
159
+ return [word for word in "".join(c.lower() if c.isalnum() else " " for c in text).split() if len(word) > 1]
160
+
161
+
162
+ def match(lines: list[dict], query: str) -> list[dict]:
163
+ """Up to 20 elements whose role, name, value or address shares the most words with the query."""
164
+ wanted = _words(query)
165
+ scored: list[tuple[int, int, dict]] = []
166
+ for index, line in enumerate(lines):
167
+ role = _words(str(line.get("role", "")))
168
+ name = _words(str(line.get("name", "")) + " " + str(line.get("value", "")) + " " + str(line.get("href", "")))
169
+ score = 0
170
+ for word in wanted:
171
+ if word in name:
172
+ score += 3
173
+ elif any(word in part or part in word for part in name if len(part) > 2):
174
+ score += 2
175
+ if word in role or any(word in part for part in role):
176
+ score += 1
177
+ if score:
178
+ scored.append((-score, index, line))
179
+ scored.sort(key=lambda item: (item[0], item[1]))
180
+ return [dict(line, depth=1) for _, _, line in scored[:FIND_LIMIT]]
181
+
182
+
183
+ _KEYS = {
184
+ "ctrl": "Control", "control": "Control", "cmd": "Meta", "command": "Meta", "meta": "Meta",
185
+ "super": "Meta", "win": "Meta", "windows": "Meta", "alt": "Alt", "option": "Alt", "opt": "Alt",
186
+ "shift": "Shift", "enter": "Enter", "return": "Enter", "esc": "Escape", "escape": "Escape",
187
+ "space": "Space", "spacebar": "Space", "tab": "Tab", "backspace": "Backspace", "delete": "Delete",
188
+ "del": "Delete", "insert": "Insert", "home": "Home", "end": "End", "pageup": "PageUp",
189
+ "page_up": "PageUp", "pagedown": "PageDown", "page_down": "PageDown", "up": "ArrowUp",
190
+ "down": "ArrowDown", "left": "ArrowLeft", "right": "ArrowRight", "arrowup": "ArrowUp",
191
+ "arrowdown": "ArrowDown", "arrowleft": "ArrowLeft", "arrowright": "ArrowRight",
192
+ "capslock": "CapsLock", "plus": "+", "minus": "-",
193
+ } # fmt: skip
194
+ MODIFIERS = ("Control", "Meta", "Alt", "Shift")
195
+
196
+
197
+ def key_name(token: str) -> str:
198
+ low = token.strip().lower()
199
+ if not low:
200
+ raise ToolError("An empty key name. Send a key such as Enter, or a chord such as ctrl+a.")
201
+ if low in _KEYS:
202
+ return _KEYS[low]
203
+ if len(low) > 1 and low[0] == "f" and low[1:].isdigit():
204
+ return low.upper()
205
+ return token.strip()
206
+
207
+
208
+ def chord(text: str) -> str:
209
+ """`ctrl+shift+a` as Playwright presses it: `Control+Shift+a`."""
210
+ text = text.strip()
211
+ if text == "+":
212
+ return "+"
213
+ parts = [part for part in text.split("+") if part != ""]
214
+ if text.endswith("++"):
215
+ parts.append("+")
216
+ return "+".join(key_name(part) for part in parts)
217
+
218
+
219
+ def chords(text: str) -> list[str]:
220
+ """A space-separated sequence of keys or chords, in order."""
221
+ found = [chord(part) for part in text.split()]
222
+ if not found:
223
+ raise ToolError("An empty key. Send a key such as Enter, or a chord such as ctrl+a.")
224
+ return found
225
+
226
+
227
+ def modifiers(text: str | None) -> list[str]:
228
+ if not text:
229
+ return []
230
+ names = [key_name(part) for part in text.split("+") if part.strip()]
231
+ for name in names:
232
+ if name not in MODIFIERS:
233
+ raise ToolError(f"{name} is not a modifier key. Use ctrl, shift, alt or cmd, joined with +.")
234
+ return names