browserwright 0.24.1__tar.gz → 0.24.3__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 (123) hide show
  1. {browserwright-0.24.1/src/browserwright.egg-info → browserwright-0.24.3}/PKG-INFO +3 -2
  2. {browserwright-0.24.1 → browserwright-0.24.3}/pyproject.toml +8 -2
  3. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/_executor/client.py +248 -26
  4. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/_executor/process.py +35 -1
  5. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/cdp.py +7 -6
  6. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/_ipc.py +211 -2
  7. browserwright-0.24.3/src/browserwright/daemon/_net.py +218 -0
  8. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/_stale.py +36 -0
  9. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/backends/cdp.py +18 -19
  10. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/cli.py +45 -7
  11. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/config.py +45 -2
  12. browserwright-0.24.3/src/browserwright/daemon/errors.py +59 -0
  13. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/launchagent.py +166 -13
  14. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/probe.py +13 -0
  15. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/daemon.py +24 -0
  16. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/facade.py +51 -22
  17. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/listener.py +168 -20
  18. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/upstream.py +53 -64
  19. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/upstream_context.py +23 -3
  20. browserwright-0.24.3/src/browserwright/daemon/server/ws_liveness.py +77 -0
  21. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon_lifecycle.py +100 -8
  22. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/errors.py +11 -0
  23. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/health.py +4 -3
  24. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/human_input.py +21 -24
  25. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/session_create.py +11 -0
  26. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/session_registry.py +9 -6
  27. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/skill_runtime.md +1 -1
  28. {browserwright-0.24.1 → browserwright-0.24.3/src/browserwright.egg-info}/PKG-INFO +3 -2
  29. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright.egg-info/SOURCES.txt +1 -0
  30. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright.egg-info/requires.txt +2 -1
  31. browserwright-0.24.1/src/browserwright/daemon/_net.py +0 -94
  32. browserwright-0.24.1/src/browserwright/daemon/errors.py +0 -34
  33. {browserwright-0.24.1 → browserwright-0.24.3}/LICENSE +0 -0
  34. {browserwright-0.24.1 → browserwright-0.24.3}/README.md +0 -0
  35. {browserwright-0.24.1 → browserwright-0.24.3}/setup.cfg +0 -0
  36. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/__init__.py +0 -0
  37. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/__main__.py +0 -0
  38. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/_executor/__init__.py +0 -0
  39. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/_executor/__main__.py +0 -0
  40. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/_executor/protocol.py +0 -0
  41. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/_text.py +0 -0
  42. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/cli.py +0 -0
  43. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/__init__.py +0 -0
  44. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/_rpc.py +0 -0
  45. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/backends/__init__.py +0 -0
  46. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/backends/base.py +0 -0
  47. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/backends/extension.py +0 -0
  48. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/doctor.py +0 -0
  49. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/launch_chrome.py +0 -0
  50. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/observability.py +0 -0
  51. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/platforms.py +0 -0
  52. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/relay_status.py +0 -0
  53. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/resolver.py +0 -0
  54. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/restart_guard.py +0 -0
  55. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/__init__.py +0 -0
  56. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/call_deadline.py +0 -0
  57. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/exec_relay.py +0 -0
  58. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/executor_registry.py +0 -0
  59. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/extension_contexts.py +0 -0
  60. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/extension_upstream.py +0 -0
  61. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/facade_extension.py +0 -0
  62. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/proxy.py +0 -0
  63. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/relay.py +0 -0
  64. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/session_state.py +0 -0
  65. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/state.py +0 -0
  66. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/status.py +0 -0
  67. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/server/verbs.py +0 -0
  68. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/supervise.py +0 -0
  69. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon/userscripts.py +0 -0
  70. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/daemon_url.py +0 -0
  71. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/discovery.py +0 -0
  72. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/install.py +0 -0
  73. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/memory/__init__.py +0 -0
  74. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/memory/_lock.py +0 -0
  75. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/memory/_md.py +0 -0
  76. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/memory/_yaml.py +0 -0
  77. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/memory/global_mem.py +0 -0
  78. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/memory/site_mem.py +0 -0
  79. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/mode_b_client.py +0 -0
  80. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/output_schema.py +0 -0
  81. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/primitives/__init__.py +0 -0
  82. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/primitives/discovery_api.py +0 -0
  83. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/primitives/http.py +0 -0
  84. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/primitives/site.py +0 -0
  85. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/__init__.py +0 -0
  86. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/_md_convert.py +0 -0
  87. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/_md_normalize.py +0 -0
  88. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/_namespace.py +0 -0
  89. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/_smart_goto.py +0 -0
  90. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/inline.py +0 -0
  91. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/isolated_world.py +0 -0
  92. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/markdown.py +0 -0
  93. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/playwright_handle.py +0 -0
  94. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/screenshot_defaults.py +0 -0
  95. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/search.py +0 -0
  96. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/snapshot.py +0 -0
  97. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/vendor/README.md +0 -0
  98. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/repl/vendor/readability.js +0 -0
  99. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/session.py +0 -0
  100. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/session_ctx.py +0 -0
  101. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/session_runtime.py +0 -0
  102. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/github.com/SKILL.md +0 -0
  103. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/github.com/memory.md +0 -0
  104. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/github.com/tasks/list_issues.py +0 -0
  105. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/google.com/SKILL.md +0 -0
  106. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/google.com/memory.md +0 -0
  107. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/google.com/tasks/search.py +0 -0
  108. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/producthunt.com/SKILL.md +0 -0
  109. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/producthunt.com/memory.md +0 -0
  110. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/producthunt.com/tasks/today.py +0 -0
  111. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/wikipedia.org/SKILL.md +0 -0
  112. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/wikipedia.org/memory.md +0 -0
  113. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/wikipedia.org/tasks/lookup.py +0 -0
  114. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/ycombinator.com/SKILL.md +0 -0
  115. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/ycombinator.com/memory.md +0 -0
  116. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/site_skills_starter/ycombinator.com/tasks/front_page.py +0 -0
  117. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/skill_doc.py +0 -0
  118. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/tab_surface.py +0 -0
  119. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/task_runner.py +0 -0
  120. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright/version.py +0 -0
  121. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright.egg-info/dependency_links.txt +0 -0
  122. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright.egg-info/entry_points.txt +0 -0
  123. {browserwright-0.24.1 → browserwright-0.24.3}/src/browserwright.egg-info/top_level.txt +0 -0
