From 73d2fe054f17de5e1cff9ce8ad95c096cc31109b Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Fri, 12 Jun 2026 16:56:07 +0100 Subject: [PATCH] refac --- cptr/app.py | 9 + cptr/frontend/src/lib/apis/admin.ts | 4 +- cptr/frontend/src/lib/components/Icon.svelte | 5 + .../lib/components/Settings/Browser.svelte | 254 ++++++++++++++ .../src/lib/components/SettingsModal.svelte | 5 + cptr/utils/browser/__init__.py | 1 + cptr/utils/browser/browser_use.py | 47 +++ cptr/utils/browser/cdp.py | 330 ++++++++++++++++++ cptr/utils/browser/firecrawl.py | 54 +++ cptr/utils/browser/launcher.py | 168 +++++++++ cptr/utils/browser/session.py | 88 +++++ cptr/utils/chat_task.py | 4 +- cptr/utils/tools.py | 181 +++++++++- 13 files changed, 1142 insertions(+), 8 deletions(-) create mode 100644 cptr/frontend/src/lib/components/Settings/Browser.svelte create mode 100644 cptr/utils/browser/__init__.py create mode 100644 cptr/utils/browser/browser_use.py create mode 100644 cptr/utils/browser/cdp.py create mode 100644 cptr/utils/browser/firecrawl.py create mode 100644 cptr/utils/browser/launcher.py create mode 100644 cptr/utils/browser/session.py diff --git a/cptr/app.py b/cptr/app.py index 4898808..53dbea3 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -69,6 +69,15 @@ async def shutdown(): bot_manager = getattr(app.state, "bot_manager", None) if bot_manager: await bot_manager.stop_all() + # Clean up browser sessions and launched Chrome + try: + from cptr.utils.browser.session import session_manager + from cptr.utils.browser.launcher import shutdown_browser + + await session_manager.close_all() + await shutdown_browser() + except Exception: + pass # Auth middleware diff --git a/cptr/frontend/src/lib/apis/admin.ts b/cptr/frontend/src/lib/apis/admin.ts index 10de548..c6243fb 100644 --- a/cptr/frontend/src/lib/apis/admin.ts +++ b/cptr/frontend/src/lib/apis/admin.ts @@ -54,8 +54,8 @@ export const getAdminConfig = async (): Promise> => { export const updateConfig = (config: Record) => fetchJSON('/api/admin/config', { - method: 'PUT', - ...jsonBody({ config }) + ...jsonBody({ config }), + method: 'PUT' }); // ── Connections ───────────────────────────────────────────── diff --git a/cptr/frontend/src/lib/components/Icon.svelte b/cptr/frontend/src/lib/components/Icon.svelte index fd661f1..71b7c15 100644 --- a/cptr/frontend/src/lib/components/Icon.svelte +++ b/cptr/frontend/src/lib/components/Icon.svelte @@ -333,5 +333,10 @@ {:else if name === 'signal'} + {:else if name === 'browser'} + + + + {/if} diff --git a/cptr/frontend/src/lib/components/Settings/Browser.svelte b/cptr/frontend/src/lib/components/Settings/Browser.svelte new file mode 100644 index 0000000..15a6905 --- /dev/null +++ b/cptr/frontend/src/lib/components/Settings/Browser.svelte @@ -0,0 +1,254 @@ + + +
+

Browser

