Skip to content
Back to search

browser-harness

MarketplaceWorks with Claude CodeGitHub

Install browser-harness directly from this repo.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/browser-use/browser-harness with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/browser-use/browser-harness'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/browser-use-browser-harness/badge.svg)](/listings/browser-use-browser-harness)

HTML

<a href="/listings/browser-use-browser-harness"><img src="/api/listings/browser-use-browser-harness/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Paste into Claude Code or Codex:

Install or upgrade browser-harness to the latest stable version with uv using Python 3.12, register the skill from `browser-harness skill`, and connect it to my browser. Ask whether I want local browser recordings enabled; default to no and preserve my existing preference on upgrades. Follow https://github.com/browser-use/browser-harness/blob/main/install.md if setup or connection fails.

The agent will open `chrome://inspect/#remote-debugging`. On first setup, tick the checkbox so the agent can connect to your browser:

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 25 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. {
  2. "name": "browser-harness",
  3. "description": "Install browser-harness directly from this repo.",
  4. "owner": {
  5. "name": "Browser Use",
  6. "url": "https://browser-use.com"
  7. },
  8. "plugins": [
  9. {
  10. "name": "browser-harness",
  11. "description": "Direct CDP browser control for agents: coordinate clicks, screenshots, persistent Python session, local Chrome or Browser Use cloud. Ships skills only; the `browser-harness` CLI is a one-time install prerequisite.",
  12. "category": "automation",
  13. "source": ".",
  14. "homepage": "https://github.com/browser-use/browser-harness",
  15. "keywords": [
  16. "browser",
  17. "automation",
  18. "cdp",
  19. "chrome",
  20. "scraping",
  21. "screenshot"
  22. ]
  23. }
  24. ]
  25. }
