browserwright 0.21.0__tar.gz → 0.23.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.21.0/src/browserwright.egg-info → browserwright-0.23.0}/PKG-INFO +1 -1
  2. {browserwright-0.21.0 → browserwright-0.23.0}/pyproject.toml +1 -1
  3. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/__init__.py +12 -0
  4. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/_executor/process.py +63 -19
  5. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/_executor/protocol.py +11 -7
  6. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/cli.py +276 -53
  7. browserwright-0.23.0/src/browserwright/daemon/server/call_deadline.py +127 -0
  8. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/exec_relay.py +25 -4
  9. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/extension_upstream.py +59 -13
  10. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/facade_extension.py +17 -3
  11. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/relay.py +43 -12
  12. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/errors.py +136 -1
  13. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/repl/_smart_goto.py +150 -39
  14. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/repl/inline.py +72 -8
  15. browserwright-0.23.0/src/browserwright/repl/search.py +308 -0
  16. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/skill_runtime.md +76 -11
  17. {browserwright-0.21.0 → browserwright-0.23.0/src/browserwright.egg-info}/PKG-INFO +1 -1
  18. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright.egg-info/SOURCES.txt +2 -0
  19. {browserwright-0.21.0 → browserwright-0.23.0}/LICENSE +0 -0
  20. {browserwright-0.21.0 → browserwright-0.23.0}/README.md +0 -0
  21. {browserwright-0.21.0 → browserwright-0.23.0}/setup.cfg +0 -0
  22. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/__main__.py +0 -0
  23. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/_executor/__init__.py +0 -0
  24. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/_executor/__main__.py +0 -0
  25. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/_executor/client.py +0 -0
  26. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/_text.py +0 -0
  27. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/cdp.py +0 -0
  28. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/__init__.py +0 -0
  29. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/_ipc.py +0 -0
  30. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/_net.py +0 -0
  31. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/_rpc.py +0 -0
  32. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/_stale.py +0 -0
  33. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/backends/__init__.py +0 -0
  34. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/backends/base.py +0 -0
  35. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/backends/cdp.py +0 -0
  36. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/backends/extension.py +0 -0
  37. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/cli.py +0 -0
  38. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/config.py +0 -0
  39. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/doctor.py +0 -0
  40. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/errors.py +0 -0
  41. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/launch_chrome.py +0 -0
  42. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/launchagent.py +0 -0
  43. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/observability.py +0 -0
  44. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/platforms.py +0 -0
  45. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/probe.py +0 -0
  46. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/relay_status.py +0 -0
  47. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/resolver.py +0 -0
  48. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/restart_guard.py +0 -0
  49. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/__init__.py +0 -0
  50. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/daemon.py +0 -0
  51. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/executor_registry.py +0 -0
  52. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/facade.py +0 -0
  53. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/listener.py +0 -0
  54. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/proxy.py +0 -0
  55. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/session_state.py +0 -0
  56. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/state.py +0 -0
  57. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/status.py +0 -0
  58. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/upstream.py +0 -0
  59. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/upstream_context.py +0 -0
  60. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/server/verbs.py +0 -0
  61. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/supervise.py +0 -0
  62. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon/userscripts.py +0 -0
  63. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon_lifecycle.py +0 -0
  64. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/daemon_url.py +0 -0
  65. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/discovery.py +0 -0
  66. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/health.py +0 -0
  67. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/install.py +0 -0
  68. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/memory/__init__.py +0 -0
  69. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/memory/_lock.py +0 -0
  70. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/memory/_md.py +0 -0
  71. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/memory/_yaml.py +0 -0
  72. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/memory/global_mem.py +0 -0
  73. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/memory/site_mem.py +0 -0
  74. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/mode_b_client.py +0 -0
  75. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/output_schema.py +0 -0
  76. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/primitives/__init__.py +0 -0
  77. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/primitives/discovery_api.py +0 -0
  78. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/primitives/http.py +0 -0
  79. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/primitives/site.py +0 -0
  80. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/repl/__init__.py +0 -0
  81. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/repl/_md_convert.py +0 -0
  82. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/repl/_md_normalize.py +0 -0
  83. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/repl/_namespace.py +0 -0
  84. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/repl/markdown.py +0 -0
  85. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/repl/playwright_handle.py +0 -0
  86. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/repl/snapshot.py +0 -0
  87. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/repl/vendor/README.md +0 -0
  88. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/repl/vendor/readability.js +0 -0
  89. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/session.py +0 -0
  90. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/session_create.py +0 -0
  91. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/session_ctx.py +0 -0
  92. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/session_registry.py +0 -0
  93. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/session_runtime.py +0 -0
  94. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/github.com/SKILL.md +0 -0
  95. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/github.com/memory.md +0 -0
  96. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/github.com/tasks/list_issues.py +0 -0
  97. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/google.com/SKILL.md +0 -0
  98. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/google.com/memory.md +0 -0
  99. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/google.com/tasks/search.py +0 -0
  100. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/producthunt.com/SKILL.md +0 -0
  101. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/producthunt.com/memory.md +0 -0
  102. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/producthunt.com/tasks/today.py +0 -0
  103. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/wikipedia.org/SKILL.md +0 -0
  104. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/wikipedia.org/memory.md +0 -0
  105. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/wikipedia.org/tasks/lookup.py +0 -0
  106. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/ycombinator.com/SKILL.md +0 -0
  107. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/ycombinator.com/memory.md +0 -0
  108. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/site_skills_starter/ycombinator.com/tasks/front_page.py +0 -0
  109. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/skill_doc.py +0 -0
  110. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/tab_surface.py +0 -0
  111. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/task_runner.py +0 -0
  112. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright/version.py +0 -0
  113. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright.egg-info/dependency_links.txt +0 -0
  114. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright.egg-info/entry_points.txt +0 -0
  115. {browserwright-0.21.0 → browserwright-0.23.0}/src/browserwright.egg-info/requires.txt +0 -0
  116. {browserwright-0.21.0 → browserwright-0.23.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.21.0
3
+ Version: 0.23.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.21.0"
18
+ version = "0.23.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"
@@ -77,6 +77,18 @@ EXPORTS = [
77
77
  "BrowserwrightError", "PageLoadFailed", "ElementNotFound", "AuthWall",
78
78
  "Captcha", "NetworkError", "DaemonUnavailable", "CDPError",
79
79
  "NeedsUserConfirm", "UnsupportedContentType", "TabMatchError",
80
+ "OperationTimeout",
80
81
  ]
81
82
 
82
83
  __all__ = EXPORTS
84
+
85
+
86
+ def __getattr__(name: str):
87
+ # `OperationTimeout` subclasses Playwright's TimeoutError, so building it
88
+ # imports `playwright.sync_api`; `errors` defers that to first use, and so
89
+ # does this re-export (see `errors._make_operation_timeout`).
90
+ if name == "OperationTimeout":
91
+ from . import errors
92
+
93
+ return errors.OperationTimeout
94
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -26,6 +26,7 @@ and a generous client-owned wait.
26
26
  from __future__ import annotations
27
27
 
28
28
  import ast
29
+ import dataclasses
29
30
  import io
30
31
  import json
31
32
  import os
@@ -41,7 +42,13 @@ from contextlib import contextmanager, redirect_stdout
41
42
  from typing import Any
42
43
 
43
44
  from .._text import spill_text, truncate_hard
44
- from ..errors import BrowserwrightError, TabRebindFailed, serialize
45
+ from ..errors import (
46
+ BrowserwrightError,
47
+ DeadlineExceeded,
48
+ OperationTimeout,
49
+ TabRebindFailed,
50
+ serialize,
51
+ )
45
52
  from .protocol import (
46
53
  MAX_TEXT_CHARS,
47
54
  RECOVERY_BOUND,
@@ -320,25 +327,41 @@ class _Worker:
320
327
  exits the whole executor process, which lets the OS tear down the
321
328
  Playwright transport without touching browser tabs."""
322
329
  box: "queue.Queue[ExecuteResponse]" = queue.Queue(maxsize=1)
330
+ budget_s = max(req.timeout_ms, 1) / 1000.0
331
+ deadline = time.monotonic() + budget_s
323
332
  self._q.put((req, box))
324
333
  try:
325
- return box.get(timeout=max(req.timeout_ms, 1) / 1000.0)
334
+ response = box.get(timeout=budget_s)
326
335
  except queue.Empty:
327
- return ExecuteResponse(
328
- error={
329
- "type": "TimeoutError",
330
- "msg": (
331
- f"executor request deadline exceeded "
332
- f"({req.timeout_ms}ms); the executor was recycled"
333
- ),
334
- "fix": (
335
- "retry the command; browser tabs were preserved, but "
336
- "executor state and Python finally blocks were not"
337
- ),
338
- },
339
- exit_code=3,
340
- terminal_reason=TERMINAL_DEADLINE_EXCEEDED,
341
- )
336
+ return self._deadline_exceeded(req)
337
+ # ADR-0014, the 7-vs-8 race: a call that FAILED once its deadline had
338
+ # run out failed because of the deadline. Classify by the clock, not by
339
+ # which thread happened to win the hand-off: a Playwright timeout that
340
+ # fires at the deadline (its `timeout=` was >= what was left, so the
341
+ # deadline was the binding cap) and a relay command cut short by the
342
+ # propagated deadline (#120; it lands `INNER_GRACE_S` after it) can
343
+ # reach this box at or after the deadline. They are the call
344
+ # deadline's, never an `OperationTimeout`. A call that finished is
345
+ # left alone: its work is done, there is nothing to blame.
346
+ if response.error is not None and time.monotonic() >= deadline:
347
+ late = self._deadline_exceeded(req)
348
+ return dataclasses.replace(
349
+ response, error=late.error, exit_code=late.exit_code,
350
+ terminal_reason=late.terminal_reason)
351
+ return response
352
+
353
+ @staticmethod
354
+ def _deadline_exceeded(req: ExecuteRequest) -> ExecuteResponse:
355
+ """The one place the internal terminal reason becomes the
356
+ caller-facing error (ADR-0014): `terminal_reason` stays the
357
+ daemon/client's signal to reap this exact process, while the agent
358
+ reads `DeadlineExceeded` (exit 7) and its `--timeout` fix."""
359
+ exc = DeadlineExceeded(timeout=req.timeout_ms / 1000.0)
360
+ return ExecuteResponse(
361
+ error=serialize(exc),
362
+ exit_code=exc.exit_code,
363
+ terminal_reason=TERMINAL_DEADLINE_EXCEEDED,
364
+ )
342
365
 
343
366
  def shutdown(self) -> None:
344
367
  self._q.put(None)
@@ -908,8 +931,13 @@ class _Worker:
908
931
  if _is_target_closed_family(e):
909
932
  return self._target_closed_response(
910
933
  buf, serialize(e), e.exit_code)
934
+ error = serialize(e)
935
+ if isinstance(e, OperationTimeout):
936
+ # Smart goto's timeout: keep the traceback, which
937
+ # says WHICH call ran out.
938
+ error["traceback"] = traceback.format_exc()
911
939
  return self._finish(
912
- buf, error=serialize(e), exit_code=e.exit_code)
940
+ buf, error=error, exit_code=e.exit_code)
913
941
  except SystemExit as e:
914
942
  code = int(e.code) if isinstance(e.code, int) else 0
915
943
  return self._finish(buf, exit_code=code)
@@ -917,8 +945,24 @@ class _Worker:
917
945
  # Restore traceback fidelity: the in-process path writes
918
946
  # `traceback.format_exc()` to stderr; a shipped heredoc must
919
947
  # show the SAME traceback. We carry it on the serialized error.
920
- from ..errors import playwright_error_fix
948
+ from ..errors import (
949
+ operation_timeout_from,
950
+ playwright_error_fix,
951
+ )
921
952
 
953
+ op = operation_timeout_from(e)
954
+ if op is not e:
955
+ # ADR-0014: inside the code a Playwright call raises
956
+ # Playwright's own TimeoutError (we never patch it);
957
+ # escaping the code, it is REPORTED as an operation
958
+ # timeout — exit 8, executor kept. The traceback (the
959
+ # original frames, ending in the reported type) says
960
+ # which call ran out.
961
+ error = serialize(op)
962
+ error["traceback"] = "".join(
963
+ traceback.format_exception(op))
964
+ return self._finish(
965
+ buf, error=error, exit_code=op.exit_code)
922
966
  error = {
923
967
  "type": type(e).__name__,
924
968
  "msg": str(e),
@@ -22,13 +22,17 @@ from dataclasses import dataclass, field
22
22
  from typing import Any
23
23
 
24
24
  from .._text import MAX_TEXT_CHARS as _MAX_TEXT_CHARS
25
-
26
- # Default per-call timeout (ms). Playwriter defaults to 10000ms, but real page
27
- # ops (cold navigation + network settle) can legitimately take longer, so we
28
- # pick a more generous default. It is deliberately bounded WELL UNDER any
29
- # realistic idle-reap threshold (`Config.idle_close_after`, default None = never)
30
- # so a slow-but-legitimate call never trips idle reclamation mid-flight.
31
- DEFAULT_TIMEOUT_MS = 90000
25
+ from ..errors import DEFAULT_CALL_TIMEOUT_S
26
+
27
+ # Default call deadline (ms) — what `timeout_ms` is when the caller sets none
28
+ # (`browserwright -e` without `--timeout`; ADR-0014). Playwriter defaults to
29
+ # 10000ms, but real page ops (cold navigation + network settle) can
30
+ # legitimately take longer, so we pick a more generous default. It is
31
+ # deliberately bounded WELL UNDER any realistic idle-reap threshold
32
+ # (`Config.idle_close_after`, default None = never) so a slow-but-legitimate
33
+ # call never trips idle reclamation mid-flight. Expiry is fail-stop and reaches
34
+ # the caller as `errors.DeadlineExceeded` (exit 7).
35
+ DEFAULT_TIMEOUT_MS = DEFAULT_CALL_TIMEOUT_S * 1000
32
36
 
33
37
  # Cap on EVERY text channel of the response — console, return value, warnings
34
38
  # and the task result JSON — so a runaway print loop, or an equally ordinary
@@ -25,9 +25,15 @@ from . import __version__
25
25
  HELP = """browserwright — Layer 2 of the browser stack.
26
26
 
27
27
  Usage:
28
- browserwright -s <session-id> [--env NAME ...] -e 'page.goto("https://example.com"); print(page.title())'
29
- browserwright -s <session-id> [--env NAME ...] -f script.py
30
- browserwright -s <session-id> [--env NAME ...] --code-stdin < script.py
28
+ browserwright -s <session-id> [--env NAME ...] [--timeout SECONDS] -e 'page.goto("https://example.com"); print(page.title())'
29
+ browserwright -s <session-id> [--env NAME ...] [--timeout SECONDS] -f script.py
30
+ browserwright -s <session-id> [--env NAME ...] [--timeout SECONDS] --code-stdin < script.py
31
+
32
+ --timeout SECONDS the call deadline (default 90). When it runs out the
33
+ code is stopped, its executor is recycled, and the
34
+ command exits 7 (DeadlineExceeded). One Playwright
35
+ call running out of its own timeout= exits 8
36
+ (OperationTimeout) when the code does not catch it.
31
37
 
32
38
  browserwright session new --backend=<extension|cdp> --name=SESSION_LABEL [--reuse] [--create | --attach=PORT]
33
39
  browserwright recover --session=<id> (the one recovery verb: exit 0 healthy, 4 needs-human)
@@ -41,10 +47,16 @@ Usage:
41
47
 
42
48
  browserwright markdown <url> [--mode=auto|article|full] [--backend=extension|cdp]
43
49
  [--attach=<port|url>] [--out=PATH] [--max-chars=N]
44
- [--name=LABEL]
50
+ [--name=LABEL] [--timeout=SECONDS]
45
51
  One page as Markdown. Creates and tears down its own session, so it takes
46
52
  no -s. Absolute links, shadow DOM flattened in, HTML only.
47
53
 
54
+ browserwright search <query> [--limit=N] [--json] [--backend=extension|cdp]
55
+ [--attach=<port|url>] [--search-url=TEMPLATE]
56
+ [--name=LABEL] [--timeout=SECONDS]
57
+ One results page as ranked links (+ answer box / knowledge panel).
58
+ Self-sessioned like markdown. Captcha/consent walls exit 5.
59
+
48
60
  browserwright -s <session-id> task <site>/<name> [--env NAME ...] [--key=value ...] [--isolated]
49
61
  browserwright list-tasks [--site SITE] [--query Q] [--json]
50
62
 
@@ -351,23 +363,71 @@ def _resolve_request_env(
351
363
  return values, None
352
364
 
353
365
 
366
+ def _parse_timeout_value(raw: object) -> tuple[Optional[float], Optional[str]]:
367
+ """Validate one ``--timeout`` value: positive seconds, finite."""
368
+ import math
369
+
370
+ try:
371
+ value = float(raw) # type: ignore[arg-type]
372
+ except (TypeError, ValueError):
373
+ return None, f"--timeout must be a number of seconds, got {raw!r}"
374
+ if not math.isfinite(value) or value <= 0:
375
+ return None, f"--timeout must be a positive number of seconds, got {raw!r}"
376
+ return value, None
377
+
378
+
379
+ def _extract_timeout_arg(
380
+ args: list[str],
381
+ ) -> tuple[Optional[float], list[str], Optional[str]]:
382
+ """Remove ``--timeout SECONDS`` / ``--timeout=SECONDS`` from ``args``.
383
+
384
+ The call deadline (ADR-0014). ``None`` means the caller did not set one,
385
+ and the default applies."""
386
+ timeout: Optional[float] = None
387
+ out: list[str] = []
388
+ i, n = 0, len(args)
389
+ while i < n:
390
+ a = args[i]
391
+ if a == "--timeout":
392
+ if i + 1 >= n:
393
+ return None, [], "--timeout requires a value in seconds"
394
+ raw: object = args[i + 1]
395
+ i += 2
396
+ elif a.startswith("--timeout="):
397
+ raw = a.split("=", 1)[1]
398
+ i += 1
399
+ else:
400
+ out.append(a)
401
+ i += 1
402
+ continue
403
+ timeout, err = _parse_timeout_value(raw)
404
+ if err:
405
+ return None, [], err
406
+ return timeout, out, None
407
+
408
+
354
409
  def _cmd_execute(args: list[str]) -> int:
355
- session_id, code, env_names, err = _parse_execute_args(args)
410
+ usage = ("usage: browserwright -s <session-id> [--env NAME ...] "
411
+ "[--timeout SECONDS] "
412
+ "(-e 'print(snapshot())' | -f script.py | --code-stdin)")
413
+ timeout_s, args, err = _extract_timeout_arg(args)
414
+ if not err:
415
+ session_id, code, env_names, err = _parse_execute_args(args)
356
416
  if err:
357
417
  print(f"usage error: {err}", file=sys.stderr)
358
- print("usage: browserwright -s <session-id> [--env NAME ...] "
359
- "(-e 'print(snapshot())' | -f script.py | --code-stdin)",
360
- file=sys.stderr)
418
+ print(usage, file=sys.stderr)
361
419
  return 1
362
420
  request_env, err = _resolve_request_env(env_names)
363
421
  if err:
364
422
  print(f"usage error: {err}", file=sys.stderr)
365
423
  return 1
424
+ from .errors import DEFAULT_CALL_TIMEOUT_S
366
425
  from .repl import inline
367
426
  return inline.run_code(
368
427
  code or "",
369
428
  session_id=session_id or "",
370
429
  env=request_env,
430
+ timeout_s=DEFAULT_CALL_TIMEOUT_S if timeout_s is None else timeout_s,
371
431
  )
372
432
 
373
433
 
@@ -520,6 +580,9 @@ Flags:
520
580
  --max-chars=N cap what is printed (default 8000; 0 prints everything).
521
581
  The FULL text is always written to the file either way.
522
582
  --name=LABEL session label; shows as the Chrome tab group title
583
+ --timeout=SECONDS
584
+ the call deadline for the navigate-and-convert step
585
+ (default 90); running out exits 7 (DeadlineExceeded)
523
586
  """
524
587
 
525
588
  # Runs inside the session's executor, which is the only place a live `page`
@@ -540,6 +603,79 @@ for _n in _r.notes:
540
603
  """
541
604
 
542
605
 
606
+ def _throwaway_options(kw: dict) -> tuple[Optional[dict], Optional[str]]:
607
+ """Parse the flags every self-sessioned command shares (``markdown``,
608
+ ``search``): ``--backend``, ``--attach``, ``--timeout``.
609
+
610
+ Returns ``(options, None)`` or ``(None, usage_error)``. Everything is
611
+ validated here so a bad value is refused before anything touches the
612
+ ledger or the daemon.
613
+ """
614
+ attach = kw.get("attach")
615
+ backend = str(kw.get("backend", "cdp" if attach is not None else "extension"))
616
+ if backend not in ("extension", "cdp"):
617
+ return None, f"--backend must be extension or cdp, got {backend!r}"
618
+ if attach is not None:
619
+ if backend != "cdp":
620
+ return None, (f"--attach borrows a CDP browser, so it implies "
621
+ f"--backend=cdp; got --backend={backend}")
622
+ from .daemon.config import check_cdp_attach
623
+ from .daemon.errors import UserError
624
+
625
+ try:
626
+ check_cdp_attach(attach)
627
+ except UserError as e:
628
+ return None, str(e)
629
+
630
+ from .errors import DEFAULT_CALL_TIMEOUT_S
631
+
632
+ timeout_s: float = DEFAULT_CALL_TIMEOUT_S
633
+ if "timeout" in kw:
634
+ parsed, err = _parse_timeout_value(kw["timeout"])
635
+ if err:
636
+ return None, err
637
+ timeout_s = parsed # type: ignore[assignment]
638
+ return {"backend": backend, "attach": attach, "timeout_s": timeout_s}, None
639
+
640
+
641
+ def _open_throwaway_session(opts: dict, name: str) -> tuple[Optional[str], int]:
642
+ """Mint the session a self-sessioned command uses and then ends.
643
+
644
+ ``cdp`` has no meaning without an owner: it must either launch a browser or
645
+ attach to one. Without --attach there is nobody to attach to, so it
646
+ launches — a real Chrome, which on macOS takes the active window; the
647
+ default backend is ``extension`` precisely so the common path never does
648
+ that. With --attach (e.g. a remote CloakBrowser endpoint) it borrows that
649
+ browser and leaves it be.
650
+ """
651
+ from . import session_create
652
+ from .errors import BrowserwrightError
653
+
654
+ try:
655
+ return session_create.new(
656
+ backend=opts["backend"],
657
+ create=(opts["backend"] == "cdp" and opts["attach"] is None),
658
+ attach=opts["attach"],
659
+ name=name,
660
+ ).id, 0
661
+ except (ValueError, BrowserwrightError) as e:
662
+ print(str(e), file=sys.stderr)
663
+ return None, 1
664
+
665
+
666
+ def _end_throwaway_session(cmd: str, sid: str) -> None:
667
+ """Always called from a ``finally``: a leaked session leaves a tab group
668
+ behind in the user's real Chrome (issue #53)."""
669
+ from . import session_create
670
+ from .session_ctx import resolve_session_or_env
671
+
672
+ try:
673
+ session_create.end(resolve_session_or_env(sid))
674
+ except Exception as e: # noqa: BLE001 — never mask the real result
675
+ print(f"[{cmd}] warning: could not end throwaway session {sid}: {e}",
676
+ file=sys.stderr)
677
+
678
+
543
679
  def _cmd_markdown(args: list[str]) -> int:
544
680
  """``browserwright markdown <url>`` — one page, as Markdown (ADR-0006).
545
681
 
@@ -566,27 +702,10 @@ def _cmd_markdown(args: list[str]) -> int:
566
702
  print(f"usage error: --mode must be one of {'|'.join(MODES)}, "
567
703
  f"got {mode!r}", file=sys.stderr)
568
704
  return 1
569
- attach = kw.get("attach")
570
- backend = str(kw.get("backend", "cdp" if attach is not None else "extension"))
571
- if backend not in ("extension", "cdp"):
572
- print(f"usage error: --backend must be extension or cdp, got "
573
- f"{backend!r}", file=sys.stderr)
705
+ opts, err = _throwaway_options(kw)
706
+ if err:
707
+ print(f"usage error: {err}", file=sys.stderr)
574
708
  return 1
575
- if attach is not None:
576
- if backend != "cdp":
577
- print(f"usage error: --attach borrows a CDP browser, so it implies "
578
- f"--backend=cdp; got --backend={backend}", file=sys.stderr)
579
- return 1
580
- # Validate here, not only in session_create.new: a bad target must be
581
- # refused before anything touches the ledger or the daemon.
582
- from .daemon.config import check_cdp_attach
583
- from .daemon.errors import UserError
584
-
585
- try:
586
- check_cdp_attach(attach)
587
- except UserError as e:
588
- print(f"usage error: {e}", file=sys.stderr)
589
- return 1
590
709
  try:
591
710
  max_chars = int(kw.get("max-chars", DEFAULT_MAX_CHARS))
592
711
  except (TypeError, ValueError):
@@ -600,33 +719,18 @@ def _cmd_markdown(args: list[str]) -> int:
600
719
 
601
720
  import contextlib
602
721
 
603
- from . import session_create
604
- from .errors import BrowserwrightError
605
722
  from .repl import inline
606
- from .session_ctx import resolve_session_or_env
607
723
 
608
- try:
609
- sid = session_create.new(
610
- backend=backend,
611
- # `cdp` has no meaning without an owner: it must either launch a
612
- # browser or attach to one. Without --attach there is nobody to
613
- # attach to, so it launches — a real Chrome, which on macOS takes
614
- # the active window; the default backend is `extension` precisely
615
- # so the common path never does that. With --attach (e.g. a remote
616
- # CloakBrowser endpoint) it borrows that browser and leaves it be.
617
- create=(backend == "cdp" and attach is None),
618
- attach=attach,
619
- name=str(kw.get("name", "markdown")),
620
- ).id
621
- except (ValueError, BrowserwrightError) as e:
622
- print(str(e), file=sys.stderr)
623
- return 1
724
+ sid, rc = _open_throwaway_session(opts, str(kw.get("name", "markdown")))
725
+ if sid is None:
726
+ return rc
624
727
 
625
728
  try:
626
729
  rc = inline.run_code(
627
730
  _MARKDOWN_CODE,
628
731
  session_id=sid,
629
732
  env={"BW_MD_URL": url, "BW_MD_OUT": out_path, "BW_MD_MODE": mode},
733
+ timeout_s=opts["timeout_s"],
630
734
  )
631
735
  if rc != 0:
632
736
  return rc
@@ -650,11 +754,126 @@ def _cmd_markdown(args: list[str]) -> int:
650
754
  if not keep_file:
651
755
  with contextlib.suppress(OSError):
652
756
  Path(out_path).unlink()
757
+ _end_throwaway_session("markdown", sid)
758
+
759
+
760
+ SEARCH_HELP = """Usage:
761
+ browserwright search <query> [--limit=N] [--json] [--backend=extension|cdp]
762
+ [--attach=<port|url>] [--search-url=TEMPLATE]
763
+ [--name=LABEL] [--timeout=SECONDS]
764
+
765
+ Search the web in a real browser and print the results page as ranked links:
766
+ title, URL, date and snippet, plus the engine's AI Overview, knowledge panel,
767
+ "people also ask" and related searches when the query triggered them. Links
768
+ only, never page bodies — read the ones worth it with `browserwright markdown`.
769
+
770
+ Owns its whole lifecycle like `markdown`: a throwaway session, torn down after.
771
+ Google's opaque `/goto?url=…` links (what a signed-out browser gets) are
772
+ resolved to the real URL. A captcha or consent wall fails with exit 5 instead
773
+ of returning an empty list; "nothing matched" is reported as zero results.
774
+
775
+ Flags:
776
+ --limit=N max results (default 10)
777
+ --json print the structured payload instead of text
778
+ --backend extension (default, the user's real Chrome) | cdp
779
+ --attach=TARGET borrow a CDP browser (port or ws/http(s) URL); implies
780
+ --backend=cdp, left running afterwards. Same values as
781
+ `session new --attach`.
782
+ --search-url=T results page template; {query} (URL-encoded) and {limit}
783
+ are substituted. Default: Google. The extraction expects
784
+ Google's markup.
785
+ --name=LABEL session label; shows as the Chrome tab group title
786
+ --timeout=SECONDS
787
+ the call deadline for the search (default 90); running out
788
+ exits 7 (DeadlineExceeded)
789
+ """
790
+
791
+ # Runs inside the session's executor; same value-passing discipline as
792
+ # _MARKDOWN_CODE, and the payload rides back on disk for the same reason.
793
+ _SEARCH_CODE = """
794
+ import json, os
795
+ from browserwright.repl.search import search_page
796
+
797
+ _p = search_page(page, os.environ["BW_SEARCH_QUERY"],
798
+ limit=int(os.environ["BW_SEARCH_LIMIT"]),
799
+ search_url=os.environ["BW_SEARCH_URL"])
800
+ with open(os.environ["BW_SEARCH_OUT"], "w", encoding="utf-8") as _f:
801
+ json.dump(_p, _f, ensure_ascii=False)
802
+ _bw_warn("search: %d results%s" % (len(_p["results"]), " (engine: nothing matched)" if _p["noMatch"] else ""))
803
+ """
804
+
805
+
806
+ def _cmd_search(args: list[str]) -> int:
807
+ """``browserwright search <query>`` — one results page, as ranked links.
808
+
809
+ Self-sessioned like ``markdown``. Every query word goes in the first
810
+ argument (quote it); flags follow.
811
+ """
812
+ if not args or args[0] in {"-h", "--help"}:
813
+ sys.stdout.write(SEARCH_HELP)
814
+ return 0 if args else 1
815
+
816
+ query = args[0].strip()
817
+ if not query or query.startswith("-"):
818
+ print(f"usage error: expected a query, got {args[0]!r}", file=sys.stderr)
819
+ print(SEARCH_HELP, file=sys.stderr)
820
+ return 1
821
+ kw = _parse_kv_args(args[1:])
822
+
823
+ from .repl.search import DEFAULT_LIMIT, DEFAULT_SEARCH_URL, render_results
824
+
825
+ try:
826
+ limit = int(kw.get("limit", DEFAULT_LIMIT))
827
+ if limit < 1:
828
+ raise ValueError
829
+ except (TypeError, ValueError):
830
+ print("usage error: --limit must be a positive integer", file=sys.stderr)
831
+ return 1
832
+ search_url = kw.get("search-url", DEFAULT_SEARCH_URL)
833
+ if not isinstance(search_url, str) or "{query}" not in search_url:
834
+ print("usage error: --search-url must contain {query}", file=sys.stderr)
835
+ return 1
836
+ opts, err = _throwaway_options(kw)
837
+ if err:
838
+ print(f"usage error: {err}", file=sys.stderr)
839
+ return 1
840
+
841
+ import contextlib
842
+ import tempfile
843
+
844
+ from .repl import inline
845
+
846
+ fd, out_path = tempfile.mkstemp(prefix="browserwright-search-", suffix=".json")
847
+ os.close(fd)
848
+ sid, rc = _open_throwaway_session(opts, str(kw.get("name", "search")))
849
+ if sid is None:
850
+ Path(out_path).unlink(missing_ok=True)
851
+ return rc
852
+
853
+ try:
854
+ rc = inline.run_code(
855
+ _SEARCH_CODE,
856
+ session_id=sid,
857
+ env={"BW_SEARCH_QUERY": query, "BW_SEARCH_LIMIT": str(limit),
858
+ "BW_SEARCH_URL": search_url, "BW_SEARCH_OUT": out_path},
859
+ timeout_s=opts["timeout_s"],
860
+ )
861
+ if rc != 0:
862
+ return rc
653
863
  try:
654
- session_create.end(resolve_session_or_env(sid))
655
- except Exception as e: # noqa: BLE001 — never mask the real result
656
- print(f"[markdown] warning: could not end throwaway session {sid}: "
657
- f"{e}", file=sys.stderr)
864
+ payload = json.loads(Path(out_path).read_text(encoding="utf-8"))
865
+ except (OSError, ValueError) as e:
866
+ print(f"search: could not read the results: {e}", file=sys.stderr)
867
+ return 3
868
+ if kw.get("json"):
869
+ sys.stdout.write(json.dumps(payload, ensure_ascii=False) + "\n")
870
+ else:
871
+ sys.stdout.write(render_results(payload))
872
+ return 0
873
+ finally:
874
+ with contextlib.suppress(OSError):
875
+ Path(out_path).unlink()
876
+ _end_throwaway_session("search", sid)
658
877
 
659
878
 
660
879
  def _cmd_doctor(args: list[str]) -> int:
@@ -1267,6 +1486,8 @@ def main(argv: Optional[list[str]] = None) -> None:
1267
1486
  or command_argv[0].startswith("--code-file=")
1268
1487
  or command_argv[0] == "--env"
1269
1488
  or command_argv[0].startswith("--env=")
1489
+ or command_argv[0] == "--timeout"
1490
+ or command_argv[0].startswith("--timeout=")
1270
1491
  ):
1271
1492
  sys.exit(_cmd_execute(argv))
1272
1493
  argv = command_argv
@@ -1291,10 +1512,12 @@ def main(argv: Optional[list[str]] = None) -> None:
1291
1512
  sys.exit(_cmd_index(rest))
1292
1513
  if cmd == "memory":
1293
1514
  sys.exit(_cmd_memory(rest))
1294
- # Deliberately NOT under the -s branch: this is the one browser-driving
1295
- # command that owns its own throwaway session (ADR-0006).
1515
+ # Deliberately NOT under the -s branch: these browser-driving commands own
1516
+ # their own throwaway session (ADR-0006).
1296
1517
  if cmd == "markdown":
1297
1518
  sys.exit(_cmd_markdown(rest))
1519
+ if cmd == "search":
1520
+ sys.exit(_cmd_search(rest))
1298
1521
  if cmd == "session":
1299
1522
  sys.exit(_cmd_session(rest, session_id=global_session))
1300
1523
  if cmd == "whoami":