specstream-client 1.4.0__tar.gz → 1.5.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.
Files changed (23) hide show
  1. {specstream_client-1.4.0 → specstream_client-1.5.0}/PKG-INFO +48 -2
  2. {specstream_client-1.4.0 → specstream_client-1.5.0}/README.md +47 -1
  3. {specstream_client-1.4.0 → specstream_client-1.5.0}/pyproject.toml +1 -1
  4. {specstream_client-1.4.0 → specstream_client-1.5.0}/specstream_client/__init__.py +1 -1
  5. specstream_client-1.5.0/specstream_client/browser.py +224 -0
  6. {specstream_client-1.4.0 → specstream_client-1.5.0}/specstream_client/client.py +3 -2
  7. specstream_client-1.5.0/tests/test_browser.py +229 -0
  8. {specstream_client-1.4.0 → specstream_client-1.5.0}/.gitignore +0 -0
  9. {specstream_client-1.4.0 → specstream_client-1.5.0}/LICENSE +0 -0
  10. {specstream_client-1.4.0 → specstream_client-1.5.0}/specstream_client/__main__.py +0 -0
  11. {specstream_client-1.4.0 → specstream_client-1.5.0}/specstream_client/authorization.py +0 -0
  12. {specstream_client-1.4.0 → specstream_client-1.5.0}/specstream_client/cli.py +0 -0
  13. {specstream_client-1.4.0 → specstream_client-1.5.0}/specstream_client/families.py +0 -0
  14. {specstream_client-1.4.0 → specstream_client-1.5.0}/specstream_client/lifecycle_commands.py +0 -0
  15. {specstream_client-1.4.0 → specstream_client-1.5.0}/specstream_client/monitors.py +0 -0
  16. {specstream_client-1.4.0 → specstream_client-1.5.0}/specstream_client/py.typed +0 -0
  17. {specstream_client-1.4.0 → specstream_client-1.5.0}/tests/__init__.py +0 -0
  18. {specstream_client-1.4.0 → specstream_client-1.5.0}/tests/test_cli.py +0 -0
  19. {specstream_client-1.4.0 → specstream_client-1.5.0}/tests/test_client.py +0 -0
  20. {specstream_client-1.4.0 → specstream_client-1.5.0}/tests/test_convergence.py +0 -0
  21. {specstream_client-1.4.0 → specstream_client-1.5.0}/tests/test_http_boundary.py +0 -0
  22. {specstream_client-1.4.0 → specstream_client-1.5.0}/tests/test_m16_exports.py +0 -0
  23. {specstream_client-1.4.0 → specstream_client-1.5.0}/tests/test_monitors.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: specstream-client
3
- Version: 1.4.0
3
+ Version: 1.5.0
4
4
  Summary: Python client for building lead lists and company lists from the live web. Every match comes with its source, priced before it runs.
5
5
  Project-URL: Homepage, https://specstream.ai
6
6
  Project-URL: Documentation, https://specstream.ai/docs/sdk
@@ -42,7 +42,7 @@ The client has no dependencies and needs Python 3.12 or newer. It uses the same
42
42
  pip install specstream-client
43
43
  ```
44
44
 
45
- The package installs the import name `specstream` and the command `specstream`.
45
+ The package installs the import name `specstream_client` and the command `specstream`.
46
46
 
47
47
  Create an API key under **Agents & API** in your SpecStream workspace and keep it in the environment:
48
48
 
@@ -217,6 +217,52 @@ verify_webhook(
217
217
  event = json.loads(raw_body)
218
218
  ```
219
219
 