README.md · README · 136 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <img src="https://raw.githubusercontent.com/browser-use/media/main/browser-harness/banner-ink.svg" alt="Browser Harness" width="100%" />
  2. > [!NOTE]
  3. > **Browser Harness is now the engine inside [Browser Use](https://github.com/browser-use/browser-use).** Use the `browser-use` CLI: same helpers and daemon, plus `browser-use login`, an MCP server (`browser-use --cli-mcp`) and `browser-use skill install`.
  4. >
  5. > ```bash
  6. > uv tool install browser-use
  7. > browser-use <<'PY'
  8. > new_tab("https://example.com")
  9. > print(page_info())
  10. > PY
  11. > ```
  12. >
  13. > The `browser-harness` command keeps working. Domain skills and interaction skills stay in this repo.
  14. # Browser Harness ♞
  15. Browser Harness lets Claude Code, Codex or Cursor use your real Chrome browser: open pages, click, type, read and download, logged in as you. Paste one prompt into your coding agent to set it up. It talks to Chrome over the DevTools Protocol (CDP), and the agent writes any missing helper as it works, so the harness gets better with each task. Open source, MIT licensed.
  16. Try browser-harness in [Browser Use Cloud](https://cloud.browser-use.com/v4?utm_campaign=browser-harness-use-in-cloud&utm_source=github) or paste the setup prompt into your coding agent.
  17. ```
  18. ● agent: wants to upload a file
  19. │
  20. ● agent-workspace/agent_helpers.py → helper missing
  21. │
  22. ● agent writes it agent_helpers.py
  23. │ + custom helper
  24. ✓ file uploaded
  25. ```
  26. **You will never use the browser again.**
  27. ## See it work
  28. **Task:** "Open my X profile, find my latest 20 video posts, and download them."
  29. [![Download my latest 20 X videos](docs/download-latest-20-x-videos.gif)](https://browser-use.com/showcase/videos/download-latest-20-x-videos.mp4)
  30. ## Setup prompt
  31. Paste into Claude Code or Codex (Cursor: use the [MCP config](#cursor) below):
  32. ```text
  33. Install browser-use with `uv tool install browser-use`, run `browser-use skill install` to register the skill, and connect it to my browser. If setup or connection fails, run `browser-use --doctor` and follow its output and the error message.
  34. ```
  35. The agent will open `chrome://inspect/#remote-debugging`. On first setup, tick
  36. the checkbox so the agent can connect to your browser:
  37. <img src="docs/setup-remote-debugging.png" alt="Remote debugging setup" width="520" style="border-radius: 12px;" />
  38. ## How it works
  39. - [`install.md`](install.md) connects the agent to your browser.
  40. - [`SKILL.md`](SKILL.md) teaches it the browser workflow.
  41. - [`src/browser_harness/`](src/browser_harness/) stays protected while the agent writes reusable helpers in its local workspace.
  42. ## Compared with other browser tools
  43. | | Works with | Browser it drives | What you approve in your own Chrome |
  44. |---|---|---|---|
  45. | **Browser Harness** | Claude Code, Codex, Cursor, any MCP client via `browser-harness-mcp` | Your running Chrome, logged in as you | Whole browser: on Chrome 144+, tick remote debugging in `chrome://inspect`, then click Allow |
  46. | **Playwright MCP** | Any MCP client (Claude Code, Codex, Cursor, Copilot and more) | Its own browser profile by default. Your Chrome with `--extension` (Playwright Extension) or `--cdp-endpoint` | Chosen tabs (one tab group per client) via the extension, approval skippable with a token; or whole browser via `--cdp-endpoint` |
  47. | **Playwright CLI** | Claude Code, GitHub Copilot and other agents that run shell commands | Its own browser by default. Your Chrome with `attach --extension=chrome` or `attach --cdp=chrome` | Chosen tab via the Playwright Extension, or whole browser via `--cdp` |
  48. | **Chrome DevTools MCP** | Any MCP client (Claude Code, Cursor, Copilot, Antigravity and more), plus a CLI | A new Chrome with a dedicated profile by default. Your Chrome 144+ with `--autoConnect` | Whole browser: the same Chrome 144+ toggle and Allow dialog; the server sees every open window of that profile |
  49. | **agent-browser** | Claude Code, Codex, Cursor, Gemini CLI, Copilot and more, as a CLI with a skill, plus an MCP server | Its own Chrome for Testing by default. A copy of your Chrome profile with `--profile`. Your running Chrome with `--auto-connect` or `--cdp` | Whole browser via `--auto-connect` or `--cdp`: the same Chrome 144+ toggle and Allow dialog |
  50. | **Claude in Chrome** | Claude Code (CLI or VS Code) with the Claude extension, signed in with a direct Anthropic plan (Pro, Max, Team, Enterprise), not an API key | Your Chrome, Edge or other Chromium browser, logged in as you | Per site: allow sites in the extension, or per action in Claude Code (auto mode can skip the per-site check). Claude works in a tab group it opens |
  51. | **ChatGPT Browser and browser extension** | Codex and ChatGPT chats in the ChatGPT desktop app, not Codex CLI or the Codex IDE extension | Browser: a separate profile. Extension: your Chrome, Edge, Brave, Opera or Vivaldi profile | Per site: asks before each new website (allow once, for this site, or for all sites) |
  52. Matched eval by Browser Use on 100 of the 200 public [BU Bench V2.1](https://github.com/browser-use/benchmark) tasks (bu2-001 to bu2-100; 101-200 not run). Measured 2026-10-14.
  53. - Same agent for every tool: Codex CLI 0.144.6, GPT-6 Luna, medium reasoning, web search off. Same frozen judge.
  54. - Browser Harness was given to the agent as its CLI and SKILL.md, not `browser-harness-mcp`. Playwright MCP and Chrome DevTools MCP ran as MCP servers with default settings. agent-browser ran as its CLI and skill.
  55. - Every tool drove the same fresh Browser Use cloud browser over CDP. This does not measure each tool's default or local-Chrome mode.
  56. - One run per task. Agent failures were never retried. Runner, browser and judge failures were rerun once (Browser Harness 3 tasks, Playwright MCP 4, Chrome DevTools MCP 6, agent-browser 0).
  57. | Tool | Mean rubric score 0-100 (95% CI) | Fully solved | Median input tokens per task | Median model cost per task (GPT-6 Luna list price) | Median agent time per task |
  58. |---|---|---|---|---|---|
  59. | Browser Harness a6426f84 (main) | 60.4 (55.2-65.4) | 11% | 2.1M | $0.042 | 9.0 min |
  60. | Playwright MCP 0.0.83 | 60.0 (55.1-65.0) | 11% | 4.4M | $0.066 | 8.3 min |
  61. | Chrome DevTools MCP 1.10.1 | 61.0 (55.8-65.9) | 11% | 6.7M | $0.097 | 8.7 min |
  62. | agent-browser 0.39.1 | 56.3 (51.1-61.5) | 9% | 3.3M | $0.056 | 11.2 min |
  63. No tool wins on score: every paired difference against Browser Harness has a 95% CI that includes zero (other tool minus Browser Harness: agent-browser -4.0, CI -10.0 to +1.8; Playwright MCP -0.4, -6.6 to +5.7; Chrome DevTools MCP +0.6, -5.6 to +6.6).
  64. Browser Harness had the lowest median input tokens (2.1M vs 3.3-6.7M) and the lowest median model cost ($0.042 vs $0.056-0.097). Model cost excludes browser, proxy and judge. It was slower than Playwright MCP and Chrome DevTools MCP (median 9.0 vs 8.3 and 8.7 min) and faster than agent-browser (11.2 min). These are medians, with no confidence intervals.
  65. A first agent-browser run was discarded: a setup bug on our side let it launch its own local browser instead of the shared cloud browser. The row shows the corrected rerun.
  66. Measured with Codex only. Claude Code, Cursor, Playwright CLI and Claude in Chrome were not measured. Method and per-task scores: [coding-agent-browser-tools.json](https://browser-use.com/benchmarks/coding-agent-browser-tools.json).
  67. ### When to use something else
  68. - **Playwright** (Test, MCP or CLI): isolated, repeatable CI tests of your own app, in a clean browser with no personal logins.
  69. - **Chrome DevTools MCP**: performance traces and DevTools debugging (network, console, source-mapped stack traces).
  70. - **Claude in Chrome**: you only use Claude and have a Pro, Max, Team or Enterprise plan.
  71. - **Cursor's built-in Browser**: the agent doesn't need your logged-in Chrome. It runs in its own per-workspace profile.
  72. OpenAI's Codex labels its browser feature "Browser use" in its settings. It is separate from Browser Use, the company behind this repo.
  73. ## Scale with Browser Use Cloud
  74. Use your local browser for logged-in, personal work. When you want many browsers in parallel, with live previews, proxies, stealth, CAPTCHA solving, and more, scale with [Browser Use Cloud](https://cloud.browser-use.com/new-api-key).
  75. ## MCP server
  76. `browser-use --cli-mcp` exposes the browser control helpers as MCP tools over
  77. stdio, so any MCP client (Claude Code, Devin, Cursor, etc.) can drive the
  78. browser without writing a second CDP layer. The older `browser-harness-mcp`
  79. keeps working; see [docs/MCP.md](docs/MCP.md).
  80. ### Cursor
  81. Add this to `.cursor/mcp.json` in your project, or to `~/.cursor/mcp.json` for
  82. every project. It needs [uv](https://docs.astral.sh/uv/).
  83. ```json
  84. {
  85. "mcpServers": {
  86. "browser-use": {
  87. "type": "stdio",
  88. "command": "uvx",
  89. "args": ["browser-use", "--cli-mcp"]
  90. }
  91. }
  92. }
  93. ```
  94. ## Contributing
  95. Bug fixes, documentation improvements, and agent-generated domain skills are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md).
  96. ---
  97. [The Bitter Lesson of Agent Harnesses](https://browser-use.com/posts/bitter-lesson-agent-harnesses) · [Web Agents That Actually Learn](https://browser-use.com/posts/web-agents-that-actually-learn)
src/browser_harness/admin.py · Bundled script · 1,588 lines · 2 findings marked
  1. import json
  2. import os
  3. import re
  4. import secrets
  5. import socket
  6. import subprocess
  7. import sys
  8. import time
  9. import urllib.request
  10. from pathlib import Path
  11. from . import _ipc as ipc
  12. from . import auth
  13. from . import paths
  14. def _process_start_time(pid):
  15. """Opaque process-start-time fingerprint at PID, or None if unavailable.
  16. Two reads returning the same non-None value mean the PID still refers to
  17. the same process; a different value means the PID was reused. Used by
  18. restart_daemon() to keep the force-kill recovery path working even when
  19. the daemon has already torn down its IPC socket (e.g. during a slow
  20. remote shutdown), without falling back to "trust the pid file" — which
  21. would re-introduce the PID-reuse hazard.
  22. Linux: /proc/<pid>/stat field 22 (starttime in clock ticks since boot).
  23. macOS: `ps -o lstart= -p <pid>` (an absolute timestamp string).
  24. Windows: GetProcessTimes via ctypes (FILETIME creation time, 100-ns since 1601).
  25. Anywhere else: returns None; restart_daemon falls back to its strict
  26. identify-only check, which is safer than no check at all.
  27. """
  28. if type(pid) is not int or pid <= 0:
  29. return None
  30. if sys.platform.startswith("linux"):
  31. try:
  32. with open(f"/proc/{pid}/stat", "rb") as f:
  33. raw = f.read().decode("ascii", errors="replace")
  34. except (FileNotFoundError, PermissionError, OSError):
  35. return None
  36. # Field 2 is `(comm)`; comm can contain spaces and parens, so split off
  37. # everything after the LAST `)` and index from there.
  38. try:
  39. tail = raw[raw.rindex(")") + 2:].split()
  40. return tail[19] # starttime is field 22 (0-indexed: 21 - skipped 2 = 19)
  41. except (ValueError, IndexError):
  42. return None
  43. if sys.platform == "darwin":
  44. try:
  45. out = subprocess.check_output(
  46. ["ps", "-o", "lstart=", "-p", str(pid)],
  47. stderr=subprocess.DEVNULL, timeout=2,
  48. )
  49. except (subprocess.SubprocessError, OSError):
  50. return None
  51. s = out.decode("ascii", errors="replace").strip()
  52. return s or None
  53. if sys.platform == "win32":
  54. # Windows users running a remote daemon hit the same slow-shutdown
  55. # window as POSIX (stop_remote() PATCHes api.browser-use.com after
  56. # the IPC socket has been torn down). Without a fingerprint here the
  57. # SIGTERM gate can never pass during that window, leaving an orphan
  58. # daemon that may continue to hold a billed cloud browser. Use
  59. # GetProcessTimes via ctypes to read the kernel-reported creation
  60. # time as a 64-bit FILETIME (100-ns intervals since 1601-01-01).
  61. try:
  62. import ctypes
  63. from ctypes import wintypes
  64. except ImportError:
  65. return None
  66. PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
  67. try:
  68. kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
  69. kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
  70. kernel32.OpenProcess.restype = wintypes.HANDLE
  71. kernel32.GetProcessTimes.argtypes = [
  72. wintypes.HANDLE,
  73. ctypes.POINTER(wintypes.FILETIME),
  74. ctypes.POINTER(wintypes.FILETIME),
  75. ctypes.POINTER(wintypes.FILETIME),
  76. ctypes.POINTER(wintypes.FILETIME),
  77. ]
  78. kernel32.GetProcessTimes.restype = wintypes.BOOL
  79. kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
  80. kernel32.CloseHandle.restype = wintypes.BOOL
  81. except (OSError, AttributeError):
  82. return None
  83. h = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
  84. if not h:
  85. return None
  86. try:
  87. creation = wintypes.FILETIME()
  88. exit_ft = wintypes.FILETIME()
  89. kernel_ft = wintypes.FILETIME()
  90. user_ft = wintypes.FILETIME()
  91. ok = kernel32.GetProcessTimes(
  92. h, ctypes.byref(creation), ctypes.byref(exit_ft),
  93. ctypes.byref(kernel_ft), ctypes.byref(user_ft),
  94. )
  95. if not ok:
  96. return None
  97. return (creation.dwHighDateTime << 32) | creation.dwLowDateTime
  98. finally:
  99. kernel32.CloseHandle(h)
  100. return None
  101. def _load_env():
  102. repo_root = Path(__file__).resolve().parents[2]
  103. workspace = paths.workspace_dir()
  104. for p in (repo_root / ".env", workspace / ".env"):
  105. if not p.exists():
  106. continue
  107. _load_env_file(p)
  108. def _load_env_file(p):
  109. for line in p.read_text(encoding="utf-8-sig", errors="replace").splitlines():
  110. line = line.strip()
  111. if not line or line.startswith("#") or "=" not in line:
  112. continue
  113. k, v = line.split("=", 1)
  114. os.environ.setdefault(k.strip(), v.strip().strip('"').strip("'"))
  115. _load_env()
  116. NAME = os.environ.get("BU_NAME", "default")
  117. BU_API = "https://api.browser-use.com/api/v3"
  118. PYPI_JSON = "https://pypi.org/pypi/browser-harness/json"
  119. VERSION_CACHE = paths.config_dir() / "version-cache.json"
  120. VERSION_CACHE_TTL = 24 * 3600
  121. DOCTOR_TEXT_LIMIT = 140
  122. def _log_tail(name):
  123. try:
  124. return ipc.log_path(name or NAME).read_text(encoding="utf-8", errors="replace").strip().splitlines()[-1]
  125. except (FileNotFoundError, IndexError, OSError):
  126. return None
  127. def _is_daemon_process(pid):
  128. """Best effort: does `pid` look like one of our daemons?
  129. Guards against pid reuse — a dead daemon's number can be handed to an
  130. unrelated process, and treating that as parked would make every caller wait
  131. instead of spawning. Where the check cannot run (Windows, no ps) we fall
  132. back to the log-freshness guard rather than blocking startup.
  133. """
  134. command = (
  135. ["powershell", "-NoProfile", "-NonInteractive", "-Command",
  136. f"(Get-CimInstance Win32_Process -Filter 'ProcessId={pid}').CommandLine"]
  137. if sys.platform == "win32"
  138. else ["ps", "-o", "command=", "-p", str(pid)]
  139. )
  140. try:
  141. result = subprocess.run(command, capture_output=True, text=True, timeout=2)
  142. except Exception:
  143. return False
  144. if result.returncode != 0:
  145. return False
  146. out = result.stdout
  147. if not out.strip():
  148. return False
  149. return "browser_harness" in out
  150. def _pending_pid_record(path):
  151. """Read a parent-published PID plus process-start fingerprint."""
  152. try:
  153. raw = path.read_text()
  154. try:
  155. record = json.loads(raw)
  156. pid = int(record["pid"])
  157. fingerprint = record.get("started")
  158. except (json.JSONDecodeError, TypeError, KeyError):
  159. fields = raw.split()
  160. pid = int(fields[0])
  161. fingerprint = None
  162. except (FileNotFoundError, OSError, ValueError, IndexError):
  163. return None
  164. if pid <= 0:
  165. return None
  166. if fingerprint is not None:
  167. current = _process_start_time(pid)
  168. return pid if current is not None and current == fingerprint else None
  169. return pid if _is_daemon_process(pid) else None
  170. def _fingerprinted_pending_generation(path):
  171. """Return (PID, start fingerprint) only while that generation is alive."""
  172. try:
  173. record = json.loads(path.read_text())
  174. pid = record["pid"]
  175. fingerprint = record.get("started")
  176. except (FileNotFoundError, OSError, TypeError, KeyError, json.JSONDecodeError):
  177. return None
  178. if type(pid) is not int or not 0 < pid < (1 << 31) or fingerprint is None:
  179. return None
  180. current = _process_start_time(pid)
  181. return (pid, fingerprint) if current is not None and current == fingerprint else None
  182. def _fingerprinted_pending_pid(path):
  183. generation = _fingerprinted_pending_generation(path)
  184. return generation[0] if generation is not None else None
  185. def _pid_number(path):
  186. """Read only the PID field, without treating it as a trusted identity."""
  187. try:
  188. raw = path.read_text()
  189. try:
  190. return int(json.loads(raw)["pid"])
  191. except (json.JSONDecodeError, TypeError, KeyError):
  192. return int(raw.split()[0])
  193. except (FileNotFoundError, OSError, ValueError, IndexError):
  194. return None
  195. def _publish_pid(path, pid):
  196. fingerprint = _process_start_time(pid)
  197. value = json.dumps({"pid": pid, "started": fingerprint}, sort_keys=True, separators=(",", ":"))
  198. tmp = path.with_name(f"{path.name}.{os.getpid()}.{secrets.token_hex(8)}.tmp")
  199. tmp.write_text(value)
  200. os.replace(tmp, path)
  201. def _parked_daemon_pid(name=None):
  202. """PID of a daemon whose handshake is still parked on Chrome's Allow popup.
  203. A parked daemon has no IPC socket yet, so daemon_alive() and identify() both
  204. say "nothing there" and every caller used to spawn a sibling, raising a
  205. second popup and truncating the first daemon's log. The pid file plus a
  206. fresh `handshake-wait` breadcrumb identify it without needing IPC.
  207. """
  208. if not (_log_tail(name) or "").startswith("handshake-wait"):
  209. return None
  210. pid = _pending_pid_record(ipc.pid_path(name or NAME))
  211. if pid is None:
  212. return None
  213. return pid
  214. def _starting_daemon_pid(name=None):
  215. """PID of a daemon child in the short gap before it writes handshake-wait."""
  216. path = ipc.pid_path(name or NAME)
  217. try:
  218. pid = _pending_pid_record(path)
  219. except OSError:
  220. return None
  221. return pid
  222. class _spawn_lock:
  223. """Only one process spawns a daemon at a time.
  224. Two cold invocations that both miss the parked check would otherwise open
  225. two connections and raise two popups, which is the bug this file is fixing.
  226. Best effort: if the lock cannot be taken we still proceed, because failing
  227. to start is worse than an extra popup.
  228. """
  229. def __init__(self, name=None, timeout=30.0):
  230. self.path = ipc.pid_path(name or NAME).with_suffix(".spawnlock")
  231. self.timeout = timeout
  232. self.fd = None
  233. def _try_lock(self):
  234. if sys.platform == "win32":
  235. import msvcrt
  236. os.lseek(self.fd, 0, os.SEEK_SET)
  237. try:
  238. msvcrt.locking(self.fd, msvcrt.LK_NBLCK, 1)
  239. return True
  240. except OSError:
  241. return False
  242. import fcntl
  243. try:
  244. fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  245. return True
  246. except OSError:
  247. return False
  248. def __enter__(self):
  249. deadline = time.time() + self.timeout
  250. self.fd = os.open(str(self.path), os.O_CREAT | os.O_RDWR, 0o600)
  251. if os.fstat(self.fd).st_size == 0:
  252. os.write(self.fd, b"1")
  253. while True:
  254. if self._try_lock():
  255. return self
  256. if time.time() >= deadline:
  257. os.close(self.fd)
  258. self.fd = None
  259. return self
  260. time.sleep(0.1)
  261. def __exit__(self, *exc):
  262. if self.fd is not None:
  263. try:
  264. if sys.platform == "win32":
  265. import msvcrt
  266. os.lseek(self.fd, 0, os.SEEK_SET)
  267. msvcrt.locking(self.fd, msvcrt.LK_UNLCK, 1)
  268. else:
  269. import fcntl
  270. fcntl.flock(self.fd, fcntl.LOCK_UN)
  271. except OSError:
  272. pass
  273. try:
  274. os.close(self.fd)
  275. except OSError:
  276. pass
  277. return False
  278. def _needs_chrome_remote_debugging_prompt(msg):
  279. """True when Chrome needs the inspect-page permission flow."""
  280. lower = (msg or "").lower()
  281. return (
  282. "devtoolsactiveport not found" in lower
  283. or "enable chrome://inspect" in lower
  284. or "not live yet" in lower
  285. or (
  286. "ws handshake failed" in lower
  287. and (
  288. "403" in lower
  289. or "opening handshake" in lower
  290. or "timed out" in lower
  291. or "timeout" in lower
  292. )
  293. )
  294. )
  295. def _needs_chrome_permission_popup(msg):
  296. """True when Chrome is reachable but waiting on the per-session Allow popup."""
  297. lower = (msg or "").lower()
  298. return "permission-blocked" in lower
  299. def _chrome_not_running(msg):
  300. """True when the daemon found no running supported browser"""
  301. return "chrome-not-running" in (msg or "").lower()
  302. def _is_local_chrome_mode(env=None):
  303. """True when the daemon discovers a local Chrome instead of a remote CDP WS."""
  304. env = env or {}
  305. return not (
  306. env.get("BU_CDP_WS")
  307. or env.get("BU_CDP_URL")
  308. or os.environ.get("BU_CDP_WS")
  309. or os.environ.get("BU_CDP_URL")
  310. )
  311. def _daemon_wait_windows(wait, local):
  312. """Return normal startup and Chrome-approval wait windows in seconds."""
  313. explicit_wait = wait is not None
  314. startup_wait = float(wait) if explicit_wait else 60.0
  315. approval_wait = None if local and not explicit_wait else startup_wait
  316. return startup_wait, approval_wait
  317. def daemon_alive(name=None):
  318. # Ping handshake (not a bare connect) so a stale .port file + port reuse
  319. # after a daemon crash doesn't make us mistake an unrelated listener for ours.
  320. return ipc.ping(name or NAME, timeout=1.0)
  321. def daemon_browser_kind(name=None):
  322. """'cloud' | 'cdp' | 'local' as self-reported by a live daemon, else None.
  323. None covers unreachable daemons and pre-browser_kind daemons still running
  324. from an older version."""
  325. c = None
  326. try:
  327. c, token = ipc.connect(name or NAME, timeout=1.0)
  328. response = ipc.request(c, token, {"meta": "ping"})
  329. kind = response.get("browser_kind") if isinstance(response, dict) else None
  330. return kind if kind in {"cloud", "cdp", "local"} else None
  331. except (FileNotFoundError, ConnectionRefusedError, TimeoutError, socket.timeout, OSError, ValueError):
  332. return None
  333. finally:
  334. if c:
  335. c.close()
  336. def _daemon_endpoint_names():
  337. # BH_RUNTIME_DIR isolates one daemon per dir → no filename-prefix discovery,
  338. # just check whether our local endpoint exists. Without BH_RUNTIME_DIR, or
  339. # with BH_RUNTIME_DIR_SHARED=1, _RUNTIME is shared and we glob `bu-*.<suffix>`
  340. # to find every daemon in that runtime dir.
  341. suffix = ".port" if ipc.IS_WINDOWS else ".sock"
  342. if ipc.BH_RUNTIME_DIR and not ipc.BH_RUNTIME_DIR_SHARED:
  343. return [NAME] if (ipc._RUNTIME / f"bu{suffix}").exists() else []
  344. names = []
  345. for p in sorted(ipc._RUNTIME.glob(f"bu-*{suffix}")):
  346. raw = p.name[3:-len(suffix)]
  347. try:
  348. ipc._check(raw)
  349. except ValueError:
  350. continue
  351. names.append(raw)
  352. return names
  353. def _daemon_browser_connection(name):
  354. c = None
  355. try:
  356. c, token = ipc.connect(name, timeout=1.0)
  357. response = ipc.request(c, token, {"meta": "connection_status"})
  358. if "error" in response:
  359. return None
  360. page = response.get("page")
  361. if page:
  362. page = {"title": page.get("title") or "(untitled)", "url": page.get("url") or ""}
  363. return {"name": name, "page": page}
  364. except (FileNotFoundError, ConnectionRefusedError, TimeoutError, socket.timeout, OSError, KeyError, ValueError, json.JSONDecodeError):
  365. return None
  366. finally:
  367. if c:
  368. c.close()
  369. def daemon_browser_ready(name=None):
  370. """Whether the selected daemon has a healthy attached browser connection."""
  371. return _daemon_browser_connection(name or NAME) is not None
  372. def browser_connections():
  373. """Live browser-harness daemons with healthy CDP browser connections and their attached page."""
  374. out = []
  375. for name in _daemon_endpoint_names():
  376. conn = _daemon_browser_connection(name)
  377. if conn:
  378. out.append(conn)
  379. return out
  380. def active_browser_connections():
  381. """Count live browser-harness daemons with a healthy CDP browser connection."""
  382. return len(browser_connections())
  383. def _doctor_short_text(value, limit=None):
  384. limit = limit or DOCTOR_TEXT_LIMIT
  385. value = str(value)
  386. return value if len(value) <= limit else value[:limit - 3] + "..."
  387. def _is_snap_browser(path: str) -> bool:
  388. """True when a Chrome binary path lives under /snap/ (Snap confinement on Linux)."""
  389. return bool(path) and "/snap/" in path.lower()
  390. def _doctor_snap_probe_path(path: str) -> str:
  391. raw = str(path)
  392. try:
  393. resolved = os.path.realpath(raw)
  394. except OSError:
  395. resolved = raw
  396. return raw if _is_snap_browser(raw) else resolved
  397. def _doctor_probe_chrome_binary_for_snap():
  398. """Return (label, probe_path) for the first Chrome/Chromium binary found, else (None, None).
  399. Honors BH_CHROME_PATH and CHROME_PATH before searching PATH for common names.
  400. """
  401. import shutil
  402. for key in ("BH_CHROME_PATH", "CHROME_PATH"):
  403. raw = (os.environ.get(key) or "").strip()
  404. if not raw:
  405. continue
  406. p = Path(raw).expanduser()
  407. try:
  408. if p.is_file():
  409. return (p.name, _doctor_snap_probe_path(str(p)))
  410. except OSError:
  411. continue
  412. for cmd in ("google-chrome-stable", "google-chrome", "chromium-browser", "chromium"):
  413. w = shutil.which(cmd)
  414. if not w:
  415. continue
  416. try:
  417. return (cmd, _doctor_snap_probe_path(w))
  418. except OSError:
  419. continue
  420. return (None, None)
  421. def _snap_linux_headless_doc_url():
  422. return "https://github.com/browser-use/browser-harness/blob/main/docs/snap-linux-headless.md"
  423. def run_doctor_fix_snap():
  424. """Print steps to replace Snap Chromium with a native Chrome for CDP. Always exit 0."""
  425. doc = _snap_linux_headless_doc_url()
  426. print("browser-harness doctor --fix-snap")
  427. print()
  428. print("Snap-packaged Chromium cannot expose DevTools the way browser-harness needs.")
  429. print(f"Full background: {doc}")
  430. print()
  431. print("1. Install Google Chrome from Google's .deb (not the Snap store):")
  432. print(" wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb")
  433. print(" sudo apt install ./google-chrome-stable_current_amd64.deb")
  434. print()
  435. print("2. Point the harness (and your shell) at the native binary so PATH does not")
  436. print(" pick the Snap wrapper first. Example for bash (~/.bashrc or session env):")
  437. print(" export BH_CHROME_PATH=/usr/bin/google-chrome-stable")
  438. print(" # CHROME_PATH is also honored by doctor's snap probe if you prefer that name.")
  439. print()
  440. print("3. Launch Chrome from that path (Way 2) or open Chrome normally (Way 1),")
  441. print(" enable remote debugging per install.md, then verify:")
  442. print(" browser-harness --doctor")
  443. print()
  444. return 0
  445. def ensure_daemon(wait=None, name=None, env=None):
  446. """Idempotent. Self-heals stale daemon, closed Chrome (launches it), cold
  447. Chrome, and missing Allow on chrome://inspect."""
  448. if daemon_alive(name):
  449. # Stale daemons accept connects AND reply to meta:* (pure Python) even when the
  450. # CDP WS to Chrome is dead — probe with a real CDP call and require "result".
  451. # Must go through ipc.connect so this works on Windows (TCP loopback) too;
  452. # raw AF_UNIX here would fail on every warm call and churn the daemon.
  453. for last in (False, True):
  454. try:
  455. s, token = ipc.connect(name or NAME, timeout=3.0)
  456. resp = ipc.request(s, token, {"method": "Target.getTargets", "params": {}})
  457. if "result" in resp: return
  458. except Exception:
  459. pass
  460. if not last: time.sleep(0.5)
  461. browser_kind = daemon_browser_kind(name)
  462. if browser_kind in {"cloud", None}:
  463. # A stale Cloud daemon still owns a billable browser. Its shutdown
  464. # handler stops that browser before acknowledging, and stays alive
  465. # when the Cloud stop fails so a later call can retry cleanup. Treat
  466. # an unknown kind the same way: the health failure that made the
  467. # daemon stale may also prevent classification, and replacing an
  468. # unclassified daemon best-effort could orphan a Cloud browser.
  469. stop_remote_daemon(name or NAME)
  470. else:
  471. restart_daemon(name)
  472. import subprocess, sys
  473. local = _is_local_chrome_mode(env)
  474. startup_wait, approval_wait = _daemon_wait_windows(wait, local)
  475. # Remote/CDP daemons retain the normal 60s startup bound. Only a local
  476. # Chrome handshake displaying the per-connection approval sheet removes a
  477. # default caller's deadline, so Browser Use cloud startup is unaffected.
  478. launched_browser = None
  479. opened_inspect = False
  480. for _ in range(3):
  481. e = {**os.environ, **({"BU_NAME": name} if name else {}), **(env or {})}
  482. try:
  483. stderr_sink = open(ipc.log_path(name or NAME), "ab")
  484. except OSError:
  485. stderr_sink = subprocess.DEVNULL
  486. if local:
  487. with _spawn_lock(name, timeout=startup_wait) as lock:
  488. if lock.fd is None:
  489. raise RuntimeError("daemon-starting: another browser-harness daemon is still starting; retry later")
  490. if daemon_alive(name):
  491. if stderr_sink is not subprocess.DEVNULL:
  492. stderr_sink.close()
  493. return
  494. pending_pid = _parked_daemon_pid(name) or _starting_daemon_pid(name)
  495. if pending_pid:
  496. p = None
  497. else:
  498. p = subprocess.Popen(
  499. [sys.executable, "-m", "browser_harness.daemon"],
  500. env=e, stdout=subprocess.DEVNULL, stderr=stderr_sink, **ipc.spawn_kwargs(),
  501. )
  502. _publish_pid(ipc.pid_path(name or NAME), p.pid)
  503. pending_pid = p.pid
  504. else:
  505. p = subprocess.Popen(
  506. [sys.executable, "-m", "browser_harness.daemon"],
  507. env=e, stdout=subprocess.DEVNULL, stderr=stderr_sink, **ipc.spawn_kwargs(),
  508. )
  509. if stderr_sink is not subprocess.DEVNULL:
  510. stderr_sink.close()
  511. spawned = time.monotonic()
  512. deadline = spawned + startup_wait
  513. hinted = not local
  514. approval_waiting = False
  515. pending_died = False
  516. while deadline is None or time.monotonic() < deadline:
  517. if daemon_alive(name):
  518. _cleanup_unattached_browser_launch(launched_browser)
  519. return
  520. if p is not None and p.poll() is not None:
  521. pending_died = True
  522. break
  523. if p is None and pending_pid and _pending_pid_record(ipc.pid_path(name or NAME)) != pending_pid:
  524. pending_died = True
  525. break
  526. log_tail = _log_tail(name) or ""
  527. if local and not approval_waiting and log_tail.startswith("handshake-wait"):
  528. approval_waiting = True
  529. deadline = None if approval_wait is None else max(deadline, spawned + approval_wait)
  530. if not hinted and time.monotonic() - spawned > 2 and log_tail.startswith("handshake-wait"):
  531. daemon_name = name or NAME
  532. approve_command = (
  533. "browser-harness mac-approve"
  534. if daemon_name == "default"
  535. else f"BU_NAME={daemon_name} browser-harness mac-approve"
  536. )
  537. action = (
  538. f"run `{approve_command}` in another shell or click Allow"
  539. if sys.platform == "darwin"
  540. else "click Allow"
  541. )
  542. print(
  543. f'browser-harness: Chrome is asking "Allow remote debugging?" — {action} to continue.',
  544. file=sys.stderr,
  545. )
  546. hinted = True
  547. time.sleep(0.2)
  548. msg = _log_tail(name) or ""
  549. permission_wait = local and (msg.startswith("handshake-wait") or _needs_chrome_permission_popup(msg))
  550. if local and pending_died:
  551. # Serialize cleanup with publishers and remove only the generation
  552. # we observed. Another waiter may already have published a healthy
  553. # successor while this caller was leaving its wait loop.
  554. with _spawn_lock(name, timeout=1.0) as cleanup_lock:
  555. if cleanup_lock.fd is not None and _pid_number(ipc.pid_path(name or NAME)) == pending_pid:
  556. try:
  557. ipc.pid_path(name or NAME).unlink()
  558. except FileNotFoundError:
  559. pass
  560. if permission_wait:
  561. # A denied/expired approval may already have dropped its sheet.
  562. # Never auto-spawn a replacement here: that would immediately
  563. # create another Chrome prompt and recreate the retry loop.
  564. raise RuntimeError(
  565. "permission-blocked: the pending Chrome connection ended before approval; "
  566. "browser-harness did not retry or create another connection."
  567. )
  568. continue
  569. if local and msg.startswith("handshake-wait"):
  570. # Leave it running: this daemon's connection is what holds the popup
  571. # on screen. Killing it dropped the popup and the retry raised a new
  572. # one, which is how a single approval turned into an endless prompt.
  573. raise RuntimeError(
  574. "permission-blocked: Chrome's Allow popup is still open and the pending daemon was left running. "
  575. "Approve that exact popup; browser-harness did not retry or create another connection."
  576. )
  577. if local and _needs_chrome_permission_popup(msg):
  578. print(
  579. 'browser-harness: Chrome is asking "Allow remote debugging?". '
  580. "Approve that exact popup; no replacement connection was started.",
  581. file=sys.stderr,
  582. )
  583. raise RuntimeError(
  584. "permission-blocked: Chrome did not approve the connection; browser-harness did not retry or create another connection."
  585. )
  586. if local and launched_browser is None and _chrome_not_running(msg):
  587. # Chrome is closed — launch the browser and retry
  588. restart_daemon(name)
  589. launched_browser = _launch_browser()
  590. if launched_browser is None:
  591. raise RuntimeError(
  592. "chrome-not-running: no supported browser is running and none could be launched -- ask the user to open Chrome, then retry."
  593. )
  594. print("browser-harness: Chrome isn't running — launching it. If Chrome shows an \"Allow remote debugging?\" popup, click Allow.", file=sys.stderr)
  595. from .daemon import supported_browser_running
  596. boot_deadline = time.time() + 15
  597. while time.time() < boot_deadline and not supported_browser_running():
  598. time.sleep(0.3)
  599. continue
  600. if local and not opened_inspect and _needs_chrome_remote_debugging_prompt(msg):
  601. opened_inspect = True
  602. from .daemon import remote_debugging_toggle_profiles, remote_debugging_user_enabled
  603. if remote_debugging_user_enabled():
  604. # chrome://inspect toggle is already on — connection died
  605. print(
  606. 'browser-harness: Chrome is asking "Allow remote debugging?". '
  607. "Approve that exact popup; no replacement connection was started.",
  608. file=sys.stderr,
  609. )
  610. raise RuntimeError(
  611. "permission-blocked: Chrome did not approve the connection; browser-harness did not retry or create another connection."
  612. )
  613. restart_daemon(name)
  614. _open_chrome_inspect_once()
  615. if remote_debugging_toggle_profiles():
  616. # Toggle already ticked from a previous run, but Chrome 144+
  617. # wants new Allow for this browser run.
  618. todo = 'click Allow on Chrome\'s "Allow remote debugging?" popup (the checkbox is already ticked; if no popup appears, untick and re-tick it)'
  619. else:
  620. todo = 'tick "Allow remote debugging for this browser instance" and click Allow on the popup'
  621. raise RuntimeError(
  622. f"remote-debugging-setup: opened chrome://inspect/#remote-debugging in Chrome -- ask the user to {todo}. "
  623. "Warn them Chrome shows ONE more Allow popup when the harness connects on the next attempt (per-connection approval; it is expected, not a re-ask). "
  624. "Retry after the user confirms; do not retry before."
  625. )
  626. raise RuntimeError(msg or f"daemon {name or NAME} didn't come up -- check {ipc.log_path(name or NAME)}")
  627. raise RuntimeError(f"daemon {name or NAME} didn't come up -- check {ipc.log_path(name or NAME)}")
  628. def require_existing_daemon(name=None):
  629. """Require a healthy existing daemon without spawning or reconnecting.
  630. Trusted orchestrators use this after they provision a scoped CDP transport.
  631. Failing closed prevents a later CLI call from silently discovering a
  632. different local Chrome when that orchestrator-owned daemon dies.
  633. """
  634. daemon_name = name or NAME
  635. if not daemon_alive(daemon_name):
  636. raise RuntimeError(f"required daemon {daemon_name!r} is not running")
  637. try:
  638. s, token = ipc.connect(daemon_name, timeout=3.0)
  639. try:
  640. resp = ipc.request(s, token, {"method": "Target.getTargets", "params": {}})
  641. finally:
  642. s.close()
  643. except Exception as exc:
  644. raise RuntimeError(f"required daemon {daemon_name!r} is unhealthy: {exc}") from exc
  645. if not isinstance(resp, dict) or "result" not in resp:
  646. raise RuntimeError(f"required daemon {daemon_name!r} failed its CDP health check")
  647. def stop_remote_daemon(name="remote"):
  648. """Stop a remote daemon and its backing Browser Use cloud browser.
  649. Triggers the daemon's clean shutdown, which PATCHes
  650. /browsers/{id} {"action":"stop"} so billing ends and any profile
  651. state in the session is persisted."""
  652. # restart_daemon is misnamed — it only stops the daemon (sends
  653. # shutdown, SIGTERMs if needed, unlinks socket+pid). It never
  654. # restarts anything on its own; a follow-up `browser-harness`
  655. # call would auto-spawn a fresh one via ensure_daemon(). That
  656. # "run-it-again-to-restart" workflow is why it was named that way.
  657. restart_daemon(name, require_clean=True)
  658. def restart_daemon(name=None, require_clean=False):
  659. """Best-effort daemon shutdown + socket/pid cleanup.
  660. Name is historical: callers typically follow this with another
  661. `browser-harness` invocation, which auto-spawns a fresh daemon via
  662. ensure_daemon(). The function itself only stops.
  663. With require_clean=True, an unavailable daemon or any response other than
  664. {"ok": true} raises before endpoint cleanup or process termination.
  665. Ready-daemon identity is verified via ipc.identify() before any process
  666. signal. A local daemon waiting on Chrome approval has no IPC socket yet;
  667. `--reload` may stop that exact pending generation only when its atomically
  668. published process-start fingerprint still matches. A stale or legacy PID
  669. file is never trusted for signaling.
  670. """
  671. import signal
  672. name = name or NAME
  673. pending_path = ipc.pid_path(name)
  674. pid_path = str(pending_path)
  675. pending_generation = None
  676. pending_unverified = False
  677. if (_log_tail(name) or "").startswith("handshake-wait"):
  678. parked_pid = _parked_daemon_pid(name)
  679. pending_generation = _fingerprinted_pending_generation(pending_path)
  680. pending_unverified = parked_pid is not None and pending_generation is None
  681. # Two pieces of information are tracked separately:
  682. # - daemon_pid: the daemon's self-reported PID, or None. Only daemons
  683. # running this version (or newer) include `pid` in the ping response;
  684. # pre-upgrade daemons return {pong: True} only and yield None here.
  685. # - daemon_alive: whether ANY daemon answers ping. Keeps the shutdown
  686. # IPC path working across upgrades — without it, a still-running
  687. # pre-upgrade daemon would have its socket deleted out from under it
  688. # while the process stayed alive.
  689. daemon_pid = ipc.identify(name, timeout=5.0)
  690. daemon_alive = daemon_pid is not None or ipc.ping(name, timeout=1.0)
  691. if require_clean and not daemon_alive:
  692. raise RuntimeError(f"daemon {name!r} is unavailable for required clean shutdown")
  693. if not daemon_alive and pending_unverified:
  694. raise RuntimeError(
  695. f"pending daemon {name!r} is live but has no verifiable process fingerprint; "
  696. "it was not signaled and its ownership records were preserved"
  697. )
  698. if not daemon_alive and pending_generation is not None:
  699. with _spawn_lock(name, timeout=5.0) as owner_lock:
  700. if owner_lock.fd is None:
  701. raise RuntimeError(
  702. f"pending daemon {name!r} is changing ownership; it was not signaled"
  703. )
  704. current_generation = _fingerprinted_pending_generation(pending_path)
  705. if current_generation != pending_generation:
  706. raise RuntimeError(
  707. f"pending daemon {name!r} changed ownership; the successor was not signaled "
  708. "and its records were preserved"
  709. )
  710. if ipc.ping(name, timeout=0.2):
  711. raise RuntimeError(
  712. f"pending daemon {name!r} became ready during cancellation; run --reload again"
  713. )
  714. try:
  715. os.kill(pending_generation[0], signal.SIGTERM)
  716. except (ProcessLookupError, OSError, SystemError, OverflowError):
  717. pass
  718. ipc.cleanup_endpoint(name)
  719. try:
  720. os.unlink(pid_path)
  721. except FileNotFoundError:
  722. pass
  723. return
  724. # Snapshot the daemon's process start-time as a secondary identity check.
  725. # The IPC socket can disappear before the process exits (e.g. the shutdown
  726. # path tears down the socket and then waits on a slow remote `stop` PATCH),
  727. # so identify() going None partway through is not proof of process death.
  728. # Comparing start-time before SIGTERM lets us recover the original
  729. # force-kill behavior for slow shutdowns without re-opening the
  730. # PID-reuse hole — a reused PID would have a different start-time.
  731. daemon_start = _process_start_time(daemon_pid)
  732. if daemon_alive:
  733. c = None
  734. try:
  735. c, token = ipc.connect(name, timeout=50.0 if require_clean else 5.0)
  736. response = ipc.request(c, token, {"meta": "shutdown"})
  737. if require_clean and (
  738. not isinstance(response, dict)
  739. or response.get("ok") is not True
  740. or bool(response.get("error"))
  741. ):
  742. error = response.get("error") if isinstance(response, dict) else None
  743. raise RuntimeError(error or f"daemon {name!r} did not confirm clean shutdown")
  744. except Exception as exc:
  745. if require_clean:
  746. if isinstance(exc, RuntimeError):
  747. raise
  748. raise RuntimeError(
  749. f"daemon {name!r} did not confirm clean shutdown: {exc}"
  750. ) from exc
  751. finally:
  752. if c is not None:
  753. close = getattr(c, "close", None)
  754. if close:
  755. close()
  756. if daemon_pid is not None:
  757. for _ in range(75):
  758. try:
  759. os.kill(daemon_pid, 0)
  760. time.sleep(0.2)
  761. except (ProcessLookupError, OSError, SystemError, OverflowError):
  762. break
  763. else:
  764. # Re-verify identity before escalating to SIGTERM. Two acceptable
  765. # signals, in priority order:
  766. # 1. ipc.identify() still returns the same PID — daemon's IPC is
  767. # live, daemon is wedged. Safe to kill.
  768. # 2. start-time fingerprint of the original PID is unchanged —
  769. # same process, just slow to exit (e.g. stuck in remote stop).
  770. # The IPC may already be gone; that's expected.
  771. # If neither holds, the PID may have been reused; skip SIGTERM.
  772. verified_pid = ipc.identify(name, timeout=1.0)
  773. same_process = verified_pid == daemon_pid or (
  774. daemon_start is not None
  775. and _process_start_time(daemon_pid) == daemon_start
  776. )
  777. if same_process:
  778. try:
  779. os.kill(daemon_pid, signal.SIGTERM)
  780. except (ProcessLookupError, OSError, SystemError, OverflowError):
  781. pass
  782. ipc.cleanup_endpoint(name)
  783. try:
  784. os.unlink(pid_path)
  785. except FileNotFoundError:
  786. pass
  787. def _browser_use(path, method, body=None):
  788. key = auth.get_browser_use_api_key()
  789. req = urllib.request.Request(
  790. f"{BU_API}{path}",
  791. method=method,
  792. data=(json.dumps(body).encode() if body is not None else None),
  793. headers={"X-Browser-Use-API-Key": key, "Content-Type": "application/json"},
  794. )
  795. return json.loads(urllib.request.urlopen(req, timeout=60).read() or b"{}")
  796. def _stop_cloud_browser(browser_id, strict=False):
  797. if not browser_id:
  798. return True
  799. last_error = None
  800. for attempt in range(3):
  801. try:
  802. _browser_use(f"/browsers/{browser_id}", "PATCH", {"action": "stop"})
  803. return True
  804. except BaseException as exc:
  805. last_error = exc
  806. if attempt < 2:
  807. time.sleep(0.5 * (attempt + 1))
  808. if strict:
  809. raise RuntimeError(f"failed to stop remote browser {browser_id}: {last_error}")
  810. return False
  811. def _cdp_ws_from_url(cdp_url):
  812. return json.loads(urllib.request.urlopen(f"{cdp_url}/json/version", timeout=15).read())["webSocketDebuggerUrl"]
  813. def _has_local_gui():
  814. """True when this machine plausibly has a browser we can open. False on headless servers."""
  815. import platform
  816. system = platform.system()
  817. if system in ("Darwin", "Windows"):
  818. return True
  819. if system == "Linux":
  820. return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
  821. return False
  822. def _show_live_url(url):
  823. """Print liveUrl and auto-open it locally if there's a GUI."""
  824. import sys, webbrowser
  825. if not url: return
  826. print(url)
  827. if not _has_local_gui():
  828. print("(no local GUI — share the liveUrl with the user)", file=sys.stderr)
  829. return
  830. try:
  831. webbrowser.open(url, new=2)
  832. print("(opened liveUrl in your default browser)", file=sys.stderr)
  833. except Exception as e:
  834. print(f"(couldn't auto-open: {e} — share the liveUrl with the user)", file=sys.stderr)
  835. def _should_show_remote_live_view():
  836. """Whether Cloud provisioning should print and open its interactive live view."""
  837. raw = os.environ.get("BH_OPEN_LIVE_URL")
  838. if raw is None:
  839. return True
  840. value = raw.strip().lower()
  841. if value in {"0", "false", "no", "off"}:
  842. return False
  843. if value in {"1", "true", "yes", "on"}:
  844. return True
  845. raise ValueError("BH_OPEN_LIVE_URL must be one of: 1, true, yes, on, 0, false, no, off")
  846. def list_cloud_profiles():
  847. """List cloud profiles under the current API key.
  848. Returns [{id, name, userId, cookieDomains, lastUsedAt}, ...]. `cookieDomains`
  849. is the array of domain strings the cloud profile has cookies for — use
  850. `len(cookieDomains)` as a cheap 'how much is logged in' summary. Per-cookie
  851. detail on a *local* profile before sync: `profile-use inspect --profile <name>`.
  852. Paginates through all pages — the API caps `pageSize` at 100."""
  853. out, page = [], 1
  854. while True:
  855. listing = _browser_use(f"/profiles?pageSize=100&pageNumber={page}", "GET")
  856. items = listing.get("items") if isinstance(listing, dict) else listing
  857. if not items:
  858. break
  859. for p in items:
  860. detail = _browser_use(f"/profiles/{p['id']}", "GET")
  861. out.append({
  862. "id": detail["id"],
  863. "name": detail.get("name"),
  864. "userId": detail.get("userId"),
  865. "cookieDomains": detail.get("cookieDomains") or [],
  866. "lastUsedAt": detail.get("lastUsedAt"),
  867. })
  868. if isinstance(listing, dict) and len(out) >= listing.get("totalItems", len(out)):
  869. break
  870. page += 1
  871. return out
  872. def _resolve_profile_name(profile_name):
  873. """Find a single cloud profile by exact name; raise if 0 or >1 match."""
  874. matches = [p for p in list_cloud_profiles() if p.get("name") == profile_name]
  875. if not matches:
  876. raise RuntimeError(f"no cloud profile named {profile_name!r} -- call list_cloud_profiles() or sync_local_profile() first")
  877. if len(matches) > 1:
  878. raise RuntimeError(f"{len(matches)} cloud profiles named {profile_name!r} -- pass profileId=<uuid> instead")
  879. return matches[0]["id"]
  880. def start_remote_daemon(name="remote", profileName=None, **create_kwargs):
  881. """Provision a Browser Use cloud browser and start a daemon attached to it.
  882. kwargs forwarded to `POST /browsers` (camelCase):
  883. profileId — cloud profile UUID; start already-logged-in. Default: none (clean browser).
  884. profileName — cloud profile name; resolved client-side to profileId via list_cloud_profiles().
  885. proxyCountryCode — ISO2 country code (default "us"); pass None to disable the BU proxy.
  886. timeout — minutes, 1..240.
  887. customProxy — {host, port, username, password, ignoreCertErrors}.
  888. browserScreenWidth / browserScreenHeight, allowResizing, enableRecording.
  889. Returns the full browser dict including `liveUrl`. By default, prints that
  890. URL and opens it locally when a GUI is detected. Set BH_OPEN_LIVE_URL to
  891. 0, false, no, or off (case-insensitive) to suppress only those display side
  892. effects; the returned URL remains present."""
  893. show_live_view = _should_show_remote_live_view()
  894. if daemon_alive(name):
  895. raise RuntimeError(f"daemon {name!r} already alive -- restart_daemon({name!r}) first")
  896. if profileName:
  897. if "profileId" in create_kwargs:
  898. raise RuntimeError("pass profileName OR profileId, not both")
  899. create_kwargs["profileId"] = _resolve_profile_name(profileName)
  900. browser = _browser_use("/browsers", "POST", create_kwargs)
  901. try:
  902. ensure_daemon(
  903. name=name,
  904. env={"BU_CDP_WS": _cdp_ws_from_url(browser["cdpUrl"]), "BU_BROWSER_ID": browser["id"]},
  905. )
  906. except BaseException as start_error:
  907. try:
  908. _stop_cloud_browser(browser.get("id"), strict=True)
  909. except BaseException as cleanup_error:
  910. raise BaseExceptionGroup(
  911. "remote daemon startup and cloud browser cleanup both failed",
  912. [start_error, cleanup_error],
  913. )
  914. raise
  915. if show_live_view:
  916. _show_live_url(browser.get("liveUrl"))
  917. return browser
  918. def list_local_profiles():
  919. """Detected local browser profiles on this machine. Shells out to `profile-use list --json`."""
  920. import json, shutil, subprocess
  921. if not shutil.which("profile-use"):
  922. raise RuntimeError("profile-use not installed -- curl -fsSL https://browser-use.com/profile.sh | sh")
  923. return json.loads(subprocess.check_output(["profile-use", "list", "--json"], text=True, encoding="utf-8", errors="replace"))
  924. def sync_local_profile(profile_name, browser=None, cloud_profile_id=None,
  925. include_domains=None, exclude_domains=None):
  926. """Sync a local profile's cookies to a cloud profile. Returns the cloud UUID.
  927. Shells out to `profile-use sync` (v1.0.5+). Requires BROWSER_USE_API_KEY.
  928. profile-use copies the profile dir to a temp and syncs from the copy, so Chrome
  929. can stay open.
  930. Args:
  931. profile_name: local Chrome profile name (as shown by `list_local_profiles`).
  932. browser: disambiguate when multiple browsers have profiles of the
  933. same name (e.g. "Google Chrome"). Default: any match.
  934. cloud_profile_id: push cookies into this existing cloud profile instead of
  935. creating a new one. Idempotent — call again to refresh
  936. the same profile. Default: create new.
  937. include_domains: only sync cookies for these domains (and subdomains).
  938. Leading dot is optional. Example: ["google.com", "stripe.com"].
  939. exclude_domains: drop cookies for these domains (and subdomains). Applied
  940. before `include_domains` so exclude wins on overlap."""
  941. import shutil, subprocess, sys
  942. if not shutil.which("profile-use"):
  943. raise RuntimeError("profile-use not installed -- curl -fsSL https://browser-use.com/profile.sh | sh")
  944. key = auth.get_browser_use_api_key()
  945. cmd = ["profile-use", "sync", "--profile", profile_name]
  946. if browser:
  947. cmd += ["--browser", browser]
  948. if cloud_profile_id:
  949. cmd += ["--cloud-profile-id", cloud_profile_id]
  950. for d in include_domains or []:
  951. cmd += ["--domain", d]
  952. for d in exclude_domains or []:
  953. cmd += ["--exclude-domain", d]
  954. r = subprocess.run(cmd, text=True, encoding="utf-8", errors="replace", capture_output=True, env={**os.environ, "BROWSER_USE_API_KEY": key})
  955. sys.stdout.write(r.stdout)
  956. sys.stderr.write(r.stderr)
  957. if r.returncode != 0:
  958. raise RuntimeError(f"profile-use sync failed (exit {r.returncode})")
  959. # With --cloud-profile-id the tool prints "♻️ Using existing cloud profile"
  960. # instead of "Profile created: <uuid>", so we already know the UUID.
  961. if cloud_profile_id:
  962. return cloud_profile_id
  963. m = re.search(r"Profile created:\s+([0-9a-f-]{36})", r.stdout)
  964. if not m:
  965. raise RuntimeError(f"profile-use did not report a profile UUID (exit {r.returncode})")
  966. return m.group(1)
  967. def _version():
  968. """Installed version of the browser-harness package. Empty string if unknown."""
  969. try:
  970. from importlib.metadata import PackageNotFoundError, version
  971. try:
  972. return version("browser-harness")
  973. except PackageNotFoundError:
  974. return ""
  975. except Exception:
  976. return ""
  977. def _repo_dir():
  978. """Return the repo root if this install is an editable git clone, else None.
  979. Only the directories that could actually hold this package as source count:
  980. the package's own parent (flat layout) and its grandparent (src layout).
  981. Walking all the way up would claim any enclosing repository — a wheel
  982. installed into a venv inside the user's project, or a tool install under a
  983. dotfiles-managed $HOME — and run_update() would then `git pull` that repo
  984. instead of upgrading browser-harness.
  985. """
  986. package = Path(__file__).resolve().parent
  987. for candidate in (package.parent, package.parent.parent):
  988. if (candidate / ".git").is_dir():
  989. return candidate
  990. return None
  991. def _install_mode():
  992. """"git" for editable clone, "pypi" for an installed wheel, "unknown" otherwise."""
  993. if _repo_dir():
  994. return "git"
  995. return "pypi" if _version() else "unknown"
  996. def _cache_read():
  997. try:
  998. return json.loads(VERSION_CACHE.read_text(encoding="utf-8"))
  999. except (OSError, ValueError):
  1000. return {}
  1001. def _cache_write(data):
  1002. try:
  1003. VERSION_CACHE.parent.mkdir(parents=True, exist_ok=True)
  1004. VERSION_CACHE.write_text(json.dumps(data))
  1005. try:
  1006. os.chmod(VERSION_CACHE, 0o600)
  1007. except OSError:
  1008. pass
  1009. except OSError:
  1010. pass
  1011. def _latest_release_tag(force=False):
  1012. """Return latest PyPI version, or None. Cached for 24h to avoid hammering PyPI."""
  1013. cache = _cache_read()
  1014. now = time.time()
  1015. if not force and cache.get("tag") and now - cache.get("fetched_at", 0) < VERSION_CACHE_TTL:
  1016. return cache["tag"]
  1017. try:
  1018. tag = json.loads(urllib.request.urlopen(PYPI_JSON, timeout=5).read()).get("info", {}).get("version") or ""
  1019. except Exception:
  1020. return cache.get("tag") # fall back to last known
  1021. tag = tag.lstrip("v")
  1022. _cache_write({**cache, "tag": tag, "fetched_at": now})
  1023. return tag or None
  1024. def _version_tuple(v):
  1025. """Best-effort PEP 440-ish parse: alpha < beta < rc < final."""
  1026. m = re.match(r"^\s*v?(\d+(?:\.\d+)*)(?:(a|b|rc)(\d+))?", v or "", re.I)
  1027. if not m:
  1028. return (0, 0, 0, 3, 0)
  1029. nums = [int(p) for p in m.group(1).split(".")[:3]]
  1030. nums.extend([0] * (3 - len(nums)))
  1031. pre = (m.group(2) or "").lower()
  1032. pre_rank = {"a": 0, "b": 1, "rc": 2}.get(pre, 3)
  1033. pre_num = int(m.group(3) or 0)
  1034. return (*nums, pre_rank, pre_num)
  1035. def check_for_update():
  1036. """(current, latest, newer_available). latest may be None if the API was unreachable and no cache exists."""
  1037. cur = _version()
  1038. latest = _latest_release_tag()
  1039. newer = bool(cur and latest and _version_tuple(latest) > _version_tuple(cur))
  1040. return cur, latest, newer
  1041. def print_update_banner(out=None):
  1042. """Print the update banner to stderr once per day. Silent when up-to-date or offline."""
  1043. import sys
  1044. if os.environ.get("BH_UPDATE_CHECK", "").strip().lower() in {"0", "false", "no", "off"}:
  1045. return
  1046. out = out or sys.stderr
  1047. cache = _cache_read()
  1048. today = time.strftime("%Y-%m-%d")
  1049. if cache.get("banner_shown_on") == today:
  1050. return
  1051. cur, latest, newer = check_for_update()
  1052. if not newer:
  1053. return
  1054. print(f"[browser-harness] update available: {cur} -> {latest}", file=out)
  1055. print(f"[browser-harness] agents: run `browser-harness --update -y` to upgrade and restart the daemon", file=out)
  1056. _cache_write({**cache, "banner_shown_on": today})
  1057. def _chrome_running():
  1058. """Cross-platform best-effort check for a running Chromium-based browser."""
  1059. import platform, subprocess
  1060. system = platform.system()
  1061. try:
  1062. if system == "Windows":
  1063. out = subprocess.check_output(["tasklist"], text=True, errors="replace", timeout=5)
  1064. names = ("chrome.exe", "msedge.exe", "helium.exe")
  1065. else:
  1066. out = subprocess.check_output(["ps", "-A", "-o", "comm="], text=True, errors="replace", timeout=5)
  1067. names = ("Google Chrome", "chrome", "chromium", "Microsoft Edge", "msedge", "helium")
  1068. return any(n.lower() in out.lower() for n in names)
  1069. except Exception:
  1070. return False
  1071. _BROWSER_LAUNCH = (
  1072. # (profile-dir fragment, macOS app name, POSIX commands, Windows `start` target)
  1073. ("chrome canary", "Google Chrome Canary", ("google-chrome-canary",), "chrome"),
  1074. ("chromium", "Chromium", ("chromium", "chromium-browser"), "chromium"),
  1075. ("chrome", "Google Chrome", ("google-chrome-stable", "google-chrome"), "chrome"),
  1076. ("edge", "Microsoft Edge", ("microsoft-edge", "microsoft-edge-stable"), "msedge"),
  1077. ("brave-origin", "Brave Origin", (), None),
  1078. ("brave", "Brave Browser", ("brave-browser", "brave"), "brave"),
  1079. ("arc", "Arc", (), None),
  1080. ("dia", "Dia", (), None),
  1081. ("comet", "Comet", (), None),
  1082. )
  1083. _DEFAULT_LAUNCH = (
  1084. "Google Chrome",
  1085. ("google-chrome-stable", "google-chrome", "chromium", "chromium-browser", "microsoft-edge"),
  1086. "chrome",
  1087. )
  1088. def _browser_launch_spec(base):
  1089. """(mac app, posix commands, windows target) for the browser w profile dir"""
  1090. tail = "/".join(p.lower() for p in Path(base).parts[-2:])
  1091. for frag, mac_app, posix_cmds, win_target in _BROWSER_LAUNCH:
  1092. if frag in tail:
  1093. return (mac_app, posix_cmds, win_target)
  1094. return _DEFAULT_LAUNCH
  1095. def _browser_binary_matches_profile(binary, base):
  1096. """True when an explicit browser binary belongs to ``base``."""
  1097. name = Path(binary).name.lower().removesuffix(".exe")
  1098. mac_app, posix_cmds, win_target = _browser_launch_spec(base)
  1099. candidates = (mac_app, *posix_cmds, win_target)
  1100. def normalize(value):
  1101. return "".join(char for char in (value or "").lower() if char.isalnum())
  1102. normalized_name = normalize(name)
  1103. return any(normalized_name == normalize(candidate) for candidate in candidates)
  1104. def _profile_directory_args(base):
  1105. """Relaunch skips Chrome's profile picker"""
  1106. if not base:
  1107. return []
  1108. try:
  1109. state = json.loads((Path(base) / "Local State").read_text(encoding="utf-8", errors="replace"))
  1110. last = ((state.get("profile") or {}).get("last_used")) or "Default"
  1111. except (OSError, ValueError, AttributeError):
  1112. last = "Default"
  1113. if not isinstance(last, str) or not (Path(base) / last).is_dir():
  1114. return []
  1115. return [f"--profile-directory={last}"]
  1116. def _launch_browser():
  1117. """Prefers the browser whose profile already has perm box checked.
  1118. Returns ``(process, profile)`` on success. ``process`` is available only
  1119. when we launched the browser directly; ``profile`` is the user-data dir we
  1120. expect that browser to use. The caller uses both to clean up a direct
  1121. launch that never becomes reachable over CDP.
  1122. """
  1123. import platform, shutil, subprocess
  1124. from .daemon import PROFILES, remote_debugging_toggle_profiles
  1125. enabled = remote_debugging_toggle_profiles()
  1126. known_profiles = enabled + [
  1127. base for base in PROFILES if base not in enabled and (base / "Local State").exists()
  1128. ]
  1129. system = platform.system()
  1130. for key in ("BH_CHROME_PATH", "CHROME_PATH"):
  1131. raw = (os.environ.get(key) or "").strip()
  1132. if raw and Path(raw).expanduser().is_file():
  1133. try:
  1134. binary = Path(raw).expanduser()
  1135. process = subprocess.Popen(
  1136. [str(binary)],
  1137. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **ipc.spawn_kwargs(),
  1138. )
  1139. profile = next(
  1140. (base for base in known_profiles if _browser_binary_matches_profile(binary, base)),
  1141. None,
  1142. ) if system not in ("Darwin", "Windows") else None
  1143. return process, profile
  1144. except (OSError, subprocess.SubprocessError):
  1145. # A path that exists but can't execute (permissions, wrong arch)
  1146. # must fall through to normal discovery, not abort
  1147. continue
  1148. base = enabled[0] if enabled else next((b for b in PROFILES if (b / "Local State").exists()), None)
  1149. mac_app, posix_cmds, win_target = _browser_launch_spec(base) if base else _DEFAULT_LAUNCH
  1150. profile_args = _profile_directory_args(base)
  1151. try:
  1152. if system == "Darwin":
  1153. cmd = ["open", "-a", mac_app] + (["--args"] + profile_args if profile_args else [])
  1154. r = subprocess.run(cmd, timeout=10, check=False, capture_output=True)
  1155. if r.returncode != 0 and mac_app != "Google Chrome":
  1156. # Different app → its profile dir may not match; launch plain
  1157. r = subprocess.run(["open", "-a", "Google Chrome"], timeout=10, check=False, capture_output=True)
  1158. return (None, base) if r.returncode == 0 else None
  1159. if system == "Windows":
  1160. # `start <name>` resolves browsers via App Paths without knowing the install dir
  1161. subprocess.Popen(["cmd", "/c", "start", "", win_target or "chrome"] + profile_args, **ipc.spawn_kwargs())
  1162. return None, base
  1163. for cmd in posix_cmds or _DEFAULT_LAUNCH[1]:
  1164. w = shutil.which(cmd)
  1165. if w:
  1166. process = subprocess.Popen(
  1167. [w] + profile_args,
  1168. stdout=subprocess.DEVNULL,
  1169. stderr=subprocess.DEVNULL,
  1170. **ipc.spawn_kwargs(),
  1171. )
  1172. return process, base
  1173. return None
  1174. except (OSError, subprocess.SubprocessError):
  1175. return None
  1176. def _cleanup_unattached_browser_launch(launch):
  1177. """Stop a browser we launched when the daemon attached somewhere else."""
  1178. if not launch:
  1179. return
  1180. process, profile = launch
  1181. if process is None or profile is None or process.poll() is not None:
  1182. return
  1183. from .daemon import _devtools_port_live
  1184. if _devtools_port_live(profile):
  1185. return
  1186. import signal
  1187. try:
  1188. if ipc.IS_WINDOWS:
  1189. process.terminate()
  1190. else:
  1191. os.killpg(process.pid, signal.SIGTERM)
  1192. except (OSError, subprocess.SubprocessError):
  1193. pass
  1194. def _open_chrome_inspect():
  1195. """Open chrome://inspect/#remote-debugging so the user can tick the checkbox."""
  1196. import platform, subprocess, webbrowser
  1197. url = "chrome://inspect/#remote-debugging"
  1198. if platform.system() == "Darwin":
  1199. try:
  1200. r = subprocess.run([
  1201. "osascript",
  1202. "-e", 'tell application "Google Chrome" to activate',
  1203. "-e", f'tell application "Google Chrome" to open location "{url}"',
  1204. ], timeout=5, check=False, capture_output=True)
  1205. if r.returncode == 0:
  1206. return True
  1207. except Exception:
  1208. pass
  1209. try:
  1210. return bool(webbrowser.open(url, new=2))
  1211. except Exception:
  1212. return False
  1213. INSPECT_REOPEN_TTL = 180.0 # seconds open new chrome://inspect tab
  1214. def _open_chrome_inspect_once():
  1215. """Open chrome://inspect at most once per INSPECT_REOPEN_TTL across invocations"""
  1216. marker = paths.inspect_marker()
  1217. try:
  1218. if time.time() - marker.stat().st_mtime < INSPECT_REOPEN_TTL:
  1219. return
  1220. except OSError:
  1221. pass
  1222. if not _open_chrome_inspect():
  1223. return
  1224. try:
  1225. marker.parent.mkdir(parents=True, exist_ok=True)
  1226. marker.touch()
  1227. except OSError:
  1228. pass
  1229. def run_doctor():
  1230. """Read-only diagnostics. Exit 0 iff everything looks healthy."""
  1231. import platform, sys
  1232. cur = _version()
  1233. mode = _install_mode()
  1234. chrome = _chrome_running()
  1235. daemon = daemon_alive()
  1236. connections = browser_connections()
  1237. try:
  1238. auth_state = auth.auth_status()
  1239. except (auth.AuthError, OSError) as e:
  1240. auth_state = {"status": "error", "source": None, "reason": str(e)}
  1241. cloud_auth = auth_state.get("status") == "authenticated"
  1242. latest = _latest_release_tag()
  1243. # Only claim an update when we know the installed version — `cur or "(unknown)"`
  1244. # for display would otherwise be parsed as (0,) and flag every latest as newer.
  1245. newer = bool(cur and latest and _version_tuple(latest) > _version_tuple(cur))
  1246. cur_display = cur or "(unknown)"
  1247. doc_url = _snap_linux_headless_doc_url()
  1248. def row(label, ok, detail=""):
  1249. mark = "ok " if ok else "FAIL"
  1250. print(f" [{mark}] {label}{(' — ' + detail) if detail else ''}")
  1251. print("browser-harness doctor")
  1252. print(f" platform {platform.system()} {platform.release()}")
  1253. print(f" python {sys.version.split()[0]}")
  1254. print(f" version {cur_display} ({mode})")
  1255. if latest:
  1256. print(f" latest release {latest}" + (" (update available)" if newer else ""))
  1257. else:
  1258. print(" latest release (could not reach PyPI)")
  1259. if platform.system() == "Linux":
  1260. bname, bpath = _doctor_probe_chrome_binary_for_snap()
  1261. if bname and bpath and _is_snap_browser(bpath):
  1262. print("[snap-detect]")
  1263. print(f"Browser: {bname} (snap) — WARNING: Snap confinement prevents CDP binding.")
  1264. print(f" Fix: Install Chrome natively (see docs/snap-linux-headless.md)")
  1265. print(f" Docs: {doc_url}")
  1266. row("chrome running", chrome, "" if chrome else "start chrome/edge")
  1267. row("daemon alive", daemon, "" if daemon else "see install.md")
  1268. row("active browser connections", bool(connections), str(len(connections)))
  1269. for conn in connections:
  1270. page = conn.get("page")
  1271. if page:
  1272. title = _doctor_short_text(page["title"])
  1273. url = _doctor_short_text(page["url"])
  1274. print(f" {conn['name']} — active page: {title} — {url}")
  1275. else:
  1276. print(f" {conn['name']} — active page: (no real page)")
  1277. row("Browser Use cloud auth", cloud_auth, auth_state.get("source") or auth_state.get("reason") or "optional: browser-harness auth login")
  1278. # Core health = chrome + daemon. Cloud auth is optional.
  1279. return 0 if (chrome and daemon) else 1
  1280. def run_doctor_json(require_existing_daemon=False):
  1281. """Print a stable, non-networked runtime health report as JSON.
  1282. The strict mode is intended for trusted orchestrators that provision an
  1283. exact named daemon. It checks only that selected daemon and its live CDP
  1284. connection; it never starts, repairs, or discovers another daemon.
  1285. """
  1286. strict = bool(require_existing_daemon)
  1287. chrome = None if strict else _chrome_running()
  1288. browser_ready = daemon_browser_ready(NAME)
  1289. daemon = browser_ready or daemon_alive(NAME)
  1290. healthy = (daemon and browser_ready) if strict else (browser_ready or (chrome and daemon))
  1291. report = {
  1292. "schema_version": 1,
  1293. "healthy": healthy,
  1294. "require_existing_daemon": strict,
  1295. "version": _version() or None,
  1296. "install_mode": _install_mode(),
  1297. "chrome_running": chrome,
  1298. "daemon": {
  1299. "name": NAME,
  1300. "alive": daemon,
  1301. "browser_ready": browser_ready,
  1302. },
  1303. }
  1304. print(json.dumps(report, sort_keys=True))
  1305. return 0 if healthy else 1
  1306. def _prompt_yes(question, default_yes=True, yes=False):
  1307. if yes:
  1308. return True
  1309. suffix = "[Y/n]" if default_yes else "[y/N]"
  1310. try:
  1311. ans = input(f"{question} {suffix} ").strip().lower()
  1312. except EOFError:
  1313. return default_yes
  1314. if not ans:
  1315. return default_yes
  1316. return ans.startswith("y")
  1317. def _uv_manages_browser_harness():
  1318. """True when `uv tool list` shows browser-harness, i.e. `uv tool upgrade` owns it.
  1319. Unknown counts as managed: if uv cannot be run or its output is unreadable we
  1320. stay quiet rather than tell a uv user to reinstall with pip.
  1321. """
  1322. try:
  1323. listed = subprocess.run(["uv", "tool", "list"], capture_output=True, text=True)
  1324. except OSError:
  1325. return True
  1326. if listed.returncode != 0:
  1327. return True
  1328. # `uv tool list` prints one "name vX.Y.Z" line per tool, then its executables as
  1329. # "- exe" lines. Match the entry name, so a tool merely containing our name (say
  1330. # my-browser-harness-wrapper) cannot silence the hint for a real pip install.
  1331. for line in (listed.stdout or "").splitlines():
  1332. entry = line.strip()
  1333. if entry.startswith("-"):
  1334. continue
  1335. if entry.split(" ", 1)[0] == "browser-harness":
  1336. return True
  1337. return False
  1338. def run_update(yes=False):
  1339. """Pull the latest version and (after prompt) restart the daemon so it picks up changed code.
  1340. Exit 0 on success, non-zero on failure."""
  1341. import subprocess, sys
  1342. cur, latest, newer = check_for_update()
  1343. # Only short-circuit as "up to date" when we actually know the installed
  1344. # version. Otherwise `newer=False` just means "couldn't compare" — proceed.
  1345. if cur and latest and not newer:
  1346. print(f"browser-harness is up to date ({cur}).")
  1347. return 0
  1348. if cur and latest:
  1349. print(f"updating browser-harness: {cur} -> {latest}")
  1350. elif latest:
  1351. print(f"installed version unknown; will try to update to {latest}.")
  1352. else:
  1353. print("could not reach PyPI; will try to update anyway.")
  1354. mode = _install_mode()
  1355. if mode == "git":
  1356. repo = _repo_dir()
  1357. status = subprocess.run(["git", "-C", str(repo), "status", "--porcelain"], capture_output=True, text=True)
  1358. if status.returncode != 0:
  1359. print(f"git status failed: {status.stderr.strip()}", file=sys.stderr)
  1360. return 1
  1361. if status.stdout.strip():
  1362. print(f"refusing to update: uncommitted changes in {repo}", file=sys.stderr)
  1363. print("commit or stash them first, or run `git -C %s pull` yourself." % repo, file=sys.stderr)
  1364. return 1
  1365. r = subprocess.run(["git", "-C", str(repo), "pull", "--ff-only"])
  1366. if r.returncode != 0:
  1367. return r.returncode
  1368. elif mode == "pypi":
  1369. tool_upgrade = subprocess.run(["uv", "tool", "upgrade", "browser-harness"])
  1370. if tool_upgrade.returncode != 0:
  1371. # `uv tool upgrade` only manages what `uv tool install` put there, so a pip
  1372. # or pipx install fails here with "`browser-harness` is not installed" and
  1373. # no way forward. Point only those users at the documented install: when the
  1374. # tool IS uv-managed the failure is uv's own (offline, auth) and its message
  1375. # already stands, so adding a pip hint there would just mislead.
  1376. if not _uv_manages_browser_harness():
  1377. print(
  1378. "if you installed with pip or pipx, upgrade with: "
  1379. "uv tool install --python 3.12 --upgrade --force browser-harness",
  1380. file=sys.stderr,
  1381. )
  1382. return tool_upgrade.returncode
  1383. else:
  1384. print("unknown install mode; can't auto-update.", file=sys.stderr)
  1385. return 1
  1386. # Invalidate banner/tag cache so the new version doesn't keep nagging.
  1387. cache = _cache_read()
  1388. cache.pop("banner_shown_on", None)
  1389. _cache_write(cache)
  1390. if daemon_alive():
  1391. if _prompt_yes("restart the running daemon so it picks up the new code?", default_yes=True, yes=yes):
  1392. restart_daemon()
  1393. print("daemon stopped; it will auto-restart on next `browser-harness` call.")
  1394. else:
  1395. print("daemon left running on old code. run `browser-harness` and it'll use the new code after the daemon recycles.")
  1396. print("update complete.")
  1397. return 0

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.