@@ -1,13 +1,14 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: browserwright
3
- Version: 0.24.1
3
+ Version: 0.24.3
4
4
  Summary: Browserwright — let AI/code agents drive a real or isolated browser and author userscripts. Single package: the agent-facing REPL/site-skills/memory layer plus the bundled browser-resolving daemon (CDP proxy + extension/cloud backends).
5
5
  License-Expression: AGPL-3.0-only
6
6
  Requires-Python: >=3.11
7
7
  License-File: LICENSE
8
8
  Requires-Dist: websockets==15.0.1
9
9
  Requires-Dist: pillow==12.2.0
10
- Requires-Dist: httpx>=0.27
10
+ Requires-Dist: httpx[socks]>=0.27
11
+ Requires-Dist: python-socks>=2.7
11
12
  Requires-Dist: playwright>=1.60.0
12
13
  Requires-Dist: pyyaml>=6.0.3
13
14
  Requires-Dist: html-to-markdown<4,>=3.10.6
@@ -15,14 +15,20 @@ name = "browserwright"
15
15
  # stamping regex is `^(version\s*=\s*)["'][^"']+["']\s*$` and CI aborts unless
16
16
  # it matches exactly once. `tests/skill/test_release_versioning.py` enforces all
17
17
  # of that before a tag is ever pushed. See RELEASING.md.
18
- version = "0.24.1"
18
+ version = "0.24.3"
19
19
  description = "Browserwright — let AI/code agents drive a real or isolated browser and author userscripts. Single package: the agent-facing REPL/site-skills/memory layer plus the bundled browser-resolving daemon (CDP proxy + extension/cloud backends)."
