specstream-claude-browser 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.
@@ -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,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,8 @@
1
+ specstream_claude_browser/__init__.py,sha256=ohfKPyULFn_GOq0BRUn6mzrOHRUPcY-JtQNmTseWua8,372
2
+ specstream_claude_browser/_client.py,sha256=XczPqSQQVBX1-5X8f4RnxaFcOxDgMw4tuyrY8kWYD6Y,5721
3
+ specstream_claude_browser/_driver.py,sha256=UuPVdIDmcuqF4fsB7KI9HI5xY8LpNLuuFj7HXF076Hs,18627
4
+ specstream_claude_browser/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ specstream_claude_browser-0.1.0.dist-info/METADATA,sha256=5QSG25qCceOESq4Z30DStUfOqMLQsrrvzEXsHGmDtGM,6500
6
+ specstream_claude_browser-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ specstream_claude_browser-0.1.0.dist-info/licenses/LICENSE,sha256=zU9kLtPXsMuOe0KBBT4KOuv-tWI7wt1I9kqtDw9uFRY,1303
8
+ specstream_claude_browser-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.