220
+ ## Drive a real browser
221
+
222
+ For a page that needs a real browser, `open_browser` starts a Chromium on SpecStream.
223
+ You drive it one step at a time, and `browser_read` returns the page's text as it stands after its JavaScript ran.
224
+
225
+ ```python
226
+ with client.browser(timeout_s=120) as session:
227
+ client.browser_navigate(session["id"], "https://example.com")
228
+ print(client.browser_read(session["id"])) # Markdown; "text" for plain text
229
+ ```
230
+
231
+ A session costs $0.10 an hour, charged by the second, plus $1 per 1,000 steps (0.1¢ a step).
232
+ An open session is charged until `timeout_s` passes, so close it: the `with` block does, also when a step fails.
233
+
234
+ | Call | What it does |
235
+ | --- | --- |
236
+ | `open_browser(timeout_s=..., allowed_domains=[...], ...)` | Opens a browser and returns the session, with its `id` and `connect_url` |
237
+ | `browser_navigate(session_id, url)` | Opens the address |
238
+ | `browser_read(session_id, format="markdown")` | The page's text, in Markdown or plain text |
239
+ | `browser_snapshot(session_id)` | The page's links, buttons and fields, each with a reference |
240
+ | `browser_step(session_id, tool, arguments)` | Any step of Playwright MCP by its name: `browser_click`, `browser_type`, `browser_take_screenshot` and the others |
241
+ | `browser_session(session_id)`, `browser_sessions(status="running")` | One session or the account's sessions, with seconds, steps and charge. Free |
242
+ | `browser_downloads(session_id)` | The files the browser downloaded, as the bytes of one zip, until ten minutes after the session ends. Free |
243
+ | `close_browser(session_id)` | Ends the session and returns it with `charged_usd` |
244
+
245
+ A page the browser may not open (a private address, a site that opted out, a host outside `allowed_domains`) is not an exception for a step: the answer's `error` holds the code `blocked` and the reason. `browser_read` raises `SpecstreamError` in that case.
246
+
247
+ Your own Playwright, Puppeteer, browser-use or Stagehand code can drive the same browser over the Chrome DevTools Protocol:
248
+
249
+ ```python
250
+ from playwright.sync_api import sync_playwright
251
+
252
+ session = client.open_browser(timeout_s=300, idempotency_key="job-42")
253
+ try:
254
+ with sync_playwright() as p:
255
+ browser = p.chromium.connect_over_cdp(session["connect_url"])
256
+ context = browser.contexts[0] if browser.contexts else browser.new_context()
257
+ page = context.new_page()
258
+ page.goto("https://example.com")
259
+ print(page.title())
260
+ finally:
261
+ print(client.close_browser(session["id"])["charged_usd"])
262
+ ```
263
+
264
+ With `idempotency_key`, the same call again answers with the same session and opens no second one.
265
+
220
266
  ## More than a first request
221
267
 
222
268
  - `quote_capacity_work` also prices `extend` (more results), `add_facts` and `refresh` (a recheck, at half price) on a finished run. Pass the original `parent_find_id`.
@@ -15,7 +15,7 @@ The client has no dependencies and needs Python 3.12 or newer. It uses the same
15
15
  pip install specstream-client
16
16
  ```
17
17
 
18
- The package installs the import name `specstream` and the command `specstream`.
18
+ The package installs the import name `specstream_client` and the command `specstream`.
19
19
 
20
20
  Create an API key under **Agents & API** in your SpecStream workspace and keep it in the environment:
21
21
 
@@ -190,6 +190,52 @@ verify_webhook(
190
190
  event = json.loads(raw_body)
191
191
  ```
192
192
 