20
20
  requires-python = ">=3.11"
21
21
  license = "AGPL-3.0-only"
22
22
  dependencies = [
23
23
  "websockets==15.0.1",
24
24
  "pillow==12.2.0",
25
- "httpx>=0.27",
25
+ # SOCKS support is default, not an extra (#136): an `--attach` session's
26
+ # proxy comes from the caller's environment, and macOS proxy apps (Surge,
27
+ # Clash) routinely export `all_proxy=socks5://...`. `socks` gives httpx
28
+ # socksio for CDP discovery; python-socks is what websockets 15 needs for
29
+ # the CDP websocket itself.
30
+ "httpx[socks]>=0.27",
31
+ "python-socks>=2.7",
26
32
  # Phase C: the skill heredoc injects a real Playwright `page`/`context`
27
33
  # bound to the daemon facade, so playwright is a runtime dependency now (it
28
34
  # was previously dev-only). `playwright install chromium` is still needed
@@ -20,22 +20,39 @@ The cost, accepted in ADR-0011: execute payloads and large outputs cross the
20
20
  daemon's event loop, and a daemon restart severs a live data plane (it used to
21
21
  survive one). The client turns that severing into ``ExecutorUnavailable`` with a
22
22
  "daemon restarted or unreachable" message rather than a bare ws error.
23
+
24
+ A *replacement* daemon is not a failure, though: it adopts the session's
25
+ executor and its browser. So the two seams that run strictly before the
26
+ request can reach the executor — the ``ensureExecutor`` verb and the ``/exec``
27
+ connect — retry a daemon that went away, re-resolving the endpoint on every
28
+ attempt (`_call_until_daemon_returns`). When those retries run out, the text
29
+ names the daemon and what happened to it, because the alternative — blaming a
30
+ missing extension for a browser that is connected and healthy — is what sent
31
+ three agent calls to `chrome://extensions` on 2026-10-19 (ADR-0013 rule 3).
23
32
  """
24
33
  from __future__ import annotations
25
34
 
26
35
  import json
27
36
  import signal
28
37
  import threading
29
- from collections.abc import Iterator
38
+ import time
39
+ from collections.abc import Callable, Iterator
30
40
  from contextlib import contextmanager
31
41
  from dataclasses import dataclass
42
+ from typing import TypeVar
32
43
 
33
44
  from websockets.exceptions import ConnectionClosed, WebSocketException
34
45
  from websockets.sync.client import connect as ws_connect
35
46
 
36
47
  from .. import session_registry as reg
48
+ from ..daemon.errors import DaemonShuttingDown
37
49
  from ..daemon_url import daemon_endpoint
38
- from ..errors import BrowserwrightError, DaemonUnavailable
50
+ from ..errors import (
51
+ BrowserwrightError,
52
+ CDPError,
53
+ CDPTransportClosed,
54
+ DaemonUnavailable,
55
+ )
39
56
  from .protocol import (
40
57
  DEFAULT_TIMEOUT_MS,
41
58
  _MAX_FRAME,
@@ -48,6 +65,24 @@ from .protocol import (
48
65
  # browser cold-start is part of the request deadline, not hidden extra time.
49
66
  _RESPONSE_DELIVERY_SLACK_S = 2.0
50
67
 
68
+ #: How long a *departed* daemon gets to come back before the client stops
69
+ #: retrying and says what happened. A replacement daemon needs the old one
70
+ #: stopped and its own endpoint bound before it can adopt the session's
71
+ #: executor, so this window is the whole difference between surviving a daemon
72
+ #: replacement and an `ExecutorUnavailable` that blames the wrong layer. It is
73
+ #: deliberately the same budget as the executor's cold-start connect
74
+ #: (13 x 0.75s ≈ 9s, `_executor/process.py`) so the two waits on one call cannot
75
+ #: stack into an apparent hang, and ADR-0014 caps it further by whatever the
76
+ #: caller's `--timeout` has left.
77
+ _DAEMON_RETURN_ATTEMPTS = 13
78
+ _DAEMON_RETURN_BACKOFF_S = 0.75
79
+
80
+ #: What `ws_connect` raises when the daemon's front door is not open (yet):
81
+ #: nothing listening, or nothing speaking the ws handshake.
82
+ _DAEMON_DOOR_ERRORS = (WebSocketException, ConnectionClosed, OSError)
83
+
84
+ _T = TypeVar("_T")
85
+
51
86
 
52
87
  class ExecutorUnavailable(BrowserwrightError):
53
88
  """The session's executor could not be ensured/reached.
