browserwright 0.21.0__tar.gz → 0.22.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.22.0}/PKG-INFO +1 -1
  2. {browserwright-0.21.0 → browserwright-0.22.0}/pyproject.toml +1 -1
  3. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/_executor/process.py +13 -13
  4. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/_executor/protocol.py +11 -7
  5. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/cli.py +274 -53
  6. browserwright-0.22.0/src/browserwright/daemon/server/call_deadline.py +127 -0
  7. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/exec_relay.py +25 -4
  8. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/extension_upstream.py +59 -13
  9. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/facade_extension.py +17 -3
  10. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/relay.py +43 -12
  11. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/errors.py +39 -1
  12. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/repl/_smart_goto.py +32 -26
  13. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/repl/inline.py +59 -6
  14. browserwright-0.22.0/src/browserwright/repl/search.py +308 -0
  15. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/skill_runtime.md +51 -7
  16. {browserwright-0.21.0 → browserwright-0.22.0/src/browserwright.egg-info}/PKG-INFO +1 -1
  17. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright.egg-info/SOURCES.txt +2 -0
  18. {browserwright-0.21.0 → browserwright-0.22.0}/LICENSE +0 -0
  19. {browserwright-0.21.0 → browserwright-0.22.0}/README.md +0 -0
  20. {browserwright-0.21.0 → browserwright-0.22.0}/setup.cfg +0 -0
  21. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/__init__.py +0 -0
  22. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/__main__.py +0 -0
  23. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/_executor/__init__.py +0 -0
  24. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/_executor/__main__.py +0 -0
  25. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/_executor/client.py +0 -0
  26. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/_text.py +0 -0
  27. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/cdp.py +0 -0
  28. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/__init__.py +0 -0
  29. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/_ipc.py +0 -0
  30. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/_net.py +0 -0
  31. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/_rpc.py +0 -0
  32. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/_stale.py +0 -0
  33. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/backends/__init__.py +0 -0
  34. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/backends/base.py +0 -0
  35. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/backends/cdp.py +0 -0
  36. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/backends/extension.py +0 -0
  37. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/cli.py +0 -0
  38. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/config.py +0 -0
  39. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/doctor.py +0 -0
  40. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/errors.py +0 -0
  41. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/launch_chrome.py +0 -0
  42. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/launchagent.py +0 -0
  43. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/observability.py +0 -0
  44. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/platforms.py +0 -0
  45. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/probe.py +0 -0
  46. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/relay_status.py +0 -0
  47. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/resolver.py +0 -0
  48. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/restart_guard.py +0 -0
  49. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/__init__.py +0 -0
  50. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/daemon.py +0 -0
  51. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/executor_registry.py +0 -0
  52. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/facade.py +0 -0
  53. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/listener.py +0 -0
  54. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/proxy.py +0 -0
  55. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/session_state.py +0 -0
  56. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/state.py +0 -0
  57. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/status.py +0 -0
  58. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/upstream.py +0 -0
  59. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/upstream_context.py +0 -0
  60. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/server/verbs.py +0 -0
  61. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/supervise.py +0 -0
  62. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon/userscripts.py +0 -0
  63. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon_lifecycle.py +0 -0
  64. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/daemon_url.py +0 -0
  65. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/discovery.py +0 -0
  66. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/health.py +0 -0
  67. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/install.py +0 -0
  68. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/memory/__init__.py +0 -0
  69. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/memory/_lock.py +0 -0
  70. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/memory/_md.py +0 -0
  71. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/memory/_yaml.py +0 -0
  72. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/memory/global_mem.py +0 -0
  73. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/memory/site_mem.py +0 -0
  74. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/mode_b_client.py +0 -0
  75. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/output_schema.py +0 -0
  76. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/primitives/__init__.py +0 -0
  77. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/primitives/discovery_api.py +0 -0
  78. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/primitives/http.py +0 -0
  79. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/primitives/site.py +0 -0
  80. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/repl/__init__.py +0 -0
  81. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/repl/_md_convert.py +0 -0
  82. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/repl/_md_normalize.py +0 -0
  83. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/repl/_namespace.py +0 -0
  84. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/repl/markdown.py +0 -0
  85. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/repl/playwright_handle.py +0 -0
  86. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/repl/snapshot.py +0 -0
  87. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/repl/vendor/README.md +0 -0
  88. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/repl/vendor/readability.js +0 -0
  89. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/session.py +0 -0
  90. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/session_create.py +0 -0
  91. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/session_ctx.py +0 -0
  92. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/session_registry.py +0 -0
  93. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/session_runtime.py +0 -0
  94. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/github.com/SKILL.md +0 -0
  95. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/github.com/memory.md +0 -0
  96. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/github.com/tasks/list_issues.py +0 -0
  97. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/google.com/SKILL.md +0 -0
  98. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/google.com/memory.md +0 -0
  99. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/google.com/tasks/search.py +0 -0
  100. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/producthunt.com/SKILL.md +0 -0
  101. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/producthunt.com/memory.md +0 -0
  102. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/producthunt.com/tasks/today.py +0 -0
  103. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/wikipedia.org/SKILL.md +0 -0
  104. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/wikipedia.org/memory.md +0 -0
  105. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/wikipedia.org/tasks/lookup.py +0 -0
  106. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/ycombinator.com/SKILL.md +0 -0
  107. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/ycombinator.com/memory.md +0 -0
  108. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/site_skills_starter/ycombinator.com/tasks/front_page.py +0 -0
  109. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/skill_doc.py +0 -0
  110. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/tab_surface.py +0 -0
  111. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/task_runner.py +0 -0
  112. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright/version.py +0 -0
  113. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright.egg-info/dependency_links.txt +0 -0
  114. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright.egg-info/entry_points.txt +0 -0
  115. {browserwright-0.21.0 → browserwright-0.22.0}/src/browserwright.egg-info/requires.txt +0 -0
  116. {browserwright-0.21.0 → browserwright-0.22.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.22.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.22.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"
@@ -41,7 +41,12 @@ from contextlib import contextmanager, redirect_stdout
41
41
  from typing import Any
42
42
 
43
43
  from .._text import spill_text, truncate_hard
44
- from ..errors import BrowserwrightError, TabRebindFailed, serialize
44
+ from ..errors import (
45
+ BrowserwrightError,
46
+ DeadlineExceeded,
47
+ TabRebindFailed,
48
+ serialize,
49
+ )
45
50
  from .protocol import (
46
51
  MAX_TEXT_CHARS,
47
52
  RECOVERY_BOUND,
@@ -324,19 +329,14 @@ class _Worker:
324
329
  try:
325
330
  return box.get(timeout=max(req.timeout_ms, 1) / 1000.0)
326
331
  except queue.Empty:
332
+ # The one place the internal terminal reason becomes the
333
+ # caller-facing error (ADR-0014): `terminal_reason` stays the
334
+ # daemon/client's signal to reap this exact process, while the
335
+ # agent reads `DeadlineExceeded` (exit 7) and its `--timeout` fix.
336
+ exc = DeadlineExceeded(timeout=req.timeout_ms / 1000.0)
327
337
  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,
338
+ error=serialize(exc),
339
+ exit_code=exc.exit_code,
340
340
  terminal_reason=TERMINAL_DEADLINE_EXCEEDED,
341
341
  )
342
342
 
@@ -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,13 @@ 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).
31
35
 
