browserwright 0.24.2__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 (122) hide show
  1. {browserwright-0.24.2/src/browserwright.egg-info → browserwright-0.24.3}/PKG-INFO +1 -1
  2. {browserwright-0.24.2 → browserwright-0.24.3}/pyproject.toml +1 -1
  3. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/_executor/client.py +248 -26
  4. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/cdp.py +7 -6
  5. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/_ipc.py +211 -2
  6. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/_stale.py +36 -0
  7. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/cli.py +45 -7
  8. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/config.py +41 -2
  9. browserwright-0.24.3/src/browserwright/daemon/errors.py +59 -0
  10. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/launchagent.py +166 -13
  11. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/probe.py +13 -0
  12. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/daemon.py +24 -0
  13. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/listener.py +168 -20
  14. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon_lifecycle.py +100 -8
  15. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/errors.py +11 -0
  16. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/health.py +4 -3
  17. {browserwright-0.24.2 → browserwright-0.24.3/src/browserwright.egg-info}/PKG-INFO +1 -1
  18. browserwright-0.24.2/src/browserwright/daemon/errors.py +0 -34
  19. {browserwright-0.24.2 → browserwright-0.24.3}/LICENSE +0 -0
  20. {browserwright-0.24.2 → browserwright-0.24.3}/README.md +0 -0
  21. {browserwright-0.24.2 → browserwright-0.24.3}/setup.cfg +0 -0
  22. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/__init__.py +0 -0
  23. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/__main__.py +0 -0
  24. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/_executor/__init__.py +0 -0
  25. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/_executor/__main__.py +0 -0
  26. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/_executor/process.py +0 -0
  27. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/_executor/protocol.py +0 -0
  28. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/_text.py +0 -0
  29. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/cli.py +0 -0
  30. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/__init__.py +0 -0
  31. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/_net.py +0 -0
  32. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/_rpc.py +0 -0
  33. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/backends/__init__.py +0 -0
  34. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/backends/base.py +0 -0
  35. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/backends/cdp.py +0 -0
  36. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/backends/extension.py +0 -0
  37. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/doctor.py +0 -0
  38. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/launch_chrome.py +0 -0
  39. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/observability.py +0 -0
  40. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/platforms.py +0 -0
  41. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/relay_status.py +0 -0
  42. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/resolver.py +0 -0
  43. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/restart_guard.py +0 -0
  44. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/__init__.py +0 -0
  45. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/call_deadline.py +0 -0
  46. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/exec_relay.py +0 -0
  47. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/executor_registry.py +0 -0
  48. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/extension_contexts.py +0 -0
  49. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/extension_upstream.py +0 -0
  50. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/facade.py +0 -0
  51. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/facade_extension.py +0 -0
  52. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/proxy.py +0 -0
  53. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/relay.py +0 -0
  54. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/session_state.py +0 -0
  55. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/state.py +0 -0
  56. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/status.py +0 -0
  57. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/upstream.py +0 -0
  58. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/upstream_context.py +0 -0
  59. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/verbs.py +0 -0
  60. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/server/ws_liveness.py +0 -0
  61. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/supervise.py +0 -0
  62. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon/userscripts.py +0 -0
  63. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/daemon_url.py +0 -0
  64. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/discovery.py +0 -0
  65. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/install.py +0 -0
  66. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/memory/__init__.py +0 -0
  67. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/memory/_lock.py +0 -0
  68. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/memory/_md.py +0 -0
  69. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/memory/_yaml.py +0 -0
  70. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/memory/global_mem.py +0 -0
  71. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/memory/site_mem.py +0 -0
  72. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/mode_b_client.py +0 -0
  73. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/output_schema.py +0 -0
  74. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/primitives/__init__.py +0 -0
  75. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/primitives/discovery_api.py +0 -0
  76. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/primitives/http.py +0 -0
  77. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/primitives/site.py +0 -0
  78. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/__init__.py +0 -0
  79. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/_md_convert.py +0 -0
  80. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/_md_normalize.py +0 -0
  81. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/_namespace.py +0 -0
  82. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/_smart_goto.py +0 -0
  83. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/human_input.py +0 -0
  84. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/inline.py +0 -0
  85. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/isolated_world.py +0 -0
  86. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/markdown.py +0 -0
  87. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/playwright_handle.py +0 -0
  88. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/screenshot_defaults.py +0 -0
  89. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/search.py +0 -0
  90. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/snapshot.py +0 -0
  91. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/vendor/README.md +0 -0
  92. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/repl/vendor/readability.js +0 -0
  93. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/session.py +0 -0
  94. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/session_create.py +0 -0
  95. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/session_ctx.py +0 -0
  96. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/session_registry.py +0 -0
  97. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/session_runtime.py +0 -0
  98. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/github.com/SKILL.md +0 -0
  99. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/github.com/memory.md +0 -0
  100. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/github.com/tasks/list_issues.py +0 -0
  101. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/google.com/SKILL.md +0 -0
  102. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/google.com/memory.md +0 -0
  103. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/google.com/tasks/search.py +0 -0
  104. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/producthunt.com/SKILL.md +0 -0
  105. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/producthunt.com/memory.md +0 -0
  106. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/producthunt.com/tasks/today.py +0 -0
  107. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/wikipedia.org/SKILL.md +0 -0
  108. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/wikipedia.org/memory.md +0 -0
  109. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/wikipedia.org/tasks/lookup.py +0 -0
  110. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/ycombinator.com/SKILL.md +0 -0
  111. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/ycombinator.com/memory.md +0 -0
  112. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/site_skills_starter/ycombinator.com/tasks/front_page.py +0 -0
  113. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/skill_doc.py +0 -0
  114. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/skill_runtime.md +0 -0
  115. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/tab_surface.py +0 -0
  116. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/task_runner.py +0 -0
  117. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright/version.py +0 -0
  118. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright.egg-info/SOURCES.txt +0 -0
  119. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright.egg-info/dependency_links.txt +0 -0
  120. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright.egg-info/entry_points.txt +0 -0
  121. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright.egg-info/requires.txt +0 -0
  122. {browserwright-0.24.2 → browserwright-0.24.3}/src/browserwright.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: browserwright