@@ -75,22 +110,51 @@ class ExecutorLease:
75
110
  executor_id: str
76
111
 
77
112
 
78
- def _ensure_executor_lease(sess) -> ExecutorLease:
79
- """Ask the daemon to ensure the session's executor and return its socket
80
- path. Uses the session's mode_b CDP client (``sess.cdp``) to send the
81
- control-plane verb."""
113
+ def _ensure_executor_lease(sess, *, deadline: float | None = None) -> ExecutorLease:
114
+ """Ask the daemon to ensure the session's executor and return its identity.
115
+
116
+ Uses the session's mode_b CDP client (``sess.cdp``) to send the
117
+ control-plane verb. ``deadline`` is the caller's ``time.monotonic()``
118
+ instant (ADR-0014), which caps the retries below.
119
+ """
82
120
  sid = _session_id(sess)
83
- try:
121
+
122
+ def _attempt() -> dict:
84
123
  # The browserwright session is already bound on the websocket query
85
124
  # (`?session=<id>`). Do not pass it as CDP's top-level `sessionId`;
86
125
  # that field means "attached target session" inside the proxy mux.
87
- res = sess.cdp.send("BrowserwrightDaemon.ensureExecutor", bsSession=sid)
88
- except DaemonUnavailable:
89
- # "the daemon is not there" already says everything, with the endpoint
90
- # named and the auto-start rule explained. Wrapping it would bury that
126
+ return sess.cdp.send("BrowserwrightDaemon.ensureExecutor", bsSession=sid)
127
+
128
+ def _give_up(exc: BaseException, attempts: int,
129
+ elapsed: float) -> BrowserwrightError:
130
+ if isinstance(exc, DaemonUnavailable):
131
+ # "nothing answered at <endpoint>" is already the better diagnosis
132
+ # (probed, and it explains the auto-start rule). Wrapping it here
133
+ # would bury that under a second, less specific story.
134
+ return exc
135
+ return ExecutorUnavailable(
136
+ f"the daemon serving session {sid!r} went away mid-call (it was "
137
+ f"replaced or is shutting down): {attempts} attempt(s) over "
138
+ f"{elapsed:.1f}s could not reach it (last: {exc}). "
139
+ f"{_endpoint_state_now()} The browser and the extension are not "
140
+ f"involved; a replacement daemon adopts the session's executor.",
141
+ fix="retry the command",
142
+ )
143
+
144
+ try:
145
+ res = _call_until_daemon_returns(
146
+ _attempt,
147
+ deadline=deadline,
148
+ departed=_daemon_departed,
149
+ before_retry=lambda: _forget_daemon_endpoint(sess),
150
+ give_up=_give_up,
151
+ )
152
+ except (DaemonUnavailable, ExecutorUnavailable):
153
+ # "nothing answered at the endpoint" / "it left mid-call" already say
154
+ # everything, with the daemon named; wrapping them would bury that
91
155
  # under a second, less specific fix about stale executors.
92
156
  raise
93
- except Exception as e:
157
+ except Exception as e: # noqa: BLE001 - keep one agent-facing envelope
94
158
  raise ExecutorUnavailable(
95
159
  f"ensureExecutor failed for session {sid!r}: {e}"
96
160
  ) from e
@@ -109,6 +173,135 @@ def _ensure_executor_lease(sess) -> ExecutorLease:
109
173
  return ExecutorLease(session_id=sid, executor_id=executor_id)
110
174
 
111
175
 
