browserwright 0.18.5__tar.gz → 0.19.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. {browserwright-0.18.5/src/browserwright.egg-info → browserwright-0.19.0}/PKG-INFO +1 -1
  2. {browserwright-0.18.5 → browserwright-0.19.0}/pyproject.toml +1 -1
  3. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/_executor/process.py +34 -0
  4. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/_executor/protocol.py +35 -0
  5. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/cli.py +76 -71
  6. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/_ipc.py +31 -0
  7. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/launchagent.py +21 -63
  8. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/daemon.py +109 -222
  9. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/exec_relay.py +43 -65
  10. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/executor_registry.py +15 -8
  11. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/extension_upstream.py +362 -20
  12. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/facade.py +7 -5
  13. browserwright-0.19.0/src/browserwright/daemon/server/listener.py +774 -0
  14. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/proxy.py +20 -13
  15. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/relay.py +55 -14
  16. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/session_state.py +11 -1
  17. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/status.py +5 -5
  18. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/upstream.py +296 -79
  19. browserwright-0.19.0/src/browserwright/daemon/server/upstream_context.py +415 -0
  20. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/verbs.py +175 -359
  21. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/userscripts.py +19 -0
  22. browserwright-0.19.0/src/browserwright/daemon_lifecycle.py +392 -0
  23. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon_url.py +2 -94
  24. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/errors.py +7 -6
  25. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/health.py +33 -41
  26. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/install.py +10 -20
  27. browserwright-0.19.0/src/browserwright/mode_b_client.py +137 -0
  28. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/repl/playwright_handle.py +6 -6
  29. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/session.py +3 -3
  30. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/session_create.py +66 -160
  31. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/skill_runtime.md +1 -1
  32. {browserwright-0.18.5 → browserwright-0.19.0/src/browserwright.egg-info}/PKG-INFO +1 -1
  33. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright.egg-info/SOURCES.txt +2 -0
  34. browserwright-0.18.5/src/browserwright/daemon/server/listener.py +0 -1586
  35. browserwright-0.18.5/src/browserwright/mode_b_client.py +0 -364
  36. {browserwright-0.18.5 → browserwright-0.19.0}/LICENSE +0 -0
  37. {browserwright-0.18.5 → browserwright-0.19.0}/README.md +0 -0
  38. {browserwright-0.18.5 → browserwright-0.19.0}/setup.cfg +0 -0
  39. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/__init__.py +0 -0
  40. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/__main__.py +0 -0
  41. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/_executor/__init__.py +0 -0
  42. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/_executor/__main__.py +0 -0
  43. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/_executor/client.py +0 -0
  44. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/_text.py +0 -0
  45. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/cdp.py +0 -0
  46. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/__init__.py +0 -0
  47. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/_net.py +0 -0
  48. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/_rpc.py +0 -0
  49. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/_stale.py +0 -0
  50. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/backends/__init__.py +0 -0
  51. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/backends/base.py +0 -0
  52. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/backends/cdp.py +0 -0
  53. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/backends/extension.py +0 -0
  54. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/cli.py +0 -0
  55. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/config.py +0 -0
  56. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/doctor.py +0 -0
  57. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/errors.py +0 -0
  58. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/launch_chrome.py +0 -0
  59. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/observability.py +0 -0
  60. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/platforms.py +0 -0
  61. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/probe.py +0 -0
  62. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/relay_status.py +0 -0
  63. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/resolver.py +0 -0
  64. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/restart_guard.py +0 -0
  65. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/__init__.py +0 -0
  66. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/facade_extension.py +0 -0
  67. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/server/state.py +0 -0
  68. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/daemon/supervise.py +0 -0
  69. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/discovery.py +0 -0
  70. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/memory/__init__.py +0 -0
  71. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/memory/_lock.py +0 -0
  72. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/memory/_md.py +0 -0
  73. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/memory/_yaml.py +0 -0
  74. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/memory/global_mem.py +0 -0
  75. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/memory/site_mem.py +0 -0
  76. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/output_schema.py +0 -0
  77. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/primitives/__init__.py +0 -0
  78. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/primitives/discovery_api.py +0 -0
  79. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/primitives/http.py +0 -0
  80. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/primitives/site.py +0 -0
  81. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/repl/__init__.py +0 -0
  82. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/repl/_md_convert.py +0 -0
  83. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/repl/_md_normalize.py +0 -0
  84. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/repl/_namespace.py +0 -0
  85. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/repl/_smart_goto.py +0 -0
  86. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/repl/inline.py +0 -0
  87. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/repl/markdown.py +0 -0
  88. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/repl/snapshot.py +0 -0
  89. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/repl/vendor/README.md +0 -0
  90. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/repl/vendor/readability.js +0 -0
  91. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/session_ctx.py +0 -0
  92. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/session_registry.py +0 -0
  93. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/session_runtime.py +0 -0
  94. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/github.com/SKILL.md +0 -0
  95. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/github.com/memory.md +0 -0
  96. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/github.com/tasks/list_issues.py +0 -0
  97. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/google.com/SKILL.md +0 -0
  98. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/google.com/memory.md +0 -0
  99. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/google.com/tasks/search.py +0 -0
  100. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/producthunt.com/SKILL.md +0 -0
  101. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/producthunt.com/memory.md +0 -0
  102. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/producthunt.com/tasks/today.py +0 -0
  103. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/wikipedia.org/SKILL.md +0 -0
  104. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/wikipedia.org/memory.md +0 -0
  105. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/wikipedia.org/tasks/lookup.py +0 -0
  106. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/ycombinator.com/SKILL.md +0 -0
  107. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/ycombinator.com/memory.md +0 -0
  108. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/site_skills_starter/ycombinator.com/tasks/front_page.py +0 -0
  109. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/skill_doc.py +0 -0
  110. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/tab_surface.py +0 -0
  111. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/task_runner.py +0 -0
  112. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright/version.py +0 -0
  113. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright.egg-info/dependency_links.txt +0 -0
  114. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright.egg-info/entry_points.txt +0 -0
  115. {browserwright-0.18.5 → browserwright-0.19.0}/src/browserwright.egg-info/requires.txt +0 -0
  116. {browserwright-0.18.5 → browserwright-0.19.0}/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.18.5