3
- Version: 0.24.2
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
@@ -15,7 +15,7 @@ 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.2"
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"
@@ -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:
@@ -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,
@@ -27,7 +27,7 @@ import socket
27
27
  import stat
28
28
  import tempfile
29
29
  import time
30
- from dataclasses import dataclass
30
+ from dataclasses import dataclass, replace
31
31
  from pathlib import Path
32
32
 
33
33
 
@@ -693,11 +693,43 @@ class EndpointProbe:
693
693
  status_line: str = ""
694
694
  server: str = ""
695
695
  detail: str = ""
696
+ #: How long the probe took, in milliseconds — set by
697
+ #: :func:`probe_endpoint_sync`, ``None`` for a probe a caller built by hand
698
+ #: (tests, or a subclassed observation). Carried so a record of a decision
699
+ #: made on a probe can say what the probes actually cost, which is the
700
+ #: difference between "it timed out" and "it timed out in 1501ms".
701
+ latency_ms: float | None = None
696
702
 
697
703
  @property
698
704
  def answered(self) -> bool:
699
705
  return self.kind == "ours"
700
706
 
707
+ @property
708
+ def silent(self) -> bool:
709
+ """The socket opened and nothing usable came back.
710
+
711
+ ``timeout`` (nothing came back in time) and ``garbage`` (bytes that are
712
+ not HTTP at all) both mean the port never gave an answer we could read.
713
+ Distinct from ``foreign`` (something answered HTTP, just not our pong)
714
+ and from ``refused`` (nothing is listening).
715
+ """
716
+ return self.kind in SILENT_PROBE_KINDS
717
+
718
+ @property
719
+ def timed_out(self) -> bool:
720
+ """Nothing came back within the budget — the one kind escalation re-asks.
721
+
722
+ ``garbage`` is not slowness: something spoke, it just did not speak
723
+ HTTP. Asking again would burn the window for an answer we already have.
724
+ """
725
+ return self.kind == "timeout"
726
+
727
+ def evidence(self) -> str:
728
+ """``timeout@1501ms`` — the kind plus its measured cost, for a record."""
729
+ if self.latency_ms is None:
730
+ return self.kind
731
+ return f"{self.kind}@{self.latency_ms:.0f}ms"
732
+
701
733
  def describe(self) -> str:
702
734
  """One clause, suitable for inlining into an error message."""
703
735
  where = f"{self.host}:{self.port}"
@@ -715,12 +747,90 @@ class EndpointProbe:
715
747
  return f"{where} answered with something that is not HTTP"
716
748
 
717
749
 