176
+ def _forget_daemon_endpoint(sess) -> None:
177
+ """Make the next attempt dial the daemon that answers *now* (ADR-0013).
178
+
179
+ ``ModeBClient.ws_url()`` caches its answer until ``invalidate()``, and
180
+ `Session.cdp` re-creates its `CDPSession` only once the old one is closed —
181
+ so both halves are needed: drop the cached url, and the dead socket is then
182
+ replaced (and re-resolved) by the property itself rather than reused.
183
+ Retrying over the socket that just died would retry the daemon that just
184
+ left, which is the entire failure this absorbs.
185
+ """
186
+ invalidate = getattr(getattr(sess, "daemon", None), "invalidate", None)
187
+ if callable(invalidate):
188
+ invalidate()
189
+
190
+
191
+ def _daemon_departed(exc: BaseException, attempt: int) -> bool:
192
+ """True only when ``exc`` says the *daemon* left — never on "any error".
193
+
194
+ Three shapes qualify, and they are exactly the ways a client learns its
195
+ daemon is gone: the request's socket died with no reply
196
+ (`CDPTransportClosed`), the daemon answered in its own words that it is
197
+ shutting down (`DaemonShuttingDown`, carried through the verb's JSON-RPC
198
+ error envelope), or nothing answers the endpoint any more
199
+ (`DaemonUnavailable`) *after* an earlier attempt already saw it leave.
200
+
201
+ A refusal on the first attempt is deliberately NOT a departure: nothing was
202
+ ever there, which `DaemonUnavailable` diagnoses on its own (probed endpoint,
203
+ auto-start rule) and which `session new` / `recover` own. Retrying it would
204
+ make every "no daemon is running" call 9s slower to say the same thing.
205
+
206
+ Everything else — the no-extension diagnosis, a -32601 from a stale daemon,
207
+ a rejected attach — would fail identically on the next attempt, so treating
208
+ it as retryable would burn the caller's deadline and then report the wrong
209
+ layer. That the daemon can tell these apart (`DaemonShuttingDown` vs the
210
+ extension text) is what makes this list exist; do not flatten it here.
211
+ """
212
+ if isinstance(exc, CDPTransportClosed):
213
+ return True
214
+ if isinstance(exc, DaemonUnavailable):
215
+ return attempt > 1
216
+ if isinstance(exc, CDPError):
217
+ return DaemonShuttingDown.MARKER in str(exc.cdp_message)
218
+ return False
219
+
220
+
221
+ def _endpoint_is_the_daemons(exc: BaseException, _attempt: int) -> bool:
222
+ """`_connect`'s classifier: the `/exec` surface lives only in the daemon.
223
+
224
+ No request frame exists yet, so a refused/closed connect is always "the
225
+ daemon is not answering yet" and never the browser or the extension — and a
226
+ first-attempt refusal here still means the daemon left, because
227
+ `ensureExecutor` reached that same daemon moments earlier. Anything that is
228
+ not a transport failure (a broken URL resolution, a bad handshake argument)
229
+ would fail identically on every attempt, so it is not retried.
230
+ """
231
+ return isinstance(exc, _DAEMON_DOOR_ERRORS)
232
+
233
+
234
+ def _endpoint_state_now() -> str:
235
+ """ADR-0013 rule 3: probe the endpoint once and say what answered.
236
+
237
+ "Nothing is listening" and "something that is not browserwright answered"
238
+ are different diagnoses with different next steps, and neither may be
239
+ guessed from a socket error — the case that rule was written for is a local
240
+ proxy answering 503 on the endpoint while the daemon is fine. So the last
241
+ words of a failed call carry the observation, not an inference.
242
+ """
243
+ from ..daemon import _ipc
244
+
245
+ ep = daemon_endpoint()
246
+ return f"Right now {_ipc.probe_endpoint_sync(ep.host, ep.port).describe()}."
247
+
248
+
249
+ def _daemon_return_budget(deadline: float | None) -> float:
250
+ """~9s of retries, or less when the caller's deadline leaves less."""
251
+ full = _DAEMON_RETURN_BACKOFF_S * _DAEMON_RETURN_ATTEMPTS
252
+ if deadline is None:
253
+ return full
254
+ return max(0.0, min(full, deadline - time.monotonic()))
255
+
256
+
257
+ def _call_until_daemon_returns(
258
+ attempt: Callable[[], _T],
259
+ *,
260
+ deadline: float | None,
261
+ departed: Callable[[BaseException, int], bool],
262
+ give_up: Callable[[BaseException, int, float], BrowserwrightError],
263
+ before_retry: Callable[[], None] | None = None,
264
+ ) -> _T:
265
+ """Run ``attempt``, retrying only while the *daemon* is what went missing.
266
+
267
+ **The retry scope is a correctness rule, not a convenience.** Both callers
268
+ sit strictly before the session's request can have reached the executor:
269
+ the `ensureExecutor` verb, and the `/exec` connect, which has no frame yet.
270
+ Replaying either cannot execute the agent's code twice. The send/recv pair
271
+ in `_run_request_on_executor` deliberately has no retry at all — once a
272
+ request frame may be on the wire a replay would run the caller's code a
273
+ second time, so that path reaps the exact executor instance instead.
274
+
275
+ ``departed`` decides what counts as the daemon leaving, and sees the
276
+ attempt number too (see `_daemon_departed`: a refused endpoint is the
277
+ departure *continuing* only once an earlier attempt saw it leave).
278
+ ``before_retry`` re-points the client at the endpoint that answers now.
279
+ ``deadline`` (a ``time.monotonic()`` instant) caps the whole loop:
280
+ ADR-0014 forbids an inner wait outliving the call deadline, and this wait
281
+ is the innermost one on the call's path.
282
+ """
283
+ started = time.monotonic()
284
+ budget_end = started + _daemon_return_budget(deadline)
285
+ attempts = 0
286
+ while True:
287
+ attempts += 1
288
+ try:
289
+ return attempt()
290
+ except Exception as e: # noqa: BLE001 - classified on the next line
291
+ if not departed(e, attempts):
292
+ raise
293
+ last = e
294
+ remaining = budget_end - time.monotonic()
295
+ if remaining <= 0 or attempts >= _DAEMON_RETURN_ATTEMPTS:
296
+ final = give_up(last, attempts, time.monotonic() - started)
297
+ if final is last:
298
+ raise final
299
+ raise final from last
300
+ if before_retry is not None:
301
+ before_retry()
302
+ time.sleep(min(_DAEMON_RETURN_BACKOFF_S, remaining))
303
+
304
+
112
305
  def ensure_executor(sess) -> str:
113
306
  """Ensure the session's executor and return its instance id."""
114
307
  return _ensure_executor_lease(sess).executor_id
@@ -180,14 +373,18 @@ def _run_request_on_executor(
180
373
  # wedged or long-running executor cannot prevent the durable idle clock
181
374
  # from reflecting that a new instruction arrived.
182
375
  reg.touch(sid)
183
- lease = _ensure_executor_lease(sess)
376
+ # One absolute deadline for the pre-request work (ADR-0014): the retries in
377
+ # `_ensure_executor_lease` / `_connect` are inner waits, so they are capped
378
+ # by what the caller's `timeout_ms` leaves rather than by their own budget.
379
+ deadline = time.monotonic() + max(request.timeout_ms, 1) / 1000.0
380
+ lease = _ensure_executor_lease(sess, deadline=deadline)
184
381
  # The executor owns the exact outer deadline, including first-call
185
382
  # cold-start. Give only a small framing/delivery margin so its terminal
186
383
  # response wins the race against the local socket timeout.
187
384
  recv_timeout = (
188
385
  max(request.timeout_ms, 1) / 1000.0 + _RESPONSE_DELIVERY_SLACK_S
189
386
  )
190
- conn = _connect(sid, timeout=recv_timeout)
387
+ conn = _connect(sid, timeout=recv_timeout, deadline=deadline)
191
388
  sent = False
192
389
  interrupted: BaseException | None = None
193
390
  transport_error: Exception | None = None
@@ -333,31 +530,56 @@ def _recv_frame(ws, timeout: float | None = None) -> dict:
333
530
  return msg
334
531
 
335
532
 
336
- def _connect(session_id: str, *, timeout: float = 30.0):
533
+ def _connect(session_id: str, *, timeout: float = 30.0,
534
+ deadline: float | None = None):
337
535
  """Open the data plane: a ws to the daemon's `/exec` relay.
338
536
 
339
537
  ``max_size`` must clear the executor's own frame cap — a screenshot-bearing
340
538
  response is legitimately large and the daemon relays it whole.
341
539
 
342
- No connect retry loop here any more: the daemon accepted our
343
- `ensureExecutor` a moment ago, so it is listening, and the executor-socket
344
- bind race the old retry absorbed is now the *daemon's* problem, handled
345
- inside `exec_relay`. A refusal here means the daemon itself is gone.
540
+ A refusal here is the daemon's front door not being open, which is exactly
541
+ what a *replacement* daemon looks like for a second or two while it binds
542
+ and adopts the session's executor. Retrying is safe (no request frame
543
+ exists yet, so nothing can run twice) and every attempt re-resolves the
544
+ endpoint through `_exec_ws_url` — reading the state file the replacement
545
+ publishes — so a daemon that came back on another port is dialed at its new
546
+ address instead of the dead one. The executor-socket bind race the old
547
+ client-side loop absorbed is still the *daemon's* problem
548
+ (`exec_relay._dial_executor`); this loop is about the daemon itself, and it
549
+ is capped by the caller's deadline (ADR-0014).
346
550
  """
347
- url = _exec_ws_url(session_id)
348
- try:
551
+ # The endpoint actually dialed last, for the failure message; the first
552
+ # attempt fills it, so it is never empty when `_give_up` runs.
553
+ attempted: list[str] = []
554
+
555
+ def _open():
556
+ attempted.append(_exec_ws_url(session_id))
349
557
  return ws_connect(
350
- url,
558
+ attempted[-1],
351
559
  open_timeout=timeout,
352
560
  close_timeout=timeout,
353
561
  max_size=_MAX_FRAME,
354
562
  proxy=None,
355
563
  compression=None,
356
564
  )
357
- except (WebSocketException, ConnectionClosed, OSError) as e:
358
- raise ExecutorUnavailable(
359
- f"could not open the executor data plane at {url}: {e}"
360
- ) from e
565
+
566
+ def _give_up(exc: BaseException, attempts: int,
567
+ elapsed: float) -> BrowserwrightError:
568
+ return ExecutorUnavailable(
569
+ f"could not open the executor data plane at {attempted[-1]} after "
570
+ f"{attempts} attempt(s) over {elapsed:.1f}s: {exc}. The daemon "
571
+ f"serving session {session_id!r} was replaced or is shutting "
572
+ f"down; nothing reached the executor, so retrying is safe. "
573
+ f"{_endpoint_state_now()}",
574
+ fix="retry the command",
575
+ )
576
+
577
+ return _call_until_daemon_returns(
578
+ _open,
579
+ deadline=deadline,
580
+ departed=_endpoint_is_the_daemons,
581
+ give_up=_give_up,
582
+ )
361
583
 
362
584
 
363
585
  def _session_id(sess) -> str:
@@ -809,7 +809,8 @@ class _Worker:
809
809
  return
810
810
  sys.stderr.write(
811
811
  f"executor {self._session_id}: facade transport dropped "
812
- "(daemon restart?); will reconnect on the next call\n")
812
+ "(daemon restart, or the link to the browser); will reconnect on "
813
+ "the next call\n")
813
814
  self._connected = False