32
36
  browserwright session new --backend=<extension|cdp> --name=SESSION_LABEL [--reuse] [--create | --attach=PORT]
33
37
  browserwright recover --session=<id> (the one recovery verb: exit 0 healthy, 4 needs-human)
@@ -41,10 +45,16 @@ Usage:
41
45
 
42
46
  browserwright markdown <url> [--mode=auto|article|full] [--backend=extension|cdp]
43
47
  [--attach=<port|url>] [--out=PATH] [--max-chars=N]
44
- [--name=LABEL]
48
+ [--name=LABEL] [--timeout=SECONDS]
45
49
  One page as Markdown. Creates and tears down its own session, so it takes
46
50
  no -s. Absolute links, shadow DOM flattened in, HTML only.
47
51
 
52
+ browserwright search <query> [--limit=N] [--json] [--backend=extension|cdp]
53
+ [--attach=<port|url>] [--search-url=TEMPLATE]
54
+ [--name=LABEL] [--timeout=SECONDS]
55
+ One results page as ranked links (+ answer box / knowledge panel).
56
+ Self-sessioned like markdown. Captcha/consent walls exit 5.
57
+
48
58
  browserwright -s <session-id> task <site>/<name> [--env NAME ...] [--key=value ...] [--isolated]
49
59
  browserwright list-tasks [--site SITE] [--query Q] [--json]