3
+ Version: 0.19.0
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.18.5"
18
+ version = "0.19.0"
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"
@@ -44,6 +44,9 @@ from .._text import spill_text, truncate_hard
44
44
  from ..errors import BrowserwrightError, TabRebindFailed, serialize
45
45
  from .protocol import (
46
46
  MAX_TEXT_CHARS,
47
+ RECOVERY_BOUND,
48
+ RECOVERY_REBOUND,
49
+ RECOVERY_TARGET_GONE,
47
50
  TERMINAL_DEADLINE_EXCEEDED,
48
51
  TERMINAL_RESET_REQUESTED,
49
52
  TERMINAL_TARGET_CLOSED,
@@ -264,6 +267,11 @@ class _Worker:
264
267
  # not yet processed the target's destruction (its `pages` cache is fed
265
268
  # by channel events that only drain while a sync call is in flight).
266
269
  self._page_maybe_dead = False
270
+ # ADR-0013 rule 1: what this call observed about the tab binding, for
271
+ # the daemon's recovery state machine (``ExecuteResponse
272
+ # .recovery_event``). The executor reports; it never decides the
273
+ # session's recovery state.
274
+ self._call_recovery_event: dict[str, str] | None = None
267
275
  # The globals dict of the CURRENTLY executing heredoc, so a mid-call
268
276
  # rebind can swap its ``page`` name (issue #21 same-call visibility).
269
277
  self._active_globals: dict[str, Any] | None = None
@@ -671,8 +679,15 @@ class _Worker:
671
679
  finally:
672
680
  self._rebinding_page = False
673
681
  self._page_maybe_dead = False
682
+ self._report_recovery(
683
+ RECOVERY_REBOUND, "executor re-bound page to a live session tab")
674
684
  return True
675
685
 
686
+ def _report_recovery(self, kind: str, detail: str) -> None:
687
+ """Record this call's tab-binding outcome for the daemon. A later
688
+ outcome in the same call supersedes an earlier one."""
689
+ self._call_recovery_event = {"kind": kind, "detail": detail}
690
+
676
691
  def _reconcile_page_binding(self) -> None:
677
692
  """Before each execute, rebind the live page if the session's DURABLE
678
693
  current target (ledger) moved — e.g. an in-process CLI heredoc called
@@ -810,6 +825,7 @@ class _Worker:
810
825
  self._call_warnings = []
811
826
  self._call_screenshots = []
812
827
  self._rebinds_this_call = 0
828
+ self._call_recovery_event = None
813
829
  try:
814
830
  self._ensure_cold_started()
815
831
  except BrowserwrightError as e:
@@ -842,6 +858,7 @@ class _Worker:
842
858
  # cold-restart (terminal recycle) instead of attempting another
843
859
  # rebind, and answer with the DISTINCT error so the caller can tell
844
860
  # "the tab died" from "the browser cannot give me a tab at all".
861
+ self._report_recovery(RECOVERY_TARGET_GONE, str(e)[:200])
845
862
  return self._finish(
846
863
  io.StringIO(), error=serialize(e), exit_code=e.exit_code,
847
864
  terminal_reason=TERMINAL_TARGET_CLOSED)
@@ -958,6 +975,8 @@ class _Worker:
958
975
  f"`browserwright recover --session {sid}`; it re-attaches or "
959
976
  "opens the session tab and returns healthy before you retry."
960
977
  )
978
+ self._report_recovery(
979
+ RECOVERY_TARGET_GONE, f"tab gone; rebind failed: {failure}"[:200])
961
980
  return self._finish(
962
981
  buf, error=error, exit_code=exit_code,
963
982
  terminal_reason=TERMINAL_TARGET_CLOSED,
@@ -1046,6 +1065,14 @@ class _Worker:
1046
1065
  )
1047
1066
  capped_warnings, warn_cut = _cap_warnings(raw_warnings)
1048
1067
 
1068
+ # Only a completed call proves the held page is live; a failed one
1069
+ # makes no claim unless a rebind above already reported one.
1070
+ recovery_event = self._call_recovery_event
1071
+ if (recovery_event is None and error is None
1072
+ and terminal_reason is None and self._page is not None):
1073
+ recovery_event = {"kind": RECOVERY_BOUND,
1074
+ "detail": "executor completed a call on a live tab"}
1075
+
1049
1076
  return ExecuteResponse(
1050
1077
  console=console,
1051
1078
  return_value=return_value,
@@ -1056,6 +1083,7 @@ class _Worker:
1056
1083
  truncated=console_cut or rv_cut or warn_cut or task_cut,
1057
1084
  terminal_reason=terminal_reason,
1058
1085
  task_result_json=task_result_json,
1086
+ recovery_event=recovery_event,
1059
1087
  )
1060
1088
 
1061
1089
  def _run_task_on_live_surface(
@@ -1280,6 +1308,12 @@ def main(argv: list[str] | None = None) -> int:
1280
1308
  # Keep the env marker for helper code that still reads it; the --session
1281
1309
  # flag is authoritative for binding.
1282
1310
  os.environ["BD_SESSION"] = session_id
1311
+ import logging
1312
+ # stderr is the daemon-kept executor log; stamp each line so a post-mortem
1313
+ # can line it up with the daemon log.
1314
+ logging.basicConfig(
1315
+ level=logging.WARNING,
1316
+ format=f"%(asctime)s session={session_id} %(levelname)s %(name)s: %(message)s")
1283
1317
 
1284
1318
  executor_id = args.executor_id
1285
1319
  worker = _Worker(session_id, executor_id=executor_id)
@@ -49,6 +49,25 @@ TERMINAL_REASONS = frozenset(
49
49
  }
50
50
  )
51
51
 
52
+ #: What the executor observed about the session's tab binding during one call
53
+ #: — reported, never decided (ADR-0013 rule 1: the daemon's recovery state
54
+ #: machine is the only authority on a session's recovery state). The exec relay
55
+ #: forwards the event to that machine and strips it from the agent-facing
56
+ #: response.
57
+ #:
58
+ #: - ``bound``: the call completed on the page the executor already held.
59
+ #: - ``rebound``: the held page's tab was gone and the executor re-bound
60
+ #: ``page`` to a live tab of the session in place (before the call, or
61
+ #: mid-call — the "RETRY the call" answer).
62
+ #: - ``target-gone``: the tab was gone and re-binding failed; the executor
63
+ #: recycles itself.
64
+ RECOVERY_BOUND = "bound"
65
+ RECOVERY_REBOUND = "rebound"
66
+ RECOVERY_TARGET_GONE = "target-gone"
67
+ RECOVERY_EVENT_KINDS = frozenset(
68
+ {RECOVERY_BOUND, RECOVERY_REBOUND, RECOVERY_TARGET_GONE}
69
+ )
70
+
52
71
  _LEN = struct.Struct(">I")
53
72
  _MAX_FRAME = 256 * 1024 * 1024 # generous: screenshots land here in PR3
54
73
  _ENV_NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
@@ -217,6 +236,10 @@ class ExecuteResponse:
217
236
  # JSON encoding of a task's result. ``None`` means this was not a
218
237
  # successful task response; the JSON string ``"null"`` is a valid result.
219
238
  task_result_json: str | None = None
239
+ # ``{"kind": RECOVERY_*, "detail": str}`` or None when the call says
240
+ # nothing about the tab binding. Addressed to the daemon, not the agent:
241
+ # the exec relay consumes it (see ``RECOVERY_EVENT_KINDS``).
242
+ recovery_event: dict[str, str] | None = None
220
243
 
221
244
  def to_dict(self) -> dict[str, Any]:
222
245
  return {
@@ -229,6 +252,7 @@ class ExecuteResponse:
229
252
  "truncated": self.truncated,
230
253
  "terminal_reason": self.terminal_reason,
231
254
  "task_result_json": self.task_result_json,
255
+ "recovery_event": self.recovery_event,
232
256
  }
233
257
 
234
258
  @classmethod
@@ -246,6 +270,13 @@ class ExecuteResponse:
246
270
  raise ValueError(
247
271
  "ExecuteResponse.task_result_json must contain valid JSON"
248
272
  ) from e
273
+ # Lenient on purpose: this field is observation for the daemon, and a
274
+ # client that rejected an unknown kind would treat the whole response
275
+ # as malformed and reap a healthy executor.
276
+ recovery_event = d.get("recovery_event")
277
+ if not (isinstance(recovery_event, dict)
278
+ and recovery_event.get("kind") in RECOVERY_EVENT_KINDS):
279
+ recovery_event = None
249
280
  return cls(
250
281
  console=str(d.get("console") or ""),
251
282
  return_value=d.get("return_value"),
@@ -256,6 +287,10 @@ class ExecuteResponse:
256
287
  truncated=bool(d.get("truncated") or False),
257
288
  terminal_reason=terminal_reason,
258
289
  task_result_json=task_result_json,
290
+ recovery_event=(
291
+ {"kind": str(recovery_event["kind"]),
292
+ "detail": str(recovery_event.get("detail") or "")}
293
+ if recovery_event is not None else None),
259
294
  )
260
295
 
261
296
 
@@ -15,7 +15,6 @@ from __future__ import annotations
15
15
 
16
16
  import json
17
17
  import os
18
- import subprocess
19
18
  import sys
20
19
  from pathlib import Path
21
20
  from typing import Optional
@@ -593,7 +592,7 @@ def _cmd_markdown(args: list[str]) -> int:
593
592
  create=(backend == "cdp"),
594
593
  attach=None,
595
594
  name=str(kw.get("name", "markdown")),
596
- )
595
+ ).id
597
596
  except (ValueError, BrowserwrightError) as e:
598
597
  print(str(e), file=sys.stderr)
599
598
  return 1
@@ -785,12 +784,13 @@ def _cmd_recover(args: list[str], *, session_id: Optional[str] = None) -> int:
785
784
  """`browserwright recover --session <id>` — ADR-0013 rule 2, the ONE
786
785
  thing an agent does when a call failed.
787
786
 
788
- Client side first: a dead daemon cannot answer an RPC, so the daemon
789
- self-check (three criteria, two agreeing probes) runs here. "Gone" or
790
- "stale version" is repaired through the default endpoint's on-demand
791
- start (the sanctioned restart path); "something else answers on the
792
- port" and "the probes disagree" are `needs-human` because recovery never
793
- signals or replaces an unidentified process. Then the daemon runs
787
+ Client side first: a dead daemon cannot answer an RPC, so
788
+ `daemon_lifecycle.diagnose(confirm=True)` (two agreeing probes) runs
789
+ here. "Down" or "stale" on the default endpoint is repaired by
790
+ `daemon_lifecycle.ensure` (the sanctioned start/replace path);
791
+ "something else answers on the port", "the probes disagree" and an
792
+ explicitly configured endpoint are `needs-human` because recovery never
793
+ signals or replaces a process it cannot prove is ours. Then the daemon runs
794
794
  the per-session ladder and reports the state reached. Exit 0 = healthy,
795
795
  4 = needs-human, 2 = usage."""
796
796
  kw = _parse_kv_args(args)
@@ -799,54 +799,35 @@ def _cmd_recover(args: list[str], *, session_id: Optional[str] = None) -> int:
799
799
  print("usage: browserwright recover --session=<id>", file=sys.stderr)
800
800
  return 2
801
801
  sid = str(sid)
802
- from . import session_create
803
- from .daemon.launchagent import daemon_self_check
804
- from .daemon_url import daemon_endpoint
802
+ from . import daemon_lifecycle as lifecycle
805
803
 
806
804
  steps: list[str] = []
807
- ep = daemon_endpoint()
808
- verdict = daemon_self_check(None)
809
- if not verdict["healthy"]:
810
- crit = verdict["criterion"]
811
- if crit in ("gone", "version") and not ep.explicit:
812
- steps.append(f"daemon: {verdict['detail']}; starting the installed one")
813
- from .daemon import _ipc
814
- _ipc.log_lifecycle(
815
- "automatic-recovery", criterion=crit,
816
- probes=",".join(verdict.get("probes") or []),
817
- reason=verdict["detail"], session=sid)
818
- try:
819
- session_create._ensure_daemon_running()
820
- except Exception as e: # noqa: BLE001
821
- return _recover_report(sid, "needs-human", steps,
822
- f"daemon could not be started: {e}")
823
- from .mode_b_client import ModeBClient
824
- if not ModeBClient().wait_until_alive(timeout=20.0):
825
- return _recover_report(sid, "needs-human", steps,
826
- "no daemon answered within 20s after the "
827
- "start; `browserwright-daemon logs` has "
828
- "its last words")
829
- steps.append("daemon: up")
830
- else:
831
- return _recover_report(sid, "needs-human", steps, verdict["detail"])
805
+ verdict = lifecycle.diagnose(confirm=True)
806
+ if verdict.healthy:
807
+ steps.append(f"daemon: {verdict.detail}")
808
+ elif verdict.replaceable:
809
+ steps.append(f"daemon: {verdict.detail}; starting the installed one")
810
+ try:
811
+ after = lifecycle.ensure(f"recover session={sid}", wait=20.0)
812
+ except Exception as e: # noqa: BLE001
813
+ return _recover_report(sid, "needs-human", steps,
814
+ f"daemon could not be started: {e}")
815
+ if not after.up:
816
+ return _recover_report(sid, "needs-human", steps,
817
+ "no daemon answered within 20s after the "
818
+ "start; `browserwright-daemon logs` has "
819
+ "its last words")
820
+ steps.append("daemon: up")
832
821
  else:
833
- steps.append(f"daemon: {verdict['detail']}")
822
+ return _recover_report(sid, "needs-human", steps, verdict.detail)
834
823
 
835
- import json as _json
836
- import subprocess
837
- try:
838
- proc = subprocess.run(
839
- ["browserwright-daemon", "recover", "--session", sid],
840
- capture_output=True, text=True, timeout=120.0,
841
- env=session_create._daemon_child_env())
842
- except (OSError, subprocess.SubprocessError) as e:
824
+ proc = lifecycle.run_verb(["recover", "--session", sid], timeout=120.0)
825
+ if proc.missing or proc.timed_out:
843
826
  return _recover_report(sid, "needs-human", steps,
844
- f"could not ask the daemon to recover: {e}")
845
- try:
846
- result = _json.loads(proc.stdout.strip().splitlines()[-1])
847
- if not isinstance(result, dict):
848
- raise ValueError("recover result is not an object")
849
- except (ValueError, IndexError):
827
+ f"could not ask the daemon to recover: "
828
+ f"{proc.stderr}")
829
+ result = proc.json()
830
+ if result is None:
850
831
  detail = ((proc.stderr or proc.stdout).strip()[:400]
851
832
  if proc.returncode != 0 else
852
833
  f"unreadable recover result: {proc.stdout[:200]!r}")
@@ -916,7 +897,7 @@ def _cmd_session(args: list[str], *, session_id: Optional[str] = None) -> int:
916
897
  file=sys.stderr)
917
898
  return 1
918
899
  try:
919
- sid = session_create.new(
900
+ made = session_create.new(
920
901
  backend=backend, create=bool(kw.get("create")),
921
902
  attach=kw.get("attach"), name=kw.get("name"),
922
903
  reuse=bool(kw.get("reuse")),
@@ -924,11 +905,16 @@ def _cmd_session(args: list[str], *, session_id: Optional[str] = None) -> int:
924
905
  except ValueError as e:
925
906
  print(str(e), file=sys.stderr)
926
907
  return 1
927
- if session_create.last_new_reused == sid:
908
+ sid = made.id
909
+ if made.reused:
928
910
  print(f"OK: reusing session {sid} (--reuse matched an existing "
929
911
  f"{backend} session named {kw.get('name')!r})", file=sys.stderr)
930
912
  else:
931
913
  print(f"OK: session {sid} created", file=sys.stderr)
914
+ if not made.daemon.up:
915
+ print(f"warning: the daemon is not answering yet — "
916
+ f"{made.daemon.detail}; `browserwright doctor` says why",
917
+ file=sys.stderr)
932
918
  print(sid) # token-frugal: bare id
933
919
  return 0
934
920
 
@@ -1027,14 +1013,14 @@ def _cmd_userscript(args: list[str], *, session_id: Optional[str] = None) -> int
1027
1013
  verify = "--verify" in args
1028
1014
  fwd = [a for a in args if a != "--verify"]
1029
1015
 
1030
- daemon_cmd = ["browserwright-daemon", "userscript"]
1016
+ verb = ["userscript"]
1031
1017
  if session_id:
1032
- daemon_cmd += ["--session", session_id]
1033
- # ADR-0011: forward this process's resolved endpoint, or the child CLI
1034
- # would push/remove userscripts on whichever daemon its own default
1035
- # resolves to.
1036
- from .daemon_url import child_env
1037
- result = subprocess.run([*daemon_cmd, *fwd], env=child_env())
1018
+ verb += ["--session", session_id]
1019
+ # The adapter forwards this process's resolved endpoint (ADR-0011), or the
1020
+ # child CLI would push/remove userscripts on whichever daemon its own
1021
+ # default resolves to. Output goes straight to this terminal.
1022
+ from . import daemon_lifecycle as lifecycle
1023
+ result = lifecycle.run_verb([*verb, *fwd], timeout=None, capture=False)
1038
1024
  if result.returncode != 0:
1039
1025
  # Push failed — don't reload/screenshot a stale state. Surface the
1040
1026
  # push failure so the agent fixes the script first.
@@ -1167,19 +1153,38 @@ def _cmd_version(args: list[str]) -> int:
1167
1153
 
1168
1154
 
1169
1155
  def _extension_relay_status() -> dict | None:
1170
- import os
1171
- import urllib.request
1156
+ """``{daemon_version, extension_details}`` for `version check`.
1157
+
1158
+ The daemon's version comes from the one source every lifecycle decision
1159
+ uses — the resolved endpoint's ``/__ping__`` (``daemon_lifecycle``), so
1160
+ `--daemon-url` / ``$BW_DAEMON_URL`` are honoured. The connected
1161
+ extensions come from the relay's ``/__status__``, located through
1162
+ ``Config`` (``BD_EXTENSION_PORT`` / toml / ``--config``) — and only when
1163
+ the endpoint is on this machine: the relay is machine-local (ADR-0011),
1164
+ so a remote daemon's extensions are not ours to read, and the local
1165
+ relay would describe a different daemon.
1166
+ """
1167
+ from . import daemon_lifecycle as lifecycle
1172
1168
 
1173
- port = os.environ.get("BD_EXTENSION_PORT") or "19989"
1174
- try:
1175
- with urllib.request.urlopen(
1176
- f"http://127.0.0.1:{port}/__status__",
1177
- timeout=1.0,
1178
- ) as resp:
1179
- payload = json.loads(resp.read().decode("utf-8"))
1180
- return payload if isinstance(payload, dict) else None
1181
- except Exception:
1169
+ verdict = lifecycle.diagnose()
1170
+ if not verdict.up:
1182
1171
  return None
1172
+ out: dict = {"daemon_version": verdict.version, "extension_details": []}
1173
+ if not verdict.endpoint.is_locally_signalable:
1174
+ return out
1175
+ try:
1176
+ from .daemon.config import load
1177
+ from .daemon.relay_status import fetch_json
1178
+ from .daemon_url import cli_config_path
1179
+
1180
+ cfg = load(cli_config_path=cli_config_path())
1181
+ host, port = cfg.backends.extension.resolved_host_port()
1182
+ relay = fetch_json(host, port)
1183
+ except Exception: # noqa: BLE001 - version check must never fail on this
1184
+ relay = None
1185
+ if relay:
1186
+ out["extension_details"] = relay.get("extension_details") or []
1187
+ return out
1183
1188
 
1184
1189
 
1185
1190
  def _split_daemon_url(argv: list[str]) -> list[str]:
@@ -210,6 +210,37 @@ def executor_inflight_path(session_id: str) -> Path:
210
210
  return _executor_inflight_dir() / f"bw-exec-{_exec_shortid(session_id)}.inflight"
211
211
 
212
212
 
213
+ #: An executor log past this is rotated to ``.1`` on the next spawn, so a
214
+ #: long-lived session keeps its recent history without growing forever.
215
+ EXECUTOR_LOG_MAX_BYTES = 1_000_000
216
+
217
+
218
+ def executor_log_path(session_id: str) -> Path:
219
+ """The executor's stderr: its warnings and any crash traceback.
220
+
221
+ Lives with the other private sidecars and deliberately survives
222
+ ``cleanup_executor`` — a log is only needed after the executor is gone."""
223
+ return _executor_inflight_dir() / f"bw-exec-{_exec_shortid(session_id)}.log"
224
+
225
+
226
+ def open_executor_log(session_id: str):
227
+ """Open the session's executor log for appending (rotating an oversized
228
+ one). Returns a binary file object, or ``None`` when the private directory
229
+ is unusable — losing the log must never block spawning the executor."""
230
+ try:
231
+ _ensure_executor_inflight_dir()
232
+ path = executor_log_path(session_id)
233
+ try:
234
+ if path.stat().st_size > EXECUTOR_LOG_MAX_BYTES:
235
+ path.replace(path.with_name(path.name + ".1"))
236
+ except FileNotFoundError:
237
+ pass
238
+ fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600)
239
+ return os.fdopen(fd, "ab")
240
+ except OSError:
241
+ return None
242
+
243
+
213
244
  def _executor_inflight_dir() -> Path:
214
245
  """Per-user private home for executor observability sidecars."""
215
246
  return runtime_dir() / f"browserwright-{os.geteuid()}"
@@ -517,11 +517,15 @@ def restart(cfg, *, force: bool = False, timeout: float = 5.0) -> dict:
517
517
  # move that on 2026-09-01 took out another agent's session. Name the
518
518
  # per-session states and the verb that acts on them instead.
519
519
  if not force:
520
- verdict = daemon_self_check(cfg, expected_version=want)
521
- if verdict["healthy"]:
520
+ from .. import daemon_lifecycle
521
+
522
+ verdict = daemon_lifecycle.diagnose(
523
+ confirm=True, endpoint=restart_endpoint(cfg),
524
+ expected_version=want)
525
+ if verdict.healthy:
522
526
  states = _session_states_text(cfg)
523
527
  raise LaunchAgentError(
524
- f"refusing to restart: {verdict['detail']}. A healthy daemon "
528
+ f"refusing to restart: {verdict.detail}. A healthy daemon "
525
529
  "is not what is wrong.\n"
526
530
  f"{states}"
527
531
  "For a broken session run `browserwright recover --session "
@@ -581,70 +585,24 @@ def restart(cfg, *, force: bool = False, timeout: float = 5.0) -> dict:
581
585
  expected=want, timeout=timeout), 3)
582
586
 
583
587
 
584
- def daemon_self_check(cfg, *, expected_version: str | None = None) -> dict:
585
- """The three daemon diagnoses of ADR-0013 rule 2, each confirmed by TWO
586
- consecutive probes so a transient glitch never triggers replacement.
588
+ def restart_endpoint(cfg):
589
+ """The endpoint `restart` diagnoses: THIS command's configured port.
587
590
 
588
- Returns ``{"healthy": bool, "criterion": None|"gone"|"foreign"|
589
- "version", "detail": str, "probes": [kind, kind]}``. ``healthy`` is True
590
- only when both probes found our daemon on the expected version. ``gone``
591
- and ``version`` permit automatic replacement; ``foreign`` is reported for
592
- human resolution because an unidentified process is never signalled.
591
+ Wildcards and specific remote binds are reached locally through the
592
+ co-bound loopback listener; a configured loopback/hostname is used
593
+ verbatim. The port must come from this command's ``cfg``, never a stale
594
+ global endpoint state file belonging to another dev instance (ADR-0012
595
+ rule 6).
593
596
  """