193
+ ## Drive a real browser
194
+
195
+ For a page that needs a real browser, `open_browser` starts a Chromium on SpecStream.
196
+ You drive it one step at a time, and `browser_read` returns the page's text as it stands after its JavaScript ran.
197
+
198
+ ```python
199
+ with client.browser(timeout_s=120) as session:
200
+ client.browser_navigate(session["id"], "https://example.com")
201
+ print(client.browser_read(session["id"])) # Markdown; "text" for plain text
202
+ ```
203
+
204
+ A session costs $0.10 an hour, charged by the second, plus $1 per 1,000 steps (0.1¢ a step).
205
+ An open session is charged until `timeout_s` passes, so close it: the `with` block does, also when a step fails.
206
+
207
+ | Call | What it does |
208
+ | --- | --- |
209
+ | `open_browser(timeout_s=..., allowed_domains=[...], ...)` | Opens a browser and returns the session, with its `id` and `connect_url` |
210
+ | `browser_navigate(session_id, url)` | Opens the address |
211
+ | `browser_read(session_id, format="markdown")` | The page's text, in Markdown or plain text |
212
+ | `browser_snapshot(session_id)` | The page's links, buttons and fields, each with a reference |
213
+ | `browser_step(session_id, tool, arguments)` | Any step of Playwright MCP by its name: `browser_click`, `browser_type`, `browser_take_screenshot` and the others |
214
+ | `browser_session(session_id)`, `browser_sessions(status="running")` | One session or the account's sessions, with seconds, steps and charge. Free |
215
+ | `browser_downloads(session_id)` | The files the browser downloaded, as the bytes of one zip, until ten minutes after the session ends. Free |
216
+ | `close_browser(session_id)` | Ends the session and returns it with `charged_usd` |
217
+
218
+ A page the browser may not open (a private address, a site that opted out, a host outside `allowed_domains`) is not an exception for a step: the answer's `error` holds the code `blocked` and the reason. `browser_read` raises `SpecstreamError` in that case.
219
+
220
+ Your own Playwright, Puppeteer, browser-use or Stagehand code can drive the same browser over the Chrome DevTools Protocol:
221
+
222
+ ```python
223
+ from playwright.sync_api import sync_playwright
224
+
225
+ session = client.open_browser(timeout_s=300, idempotency_key="job-42")
226
+ try:
227
+ with sync_playwright() as p:
228
+ browser = p.chromium.connect_over_cdp(session["connect_url"])
229
+ context = browser.contexts[0] if browser.contexts else browser.new_context()
230
+ page = context.new_page()
231
+ page.goto("https://example.com")
232
+ print(page.title())
233
+ finally:
234
+ print(client.close_browser(session["id"])["charged_usd"])
235
+ ```
236
+
237
+ With `idempotency_key`, the same call again answers with the same session and opens no second one.
238
+
193
239
  ## More than a first request
194
240
 
195
241
  - `quote_capacity_work` also prices `extend` (more results), `add_facts` and `refresh` (a recheck, at half price) on a finished run. Pass the original `parent_find_id`.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "specstream-client"
3
- version = "1.4.0"
3
+ version = "1.5.0"
4
4
  description = "Python client for building lead lists and company lists from the live web. Every match comes with its source, priced before it runs."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -13,4 +13,4 @@ __all__ = [
13
13
  "assert_family",
14
14
  "verify_webhook",
15
15
  ]