750
+ #: The escalated-probe window: how long the port may stay silent before
751
+ #: "unresponsive" is a conclusion rather than a guess.
752
+ #:
753
+ #: A single short ``/__ping__`` cannot tell a dead daemon from a busy one: on
754
+ #: 2026-10-19 two consecutive 1.5s probes timed out on a machine-global daemon
755
+ #: that was still accepting ws clients, and a fresh ``serve`` SIGTERMed it two
756
+ #: seconds later — it was never wedged, just slow. Silence is therefore measured
757
+ #: across this window, which every escalated attempt may spend in full: anything
758
+ #: that answers inside it is alive, and only a holder silent for the WHOLE
759
+ #: window is called unresponsive. Bounded on purpose — the probe sits on the
760
+ #: CLI's hot path, so the worst case for a port that accepts and then says
761
+ #: nothing is ``2 x 1.5s`` (``confirm=True``) plus this window. Nothing else pays
762
+ #: it: a responsive daemon answers the short probes, a dead one is ``refused``,
763
+ #: and neither escalates.
764
+ ESCALATED_PROBE_WINDOW_S = 6.0
765
+
766
+ #: Upper bound on escalated attempts. An attempt may spend what is left of the
767
+ #: window, so a real timeout normally runs once; the bound exists so an
768
+ #: observation that returns *early* can never turn the escalation into a spin.
769
+ ESCALATED_PROBE_ATTEMPTS = 3
770
+
771
+ #: Probe kinds that mean "nothing usable came back": a socket that opened and
772
+ #: then said nothing, or bytes that were not HTTP. These are exactly the kinds
773
+ #: that must never be read as ``foreign`` — "something else is on the port" is
774
+ #: an observation, not an inference from silence.
775
+ SILENT_PROBE_KINDS = ("timeout", "garbage")
776
+
777
+
778
+ def probes_until_answered(
779
+ host: str,
780
+ port: int,
781
+ *,
782
+ window: float | None = None,
783
+ probe=None,
784
+ ) -> list[EndpointProbe]:
785
+ """Re-probe ``host:port`` inside a bounded window until something answers.
786
+
787
+ The one escalation both liveness callers use: ``daemon_lifecycle.diagnose``
788
+ before it calls a silent endpoint unresponsive, and ``serve``'s port reclaim
789
+ before it SIGTERMs whoever holds the port. One short probe is not evidence —
790
+ a daemon that is merely busy misses it (see
791
+ :data:`ESCALATED_PROBE_WINDOW_S`) — so the question is asked again, with a
792
+ much larger budget, until either something comes back or the window runs
793
+ out. Only a ``timeout`` is re-asked (see :attr:`EndpointProbe.timed_out`):
794
+ bytes that were not HTTP are an answer, and asking again would spend the
795
+ window for information we already have.
796
+
797
+ Returns every probe taken, in order: the last one carries the observation,
798
+ and the whole list is the evidence a caller records (kind plus measured
799
+ latency) before it acts on it. Never raises.
800
+ """
801
+ window = ESCALATED_PROBE_WINDOW_S if window is None else window
802
+ probe = probe_endpoint_sync if probe is None else probe
803
+ observed: list[EndpointProbe] = []
804
+ deadline = time.monotonic() + window
805
+ while len(observed) < ESCALATED_PROBE_ATTEMPTS:
806
+ remaining = deadline - time.monotonic()
807
+ if remaining <= 0:
808
+ break
809
+ # The whole remainder, deliberately not a divided slice: a daemon that
810
+ # answers 5s into a 6s window must be caught by the attempt that is
811
+ # waiting when it answers, and a divided budget would have given up on
812
+ # it three times over.
813
+ observed.append(probe(host, port, timeout=remaining))
814
+ if not observed[-1].timed_out:
815
+ break
816
+ return observed
817
+
818
+
718
819
  def probe_endpoint_sync(host: str, port: int, timeout: float = 1.5) -> EndpointProbe:
719
820
  """Classify whatever is on ``host:port``. Never raises.
720
821
 
721
822
  Same request as :func:`ping_status_sync`, but keeps the response instead
722
- of collapsing every non-pong into "no daemon".
823
+ of collapsing every non-pong into "no daemon", and stamps how long the
824
+ probe took (``latency_ms``).
723
825
  """
826
+ started = time.monotonic()
827
+ observed = _probe_endpoint_once(host, port, timeout)
828
+ return replace(observed,
829
+ latency_ms=round((time.monotonic() - started) * 1000.0, 1))
830
+
831
+
832
+ def _probe_endpoint_once(host: str, port: int, timeout: float) -> EndpointProbe:
833
+ """One classification attempt inside ``timeout``. No latency stamping."""
724
834
  deadline = time.monotonic() + timeout
725
835
  try:
726
836
  sock = socket.create_connection((host, port), timeout=timeout)
@@ -852,6 +962,105 @@ def log_lifecycle(event: str, **fields: object) -> None:
852
962
  pass
853
963
 
854
964
 
