browser-automation-cli 0.1.0__py2.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.
@@ -0,0 +1,7 @@
1
+ Metadata-Version: 2.4
2
+ Name: browser-automation-cli
3
+ Version: 0.1.0
4
+ Summary: Browser automation daemon + CLI for coding agents. Persistent sessions, no MCP, no extensions.
5
+ Project-URL: Homepage, https://github.com/jshan9078/browser-automation-cli
6
+ Project-URL: Repository, https://github.com/jshan9078/browser-automation-cli
7
+ License-File: LICENSE.txt
@@ -0,0 +1,9 @@
1
+ cli/main.py,sha256=eQA5jji9rSQmygQt6Wn4L-Ys71bKTwEM5MeFgOjElQk,12342
2
+ daemon/browser.py,sha256=9f_ZEIXrGEkRaO9ln_TR0NKoA9_KD3sE47-GnEbvqtU,8972
3
+ daemon/server.py,sha256=lsL9gNuaiaowbDGEjstDqzf9VOqXujgB3-vcVZNjikI,4357
4
+ daemon/session.py,sha256=GxGFBKTehRBHLGguwDrbA_XGwLJgHOphXKGRJOtkIhs,2947
5
+ browser_automation_cli-0.1.0.dist-info/METADATA,sha256=O1gB3KBcj9jdBsi09R_Ex0aYI3hLumYHS1l88LgOefM,348
6
+ browser_automation_cli-0.1.0.dist-info/WHEEL,sha256=e22IIVjxDyt0lABi4WpktFIGsmO_ebSDXLnPUbPK0E0,105
7
+ browser_automation_cli-0.1.0.dist-info/entry_points.txt,sha256=ev7XKNYCN3ODry1OPBmN0ZgAHxsm8QcYjdZkA2lZteY,78
8
+ browser_automation_cli-0.1.0.dist-info/licenses/LICENSE.txt,sha256=jWVqb-E4JWCYCS7z3ykzrLmzBRE68zOLJyvKbZpo-mU,1080
9
+ browser_automation_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ browser = cli.main:main
3
+ browser-daemon = daemon.server:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Browser CLI Maintainers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
cli/main.py ADDED
@@ -0,0 +1,355 @@
1
+ #!/usr/bin/env python3
2
+ import asyncio
3
+ import base64
4
+ import json
5
+ import logging
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ SOCKET_PATH = Path.home() / ".browser-daemon" / "socket"
11
+
12
+
13
+ async def cmd_capture(url: str, full_page: bool = True, output: str | None = None):
14
+ """Standalone screenshot capture without daemon. Saves to /tmp."""
15
+ from playwright.async_api import async_playwright
16
+ import time
17
+
18
+ async with async_playwright() as p:
19
+ browser = await p.chromium.launch(headless=True)
20
+
21
+ # Create context with anti-detection measures
22
+ context = await browser.new_context(
23
+ viewport={"width": 1920, "height": 1080},
24
+ user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
25
+ )
26
+
27
+ # Hide navigator.webdriver to avoid automation detection
28
+ await context.add_init_script("""
29
+ Object.defineProperty(navigator, 'webdriver', {
30
+ get: () => undefined,
31
+ configurable: true
32
+ });
33
+ """)
34
+
35
+ page = await context.new_page()
36
+
37
+ try:
38
+ await page.goto(url, wait_until="networkidle", timeout=30000)
39
+
40
+ # Wait for body to be fully loaded/rendered
41
+ await page.wait_for_selector("body", state="attached")
42
+ await page.wait_for_load_state("domcontentloaded")
43
+ await asyncio.sleep(2) # Additional wait for JS frameworks
44
+
45
+ # Take screenshot - JPEG for smaller file size
46
+ screenshot_bytes = await page.screenshot(
47
+ full_page=full_page,
48
+ type="jpeg",
49
+ quality=85
50
+ )
51
+
52
+ # Determine output path
53
+ timestamp = int(time.time())
54
+ if output:
55
+ output_path = Path(output)
56
+ else:
57
+ filename = f"browser_capture_{timestamp}.jpg"
58
+ output_path = Path("/tmp") / filename
59
+
60
+ output_path.write_bytes(screenshot_bytes)
61
+
62
+ print(json.dumps({
63
+ "success": True,
64
+ "path": str(output_path),
65
+ "full_page": full_page,
66
+ "format": "jpeg"
67
+ }))
68
+
69
+ except Exception as e:
70
+ print(json.dumps({"success": False, "error": str(e)}), file=sys.stderr)
71
+ sys.exit(1)
72
+ finally:
73
+ await context.close()
74
+ await browser.close()
75
+
76
+
77
+ async def send_request(request: dict) -> dict:
78
+ try:
79
+ reader, writer = await asyncio.open_unix_connection(str(SOCKET_PATH))
80
+ writer.write(json.dumps(request).encode())
81
+ await writer.drain()
82
+ writer.write_eof() # Signal we're done writing
83
+
84
+ # Read all data until connection is closed
85
+ chunks = []
86
+ while True:
87
+ chunk = await reader.read(65536)
88
+ if not chunk:
89
+ break
90
+ chunks.append(chunk)
91
+
92
+ data = b''.join(chunks)
93
+ writer.close()
94
+ await writer.wait_closed()
95
+ return json.loads(data.decode())
96
+ except FileNotFoundError:
97
+ return {"success": False, "error": "Daemon not running. Start with: browser-daemon"}
98
+ except ConnectionRefusedError:
99
+ return {"success": False, "error": "Connection refused. Is another daemon running?"}
100
+ except Exception as e:
101
+ return {"success": False, "error": str(e)}
102
+
103
+
104
+ async def cmd_create():
105
+ result = await send_request({"action": "create"})
106
+ if result["success"]:
107
+ print(result["session_id"])
108
+ else:
109
+ print(f"Error: {result.get('error')}", file=sys.stderr)
110
+ sys.exit(1)
111
+
112
+
113
+ async def cmd_list():
114
+ result = await send_request({"action": "list"})
115
+ if not result["success"]:
116
+ print(f"Error: {result.get('error')}", file=sys.stderr)
117
+ sys.exit(1)
118
+
119
+ sessions = result.get("sessions", [])
120
+ if not sessions:
121
+ print("No active sessions")
122
+ return
123
+
124
+ print(f"{'SESSION_ID':<12} {'URL':<50} {'TITLE'}")
125
+ print("-" * 100)
126
+ for s in sessions:
127
+ url = s["url"][:48] if s["url"] else "(empty)"
128
+ title = s["title"][:30] if s["title"] else ""
129
+ print(f"{s['session_id']:<12} {url:<50} {title}")
130
+
131
+
132
+ async def cmd_delete(session_id: str):
133
+ result = await send_request({"action": "delete", "session_id": session_id})
134
+ if result["success"]:
135
+ print(f"Deleted session {session_id}")
136
+ else:
137
+ print(f"Error: {result.get('error')}", file=sys.stderr)
138
+ sys.exit(1)
139
+
140
+
141
+ async def cmd_navigate(session_id: str, url: str):
142
+ result = await send_request({"action": "navigate", "session_id": session_id, "params": {"url": url}})
143
+ print_json(result)
144
+
145
+
146
+ async def cmd_snapshot(session_id: str, selector: str | None):
147
+ params = {"selector": selector} if selector else {}
148
+ result = await send_request({"action": "snapshot", "session_id": session_id, "params": params})
149
+ print_json(result)
150
+
151
+
152
+ async def cmd_click(session_id: str, selector: str):
153
+ result = await send_request({"action": "click", "session_id": session_id, "params": {"selector": selector}})
154
+ print_json(result)
155
+
156
+
157
+ async def cmd_type(session_id: str, selector: str, text: str):
158
+ result = await send_request({"action": "type", "session_id": session_id, "params": {"selector": selector, "text": text}})
159
+ print_json(result)
160
+
161
+
162
+ async def cmd_hover(session_id: str, selector: str):
163
+ result = await send_request({"action": "hover", "session_id": session_id, "params": {"selector": selector}})
164
+ print_json(result)
165
+
166
+
167
+ async def cmd_select_option(session_id: str, selector: str, value: str):
168
+ result = await send_request({"action": "select_option", "session_id": session_id, "params": {"selector": selector, "value": value}})
169
+ print_json(result)
170
+
171
+
172
+ async def cmd_press_key(session_id: str, key: str):
173
+ result = await send_request({"action": "press_key", "session_id": session_id, "params": {"key": key}})
174
+ print_json(result)
175
+
176
+
177
+ async def cmd_screenshot(session_id: str, selector: str | None, output: str | None = None):
178
+ params = {}
179
+ if selector:
180
+ params["selector"] = selector
181
+ if output:
182
+ params["output"] = output
183
+ result = await send_request({"action": "screenshot", "session_id": session_id, "params": params})
184
+ print_json(result)
185
+
186
+
187
+ async def cmd_go_back(session_id: str):
188
+ result = await send_request({"action": "go_back", "session_id": session_id})
189
+ print_json(result)
190
+
191
+
192
+ async def cmd_go_forward(session_id: str):
193
+ result = await send_request({"action": "go_forward", "session_id": session_id})
194
+ print_json(result)
195
+
196
+
197
+ def cmd_install():
198
+ try:
199
+ subprocess.run([sys.executable, "-m", "playwright", "install", "chromium"], check=True)
200
+ print("Installed Chromium for Browser CLI")
201
+ except subprocess.CalledProcessError as e:
202
+ print(f"Error: failed to install Chromium ({e.returncode})", file=sys.stderr)
203
+ sys.exit(1)
204
+
205
+
206
+ def cmd_cleanup():
207
+ """Kill all Playwright Chrome processes."""
208
+ try:
209
+ result = subprocess.run(
210
+ ["pkill", "-f", "playwright"],
211
+ capture_output=True,
212
+ text=True
213
+ )
214
+ if result.returncode == 0:
215
+ print("Killed Playwright Chrome processes")
216
+ elif result.returncode == 1:
217
+ print("No Playwright processes found")
218
+ else:
219
+ print(f"Error: pkill returned {result.returncode}", file=sys.stderr)
220
+ sys.exit(1)
221
+ except FileNotFoundError:
222
+ print("Error: pkill not found", file=sys.stderr)
223
+ sys.exit(1)
224
+
225
+
226
+ def print_json(data: dict):
227
+ print(json.dumps(data, indent=2))
228
+
229
+
230
+ def main():
231
+ logging.basicConfig(level=logging.WARNING)
232
+
233
+ args = sys.argv[1:]
234
+
235
+ if len(args) == 0 or args[0] in ("-h", "--help"):
236
+ print("""Browser CLI - Authenticated browser automation
237
+
238
+ Standalone Commands (no daemon required):
239
+ browser capture <url> [options] Capture screenshot to /tmp
240
+ Options:
241
+ -f, --full-page Capture full page (default: viewport only)
242
+ -o, --output <path> Custom output path
243
+
244
+ Examples:
245
+ browser capture https://example.com
246
+ browser capture https://example.com -f
247
+ browser capture https://example.com -o ./screenshot.jpg
248
+
249
+ Daemon Commands (requires browser-daemon running):
250
+ browser install Install Chromium runtime
251
+ browser cleanup Kill stale Chrome processes
252
+ browser create Create new session (opens browser for login)
253
+ browser list List active sessions
254
+ browser <id> navigate <url> Navigate to URL
255
+ browser <id> snapshot [selector] Get page elements
256
+ browser <id> click <selector> Click element
257
+ browser <id> type <selector> <text> Type text
258
+ browser <id> hover <selector> Hover element
259
+ browser <id> select <selector> <val> Select dropdown option
260
+ browser <id> press <key> Press keyboard key
261
+ browser <id> screenshot [selector] [-o <path>]
262
+ Take screenshot (JPEG, saved to /tmp)
263
+ Use -o for custom output path
264
+ browser <id> back Go back
265
+ browser <id> forward Go forward
266
+ browser <id> delete Delete session
267
+ browser -h, --help Show this help
268
+
269
+ Start daemon: browser-daemon
270
+ """)
271
+ return
272
+
273
+ asyncio.run(_main(args))
274
+
275
+
276
+ async def _main(args: list[str]):
277
+ cmd = args[0]
278
+
279
+ if cmd == "capture" and len(args) >= 2:
280
+ url = args[1]
281
+ full_page = True # Default to full page for better results
282
+ output = None
283
+
284
+ # Parse flags
285
+ i = 2
286
+ while i < len(args):
287
+ if args[i] in ("-f", "--full-page"):
288
+ full_page = True
289
+ i += 1
290
+ elif args[i] in ("-o", "--output") and i + 1 < len(args):
291
+ output = args[i + 1]
292
+ i += 2
293
+ else:
294
+ i += 1
295
+
296
+ await cmd_capture(url, full_page=full_page, output=output)
297
+ elif cmd == "install":
298
+ cmd_install()
299
+ elif cmd == "cleanup":
300
+ cmd_cleanup()
301
+ elif cmd == "create":
302
+ await cmd_create()
303
+ elif cmd == "list":
304
+ await cmd_list()
305
+ elif cmd == "delete" and len(args) >= 2:
306
+ await cmd_delete(args[1])
307
+ elif len(args) >= 2:
308
+ session_id = args[0]
309
+ action = args[1]
310
+
311
+ if action == "navigate" and len(args) >= 3:
312
+ await cmd_navigate(session_id, args[2])
313
+ elif action == "snapshot":
314
+ selector = args[2] if len(args) >= 3 else None
315
+ await cmd_snapshot(session_id, selector)
316
+ elif action == "click" and len(args) >= 3:
317
+ await cmd_click(session_id, args[2])
318
+ elif action == "type" and len(args) >= 4:
319
+ await cmd_type(session_id, args[2], args[3])
320
+ elif action == "hover" and len(args) >= 3:
321
+ await cmd_hover(session_id, args[2])
322
+ elif action == "select" and len(args) >= 4:
323
+ await cmd_select_option(session_id, args[2], args[3])
324
+ elif action == "press" and len(args) >= 3:
325
+ await cmd_press_key(session_id, args[2])
326
+ elif action == "screenshot":
327
+ selector = None
328
+ output = None
329
+ i = 2
330
+ while i < len(args):
331
+ if args[i] in ("-o", "--output") and i + 1 < len(args):
332
+ output = args[i + 1]
333
+ i += 2
334
+ elif args[i] and not args[i].startswith("-"):
335
+ selector = args[i]
336
+ i += 1
337
+ else:
338
+ i += 1
339
+ await cmd_screenshot(session_id, selector, output)
340
+ elif action == "back":
341
+ await cmd_go_back(session_id)
342
+ elif action == "forward":
343
+ await cmd_go_forward(session_id)
344
+ elif action == "delete":
345
+ await cmd_delete(session_id)
346
+ else:
347
+ print(f"Unknown action or missing args: {action}", file=sys.stderr)
348
+ sys.exit(1)
349
+ else:
350
+ print("Invalid command", file=sys.stderr)
351
+ sys.exit(1)
352
+
353
+
354
+ if __name__ == "__main__":
355
+ main()
daemon/browser.py ADDED
@@ -0,0 +1,236 @@
1
+ import base64
2
+ import logging
3
+ from typing import Any
4
+
5
+ from playwright.async_api import Page
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ async def navigate(page: Page, url: str) -> dict[str, Any]:
11
+ logger.debug(f"Navigating to {url}")
12
+ try:
13
+ await page.goto(url, wait_until="domcontentloaded", timeout=30000)
14
+ await page.wait_for_load_state("networkidle", timeout=10000)
15
+ return {
16
+ "success": True,
17
+ "url": page.url,
18
+ "title": await page.title(),
19
+ }
20
+ except Exception as e:
21
+ logger.error(f"Navigation failed: {e}")
22
+ return {"success": False, "error": str(e)}
23
+
24
+
25
+ async def snapshot(page: Page, selector: str | None = None) -> dict[str, Any]:
26
+ logger.debug(f"Taking snapshot (selector={selector})")
27
+ try:
28
+ # Use page.evaluate to get element data and page state
29
+ result = await page.evaluate("""(selector) => {
30
+ function getSelector(el) {
31
+ // Try to build a good CSS selector
32
+ if (el.id) return '#' + el.id;
33
+ if (el.name && ['input', 'select', 'textarea', 'button'].includes(el.tagName.toLowerCase())) {
34
+ return el.tagName.toLowerCase() + '[name="' + el.name + '"]';
35
+ }
36
+ if (el.getAttribute('data-testid')) return '[data-testid="' + el.getAttribute('data-testid') + '"]';
37
+
38
+ // Build class selector
39
+ const classes = Array.from(el.classList).filter(c => !c.match(/^[0-9]/)).slice(0, 2);
40
+ if (classes.length > 0) {
41
+ return el.tagName.toLowerCase() + '.' + classes.join('.');
42
+ }
43
+
44
+ // Text-based selector for clickable elements
45
+ const text = el.innerText?.trim();
46
+ if (text && text.length < 50 && ['a', 'button'].includes(el.tagName.toLowerCase())) {
47
+ return el.tagName.toLowerCase() + ':has-text("' + text.replace(/"/g, '\\"') + '")';
48
+ }
49
+
50
+ // nth-child fallback
51
+ const parent = el.parentElement;
52
+ if (parent) {
53
+ const siblings = Array.from(parent.children).filter(c => c.tagName === el.tagName);
54
+ if (siblings.length > 1) {
55
+ const index = siblings.indexOf(el) + 1;
56
+ return getSelector(parent) + ' > ' + el.tagName.toLowerCase() + ':nth-child(' + index + ')';
57
+ }
58
+ return getSelector(parent) + ' > ' + el.tagName.toLowerCase();
59
+ }
60
+ return el.tagName.toLowerCase();
61
+ }
62
+
63
+ const elements = selector
64
+ ? Array.from(document.querySelectorAll(selector))
65
+ : Array.from(document.body.querySelectorAll('*'));
66
+
67
+ const elementData = elements.slice(0, 100).map((el, i) => {
68
+ const tag = el.tagName.toLowerCase();
69
+ if (['script', 'style', 'meta', 'link', 'noscript'].includes(tag)) return null;
70
+
71
+ const text = (el.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 150);
72
+ const isInteractive = ['a', 'button', 'input', 'select', 'textarea'].includes(tag) ||
73
+ el.onclick || el.getAttribute('role') === 'button';
74
+
75
+ return {
76
+ ref: 'el_' + i,
77
+ tag: tag,
78
+ selector: getSelector(el),
79
+ text: text || null,
80
+ interactive: isInteractive,
81
+ href: el.href || null,
82
+ name: el.name || null,
83
+ placeholder: el.placeholder || null,
84
+ ariaLabel: el.getAttribute('aria-label') || null,
85
+ };
86
+ }).filter(Boolean);
87
+
88
+ return {
89
+ elements: elementData,
90
+ scrollY: window.scrollY,
91
+ viewportHeight: window.innerHeight,
92
+ documentHeight: document.documentElement.scrollHeight
93
+ };
94
+ }""", selector)
95
+
96
+ return {
97
+ "success": True,
98
+ "url": page.url,
99
+ "title": await page.title(),
100
+ "scrollY": result["scrollY"],
101
+ "viewportHeight": result["viewportHeight"],
102
+ "documentHeight": result["documentHeight"],
103
+ "elements": result["elements"]
104
+ }
105
+ except Exception as e:
106
+ logger.error(f"Snapshot failed: {e}")
107
+ return {"success": False, "error": str(e)}
108
+
109
+
110
+ async def click(page: Page, selector: str) -> dict[str, Any]:
111
+ logger.debug(f"Clicking {selector}")
112
+ try:
113
+ await page.click(selector, timeout=10000)
114
+ await page.wait_for_load_state("domcontentloaded", timeout=10000)
115
+ return {"success": True, "url": page.url, "title": await page.title()}
116
+ except Exception as e:
117
+ logger.error(f"Click failed: {e}")
118
+ return {"success": False, "error": str(e)}
119
+
120
+
121
+ async def type_text(page: Page, selector: str, text: str) -> dict[str, Any]:
122
+ logger.debug(f"Typing into {selector}")
123
+ try:
124
+ await page.fill(selector, text, timeout=10000)
125
+ return {"success": True}
126
+ except Exception as e:
127
+ logger.error(f"Type failed: {e}")
128
+ return {"success": False, "error": str(e)}
129
+
130
+
131
+ async def hover(page: Page, selector: str) -> dict[str, Any]:
132
+ logger.debug(f"Hovering {selector}")
133
+ try:
134
+ await page.hover(selector, timeout=10000)
135
+ return {"success": True}
136
+ except Exception as e:
137
+ logger.error(f"Hover failed: {e}")
138
+ return {"success": False, "error": str(e)}
139
+
140
+
141
+ async def select_option(page: Page, selector: str, value: str) -> dict[str, Any]:
142
+ logger.debug(f"Selecting {value} in {selector}")
143
+ try:
144
+ await page.select_option(selector, value, timeout=10000)
145
+ return {"success": True}
146
+ except Exception as e:
147
+ logger.error(f"Select failed: {e}")
148
+ return {"success": False, "error": str(e)}
149
+
150
+
151
+ async def press_key(page: Page, key: str) -> dict[str, Any]:
152
+ logger.debug(f"Pressing key {key}")
153
+ try:
154
+ await page.keyboard.press(key)
155
+ return {"success": True}
156
+ except Exception as e:
157
+ logger.error(f"Press failed: {e}")
158
+ return {"success": False, "error": str(e)}
159
+
160
+
161
+ async def screenshot(page: Page, selector: str | None = None, output: str | None = None) -> dict[str, Any]:
162
+ logger.debug(f"Taking screenshot (selector={selector})")
163
+ try:
164
+ from pathlib import Path
165
+ import time
166
+
167
+ if selector:
168
+ element = await page.query_selector(selector)
169
+ if element:
170
+ image_bytes = await element.screenshot(type="jpeg", quality=85)
171
+ else:
172
+ return {"success": False, "error": f"Element not found: {selector}"}
173
+ else:
174
+ image_bytes = await page.screenshot(type="jpeg", quality=85)
175
+
176
+ # Save to file
177
+ if output:
178
+ output_path = Path(output)
179
+ else:
180
+ timestamp = int(time.time())
181
+ filename = f"browser_screenshot_{timestamp}.jpg"
182
+ output_path = Path("/tmp") / filename
183
+
184
+ output_path.write_bytes(image_bytes)
185
+
186
+ return {"success": True, "path": str(output_path), "format": "jpeg"}
187
+ except Exception as e:
188
+ logger.error(f"Screenshot failed: {e}")
189
+ return {"success": False, "error": str(e)}
190
+
191
+
192
+ async def console_logs(page: Page) -> dict[str, Any]:
193
+ logger.debug("Getting console logs")
194
+ try:
195
+ logs = await page.evaluate("""() => {
196
+ return window.__browser_logs || [];
197
+ }""")
198
+ return {"success": True, "logs": logs}
199
+ except Exception as e:
200
+ logger.error(f"Console logs failed: {e}")
201
+ return {"success": False, "error": str(e)}
202
+
203
+
204
+ async def go_back(page: Page) -> dict[str, Any]:
205
+ logger.debug("Going back")
206
+ try:
207
+ await page.go_back(wait_until="domcontentloaded", timeout=15000)
208
+ return {"success": True, "url": page.url, "title": await page.title()}
209
+ except Exception as e:
210
+ logger.error(f"Go back failed: {e}")
211
+ return {"success": False, "error": str(e)}
212
+
213
+
214
+ async def go_forward(page: Page) -> dict[str, Any]:
215
+ logger.debug("Going forward")
216
+ try:
217
+ await page.go_forward(wait_until="domcontentloaded", timeout=15000)
218
+ return {"success": True, "url": page.url, "title": await page.title()}
219
+ except Exception as e:
220
+ logger.error(f"Go forward failed: {e}")
221
+ return {"success": False, "error": str(e)}
222
+
223
+
224
+ ACTIONS = {
225
+ "navigate": navigate,
226
+ "snapshot": snapshot,
227
+ "click": click,
228
+ "type": type_text,
229
+ "hover": hover,
230
+ "select_option": select_option,
231
+ "press_key": press_key,
232
+ "screenshot": screenshot,
233
+ "console_logs": console_logs,
234
+ "go_back": go_back,
235
+ "go_forward": go_forward,
236
+ }
daemon/server.py ADDED
@@ -0,0 +1,152 @@
1
+ import asyncio
2
+ import json
3
+ import logging
4
+ import os
5
+ import signal
6
+ from pathlib import Path
7
+
8
+ from playwright.async_api import async_playwright
9
+
10
+ from .browser import ACTIONS
11
+ from .session import SessionManager
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ SOCKET_PATH = Path.home() / ".browser-daemon" / "socket"
16
+
17
+
18
+ class Daemon:
19
+ def __init__(self):
20
+ self.sessions = SessionManager()
21
+ self.browser = None
22
+ self.browser_launcher = None
23
+ self.server = None
24
+ self._shutdown = asyncio.Event()
25
+
26
+ async def start(self):
27
+ logger.info("Starting browser daemon...")
28
+
29
+ os.makedirs(SOCKET_PATH.parent, exist_ok=True)
30
+
31
+ if SOCKET_PATH.exists():
32
+ SOCKET_PATH.unlink()
33
+
34
+ self.browser_launcher = await async_playwright().start()
35
+ self.browser = await self.browser_launcher.chromium.launch(
36
+ headless=False,
37
+ args=[
38
+ "--disable-dev-shm-usage",
39
+ "--no-sandbox",
40
+ "--disable-blink-features=AutomationControlled",
41
+ ],
42
+ )
43
+ logger.info(f"Browser launched, socket at {SOCKET_PATH}")
44
+
45
+ self.server = await asyncio.start_unix_server(
46
+ self.handle_client,
47
+ path=str(SOCKET_PATH),
48
+ )
49
+
50
+ logger.info("Daemon ready")
51
+
52
+ await self._shutdown.wait()
53
+
54
+ async def handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
55
+ try:
56
+ data = await reader.read(10 * 1024 * 1024) # 10MB max
57
+ if not data:
58
+ return
59
+
60
+ request = json.loads(data.decode())
61
+ logger.debug(f"Received: {request}")
62
+
63
+ response = await self.process(request)
64
+ writer.write(json.dumps(response).encode())
65
+ await writer.drain()
66
+ writer.close()
67
+ await writer.wait_closed()
68
+
69
+ except Exception as e:
70
+ logger.error(f"Client error: {e}")
71
+ try:
72
+ writer.write(json.dumps({"success": False, "error": str(e)}).encode())
73
+ await writer.drain()
74
+ writer.close()
75
+ except Exception:
76
+ pass
77
+
78
+ async def process(self, request: dict) -> dict:
79
+ action = request.get("action")
80
+ session_id = request.get("session_id")
81
+
82
+ if action == "create":
83
+ session = await self.sessions.create(self.browser)
84
+ return {"success": True, "session_id": session.id}
85
+
86
+ if action == "list":
87
+ sessions = await self.sessions.list()
88
+ return {"success": True, "sessions": sessions}
89
+
90
+ if action == "delete":
91
+ if not session_id:
92
+ return {"success": False, "error": "session_id required"}
93
+ deleted = await self.sessions.delete(session_id)
94
+ return {"success": deleted, "error": None if deleted else "Session not found"}
95
+
96
+ if not session_id:
97
+ return {"success": False, "error": "session_id required for this action"}
98
+
99
+ session = await self.sessions.get(session_id)
100
+ if not session:
101
+ return {"success": False, "error": f"Session {session_id} not found"}
102
+
103
+ if action not in ACTIONS:
104
+ return {"success": False, "error": f"Unknown action: {action}"}
105
+
106
+ handler = ACTIONS[action]
107
+ params = request.get("params", {})
108
+
109
+ return await handler(session.page, **params)
110
+
111
+ async def stop(self):
112
+ logger.info("Stopping daemon...")
113
+
114
+ if self.server:
115
+ self.server.close()
116
+ await self.server.wait_closed()
117
+
118
+ await self.sessions.close_all()
119
+
120
+ if self.browser:
121
+ await self.browser.close()
122
+
123
+ if self.browser_launcher:
124
+ await self.browser_launcher.stop()
125
+
126
+ if SOCKET_PATH.exists():
127
+ SOCKET_PATH.unlink()
128
+
129
+ self._shutdown.set()
130
+ logger.info("Daemon stopped")
131
+
132
+
133
+ def main():
134
+ logging.basicConfig(
135
+ level=logging.INFO,
136
+ format="%(asctime)s [%(levelname)s] %(message)s",
137
+ )
138
+
139
+ daemon = Daemon()
140
+ loop = asyncio.new_event_loop()
141
+
142
+ def signal_handler(sig, frame):
143
+ loop.create_task(daemon.stop())
144
+
145
+ signal.signal(signal.SIGINT, signal_handler)
146
+ signal.signal(signal.SIGTERM, signal_handler)
147
+
148
+ loop.run_until_complete(daemon.start())
149
+
150
+
151
+ if __name__ == "__main__":
152
+ main()
daemon/session.py ADDED
@@ -0,0 +1,91 @@
1
+ import asyncio
2
+ import logging
3
+ import time
4
+ import uuid
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ from playwright.async_api import Browser, BrowserContext, Page
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ @dataclass
14
+ class Session:
15
+ id: str
16
+ context: BrowserContext
17
+ page: Page
18
+ created_at: float = field(default_factory=time.time)
19
+
20
+ @property
21
+ def url(self) -> str:
22
+ return self.page.url
23
+
24
+
25
+ class SessionManager:
26
+ def __init__(self):
27
+ self._sessions: dict[str, Session] = {}
28
+ self._lock = asyncio.Lock()
29
+ logger.info("SessionManager initialized")
30
+
31
+ async def create(self, browser: Browser) -> Session:
32
+ async with self._lock:
33
+ session_id = uuid.uuid4().hex[:8]
34
+
35
+ # Set explicit desktop user agent
36
+ user_agent = (
37
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
38
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
39
+ "Chrome/123.0.0.0 Safari/537.36"
40
+ )
41
+
42
+ context = await browser.new_context(
43
+ viewport={"width": 1920, "height": 1080},
44
+ user_agent=user_agent,
45
+ )
46
+
47
+ # Hide navigator.webdriver to avoid automation detection
48
+ await context.add_init_script("""
49
+ Object.defineProperty(navigator, 'webdriver', {
50
+ get: () => undefined,
51
+ configurable: true
52
+ });
53
+ """)
54
+
55
+ page = await context.new_page()
56
+ await page.set_viewport_size({"width": 1920, "height": 1080})
57
+ session = Session(id=session_id, context=context, page=page)
58
+ self._sessions[session_id] = session
59
+ logger.info(f"Created session {session_id}")
60
+ return session
61
+
62
+ async def get(self, session_id: str) -> Session | None:
63
+ async with self._lock:
64
+ return self._sessions.get(session_id)
65
+
66
+ async def list(self) -> list[dict[str, Any]]:
67
+ async with self._lock:
68
+ result = []
69
+ for s in self._sessions.values():
70
+ result.append({
71
+ "session_id": s.id,
72
+ "url": s.url,
73
+ "title": await s.page.title(),
74
+ })
75
+ return result
76
+
77
+ async def delete(self, session_id: str) -> bool:
78
+ async with self._lock:
79
+ if session_id in self._sessions:
80
+ session = self._sessions.pop(session_id)
81
+ await session.context.close()
82
+ logger.info(f"Deleted session {session_id}")
83
+ return True
84
+ return False
85
+
86
+ async def close_all(self):
87
+ async with self._lock:
88
+ logger.info(f"Closing {len(self._sessions)} sessions")
89
+ for session in self._sessions.values():
90
+ await session.context.close()
91
+ self._sessions.clear()