50
60
 
@@ -351,23 +361,71 @@ def _resolve_request_env(
351
361
  return values, None
352
362
 
353
363
 
364
+ def _parse_timeout_value(raw: object) -> tuple[Optional[float], Optional[str]]:
365
+ """Validate one ``--timeout`` value: positive seconds, finite."""
366
+ import math
367
+
368
+ try:
369
+ value = float(raw) # type: ignore[arg-type]
370
+ except (TypeError, ValueError):
371
+ return None, f"--timeout must be a number of seconds, got {raw!r}"
372
+ if not math.isfinite(value) or value <= 0:
373
+ return None, f"--timeout must be a positive number of seconds, got {raw!r}"
374
+ return value, None
375
+
376
+
377
+ def _extract_timeout_arg(
378
+ args: list[str],
379
+ ) -> tuple[Optional[float], list[str], Optional[str]]:
380
+ """Remove ``--timeout SECONDS`` / ``--timeout=SECONDS`` from ``args``.
381
+
382
+ The call deadline (ADR-0014). ``None`` means the caller did not set one,
383
+ and the default applies."""
384
+ timeout: Optional[float] = None
385
+ out: list[str] = []
386
+ i, n = 0, len(args)
387
+ while i < n:
388
+ a = args[i]
389
+ if a == "--timeout":
390
+ if i + 1 >= n:
391
+ return None, [], "--timeout requires a value in seconds"
392
+ raw: object = args[i + 1]
393
+ i += 2
394
+ elif a.startswith("--timeout="):
395
+ raw = a.split("=", 1)[1]
396
+ i += 1
397
+ else:
398
+ out.append(a)
399
+ i += 1
400
+ continue
401
+ timeout, err = _parse_timeout_value(raw)
402
+ if err:
403
+ return None, [], err
404
+ return timeout, out, None
405
+
406
+
354
407
  def _cmd_execute(args: list[str]) -> int:
355
- session_id, code, env_names, err = _parse_execute_args(args)
408
+ usage = ("usage: browserwright -s <session-id> [--env NAME ...] "
409
+ "[--timeout SECONDS] "
410
+ "(-e 'print(snapshot())' | -f script.py | --code-stdin)")
411
+ timeout_s, args, err = _extract_timeout_arg(args)
412
+ if not err:
413
+ session_id, code, env_names, err = _parse_execute_args(args)
356
414
  if err:
357
415
  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)
416
+ print(usage, file=sys.stderr)
361
417
  return 1
362
418
  request_env, err = _resolve_request_env(env_names)
363
419
  if err:
364
420
  print(f"usage error: {err}", file=sys.stderr)
365
421
  return 1
422
+ from .errors import DEFAULT_CALL_TIMEOUT_S
366
423
  from .repl import inline
367
424
  return inline.run_code(
368
425
  code or "",
369
426
  session_id=session_id or "",
370
427
  env=request_env,
428
+ timeout_s=DEFAULT_CALL_TIMEOUT_S if timeout_s is None else timeout_s,
371
429
  )
372
430
 
373
431
 
@@ -520,6 +578,9 @@ Flags:
520
578
  --max-chars=N cap what is printed (default 8000; 0 prints everything).
521
579
  The FULL text is always written to the file either way.
522
580
  --name=LABEL session label; shows as the Chrome tab group title
581
+ --timeout=SECONDS
582
+ the call deadline for the navigate-and-convert step
583
+ (default 90); running out exits 7 (DeadlineExceeded)
523
584
  """
524
585
 
525
586
  # Runs inside the session's executor, which is the only place a live `page`
@@ -540,6 +601,79 @@ for _n in _r.notes:
540
601
  """
541
602
 
542
603
 