965
+ # ---- attributed shutdown (ADR-0012 rule 5) --------------------------------
966
+
967
+ #: How recently the ``stop`` verb must have recorded its own ``LIFECYCLE stop``
968
+ #: for a SIGTERM to count as that verb's doing. The verb writes the line and
969
+ #: then signals, so the real gap is milliseconds; the window only has to
970
+ #: survive a loaded machine.
971
+ VERB_STOP_ATTRIBUTION_S = 10.0
972
+
973
+ #: Bytes read back from the daemon log when looking for that line. Read from
974
+ #: the end: this file is multi-megabyte on a machine that has been up a while,
975
+ #: and only the last few seconds can matter.
976
+ _LOG_SCAN_BYTES = 65536
977
+
978
+
979
+ def _log_tail_text(limit: int = _LOG_SCAN_BYTES) -> str:
980
+ """The last *limit* bytes of the daemon log, decoded (empty when absent)."""
981
+ start = 0
982
+ try:
983
+ with log_path().open("rb") as fh:
984
+ fh.seek(0, os.SEEK_END)
985
+ size = fh.tell()
986
+ start = max(0, size - limit)
987
+ fh.seek(start)
988
+ data = fh.read()
989
+ except OSError:
990
+ return ""
991
+ text = data.decode("utf-8", "replace")
992
+ # Drop the partial first line of a windowed read.
993
+ return text.split("\n", 1)[-1] if start else text
994
+
995
+
996
+ def log_tail(lines: int = 12) -> str:
997
+ """The last few non-empty lines of the daemon log.
998
+
999
+ The CLI-owned daemon's channel: unlike a launchd-owned one it is spawned
1000
+ with ``stderr=DEVNULL`` (``daemon_lifecycle._spawn_detached``), so this file
1001
+ is the only place its startup says anything.
1002
+ """
1003
+ tail = [ln for ln in _log_tail_text().splitlines() if ln.strip()][-lines:]
1004
+ return "\n".join(tail)
1005
+
1006
+
1007
+ def stop_recorded_by_a_verb(pid: int, *, now: float | None = None) -> bool:
1008
+ """Whether a verb's own ``LIFECYCLE stop pid=<pid>`` line is still fresh.
1009
+
1010
+ ``stop`` records the stop *before* it signals, so the daemon on the
1011
+ receiving end can tell "a verb asked for this" from "someone signalled
1012
+ me" by reading the trail that already exists, instead of inventing a
1013
+ second mechanism beside it.
1014
+ """
1015
+ import datetime as _dt
1016
+ import re as _re
1017
+
1018
+ now = time.time() if now is None else now
1019
+ # `pid=<pid>` must end the field: `pid=1234` is not evidence about 12345.
1020
+ stop_line = _re.compile(rf" LIFECYCLE stop pid={pid}(?=\s|$)")
1021
+ for line in _log_tail_text().splitlines():
1022
+ if not stop_line.search(line):
1023
+ continue
1024
+ stamp = line[:24] # _iso_now(): "%Y-%m-%dT%H:%M:%S%z"
1025
+ try:
1026
+ at = _dt.datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%S%z").timestamp()
1027
+ except ValueError:
1028
+ continue
1029
+ if 0.0 <= now - at <= VERB_STOP_ATTRIBUTION_S:
1030
+ return True
1031
+ return False
1032
+
1033
+
1034
+ def record_signal_shutdown(signum: int) -> None:
1035
+ """ADR-0012 rule 5 for the one stop no verb can record: a signal.
1036
+
1037
+ A stop a verb asked for is already attributed by that verb's own
1038
+ ``LIFECYCLE stop`` line. A SIGTERM from anywhere else — a script, a shell,
1039
+ ``kill`` — used to leave nothing behind but ``shutdown requested``: on
1040
+ 2026-10-19 a dev-checkout script took the machine-global daemon down
1041
+ mid-call and reconstructing who did it cost hours. So the daemon writes its
1042
+ own line, naming the signal, its pid and the initiator from its
1043
+ environment, and skips it when a fresh ``LIFECYCLE stop`` for this pid is
1044
+ already on disk — a verb's record is never duplicated.
1045
+
1046
+ A ``restart``/``replace`` SIGTERM still gets this line: those verbs record
1047
+ the *request* before they signal, so the daemon observing the signal is the
1048
+ only proof it arrived — a different fact from who asked for it.
1049
+
1050
+ Called from the signal handler, before the shutdown sequence starts.
1051
+ """
1052
+ import signal as _signal
1053
+
1054
+ pid = os.getpid()
1055
+ if stop_recorded_by_a_verb(pid):
1056
+ return
1057
+ try:
1058
+ name = _signal.Signals(signum).name
1059
+ except ValueError:
1060
+ name = str(signum)
1061
+ log_lifecycle("signal", sig=name, pid=pid, initiator=initiator_from_env())
1062
+
1063
+
855
1064
  #: Collapse window for the "already running" line. launchd's KeepAlive
856
1065
  #: respawns a daemon that exits 1 every few seconds forever, and each spawn is
857
1066
  #: a fresh process, so the collapse state has to live on disk.