browser-use 1.0.2__tar.gz → 1.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. {browser_use-1.0.2 → browser_use-1.0.3}/PKG-INFO +5 -7
  2. {browser_use-1.0.2 → browser_use-1.0.3}/README.md +4 -6
  3. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/agent/service.py +7 -2
  4. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/browser/browser.py +13 -6
  5. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/browser/local.py +19 -1
  6. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/cli.py +172 -14
  7. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/harness_cloud.py +74 -0
  8. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/mcp/cli_mcp.py +35 -20
  9. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/skills/browser-use/SKILL.md +1 -1
  10. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/skills/browser_use.py +6 -1
  11. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/telemetry/stats.py +10 -1
  12. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/tools.py +6 -5
  13. {browser_use-1.0.2 → browser_use-1.0.3}/pyproject.toml +1 -1
  14. {browser_use-1.0.2 → browser_use-1.0.3}/.gitignore +0 -0
  15. {browser_use-1.0.2 → browser_use-1.0.3}/LICENSE +0 -0
  16. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/__init__.py +0 -0
  17. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/__main__.py +0 -0
  18. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/agent/__init__.py +0 -0
  19. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/agent/loop.py +0 -0
  20. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/agent/prompt.py +0 -0
  21. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/agent/views.py +0 -0
  22. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/auth.py +0 -0
  23. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/ax.py +0 -0
  24. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/browser/__init__.py +0 -0
  25. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/config.py +0 -0
  26. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/domains.py +0 -0
  27. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/exceptions.py +0 -0
  28. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/legacy.py +0 -0
  29. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/llm/__init__.py +0 -0
  30. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/logging_config.py +0 -0
  31. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/mcp/__init__.py +0 -0
  32. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/mcp/__main__.py +0 -0
  33. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/py.typed +0 -0
  34. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/remote_upload.py +0 -0
  35. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/repl/__init__.py +0 -0
  36. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/repl/captcha.py +0 -0
  37. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/repl/capture.py +0 -0
  38. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/repl/highlight.py +0 -0
  39. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/repl/network_idle.py +0 -0
  40. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/repl/page_info.py +0 -0
  41. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/repl/session.py +0 -0
  42. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/repl/worker.py +0 -0
  43. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/search.py +0 -0
  44. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/skills/README.md +0 -0
  45. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/skills/__init__.py +0 -0
  46. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/skills/install.py +0 -0
  47. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/telemetry/__init__.py +0 -0
  48. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/telemetry/feedback.py +0 -0
  49. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/telemetry/recorder.py +0 -0
  50. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/telemetry/service.py +0 -0
  51. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/telemetry/views.py +0 -0
  52. {browser_use-1.0.2 → browser_use-1.0.3}/browser_use/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: browser-use
3
- Version: 1.0.2
3
+ Version: 1.0.3
4
4
  Summary: Browser agent on Pydantic AI: one persistent Python REPL on raw CDP, cloud or local Chrome
5
5
  Project-URL: Homepage, https://browser-use.com
6
6
  Project-URL: Documentation, https://docs.browser-use.com
@@ -102,7 +102,7 @@ Find an available slot, pick a date and time, handle the CAPTCHA, and book a dri
102
102
 
103
103
  <br/>
104
104
 