604
+ def _throwaway_options(kw: dict) -> tuple[Optional[dict], Optional[str]]:
605
+ """Parse the flags every self-sessioned command shares (``markdown``,
606
+ ``search``): ``--backend``, ``--attach``, ``--timeout``.
607
+
608
+ Returns ``(options, None)`` or ``(None, usage_error)``. Everything is
609
+ validated here so a bad value is refused before anything touches the
610
+ ledger or the daemon.
611
+ """
612
+ attach = kw.get("attach")
613
+ backend = str(kw.get("backend", "cdp" if attach is not None else "extension"))
614
+ if backend not in ("extension", "cdp"):
615
+ return None, f"--backend must be extension or cdp, got {backend!r}"
616
+ if attach is not None:
617
+ if backend != "cdp":
618
+ return None, (f"--attach borrows a CDP browser, so it implies "
619
+ f"--backend=cdp; got --backend={backend}")
620
+ from .daemon.config import check_cdp_attach
621
+ from .daemon.errors import UserError
622
+
623
+ try:
624
+ check_cdp_attach(attach)
625
+ except UserError as e:
626
+ return None, str(e)
627
+
628
+ from .errors import DEFAULT_CALL_TIMEOUT_S
629
+
630
+ timeout_s: float = DEFAULT_CALL_TIMEOUT_S
631
+ if "timeout" in kw:
632
+ parsed, err = _parse_timeout_value(kw["timeout"])
633
+ if err:
634
+ return None, err
635
+ timeout_s = parsed # type: ignore[assignment]
636
+ return {"backend": backend, "attach": attach, "timeout_s": timeout_s}, None
637
+
638
+
639
+ def _open_throwaway_session(opts: dict, name: str) -> tuple[Optional[str], int]:
640
+ """Mint the session a self-sessioned command uses and then ends.
641
+
642
+ ``cdp`` has no meaning without an owner: it must either launch a browser or
643
+ attach to one. Without --attach there is nobody to attach to, so it
644
+ launches — a real Chrome, which on macOS takes the active window; the
645
+ default backend is ``extension`` precisely so the common path never does
646
+ that. With --attach (e.g. a remote CloakBrowser endpoint) it borrows that
647
+ browser and leaves it be.
648
+ """
649
+ from . import session_create
650
+ from .errors import BrowserwrightError
651
+
652
+ try:
653
+ return session_create.new(
654
+ backend=opts["backend"],
655
+ create=(opts["backend"] == "cdp" and opts["attach"] is None),
656
+ attach=opts["attach"],
657
+ name=name,
658
+ ).id, 0
659
+ except (ValueError, BrowserwrightError) as e:
660
+ print(str(e), file=sys.stderr)
661
+ return None, 1
662
+
663
+
664
+ def _end_throwaway_session(cmd: str, sid: str) -> None:
665
+ """Always called from a ``finally``: a leaked session leaves a tab group
666
+ behind in the user's real Chrome (issue #53)."""
667
+ from . import session_create
668
+ from .session_ctx import resolve_session_or_env
669
+
670
+ try:
671
+ session_create.end(resolve_session_or_env(sid))
672
+ except Exception as e: # noqa: BLE001 — never mask the real result
673
+ print(f"[{cmd}] warning: could not end throwaway session {sid}: {e}",
674
+ file=sys.stderr)
675
+
676
+
543
677
  def _cmd_markdown(args: list[str]) -> int:
544
678
  """``browserwright markdown <url>`` — one page, as Markdown (ADR-0006).
545
679
 
@@ -566,27 +700,10 @@ def _cmd_markdown(args: list[str]) -> int:
566
700
  print(f"usage error: --mode must be one of {'|'.join(MODES)}, "
567
701
  f"got {mode!r}", file=sys.stderr)
568
702
  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)
703
+ opts, err = _throwaway_options(kw)
704
+ if err:
705
+ print(f"usage error: {err}", file=sys.stderr)
574
706
  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
707
  try:
591
708
  max_chars = int(kw.get("max-chars", DEFAULT_MAX_CHARS))
592
709
  except (TypeError, ValueError):
@@ -600,33 +717,18 @@ def _cmd_markdown(args: list[str]) -> int:
600
717
 
601
718
  import contextlib
602
719
 
603
- from . import session_create
604
- from .errors import BrowserwrightError
605
720
  from .repl import inline
606
- from .session_ctx import resolve_session_or_env
607
721
 
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
722
+ sid, rc = _open_throwaway_session(opts, str(kw.get("name", "markdown")))
723
+ if sid is None:
724
+ return rc
624
725
 
625
726
  try:
626
727
  rc = inline.run_code(
627
728
  _MARKDOWN_CODE,
628
729
  session_id=sid,
629
730
  env={"BW_MD_URL": url, "BW_MD_OUT": out_path, "BW_MD_MODE": mode},
731
+ timeout_s=opts["timeout_s"],
630
732
  )
631
733
  if rc != 0:
632
734
  return rc
@@ -650,11 +752,126 @@ def _cmd_markdown(args: list[str]) -> int:
650
752
  if not keep_file:
651
753
  with contextlib.suppress(OSError):
652
754
  Path(out_path).unlink()
755
+ _end_throwaway_session("markdown", sid)
756
+
757
+
758
+ SEARCH_HELP = """Usage:
759
+ browserwright search <query> [--limit=N] [--json] [--backend=extension|cdp]
760
+ [--attach=<port|url>] [--search-url=TEMPLATE]
761
+ [--name=LABEL] [--timeout=SECONDS]
762
+
763
+ Search the web in a real browser and print the results page as ranked links:
764
+ title, URL, date and snippet, plus the engine's AI Overview, knowledge panel,
765
+ "people also ask" and related searches when the query triggered them. Links
766
+ only, never page bodies — read the ones worth it with `browserwright markdown`.
767
+
768
+ Owns its whole lifecycle like `markdown`: a throwaway session, torn down after.
769
+ Google's opaque `/goto?url=…` links (what a signed-out browser gets) are
770
+ resolved to the real URL. A captcha or consent wall fails with exit 5 instead
771
+ of returning an empty list; "nothing matched" is reported as zero results.
772
+
773
+ Flags:
774
+ --limit=N max results (default 10)
775
+ --json print the structured payload instead of text
776
+ --backend extension (default, the user's real Chrome) | cdp
777
+ --attach=TARGET borrow a CDP browser (port or ws/http(s) URL); implies
778
+ --backend=cdp, left running afterwards. Same values as
779
+ `session new --attach`.
780
+ --search-url=T results page template; {query} (URL-encoded) and {limit}
781
+ are substituted. Default: Google. The extraction expects
782
+ Google's markup.
783
+ --name=LABEL session label; shows as the Chrome tab group title
784
+ --timeout=SECONDS
785
+ the call deadline for the search (default 90); running out
786
+ exits 7 (DeadlineExceeded)
787
+ """
788
+
789
+ # Runs inside the session's executor; same value-passing discipline as
790
+ # _MARKDOWN_CODE, and the payload rides back on disk for the same reason.
791
+ _SEARCH_CODE = """
792
+ import json, os
793
+ from browserwright.repl.search import search_page
794
+
795
+ _p = search_page(page, os.environ["BW_SEARCH_QUERY"],
796
+ limit=int(os.environ["BW_SEARCH_LIMIT"]),
797
+ search_url=os.environ["BW_SEARCH_URL"])
798
+ with open(os.environ["BW_SEARCH_OUT"], "w", encoding="utf-8") as _f:
799
+ json.dump(_p, _f, ensure_ascii=False)
800
+ _bw_warn("search: %d results%s" % (len(_p["results"]), " (engine: nothing matched)" if _p["noMatch"] else ""))
801
+ """
802
+
803
+
804
+ def _cmd_search(args: list[str]) -> int:
805
+ """``browserwright search <query>`` — one results page, as ranked links.
806
+
807
+ Self-sessioned like ``markdown``. Every query word goes in the first
808
+ argument (quote it); flags follow.
809
+ """
810
+ if not args or args[0] in {"-h", "--help"}:
811
+ sys.stdout.write(SEARCH_HELP)
812
+ return 0 if args else 1
813
+
814
+ query = args[0].strip()
815
+ if not query or query.startswith("-"):
816
+ print(f"usage error: expected a query, got {args[0]!r}", file=sys.stderr)
817
+ print(SEARCH_HELP, file=sys.stderr)
818
+ return 1
819
+ kw = _parse_kv_args(args[1:])
820
+
821
+ from .repl.search import DEFAULT_LIMIT, DEFAULT_SEARCH_URL, render_results
822
+
823
+ try:
824
+ limit = int(kw.get("limit", DEFAULT_LIMIT))
825
+ if limit < 1:
826
+ raise ValueError
827
+ except (TypeError, ValueError):
828
+ print("usage error: --limit must be a positive integer", file=sys.stderr)
829
+ return 1
830
+ search_url = kw.get("search-url", DEFAULT_SEARCH_URL)
831
+ if not isinstance(search_url, str) or "{query}" not in search_url:
832
+ print("usage error: --search-url must contain {query}", file=sys.stderr)
833
+ return 1
834
+ opts, err = _throwaway_options(kw)
835
+ if err:
836
+ print(f"usage error: {err}", file=sys.stderr)
837
+ return 1
838
+
839
+ import contextlib
840
+ import tempfile
841
+
842
+ from .repl import inline
843
+
844
+ fd, out_path = tempfile.mkstemp(prefix="browserwright-search-", suffix=".json")
845
+ os.close(fd)
846
+ sid, rc = _open_throwaway_session(opts, str(kw.get("name", "search")))
847
+ if sid is None:
848
+ Path(out_path).unlink(missing_ok=True)
849
+ return rc
850
+
851
+ try:
852
+ rc = inline.run_code(
853
+ _SEARCH_CODE,
854
+ session_id=sid,
855
+ env={"BW_SEARCH_QUERY": query, "BW_SEARCH_LIMIT": str(limit),
856
+ "BW_SEARCH_URL": search_url, "BW_SEARCH_OUT": out_path},
857
+ timeout_s=opts["timeout_s"],
858
+ )
859
+ if rc != 0:
860
+ return rc
653
861
  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)
862
+ payload = json.loads(Path(out_path).read_text(encoding="utf-8"))
863
+ except (OSError, ValueError) as e:
864
+ print(f"search: could not read the results: {e}", file=sys.stderr)
865
+ return 3
866
+ if kw.get("json"):
867
+ sys.stdout.write(json.dumps(payload, ensure_ascii=False) + "\n")
868
+ else:
869
+ sys.stdout.write(render_results(payload))
870
+ return 0
871
+ finally:
872
+ with contextlib.suppress(OSError):
873
+ Path(out_path).unlink()
874
+ _end_throwaway_session("search", sid)
658
875
 
659
876
 
660
877
  def _cmd_doctor(args: list[str]) -> int:
@@ -1267,6 +1484,8 @@ def main(argv: Optional[list[str]] = None) -> None:
1267
1484
  or command_argv[0].startswith("--code-file=")
1268
1485
  or command_argv[0] == "--env"
1269
1486
  or command_argv[0].startswith("--env=")
1487
+ or command_argv[0] == "--timeout"
1488
+ or command_argv[0].startswith("--timeout=")
1270
1489
  ):
1271
1490
  sys.exit(_cmd_execute(argv))
1272
1491
  argv = command_argv
@@ -1291,10 +1510,12 @@ def main(argv: Optional[list[str]] = None) -> None:
1291
1510
  sys.exit(_cmd_index(rest))
1292
1511
  if cmd == "memory":
1293
1512
  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).
1513
+ # Deliberately NOT under the -s branch: these browser-driving commands own
1514
+ # their own throwaway session (ADR-0006).
1296
1515
  if cmd == "markdown":
1297
1516
  sys.exit(_cmd_markdown(rest))
1517
+ if cmd == "search":
1518
+ sys.exit(_cmd_search(rest))
1298
1519
  if cmd == "session":
1299
1520
  sys.exit(_cmd_session(rest, session_id=global_session))
1300
1521
  if cmd == "whoami":
@@ -0,0 +1,127 @@
1
+ """The **call deadline** as the daemon sees it (ADR-0014).
2
+
3
+ An agent's call reaches the daemon as one `ExecuteRequest` on the `/exec`
4
+ relay, and that request carries `timeout_ms`. The executor enforces it as a
5
+ fail-stop deadline. Everything the executor's Playwright then sends to the
6
+ browser crosses the daemon again — as CDP commands on the session's facade
7
+ connection — and those commands must not wait on a fixed budget of their own
8
+ that can expire first (#116). So the relay binds the call's absolute deadline
9
+ to the session for the lifetime of the call, and the facade asks how much of
10
+ it is left whenever it forwards a command for that session.
11
+
12
+ Daemon-internal work with no caller (attach on extension connect, teardown,
13
+ heartbeats — ADR-0009, ADR-0013) never asks, and keeps its own budgets.
14
+
15
+ The executor runs requests FIFO, so when several calls for one session are in
16
+ flight the one actually running is the OLDEST still bound; that is the
17
+ deadline `remaining_s` reports.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import itertools
22
+ import json
23
+ import time
24
+
25
+ from ..._executor.protocol import ExecuteRequest
26
+
27
+ #: session id -> [(token, absolute monotonic deadline)], oldest first.
28
+ _bound: dict[str, list[tuple[int, float]]] = {}
29
+ _tokens = itertools.count(1)
30
+
31
+
32
+ def bind(session_id: str, timeout_ms: int) -> int:
33
+ """Bind one call's absolute deadline to ``session_id``; returns a token
34
+ for `release`."""
35
+ token = next(_tokens)
36
+ deadline = time.monotonic() + max(0, timeout_ms) / 1000.0
37
+ _bound.setdefault(session_id, []).append((token, deadline))
38
+ return token
39
+
40
+
41
+ def release(session_id: str, token: int) -> None:
42
+ """Unbind one call. Releasing an unknown or already-released token is a
43
+ no-op, so every exit path may release unconditionally."""
44
+ calls = _bound.get(session_id)
45
+ if not calls:
46
+ return
47
+ calls[:] = [c for c in calls if c[0] != token]
48
+ if not calls:
49
+ _bound.pop(session_id, None)
50
+
51
+
52
+ def remaining_s(session_id: str | None) -> float | None:
53
+ """Seconds left on the call currently running for ``session_id``, or
54
+ ``None`` when no agent call is bound (the caller then keeps its own
55
+ budget). Never negative: an expired deadline reports 0.0 — the executor
56
+ is about to be fail-stopped, and nothing should start a fresh wait."""
57
+ if session_id is None:
58
+ return None
59
+ calls = _bound.get(session_id)
60
+ if not calls:
61
+ return None
62
+ return max(0.0, calls[0][1] - time.monotonic())
63
+
64
+
65
+ #: How far past the call deadline an agent command's inner waits reach.
66
+ #:
67
+ #: The executor owns the call deadline: when it runs out the executor is
68
+ #: fail-stopped and the caller gets `DeadlineExceeded` (exit 7). An inner wait
69
+ #: that ended *at* the deadline would race that — and the extension, which by
70
+ #: construction settles before the relay, would win it, surfacing the expiry
71
+ #: as a command timeout inside the agent's code (`PageLoadFailed`, exit 3)
72
+ #: instead. So the inner waits are derived from the deadline but end this much
73
+ #: after it: the executor always fires first, and the inner bounds stay what
74
+ #: they are for — a net for a wedged extension or Chrome. The relay's margin
75
+ #: (at most 1s) is taken out of this, so the extension still outlasts the
76
+ #: deadline by at least 1s.
77
+ INNER_GRACE_S = 2.0
78
+
79
+
80
+ def command_wait_s(session_id: str | None) -> float | None:
81
+ """How long an agent command for ``session_id`` may wait in the relay:
82
+ the remaining call deadline plus `INNER_GRACE_S`, or ``None`` when no
83
+ call is bound (the relay keeps its own default)."""
84
+ remaining = remaining_s(session_id)
85
+ return None if remaining is None else remaining + INNER_GRACE_S
86
+
87
+
88
+ def timeout_ms_of(payload: bytes) -> int | None:
89
+ """The `timeout_ms` the executor will enforce for one request frame, or
90
+ ``None`` when the frame is not a request it will run.
91
+
92
+ Parsed with the executor's own `ExecuteRequest.from_dict`, so a missing or
93
+ invalid value resolves to the same default the executor applies."""
94
+ try:
95
+ frame = json.loads(payload)
96
+ return ExecuteRequest.from_dict(frame).timeout_ms
97
+ except (ValueError, TypeError, AttributeError):
98
+ return None
99
+
100
+
101
+ class RelayedCalls:
102
+ """The calls one `/exec` connection has in flight for its session.
103
+
104
+ The relay feeds it every request frame it forwards to the executor and
105
+ every response frame it forwards back: a request binds its deadline before
106
+ the executor can act on it, its response releases it, and closing the
107
+ connection releases whatever is left (a fail-stopped executor answers
108
+ nothing). One response answers the oldest request, as the executor is
109
+ FIFO.
110
+ """
111
+
112
+ def __init__(self, session_id: str) -> None:
113
+ self._session_id = session_id
114
+ self._tokens: list[int] = []
115
+
116
+ def request(self, payload: bytes) -> None:
117
+ timeout_ms = timeout_ms_of(payload)
118
+ if timeout_ms is not None:
119
+ self._tokens.append(bind(self._session_id, timeout_ms))
120
+
121
+ def response(self) -> None:
122
+ if self._tokens:
123
+ release(self._session_id, self._tokens.pop(0))
124
+
125
+ def close(self) -> None:
126
+ while self._tokens:
127
+ release(self._session_id, self._tokens.pop())