814
815
  self._facade_death_handler = None
815
816
  self._facade_daemon_pid = None
@@ -1003,6 +1004,20 @@ class _Worker:
1003
1004
  outcomes, no loop.
1004
1005
  """
1005
1006
  sid = self._session_id or "<id>"
1007
+ if self._transport_lost():
1008
+ # Not the tab: the executor's connection to the browser is gone,
1009
+ # and with it every Page and the context. Rebinding here would run
1010
+ # on no context, and forgetting the binding would abandon a tab
1011
+ # that is still alive. The next call reconnects and re-binds the
1012
+ # SAME tab (`_ensure_connected`), with `state` intact.
1013
+ error["fix"] = (
1014
+ "the executor's connection to the browser dropped mid-call "
1015
+ "(the tab itself was not closed). It reconnects to the same "
1016
+ "tab on the next call and `state` is kept — RETRY the call. "
1017
+ "Do not create a new session; if this repeats, check the link "
1018
+ "to the browser (`browserwright-daemon` log names why the "
1019
+ "connection ended).")
1020
+ return self._finish(buf, error=error, exit_code=exit_code)
1006
1021
  failure: str | None = None
1007
1022
  try:
1008
1023
  if not self._rebind_dead_page():
@@ -1034,6 +1049,25 @@ class _Worker:
1034
1049
  )
1035
1050
  return self._finish(buf, error=error, exit_code=exit_code)
1036
1051
 
1052
+ def _transport_lost(self) -> bool:
1053
+ """Is the Playwright Browser disconnected from the cdp surface?
1054
+
1055
+ A dropped connection closes every Page at once, so the call fails with
1056
+ the same TargetClosedError a dead tab produces. Playwright usually
1057
+ dispatched ``disconnected`` while the failing call pumped events; if it
1058
+ has not yet, its ``is_connected()`` already reads False and the armed
1059
+ handler is run here."""
1060
+ if not self._connected:
1061
+ return True
1062
+ is_connected = getattr(self._browser, "is_connected", None)
1063
+ try:
1064
+ alive = bool(is_connected()) if callable(is_connected) else True
1065
+ except Exception: # noqa: BLE001 - a failed probe is disconnected
1066
+ alive = False
1067
+ if not alive:
1068
+ self._on_facade_dead(self._browser)
1069
+ return not alive
1070
+
1037
1071
  @staticmethod
1038
1072
  def _exec_with_return(code: str, globals_: dict[str, Any]) -> str | None:
1039
1073
  """Exec ``code``; if the LAST statement is a bare expression, return its