594
- from . import _ipc
595
- from .. import __version__
596
- from ..daemon_url import DaemonEndpoint, daemon_endpoint
597
+ from ..daemon_url import DaemonEndpoint
597
598
  from .config import LOOPBACK_HOST, needs_loopback_cobind
598
599
 
599
- want = expected_version or __version__
600
- if cfg is None or not hasattr(cfg, "resolved_facade_port"):
601
- ep = daemon_endpoint()
602
- else:
603
- host = str(getattr(cfg, "facade_host", LOOPBACK_HOST) or LOOPBACK_HOST)
604
- # Wildcards and specific remote binds are locally reached through the
605
- # co-bound loopback listener; a configured loopback/hostname is used
606
- # verbatim. The port must come from THIS command's cfg, never a stale
607
- # global endpoint state file belonging to another dev instance.
608
- probe_host = LOOPBACK_HOST if (
609
- needs_loopback_cobind(host) or host in ("0.0.0.0", "::", "::0", "*")) else host
610
- port = int(cfg.resolved_facade_port())
611
- ep = DaemonEndpoint(url=f"http://{probe_host}:{port}",
612
- explicit=True, source="restart_config")
613
- probes = [_ipc.probe_endpoint_sync(ep.host, ep.port, timeout=1.5)
614
- for _ in range(2)]
615
- kinds = [p.kind for p in probes]
616
-
617
- def _classification(probe) -> tuple[str, str | None]:
618
- if probe.kind == "ours":
619
- return "ours", probe.version
620
- if probe.kind in ("foreign", "garbage", "timeout"):
621
- return "foreign", None
622
- return "gone", None
623
-
624
- conclusions = [_classification(p) for p in probes]
625
- if conclusions[0] != conclusions[1]:
626
- return {"healthy": False, "criterion": None,
627
- "detail": ("two consecutive probes disagree "
628
- f"({conclusions[0]} then {conclusions[1]}); "
629
- "nothing is concluded from that"),
630
- "probes": kinds}
631
- p = probes[1]
632
- if p.kind == "ours":
633
- if p.version != want:
634
- return {"healthy": False, "criterion": "version",
635
- "detail": (f"the daemon at {ep.host}:{ep.port} runs "
636
- f"{p.version}, installed is {want}"),
637
- "probes": kinds}
638
- return {"healthy": True, "criterion": None,
639
- "detail": (f"the daemon answers at {ep.host}:{ep.port} "
640
- f"(pid {p.pid}, version {p.version or 'unknown'}) "
641
- "on both probes"),
642
- "probes": kinds}
643
- if p.kind in ("foreign", "garbage", "timeout"):
644
- return {"healthy": False, "criterion": "foreign",
645
- "detail": p.describe(), "probes": kinds}
646
- return {"healthy": False, "criterion": "gone",
647
- "detail": p.describe(), "probes": kinds}
600
+ host = str(getattr(cfg, "facade_host", LOOPBACK_HOST) or LOOPBACK_HOST)
601
+ probe_host = LOOPBACK_HOST if (
602
+ needs_loopback_cobind(host) or host in ("0.0.0.0", "::", "::0", "*")) else host
603
+ port = int(cfg.resolved_facade_port())
604
+ return DaemonEndpoint(url=f"http://{probe_host}:{port}",
605
+ explicit=True, source="restart_config")
648
606
 
649
607
 
650
608
  def _session_states_text(cfg) -> str: