waybound 0.2.2__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.
waybound/mcp_server.py ADDED
@@ -0,0 +1,343 @@
1
+ """Zero-dependency stdio Model Context Protocol (MCP) server for `waybound`.
2
+
3
+ Exposes semantic, out-of-band browser automation tools to AI agents
4
+ (Antigravity, Claude Code, Cursor, Codex) over JSON-RPC 2.0 stdio.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import json
11
+ import os
12
+ import sys
13
+ from typing import TYPE_CHECKING
14
+
15
+ from waybound.session import BackendName, LaunchOptions, launch
16
+ from waybound.types import Role
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Callable
20
+
21
+ from waybound.client import Page
22
+ from waybound.session import Session
23
+
24
+ PROTOCOL_VERSION = "2024-11-05"
25
+
26
+ TOOLS: list[dict[str, object]] = [
27
+ {
28
+ "name": "waybound_goto",
29
+ "description": "Navigate the active browser tab to an http:// or https:// URL.",
30
+ "inputSchema": {
31
+ "type": "object",
32
+ "properties": {"url": {"type": "string"}},
33
+ "required": ["url"],
34
+ },
35
+ },
36
+ {
37
+ "name": "waybound_url",
38
+ "description": "Return the active tab URL.",
39
+ "inputSchema": {"type": "object", "properties": {}},
40
+ },
41
+ {
42
+ "name": "waybound_snapshot",
43
+ "description": "Return the live semantic accessibility tree of the current page.",
44
+ "inputSchema": {"type": "object", "properties": {}},
45
+ },
46
+ {
47
+ "name": "waybound_click",
48
+ "description": "Click an element matching semantic role and/or accessible name.",
49
+ "inputSchema": {
50
+ "type": "object",
51
+ "properties": {
52
+ "role": {"type": "string"},
53
+ "name": {"type": "string"},
54
+ "nth": {"type": "integer", "default": 0},
55
+ },
56
+ },
57
+ },
58
+ {
59
+ "name": "waybound_fill",
60
+ "description": "Focus an input element and type text via native OS keyboard events.",
61
+ "inputSchema": {
62
+ "type": "object",
63
+ "properties": {
64
+ "role": {"type": "string", "default": "text_box"},
65
+ "name": {"type": "string"},
66
+ "text": {"type": "string"},
67
+ "nth": {"type": "integer", "default": 0},
68
+ },
69
+ "required": ["text"],
70
+ },
71
+ },
72
+ {
73
+ "name": "waybound_scroll",
74
+ "description": "Scroll the viewport by (delta_x, delta_y) pixels.",
75
+ "inputSchema": {
76
+ "type": "object",
77
+ "properties": {
78
+ "delta_x": {"type": "number", "default": 0.0},
79
+ "delta_y": {"type": "number", "default": -300.0},
80
+ },
81
+ },
82
+ },
83
+ {
84
+ "name": "waybound_screenshot",
85
+ "description": "Capture a native OS PNG screenshot of the browser window.",
86
+ "inputSchema": {"type": "object", "properties": {}},
87
+ },
88
+ {
89
+ "name": "waybound_wait_for_response",
90
+ "description": "Wait for a passively decrypted HTTP response matching url_contains.",
91
+ "inputSchema": {
92
+ "type": "object",
93
+ "properties": {
94
+ "url_contains": {"type": "string"},
95
+ "timeout_ms": {"type": "integer", "default": 10000},
96
+ },
97
+ "required": ["url_contains"],
98
+ },
99
+ },
100
+ ]
101
+
102
+
103
+ def _parse_role(raw: object) -> Role | None:
104
+ if not isinstance(raw, str) or not raw:
105
+ return None
106
+ try:
107
+ return Role(raw)
108
+ except ValueError:
109
+ # Fail loudly: silently dropping an unknown role would turn the call into a
110
+ # different, broader locator than the one the caller asked for.
111
+ valid = ", ".join(sorted(r.value for r in Role))
112
+ msg = f"unknown role {raw!r} (expected one of: {valid})"
113
+ raise ValueError(msg) from None
114
+
115
+
116
+ def _as_int(raw: object, default: int) -> int:
117
+ return raw if isinstance(raw, int) and not isinstance(raw, bool) else default
118
+
119
+
120
+ def _as_float(raw: object, default: float) -> float:
121
+ if isinstance(raw, int | float) and not isinstance(raw, bool):
122
+ return float(raw)
123
+ return default
124
+
125
+
126
+ def _text_result(text: str) -> dict[str, object]:
127
+ return {"content": [{"type": "text", "text": text}]}
128
+
129
+
130
+ def _tool_goto(page: Page, args: dict[str, object]) -> dict[str, object]:
131
+ url = str(args.get("url", ""))
132
+ page.goto(url)
133
+ return _text_result(f"Navigated to {url}")
134
+
135
+
136
+ def _tool_url(page: Page, _args: dict[str, object]) -> dict[str, object]:
137
+ return _text_result(page.url() or "")
138
+
139
+
140
+ def _tool_snapshot(page: Page, _args: dict[str, object]) -> dict[str, object]:
141
+ nodes = [
142
+ {
143
+ "id": n.id,
144
+ "role": n.role.value,
145
+ "name": n.name,
146
+ "value": n.value,
147
+ "bounds": {
148
+ "x": n.bounds.x,
149
+ "y": n.bounds.y,
150
+ "width": n.bounds.width,
151
+ "height": n.bounds.height,
152
+ },
153
+ }
154
+ for n in page.snapshot_tree()
155
+ ]
156
+ return _text_result(json.dumps(nodes))
157
+
158
+
159
+ def _tool_click(page: Page, args: dict[str, object]) -> dict[str, object]:
160
+ role = _parse_role(args.get("role"))
161
+ label = args.get("name")
162
+ label_str = label if isinstance(label, str) and label else None
163
+ if role is None and label_str is None:
164
+ msg = "waybound_click requires at least 'role' or 'name'"
165
+ raise ValueError(msg)
166
+ nth = max(0, _as_int(args.get("nth"), 0))
167
+ loc = (
168
+ page.get_by_role(role, name=label_str)
169
+ if role is not None
170
+ else page.get_by_text(label_str or "")
171
+ )
172
+ loc.nth(nth).click()
173
+ return _text_result("Clicked element")
174
+
175
+
176
+ def _tool_fill(page: Page, args: dict[str, object]) -> dict[str, object]:
177
+ role = _parse_role(args.get("role")) or Role.TEXTBOX
178
+ label = args.get("name")
179
+ label_str = label if isinstance(label, str) else None
180
+ text = str(args.get("text", ""))
181
+ nth = max(0, _as_int(args.get("nth"), 0))
182
+ page.get_by_role(role, name=label_str).nth(nth).fill(text)
183
+ return _text_result(f"Filled {len(text)} chars")
184
+
185
+
186
+ def _tool_scroll(page: Page, args: dict[str, object]) -> dict[str, object]:
187
+ dx = _as_float(args.get("delta_x"), 0.0)
188
+ dy = _as_float(args.get("delta_y"), -300.0)
189
+ page.scroll(delta_x=dx, delta_y=dy)
190
+ return _text_result(f"Scrolled ({dx}, {dy})")
191
+
192
+
193
+ def _tool_screenshot(page: Page, _args: dict[str, object]) -> dict[str, object]:
194
+ png = page.screenshot()
195
+ encoded = base64.b64encode(png).decode("ascii")
196
+ return {"content": [{"type": "image", "data": encoded, "mimeType": "image/png"}]}
197
+
198
+
199
+ def _tool_wait_for_response(page: Page, args: dict[str, object]) -> dict[str, object]:
200
+ needle = str(args.get("url_contains", ""))
201
+ timeout_ms = _as_int(args.get("timeout_ms"), 10_000)
202
+ resp = page.wait_for_response(needle, timeout_ms=timeout_ms)
203
+ payload = {
204
+ "url": resp.url,
205
+ "status": resp.status,
206
+ "content_type": resp.content_type,
207
+ "body": resp.body,
208
+ }
209
+ return _text_result(json.dumps(payload))
210
+
211
+
212
+ _TOOL_HANDLERS: dict[str, Callable[[Page, dict[str, object]], dict[str, object]]] = {
213
+ "waybound_goto": _tool_goto,
214
+ "waybound_url": _tool_url,
215
+ "waybound_snapshot": _tool_snapshot,
216
+ "waybound_click": _tool_click,
217
+ "waybound_fill": _tool_fill,
218
+ "waybound_scroll": _tool_scroll,
219
+ "waybound_screenshot": _tool_screenshot,
220
+ "waybound_wait_for_response": _tool_wait_for_response,
221
+ }
222
+
223
+
224
+ def _handle_tools_call(
225
+ page_provider: Callable[[], Page], req_id: object, params: object
226
+ ) -> dict[str, object]:
227
+ if not isinstance(params, dict):
228
+ return _rpc_error(req_id, -32602, "missing params object")
229
+ tool_name = params.get("name")
230
+ if not isinstance(tool_name, str):
231
+ return _rpc_error(req_id, -32602, "missing tool name")
232
+ handler = _TOOL_HANDLERS.get(tool_name)
233
+ if handler is None:
234
+ return _rpc_error(req_id, -32602, f"unknown tool: {tool_name}")
235
+
236
+ raw_args = params.get("arguments")
237
+ args = raw_args if isinstance(raw_args, dict) else {}
238
+ try:
239
+ # The provider launches the browser on first use. A launch failure (daemon binary or
240
+ # Chrome missing, Accessibility not granted) is reported as a tool error, like any
241
+ # other tool failure, instead of taking the whole server down.
242
+ result = handler(page_provider(), args)
243
+ except Exception as exc:
244
+ return {
245
+ "jsonrpc": "2.0",
246
+ "id": req_id,
247
+ "result": {"content": [{"type": "text", "text": str(exc)}], "isError": True},
248
+ }
249
+ return {"jsonrpc": "2.0", "id": req_id, "result": result}
250
+
251
+
252
+ def handle_rpc_message(
253
+ page_provider: Callable[[], Page],
254
+ msg: dict[str, object],
255
+ ) -> dict[str, object] | None:
256
+ """Process one JSON-RPC 2.0 MCP message; returns None for any notification."""
257
+ method = msg.get("method")
258
+ if "id" not in msg or method is None:
259
+ # Notifications carry no id; a message with an id but no method is the client's
260
+ # response to a server-initiated request. Neither is ever answered.
261
+ return None
262
+ req_id = msg.get("id")
263
+
264
+ if method == "ping":
265
+ return {"jsonrpc": "2.0", "id": req_id, "result": {}}
266
+ if method == "initialize":
267
+ return {
268
+ "jsonrpc": "2.0",
269
+ "id": req_id,
270
+ "result": {
271
+ "protocolVersion": PROTOCOL_VERSION,
272
+ "capabilities": {"tools": {}},
273
+ "serverInfo": {"name": "waybound-mcp", "version": "0.1.0"},
274
+ },
275
+ }
276
+ if method == "tools/list":
277
+ return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}}
278
+ if method == "tools/call":
279
+ return _handle_tools_call(page_provider, req_id, msg.get("params"))
280
+ return _rpc_error(req_id, -32601, f"method not found: {method!r}")
281
+
282
+
283
+ def _rpc_error(req_id: object, code: int, message: str) -> dict[str, object]:
284
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
285
+
286
+
287
+ def _options_from_env() -> LaunchOptions:
288
+ raw = os.environ.get("WAYBOUND_BACKEND", "macos")
289
+ backend: BackendName = "mock" if raw == "mock" else ("android" if raw == "android" else "macos")
290
+ return LaunchOptions(
291
+ backend=backend,
292
+ launch_chrome=backend == "macos",
293
+ serial=os.environ.get("WAYBOUND_SERIAL"),
294
+ proxy=os.environ.get("WAYBOUND_PROXY"),
295
+ timezone=os.environ.get("WAYBOUND_TIMEZONE"),
296
+ locale=os.environ.get("WAYBOUND_LOCALE"),
297
+ ssl_keylog=os.environ.get("WAYBOUND_SSL_KEYLOG"),
298
+ )
299
+
300
+
301
+ def main() -> None:
302
+ """Run the `waybound-mcp` stdio server, lazily launching the browser on first tool call."""
303
+ session: Session | None = None
304
+ active_page: Page | None = None
305
+
306
+ def get_page() -> Page:
307
+ nonlocal session, active_page
308
+ if active_page is None:
309
+ # Created lazily so a missing daemon binary surfaces as a tool error on the
310
+ # first call rather than killing the server before `initialize`.
311
+ candidate = launch(_options_from_env())
312
+ try:
313
+ active_page = candidate.__enter__()
314
+ except BaseException:
315
+ candidate.close()
316
+ raise
317
+ session = candidate
318
+ return active_page
319
+
320
+ try:
321
+ for raw_line in sys.stdin:
322
+ trimmed = raw_line.strip()
323
+ if not trimmed:
324
+ continue
325
+ try:
326
+ decoded: object = json.loads(trimmed)
327
+ except json.JSONDecodeError as exc:
328
+ sys.stdout.write(json.dumps(_rpc_error(None, -32700, str(exc))) + "\n")
329
+ sys.stdout.flush()
330
+ continue
331
+ if not isinstance(decoded, dict):
332
+ continue
333
+ response = handle_rpc_message(get_page, decoded)
334
+ if response is not None:
335
+ sys.stdout.write(json.dumps(response) + "\n")
336
+ sys.stdout.flush()
337
+ finally:
338
+ if session is not None:
339
+ session.close()
340
+
341
+
342
+ if __name__ == "__main__":
343
+ main()
waybound/py.typed ADDED
File without changes
waybound/session.py ADDED
@@ -0,0 +1,287 @@
1
+ """High-level ergonomic session lifecycle manager (`waybound.launch`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import os
7
+ import shutil
8
+ import socket
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import time
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+ from typing import TYPE_CHECKING, Literal
16
+
17
+ from waybound.binary import find_cached_daemon
18
+ from waybound.client import Page
19
+ from waybound.transport import UnixSocketTransport, WayboundDaemonError
20
+
21
+ if TYPE_CHECKING:
22
+ from types import TracebackType
23
+
24
+ BackendName = Literal["mock", "macos", "linux", "windows", "android"]
25
+ _MIN_WORKSPACE_PARENTS = 4
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class LaunchOptions:
30
+ """Configuration options for launching a `waybound` automation session."""
31
+
32
+ backend: BackendName = "mock"
33
+ pid: int | None = None
34
+ serial: str | None = None
35
+ display: str | None = None
36
+ headless_xvfb: bool = False
37
+ launch_chrome: bool = False
38
+ launch_waydroid: bool = False
39
+ instance_id: str | None = None
40
+ adb_port: int | None = None
41
+ url: str | None = None
42
+ profile_dir: Path | str | None = None
43
+ ssl_keylog: Path | str | None = None
44
+ proxy: str | None = None
45
+ timezone: str | None = None
46
+ locale: str | None = None
47
+ focus: bool = False
48
+ no_motion: bool = False
49
+ use_tcp: bool = False
50
+ daemon_binary: Path | str | None = None
51
+ startup_timeout_s: float = 5.0
52
+
53
+
54
+ def _daemon_bin_name() -> str:
55
+ return "waybound-daemon.exe" if sys.platform == "win32" else "waybound-daemon"
56
+
57
+
58
+ def _resolve_daemon_binary(explicit: Path | str | None) -> Path:
59
+ if explicit is not None:
60
+ return Path(explicit)
61
+
62
+ env_bin = os.environ.get("WAYBOUND_DAEMON_BIN")
63
+ if env_bin:
64
+ return Path(env_bin)
65
+
66
+ bin_name = _daemon_bin_name()
67
+ on_path = shutil.which(bin_name)
68
+ if on_path is not None:
69
+ return Path(on_path)
70
+
71
+ parents = Path(__file__).resolve().parents
72
+ if len(parents) >= _MIN_WORKSPACE_PARENTS:
73
+ repo_root = parents[3]
74
+ for profile in ("release", "debug"):
75
+ candidate = repo_root / "target" / profile / bin_name
76
+ if candidate.exists():
77
+ return candidate
78
+
79
+ cached = find_cached_daemon()
80
+ if cached is not None:
81
+ return cached
82
+
83
+ msg = (
84
+ f"{bin_name} binary not found on PATH, in target/{{release,debug}}, or in ~/.cache/waybound"
85
+ )
86
+ raise FileNotFoundError(msg)
87
+
88
+
89
+ def _reserve_loopback_port() -> int:
90
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
91
+ probe.bind(("127.0.0.1", 0))
92
+ addr: tuple[str, int] = probe.getsockname()
93
+ return addr[1]
94
+
95
+
96
+ def _connect_with_retry(
97
+ *,
98
+ socket_path: Path | None,
99
+ tcp_addr: tuple[str, int] | None,
100
+ stderr_log: Path,
101
+ proc: subprocess.Popen[bytes],
102
+ timeout_s: float,
103
+ ) -> UnixSocketTransport:
104
+ deadline = time.monotonic() + timeout_s
105
+ while time.monotonic() < deadline:
106
+ if proc.poll() is not None:
107
+ stderr_text = ""
108
+ if stderr_log.exists():
109
+ stderr_text = stderr_log.read_text(encoding="utf-8", errors="replace").strip()
110
+ msg = f"waybound-daemon exited early (code {proc.returncode}): {stderr_text}"
111
+ raise RuntimeError(msg)
112
+ if tcp_addr is not None:
113
+ try:
114
+ return UnixSocketTransport(tcp_addr=tcp_addr)
115
+ except (ConnectionRefusedError, OSError):
116
+ pass
117
+ elif socket_path is not None and socket_path.exists():
118
+ try:
119
+ return UnixSocketTransport(socket_path)
120
+ except (FileNotFoundError, ConnectionRefusedError, PermissionError):
121
+ pass
122
+ time.sleep(0.02)
123
+ target = f"{tcp_addr[0]}:{tcp_addr[1]}" if tcp_addr is not None else str(socket_path)
124
+ msg = f"timed out waiting for waybound-daemon at {target}"
125
+ raise TimeoutError(msg)
126
+
127
+
128
+ class Session:
129
+ """Context manager that starts `waybound-daemon`, connects, and cleans up on exit."""
130
+
131
+ def __init__(self, options: LaunchOptions | None = None) -> None:
132
+ opts = options if options is not None else LaunchOptions()
133
+ self._options = opts
134
+ self._daemon_binary = _resolve_daemon_binary(opts.daemon_binary)
135
+ self._tmp_dir: tempfile.TemporaryDirectory[str] | None = None
136
+ self._proc: subprocess.Popen[bytes] | None = None
137
+ self._transport: UnixSocketTransport | None = None
138
+
139
+ def _build_daemon_cmd(
140
+ self,
141
+ *,
142
+ socket_path: Path | None,
143
+ tcp_addr: tuple[str, int] | None,
144
+ ) -> list[str]:
145
+ opts = self._options
146
+ cmd = [str(self._daemon_binary)]
147
+ if tcp_addr is not None:
148
+ cmd.extend(["--tcp", f"{tcp_addr[0]}:{tcp_addr[1]}"])
149
+ elif socket_path is not None:
150
+ cmd.extend(["--socket", str(socket_path)])
151
+ cmd.extend(["--backend", opts.backend])
152
+ pairs: tuple[tuple[str, str | None], ...] = (
153
+ ("--pid", str(opts.pid) if opts.pid is not None else None),
154
+ ("--serial", opts.serial),
155
+ ("--display", opts.display),
156
+ ("--instance-id", opts.instance_id),
157
+ ("--adb-port", str(opts.adb_port) if opts.adb_port is not None else None),
158
+ ("--url", opts.url),
159
+ (
160
+ "--profile-dir",
161
+ str(Path(opts.profile_dir)) if opts.profile_dir is not None else None,
162
+ ),
163
+ ("--ssl-keylog", str(Path(opts.ssl_keylog)) if opts.ssl_keylog is not None else None),
164
+ ("--timezone", opts.timezone),
165
+ ("--locale", opts.locale),
166
+ )
167
+ for flag, val in pairs:
168
+ if val is not None:
169
+ cmd.extend([flag, val])
170
+ if opts.headless_xvfb:
171
+ cmd.append("--headless-xvfb")
172
+ if opts.launch_chrome:
173
+ cmd.append("--launch-chrome")
174
+ if opts.launch_waydroid:
175
+ cmd.append("--launch-waydroid")
176
+ if opts.focus:
177
+ cmd.append("--focus")
178
+ if opts.no_motion:
179
+ cmd.append("--no-motion")
180
+ return cmd
181
+
182
+ def __enter__(self) -> Page:
183
+ if self._proc is not None or self._transport is not None:
184
+ msg = "Session is already active and cannot be re-entered"
185
+ raise RuntimeError(msg)
186
+
187
+ opts = self._options
188
+ use_tcp = opts.use_tcp or sys.platform == "win32" or not hasattr(socket, "AF_UNIX")
189
+
190
+ if use_tcp:
191
+ tmp_dir = tempfile.TemporaryDirectory(prefix="wb-")
192
+ socket_path: Path | None = None
193
+ tcp_addr: tuple[str, int] | None = ("127.0.0.1", _reserve_loopback_port())
194
+ else:
195
+ # Keep socket path short to stay within macOS's 104-byte AF_UNIX sun_path limit.
196
+ tmp_dir = tempfile.TemporaryDirectory(prefix="wb-", dir="/tmp")
197
+ socket_path = Path(tmp_dir.name) / "w.sock"
198
+ tcp_addr = None
199
+
200
+ self._tmp_dir = tmp_dir
201
+ stderr_log = Path(tmp_dir.name) / "daemon.stderr.log"
202
+ cmd = self._build_daemon_cmd(socket_path=socket_path, tcp_addr=tcp_addr)
203
+
204
+ child_env = os.environ.copy()
205
+ if opts.proxy is not None:
206
+ # Pass proxy via env var so credentials do not appear in process argv (`ps`).
207
+ child_env["WAYBOUND_PROXY"] = opts.proxy
208
+
209
+ try:
210
+ with stderr_log.open("wb") as stderr_file:
211
+ proc = subprocess.Popen( # noqa: S603
212
+ cmd,
213
+ stdout=subprocess.DEVNULL,
214
+ stderr=stderr_file,
215
+ env=child_env,
216
+ )
217
+ self._proc = proc
218
+ transport = _connect_with_retry(
219
+ socket_path=socket_path,
220
+ tcp_addr=tcp_addr,
221
+ stderr_log=stderr_log,
222
+ proc=proc,
223
+ timeout_s=opts.startup_timeout_s,
224
+ )
225
+ self._transport = transport
226
+ return Page(transport)
227
+ except BaseException:
228
+ self.close()
229
+ raise
230
+
231
+ def __exit__(
232
+ self,
233
+ _exc_type: type[BaseException] | None,
234
+ _exc_val: BaseException | None,
235
+ _exc_tb: TracebackType | None,
236
+ ) -> None:
237
+ self.close()
238
+
239
+ def close(self) -> None:
240
+ """Gracefully shut down the daemon (unwinding browser & socket guards) and clean up."""
241
+ shutdown_sent = False
242
+ try:
243
+ if self._transport is not None:
244
+ with contextlib.suppress(OSError, WayboundDaemonError):
245
+ self._transport.shutdown()
246
+ shutdown_sent = True
247
+ with contextlib.suppress(OSError):
248
+ self._transport.close()
249
+ self._transport = None
250
+ finally:
251
+ try:
252
+ if self._proc is not None:
253
+ proc = self._proc
254
+ self._proc = None
255
+ if proc.poll() is None:
256
+ if shutdown_sent:
257
+ with contextlib.suppress(subprocess.TimeoutExpired):
258
+ proc.wait(timeout=2.0)
259
+ if proc.poll() is None:
260
+ proc.terminate()
261
+ try:
262
+ proc.wait(timeout=2.0)
263
+ except subprocess.TimeoutExpired:
264
+ proc.kill()
265
+ with contextlib.suppress(subprocess.TimeoutExpired):
266
+ proc.wait(timeout=1.0)
267
+ finally:
268
+ if self._tmp_dir is not None:
269
+ with contextlib.suppress(OSError):
270
+ self._tmp_dir.cleanup()
271
+ self._tmp_dir = None
272
+
273
+
274
+ def launch(
275
+ options: LaunchOptions | None = None,
276
+ *,
277
+ backend: BackendName = "mock",
278
+ launch_chrome: bool = False,
279
+ url: str | None = None,
280
+ ) -> Session:
281
+ """Create a `Session` context manager for ergonomic out-of-band browser automation."""
282
+ resolved = (
283
+ options
284
+ if options is not None
285
+ else LaunchOptions(backend=backend, launch_chrome=launch_chrome, url=url)
286
+ )
287
+ return Session(resolved)