+ + {#if loading} +
+ {:else} + +

Enable

+ +
+ +

+ Give the AI access to a web browser for navigating pages, clicking elements, and taking screenshots. +

+
+ + {#if enabled} + +

Provider

+ +
+ {#each [ + { value: 'local' as const, label: 'Local CDP' }, + { value: 'firecrawl' as const, label: 'Firecrawl' }, + { value: 'browser_use' as const, label: 'Browser-Use' } + ] as opt} + + {/each} +
+

+ {#if provider === 'local'} + Connects to Chrome via DevTools Protocol. Full interactive browsing with clicking, typing, and screenshots. + {:else if provider === 'firecrawl'} + Cloud API that converts web pages to markdown. Fast extraction, no interactive browsing. + {:else} + Cloud API for LLM-driven browser tasks. Describe what you need in natural language. + {/if} +

+ + + {#if provider === 'local'} +

Connection

+ +
+ + +
+ +
+ + +
+ {#if testResult} +

+ {testResult.message} +

+ {/if} +
+ +
+ +
+ + minutes +
+
+
+ {/if} + + + {#if provider === 'firecrawl'} +

Firecrawl

+ +
+
+ + +
+
+ + +

Change for self-hosted Firecrawl instances

+
+
+ {/if} + + + {#if provider === 'browser_use'} +

Browser-Use

+ +
+
+ + +
+
+ + +
+
+ {/if} + {/if} + + +
+ +
+ {/if} +
diff --git a/cptr/frontend/src/lib/components/SettingsModal.svelte b/cptr/frontend/src/lib/components/SettingsModal.svelte index a5de3f1..4dc97fa 100644 --- a/cptr/frontend/src/lib/components/SettingsModal.svelte +++ b/cptr/frontend/src/lib/components/SettingsModal.svelte @@ -4,6 +4,7 @@ import General from './Settings/General.svelte'; import Account from './Settings/Account.svelte'; import Keyboard from './Settings/Keyboard.svelte'; + import Browser from './Settings/Browser.svelte'; import About from './Settings/About.svelte'; import Users from './Admin/Users.svelte'; import Connections from './Admin/Connections.svelte'; @@ -16,6 +17,7 @@ type Tab = | 'general' | 'keyboard' + | 'browser' | 'account' | 'about' | 'users' @@ -47,6 +49,7 @@ { id: 'connections', label: $t('admin.connections'), icon: 'plug' }, { id: 'models', label: $t('admin.models'), icon: 'cube' }, { id: 'messaging', label: $t('admin.messaging'), icon: 'chat-bubble' }, + { id: 'browser', label: 'Browser', icon: 'browser' }, { id: 'admin_settings', label: $t('settings.configuration'), icon: 'shield' } ]); @@ -106,6 +109,8 @@ {:else if activeTab === 'keyboard'} + {:else if activeTab === 'browser'} + {:else if activeTab === 'account'} {:else if activeTab === 'about'} diff --git a/cptr/utils/browser/__init__.py b/cptr/utils/browser/__init__.py new file mode 100644 index 0000000..defe8f9 --- /dev/null +++ b/cptr/utils/browser/__init__.py @@ -0,0 +1 @@ +"""Browser automation package — pluggable providers behind unified tool interface.""" diff --git a/cptr/utils/browser/browser_use.py b/cptr/utils/browser/browser_use.py new file mode 100644 index 0000000..1c4c439 --- /dev/null +++ b/cptr/utils/browser/browser_use.py @@ -0,0 +1,47 @@ +"""Browser-Use cloud provider — LLM-driven browser tasks via REST API. + +Pure httpx, no SDK dependency. +""" + +from __future__ import annotations + +import logging + +import httpx + +logger = logging.getLogger(__name__) + +DEFAULT_BASE_URL = "https://api.browser-use.com" + + +async def browse( + task: str, + api_key: str, + base_url: str = DEFAULT_BASE_URL, +) -> str: + """Run a natural language browser task and return the result. + + Uses POST /v1/run. + """ + headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"} + payload = {"task": task} + + async with httpx.AsyncClient(timeout=120) as http: + resp = await http.post( + f"{base_url.rstrip('/')}/v1/run", + json=payload, + headers=headers, + ) + resp.raise_for_status() + data = resp.json() + + result = data.get("result", data.get("output", "")) + + if not result: + return f"Browser-Use returned no result for task: {task}" + + # Trim if needed + if isinstance(result, str) and len(result) > 50_000: + result = result[:50_000] + "\n\n[... truncated]" + + return str(result) diff --git a/cptr/utils/browser/cdp.py b/cptr/utils/browser/cdp.py new file mode 100644 index 0000000..2c49056 --- /dev/null +++ b/cptr/utils/browser/cdp.py @@ -0,0 +1,330 @@ +"""Chrome DevTools Protocol client over WebSocket. + +Connects to a running Chrome/Chromium instance via CDP and provides methods for +navigation, accessibility tree snapshots with ref IDs, clicking, typing, +screenshots, and JS evaluation. Zero external dependencies beyond websockets. +""" + +from __future__ import annotations + +import asyncio +import base64 +import json +import logging +from typing import Any + +import websockets + +logger = logging.getLogger(__name__) + +# Ref ID prefix used in accessibility tree snapshots +_REF_PREFIX = "@e" + + +class CDPClient: + """Low-level Chrome DevTools Protocol client.""" + + def __init__(self, ws: Any, target_id: str) -> None: + self._ws = ws + self._target_id = target_id + self._msg_id = 0 + self._ref_map: dict[str, int] = {} # ref_id -> backend_node_id + self._closed = False + + # ── Connection ───────────────────────────────────────── + + @classmethod + async def connect(cls, cdp_url: str = "http://localhost:9222") -> "CDPClient": + """Connect to a Chrome instance via CDP. + + Discovers the WebSocket debug URL from the /json/version endpoint, + then opens a WebSocket connection to the first available page target. + """ + import httpx + + base = cdp_url.rstrip("/") + + # Get available targets (pages/tabs) + async with httpx.AsyncClient() as http: + resp = await http.get(f"{base}/json/list", timeout=5) + targets = resp.json() + + # Find a page target, or create one + page_target = None + for t in targets: + if t.get("type") == "page": + page_target = t + break + + if not page_target: + # Create a new tab + async with httpx.AsyncClient() as http: + resp = await http.put(f"{base}/json/new?about:blank", timeout=5) + page_target = resp.json() + + ws_url = page_target["webSocketDebuggerUrl"] + target_id = page_target["id"] + + ws = await websockets.connect(ws_url, max_size=50 * 1024 * 1024) + + client = cls(ws, target_id) + + # Enable required domains + await client._send("Page.enable") + await client._send("DOM.enable") + await client._send("Accessibility.enable") + await client._send("Runtime.enable") + + return client + + # ── Low-level CDP messaging ──────────────────────────── + + async def _send(self, method: str, params: dict | None = None) -> dict: + """Send a CDP command and wait for the result.""" + self._msg_id += 1 + msg_id = self._msg_id + payload = {"id": msg_id, "method": method} + if params: + payload["params"] = params + + await self._ws.send(json.dumps(payload)) + + # Wait for matching response (skip events) + while True: + raw = await asyncio.wait_for(self._ws.recv(), timeout=30) + data = json.loads(raw) + if data.get("id") == msg_id: + if "error" in data: + raise RuntimeError(f"CDP error: {data['error'].get('message', data['error'])}") + return data.get("result", {}) + # Ignore events (no "id" field) + + # ── Navigation ───────────────────────────────────────── + + async def navigate(self, url: str) -> dict: + """Navigate to a URL and wait for the page to load.""" + result = await self._send("Page.navigate", {"url": url}) + + # Wait for load event + while True: + raw = await asyncio.wait_for(self._ws.recv(), timeout=30) + data = json.loads(raw) + if data.get("method") == "Page.loadEventFired": + break + + # Small delay for DOM to settle + await asyncio.sleep(0.5) + + # Get page title + title_result = await self._send( + "Runtime.evaluate", {"expression": "document.title"} + ) + title = title_result.get("result", {}).get("value", "") + + return {"url": url, "title": title, "frame_id": result.get("frameId")} + + # ── Accessibility tree snapshot ──────────────────────── + + async def snapshot(self) -> str: + """Capture the accessibility tree and return a text representation with ref IDs. + + Interactive elements (links, buttons, inputs, etc.) are assigned ref IDs + like @e1, @e2 that can be used with click() and type_text(). + """ + result = await self._send("Accessibility.getFullAXTree") + nodes = result.get("nodes", []) + + self._ref_map.clear() + ref_counter = 0 + lines: list[str] = [] + + # Interactive roles that get ref IDs + interactive_roles = { + "link", "button", "textbox", "searchbox", "combobox", + "checkbox", "radio", "tab", "menuitem", "option", + "switch", "slider", "spinbutton", "textfield", + } + + for node in nodes: + role_data = node.get("role", {}) + role = role_data.get("value", "") if isinstance(role_data, dict) else str(role_data) + if not role or role in ("none", "generic", "InlineTextBox", "StaticText"): + continue + + name_data = node.get("name", {}) + name = name_data.get("value", "") if isinstance(name_data, dict) else str(name_data) + if not name and role not in interactive_roles: + continue + + # Build indent based on depth (simplified: flat for now) + depth = 0 + for prop in node.get("properties", []): + if isinstance(prop, dict) and prop.get("name") == "level": + depth = int(prop.get("value", {}).get("value", 0)) + break + + indent = " " * min(depth, 4) + + # Assign ref ID to interactive elements + ref_label = "" + if role.lower() in interactive_roles: + ref_counter += 1 + ref_id = f"{_REF_PREFIX}{ref_counter}" + backend_node_id = node.get("backendDOMNodeId") + if backend_node_id: + self._ref_map[ref_id] = backend_node_id + ref_label = f" {ref_id}" + + # Format: [role @ref] Name + display_name = f" {name}" if name else "" + lines.append(f"{indent}[{role}{ref_label}]{display_name}") + + if not lines: + return "[empty page]" + + return "\n".join(lines) + + # ── Interaction ──────────────────────────────────────── + + async def click(self, ref: str) -> None: + """Click an element identified by its ref ID from the latest snapshot.""" + ref = ref.strip() + if not ref.startswith(_REF_PREFIX): + ref = f"{_REF_PREFIX}{ref}" + + backend_node_id = self._ref_map.get(ref) + if not backend_node_id: + raise ValueError(f"Unknown ref '{ref}'. Run browser_snapshot() first to get valid ref IDs.") + + # Resolve to a remote object + result = await self._send( + "DOM.resolveNode", {"backendNodeId": backend_node_id} + ) + object_id = result.get("object", {}).get("objectId") + if not object_id: + raise RuntimeError(f"Could not resolve element for ref {ref}") + + # Scroll into view + try: + await self._send( + "DOM.scrollIntoViewIfNeeded", {"backendNodeId": backend_node_id} + ) + except RuntimeError: + pass + + # Get box model for click coordinates + try: + box = await self._send( + "DOM.getBoxModel", {"backendNodeId": backend_node_id} + ) + content = box.get("model", {}).get("content", []) + if len(content) >= 4: + x = (content[0] + content[2]) / 2 + y = (content[1] + content[5]) / 2 + else: + x, y = 0, 0 + except RuntimeError: + # Fallback: use JS click + await self._send( + "Runtime.callFunctionOn", + {"objectId": object_id, "functionDeclaration": "function() { this.click(); }"}, + ) + return + + # Dispatch mouse events + for event_type in ("mousePressed", "mouseReleased"): + await self._send( + "Input.dispatchMouseEvent", + { + "type": event_type, + "x": x, + "y": y, + "button": "left", + "clickCount": 1, + }, + ) + + # Wait for potential navigation + await asyncio.sleep(0.3) + + async def type_text(self, ref: str, text: str) -> None: + """Type text into an element identified by its ref ID.""" + # Focus the element first + ref = ref.strip() + if not ref.startswith(_REF_PREFIX): + ref = f"{_REF_PREFIX}{ref}" + + backend_node_id = self._ref_map.get(ref) + if not backend_node_id: + raise ValueError(f"Unknown ref '{ref}'. Run browser_snapshot() first.") + + await self._send("DOM.focus", {"backendNodeId": backend_node_id}) + + # Clear existing content + await self._send( + "Input.dispatchKeyEvent", + {"type": "keyDown", "key": "a", "modifiers": 2}, # Ctrl+A / Cmd+A + ) + await self._send( + "Input.dispatchKeyEvent", + {"type": "keyUp", "key": "a", "modifiers": 2}, + ) + + # Type each character + for char in text: + await self._send( + "Input.dispatchKeyEvent", + {"type": "keyDown", "key": char, "text": char}, + ) + await self._send( + "Input.dispatchKeyEvent", + {"type": "keyUp", "key": char}, + ) + + async def scroll(self, direction: str = "down", amount: int = 3) -> None: + """Scroll the page. Direction: 'up' or 'down'.""" + delta_y = 300 * amount * (1 if direction == "down" else -1) + await self._send( + "Input.dispatchMouseEvent", + {"type": "mouseWheel", "x": 400, "y": 400, "deltaX": 0, "deltaY": delta_y}, + ) + await asyncio.sleep(0.3) + + # ── Observation ──────────────────────────────────────── + + async def screenshot(self) -> bytes: + """Capture a screenshot of the current viewport. Returns PNG bytes.""" + result = await self._send( + "Page.captureScreenshot", {"format": "png", "quality": 80} + ) + return base64.b64decode(result["data"]) + + async def get_text(self) -> str: + """Extract visible text content from the page.""" + result = await self._send( + "Runtime.evaluate", + {"expression": "document.body?.innerText || ''"}, + ) + return result.get("result", {}).get("value", "") + + async def evaluate(self, expression: str) -> str: + """Evaluate a JavaScript expression and return the result.""" + result = await self._send( + "Runtime.evaluate", + {"expression": expression, "returnByValue": True}, + ) + value = result.get("result", {}) + if value.get("type") == "undefined": + return "undefined" + return str(value.get("value", value.get("description", ""))) + + # ── Lifecycle ────────────────────────────────────────── + + async def close(self) -> None: + """Close the CDP connection.""" + if not self._closed: + self._closed = True + try: + await self._ws.close() + except Exception: + pass diff --git a/cptr/utils/browser/firecrawl.py b/cptr/utils/browser/firecrawl.py new file mode 100644 index 0000000..c259bd4 --- /dev/null +++ b/cptr/utils/browser/firecrawl.py @@ -0,0 +1,54 @@ +"""Firecrawl browser provider — page-to-markdown via REST API. + +Pure httpx, no SDK dependency. Supports both cloud (api.firecrawl.dev) and +self-hosted instances. +""" + +from __future__ import annotations + +import logging + +import httpx + +logger = logging.getLogger(__name__) + +DEFAULT_BASE_URL = "https://api.firecrawl.dev" + + +async def scrape( + url: str, + api_key: str, + base_url: str = DEFAULT_BASE_URL, + format: str = "markdown", +) -> str: + """Scrape a single page and return content as markdown. + + Uses POST /v1/scrape. + """ + headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"} + payload = {"url": url, "formats": [format]} + + async with httpx.AsyncClient(timeout=30) as http: + resp = await http.post( + f"{base_url.rstrip('/')}/v1/scrape", + json=payload, + headers=headers, + ) + resp.raise_for_status() + data = resp.json() + + if not data.get("success"): + error = data.get("error", "Unknown error") + return f"Firecrawl error: {error}" + + result = data.get("data", {}) + content = result.get(format, result.get("markdown", "")) + + if not content: + return f"Firecrawl returned empty content for {url}" + + # Trim to reasonable size for LLM context + if len(content) > 50_000: + content = content[:50_000] + "\n\n[... truncated]" + + return content diff --git a/cptr/utils/browser/launcher.py b/cptr/utils/browser/launcher.py new file mode 100644 index 0000000..d3354e8 --- /dev/null +++ b/cptr/utils/browser/launcher.py @@ -0,0 +1,168 @@ +"""Chrome/Chromium discovery and auto-launch. + +Finds a running Chrome instance or launches one headless with a debug port. +Supports macOS and Linux. Called automatically when browser tools are invoked. +""" + +from __future__ import annotations + +import asyncio +import logging +import os +import shutil +import tempfile +from pathlib import Path + +logger = logging.getLogger(__name__) + +# Common Chrome/Chromium binary paths by platform +_CHROME_PATHS_MACOS = [ + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Chromium.app/Contents/MacOS/Chromium", + "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser", + "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", +] + +_CHROME_PATHS_LINUX = [ + "google-chrome", + "google-chrome-stable", + "chromium", + "chromium-browser", + "brave-browser", + "microsoft-edge", +] + +# Track launched process so we can kill it on shutdown +_launched_process: asyncio.subprocess.Process | None = None +_user_data_dir: str | None = None + + +def _find_chrome() -> str | None: + """Find a Chrome/Chromium binary on this system.""" + import platform + + if platform.system() == "Darwin": + for path in _CHROME_PATHS_MACOS: + if Path(path).exists(): + return path + # Also check PATH + for name in ("google-chrome", "chromium"): + found = shutil.which(name) + if found: + return found + else: + # Linux / other + for name in _CHROME_PATHS_LINUX: + found = shutil.which(name) + if found: + return found + + return None + + +async def _probe_cdp(base_url: str) -> bool: + """Check if a CDP endpoint is responding.""" + import httpx + + try: + async with httpx.AsyncClient() as http: + resp = await http.get(f"{base_url}/json/version", timeout=3) + data = resp.json() + logger.info( + "Found Chrome %s at %s", + data.get("Browser", "unknown"), + base_url, + ) + return True + except Exception: + return False + + +async def ensure_browser(port: int = 9222) -> str: + """Ensure a Chrome instance is available for CDP connection. + + 1. Check if CDP is already available at the configured URL + 2. If not, find and launch Chrome/Chromium headless + 3. Return the CDP base URL + + Called automatically when any browser tool is invoked. + """ + global _launched_process, _user_data_dir + + base_url = f"http://localhost:{port}" + + # 1. Check if already running + if await _probe_cdp(base_url): + return base_url + + # 2. Find Chrome binary + chrome_path = _find_chrome() + if not chrome_path: + raise RuntimeError( + "No Chrome or Chromium found. Install Google Chrome, Chromium, or Brave, " + "or set browser.cdp_url to point to a running instance." + ) + + # 3. Launch headless with debug port + _user_data_dir = tempfile.mkdtemp(prefix="cptr-browser-") + + args = [ + chrome_path, + f"--remote-debugging-port={port}", + "--headless=new", + "--no-first-run", + "--no-default-browser-check", + "--disable-background-networking", + "--disable-sync", + "--disable-translate", + "--disable-extensions", + f"--user-data-dir={_user_data_dir}", + "about:blank", + ] + + logger.info("Launching Chrome: %s", " ".join(args[:3])) + + _launched_process = await asyncio.create_subprocess_exec( + *args, + stdout=asyncio.subprocess.DEVNULL, + stderr=asyncio.subprocess.DEVNULL, + ) + + # Wait for CDP to become available + for _ in range(20): + await asyncio.sleep(0.5) + if await _probe_cdp(base_url): + logger.info("Chrome launched successfully on port %d", port) + return base_url + + raise RuntimeError( + f"Chrome launched but CDP not responding on port {port} after 10s. " + f"Binary: {chrome_path}" + ) + + +async def shutdown_browser() -> None: + """Kill the Chrome process we launched (if any). Called on app shutdown.""" + global _launched_process, _user_data_dir + + if _launched_process and _launched_process.returncode is None: + logger.info("Shutting down launched Chrome (pid %d)", _launched_process.pid) + try: + _launched_process.terminate() + await asyncio.wait_for(_launched_process.wait(), timeout=5) + except (asyncio.TimeoutError, ProcessLookupError): + try: + _launched_process.kill() + except ProcessLookupError: + pass + _launched_process = None + + # Clean up temp profile + if _user_data_dir: + import shutil as sh + + try: + sh.rmtree(_user_data_dir, ignore_errors=True) + except Exception: + pass + _user_data_dir = None diff --git a/cptr/utils/browser/session.py b/cptr/utils/browser/session.py new file mode 100644 index 0000000..b30a4bc --- /dev/null +++ b/cptr/utils/browser/session.py @@ -0,0 +1,88 @@ +"""Per-chat browser session manager. + +Maintains one CDPClient per chat so the AI can do multi-step browser flows +(navigate -> snapshot -> click -> type -> snapshot) without losing state. +Sessions auto-close after an idle timeout. +""" + +from __future__ import annotations + +import asyncio +import logging +import time + +from cptr.utils.browser.cdp import CDPClient + +logger = logging.getLogger(__name__) + +DEFAULT_TIMEOUT_MINUTES = 10 + + +class BrowserSessionManager: + """One browser session per chat, with idle timeout cleanup.""" + + def __init__(self) -> None: + self._sessions: dict[str, CDPClient] = {} + self._last_used: dict[str, float] = {} + self._cleanup_task: asyncio.Task | None = None + self._timeout_minutes = DEFAULT_TIMEOUT_MINUTES + + def set_timeout(self, minutes: int) -> None: + self._timeout_minutes = max(1, minutes) + + async def get_or_create(self, chat_id: str, cdp_url: str) -> CDPClient: + """Get an existing session for this chat, or create a new one.""" + if chat_id in self._sessions: + client = self._sessions[chat_id] + if not client._closed: + self._last_used[chat_id] = time.monotonic() + return client + # Session was closed externally, remove it + del self._sessions[chat_id] + self._last_used.pop(chat_id, None) + + # Create new session + client = await CDPClient.connect(cdp_url) + self._sessions[chat_id] = client + self._last_used[chat_id] = time.monotonic() + + # Start cleanup loop if not running + if self._cleanup_task is None or self._cleanup_task.done(): + self._cleanup_task = asyncio.create_task(self._cleanup_loop()) + + logger.info("Browser session created for chat %s", chat_id[:8]) + return client + + async def close(self, chat_id: str) -> None: + """Close and remove a specific chat's session.""" + client = self._sessions.pop(chat_id, None) + self._last_used.pop(chat_id, None) + if client: + await client.close() + logger.info("Browser session closed for chat %s", chat_id[:8]) + + async def close_all(self) -> None: + """Close all sessions. Called on app shutdown.""" + if self._cleanup_task and not self._cleanup_task.done(): + self._cleanup_task.cancel() + for chat_id in list(self._sessions): + await self.close(chat_id) + + async def _cleanup_loop(self) -> None: + """Periodically close idle sessions.""" + while self._sessions: + await asyncio.sleep(60) # Check every minute + now = time.monotonic() + timeout_seconds = self._timeout_minutes * 60 + expired = [ + cid + for cid, last in self._last_used.items() + if now - last > timeout_seconds + ] + for chat_id in expired: + logger.info("Browser session timed out for chat %s", chat_id[:8]) + await self.close(chat_id) + + +# Singleton instance +session_manager = BrowserSessionManager() diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 74d02c6..e45930d 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -798,7 +798,7 @@ async def run_chat_task( system += f"\n\n[CONVERSATION SUMMARY]\n{loaded_summary}" if regeneration_prompt: messages.append({"role": "user", "content": regeneration_prompt}) - tools = get_tool_list() + tools = await get_tool_list() # Remove view_skill tool if no skills are available skills = discover_skills(workspace) @@ -955,7 +955,7 @@ async def run_chat_task( if name == "create_artifact": result = await create_artifact(**event["arguments"], workspace=workspace) else: - result = await execute_tool(name, event["arguments"], {"workspace": workspace, "user_id": user_id, "model_id": model}) + result = await execute_tool(name, event["arguments"], {"workspace": workspace, "user_id": user_id, "model_id": model, "chat_id": chat_id}) # Update status to completed item["status"] = "completed" diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index bce8ff6..eb2e03f 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -939,6 +939,158 @@ async def view_skill( return format_skill_content(skill) +# ── Browser tools ──────────────────────────────────────────── + + +async def _get_browser_config() -> dict: + """Read browser config from DB.""" + try: + from cptr.models import Config + + return { + "enabled": await Config.get("browser.enabled") or False, + "provider": await Config.get("browser.provider") or "local", + "cdp_url": await Config.get("browser.cdp_url") or "http://localhost:9222", + "auto_launch": await Config.get("browser.auto_launch") if await Config.get("browser.auto_launch") is not None else True, + "session_timeout": int(await Config.get("browser.session_timeout_minutes") or 10), + "firecrawl_api_key": await Config.get("browser.firecrawl_api_key") or "", + "firecrawl_base_url": await Config.get("browser.firecrawl_base_url") or "https://api.firecrawl.dev", + "browser_use_api_key": await Config.get("browser.browser_use_api_key") or "", + "browser_use_base_url": await Config.get("browser.browser_use_base_url") or "https://api.browser-use.com", + } + except Exception: + return {"enabled": False, "provider": "local"} + + +async def _get_cdp_session(chat_id: str) -> "CDPClient": + """Get or create a CDP session for the current chat.""" + cfg = await _get_browser_config() + cdp_url = cfg["cdp_url"] + + if cfg.get("auto_launch", True): + from cptr.utils.browser.launcher import ensure_browser + + cdp_url = await ensure_browser(port=int(cdp_url.split(":")[-1])) + + from cptr.utils.browser.session import session_manager + + session_manager.set_timeout(cfg.get("session_timeout", 10)) + return await session_manager.get_or_create(chat_id, cdp_url) + + +async def browser_navigate(url: str, *, __context__: dict) -> str: + """Navigate to a URL in the browser. Returns the page title and status. + :param url: The URL to navigate to. + """ + cfg = await _get_browser_config() + provider = cfg.get("provider", "local") + + if provider == "firecrawl": + key = cfg.get("firecrawl_api_key", "") + if not key: + return "Error: Firecrawl API key not configured. Set it in Settings > Browser." + from cptr.utils.browser.firecrawl import scrape + + content = await scrape(url, key, cfg.get("firecrawl_base_url", "")) + return f"Navigated to {url} (via Firecrawl)\n\n{content}" + + if provider == "browser_use": + key = cfg.get("browser_use_api_key", "") + if not key: + return "Error: Browser-Use API key not configured. Set it in Settings > Browser." + from cptr.utils.browser.browser_use import browse + + result = await browse(f"Navigate to {url} and describe what you see", key, cfg.get("browser_use_base_url", "")) + return f"Navigated to {url} (via Browser-Use)\n\n{result}" + + # Local CDP + chat_id = __context__.get("chat_id", "default") + client = await _get_cdp_session(chat_id) + result = await client.navigate(url) + return f"Navigated to {url}\nTitle: {result.get('title', '')}" + + +async def browser_snapshot(*, __context__: dict) -> str: + """Get the current page content. For local browser, returns an accessibility tree with ref IDs (@e1, @e2, etc.) that can be used with browser_click and browser_type. For cloud providers, returns page content as text.""" + cfg = await _get_browser_config() + provider = cfg.get("provider", "local") + + if provider in ("firecrawl", "browser_use"): + return "Snapshot is only meaningful after browser_navigate. The navigate result already contains the page content." + + chat_id = __context__.get("chat_id", "default") + client = await _get_cdp_session(chat_id) + return await client.snapshot() + + +async def browser_click(ref: str, *, __context__: dict) -> str: + """Click an element on the page identified by its ref ID from the snapshot (e.g. @e1). + :param ref: The ref ID of the element to click (e.g. @e1, @e5). + """ + cfg = await _get_browser_config() + if cfg.get("provider", "local") != "local": + return "Error: browser_click requires Local CDP provider. Cloud providers (Firecrawl, Browser-Use) don't support interactive browsing. Switch to Local CDP in Settings > Browser." + + chat_id = __context__.get("chat_id", "default") + client = await _get_cdp_session(chat_id) + await client.click(ref) + # Return updated snapshot so the AI sees the result + return await client.snapshot() + + +async def browser_type(ref: str, text: str, *, __context__: dict) -> str: + """Type text into an input element identified by its ref ID from the snapshot. + :param ref: The ref ID of the input element (e.g. @e3). + :param text: The text to type. + """ + cfg = await _get_browser_config() + if cfg.get("provider", "local") != "local": + return "Error: browser_type requires Local CDP provider. Switch to Local CDP in Settings > Browser." + + chat_id = __context__.get("chat_id", "default") + client = await _get_cdp_session(chat_id) + await client.type_text(ref, text) + return await client.snapshot() + + +async def browser_screenshot(*, __context__: dict) -> str: + """Take a screenshot of the current browser page. Saves the image to the workspace. + """ + cfg = await _get_browser_config() + if cfg.get("provider", "local") != "local": + return "Error: browser_screenshot requires Local CDP provider." + + chat_id = __context__.get("chat_id", "default") + client = await _get_cdp_session(chat_id) + png_bytes = await client.screenshot() + + # Save to workspace + workspace = __context__.get("workspace", ".") + screenshots_dir = Path(workspace) / ".cptr" / "screenshots" + screenshots_dir.mkdir(parents=True, exist_ok=True) + + import time + + filename = f"screenshot_{int(time.time())}.png" + filepath = screenshots_dir / filename + filepath.write_bytes(png_bytes) + + return f"Screenshot saved: {filepath}" + + +async def browser_evaluate(javascript: str, *, __context__: dict) -> str: + """Execute JavaScript in the browser page and return the result. + :param javascript: The JavaScript expression to evaluate. + """ + cfg = await _get_browser_config() + if cfg.get("provider", "local") != "local": + return "Error: browser_evaluate requires Local CDP provider." + + chat_id = __context__.get("chat_id", "default") + client = await _get_cdp_session(chat_id) + return await client.evaluate(javascript) + + # ── Registry ──────────────────────────────────────────────── TOOLS: dict[str, dict] = { @@ -964,6 +1116,16 @@ TOOLS: dict[str, dict] = { "delete_automation": {"fn": delete_automation, "auto": False}, } +# Browser tools — registered conditionally based on browser.enabled config +BROWSER_TOOLS: dict[str, dict] = { + "browser_navigate": {"fn": browser_navigate, "auto": False}, + "browser_snapshot": {"fn": browser_snapshot, "auto": True}, + "browser_click": {"fn": browser_click, "auto": False}, + "browser_type": {"fn": browser_type, "auto": False}, + "browser_screenshot": {"fn": browser_screenshot, "auto": True}, + "browser_evaluate": {"fn": browser_evaluate, "auto": False}, +} + # ── Schema from function signature ────────────────────────── @@ -1017,14 +1179,25 @@ def _fn_to_schema(name: str, fn) -> dict: } -def get_tool_list() -> list[dict]: - """Return tool schemas for the LLM.""" - return [_fn_to_schema(name, t["fn"]) for name, t in TOOLS.items()] +async def get_tool_list() -> list[dict]: + """Return tool schemas for the LLM. + + Automatically includes browser tools when browser.enabled is true in config. + """ + tools = dict(TOOLS) + try: + from cptr.models import Config + + if (await Config.get("browser.enabled")) in (True, "true", "1"): + tools.update(BROWSER_TOOLS) + except Exception: + pass + return [_fn_to_schema(name, t["fn"]) for name, t in tools.items()] async def execute_tool(name: str, args: dict, __context__: dict) -> str: """Execute a tool by name, injecting execution context.""" - info = TOOLS.get(name) + info = TOOLS.get(name) or BROWSER_TOOLS.get(name) if not info: return f"Error: unknown tool: {name}" fn = info["fn"]