16
- __version__ = "1.4.0"
16
+ __version__ = "1.5.0"
@@ -0,0 +1,224 @@
1
+ """Browser sessions: a real Chromium on SpecStream that your code drives.
2
+
3
+ A session is charged for each second it runs and for each step, until it is
4
+ closed or its timeout_s passes. Drive it step by step with browser_step (the
5
+ tools of Playwright MCP by name, plus browser_read for the page's text), or
6
+ connect Playwright, Puppeteer, browser-use or Stagehand to its connect_url over
7
+ the Chrome DevTools Protocol.
8
+ Client includes BrowserMixin, so these are methods of Client.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import copy
14
+ import urllib.error
15
+ import urllib.request
16
+ from collections.abc import Callable, Iterator
17
+ from contextlib import contextmanager
18
+ from typing import Any
19
+ from urllib.parse import quote as quote_path
20
+ from urllib.parse import urlencode, urljoin
21
+
22
+ SESSIONS_PATH = "/v1/browser/sessions"
23
+ SESSION_STATES = ("starting", "running", "ended")
24
+ READ_FORMATS = ("markdown", "text")
25
+ IDEMPOTENCY_KEY_MAX = 128
26
+
27
+
28
+ class BrowserMixin:
29
+ """Browser session calls of Client. They need Client's _request, _headers and _opener."""
30
+
31
+ _request: Callable[..., dict[str, Any]]
32
+ _headers: Callable[[], dict[str, str]]
33
+ _opener: Callable[..., Any]
34
+ base_url: str
35
+ timeout: float
36
+
37
+ def open_browser(
38
+ self,
39
+ *,
40
+ timeout_s: int | None = None,
41
+ idle_timeout_s: int | None = None,
42
+ keep_alive: bool | None = None,
43
+ headless: bool | None = None,
44
+ viewport: dict[str, int] | None = None,
45
+ allowed_domains: list[str] | None = None,
46
+ block_media: bool | None = None,
47
+ metadata: dict[str, Any] | None = None,
48
+ idempotency_key: str | None = None,
49
+ ) -> dict[str, Any]:
50
+ """POST /v1/browser/sessions: open a browser and return the running session.
51
+
52
+ The session holds its id, its connect_url (the Chrome DevTools Protocol
53
+ address) and its price. Charges start now: call close_browser when you
54
+ are done. timeout_s is the most seconds the session runs (60 to 3,600,
55
+ default 300). allowed_domains limits the hosts the browser may open.
56
+ A setting you leave out takes the API's default. With idempotency_key,
57
+ the same call again answers with the same session and opens no second one.
58
+ """
59
+ settings = {
60
+ "timeout_s": timeout_s,
61
+ "idle_timeout_s": idle_timeout_s,
62
+ "keep_alive": keep_alive,
63
+ "headless": headless,
64
+ "viewport": viewport,
65
+ "allowed_domains": allowed_domains,
66
+ "block_media": block_media,
67
+ "metadata": metadata,
68
+ }
69
+ body = {name: value for name, value in settings.items() if value is not None}
70
+ if idempotency_key is None:
71
+ return self._request("POST", SESSIONS_PATH, body)
72
+ key = str(idempotency_key).strip()
73
+ if not key or len(key) > IDEMPOTENCY_KEY_MAX:
74
+ raise ValueError(f"idempotency_key must hold 1 to {IDEMPOTENCY_KEY_MAX} characters")
75
+ # A copy of the client whose requests carry the key: _request stays as it is,
76
+ # with its errors and its one retry after Retry-After.
77
+ keyed = copy.copy(self)
78
+ send = self._opener
79
+
80
+ def with_key(request: urllib.request.Request, timeout: float) -> Any:
81
+ request.add_header("Idempotency-Key", key)
82
+ return send(request, timeout)
83
+
84
+ keyed._opener = with_key
85
+ return keyed._request("POST", SESSIONS_PATH, body)
86
+
87
+ def browser_sessions(
88
+ self,
89
+ *,
90
+ status: str | None = None,
91
+ limit: int | None = None,
92
+ cursor: str | None = None,
93
+ ) -> dict[str, Any]:
94
+ """GET /v1/browser/sessions: the account's sessions, newest first.
95
+
96
+ Returns {"sessions": [...], "next_cursor": ...}. status is "starting",
97
+ "running" or "ended". Pass next_cursor as cursor for the next page.
98
+ """
99
+ if status is not None and status not in SESSION_STATES:
100
+ raise ValueError('status must be "starting", "running" or "ended"')
101
+ query = {
102
+ name: value
103
+ for name, value in (("status", status), ("limit", limit), ("cursor", cursor))
104
+ if value is not None
105
+ }
106
+ path = SESSIONS_PATH + (f"?{urlencode(query)}" if query else "")
107
+ return self._request("GET", path, None)
108
+
109
+ def browser_session(self, session_id: str) -> dict[str, Any]:
110
+ """GET /v1/browser/sessions/{id}: status, why it ended, seconds, steps and charge."""
111
+ return self._request("GET", _session_path(session_id), None)
112
+
113
+ def close_browser(self, session_id: str) -> dict[str, Any]:
114
+ """POST /v1/browser/sessions/{id}/release: end the session and settle its charge.
115
+
116
+ Returns the ended session with charged_usd. A repeat call answers the same.
117
+ """
118
+ return self._request("POST", _session_path(session_id) + "/release", {})
119
+
120
+ def browser_step(
121
+ self, session_id: str, tool: str, arguments: dict[str, Any] | None = None
122
+ ) -> dict[str, Any]:
123
+ """POST /v1/browser/sessions/{id}/actions: run one step in the browser.
124
+
125
+ tool is a Playwright MCP tool by its name (browser_navigate,
126
+ browser_snapshot, browser_click, browser_type, browser_take_screenshot
127
+ and the others) or browser_read. Returns the step's result, the page's
128
+ url and title, and price_usd. A page the browser may not open does not
129
+ raise: the answer's error holds code "blocked" and the reason.
130
+ """
131
+ name = str(tool or "").strip()
132
+ if not name.startswith("browser_"):
133
+ raise ValueError('tool is a step name that starts with "browser_"')
134
+ body = {"tool": name, "arguments": dict(arguments or {})}
135
+ return self._request("POST", _session_path(session_id) + "/actions", body)
136
+
137
+ def browser_navigate(self, session_id: str, url: str) -> dict[str, Any]:
138
+ """One step: open the address in the session's browser."""
139
+ address = str(url or "").strip()
140
+ if not address:
141
+ raise ValueError("Give the url to open")
142
+ return self.browser_step(session_id, "browser_navigate", {"url": address})
143
+
144
+ def browser_snapshot(self, session_id: str) -> dict[str, Any]:
145
+ """One step: the page's links, buttons and fields, each with a reference to act on."""
146
+ return self.browser_step(session_id, "browser_snapshot")
147
+
148
+ def browser_read(self, session_id: str, format: str = "markdown") -> str:
149
+ """One step: the page's text as it stands after its JavaScript ran.
150
+
151
+ format is "markdown" or "text". Raises SpecstreamError when the step
152
+ answers with an error, for example a page the browser may not open.
153
+ """
154
+ if format not in READ_FORMATS:
155
+ raise ValueError('format must be "markdown" or "text"')
156
+ step = self.browser_step(session_id, "browser_read", {"format": format})
157
+ failure = step.get("error")
158
+ if failure:
159
+ from specstream_client.client import SpecstreamError
160
+
161
+ message = failure.get("message") if isinstance(failure, dict) else None
162
+ raise SpecstreamError(f"browser_read failed: {message or failure}", body=step)
163
+ return step_text(step)
164
+
165
+ def browser_downloads(self, session_id: str) -> bytes:
166
+ """GET /v1/browser/sessions/{id}/downloads: the files the browser downloaded, as one zip.
167
+
168
+ They are kept until ten minutes after the session ends.
169
+ """
170
+ from specstream_client.client import SpecstreamError
171
+
172
+ path = _session_path(session_id) + "/downloads"
173
+ request = urllib.request.Request(
174
+ urljoin(self.base_url, path.lstrip("/")), method="GET", headers=self._headers()
175
+ )
176
+ try:
177
+ with self._opener(request, self.timeout) as response:
178
+ status = getattr(response, "status", 200)
179
+ content = response.read()
180
+ except urllib.error.HTTPError as exc:
181
+ raise SpecstreamError(
182
+ f"GET {path} failed with HTTP {exc.code}", status=exc.code
183
+ ) from exc
184
+ except (urllib.error.URLError, OSError) as exc:
185
+ raise SpecstreamError(f"GET {path} transport failed") from exc
186
+ if not 200 <= status < 300:
187
+ raise SpecstreamError(f"GET {path} failed with HTTP {status}", status=status)
188
+ return bytes(content)
189
+
190
+ @contextmanager
191
+ def browser(self, **settings: Any) -> Iterator[dict[str, Any]]:
192
+ """Open a browser for a with block and close it at the end, also after an error.
193
+
194
+ Takes the arguments of open_browser and yields the session.
195
+ """
196
+ session = self.open_browser(**settings)
197
+ try:
198
+ yield session
199
+ finally:
200
+ self.close_browser(session["id"])
201
+
202
+
203
+ def step_text(step: dict[str, Any]) -> str:
204
+ """The text parts of a step's result, joined."""
205
+ parts = step.get("result")
206
+ if not isinstance(parts, list):
207
+ return ""
208
+ return "\n".join(
209
+ part["text"]
210
+ for part in parts
211
+ if isinstance(part, dict)
212
+ and part.get("type") == "text"
213
+ and isinstance(part.get("text"), str)
214
+ )
215
+
216
+
217
+ def _session_path(session_id: str) -> str:
218
+ value = str(session_id or "").strip()
219
+ if not value:
220
+ raise ValueError("Give the session's id, from open_browser")
221
+ return f"{SESSIONS_PATH}/{quote_path(value, safe='')}"
222
+
223
+
224
+ __all__ = ["BrowserMixin", "step_text"]
@@ -15,11 +15,12 @@ from urllib.parse import quote as quote_path
15
15
  from urllib.parse import urlencode, urljoin, urlsplit
