specstream-claude-toolset 0.1.0__py3-none-any.whl
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_toolset/__init__.py +7 -0
- specstream_claude_toolset/_page.py +234 -0
- specstream_claude_toolset/_session.py +99 -0
- specstream_claude_toolset/browser.py +598 -0
- specstream_claude_toolset/py.typed +0 -0
- specstream_claude_toolset-0.1.0.dist-info/METADATA +135 -0
- specstream_claude_toolset-0.1.0.dist-info/RECORD +9 -0
- specstream_claude_toolset-0.1.0.dist-info/WHEEL +4 -0
- specstream_claude_toolset-0.1.0.dist-info/licenses/LICENSE +24 -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
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""The SpecStream browser-session calls the driver makes: open a session and end it.
|
|
2
|
+
|
|
3
|
+
Two calls, so the standard library's HTTP client serves them and the package adds no HTTP dependency.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.parse
|
|
12
|
+
import urllib.request
|
|
13
|
+
from typing import Any, Callable
|
|
14
|
+
|
|
15
|
+
BASE_URL = "https://api.specstream.ai"
|
|
16
|
+
USER_AGENT = "specstream-claude-toolset/0.1.0"
|
|
17
|
+
KEY_ENV = "SPECSTREAM_API_KEY"
|
|
18
|
+
# A session's create call waits for a browser to start.
|
|
19
|
+
REQUEST_TIMEOUT_S = 150.0
|
|
20
|
+
|
|
21
|
+
Send = Callable[[str, dict[str, Any], dict[str, str]], "tuple[int, bytes]"]
|
|
22
|
+
"""`(url, json body, headers) -> (status, body)`: one POST. Replace it to use your own HTTP client."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SpecStreamError(Exception):
|
|
26
|
+
"""SpecStream refused a call, or answered with something this driver cannot read."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _post(url: str, body: dict[str, Any], headers: dict[str, str]) -> tuple[int, bytes]:
|
|
30
|
+
request = urllib.request.Request(url, data=json.dumps(body).encode(), headers=headers, method="POST")
|
|
31
|
+
try:
|
|
32
|
+
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_S) as response: # noqa: S310 - https, checked below
|
|
33
|
+
return response.status, response.read()
|
|
34
|
+
except urllib.error.HTTPError as error:
|
|
35
|
+
return error.code, error.read()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _message(raw: bytes) -> str:
|
|
39
|
+
text = raw.decode("utf-8", "replace")
|
|
40
|
+
try:
|
|
41
|
+
body = json.loads(text)
|
|
42
|
+
except ValueError:
|
|
43
|
+
return text[:300]
|
|
44
|
+
if isinstance(body, dict):
|
|
45
|
+
error = body.get("error")
|
|
46
|
+
if isinstance(error, dict) and error.get("message"):
|
|
47
|
+
return str(error["message"])[:300]
|
|
48
|
+
for field in ("message", "detail", "error"):
|
|
49
|
+
if isinstance(body.get(field), str):
|
|
50
|
+
return body[field][:300]
|
|
51
|
+
return text[:300]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class SessionClient:
|
|
55
|
+
"""`POST /v1/browser/sessions` and `POST /v1/browser/sessions/{id}/release`, with an API key."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, api_key: str | None = None, *, base_url: str | None = None, send: Send | None = None) -> None:
|
|
58
|
+
key = (api_key or os.environ.get(KEY_ENV, "")).strip()
|
|
59
|
+
if not key:
|
|
60
|
+
raise SpecStreamError(
|
|
61
|
+
f"No SpecStream API key. Pass api_key, or set {KEY_ENV}. Keys: https://specstream.ai/workspace"
|
|
62
|
+
)
|
|
63
|
+
self._key = key if key.lower().startswith("bearer ") else f"Bearer {key}"
|
|
64
|
+
self._base_url = (base_url or BASE_URL).rstrip("/")
|
|
65
|
+
if urllib.parse.urlsplit(self._base_url).scheme not in ("http", "https"):
|
|
66
|
+
raise SpecStreamError("base_url is an http or https address.")
|
|
67
|
+
self._send = send or _post
|
|
68
|
+
|
|
69
|
+
def _call(self, path: str, body: dict[str, Any]) -> dict[str, Any]:
|
|
70
|
+
headers = {
|
|
71
|
+
"Authorization": self._key,
|
|
72
|
+
"Accept": "application/json",
|
|
73
|
+
"Content-Type": "application/json",
|
|
74
|
+
"User-Agent": USER_AGENT,
|
|
75
|
+
}
|
|
76
|
+
try:
|
|
77
|
+
status, raw = self._send(self._base_url + path, body, headers)
|
|
78
|
+
except SpecStreamError:
|
|
79
|
+
raise
|
|
80
|
+
except Exception as error:
|
|
81
|
+
raise SpecStreamError(f"SpecStream did not answer: {type(error).__name__}") from error
|
|
82
|
+
if status >= 400:
|
|
83
|
+
raise SpecStreamError(f"SpecStream answered {status}: {_message(raw)}")
|
|
84
|
+
try:
|
|
85
|
+
data = json.loads(raw)
|
|
86
|
+
except ValueError as error:
|
|
87
|
+
raise SpecStreamError("SpecStream answered with something that is not JSON.") from error
|
|
88
|
+
if not isinstance(data, dict):
|
|
89
|
+
raise SpecStreamError("SpecStream answered with something that is not a session.")
|
|
90
|
+
return data
|
|
91
|
+
|
|
92
|
+
def open(self, options: dict[str, Any]) -> dict[str, Any]:
|
|
93
|
+
session = self._call("/v1/browser/sessions", options)
|
|
94
|
+
if not session.get("id") or not session.get("connect_url"):
|
|
95
|
+
raise SpecStreamError("SpecStream opened a session without an id or a connect_url.")
|
|
96
|
+
return session
|
|
97
|
+
|
|
98
|
+
def release(self, session_id: str) -> dict[str, Any]:
|
|
99
|
+
return self._call(f"/v1/browser/sessions/{urllib.parse.quote(session_id, safe='')}/release", {})
|
|
@@ -0,0 +1,598 @@
|
|
|
1
|
+
"""`SpecStreamBrowser`: a driver for the Claude SDK's browser toolset on a SpecStream browser session.
|
|
2
|
+
|
|
3
|
+
The driver opens a session with `POST /v1/browser/sessions` on the first call Claude makes, connects
|
|
4
|
+
Playwright to the session's `connect_url` (the Chrome DevTools Protocol) and runs each member of the
|
|
5
|
+
toolset there. `close()` releases the session, which ends its charge.
|
|
6
|
+
|
|
7
|
+
Playwright's synchronous objects belong to the thread that made them, and the SDK may call a toolset
|
|
8
|
+
from more than one thread (the tool runner's early start). So the driver keeps one worker thread and
|
|
9
|
+
runs every browser call on it, in the order the calls arrive.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import base64
|
|
15
|
+
import logging
|
|
16
|
+
import re
|
|
17
|
+
import time
|
|
18
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
19
|
+
from typing import Any, Callable, TypeVar
|
|
20
|
+
|
|
21
|
+
from anthropic.tools import ToolError
|
|
22
|
+
from anthropic.tools.browser import (
|
|
23
|
+
BetaAbstractBrowserToolset20260801,
|
|
24
|
+
BetaBrowserNavigateResult,
|
|
25
|
+
BetaBrowserState,
|
|
26
|
+
BetaDialogDismissed,
|
|
27
|
+
BetaScreenshotResult,
|
|
28
|
+
BetaToolsetCallContext,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
from . import _page
|
|
32
|
+
from ._session import Send, SessionClient, SpecStreamError
|
|
33
|
+
|
|
34
|
+
log = logging.getLogger("specstream_claude_toolset")
|
|
35
|
+
|
|
36
|
+
T = TypeVar("T")
|
|
37
|
+
|
|
38
|
+
_SCHEME = re.compile(r"^[a-z][a-z0-9+.-]*:", re.IGNORECASE)
|
|
39
|
+
_HOST_PORT = re.compile(r"^[^/?#:@]+:\d+(?:[/?#]|$)")
|
|
40
|
+
HISTORY = ("back", "forward", "reload")
|
|
41
|
+
NOTCH_PX = 100
|
|
42
|
+
NAVIGATION_TIMEOUT_MS = 45_000
|
|
43
|
+
ACTION_TIMEOUT_MS = 15_000
|
|
44
|
+
MAX_WAIT_S = 30.0
|
|
45
|
+
# The changes kept between two reports: a page that opens dialogs in a loop does not grow the list.
|
|
46
|
+
MAX_PENDING = 50
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _connect_playwright(connect_url: str) -> tuple[Any, Any]:
|
|
50
|
+
"""Playwright connected to the session over CDP: (the Playwright handle, the browser)."""
|
|
51
|
+
try:
|
|
52
|
+
from playwright.sync_api import sync_playwright
|
|
53
|
+
except ImportError as error: # pragma: no cover - playwright is a declared dependency
|
|
54
|
+
raise SpecStreamError("Playwright is not installed. Run: pip install playwright") from error
|
|
55
|
+
handle = sync_playwright().start()
|
|
56
|
+
try:
|
|
57
|
+
return handle, handle.chromium.connect_over_cdp(connect_url)
|
|
58
|
+
except Exception:
|
|
59
|
+
handle.stop()
|
|
60
|
+
raise
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _short(error: BaseException) -> str:
|
|
64
|
+
"""The first line of a browser error, without Playwright's call log."""
|
|
65
|
+
text = str(error).strip().splitlines()[0] if str(error).strip() else type(error).__name__
|
|
66
|
+
return text[:300]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def web_url(url: str) -> str:
|
|
70
|
+
"""The address `navigate` opens: `https://` for one with no scheme, and only http and https."""
|
|
71
|
+
url = url.strip()
|
|
72
|
+
if not url:
|
|
73
|
+
raise ToolError("An empty URL. Send an http or https address, or back, forward or reload.")
|
|
74
|
+
if not _SCHEME.match(url) or _HOST_PORT.match(url):
|
|
75
|
+
return f"https://{url}"
|
|
76
|
+
scheme = url.split(":", 1)[0].lower()
|
|
77
|
+
if scheme not in ("http", "https"):
|
|
78
|
+
raise ToolError(f"A {scheme}: address is not opened. Send an http or https address.")
|
|
79
|
+
return url
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class SpecStreamBrowser(BetaAbstractBrowserToolset20260801):
|
|
83
|
+
"""The Claude browser toolset on a SpecStream browser session.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
api_key: A SpecStream API key. Without one, the `SPECSTREAM_API_KEY` environment variable.
|
|
87
|
+
allowed_domains: Hosts the session may open, such as `example.com` or `*.example.com`.
|
|
88
|
+
SpecStream refuses every other host for the whole session: links, redirects and the
|
|
89
|
+
requests a page makes, not only `navigate`. Empty allows every public host.
|
|
90
|
+
timeout_s: The most seconds the session runs (60 to 3,600; default 300).
|
|
91
|
+
idle_timeout_s: The session ends after this many seconds with no client (10 to 600).
|
|
92
|
+
viewport: `(width, height)` of the page and of every screenshot. Default 1280 by 720.
|
|
93
|
+
block_media: True skips images, video, audio and fonts.
|
|
94
|
+
headless: False runs the browser with a screen.
|
|
95
|
+
metadata: Your own labels for the session.
|
|
96
|
+
base_url: The API's address, for a test server.
|
|
97
|
+
send: Your own `(url, body, headers) -> (status, bytes)` for the two session calls.
|
|
98
|
+
configs, confirm, url_policy, file_policy, tool_configs: the SDK's own options, passed on.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
def __init__(
|
|
102
|
+
self,
|
|
103
|
+
api_key: str | None = None,
|
|
104
|
+
*,
|
|
105
|
+
allowed_domains: list[str] | None = None,
|
|
106
|
+
timeout_s: int = 300,
|
|
107
|
+
idle_timeout_s: int = 60,
|
|
108
|
+
viewport: tuple[int, int] = (1280, 720),
|
|
109
|
+
block_media: bool = False,
|
|
110
|
+
headless: bool = True,
|
|
111
|
+
metadata: dict[str, Any] | None = None,
|
|
112
|
+
base_url: str | None = None,
|
|
113
|
+
send: Send | None = None,
|
|
114
|
+
connect: Callable[[str], tuple[Any, Any]] | None = None,
|
|
115
|
+
**options: Any,
|
|
116
|
+
) -> None:
|
|
117
|
+
super().__init__(**options)
|
|
118
|
+
self._client = SessionClient(api_key, base_url=base_url, send=send)
|
|
119
|
+
self._create: dict[str, Any] = {
|
|
120
|
+
"timeout_s": timeout_s,
|
|
121
|
+
"idle_timeout_s": idle_timeout_s,
|
|
122
|
+
"viewport": {"width": int(viewport[0]), "height": int(viewport[1])},
|
|
123
|
+
}
|
|
124
|
+
if allowed_domains:
|
|
125
|
+
self._create["allowed_domains"] = list(allowed_domains)
|
|
126
|
+
if block_media:
|
|
127
|
+
self._create["block_media"] = True
|
|
128
|
+
if not headless:
|
|
129
|
+
self._create["headless"] = False
|
|
130
|
+
if metadata:
|
|
131
|
+
self._create["metadata"] = dict(metadata)
|
|
132
|
+
self._viewport = (int(viewport[0]), int(viewport[1]))
|
|
133
|
+
self._connect = connect or _connect_playwright
|
|
134
|
+
self._worker = ThreadPoolExecutor(max_workers=1, thread_name_prefix="specstream-browser")
|
|
135
|
+
self._session: dict[str, Any] | None = None
|
|
136
|
+
self._handle: Any = None
|
|
137
|
+
self._browser: Any = None
|
|
138
|
+
self._context: Any = None
|
|
139
|
+
self._tabs: dict[str, Any] = {}
|
|
140
|
+
self._next_tab = 1
|
|
141
|
+
self._active: str | None = None
|
|
142
|
+
self._pending: list[Any] = []
|
|
143
|
+
self._watched: set[int] = set()
|
|
144
|
+
self._done = False
|
|
145
|
+
|
|
146
|
+
# --- The session ---------------------------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def session(self) -> dict[str, Any] | None:
|
|
150
|
+
"""The session as SpecStream answered it (`id`, `live_url`, `expires_at`), once one is open."""
|
|
151
|
+
return self._session
|
|
152
|
+
|
|
153
|
+
def _on_worker(self, call: Callable[[], T]) -> T:
|
|
154
|
+
return self._worker.submit(call).result()
|
|
155
|
+
|
|
156
|
+
def _run(self, call: Callable[[], T]) -> T:
|
|
157
|
+
"""Run a browser call on the worker thread; a browser error reaches Claude as one line."""
|
|
158
|
+
|
|
159
|
+
def guarded() -> T:
|
|
160
|
+
self._open()
|
|
161
|
+
try:
|
|
162
|
+
return call()
|
|
163
|
+
except ToolError:
|
|
164
|
+
raise
|
|
165
|
+
except SpecStreamError:
|
|
166
|
+
raise
|
|
167
|
+
except Exception as error:
|
|
168
|
+
raise ToolError(_short(error)) from error
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
return self._on_worker(guarded)
|
|
172
|
+
except SpecStreamError as error:
|
|
173
|
+
raise ToolError(str(error)) from error
|
|
174
|
+
|
|
175
|
+
def _open(self) -> None:
|
|
176
|
+
if self._context is not None:
|
|
177
|
+
return
|
|
178
|
+
if self._done:
|
|
179
|
+
raise ToolError("The browser is closed.")
|
|
180
|
+
if self._session is None:
|
|
181
|
+
self._session = self._client.open(self._create)
|
|
182
|
+
log.debug("SpecStream browser session %s is open", self._session.get("id"))
|
|
183
|
+
handle, browser = self._connect(str(self._session["connect_url"]))
|
|
184
|
+
self._handle, self._browser = handle, browser
|
|
185
|
+
contexts = list(browser.contexts)
|
|
186
|
+
self._context = contexts[0] if contexts else browser.new_context()
|
|
187
|
+
if not list(self._context.pages):
|
|
188
|
+
self._context.new_page()
|
|
189
|
+
self._sync_tabs(report=False)
|
|
190
|
+
|
|
191
|
+
def close(self) -> None:
|
|
192
|
+
"""End the toolset, then the browser and the session. Safe to call twice."""
|
|
193
|
+
super().close() # first, so no call is still using the browser when it closes
|
|
194
|
+
if self._done:
|
|
195
|
+
return
|
|
196
|
+
self._done = True
|
|
197
|
+
|
|
198
|
+
def end() -> None:
|
|
199
|
+
for step in (
|
|
200
|
+
lambda: self._browser.close() if self._browser is not None else None,
|
|
201
|
+
lambda: self._handle.stop() if self._handle is not None else None,
|
|
202
|
+
lambda: self._client.release(str(self._session["id"])) if self._session else None,
|
|
203
|
+
):
|
|
204
|
+
try:
|
|
205
|
+
step()
|
|
206
|
+
except Exception as error: # the session also ends by itself at its timeout
|
|
207
|
+
log.debug("closing the SpecStream browser: %s", _short(error))
|
|
208
|
+
self._context = None
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
self._on_worker(end)
|
|
212
|
+
finally:
|
|
213
|
+
self._worker.shutdown(wait=False)
|
|
214
|
+
|
|
215
|
+
# --- Tabs and state --------------------------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
def _remember(self, change: Any) -> None:
|
|
218
|
+
if len(self._pending) < MAX_PENDING:
|
|
219
|
+
self._pending.append(change)
|
|
220
|
+
|
|
221
|
+
def _watch(self, page: Any) -> None:
|
|
222
|
+
if id(page) in self._watched:
|
|
223
|
+
return
|
|
224
|
+
self._watched.add(id(page))
|
|
225
|
+
|
|
226
|
+
def dismiss(dialog: Any) -> None:
|
|
227
|
+
kind, message = str(dialog.type), str(dialog.message)[:500]
|
|
228
|
+
try:
|
|
229
|
+
dialog.dismiss()
|
|
230
|
+
except Exception:
|
|
231
|
+
pass
|
|
232
|
+
self._remember(BetaDialogDismissed(kind=kind, message=message))
|
|
233
|
+
|
|
234
|
+
try:
|
|
235
|
+
page.on("dialog", dismiss)
|
|
236
|
+
except Exception as error:
|
|
237
|
+
log.debug("no dialog watch on a tab: %s", _short(error))
|
|
238
|
+
|
|
239
|
+
def _sync_tabs(self, *, report: bool = True) -> None:
|
|
240
|
+
"""Match the tab ids to the pages the browser has now: a page a click opened gets an id."""
|
|
241
|
+
pages = [page for page in self._context.pages if not page.is_closed()]
|
|
242
|
+
self._tabs = {tab: page for tab, page in self._tabs.items() if any(page is p for p in pages)}
|
|
243
|
+
for page in pages:
|
|
244
|
+
if not any(page is known for known in self._tabs.values()):
|
|
245
|
+
tab_id = f"tab-{self._next_tab}"
|
|
246
|
+
self._next_tab += 1
|
|
247
|
+
self._tabs[tab_id] = page
|
|
248
|
+
self._watch(page)
|
|
249
|
+
if report:
|
|
250
|
+
self._remember({"type": "tab_opened", "tab_id": tab_id})
|
|
251
|
+
self._active = tab_id # a tab the page opened comes to the front, as in a browser
|
|
252
|
+
if self._active not in self._tabs:
|
|
253
|
+
self._active = next(reversed(self._tabs), None)
|
|
254
|
+
|
|
255
|
+
def _page(self, tab_id: str | None) -> Any:
|
|
256
|
+
self._sync_tabs()
|
|
257
|
+
wanted = tab_id or self._active
|
|
258
|
+
if wanted is None:
|
|
259
|
+
raise ToolError("No tab is open. Open one with new_tab.")
|
|
260
|
+
page = self._tabs.get(wanted)
|
|
261
|
+
if page is None:
|
|
262
|
+
raise ToolError(f"No tab {wanted!r}. Open tabs: {', '.join(self._tabs) or 'none'}.")
|
|
263
|
+
return page
|
|
264
|
+
|
|
265
|
+
def _entry(self, tab_id: str) -> dict[str, Any]:
|
|
266
|
+
page = self._tabs[tab_id]
|
|
267
|
+
try:
|
|
268
|
+
title = page.title()
|
|
269
|
+
except Exception:
|
|
270
|
+
title = ""
|
|
271
|
+
entry: dict[str, Any] = {"tab_id": tab_id, "title": title, "url": page.url}
|
|
272
|
+
if tab_id == self._active:
|
|
273
|
+
entry["active"] = True
|
|
274
|
+
return entry
|
|
275
|
+
|
|
276
|
+
def _browser_state(self, context: BetaToolsetCallContext) -> BetaBrowserState:
|
|
277
|
+
def report() -> BetaBrowserState:
|
|
278
|
+
if self._context is None:
|
|
279
|
+
return BetaBrowserState(tabs=[])
|
|
280
|
+
self._sync_tabs()
|
|
281
|
+
changes, self._pending = self._pending, []
|
|
282
|
+
open_now = set(self._tabs)
|
|
283
|
+
changes = [
|
|
284
|
+
change
|
|
285
|
+
for change in changes
|
|
286
|
+
if not (isinstance(change, dict) and change.get("type") == "tab_opened") or change["tab_id"] in open_now
|
|
287
|
+
]
|
|
288
|
+
return BetaBrowserState(tabs=[self._entry(tab) for tab in self._tabs], state_changes=changes)
|
|
289
|
+
|
|
290
|
+
return self._on_worker(report)
|
|
291
|
+
|
|
292
|
+
def new_tab(self, context: BetaToolsetCallContext, input: Any) -> Any:
|
|
293
|
+
def act() -> dict[str, Any]:
|
|
294
|
+
self._sync_tabs()
|
|
295
|
+
page = self._context.new_page()
|
|
296
|
+
self._sync_tabs(report=False)
|
|
297
|
+
tab_id = next(tab for tab, known in self._tabs.items() if known is page)
|
|
298
|
+
self._remember({"type": "tab_opened", "tab_id": tab_id})
|
|
299
|
+
self._active = tab_id
|
|
300
|
+
return self._entry(tab_id)
|
|
301
|
+
|
|
302
|
+
return self._run(act)
|
|
303
|
+
|
|
304
|
+
def list_tabs(self, context: BetaToolsetCallContext, input: Any) -> Any:
|
|
305
|
+
def act() -> list[dict[str, Any]]:
|
|
306
|
+
self._sync_tabs()
|
|
307
|
+
return [self._entry(tab) for tab in self._tabs]
|
|
308
|
+
|
|
309
|
+
return self._run(act)
|
|
310
|
+
|
|
311
|
+
def switch_tab(self, context: BetaToolsetCallContext, input: Any) -> Any:
|
|
312
|
+
def act() -> dict[str, Any]:
|
|
313
|
+
page = self._page(input.tab_id)
|
|
314
|
+
self._active = input.tab_id
|
|
315
|
+
try:
|
|
316
|
+
page.bring_to_front()
|
|
317
|
+
except Exception as error:
|
|
318
|
+
log.debug("bring_to_front: %s", _short(error))
|
|
319
|
+
return self._entry(input.tab_id)
|
|
320
|
+
|
|
321
|
+
return self._run(act)
|
|
322
|
+
|
|
323
|
+
def close_tab(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
324
|
+
def act() -> None:
|
|
325
|
+
self._page(input.tab_id).close()
|
|
326
|
+
self._sync_tabs()
|
|
327
|
+
|
|
328
|
+
return self._run(act)
|
|
329
|
+
|
|
330
|
+
# --- Navigation and capture ------------------------------------------------------------------
|
|
331
|
+
|
|
332
|
+
def navigate(self, context: BetaToolsetCallContext, input: Any) -> BetaBrowserNavigateResult:
|
|
333
|
+
def act() -> BetaBrowserNavigateResult:
|
|
334
|
+
page = self._page(input.tab_id)
|
|
335
|
+
page.set_default_timeout(ACTION_TIMEOUT_MS)
|
|
336
|
+
word = input.url.strip().lower()
|
|
337
|
+
options = {"wait_until": "domcontentloaded", "timeout": NAVIGATION_TIMEOUT_MS}
|
|
338
|
+
if word == "back":
|
|
339
|
+
response = page.go_back(**options)
|
|
340
|
+
elif word == "forward":
|
|
341
|
+
response = page.go_forward(**options)
|
|
342
|
+
elif word == "reload":
|
|
343
|
+
response = page.reload(**options)
|
|
344
|
+
else:
|
|
345
|
+
response = page.goto(web_url(input.url), **options)
|
|
346
|
+
status = response.status if response is not None else None
|
|
347
|
+
return BetaBrowserNavigateResult(url=page.url, status=status, title=page.title())
|
|
348
|
+
|
|
349
|
+
return self._run(act)
|
|
350
|
+
|
|
351
|
+
def screenshot(self, context: BetaToolsetCallContext, input: Any) -> BetaScreenshotResult:
|
|
352
|
+
def act() -> BetaScreenshotResult:
|
|
353
|
+
data = self._page(input.tab_id).screenshot(type="png", scale="css")
|
|
354
|
+
return BetaScreenshotResult(data=base64.b64encode(data).decode("ascii"), media_type="image/png")
|
|
355
|
+
|
|
356
|
+
return self._run(act)
|
|
357
|
+
|
|
358
|
+
def zoom(self, context: BetaToolsetCallContext, input: Any) -> BetaScreenshotResult:
|
|
359
|
+
def act() -> BetaScreenshotResult:
|
|
360
|
+
region = list(input.region)
|
|
361
|
+
if len(region) != 4:
|
|
362
|
+
raise ToolError("region is [x0, y0, x1, y1] in viewport pixels.")
|
|
363
|
+
x0, y0, x1, y1 = (int(value) for value in region)
|
|
364
|
+
width, height = self._viewport
|
|
365
|
+
x0, x1 = max(0, min(x0, x1)), min(width, max(x0, x1))
|
|
366
|
+
y0, y1 = max(0, min(y0, y1)), min(height, max(y0, y1))
|
|
367
|
+
if x1 - x0 < 1 or y1 - y0 < 1:
|
|
368
|
+
raise ToolError(f"region is empty inside the {width} by {height} viewport.")
|
|
369
|
+
data = self._page(input.tab_id).screenshot(
|
|
370
|
+
type="png", scale="device", clip={"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0}
|
|
371
|
+
)
|
|
372
|
+
return BetaScreenshotResult(data=base64.b64encode(data).decode("ascii"), media_type="image/png")
|
|
373
|
+
|
|
374
|
+
return self._run(act)
|
|
375
|
+
|
|
376
|
+
# --- Pointer ---------------------------------------------------------------------------------
|
|
377
|
+
|
|
378
|
+
def _point(self, target: Any) -> tuple[int, int]:
|
|
379
|
+
if getattr(target, "type", None) != "coordinate":
|
|
380
|
+
raise ToolError("This member takes a coordinate target: {type: coordinate, x, y}.")
|
|
381
|
+
x, y = int(target.x), int(target.y)
|
|
382
|
+
width, height = self._viewport
|
|
383
|
+
if not (0 <= x < width and 0 <= y < height):
|
|
384
|
+
raise ToolError(f"({x}, {y}) is outside the {width} by {height} viewport.")
|
|
385
|
+
return x, y
|
|
386
|
+
|
|
387
|
+
def _element(self, page: Any, target: Any) -> Any:
|
|
388
|
+
ref = getattr(target, "ref", None)
|
|
389
|
+
if getattr(target, "type", None) != "ref" or not ref:
|
|
390
|
+
raise ToolError("This member takes an element reference: {type: ref, ref}.")
|
|
391
|
+
element = page.evaluate_handle(_page.ELEMENT_SCRIPT, ref).as_element()
|
|
392
|
+
if element is None:
|
|
393
|
+
raise ToolError(
|
|
394
|
+
f"{ref} is stale or not found on the current page. Re-read the page to get fresh references."
|
|
395
|
+
)
|
|
396
|
+
return element
|
|
397
|
+
|
|
398
|
+
def _click(self, input: Any, *, button: str = "left", count: int = 1) -> None:
|
|
399
|
+
def act() -> None:
|
|
400
|
+
page = self._page(input.tab_id)
|
|
401
|
+
held = _page.modifiers(getattr(input, "modifiers", None))
|
|
402
|
+
if input.target.type == "ref":
|
|
403
|
+
self._element(page, input.target).click(
|
|
404
|
+
button=button, click_count=count, modifiers=held or None, timeout=ACTION_TIMEOUT_MS
|
|
405
|
+
)
|
|
406
|
+
return
|
|
407
|
+
x, y = self._point(input.target)
|
|
408
|
+
for name in held:
|
|
409
|
+
page.keyboard.down(name)
|
|
410
|
+
try:
|
|
411
|
+
page.mouse.click(x, y, button=button, click_count=count)
|
|
412
|
+
finally:
|
|
413
|
+
for name in reversed(held):
|
|
414
|
+
page.keyboard.up(name)
|
|
415
|
+
|
|
416
|
+
self._run(act)
|
|
417
|
+
|
|
418
|
+
def left_click(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
419
|
+
self._click(input)
|
|
420
|
+
|
|
421
|
+
def right_click(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
422
|
+
self._click(input, button="right")
|
|
423
|
+
|
|
424
|
+
def middle_click(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
425
|
+
self._click(input, button="middle")
|
|
426
|
+
|
|
427
|
+
def double_click(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
428
|
+
self._click(input, count=2)
|
|
429
|
+
|
|
430
|
+
def triple_click(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
431
|
+
self._click(input, count=3)
|
|
432
|
+
|
|
433
|
+
def hover(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
434
|
+
def act() -> None:
|
|
435
|
+
page = self._page(input.tab_id)
|
|
436
|
+
if input.target.type == "ref":
|
|
437
|
+
self._element(page, input.target).hover(timeout=ACTION_TIMEOUT_MS)
|
|
438
|
+
else:
|
|
439
|
+
page.mouse.move(*self._point(input.target))
|
|
440
|
+
|
|
441
|
+
self._run(act)
|
|
442
|
+
|
|
443
|
+
def mouse_move(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
444
|
+
self._run(lambda: self._page(input.tab_id).mouse.move(*self._point(input.target)))
|
|
445
|
+
|
|
446
|
+
def left_mouse_down(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
447
|
+
def act() -> None:
|
|
448
|
+
page = self._page(input.tab_id)
|
|
449
|
+
page.mouse.move(*self._point(input.target))
|
|
450
|
+
page.mouse.down()
|
|
451
|
+
|
|
452
|
+
self._run(act)
|
|
453
|
+
|
|
454
|
+
def left_mouse_up(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
455
|
+
def act() -> None:
|
|
456
|
+
page = self._page(input.tab_id)
|
|
457
|
+
page.mouse.move(*self._point(input.target))
|
|
458
|
+
page.mouse.up()
|
|
459
|
+
|
|
460
|
+
self._run(act)
|
|
461
|
+
|
|
462
|
+
def left_click_drag(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
463
|
+
def act() -> None:
|
|
464
|
+
page = self._page(input.tab_id)
|
|
465
|
+
start, end = self._point(input.from_), self._point(input.target)
|
|
466
|
+
page.mouse.move(*start)
|
|
467
|
+
page.mouse.down()
|
|
468
|
+
try:
|
|
469
|
+
page.mouse.move(*end, steps=10)
|
|
470
|
+
finally:
|
|
471
|
+
page.mouse.up()
|
|
472
|
+
|
|
473
|
+
self._run(act)
|
|
474
|
+
|
|
475
|
+
def scroll(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
476
|
+
def act() -> None:
|
|
477
|
+
page = self._page(input.tab_id)
|
|
478
|
+
notches = input.scroll_amount if input.scroll_amount is not None else 3
|
|
479
|
+
distance = max(1, min(int(notches), 10)) * NOTCH_PX
|
|
480
|
+
dx, dy = {"up": (0, -distance), "down": (0, distance), "left": (-distance, 0), "right": (distance, 0)}[
|
|
481
|
+
str(input.scroll_direction)
|
|
482
|
+
]
|
|
483
|
+
page.mouse.move(*self._point(input.target))
|
|
484
|
+
page.mouse.wheel(dx, dy)
|
|
485
|
+
|
|
486
|
+
self._run(act)
|
|
487
|
+
|
|
488
|
+
def scroll_to(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
489
|
+
def act() -> None:
|
|
490
|
+
page = self._page(input.tab_id)
|
|
491
|
+
self._element(page, input.target).scroll_into_view_if_needed(timeout=ACTION_TIMEOUT_MS)
|
|
492
|
+
|
|
493
|
+
self._run(act)
|
|
494
|
+
|
|
495
|
+
# --- Keyboard and timing ---------------------------------------------------------------------
|
|
496
|
+
|
|
497
|
+
def type(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
498
|
+
self._run(lambda: self._page(input.tab_id).keyboard.type(input.text))
|
|
499
|
+
|
|
500
|
+
def key(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
501
|
+
def act() -> None:
|
|
502
|
+
page = self._page(input.tab_id)
|
|
503
|
+
keys = _page.chords(input.text)
|
|
504
|
+
repeat = max(1, min(int(input.repeat or 1), 100))
|
|
505
|
+
for _ in range(repeat):
|
|
506
|
+
for name in keys:
|
|
507
|
+
page.keyboard.press(name)
|
|
508
|
+
|
|
509
|
+
self._run(act)
|
|
510
|
+
|
|
511
|
+
def hold_key(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
512
|
+
def act() -> None:
|
|
513
|
+
page = self._page(input.tab_id)
|
|
514
|
+
names = _page.chord(input.text).split("+") if input.text.strip() != "+" else ["+"]
|
|
515
|
+
names = [name for name in names if name]
|
|
516
|
+
if not names:
|
|
517
|
+
raise ToolError("An empty key. Send a key such as Shift, or a chord such as ctrl+a.")
|
|
518
|
+
for name in names:
|
|
519
|
+
page.keyboard.down(name)
|
|
520
|
+
try:
|
|
521
|
+
time.sleep(max(0.0, min(float(input.duration), MAX_WAIT_S)))
|
|
522
|
+
finally:
|
|
523
|
+
for name in reversed(names):
|
|
524
|
+
page.keyboard.up(name)
|
|
525
|
+
|
|
526
|
+
self._run(act)
|
|
527
|
+
|
|
528
|
+
def wait(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
529
|
+
def act() -> None:
|
|
530
|
+
self._page(input.tab_id)
|
|
531
|
+
time.sleep(max(0.0, min(float(input.duration), MAX_WAIT_S)))
|
|
532
|
+
|
|
533
|
+
self._run(act)
|
|
534
|
+
|
|
535
|
+
# --- Reading ---------------------------------------------------------------------------------
|
|
536
|
+
|
|
537
|
+
def _tree(self, page: Any, *, filter: str, depth: int, ref: str | None) -> list[dict]:
|
|
538
|
+
answer = page.evaluate(
|
|
539
|
+
_page.TREE_SCRIPT, {"filter": filter, "depth": max(1, int(depth)), "ref": ref, "maxLines": 5_000}
|
|
540
|
+
)
|
|
541
|
+
if answer.get("stale"):
|
|
542
|
+
raise ToolError(
|
|
543
|
+
f"{ref} is stale or not found on the current page. Re-read the page to get fresh references."
|
|
544
|
+
)
|
|
545
|
+
return list(answer.get("lines") or [])
|
|
546
|
+
|
|
547
|
+
def read_page(self, context: BetaToolsetCallContext, input: Any) -> str:
|
|
548
|
+
def act() -> str:
|
|
549
|
+
lines = self._tree(
|
|
550
|
+
self._page(input.tab_id),
|
|
551
|
+
filter=str(input.filter) if input.filter else "visible",
|
|
552
|
+
depth=input.depth if input.depth is not None else 15,
|
|
553
|
+
ref=input.ref,
|
|
554
|
+
)
|
|
555
|
+
return _page.render(lines)
|
|
556
|
+
|
|
557
|
+
return self._run(act)
|
|
558
|
+
|
|
559
|
+
def find(self, context: BetaToolsetCallContext, input: Any) -> str:
|
|
560
|
+
def act() -> str:
|
|
561
|
+
lines = self._tree(self._page(input.tab_id), filter="all", depth=1_000, ref=None)
|
|
562
|
+
found = _page.match(lines, input.query)
|
|
563
|
+
if not found:
|
|
564
|
+
return f"No element matches {input.query!r}. Try other words, or read_page."
|
|
565
|
+
return _page.render(found)
|
|
566
|
+
|
|
567
|
+
return self._run(act)
|
|
568
|
+
|
|
569
|
+
def get_page_text(self, context: BetaToolsetCallContext, input: Any) -> str:
|
|
570
|
+
def act() -> str:
|
|
571
|
+
text = str(self._page(input.tab_id).evaluate(_page.TEXT_SCRIPT) or "")
|
|
572
|
+
text = re.sub(r"\n{3,}", "\n\n", text).strip()
|
|
573
|
+
if len(text) > _page.TEXT_LIMIT:
|
|
574
|
+
text = text[: _page.TEXT_LIMIT] + "\n(Cut at 100,000 characters.)"
|
|
575
|
+
return text
|
|
576
|
+
|
|
577
|
+
return self._run(act)
|
|
578
|
+
|
|
579
|
+
def form_input(self, context: BetaToolsetCallContext, input: Any) -> None:
|
|
580
|
+
def act() -> None:
|
|
581
|
+
page = self._page(input.tab_id)
|
|
582
|
+
element = self._element(page, input.target)
|
|
583
|
+
kind = element.evaluate(_page.KIND_SCRIPT)
|
|
584
|
+
value = input.value
|
|
585
|
+
if kind["tag"] == "input" and kind["type"] in ("checkbox", "radio"):
|
|
586
|
+
if not isinstance(value, bool):
|
|
587
|
+
raise ToolError("A checkbox or radio takes true or false.")
|
|
588
|
+
element.set_checked(value, timeout=ACTION_TIMEOUT_MS)
|
|
589
|
+
elif kind["tag"] == "select":
|
|
590
|
+
try:
|
|
591
|
+
element.select_option(value=str(value), timeout=2_000)
|
|
592
|
+
except Exception:
|
|
593
|
+
element.select_option(label=str(value), timeout=ACTION_TIMEOUT_MS)
|
|
594
|
+
else:
|
|
595
|
+
text = ("true" if value else "false") if isinstance(value, bool) else str(value)
|
|
596
|
+
element.fill(text, timeout=ACTION_TIMEOUT_MS)
|
|
597
|
+
|
|
598
|
+
self._run(act)
|
|
File without changes
|
|
@@ -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,9 @@
|
|
|
1
|
+
specstream_claude_toolset/__init__.py,sha256=sJ3HBjOxZDzHnowCWvwu92lxB4MeI3cMZJXNSViFtTo,216
|
|
2
|
+
specstream_claude_toolset/_page.py,sha256=szxptfqjEBo3BENtdsOcva5VF1zuFAJJ4f0Y_hgFXXI,10281
|
|
3
|
+
specstream_claude_toolset/_session.py,sha256=Ts0-zCyQz217jWi25PEcfNhdqzwaZJMLd21PdhwjrNE,4111
|
|
4
|
+
specstream_claude_toolset/browser.py,sha256=nVkwswfZ2Rmc6T6aXFgoERZkbscnD7CzI2Z7to88juU,24908
|
|
5
|
+
specstream_claude_toolset/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
specstream_claude_toolset-0.1.0.dist-info/METADATA,sha256=c-XHUf-fwsizRruFIX9e4jmkiq79IrHpXZ4SRoLEExE,6504
|
|
7
|
+
specstream_claude_toolset-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
specstream_claude_toolset-0.1.0.dist-info/licenses/LICENSE,sha256=zU9kLtPXsMuOe0KBBT4KOuv-tWI7wt1I9kqtDw9uFRY,1303
|
|
9
|
+
specstream_claude_toolset-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|