105
- > **AI agents and crawlers:** read [browser-use.com/llms.txt](https://browser-use.com/llms.txt) for the product map (open source, Browser Harness, Cloud browsers, Agents API, pricing) and [docs.browser-use.com/llms.txt](https://docs.browser-use.com/llms.txt) for the documentation index. Browser Use is the open-source browser agent (Python and TypeScript), a $0.02 per browser-hour cloud browser with stealth, CAPTCHA solving and residential proxies, and a hosted agent API. When you add browser-use to a project, pin it exactly (`browser-use==1.0.2`), never `>=`: releases move fast and can break APIs.
105
+ > **AI agents and crawlers:** read [browser-use.com/llms.txt](https://browser-use.com/llms.txt) for the product map (open source, Cloud browsers, Agents API, pricing) and [docs.browser-use.com/llms.txt](https://docs.browser-use.com/llms.txt) for the documentation index. Browser Use is the open-source browser agent (Python and TypeScript), a $0.02 per browser-hour cloud browser with stealth, CAPTCHA solving and residential proxies, and a hosted agent API. When you add browser-use to a project, pin it exactly (`browser-use==1.0.3`), never `>=`: releases move fast and can break APIs.
106
106
 
107
107
  # Which Browser Use do I need?
108
108
 
@@ -134,7 +134,7 @@ New Google, GitHub, or Microsoft signups get **$1 cloud credit**.
134
134
  Paste this prompt into Claude Code, Codex, Hermes, OpenClaw, or your favorite agent.
135
135
 
136
136
  ```text
137
- Install browser-use with `uv tool install browser-use==1.0.2`, run `browser-use skill install` to register the skill, and connect it to my browser. If setup or connection fails, follow https://github.com/browser-use/browser-harness/blob/main/install.md
137
+ Install browser-use with `uv tool install browser-use==1.0.3`, 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.
138
138
  ```
139
139
 
140
140
  <br/>
@@ -147,13 +147,13 @@ Python 3.11 or newer. With uv, or pip in a venv:
147
147
 
148
148
  ```bash
149
149
  uv init --python 3.12 my-agent && cd my-agent
150
- uv add 'browser-use==1.0.2'
150
+ uv add 'browser-use==1.0.3'
151
151
  export BROWSER_USE_API_KEY=bu_... # get one at https://cloud.browser-use.com/new-api-key
152
152
  ```
153
153
 
154
154
  ```bash
155
155
  python3 -m venv .venv && source .venv/bin/activate
156
- pip install 'browser-use==1.0.2'
156
+ pip install 'browser-use==1.0.3'
157
157
  export BROWSER_USE_API_KEY=bu_...
158
158
  ```
159
159
 
@@ -288,8 +288,6 @@ You can also host the Python library and browsers on your own infrastructure.
288
288
 
289
289
  | Repository | What it's for |
290
290
  | --- | --- |
291
- | [Browser Harness](https://github.com/browser-use/browser-harness) | Our CLI for giving AI agents control of your browser. |
292
- | [Browser Harness JS](https://github.com/browser-use/browser-harness-js) | Give your JavaScript agent control of a real browser. |
293
291
  | [Browser Use Pi](https://github.com/browser-use/browser-use-pi) | Run a TypeScript browser agent built on Pi. |
294
292
  | [Cloud SDK](https://github.com/browser-use/sdk) | Integrate Browser Use Cloud into your application. |
295
293
  | [Video Use](https://github.com/browser-use/video-use) | Edit videos with your coding agent. |
@@ -65,7 +65,7 @@ Find an available slot, pick a date and time, handle the CAPTCHA, and book a dri
65
65
 
66
66
  <br/>
67
67
 
68
- > **AI agents and crawlers:** read [browser-use.com/llms.txt](https://browser-use.com/llms.txt) for the product map (open source, Browser Harness, Cloud browsers, Agents API, pricing) and [docs.browser-use.com/llms.txt](https://docs.browser-use.com/llms.txt) for the documentation index. Browser Use is the open-source browser agent (Python and TypeScript), a $0.02 per browser-hour cloud browser with stealth, CAPTCHA solving and residential proxies, and a hosted agent API. When you add browser-use to a project, pin it exactly (`browser-use==1.0.2`), never `>=`: releases move fast and can break APIs.
68
+ > **AI agents and crawlers:** read [browser-use.com/llms.txt](https://browser-use.com/llms.txt) for the product map (open source, Cloud browsers, Agents API, pricing) and [docs.browser-use.com/llms.txt](https://docs.browser-use.com/llms.txt) for the documentation index. Browser Use is the open-source browser agent (Python and TypeScript), a $0.02 per browser-hour cloud browser with stealth, CAPTCHA solving and residential proxies, and a hosted agent API. When you add browser-use to a project, pin it exactly (`browser-use==1.0.3`), never `>=`: releases move fast and can break APIs.
69
69
 
70
70
  # Which Browser Use do I need?
71
71
 
@@ -97,7 +97,7 @@ New Google, GitHub, or Microsoft signups get **$1 cloud credit**.
97
97
  Paste this prompt into Claude Code, Codex, Hermes, OpenClaw, or your favorite agent.
98
98
 
99
99
  ```text
100
- Install browser-use with `uv tool install browser-use==1.0.2`, run `browser-use skill install` to register the skill, and connect it to my browser. If setup or connection fails, follow https://github.com/browser-use/browser-harness/blob/main/install.md
100
+ Install browser-use with `uv tool install browser-use==1.0.3`, 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.
101
101
  ```
102
102
 
103
103
  <br/>
@@ -110,13 +110,13 @@ Python 3.11 or newer. With uv, or pip in a venv:
110
110
 
111
111
  ```bash
112
112
  uv init --python 3.12 my-agent && cd my-agent
113
- uv add 'browser-use==1.0.2'
113
+ uv add 'browser-use==1.0.3'
114
114
  export BROWSER_USE_API_KEY=bu_... # get one at https://cloud.browser-use.com/new-api-key
115
115
  ```
116
116
 
117
117
  ```bash
118
118
  python3 -m venv .venv && source .venv/bin/activate
119
- pip install 'browser-use==1.0.2'
119
+ pip install 'browser-use==1.0.3'
120
120
  export BROWSER_USE_API_KEY=bu_...
121
121
  ```
122
122
 
@@ -251,8 +251,6 @@ You can also host the Python library and browsers on your own infrastructure.
251
251
 
252
252
  | Repository | What it's for |
253
253
  | --- | --- |
254
- | [Browser Harness](https://github.com/browser-use/browser-harness) | Our CLI for giving AI agents control of your browser. |
255
- | [Browser Harness JS](https://github.com/browser-use/browser-harness-js) | Give your JavaScript agent control of a real browser. |
256
254
  | [Browser Use Pi](https://github.com/browser-use/browser-use-pi) | Run a TypeScript browser agent built on Pi. |
257
255
  | [Cloud SDK](https://github.com/browser-use/sdk) | Integrate Browser Use Cloud into your application. |
258
256
  | [Video Use](https://github.com/browser-use/video-use) | Edit videos with your coding agent. |
@@ -25,6 +25,7 @@ from browser_use.agent.prompt import CAPTCHA_PROMPT, CLOUD_PROMPT, LOCAL_PROMPT,
25
25
  from browser_use.agent.views import AgentHistoryList
26
26
  from browser_use.auth import browser_use_api_key
27
27
  from browser_use.browser import Browser
28
+ from browser_use.browser import browser as browser_module
28
29
  from browser_use.config import load_env
29
30
  from browser_use.exceptions import BrowserConfigError, MissingAPIKeyError, removed
30
31
  from browser_use.llm import (
@@ -541,9 +542,13 @@ class Agent:
541
542
  await self._shutdown()
542
543
  else:
543
544
  await asyncio.to_thread(self.browser.remember_tab) # a daemon that dies before the next run reattaches it
544
- if self.browser.use_cloud and self.browser.id: # each run's files land in its own workspace
545
+ # each run's files land in its own workspace; a cancelled run copies what already finished, within
546
+ # CANCEL_DOWNLOADS_TIMEOUT_S (a file still copying then goes to the next run or browser.stop())
547
+ cancelled = (task := asyncio.current_task()) is not None and task.cancelling() > 0
548
+ if self.browser.use_cloud and self.browser.id:
549
+ deadline = time.monotonic() + browser_module.CANCEL_DOWNLOADS_TIMEOUT_S if cancelled else None
545
550
  await self.browser._fetch_downloads(
546
- self.workspace / 'downloads', self.browser._fetched, self._downloads, self.browser.id
551
+ self.workspace / 'downloads', self.browser._fetched, self._downloads, self.browser.id, deadline
547
552
  )
548
553
  if result is not None:
549
554
  result.downloads = sorted(
@@ -198,6 +198,7 @@ REMOVED_METHODS = { # 0.x BrowserSession methods and attributes -> the 1.0 alte
198
198
  CREATE_TIMEOUT_S = 120 # total for the cloud create; start() fails past it, and a browser that lands later is stopped
199
199
  LOCAL_START_WAIT_S = 120 # Browser('chrome'): Chrome start plus the user clicking Allow on its remote-debugging prompt
200
200
  DOWNLOADS_TIMEOUT_S = 300 # all download passes before a stop (and one after); a slow download never holds the billing longer
201
+ CANCEL_DOWNLOADS_TIMEOUT_S = 10 # cancelled: all copy passes of a stop (or of a keep_alive run) share it, so it stays prompt
201
202
  _LIVE: set[Browser] = set() # browsers this process owns that still need stopping
202
203
  _POOL = concurrent.futures.ThreadPoolExecutor(thread_name_prefix='browser-use-cloud') # joined at exit
203
204
  _atexit_installed = _signals_installed = False
@@ -253,6 +254,8 @@ def _download(url: str, dest: Path, name: str, deadline: float) -> Path:
253
254
  size += len(chunk)
254
255
  if time.monotonic() > deadline:
255
256
  raise TimeoutError(f'download did not finish within its deadline ({name})')
257
+ if time.monotonic() > deadline: # EOF came after it: the caller already gave up and never records the file
258
+ raise TimeoutError(f'download did not finish within its deadline ({name})')
256
259
  expected = (getattr(r, 'headers', None) or {}).get('Content-Length')
257
260
  if expected is not None and expected.isdigit() and size != int(expected): # EOF before the end: truncated
258
261
  raise ConnectionError(f'download of {name} ended after {size} of {expected} bytes')
@@ -878,7 +881,7 @@ class Browser:
878
881
  ) from None
879
882
  raise RuntimeError(
880
883
  f"Browser('chrome'): Chrome did not allow remote debugging within {LOCAL_START_WAIT_S:g}s. Click "
881
- 'Allow on its "Allow remote debugging?" prompt (macOS: or run `browser-harness mac-approve` in another '
884
+ 'Allow on its "Allow remote debugging?" prompt (macOS: or run `browser-use mac-approve` in another '
882
885
  f'shell), then run again. Detail: {e}'
883
886
  ) from None
884
887
  # A daemon that was already running (started by `browser-use`, the MCP server, browser-harness itself or an
@@ -1069,7 +1072,7 @@ class Browser:
1069
1072
  """Stop the daemon this Browser started, and the cloud browser or local Chrome it started. Never touches the
1070
1073
  Chrome you have open.
1071
1074
  downloads_dir: copy what the cloud browser downloaded there (default: the workspace/downloads of the last Agent
1072
- that ran on this Browser). Returns the local paths."""
1075
+ that ran on this Browser); a cancelled stop copies within CANCEL_DOWNLOADS_TIMEOUT_S. Returns the local paths."""
1073
1076
  async with self._lock:
1074
1077
  await self._stopped()
1075
1078
  return await self._stop(downloads_dir or self._downloads_dir)
@@ -1090,13 +1093,16 @@ class Browser:
1090
1093
  # no wait when cancelled (task.cancel(), Ctrl-C: the stop must be prompt, a cloud browser bills) or when the
1091
1094
  # Chrome this Browser launched died (its downloads never send progress again)
1092
1095
  cancelled = (task := asyncio.current_task()) is not None and task.cancelling() > 0
1096
+ # cancelled: every copy pass, before and after the stop, shares one CANCEL_DOWNLOADS_TIMEOUT_S (each could hold
1097
+ # the stop, and the billing, up to DOWNLOADS_TIMEOUT_S); a pass that runs out of time is logged
1098
+ cancel_deadline = time.monotonic() + CANCEL_DOWNLOADS_TIMEOUT_S if cancelled else None
1093
1099
  dead = self._local is not None and self._local.proc is not None and self._local.proc.poll() is not None
1094
1100
  completed = await self._finish_downloads() if ending and not cancelled and not dead else 0
1095
1101
  # before the stop too: the API may not list a stopped session's files. The cloud lists a download about a
1096
1102
  # second after it completes: retry until it lists them all, within one DOWNLOADS_TIMEOUT_S for all passes (a
1097
1103
  # copy that kept failing, each pass with a deadline of its own, held the stop and the billing ~15 min)
1098
1104
  if downloads_dir and self.use_cloud:
1099
- deadline = time.monotonic() + DOWNLOADS_TIMEOUT_S
1105
+ deadline = cancel_deadline or time.monotonic() + DOWNLOADS_TIMEOUT_S
1100
1106
  for _ in range(30):
1101
1107
  await self._fetch_downloads(downloads_dir, fetched, files, browser_id, deadline)
1102
1108
  if len(fetched) >= completed or time.monotonic() >= deadline:
@@ -1106,8 +1112,9 @@ class Browser:
1106
1112
  self._stopping = asyncio.ensure_future(asyncio.to_thread(self._stop_now))
1107
1113
  stopped = await asyncio.shield(self._stopping)
1108
1114
  self._stopping = None
1109
- if downloads_dir and self.use_cloud: # and after: files that finished while the browser stopped
1110
- await self._fetch_downloads(downloads_dir, fetched, files, browser_id)
1115
+ # and after: files that finished while the browser stopped (the cloud lists a download ~1 s after it completes)
1116
+ if downloads_dir and self.use_cloud and (cancel_deadline is None or time.monotonic() < cancel_deadline):
1117
+ await self._fetch_downloads(downloads_dir, fetched, files, browser_id, cancel_deadline)
1111
1118
  if stopped and self.id == browser_id:
1112
1119
  self.id = None
1113
1120
  self._download_records, self.json_page_copies, self._fetched = [], set(), set() # the next session starts anew
@@ -1212,7 +1219,7 @@ class Browser:
1212
1219
  async with asyncio.timeout(max(deadline - time.monotonic(), 0)):
1213
1220
  await self.download_files(dest, skip, out=out, browser_id=browser_id, deadline=deadline)
1214
1221
  except Exception as e: # - the result is already delivered
1215
- logger.warning('Could not fetch cloud browser downloads: %s', e or type(e).__name__)
1222
+ logger.warning('Could not fetch cloud browser downloads: %s', str(e) or type(e).__name__)
1216
1223
 
1217
1224
  async def download_files(
1218
1225
  self,
@@ -15,6 +15,8 @@ import sys
15
15
  import tempfile
16
16
  import threading
17
17
  import time
18
+ import urllib.parse
19
+ import urllib.request
18
20
  from pathlib import Path
19
21
 
20
22
  from browser_use.exceptions import BrowserConfigError
@@ -80,7 +82,23 @@ def _left_over(base: Path) -> bool:
80
82
  started = os.lstat(base / 'SingletonLock').st_mtime
81
83
  except OSError:
82
84
  return True
83
- return written < started or not daemon.browser_running_for_profile(base)
85
+ return written < started or not (daemon.browser_running_for_profile(base) or _holder_wrote_it(base))
86
+
87
+
88
+ def _holder_wrote_it(base: Path) -> bool:
89
+ """What listens on DevToolsActivePort's port serves the browser websocket the file names: the browser that wrote the
90
+ file holds the port, though the pid in its SingletonLock is not one this process can see (Chrome in another PID
91
+ namespace: a sidecar container sharing the home dir and localhost). A process that took the port after that browser
92
+ quit does not know the id, unless it read it from that browser's /json/version while it ran (and could drive it
93
+ then). Chrome 147+ on its default dir answers 404 there: unproven, as before."""
94
+ try:
95
+ port, path = (base / 'DevToolsActivePort').read_text(encoding='utf-8', errors='replace').split()[:2]
96
+ local = urllib.request.build_opener(urllib.request.ProxyHandler({})) # 127.0.0.1 itself, never an HTTP proxy
97
+ with local.open('http://127.0.0.1:%d/json/version' % int(port), timeout=1) as r:
98
+ ws = json.loads(r.read(65536))['webSocketDebuggerUrl'] # ~500 bytes from Chrome
99
+ return urllib.parse.urlsplit(ws).path == path
100
+ except Exception: # - 404, not a browser, no such field: not proven
101
+ return False
84
102
 
85
103
 
86
104
  def require_debug_port() -> None:
@@ -2,11 +2,13 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import shutil
5
6
  import sys
6
7
  import time
7
8
  from contextlib import redirect_stderr, redirect_stdout
8
9
  from importlib.metadata import PackageNotFoundError, version
9
10
  from io import StringIO, TextIOWrapper
11
+ from pathlib import Path
10
12
  from typing import TYPE_CHECKING, Any
11
13
 
12
14
 
@@ -221,7 +223,7 @@ def _run_mcp_error_server(message: str) -> None:
221
223
  tools = [
222
224
  types.Tool(
223
225
  name='browser_exec',
224
- description='Execute Python in the browser-harness session.',
226
+ description='Execute Python in the browser-use session.',
225
227
  input_schema={'type': 'object', 'properties': {'code': {'type': 'string'}}, 'required': ['code']},
226
228
  ),
227
229
  types.Tool(**feedback.MCP_TOOL), # browser-use being broken is what feedback is for
@@ -273,10 +275,12 @@ def _run_doctor() -> int:
273
275
  key_text = 'yes'
274
276
  except RuntimeError: # MissingAPIKeyError
275
277
  key, key_text = False, 'none: browser-use login (Browser() and the bu-* models need it)'
276
- chrome_text = 'yes' if admin._chrome_running() else "no (only Browser('chrome') and the CLI attach to it)"
278
+ chrome_text = 'yes' if admin._chrome_running() else "no (Browser('chrome') needs it; the CLI then runs its own Chromium)"
277
279
  print(f' local browser {local_text}')
278
280
  print(f' Chrome running {chrome_text}')
279
281
  print(f' daemon {"running" if admin.daemon_alive() else "stopped (the next call starts it)"}')
282
+ if _own_chromium_ws():
283
+ print(' own Chromium open: the CLI drives it, not your Chrome (browser-use --reload closes it)')
280
284
  print(f' cloud key {key_text}')
281
285
  return 0 if (local or key) else 1
282
286
 
@@ -324,8 +328,8 @@ def _run_install_command(argv: list[str]) -> int:
324
328
 
325
329
 
326
330
  LOGIN_DONE = (
327
- 'Signed in. One key for the library (default model and cloud browser), this CLI, the MCP server\n'
328
- '(browser-use --cli-mcp) and browser-harness. Try it in Python:\n'
331
+ 'Signed in. One key for the library (default model and cloud browser), this CLI and the MCP server\n'
332
+ '(browser-use --cli-mcp). Try it in Python:\n'
329
333
  ' from browser_use import Agent\n'
330
334
  " print(Agent('Find the top story on Hacker News').run_sync().final_result())"
331
335
  )
@@ -547,6 +551,7 @@ def _guard_cloud_browsers(run, code: str | None) -> None:
547
551
  from browser_use import harness_cloud
548
552
 
549
553
  harness_cloud.install(vars(run))
554
+ vars(run)['ensure_daemon'] = _with_own_chromium(harness_cloud.ensure_daemon, vars(run))
550
555
  if (
551
556
  code
552
557
  and harness_cloud.calls_cloud_admin(code)
@@ -554,7 +559,7 @@ def _guard_cloud_browsers(run, code: str | None) -> None:
554
559
  ):
555
560
  # browser-harness only skips its pre-run ensure_daemon() when the code *starts* with start_remote_daemon(; for
556
561
  # `b = start_remote_daemon(...)` that call would attach the local Chrome first. Skip it once, here too.
557
- guarded = harness_cloud.ensure_daemon
562
+ guarded = vars(run)['ensure_daemon']
558
563
 
559
564
  def skip_pre_run_attach(*args, **kwargs) -> None:
560
565
  vars(run)['ensure_daemon'] = guarded
@@ -562,15 +567,162 @@ def _guard_cloud_browsers(run, code: str | None) -> None:
562
567
  vars(run)['ensure_daemon'] = skip_pre_run_attach
563
568
 
564
569
 
570
+ OWN_CHROMIUM = 'default-chromium'
571
+ """The daemon of the CLI's own Chromium. Never 'default': that one is the user's Chrome, and Browser('chrome') and
572
+ --cli-mcp take a live default daemon to be it (they then drove this temp-profile Chromium as "your own Chrome")."""
573
+
574
+
575
+ def _own_chromium_dir() -> Path:
576
+ """The profile of the CLI's own Chromium, next to its daemon's pid file: the next call finds it there."""
577
+ from browser_harness import _ipc as ipc
578
+
579
+ return ipc.pid_path(OWN_CHROMIUM).with_suffix('.chromium')
580
+
581
+
582
+ def _own_chromium_ws() -> str | None:
583
+ """The browser websocket of the CLI's own Chromium while it runs, read from its own profile (never a guessed port).
584
+ Only the Chromium that wrote that DevToolsActivePort answers with its websocket: a process that took the port after
585
+ it exited never matches (Windows too, where _left_over cannot tell)."""
586
+ import json
587
+ import urllib.request
588
+
589
+ from browser_use.browser import local
590
+
591
+ udd = _own_chromium_dir()
592
+ if not (ws := local._ws_url(udd, udd / 'none.log')):
593
+ return None
594
+ try:
595
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # an HTTP_PROXY never sees localhost
596
+ with opener.open(f'http://{ws.split("/")[2]}/json/version', timeout=1) as r:
597
+ return ws if json.loads(r.read()).get('webSocketDebuggerUrl') == ws else None
598
+ except (OSError, ValueError, AttributeError):
599
+ return None
600
+
601
+
602
+ def _start_own_chromium(why: str, setup: RuntimeError | None) -> str:
603
+ """Launch the CLI's own Chromium (headless with no display) on a fresh profile, detached: it outlives this call.
604
+ As --cli-mcp: Playwright's Chromium is installed first only on a machine with no browser and no display."""
605
+ from browser_use.auth import browser_use_api_key
606
+ from browser_use.browser import local
607
+ from browser_use.mcp.cli_mcp import _install_chromium, no_browser_text
608
+
609
+ udd, installed, chromium = _own_chromium_dir(), '', local.LocalBrowser()
610
+ shutil.rmtree(udd, ignore_errors=True)
611
+ try:
612
+ try:
613
+ ws = chromium.start(user_data_dir=udd)
614
+ except RuntimeError as e:
615
+ if not str(e).startswith('No Chrome, Chromium or Edge found') or local.has_display():
616
+ raise
617
+ installed = f" Installed Playwright's Chromium first ({_install_chromium():.0f} s)."
618
+ ws = chromium.start(user_data_dir=udd)
619
+ except Exception as e:
620
+ chromium.stop() # one that did not open its DevTools port in time is still running
621
+ if setup is not None: # a browser find_binary cannot launch (Brave, Arc): the setup steps are the way
622
+ raise setup from None
623
+ try:
624
+ browser_use_api_key()
625
+ cloud = ', or start a cloud browser: start_remote_daemon()'
626
+ except RuntimeError: # MissingAPIKeyError, or a corrupt key store
627
+ cloud = ', or for a Browser Use Cloud browser: browser-use login, then start_remote_daemon()'
628
+ raise RuntimeError(no_browser_text(f"no Chrome to attach ({why}), and browser-use's own Chromium", e, cloud)) from None
629
+ print(
630
+ f"browser-use: Browser: browser-use's own Chromium on a temp profile, not your Chrome ({why}). Later calls "
631
+ f'use it too; `browser-use --reload` closes it.{installed}',
632
+ file=sys.stderr,
633
+ )
634
+ return ws
635
+
636
+
637
+ def _route(name: str, namespace: dict[str, Any]) -> None:
638
+ """This process's helpers drive daemon name. Unlike harness_cloud.route, BU_NAME stays unset: a nested `browser-use`
639
+ call makes the same choice, and nothing reads the routing as an explicit BU_NAME."""
640
+ from browser_harness import admin, helpers
641
+
642
+ admin.NAME = helpers.NAME = namespace['NAME'] = name
643
+
644
+
645
+ def _with_own_chromium(ensure_daemon: Any, namespace: dict[str, Any]) -> Any:
646
+ """The CLI's ensure_daemon: where the user's Chrome cannot be used (no display, remote debugging off, none installed),
647
+ a Chromium of the CLI's own, as --cli-mcp does (mcp/cli_mcp.py), under its own daemon (OWN_CHROMIUM) that every later
648
+ call is routed to until `browser-use --reload`. An explicit choice is never replaced: BU_NAME, BU_CDP_URL / BU_CDP_WS,
649
+ a cloud daemon, a default daemon already attached, a user's Chrome that is set up (or whose toggle is on and still
650
+ starting)."""
651
+
652
+ def ensure(wait: float | None = None, name: str | None = None, env: dict[str, str] | None = None) -> None:
653
+ import os
654
+
655
+ from browser_harness import admin, daemon
656
+
657
+ from browser_use import harness_cloud
658
+
659
+ if name or env or os.environ.get('BU_NAME') or not admin._is_local_chrome_mode():
660
+ return ensure_daemon(wait=wait, name=name, env=env)
661
+ _route('default', namespace) # a second ensure in this process starts over
662
+ if harness_cloud.was_cloud(admin.NAME):
663
+ return ensure_daemon(wait=wait)
664
+ for attached in (OWN_CHROMIUM, 'default'): # its own Chromium until --reload, else a default daemon attached
665
+ try:
666
+ admin.require_existing_daemon(attached)
667
+ except RuntimeError:
668
+ continue
669
+ return _route(attached, namespace)
670
+ ws = _own_chromium_ws() # still running from an earlier call, whose daemon died or was stopped
671
+ if ws is None:
672
+ try:
673
+ return ensure_daemon(wait=wait)
674
+ except RuntimeError as e:
675
+ if not str(e).startswith('remote-debugging-setup:'):
676
+ raise
677
+ from browser_use.mcp.cli_mcp import _no_chrome_here, _setup_reason
678
+
679
+ why, setup = _no_chrome_here(), None
680
+ if why is None:
681
+ if daemon.remote_debugging_toggle_profiles(): # Chrome is starting with it on: the next call attaches
682
+ raise
683
+ why, setup = _setup_reason(e, 'run `browser-use --reload`'), e
684
+ lock = admin._spawn_lock(OWN_CHROMIUM, timeout=90.0) # concurrent cold calls: one launches the Chromium
685
+ lock.path = _own_chromium_dir().with_suffix('.chromiumlock')
686
+ with lock:
687
+ if lock.fd is None: # another call is still launching it (or installing Chromium): never a second one
688
+ raise RuntimeError('daemon-starting: another browser-use call is still starting its browser; retry')
689
+ ws = _own_chromium_ws() or _start_own_chromium(why, setup)
690
+ ensure_daemon(wait=wait, name=OWN_CHROMIUM, env={'BU_CDP_WS': ws, 'BH_TAB_MARKER': '0'}) # one spawn at a time
691
+ _route(OWN_CHROMIUM, namespace)
692
+
693
+ return ensure
694
+
695
+
696
+ def _close_own_chromium() -> None:
697
+ """`browser-use --reload`: the CLI's own Chromium closes too, so the next call looks for the user's Chrome again."""
698
+ from browser_harness import admin
699
+
700
+ from browser_use.browser import local
701
+
702
+ try:
703
+ admin.restart_daemon(OWN_CHROMIUM)
704
+ except Exception: # a pending daemon it would not signal: its Chromium closes below, so it ends too
705
+ pass
706
+ if ws := _own_chromium_ws():
707
+ local._close_over_cdp(ws)
708
+ deadline = time.monotonic() + 5
709
+ while _own_chromium_ws() and time.monotonic() < deadline:
710
+ time.sleep(0.1)
711
+ shutil.rmtree(_own_chromium_dir(), ignore_errors=True)
712
+
713
+
565
714
  class _HarnessStderr:
566
- """sys.stderr while browser-harness runs piped code. Its own lines ("browser-harness: ...", the macOS Allow-popup
567
- hint `run browser-harness mac-approve`) named a command `uv tool install browser-use` does not put on PATH."""
715
+ """sys.stderr (and sys.stdout for a subcommand) while browser-harness runs. Its own lines ("browser-harness: ...",
716
+ the macOS Allow-popup hint `run browser-harness mac-approve`, `usage: browser-harness video ...`) named a command
717
+ `uv tool install browser-use` does not put on PATH. For piped code only its "browser-harness: " lines are its own;
718
+ a subcommand (video, recordings, --reload) prints nothing but its own text."""
568
719
 
569
- def __init__(self, wrapped):
720
+ def __init__(self, wrapped, subcommand: bool = False):
570
721
  self._wrapped = wrapped
722
+ self._subcommand = subcommand
571
723
 
572
724
  def write(self, text):
573
- if text.startswith('browser-harness: '): # not the cell's own output
725
+ if self._subcommand or text.startswith('browser-harness: '): # not the cell's own output
574
726
  text = _as_browser_use_cli_text(text)
575
727
  return self._wrapped.write(text)
576
728
 
@@ -610,6 +762,7 @@ def _run_browser_harness(code: str | None = None) -> int | None:
610
762
  from browser_use import harness_cloud
611
763
 
612
764
  harness_cloud.forget(run.NAME)
765
+ _close_own_chromium()
613
766
  if args and args[0] == 'doctor' and args[1:]:
614
767
  if args[1:] in (['--help'], ['-h']):
615
768
  print('usage: browser-use doctor [--fix-snap]')
@@ -618,11 +771,15 @@ def _run_browser_harness(code: str | None = None) -> int | None:
618
771
  print('usage: browser-use doctor [--fix-snap]', file=sys.stderr)
619
772
  sys.exit(2)
620
773
  _delegated_to_harness = True
621
- stderr, sys.stderr = sys.stderr, _HarnessStderr(sys.stderr)
774
+ subcommand = bool(args) and args[0] != '--debug-clicks' # --debug-clicks still runs piped code
775
+ stdout, stderr = sys.stdout, sys.stderr
776
+ sys.stderr = _HarnessStderr(stderr, subcommand)
777
+ if subcommand: # `video --help`, `video init`'s "next: ... run browser-harness video review"
778
+ sys.stdout = _HarnessStderr(stdout, subcommand)
622
779
  try:
623
780
  run.main()
624
781
  finally:
625
- sys.stderr = stderr
782
+ sys.stdout, sys.stderr = stdout, stderr
626
783
  return None
627
784
 
628
785
 
@@ -762,7 +919,7 @@ You can also paste this into your agent to get started:
762
919
 
763
920
  Install browser-use with `uv tool install browser-use=={version}`, run `browser-use skill install`
764
921
  to register the skill, and connect it to my browser. If setup or connection fails,
765
- follow https://github.com/browser-use/browser-harness/blob/main/install.md
922
+ run `browser-use --doctor` and follow its output and the error message.
766
923
 
767
924
  More:
768
925
  browser-use login sign in once for cloud browsers and the default model
@@ -783,7 +940,8 @@ HELP = """Browser Use CLI: your coding agent drives a browser with Python piped
783
940
  print(page_info())
784
941
  PY
785
942
 
786
- Helpers are pre-imported; the daemon starts and attaches to your running Chrome by itself.
943
+ Helpers are pre-imported; the daemon starts and attaches to your running Chrome by itself, or to a Chromium of its own
944
+ where it cannot (no display, remote debugging off).
787
945
 
788
946
  Commands:
789
947
  browser-use login [--device-code | --api-key-stdin] sign in to Browser Use Cloud (cloud browsers, default model)
@@ -792,7 +950,7 @@ Commands:
792
950
  browser-use --doctor check install, daemon and browser
793
951
  browser-use doctor --fix-snap how to fix Snap Chromium blocking CDP (Linux)
794
952
  browser-use mac-approve approve Chrome's macOS remote-debugging prompt
795
- browser-use --reload restart the daemon
953
+ browser-use --reload restart the daemon and close its own Chromium
796
954
  browser-use install install Chromium for the library's Browser('chromium') (Playwright's build)
797
955
  browser-use skill [show | install [--target NAME] [--path DIR] [--install-cli]]
798
956
  print or install the agent skill
@@ -16,9 +16,13 @@ it is stopped, so a later process (the next CLI call) knows it too.
16
16
  """
17
17
 
18
18
  import ast
19
+ import ipaddress
19
20
  import os
21
+ import socket
20
22
  import time
21
23
  import urllib.error
24
+ import urllib.parse
25
+ import urllib.request
22
26
  from pathlib import Path
23
27
  from typing import Any
24
28
 
@@ -136,6 +140,7 @@ def ensure_daemon(wait: float | None = None, name: str | None = None, env: dict[
136
140
 
137
141
  require_debug_port_unless_attached(name) # never the 127.0.0.1:9222 guess (local.py)
138
142
  return admin.ensure_daemon(wait=wait, name=name, env=env)
143
+ require_cdp_url_listening(name, env)
139
144
  # BU_CDP_URL / BU_CDP_WS: browser-harness takes no spawn lock there, so concurrent cold CLI calls each started
140
145
  # a daemon under one name and orphaned all but one. One spawn at a time (its own lock file: a stale daemon's
141
146
  # restart inside ensure_daemon takes browser-harness's).
@@ -153,6 +158,75 @@ def ensure_daemon(wait: float | None = None, name: str | None = None, env: dict[
153
158
  )
154
159
 
155
160
 
161
+ CDP_REFUSED_GRACE_S = 3.0 # a Chrome started just before this call opens its port within that
162
+
163
+
164
+ def require_cdp_url_listening(name: str, env: dict[str, str] | None = None) -> None:
165
+ """BU_CDP_URL (and no BU_CDP_WS, which wins) whose host refuses connections: nothing listens on that port, yet
166
+ browser-harness retried it for 30 s on every call and then failed. Raise at once with both ways out, unless daemon
167
+ name is still healthy (browser-harness then reuses it and never reads BU_CDP_URL). A port that is no number never
168
+ works: raise at once too. A timeout, DNS, an HTTP error, or a proxy urllib uses for a host off this machine stays
169
+ browser-harness's to retry and report."""
170
+ merged = {**os.environ, **(env or {})}
171
+ url = merged.get('BU_CDP_URL')
172
+ if not url or merged.get('BU_CDP_WS'):
173
+ return
174
+ dedicated = '--user-data-dir=<a dir of its own>'
175
+ try:
176
+ u = urllib.parse.urlsplit(url)
177
+ shown = f'{u.scheme}://{u.netloc.rpartition("@")[2]}' # never the user:password@, path or query (a token)
178
+ port = u.port
179
+ except ValueError:
180
+ scheme, sep, rest = url.partition('://')
181
+ shown = scheme + sep + rest.split('/')[0].split('?')[0].rpartition('@')[2]
182
+ raise RuntimeError(
183
+ f'BU_CDP_URL={shown} is not a valid http://HOST:PORT URL. Set it to http://127.0.0.1:PORT where PORT is the number a Chrome '
184
+ f'started with --remote-debugging-port=PORT {dedicated} listens on{_WAYS_OUT}'
185
+ ) from None
186
+ host = u.hostname
187
+ if not host:
188
+ return
189
+ if port is None: # urllib dials the scheme's port; a remote https endpoint can serve DevTools there
190
+ port = 443 if u.scheme in ('https', 'wss') else 80
191
+ fix = (
192
+ f'It names no port, so {port} was tried. Set it to http://127.0.0.1:PORT of a Chrome started with '
193
+ f'--remote-debugging-port=PORT {dedicated}'
194
+ )
195
+ else:
196
+ fix = f'Start Chrome with --remote-debugging-port={port} {dedicated}'
197
+ if urllib.request.getproxies().get(u.scheme) and not _loopback(host) and not urllib.request.proxy_bypass(host):
198
+ return # browser-harness's urllib reaches it through that proxy, not directly
199
+ deadline, checked = time.monotonic() + CDP_REFUSED_GRACE_S, False
200
+ while True:
201
+ try:
202
+ socket.create_connection((host, port), timeout=5).close() # Windows takes ~2 s to report a refusal
203
+ return
204
+ except ConnectionRefusedError:
205
+ if not checked and admin.daemon_alive(name) and daemon_healthy(name):
206
+ return
207
+ checked = True
208
+ if time.monotonic() >= deadline:
209
+ break
210
+ time.sleep(0.25)
211
+ except OSError:
212
+ return
213
+ raise RuntimeError(f'BU_CDP_URL={shown} refused the connection: no browser listens on {host}:{port}. {fix}{_WAYS_OUT}')
214
+
215
+
216
+ _WAYS_OUT = (
217
+ ', or unset BU_CDP_URL and browser-use finds a browser itself (your Chrome with remote debugging on; --cli-mcp falls '
218
+ "back to its own Chromium). For an MCP server, change it in the server's env in the MCP config, then restart the "
219
+ 'server.'
220
+ )
221
+
222
+
223
+ def _loopback(host: str) -> bool:
224
+ try:
225
+ return host == 'localhost' or ipaddress.ip_address(host).is_loopback
226
+ except ValueError:
227
+ return False
228
+
229
+
156
230
  def start(name: str, profile_name: str | None, create_kwargs: dict[str, Any], namespace: dict[str, Any] | None) -> dict:
157
231
  """browser-harness's start_remote_daemon with one-line errors, then route this process to the new daemon."""
158
232
  os.environ.setdefault('BH_TAB_MARKER', '0') # the daemon spawned below inherits it
@@ -5,6 +5,7 @@ Run with: browser-use --cli-mcp
5
5
  import asyncio
6
6
  import base64
7
7
  import contextvars
8
+ import errno
8
9
  import functools
9
10
  import locale
10
11
  import os
@@ -143,6 +144,14 @@ _call_errors: contextvars.ContextVar[list[tuple[str, str]] | None] = contextvars
143
144
  TOOLS = ('browser_exec', 'browser_screenshot', 'browser_login', 'browser_feedback')
144
145
 
145
146
 
147
+ def _client_gone(e: BaseException) -> bool:
148
+ """Writing to the client failed because it closed its end of the pipe: it quit, or gave up waiting for a reply (a
149
+ slow first start). Windows can report that as EINVAL instead of EPIPE (CPython bpo-35754)."""
150
+ if isinstance(e, BrokenPipeError | ConnectionResetError):
151
+ return True
152
+ return os.name == 'nt' and isinstance(e, OSError) and e.errno == errno.EINVAL
153
+
154
+
146
155
  def _error_class(e: BaseException) -> str:
147
156
  """The exception's class for telemetry, and its message unless the cell's own code raised it: Claude's code raises
148
157
  with what it typed or read from the page (`assert name in text, f'{name} missing'`), which no scrub can know."""
@@ -215,12 +224,13 @@ CHROME_SETUP = (
215
224
  )
216
225
 
217
226
 
218
- def _setup_reason(e: RuntimeError) -> str:
219
- """Why --cli-mcp runs its own Chromium after the chrome://inspect setup failed, and how to get the user's Chrome."""
227
+ def _setup_reason(e: RuntimeError, then: str = 'restart this MCP server') -> str:
228
+ """Why --cli-mcp (or the CLI: then='run `browser-use --reload`') runs its own Chromium after the chrome://inspect
229
+ setup failed, and how to get the user's Chrome."""
220
230
  text = str(e).removeprefix('remote-debugging-setup:').strip()
221
231
  if text.startswith('none of your browsers'):
222
- return CHROME_SETUP
223
- return f'{text.rstrip(".").removesuffix(", then run again")}, then restart this MCP server'
232
+ return CHROME_SETUP.replace('restart this MCP server', then)
233
+ return f'{text.rstrip(".").removesuffix(", then run again")}, then {then}'
224
234
 
225
235
 
226
236
  def _utf8_open(file: Any, mode: str = 'r', buffering: int = -1, encoding: str | None = None, *args: Any, **kwargs: Any):
@@ -263,6 +273,19 @@ def _install_chromium() -> float:
263
273
  return time.monotonic() - started
264
274
 
265
275
 
276
+ def no_browser_text(what: str, e: Exception, cloud: str) -> str:
277
+ """One line (a Chrome log tail has several) when nothing can be driven: what could not start, why, and the fix.
278
+ --cli-mcp and the CLI."""
279
+ reason = ' '.join((str(e) or type(e).__name__).split()).rstrip('.')
280
+ how = (
281
+ 'sudo apt-get install -y libatomic1 && browser-use install' if sys.platform.startswith('linux') else 'browser-use install'
282
+ )
283
+ return (
284
+ f'No browser to drive: {what} could not start: {reason}. Install Google Chrome or Chromium on this machine (or run '
285
+ f'`{how}`){cloud}.'
286
+ )
287
+
288
+
266
289
  def _cloud_hint() -> str:
267
290
  """The way to a cloud browser: start_remote_daemon() only when a key is there for it to use."""
268
291
  try:
@@ -420,7 +443,7 @@ class CLIMCPServer:
420
443
  types.Tool(
421
444
  name='browser_exec',
422
445
  description=(
423
- 'Execute Python in the browser-harness session. Helpers like new_tab(url), '
446
+ 'Execute Python in the browser-use session. Helpers like new_tab(url), '
424
447
  'goto_url(url), page_info(), click_at_xy(x, y), type_text(text), js(code), '
425
448
  'cdp(method, ...), wait_for_load(), list_tabs() are pre-imported. The namespace '
426
449
  'persists across calls. Returns whatever the code prints (prints from threads it starts are not '
@@ -458,7 +481,7 @@ class CLIMCPServer:
458
481
  name='browser_login',
459
482
  description=(
460
483
  "Sign in to Browser Use Cloud for cloud browsers (start_remote_daemon). Opens the user's browser "
461
- 'to approve; the key is stored for browser-use, browser-harness and this server, never shown. '
484
+ 'to approve; the key is stored for browser-use and this server, never shown. '
462
485
  'Returns once signed in, or with the URL to approve: call it again to finish.'
463
486
  ),
464
487
  input_schema={
@@ -671,19 +694,9 @@ class CLIMCPServer:
671
694
  return await browser.start()
672
695
 
673
696
  def _no_browser(self, e: Exception) -> NoBrowserError:
674
- reason = ' '.join((str(e) or type(e).__name__).split()).rstrip('.') # one line: a Chrome log tail has several
675
697
  chrome = f'no Chrome to attach ({self._fallback}), and ' if self._fallback else ''
676
698
  rules = self._browser is not None and self._browser.domains
677
- cloud = '' if rules else f', or {_cloud_hint()}'
678
- how = (
679
- 'sudo apt-get install -y libatomic1 && browser-use install'
680
- if sys.platform.startswith('linux')
681
- else 'browser-use install'
682
- )
683
- return NoBrowserError(
684
- f"No browser to drive: {chrome}this server's own Chromium could not start: {reason}. Install Google Chrome or "
685
- f'Chromium on this machine (or run `{how}`){cloud}.'
686
- )
699
+ return NoBrowserError(no_browser_text(f"{chrome}this server's own Chromium", e, '' if rules else f', or {_cloud_hint()}'))
687
700
 
688
701
  def _browser_note(self) -> str | None:
689
702
  """The browser now in use, once per change, for the browser_exec result: None for a cloud browser (its start said)."""
@@ -858,8 +871,6 @@ class CLIMCPServer:
858
871
  write_stream,
859
872
  self.server.create_initialization_options(),
860
873
  )
861
- except BrokenPipeError:
862
- pass
863
874
  finally:
864
875
  sys.stdout = stdout
865
876
  # Windows: the client closed the session; stop the cloud browser before exiting, not only from the reaper (the
@@ -876,7 +887,11 @@ async def main(own_browser: bool = False, **browser_options: Any):
876
887
  os.environ.setdefault('BH_CLIENT', 'browser-use-mcp')
877
888
  os.environ['BU_MODEL_CODE'] = '1' # browser_exec runs the client model's code: its browser_use.feedback() is not consent
878
889
  server = CLIMCPServer(own_browser, **browser_options)
879
- await server.run()
890
+ try:
891
+ await server.run()
892
+ except* OSError as group: # the mcp library's task group raises a failed write inside an ExceptionGroup
893
+ if (rest := group.split(_client_gone)[1]) is not None:
894
+ raise rest from None
880
895
 
881
896
 
882
897
  if __name__ == '__main__':
@@ -23,7 +23,7 @@ metadata:
23
23
 
24
24
  # Browser Use
25
25
 
26
- Direct browser control via CDP. For task-specific edits, use `agent-workspace/agent_helpers.py`. For setup, install, or connection problems, read https://github.com/browser-use/browser-harness/blob/main/install.md.
26
+ Direct browser control via CDP. For task-specific edits, use `agent-workspace/agent_helpers.py`. For setup, install, or connection problems, run `browser-use --doctor` and follow its output and the error message.
27
27
 
28
28
  ## When Not to Use
29
29
 
@@ -41,6 +41,9 @@ FEEDBACK_LINE = (
41
41
  "'what happened'`: it goes straight to the Browser Use team. Never include secrets."
42
42
  )
43
43
 
44
+ HARNESS_INSTALL_LINK = 'read https://github.com/browser-use/browser-harness/blob/main/install.md' # the sentence's period follows
45
+ SETUP_HELP = 'run `browser-use --doctor` and follow its output and the error message'
46
+
44
47
 
45
48
  def as_browser_use_skill(text: str) -> str:
46
49
  """Expose the Browser Harness skill under the Browser Use skill identity."""
@@ -75,6 +78,8 @@ def as_browser_use_skill(text: str) -> str:
75
78
  lines.extend(OPENCLAW_METADATA_LINES)
76
79
 
77
80
  body = body.replace('# browser-harness', '# Browser Use', 1).replace('# Browser Harness', '# Browser Use', 1)
81
+ # browser-harness's install.md installs and runs `browser-harness`, which `uv tool install browser-use` does not provide
82
+ body = body.replace(HARNESS_INSTALL_LINK, SETUP_HELP)
78
83
  # Rebrand every mention except repo URLs (github.com/browser-use/browser-harness/...)
79
84
  body = re.sub(r'(?<!/)browser-harness', 'browser-use', body)
80
85
  body = body.replace('Browser Harness', 'Browser Use')
@@ -96,6 +101,6 @@ def skill_text() -> str:
96
101
  text = resources.files('browser_harness').joinpath('SKILL.md').read_text(encoding='utf-8')
97
102
  except ModuleNotFoundError as exc:
98
103
  raise RuntimeError(
99
- 'The Browser Use skill relies on the browser-harness package. Install browser-use again or install `browser-harness`.'
104
+ 'The Browser Use skill relies on the browser-harness package. Install browser-use again: uv tool install --force browser-use'
100
105
  ) from exc
101
106
  return as_browser_use_skill(text)
@@ -449,6 +449,13 @@ def error_class(e: BaseException | type) -> str:
449
449
  return cls.__name__[:MAX_NAME] if known else 'custom'
450
450
 
451
451
 
452
+ def group_class(e: BaseException) -> str:
453
+ """An exception group's class with the classes inside it (error_class each), 'ExceptionGroup(BrokenPipeError)'."""
454
+ if not isinstance(e, BaseExceptionGroup):
455
+ return error_class(e)
456
+ return f'{error_class(e)}({", ".join(sorted({group_class(inner) for inner in e.exceptions}))})'[:MAX_ERROR]
457
+
458
+
452
459
  CDP_PART = re.compile(r'[A-Za-z][A-Za-z0-9]{0,63}')
453
460
  CLOUD_METHODS = frozenset({'BrowserUse.setCaptchaSolverEnabled', 'BrowserUse.getCaptchaSolverEnabled'})
454
461
 
@@ -607,7 +614,9 @@ def scrub_cli_event(payload: dict, error: BaseException | None = None) -> dict:
607
614
  return payload
608
615
  steps = [s for s in props.get('steps') or [] if isinstance(s, dict)]
609
616
  clean = {k: v for k, v in props.items() if k not in CLI_CONTENT}
610
- if clean.get('error_message') is not None and error is not None and raised_by_cell(error):
617
+ if clean.get('error_message') is not None and isinstance(error, BaseExceptionGroup):
618
+ clean['error_message'] = group_class(error) # 'ExceptionGroup' (11-11, 3% of --cli-mcp devices) named no cause
619
+ elif clean.get('error_message') is not None and error is not None and raised_by_cell(error):
611
620
  clean['error_message'] = error_class(error)
612
621
  elif clean.get('error_message') is not None: # a traceback's frames quote the code: its last line only
613
622
  clean['error_message'] = scrub(error_line(clean['error_message']), [], MAX_ERROR) or None
@@ -83,11 +83,12 @@ class ActionResult(BaseModel):
83
83
  data = _without_0x_defaults(data)
84
84
  if isinstance(data, dict) and (name := next((k for k in data if k in REMOVED_FIELDS), None)):
85
85
  raise RemovedField(removed(f'ActionResult({name}=...)', REMOVED_FIELDS[name]))
86
- if isinstance(data, dict) and (name := next((k for k in data if k in IGNORED_FIELDS), None)):
87
- if name not in _warned: # once: an action returns it on every call
88
- _warned.add(name)
89
- logger.warning(f'ActionResult({name}=...) is ignored in browser-use 1.0: {IGNORED_FIELDS[name]}')
90
- data = {k: v for k, v in data.items() if k != name}
86
+ if isinstance(data, dict) and (names := [k for k in data if k in IGNORED_FIELDS]):
87
+ for name in names: # every one: an ignored field left in reached the model as JSON
88
+ if name not in _warned: # once: an action returns it on every call
89
+ _warned.add(name)
90
+ logger.warning(f'ActionResult({name}=...) is ignored in browser-use 1.0: {IGNORED_FIELDS[name]}')
91
+ data = {k: v for k, v in data.items() if k not in IGNORED_FIELDS}
91
92
  return data
92
93
 
93
94
 
@@ -2,7 +2,7 @@
2
2
  name = "browser-use"
3
3
  description = "Browser agent on Pydantic AI: one persistent Python REPL on raw CDP, cloud or local Chrome"
4
4
  authors = [{ name = "Gregor Zunic" }]
5
- version = "1.0.2"
5
+ version = "1.0.3"
6
6
  readme = "README.md"
7
7
  license = "MIT"
8
8
  requires-python = ">=3.11,<4.0"
File without changes
File without changes