16
16
 
17
17
  from specstream_client.authorization import require_work_authorization
18
+ from specstream_client.browser import BrowserMixin
18
19
  from specstream_client.families import FAMILIES
19
20
  from specstream_client.monitors import MonitorsMixin
20
21
 
21
22
  DEFAULT_BASE_URL = "https://api.specstream.ai"
22
- USER_AGENT = "specstream-python/1.4.0"
23
+ USER_AGENT = "specstream-python/1.5.0"
23
24
 
24
25
  OpenFn = Callable[[urllib.request.Request, float], Any]
25
26
 
@@ -74,7 +75,7 @@ class SpecstreamError(RuntimeError):
74
75
  self.details = dict(error["details"])
75
76
 
76
77
 
77
- class Client(MonitorsMixin):
78
+ class Client(MonitorsMixin, BrowserMixin):
78
79
  """Typed HTTP client for finder.cross-source.v1 public operations."""
79
80
 
80
81
  def __init__(
@@ -0,0 +1,229 @@
1
+ """Browser session calls: open, step, read, list, downloads and close, on a scripted API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import json
7
+ import urllib.error
8
+ from typing import Any
9
+ from urllib.parse import parse_qs, urlsplit
10
+
11
+ import pytest
12
+ from specstream_client import Client, SpecstreamError
13
+
14
+ SESSIONS = "/v1/browser/sessions"
15
+
16
+
17
+ class _Response:
18
+ def __init__(self, content: bytes, status: int = 200) -> None:
19
+ self.status = status
20
+ self._buf = io.BytesIO(content)
21
+
22
+ def read(self) -> bytes:
23
+ return self._buf.read()
24
+
25
+ def __enter__(self):
26
+ return self
27
+
28
+ def __exit__(self, *args):
29
+ return None
30
+
31
+
32
+ class _Api:
33
+ """Scripted API: answers by (method, path) and records each request."""
34
+
35
+ def __init__(self, answers: dict[tuple[str, str], Any]) -> None:
36
+ self.answers = answers
37
+ self.calls: list[tuple[str, str, dict[str, list[str]], Any]] = []
38
+ self.headers: list[dict[str, str]] = []
39
+
40
+ def __call__(self, request, timeout):
41
+ parts = urlsplit(request.full_url)
42
+ body = json.loads(request.data) if request.data else None
43
+ self.calls.append((request.get_method(), parts.path, parse_qs(parts.query), body))
44
+ self.headers.append({name.lower(): value for name, value in request.header_items()})
45
+ answer = self.answers[(request.get_method(), parts.path)]
46
+ if isinstance(answer, Exception):
47
+ raise answer
48
+ if isinstance(answer, bytes):
49
+ return _Response(answer)
50
+ status = 201 if (request.get_method(), parts.path) == ("POST", SESSIONS) else 200
51
+ return _Response(json.dumps({"data": answer}).encode(), status)
52
+
53
+
54
+ def _session(**extra: Any) -> dict[str, Any]:
55
+ data = {
56
+ "id": "bs_1",
57
+ "status": "running",
58
+ "connect_url": "wss://api.example.test/v1/browser/connect/bs_1?token=fixture",
59
+ "actions_url": "https://api.example.test/v1/browser/sessions/bs_1/actions",
60
+ "timeout_s": 300,
61
+ "seconds": 0,
62
+ "actions": 0,
63
+ "charged_usd": 0.0,
64
+ "price": {"per_second_usd": 0.1 / 3600, "per_action_usd": 0.001},
65
+ }
66
+ data.update(extra)
67
+ return data
68
+
69
+
70
+ def _step(text: str = "", **extra: Any) -> dict[str, Any]:
71
+ data = {
72
+ "result": [{"type": "text", "text": text}] if text else [],
73
+ "error": None,
74
+ "url": "https://example.com/",
75
+ "title": "Example Domain",
76
+ "took_ms": 12,
77
+ "price_usd": 0.001,
78
+ }
79
+ data.update(extra)
80
+ return data
81
+
82
+
83
+ def _client(api: _Api) -> Client:
84
+ return Client("fixture-key", base_url="https://api.example.test", opener=api)
85
+
86
+
87
+ def test_open_browser_sends_only_the_settings_given_and_returns_the_session():
88
+ api = _Api({("POST", SESSIONS): _session(timeout_s=120)})
89
+ session = _client(api).open_browser(timeout_s=120, allowed_domains=["example.com"])
90
+
91
+ assert session["id"] == "bs_1"
92
+ assert session["connect_url"].startswith("wss://")
93
+ assert api.calls == [
94
+ ("POST", SESSIONS, {}, {"timeout_s": 120, "allowed_domains": ["example.com"]})
95
+ ]
96
+ assert api.headers[0]["authorization"] == "Bearer fixture-key"
97
+ assert "idempotency-key" not in api.headers[0]
98
+
99
+
100
+ def test_open_browser_with_no_settings_sends_an_empty_object():
101
+ api = _Api({("POST", SESSIONS): _session()})
102
+ _client(api).open_browser()
103
+ assert api.calls[0][3] == {}
104
+
105
+
106
+ def test_idempotency_key_goes_in_the_header_of_that_call_only():
107
+ api = _Api({("POST", SESSIONS): _session(), ("GET", f"{SESSIONS}/bs_1"): _session()})
108
+ client = _client(api)
109
+ client.open_browser(idempotency_key="job-42")
110
+ client.browser_session("bs_1")
111
+
112
+ assert api.headers[0]["idempotency-key"] == "job-42"
113
+ assert api.calls[0][3] == {}
114
+ assert "idempotency-key" not in api.headers[1]
115
+
116
+
117
+ @pytest.mark.parametrize("key", ["", " ", "k" * 129])
118
+ def test_a_bad_idempotency_key_sends_nothing(key):
119
+ api = _Api({})
120
+ with pytest.raises(ValueError, match="idempotency_key"):
121
+ _client(api).open_browser(idempotency_key=key)
122
+ assert api.calls == []
123
+
124
+
125
+ def test_steps_post_the_tool_and_its_arguments_to_the_actions_route():
126
+ api = _Api({("POST", f"{SESSIONS}/bs_1/actions"): _step("- link \"More\" [ref=e2]")})
127
+ client = _client(api)
128
+ client.browser_navigate("bs_1", "https://example.com")
129
+ client.browser_snapshot("bs_1")
130
+ clicked = client.browser_step("bs_1", "browser_click", {"element": "More", "ref": "e2"})
131
+
132
+ assert [call[3] for call in api.calls] == [
133
+ {"tool": "browser_navigate", "arguments": {"url": "https://example.com"}},
134
+ {"tool": "browser_snapshot", "arguments": {}},
135
+ {"tool": "browser_click", "arguments": {"element": "More", "ref": "e2"}},
136
+ ]
137
+ assert clicked["price_usd"] == 0.001
138
+
139
+
140
+ def test_browser_read_returns_the_text_of_the_page():
141
+ api = _Api({("POST", f"{SESSIONS}/bs_1/actions"): _step("# Example Domain")})
142
+ text = _client(api).browser_read("bs_1", "text")
143
+
144
+ assert text == "# Example Domain"
145
+ assert api.calls[0][3] == {"tool": "browser_read", "arguments": {"format": "text"}}
146
+
147
+
148
+ def test_a_blocked_page_is_an_answer_for_a_step_and_an_error_for_a_read():
149
+ blocked = _step(
150
+ error={"code": "blocked", "reason": "robots", "message": "The site's robots file refuses"}
151
+ )
152
+ api = _Api({("POST", f"{SESSIONS}/bs_1/actions"): blocked})
153
+ client = _client(api)
154
+
155
+ step = client.browser_navigate("bs_1", "https://example.com")
156
+ assert step["error"]["code"] == "blocked"
157
+ with pytest.raises(SpecstreamError, match="robots file refuses") as caught:
158
+ client.browser_read("bs_1")
159
+ assert caught.value.body["error"]["reason"] == "robots"
160
+
161
+
162
+ def test_bad_arguments_send_nothing():
163
+ api = _Api({})
164
+ client = _client(api)
165
+ with pytest.raises(ValueError):
166
+ client.browser_step("bs_1", "click")
167
+ with pytest.raises(ValueError):
168
+ client.browser_step("", "browser_click")
169
+ with pytest.raises(ValueError):
170
+ client.browser_navigate("bs_1", " ")
171
+ with pytest.raises(ValueError):
172
+ client.browser_read("bs_1", "html")
173
+ with pytest.raises(ValueError):
174
+ client.browser_sessions(status="open")
175
+ assert api.calls == []
176
+
177
+
178
+ def test_browser_sessions_lists_with_its_filters_in_the_query():
179
+ api = _Api({("GET", SESSIONS): {"sessions": [_session()], "next_cursor": "c2"}})
180
+ client = _client(api)
181
+ page = client.browser_sessions(status="running", limit=5, cursor="c1")
182
+ client.browser_sessions()
183
+
184
+ assert page["next_cursor"] == "c2"
185
+ assert api.calls[0][2] == {"status": ["running"], "limit": ["5"], "cursor": ["c1"]}
186
+ assert api.calls[1][2] == {}
187
+
188
+
189
+ def test_close_browser_releases_the_session_and_the_id_is_escaped():
190
+ ended = _session(status="ended", ended_reason="released", charged_usd=0.0032)
191
+ api = _Api({("POST", f"{SESSIONS}/bs%2F1/release"): ended})
192
+ closed = _client(api).close_browser("bs/1")
193
+
194
+ assert closed["charged_usd"] == 0.0032
195
+ assert api.calls == [("POST", f"{SESSIONS}/bs%2F1/release", {}, {})]
196
+
197
+
198
+ def test_browser_downloads_returns_the_zip_bytes():
199
+ api = _Api({("GET", f"{SESSIONS}/bs_1/downloads"): b"PK\x03\x04zip"})
200
+ assert _client(api).browser_downloads("bs_1") == b"PK\x03\x04zip"
201
+ assert api.headers[0]["authorization"] == "Bearer fixture-key"
202
+
203
+
204
+ def test_browser_downloads_of_an_unknown_session_raises_with_the_status():
205
+ missing = urllib.error.HTTPError("https://api.example.test", 404, "Not Found", None, None)
206
+ api = _Api({("GET", f"{SESSIONS}/bs_9/downloads"): missing})
207
+ with pytest.raises(SpecstreamError) as caught:
208
+ _client(api).browser_downloads("bs_9")
209
+ assert caught.value.status == 404
210
+
211
+
212
+ def test_the_with_block_closes_the_browser_after_an_error():
213
+ api = _Api(
214
+ {
215
+ ("POST", SESSIONS): _session(),
216
+ ("POST", f"{SESSIONS}/bs_1/release"): _session(status="ended"),
217
+ }
218
+ )
219
+ client = _client(api)
220
+ with pytest.raises(RuntimeError, match="the caller's own"):
221
+ with client.browser(timeout_s=60) as session:
222
+ assert session["id"] == "bs_1"
223
+ raise RuntimeError("the caller's own")
224
+
225
+ assert [call[:2] for call in api.calls] == [
226
+ ("POST", SESSIONS),
227
+ ("POST", f"{SESSIONS}/bs_1/release"),
228
+ ]
229
+ assert api.calls[0][3] == {"timeout_s": 60}