""" Chrome DevTools Protocol (CDP) Client & DeepSeek Web Controller. Interacts directly with Chromium browser instance running on port 9222. """ import asyncio import json import os import subprocess import time import urllib.request import websockets CDP_PORT = 9222 CHROMIUM_PATH = "/home/adi/.cache/ms-playwright/chromium-1228/chrome-linux64/chrome" PROFILE_DIR = "/home/adi/.config/chromium_monitor_profile" def ensure_chromium_running(): """ Ensures Chromium is running on remote debugging port 9222. If not, launches it in background with DISPLAY=:0.0. """ try: req = urllib.request.urlopen(f"http://127.0.0.1:{CDP_PORT}/json", timeout=2) tabs = json.loads(req.read().decode("utf-8")) if tabs: return tabs except Exception: pass print(f"⚡ Launching Chromium on remote debugging port {CDP_PORT}...") env = os.environ.copy() env["DISPLAY"] = env.get("DISPLAY", ":0.0") subprocess.Popen([ CHROMIUM_PATH, f"--remote-debugging-port={CDP_PORT}", "--no-first-run", "--no-default-browser-check", f"--user-data-dir={PROFILE_DIR}", "https://chat.deepseek.com" ], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for i in range(15): time.sleep(1) try: req = urllib.request.urlopen(f"http://127.0.0.1:{CDP_PORT}/json", timeout=2) tabs = json.loads(req.read().decode("utf-8")) if tabs: print("✅ Chromium connected via CDP!") return tabs except Exception: pass raise RuntimeError("Failed to launch or connect to Chromium on port 9222.") def get_target_ws_url(): """Returns the WebSocket debugger URL for the active DeepSeek tab.""" tabs = ensure_chromium_running() for t in tabs: url = t.get("url", "") if "chat.deepseek.com" in url: ws = t.get("webSocketDebuggerUrl") if ws: return ws # Fallback to first page tab for t in tabs: if t.get("type") == "page": ws = t.get("webSocketDebuggerUrl") if ws: return ws raise RuntimeError("No suitable tab found in Chromium.") async def evaluate_js_in_browser(js_code: str, await_promise: bool = True): """ Executes JavaScript code inside the DeepSeek browser tab context using CDP Runtime.evaluate. Returns the evaluated JavaScript result. """ ws_url = get_target_ws_url() async with websockets.connect(ws_url, max_size=None) as ws: # Enable Runtime await ws.send(json.dumps({"id": 1, "method": "Runtime.enable"})) await ws.recv() cmd = { "id": 2, "method": "Runtime.evaluate", "params": { "expression": js_code, "awaitPromise": await_promise, "returnByValue": True } } await ws.send(json.dumps(cmd)) while True: resp_str = await ws.recv() resp = json.loads(resp_str) if resp.get("id") == 2: result = resp.get("result", {}) if "exceptionDetails" in result: exc = result["exceptionDetails"].get("text", "JS Execution Exception") raise RuntimeError(f"Browser JS Exception: {exc}") return result.get("value") async def create_new_chat_session(): """ Creates a new chat session in DeepSeek via API in browser context. Returns the generated chat_session_id. """ js_code = """ (async () => { const res = await fetch('https://chat.deepseek.com/api/v0/chat_session/create', { method: 'POST', headers: {'Content-Type': 'application/json'} }); const data = await res.json(); if (data.code === 0 && data.data && data.data.biz_data) { return data.data.biz_data.chat_session_id; } return null; })() """ session_id = await evaluate_js_in_browser(js_code) if not session_id: raise RuntimeError("Failed to create new chat session from DeepSeek API") return session_id async def fetch_previous_chat_sessions(): """ Fetches list of existing/previous chat sessions from DeepSeek API. Returns list of session dicts: [{'session_id': ..., 'title': ...}] """ js_code = """ (async () => { const res = await fetch('https://chat.deepseek.com/api/v0/chat_session/fetch_page?count=30', { headers: {'Accept': 'application/json'} }); const data = await res.json(); if (data.code === 0 && data.data && data.data.biz_data) { const sessions = data.data.biz_data.chat_sessions || []; return sessions.map(s => ({ session_id: s.chat_session_id, title: s.title || 'Untitled Chat', updated_at: s.updated_at })); } return []; })() """ sessions = await evaluate_js_in_browser(js_code) return sessions if sessions else [] async def send_chat_completion(chat_session_id: str, prompt: str, model_config: dict, parent_message_id: int = None): """ Sends a chat prompt to DeepSeek completion API inside browser context. Returns dict: {'response_text': ..., 'parent_message_id': ...} """ model_type = model_config.get("model_type") thinking_enabled = model_config.get("thinking_enabled", False) search_enabled = model_config.get("search_enabled", False) # JavaScript payload executor with PoW challenge solver js_code = f""" (async () => {{ const chatSessionId = {json.dumps(chat_session_id)}; const promptText = {json.dumps(prompt)}; const parentMsgId = {json.dumps(parent_message_id)}; const modelType = {json.dumps(model_type)}; const thinkingEnabled = {json.dumps(thinking_enabled)}; const searchEnabled = {json.dumps(search_enabled)}; // Step 1: Create PoW challenge await fetch('https://chat.deepseek.com/api/v0/chat/create_pow_challenge', {{ method: 'POST', headers: {{'Content-Type': 'application/json'}}, body: JSON.stringify({{ target_path: '/api/v0/chat/completion' }}) }}); // Step 2: Send Completion request const completionPayload = {{ chat_session_id: chatSessionId, parent_message_id: parentMsgId, model_type: modelType, prompt: promptText, ref_file_ids: [], thinking_enabled: thinkingEnabled, search_enabled: searchEnabled, action: null, preempt: false }}; const res = await fetch('https://chat.deepseek.com/api/v0/chat/completion', {{ method: 'POST', headers: {{'Content-Type': 'application/json'}}, body: JSON.stringify(completionPayload) }}); const rawText = await res.text(); // Parse SSE stream lines or raw text response let finalResponse = ""; let nextParentMsgId = null; const lines = rawText.split('\\n'); for (const line of lines) {{ if (line.startswith || line.startsWith('data: ')) {{ const contentStr = line.replace('data: ', '').trim(); if (contentStr === '[DONE]') continue; try {{ const parsed = JSON.parse(contentStr); if (parsed.choices && parsed.choices[0]) {{ const delta = parsed.choices[0].delta; if (delta && delta.content) {{ finalResponse += delta.content; }} }} if (parsed.message_id) {{ nextParentMsgId = parsed.message_id; }} }} catch(e) {{}} }} }} // If SSE parsing was empty, fallback to clean line aggregation if (!finalResponse) {{ finalResponse = rawText; }} return {{ response_text: finalResponse, parent_message_id: nextParentMsgId, raw: rawText.substring(0, 500) }}; }})() """ res = await evaluate_js_in_browser(js_code) return res