@@ -21,7 +21,7 @@ from typing import Optional
21
21
  from websockets.exceptions import ConnectionClosed
22
22
  from websockets.sync.client import connect as ws_connect
23
23
 
24
- from .errors import CDPError
24
+ from .errors import CDPError, CDPTransportClosed
25
25
 
26
26
 
27
27
  def _rpc_error_fix(method: str, err: object) -> str:
@@ -98,8 +98,8 @@ class CDPSession:
98
98
 
99
99
  def send(self, method: str, *, session: Optional[str] = None, **params) -> dict:
100
100
  if self._closed:
101
- raise CDPError(method=method, params=params,
102
- cdp_message=f"ws closed: {self._closed_reason}")
101
+ raise CDPTransportClosed(method=method, params=params,
102
+ cdp_message=f"ws closed: {self._closed_reason}")
103
103
  with self._lock:
104
104
  mid = self._next_id
105
105
  self._next_id += 1
@@ -113,7 +113,8 @@ class CDPSession:
113
113
  self._ws.send(payload)
114
114
  except ConnectionClosed as e:
115
115
  self._closed, self._closed_reason = True, str(e)
116
- raise CDPError(method=method, params=params, cdp_message=str(e)) from e
116
+ raise CDPTransportClosed(method=method, params=params,
117
+ cdp_message=str(e)) from e
117
118
  # Wait for the reply.
118
119
  deadline = time.monotonic() + 30.0
119
120
  with self._inflight_cv:
@@ -128,8 +129,8 @@ class CDPSession:
128
129
  entry = self._inflight.pop(mid, None)
129
130
  self._inflight_meta.pop(mid, None)
130
131
  if self._closed and not entry:
131
- raise CDPError(method=method, params=params,
132
- cdp_message=f"ws closed: {self._closed_reason}")
132
+ raise CDPTransportClosed(method=method, params=params,
133
+ cdp_message=f"ws closed: {self._closed_reason}")
133
134
  if "error" in entry:
134
135
  err = entry["error"]
135
136
  raise CDPError(method=method, params=params,