ok-use 0.1.0__py3-none-any.whl

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.
ok_use/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ """ok-use: computer-use style MCP server for the Windows desktop (see server.py)."""
2
+ __version__ = '0.1.0'
ok_use/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .server import main
4
+
5
+ sys.exit(main())
ok_use/advisor.py ADDED
@@ -0,0 +1,112 @@
1
+ """inspect_window: what kind of app a window is, and which ok-use tools to use for it.
2
+
3
+ Agents call it once per new app instead of guessing; it costs a few hundred tokens and saves screenshots
4
+ (1,500-2,500 tokens each) wherever the accessibility tree can do the job.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from . import win32 as w
9
+
10
+ BROWSERS = {'chrome.exe', 'msedge.exe', 'firefox.exe', 'brave.exe', 'opera.exe', 'vivaldi.exe', 'arc.exe',
11
+ 'chromium.exe', 'iexplore.exe', 'thorium.exe', 'waterfox.exe', 'librewolf.exe', 'zen.exe'}
12
+ GAME_CLASSES = ('unitywndclass', 'unrealwindow', 'sdl_app', 'glfw', 'waapplication window', 'valve001',
13
+ 'cryengine', 'launchunrealuesandbox', 'godot', 'gamewindow', 'd3d', 'dx11', 'ogl', 'opengl',
14
+ 'riotwindowclass', 'unityeditor')
15
+
16
+ PLAN = {
17
+ 'accessible_app': [
18
+ 'Read with find_elements (filter by name/role) and element_text: text instead of images, works while '
19
+ 'the window is covered.',
20
+ 'Act with element_action (invoke, toggle, select, expand, set_value): no coordinates, no mouse. Windows '
21
+ 'brings the window forward during the action; ok-use puts the previous window back.',
22
+ 'Use screenshot only to check layout or visuals, or when an element is missing or an action fails; '
23
+ 'then click/type_text with window=... (background mode first, mode="foreground" if ignored).',
24
+ ],
25
+ 'no_tree': [
26
+ 'This app exposes no accessibility tree (custom-drawn, GPU-rendered, or a Qt 5 app without '
27
+ 'accessibility): use screenshot (window=..., small max_size to save tokens) and zoom for detail.',
28
+ 'Act with click/key/type_text/drag/scroll with window=...: background mode first, mode="foreground" '
29
+ 'if an action has no visible effect.',
30
+ ],
31
+ 'sparse_tree': [
32
+ 'The accessibility tree is thin: try find_elements once for the controls you need; if they are not '
33
+ 'there, use screenshot + click/key/type_text with window=....',
34
+ 'Background mode (the default with window=...) first; if an action has no visible effect, retry with '
35
+ 'mode="foreground".',
36
+ ],
37
+ 'game': [
38
+ 'No accessibility tree: use screenshot (window=..., small max_size to save tokens) and zoom for detail.',
39
+ 'Act with click/key/type_text/drag/scroll. Many games read the live mouse/keyboard state and ignore '
40
+ 'posted (background) input: use mode="foreground" when background input has no effect. drag already '
41
+ 'uses real input.',
42
+ 'Keys and clicks with real input stay down 0.05 s so games polling each frame see them; use key(hold=...) '
43
+ 'for longer presses (movement).',
44
+ ],
45
+ 'user_browser': [
46
+ "This is the user's own browser (their tabs and logins). Do not restart it or ask for a remote-debugging "
47
+ 'connection: attaching Playwright needs the browser restarted with a debugging port and the user '
48
+ 'approving it each time.',
49
+ 'Read the page with element_text(window=...) (the page text, in the background) or find_elements '
50
+ '(links, buttons, fields with their rects).',
51
+ 'Act with element_action (invoke links/buttons, set_value on fields) or screenshot + click/type_text. '
52
+ 'Background posted input often fails in Chromium pages; use mode="foreground" for clicks and typing.',
53
+ "For web work that does not need the user's tabs or logins, use ok-use's own Playwright browser "
54
+ 'instead (playwright_env): no prompts, full DOM control.',
55
+ ],
56
+ 'session_browser': [
57
+ "ok-use's own Playwright browser session: drive it with Playwright scripts (playwright_env), not with "
58
+ 'the window tools.',
59
+ 'Use the window tools only for what Playwright cannot reach: permission prompts, native file dialogs.',
60
+ ],
61
+ 'chromium_app': [
62
+ 'An Electron/Chromium app: its accessibility tree usually describes the UI well. Use find_elements, '
63
+ 'element_text and element_action first.',
64
+ 'For clicks and typing by coordinates use mode="foreground": Chromium content often ignores posted '
65
+ 'background input.',
66
+ ],
67
+ 'elevated': [
68
+ 'The window belongs to an elevated (admin) process and this server is not elevated: input and UI '
69
+ 'Automation are blocked. Run ok-use setup so the server runs elevated.',
70
+ ],
71
+ }
72
+
73
+
74
+ def classify(desk, uia, window) -> dict:
75
+ hwnd = desk.resolve(window)
76
+ if not hwnd:
77
+ raise ValueError('inspect_window needs a window')
78
+ info = desk.describe(hwnd)
79
+ cls, proc = info['class'].lower(), (info['process'] or '').lower()
80
+ out = {'hwnd': hwnd, 'title': info['title'], 'process': info['process'], 'class': info['class'],
81
+ 'elevated': info['elevated'], 'controllable': info['controllable'], 'minimized': info['minimized']}
82
+ if not info['controllable']:
83
+ out.update(kind='elevated', plan=PLAN['elevated'])
84
+ return out
85
+ tree = uia.tree_summary(hwnd)
86
+ out['accessibility'] = tree
87
+ sessions = _session_pids()
88
+ if proc in BROWSERS:
89
+ kind = 'session_browser' if info['pid'] in sessions else 'user_browser'
90
+ elif any(g in cls for g in GAME_CLASSES):
91
+ kind = 'game'
92
+ elif tree['named'] <= 3 and tree['interactive'] <= 1:
93
+ kind = 'no_tree'
94
+ elif cls.startswith('chrome_widgetwin'):
95
+ kind = 'chromium_app'
96
+ elif tree['interactive'] < 3 or tree['named'] < 8:
97
+ kind = 'sparse_tree'
98
+ else:
99
+ kind = 'accessible_app'
100
+ out['kind'] = kind
101
+ out['plan'] = PLAN[kind]
102
+ if info['minimized']:
103
+ out['note'] = 'Minimized: screenshots fail; window_action(action="show_noactivate") first.'
104
+ return out
105
+
106
+
107
+ def _session_pids() -> set[int]:
108
+ try:
109
+ from . import browser
110
+ return {int(s['pid']) for s in browser.list_sessions() if s.get('pid')}
111
+ except Exception: # noqa: BLE001
112
+ return set()
ok_use/bridge.py ADDED
@@ -0,0 +1,156 @@
1
+ """stdio <-> elevated HTTP bridge.
2
+
3
+ The agent launches `ok-use` over stdio as with any MCP server. When the scheduled task is installed and
4
+ this process is not elevated, the bridge starts the elevated HTTP server through the task (no UAC
5
+ prompt), then relays each JSON-RPC message to it with the bearer token. The server is stateless, so if
6
+ it has exited (idle timeout) or crashed, the bridge starts it again and resends the message.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import socket
12
+ import sys
13
+ import threading
14
+ import time
15
+ import urllib.error
16
+ import urllib.request
17
+ from urllib.parse import urlsplit
18
+
19
+ START_TIMEOUT = 30.0
20
+
21
+
22
+ def _log(*parts):
23
+ print('[ok-use bridge]', *parts, file=sys.stderr, flush=True)
24
+
25
+
26
+ def live_server() -> dict | None:
27
+ """The connection record of a running server, if its process and port are alive."""
28
+ from .server import _state_path
29
+ try:
30
+ info = json.loads(_state_path().read_text(encoding='utf-8'))
31
+ import psutil
32
+ if not psutil.pid_exists(int(info['pid'])):
33
+ return None
34
+ parts = urlsplit(info['url'])
35
+ with socket.create_connection((parts.hostname, parts.port), timeout=1):
36
+ return info
37
+ except (OSError, ValueError, KeyError, TypeError):
38
+ return None
39
+
40
+
41
+ def start_server(timeout: float = START_TIMEOUT) -> dict:
42
+ """Start the elevated server through the scheduled task and wait for it to listen."""
43
+ from . import task
44
+ info = live_server()
45
+ if info and info.get('elevated'):
46
+ return info
47
+ task.run()
48
+ deadline = time.monotonic() + timeout
49
+ while time.monotonic() < deadline:
50
+ info = live_server()
51
+ if info and info.get('elevated'):
52
+ return info
53
+ time.sleep(0.2)
54
+ raise RuntimeError(f'the elevated server did not start within {timeout:.0f}s '
55
+ '(see %APPDATA%\\ok-use\\server.log)')
56
+
57
+
58
+ class Bridge:
59
+ def __init__(self, info: dict):
60
+ self.info = info
61
+ self.lock = threading.Lock()
62
+ self.out_lock = threading.Lock()
63
+ self.protocol: str | None = None
64
+
65
+ def _server(self, stale: dict | None = None) -> dict:
66
+ with self.lock:
67
+ if stale is not None and self.info is stale:
68
+ _log('server is gone, restarting it')
69
+ self.info = start_server()
70
+ return self.info
71
+
72
+ def write(self, msg):
73
+ data = json.dumps(msg, ensure_ascii=False, separators=(',', ':')).encode('utf-8') + b'\n'
74
+ with self.out_lock:
75
+ sys.stdout.buffer.write(data)
76
+ sys.stdout.buffer.flush()
77
+
78
+ def error(self, msg: dict, text: str):
79
+ if isinstance(msg, dict) and 'id' in msg and 'method' in msg:
80
+ self.write({'jsonrpc': '2.0', 'id': msg['id'], 'error': {'code': -32603, 'message': text}})
81
+
82
+ def _post(self, info: dict, body: bytes):
83
+ headers = {'Content-Type': 'application/json', 'Accept': 'application/json, text/event-stream',
84
+ 'Authorization': f'Bearer {info["token"]}'}
85
+ if self.protocol:
86
+ headers['MCP-Protocol-Version'] = self.protocol
87
+ req = urllib.request.Request(info['url'], data=body, headers=headers, method='POST')
88
+ with urllib.request.urlopen(req, timeout=None) as resp:
89
+ return resp.headers.get('Content-Type', ''), resp.read()
90
+
91
+ def forward(self, msg: dict, body: bytes):
92
+ try:
93
+ info = self._server()
94
+ try:
95
+ ctype, data = self._post(info, body)
96
+ except urllib.error.URLError as e:
97
+ # Only a refused connection is safe to resend: the server never saw the message.
98
+ if isinstance(e, urllib.error.HTTPError) or not isinstance(e.reason, ConnectionRefusedError):
99
+ raise
100
+ ctype, data = self._post(self._server(stale=info), body)
101
+ except urllib.error.HTTPError as e:
102
+ detail = e.read().decode('utf-8', 'replace')[:500]
103
+ try:
104
+ self.write(json.loads(detail)) # a JSON-RPC error from the server
105
+ except ValueError:
106
+ self.error(msg, f'ok-use server returned HTTP {e.code}: {detail}')
107
+ return
108
+ except Exception as e: # noqa: BLE001
109
+ _log(f'{type(e).__name__}: {e}')
110
+ self.error(msg, f'ok-use bridge: {type(e).__name__}: {e}')
111
+ return
112
+ for reply in self._messages(ctype, data):
113
+ if isinstance(reply, dict) and msg.get('method') == 'initialize':
114
+ self.protocol = (reply.get('result') or {}).get('protocolVersion') or self.protocol
115
+ self.write(reply)
116
+
117
+ @staticmethod
118
+ def _messages(ctype: str, data: bytes):
119
+ if not data.strip():
120
+ return []
121
+ if 'text/event-stream' in ctype:
122
+ out = []
123
+ for event in data.decode('utf-8').replace('\r\n', '\n').split('\n\n'):
124
+ payload = '\n'.join(l[5:].lstrip() for l in event.split('\n') if l.startswith('data:'))
125
+ if payload:
126
+ out.append(json.loads(payload))
127
+ return out
128
+ return [json.loads(data)]
129
+
130
+ def serve(self):
131
+ for line in sys.stdin.buffer:
132
+ line = line.strip()
133
+ if not line:
134
+ continue
135
+ try:
136
+ msg = json.loads(line)
137
+ except ValueError:
138
+ self.write({'jsonrpc': '2.0', 'id': None, 'error': {'code': -32700, 'message': 'Parse error'}})
139
+ continue
140
+ threading.Thread(target=self.forward, args=(msg, line), daemon=True).start()
141
+
142
+
143
+ def run_stdio(local: bool = False):
144
+ """The stdio entry point: bridge to the elevated server when possible, otherwise serve in-process."""
145
+ from . import task, win32
146
+ if not local and not win32.is_admin() and task.exists():
147
+ try:
148
+ info = start_server()
149
+ except Exception as e: # noqa: BLE001
150
+ _log(f'could not start the elevated server ({e}); running without admin rights')
151
+ else:
152
+ _log(f'relaying to the elevated server at {info["url"]}')
153
+ Bridge(info).serve()
154
+ return
155
+ from .server import build_server
156
+ build_server().run('stdio')
ok_use/browser.py ADDED
@@ -0,0 +1,369 @@
1
+ """Browser automation with Playwright (Python) over a persistent CDP connection.
2
+
3
+ The preferred way for an agent to automate a browser: write an ordinary Playwright script and run it
4
+ with this environment's Python. Scripts don't launch a fresh browser each time. They connect over the
5
+ Chrome DevTools Protocol to one long-lived browser session, so tabs, logins and page state carry over
6
+ from one script to the next:
7
+
8
+ from ok_use.browser import session
9
+
10
+ with session() as s: # starts the "default" browser once, then reuses it
11
+ s.page.goto("https://example.com")
12
+ print(s.page.title())
13
+ # leaving the block only disconnects; the browser and its tabs stay open
14
+
15
+ A session is a Chromium-family browser (installed Edge or Chrome, or Playwright's bundled Chromium) started with
16
+ --remote-debugging-port and its own persistent profile in %LOCALAPPDATA%\\ok-use\\browsers\\<name>.
17
+ session(cdp_url=...) attaches to any other browser that already has a debugging port open.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import shutil
24
+ import socket
25
+ import subprocess
26
+ import sys
27
+ import time
28
+ import urllib.request
29
+ from contextlib import contextmanager
30
+ from dataclasses import dataclass
31
+ from pathlib import Path
32
+ from typing import Any, Iterator
33
+
34
+ ROOT = Path(os.environ.get('LOCALAPPDATA', Path.home())) / 'ok-use' / 'browsers'
35
+ DEFAULT = 'default'
36
+
37
+ EXAMPLE = '''from ok_use.browser import session
38
+
39
+ with session() as s: # reuses the running "default" browser, or starts it
40
+ page = s.page # the last tab; s.new_page() opens another
41
+ page.goto("https://example.com")
42
+ print(page.title())
43
+ page.screenshot(path="example.png")
44
+ # the browser keeps running for the next script; `ok-use browser stop` closes it
45
+ '''
46
+
47
+
48
+ # -- environment -------------------------------------------------------------------------
49
+ def _browsers_path() -> Path:
50
+ env = os.environ.get('PLAYWRIGHT_BROWSERS_PATH')
51
+ if env and env != '0':
52
+ return Path(env)
53
+ return Path(os.environ.get('LOCALAPPDATA', Path.home())) / 'ms-playwright'
54
+
55
+
56
+ def _python() -> Path:
57
+ python = Path(sys.executable)
58
+ if python.name.lower() == 'pythonw.exe': # the logon task runs pythonw; scripts want console output
59
+ python = python.with_name('python.exe')
60
+ return python
61
+
62
+
63
+ def channels() -> dict[str, str]:
64
+ """Installed branded browsers that can be used as a session's channel."""
65
+ roots = [os.environ.get(k) for k in ('PROGRAMFILES', 'PROGRAMFILES(X86)', 'LOCALAPPDATA')]
66
+ candidates = {'msedge': r'Microsoft\Edge\Application\msedge.exe',
67
+ 'chrome': r'Google\Chrome\Application\chrome.exe',
68
+ 'msedge-beta': r'Microsoft\Edge Beta\Application\msedge.exe',
69
+ 'chrome-beta': r'Google\Chrome Beta\Application\chrome.exe'}
70
+ found = {}
71
+ for channel, rel in candidates.items():
72
+ for root in filter(None, roots):
73
+ exe = Path(root) / rel
74
+ if exe.exists():
75
+ found[channel] = str(exe)
76
+ break
77
+ return found
78
+
79
+
80
+ def bundled_chromium() -> str | None:
81
+ """Playwright's own Chromium (installed with `python -m playwright install chromium`)."""
82
+ base = _browsers_path()
83
+ builds = sorted(base.glob('chromium-*'), key=lambda p: int(p.name.split('-')[-1]) if p.name.split('-')[-1]
84
+ .isdigit() else 0, reverse=True)
85
+ for build in builds:
86
+ for rel in ('chrome-win64/chrome.exe', 'chrome-win/chrome.exe'):
87
+ exe = build / rel
88
+ if exe.exists():
89
+ return str(exe)
90
+ return None
91
+
92
+
93
+ def playwright_env() -> dict:
94
+ try:
95
+ from importlib.metadata import version
96
+ pw_version = version('playwright')
97
+ except Exception: # noqa: BLE001
98
+ pw_version = None
99
+ python = _python()
100
+ browsers_dir = _browsers_path()
101
+ return {
102
+ 'python': str(python),
103
+ 'playwright_version': pw_version,
104
+ 'browsers_path': str(browsers_dir),
105
+ 'installed_browsers': sorted(p.name for p in browsers_dir.iterdir() if p.is_dir() and not p.name.startswith('.'))
106
+ if browsers_dir.is_dir() else [],
107
+ 'bundled_chromium': bundled_chromium(),
108
+ 'channels': channels(),
109
+ 'sessions': list_sessions(),
110
+ 'run': f'"{python}" path\\to\\script.py',
111
+ 'cli': {
112
+ 'start': f'"{python}" -m ok_use browser start [--name NAME] [--channel auto|msedge|chrome|chromium] '
113
+ '[--headless] [--url URL]',
114
+ 'status': f'"{python}" -m ok_use browser status',
115
+ 'stop': f'"{python}" -m ok_use browser stop [--name NAME]',
116
+ 'install_chromium': f'"{python}" -m playwright install chromium',
117
+ },
118
+ 'how_to': [
119
+ 'For web tasks that do not need the user\'s own browser: write a Playwright for Python script and run '
120
+ 'it with `python` above from your shell (no MCP calls).',
121
+ 'Use `with ok_use.browser.session(name=...) as s:` to connect over CDP to a persistent browser. '
122
+ 'It is started on first use and kept running, so tabs, cookies and logins persist between scripts. '
123
+ 's.browser, s.context and s.page are ordinary Playwright objects; s.find_page(text) picks a tab by URL '
124
+ 'or title (tab order is not stable between scripts) and s.new_page(url) opens one.',
125
+ 'The user\'s own browser (their tabs, logins): do not attach Playwright to it. That needs it restarted '
126
+ 'with a remote-debugging port and the user approving the connection every time. Use the MCP tools on '
127
+ 'its window instead: element_text (page text), find_elements, element_action, or screenshot + click. '
128
+ 'Only if the user already runs a browser with --remote-debugging-port=N and asks for it: '
129
+ 'session(cdp_url="http://127.0.0.1:N").',
130
+ 'Do not call browser.close() in scripts; it would close a browser that other scripts reuse. '
131
+ 'Stop a session with `ok-use browser stop`.',
132
+ 'Session browsers run with the privileges of the script that started them; start them from your '
133
+ 'normal shell, not from an elevated one.',
134
+ 'The session browser is a normal window: ok-use window tools can screenshot or drive it too '
135
+ '(e.g. native dialogs Playwright cannot reach).',
136
+ ],
137
+ 'example': EXAMPLE,
138
+ }
139
+
140
+
141
+ def install(browsers: list[str] | None = None) -> int:
142
+ return subprocess.call([str(_python()), '-m', 'playwright', 'install', *(browsers or ['chromium'])])
143
+
144
+
145
+ # -- sessions ------------------------------------------------------------------------------
146
+ def _dir(name: str) -> Path:
147
+ if not name or any(c in name for c in '\\/:*?"<>|') or name in ('.', '..'):
148
+ raise ValueError(f'invalid session name {name!r}')
149
+ return ROOT / name
150
+
151
+
152
+ def _record_path(name: str) -> Path:
153
+ return _dir(name) / 'session.json'
154
+
155
+
156
+ def _free_port() -> int:
157
+ with socket.socket() as s:
158
+ s.bind(('127.0.0.1', 0))
159
+ return s.getsockname()[1]
160
+
161
+
162
+ def _version_info(cdp_url: str, timeout: float = 1.0) -> dict | None:
163
+ try:
164
+ with urllib.request.urlopen(cdp_url.rstrip('/') + '/json/version', timeout=timeout) as r:
165
+ return json.loads(r.read().decode('utf-8'))
166
+ except (OSError, ValueError):
167
+ return None
168
+
169
+
170
+ def _resolve_exe(channel: str) -> str:
171
+ if channel in ('auto', '', None):
172
+ found = channels()
173
+ for preferred in ('msedge', 'chrome'):
174
+ if preferred in found:
175
+ return found[preferred]
176
+ channel = 'chromium'
177
+ if channel == 'chromium':
178
+ exe = bundled_chromium()
179
+ if not exe:
180
+ raise RuntimeError('Playwright Chromium is not installed: run '
181
+ f'"{_python()}" -m playwright install chromium, or use channel="msedge"')
182
+ return exe
183
+ found = channels()
184
+ if channel in found:
185
+ return found[channel]
186
+ if os.path.isfile(channel):
187
+ return channel
188
+ raise RuntimeError(f'browser channel {channel!r} not found; available: chromium, {", ".join(found) or "-"}')
189
+
190
+
191
+ def status(name: str = DEFAULT) -> dict | None:
192
+ """The running session's record (cdp_url, pid, channel, ...) or None when it is not running."""
193
+ try:
194
+ rec = json.loads(_record_path(name).read_text(encoding='utf-8'))
195
+ except (OSError, ValueError):
196
+ return None
197
+ info = _version_info(rec.get('cdp_url', ''))
198
+ if not info:
199
+ return None
200
+ rec['browser_version'] = info.get('Browser')
201
+ rec['running'] = True
202
+ return rec
203
+
204
+
205
+ def list_sessions() -> list[dict]:
206
+ out = []
207
+ if ROOT.is_dir():
208
+ for d in sorted(ROOT.iterdir()):
209
+ if (d / 'session.json').exists():
210
+ rec = status(d.name)
211
+ out.append(rec or {'name': d.name, 'running': False, 'profile': str(d / 'profile')})
212
+ return out
213
+
214
+
215
+ def start(name: str = DEFAULT, channel: str = 'auto', headless: bool = False, port: int | None = None,
216
+ url: str | None = None, args: list[str] | None = None, timeout: float = 20.0) -> dict:
217
+ """Start the named session's browser (or return it when already running).
218
+
219
+ The browser is detached from the caller, so it outlives the script or shell that started it."""
220
+ running = status(name)
221
+ if running:
222
+ return running
223
+ exe = _resolve_exe(channel)
224
+ profile = _dir(name) / 'profile'
225
+ profile.mkdir(parents=True, exist_ok=True)
226
+ port = port or _free_port()
227
+ cmd = [exe, f'--remote-debugging-port={port}', '--remote-debugging-address=127.0.0.1',
228
+ f'--user-data-dir={profile}', '--no-first-run', '--no-default-browser-check',
229
+ '--disable-sync', '--disable-features=Translate', *(args or [])]
230
+ if headless:
231
+ cmd.append('--headless=new')
232
+ cmd.append(url or 'about:blank')
233
+ detached = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
234
+ try:
235
+ proc = subprocess.Popen(cmd, creationflags=detached | 0x01000000, # CREATE_BREAKAWAY_FROM_JOB
236
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
237
+ close_fds=True)
238
+ except OSError: # the caller's job does not allow breakaway
239
+ proc = subprocess.Popen(cmd, creationflags=detached, stdin=subprocess.DEVNULL,
240
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True)
241
+ cdp_url = f'http://127.0.0.1:{port}'
242
+ deadline = time.monotonic() + timeout
243
+ info = None
244
+ while time.monotonic() < deadline:
245
+ info = _version_info(cdp_url, 0.5)
246
+ if info:
247
+ break
248
+ if proc.poll() is not None:
249
+ raise RuntimeError(f'the browser exited with code {proc.returncode}; is the profile {profile} '
250
+ 'already open in another browser window without a debugging port?')
251
+ time.sleep(0.2)
252
+ if not info:
253
+ raise RuntimeError(f'the browser did not open its debugging port {port} within {timeout:.0f}s')
254
+ rec = {'name': name, 'channel': channel, 'exe': exe, 'pid': proc.pid, 'port': port, 'cdp_url': cdp_url,
255
+ 'ws_url': info.get('webSocketDebuggerUrl'), 'profile': str(profile), 'headless': headless,
256
+ 'started_at': time.strftime('%Y-%m-%dT%H:%M:%S')}
257
+ _record_path(name).write_text(json.dumps(rec, indent=2), encoding='utf-8')
258
+ rec['browser_version'] = info.get('Browser')
259
+ rec['running'] = True
260
+ return rec
261
+
262
+
263
+ def stop(name: str = DEFAULT, timeout: float = 5.0) -> bool:
264
+ """Close the named session's browser (gracefully over CDP, then by killing its process tree)."""
265
+ rec = status(name)
266
+ if not rec:
267
+ return False
268
+ try:
269
+ from playwright.sync_api import sync_playwright
270
+ with sync_playwright() as p:
271
+ # Browser.close shuts the browser down cleanly (cookies flushed); Playwright's close() would only
272
+ # disconnect from a browser it did not launch.
273
+ p.chromium.connect_over_cdp(rec['cdp_url']).new_browser_cdp_session().send('Browser.close')
274
+ except Exception: # noqa: BLE001
275
+ pass
276
+ deadline = time.monotonic() + timeout
277
+ while time.monotonic() < deadline and _version_info(rec['cdp_url'], 0.3):
278
+ time.sleep(0.2)
279
+ if _version_info(rec['cdp_url'], 0.3):
280
+ import psutil
281
+ try:
282
+ root = psutil.Process(int(rec['pid']))
283
+ for p in root.children(recursive=True) + [root]:
284
+ p.kill()
285
+ except psutil.Error:
286
+ pass
287
+ return True
288
+
289
+
290
+ def delete_profile(name: str) -> None:
291
+ """Stop the session and remove its profile (cookies, logins, history)."""
292
+ stop(name)
293
+ shutil.rmtree(_dir(name), ignore_errors=True)
294
+
295
+
296
+ @dataclass
297
+ class Session:
298
+ playwright: Any
299
+ browser: Any
300
+ context: Any
301
+ page: Any
302
+ info: dict
303
+
304
+ def find_page(self, text: str):
305
+ """The first open tab whose URL or title contains text (tab order is not stable between scripts)."""
306
+ for page in self.context.pages:
307
+ if text in page.url or text in page.title():
308
+ self.page = page
309
+ return page
310
+ raise LookupError(f'no open tab matches {text!r}: {[p.url for p in self.context.pages]}')
311
+
312
+ def new_page(self, url: str | None = None):
313
+ page = self.context.new_page()
314
+ if url:
315
+ page.goto(url)
316
+ self.page = page
317
+ return page
318
+
319
+
320
+ @contextmanager
321
+ def session(name: str = DEFAULT, *, cdp_url: str | None = None, channel: str = 'auto',
322
+ headless: bool = False, new_page: bool = False, url: str | None = None) -> Iterator[Session]:
323
+ """Connect to a persistent browser over CDP (starting the named session first if needed).
324
+
325
+ Yields a Session with .browser, .context (the profile's default context), .page (an open tab, or a new
326
+ one with new_page=True), .find_page(text) and .new_page(url). Exiting only disconnects; the browser
327
+ stays open."""
328
+ from playwright.sync_api import sync_playwright
329
+
330
+ info = {'cdp_url': cdp_url} if cdp_url else start(name, channel=channel, headless=headless)
331
+ pw = sync_playwright().start()
332
+ try:
333
+ browser = pw.chromium.connect_over_cdp(info['cdp_url'])
334
+ context = browser.contexts[0] if browser.contexts else browser.new_context()
335
+ pages = [p for p in context.pages if not p.url.startswith(('devtools://', 'chrome-extension://', 'edge://', 'chrome://'))]
336
+ page = context.new_page() if new_page or not pages else pages[-1]
337
+ if url:
338
+ page.goto(url)
339
+ yield Session(pw, browser, context, page, info)
340
+ finally:
341
+ pw.stop() # drops the connection; the browser process keeps running
342
+
343
+
344
+ def main(argv: list[str]) -> int:
345
+ import argparse
346
+ parser = argparse.ArgumentParser(prog='ok-use browser', description=__doc__,
347
+ formatter_class=argparse.RawDescriptionHelpFormatter)
348
+ parser.add_argument('action', choices=['start', 'stop', 'status', 'env', 'install', 'delete'])
349
+ parser.add_argument('--name', default=DEFAULT, help='session name (one profile and port per name)')
350
+ parser.add_argument('--channel', default='auto',
351
+ help='auto (Edge, else Chrome, else bundled Chromium), msedge, chrome, chromium, or an exe path')
352
+ parser.add_argument('--headless', action='store_true')
353
+ parser.add_argument('--port', type=int, help='remote debugging port (default: a free port)')
354
+ parser.add_argument('--url', help='page to open when starting')
355
+ a = parser.parse_args(argv)
356
+ if a.action == 'start':
357
+ print(json.dumps(start(a.name, a.channel, a.headless, a.port, a.url), indent=2))
358
+ elif a.action == 'stop':
359
+ print('stopped' if stop(a.name) else f'session {a.name!r} is not running')
360
+ elif a.action == 'status':
361
+ print(json.dumps(list_sessions(), indent=2))
362
+ elif a.action == 'env':
363
+ print(json.dumps(playwright_env(), indent=2))
364
+ elif a.action == 'install':
365
+ return install()
366
+ elif a.action == 'delete':
367
+ delete_profile(a.name)
368
+ print(f'deleted session {a.name!r} and its profile')
369
+ return 0