// Service worker for opencode. // // Receives tool calls from the native host (one per MCP session), runs them // against the session's own tab group through the Chrome DevTools Protocol // (chrome.debugger) and the content script, and answers with MCP content. import { charDescriptor, parseCombo, parseModifiers, macEditingCommands, isZoomShortcut } from "./keyboard.js"; import { encodeGif } from "./gif.js"; self.addEventListener("unhandledrejection", (e) => e.preventDefault()); const NATIVE_HOST_NAME = "com.opencode.browser"; const VERSION = chrome.runtime.getManifest().version; const GROUP_TITLE = "opencode"; const GROUP_COLORS = ["blue", "purple", "cyan", "green", "orange", "pink", "yellow", "red"]; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); // --------------------------------------------------------------------------- // Identity: which browser this is, as shown by list_connected_browsers. // --------------------------------------------------------------------------- async function detectBrowser() { try { if (navigator.brave && (await navigator.brave.isBrave?.())) return "Brave"; } catch {} const ua = navigator.userAgent || ""; if (/Edg\//.test(ua)) return "Edge"; if (/OPR\//.test(ua)) return "Opera"; if (/Vivaldi/.test(ua)) return "Vivaldi"; return "Chrome"; } let platformOs = null; async function platform() { if (!platformOs) platformOs = (await chrome.runtime.getPlatformInfo()).os; return platformOs; } const PLATFORM_LABEL = { mac: "macOS", win: "Windows", linux: "Linux", cros: "ChromeOS" }; async function getIdentity() { const { ocb_identity: id } = await chrome.storage.local.get("ocb_identity"); if (id?.deviceId) return id; const browser = await detectBrowser(); const fresh = { deviceId: crypto.randomUUID(), name: `${browser} on ${PLATFORM_LABEL[await platform()] || "this computer"}` }; await chrome.storage.local.set({ ocb_identity: fresh }); return fresh; } export async function renameBrowser(name) { const id = await getIdentity(); id.name = String(name || id.name).slice(0, 80); await chrome.storage.local.set({ ocb_identity: id }); post({ type: "rename", name: id.name }); return id; } // --------------------------------------------------------------------------- // Native messaging // --------------------------------------------------------------------------- let port = null; let heartbeat = null; let lastConnectError = null; const pendingNative = new Map(); // id -> {resolve, reject} chrome.alarms.create("keepalive", { periodInMinutes: 0.4 }); chrome.alarms.onAlarm.addListener((a) => { if (a.name === "keepalive" && !port) connectNative(); }); function post(msg) { try { port?.postMessage(msg); } catch {} } async function connectNative() { if (port) return; try { port = chrome.runtime.connectNative(NATIVE_HOST_NAME); } catch (e) { port = null; lastConnectError = String(e?.message || e); setTimeout(connectNative, 2000); return; } port.onMessage.addListener(onNativeMessage); port.onDisconnect.addListener(() => { lastConnectError = chrome.runtime.lastError?.message || "disconnected"; port = null; clearInterval(heartbeat); heartbeat = null; // Fast retry: the host is respawned on every service-worker wake. setTimeout(connectNative, lastConnectError.includes("not found") ? 5000 : 250); }); heartbeat = setInterval(() => post({ type: "heartbeat", t: Date.now() }), 15000); const id = await getIdentity(); post({ type: "hello", deviceId: id.deviceId, name: id.name, browser: await detectBrowser(), platform: await platform(), version: VERSION }); lastConnectError = null; } function onNativeMessage(msg) { if (!msg) return; if (msg.type === "tool_request" && msg.id) { handleToolRequest(msg.id, msg.tool, msg.args || {}, msg.session || "default"); return; } if (msg.type === "connect_request" && msg.id) { openConnectPrompt(msg.id, msg.requestId); return; } if (msg.type === "session_end") { // The opencode session went away: nothing is driving its tabs any more. groupTabs(msg.session).then((tabs) => overlayOff(tabs.map((t) => t.id))); return; } if (msg.type === "connect_cancel") { closeConnectPrompt(msg.requestId); return; } if (msg.id && pendingNative.has(msg.id)) { const p = pendingNative.get(msg.id); pendingNative.delete(msg.id); msg.ok ? p.resolve(msg.result) : p.reject(new Error(msg.error || "native request failed")); } } let nativeSeq = 0; function nativeRequest(msg, timeoutMs = 20000) { return new Promise((resolve, reject) => { if (!port) return reject(new Error("native host not connected")); const id = `n${Date.now()}_${nativeSeq++}`; pendingNative.set(id, { resolve, reject }); post({ ...msg, id }); setTimeout(() => { if (pendingNative.delete(id)) reject(new Error("native request timed out")); }, timeoutMs); }); } // --------------------------------------------------------------------------- // switch_browser: a small window asking the user to connect this browser. // --------------------------------------------------------------------------- const connectPrompts = new Map(); // requestId -> {windowId, replyId} async function openConnectPrompt(replyId, requestId) { const id = await getIdentity(); const url = chrome.runtime.getURL( `connect.html?request=${encodeURIComponent(requestId)}&name=${encodeURIComponent(id.name)}` ); const win = await chrome.windows.create({ url, type: "popup", width: 420, height: 300, focused: true }); connectPrompts.set(requestId, { windowId: win.id, replyId }); } function closeConnectPrompt(requestId) { const p = connectPrompts.get(requestId); if (!p) return; connectPrompts.delete(requestId); chrome.windows.remove(p.windowId).catch(() => {}); } chrome.windows.onRemoved.addListener((windowId) => { for (const [requestId, p] of connectPrompts) { if (p.windowId === windowId) { connectPrompts.delete(requestId); post({ id: p.replyId, type: "connect_response", accepted: false }); } } }); chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => { if (msg?.type === "connect_answer") { const p = connectPrompts.get(msg.requestId); (async () => { if (p) { connectPrompts.delete(msg.requestId); let name; if (msg.accepted && msg.name) name = (await renameBrowser(msg.name)).name; post({ id: p.replyId, type: "connect_response", accepted: !!msg.accepted, name }); chrome.windows.remove(p.windowId).catch(() => {}); } sendResponse({ ok: true }); })(); return true; } if (msg?.type === "status") { (async () => { const id = await getIdentity(); sendResponse({ connected: !!port, error: lastConnectError, identity: id, extensionId: chrome.runtime.id, version: VERSION }); })(); return true; } if (msg?.type === "rename") { renameBrowser(msg.name).then((id) => sendResponse({ ok: true, identity: id })); return true; } return false; }); // --------------------------------------------------------------------------- // Sessions: every MCP session gets its own tab group. // --------------------------------------------------------------------------- let sessions = null; // session -> {groupId, color} async function loadSessions() { if (sessions) return sessions; const { ocb_sessions } = await chrome.storage.session.get("ocb_sessions"); sessions = ocb_sessions || {}; return sessions; } async function saveSessions() { await chrome.storage.session.set({ ocb_sessions: sessions }); } async function groupTabs(session) { const s = (await loadSessions())[session]; if (!s || s.groupId == null) return []; try { await chrome.tabGroups.get(s.groupId); return await chrome.tabs.query({ groupId: s.groupId }); } catch { return []; } } async function ensureGroup(session, create) { const tabs = await groupTabs(session); if (tabs.length) return { groupId: tabs[0].groupId, tabs, created: false }; if (!create) return null; const all = await loadSessions(); const color = GROUP_COLORS[Object.keys(all).length % GROUP_COLORS.length]; // Where the official extension actually puts it (its tool description says // a new window): a background tab at the end of the window the user is in, // so the user's own tab stays in front. Focus emulation (ensureAttached) // keeps the background tab rendering. A new window only when there is no // normal window to use. const win = await chrome.windows.getLastFocused({ windowTypes: ["normal"] }).catch(() => null); const tab = win && !win.incognito ? await chrome.tabs.create({ windowId: win.id, active: false }) : (await chrome.windows.create({ focused: false })).tabs[0]; const groupId = await chrome.tabs.group({ tabIds: [tab.id], createProperties: { windowId: tab.windowId } }); await chrome.tabGroups.update(groupId, { title: GROUP_TITLE, color }); all[session] = { groupId, color }; await saveSessions(); return { groupId, tabs: [await chrome.tabs.get(tab.id)], created: true }; } async function inGroup(session, tabId) { if (typeof tabId !== "number") return false; const s = (await loadSessions())[session]; if (!s) return false; try { return (await chrome.tabs.get(tabId)).groupId === s.groupId; } catch { return false; } } const tabInfo = (t) => ({ tabId: t.id, title: t.title || "New tab", url: t.url || "" }); function contextJson(tabs, groupId) { return JSON.stringify({ availableTabs: tabs.map(tabInfo), tabGroupId: groupId }); } // The "Tab Context" block the official extension appends to every result. async function contextBlock(session, executedTabId) { const tabs = (await groupTabs(session)).sort((a, b) => a.index - b.index); let text = "\n\nTab Context:\n"; if (executedTabId != null) text += `- Executed on tabId: ${executedTabId}\n`; text += "- Available tabs:"; for (const t of tabs.map(tabInfo)) text += `\n • tabId ${t.tabId}: "${t.title}" ("${t.url}")`; return text; } // --------------------------------------------------------------------------- // CDP // --------------------------------------------------------------------------- const CDP_TIMEOUT_MS = 20000; const attached = new Map(); // tabId -> true const attaching = new Map(); // tabId -> Promise const consoleLog = new Map(); // tabId -> [{level, text, url, origin, t}] const networkLog = new Map(); // tabId -> {list, byId} // As in the official extension, a tab's requests are recorded from the first // read_network_requests call on it. const networkTracked = new Set(); const tabOrigin = new Map(); // tabId -> origin of the page currently shown const openDialogs = new Map(); // tabId -> {type, message} function withTimeout(promise, ms, label) { let timer; return Promise.race([ promise, new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`${label} timed out after ${ms}ms`)), ms); }) ]).finally(() => clearTimeout(timer)); } const originOf = (url) => { try { const u = new URL(url); if (u.protocol === "file:") return "file://"; return u.origin === "null" ? "" : u.origin; } catch { return ""; } }; async function ensureAttached(tabId) { if (attached.has(tabId)) return; if (attaching.has(tabId)) return attaching.get(tabId); const p = (async () => { await chrome.debugger.attach({ tabId }, "1.3"); attached.set(tabId, true); const send = (m, params = {}) => chrome.debugger.sendCommand({ tabId }, m, params).catch(() => {}); // Capture console and network from the moment we attach, so a read after // a page load sees what the load did. await Promise.all([send("Runtime.enable"), send("Network.enable"), send("Page.enable")]); // Input to a tab that is not focused can be dropped; focus emulation makes // the page behave as focused without stealing the user's focus. await send("Emulation.setFocusEmulationEnabled", { enabled: true }); try { tabOrigin.set(tabId, originOf((await chrome.tabs.get(tabId)).url)); } catch {} })(); attaching.set(tabId, p); try { await p; } catch (e) { attached.delete(tabId); throw e; } finally { attaching.delete(tabId); } } async function cdp(tabId, method, params = {}, timeout = CDP_TIMEOUT_MS) { await ensureAttached(tabId); return withTimeout(chrome.debugger.sendCommand({ tabId }, method, params), timeout, `CDP ${method}`); } chrome.debugger.onDetach.addListener((src) => { attached.delete(src.tabId); }); chrome.tabs.onRemoved.addListener((tabId) => { attached.delete(tabId); consoleLog.delete(tabId); networkLog.delete(tabId); networkTracked.delete(tabId); tabOrigin.delete(tabId); openDialogs.delete(tabId); }); chrome.tabs.onUpdated.addListener((tabId, info) => { if (info.url) tabOrigin.set(tabId, originOf(info.url)); }); function pushConsole(tabId, entry) { const list = consoleLog.get(tabId) || []; list.push({ ...entry, origin: tabOrigin.get(tabId) || "", t: Date.now() }); if (list.length > 2000) list.splice(0, list.length - 2000); consoleLog.set(tabId, list); } // Arguments print the way the official extension prints them: primitives as // values, objects by their short description ("Object", "Array(2)"). function remoteObjectText(o) { if (!o || o.type === "undefined") return ""; if (o.type === "string") return o.value; if (o.subtype === "null") return "null"; if (o.unserializableValue) return o.unserializableValue; if (o.value !== undefined && typeof o.value !== "object") return String(o.value); return o.description || o.className || o.type; } const at = (url, line, col) => (url ? `${url}:${line ?? 0}:${col ?? 0}` : ""); chrome.debugger.onEvent.addListener((src, method, p) => { const tabId = src.tabId; switch (method) { case "Runtime.consoleAPICalled": { const f = p.stackTrace?.callFrames?.[0]; pushConsole(tabId, { level: p.type === "warning" ? "warn" : p.type, text: (p.args || []).map(remoteObjectText).join(" "), url: f?.url || "", location: f ? at(f.url, f.lineNumber, f.columnNumber) : "" }); } break; case "Runtime.exceptionThrown": { const d = p.exceptionDetails || {}; pushConsole(tabId, { level: "exception", text: d.exception?.description || d.text || "Uncaught exception", url: d.url || "", location: at(d.url, d.lineNumber, d.columnNumber) }); break; } case "Network.requestWillBeSent": { if (!networkTracked.has(tabId)) break; let log = networkLog.get(tabId); // A top-level navigation request (it is its own loader, in a frame with // no parent) to a different domain starts a fresh log, so the new // page's own document request is its first entry. const isTopNav = p.type === "Document" && p.requestId === p.loaderId && (!log?.mainFrame || p.frameId === log.mainFrame); if (isTopNav) { const origin = originOf(p.request.url); if (!log || (log.origin && log.origin !== origin)) log = null; log ??= { list: [], byId: new Map() }; log.origin = origin; log.mainFrame = p.frameId; } log ??= { list: [], byId: new Map() }; networkLog.set(tabId, log); const existing = log.byId.get(p.requestId); if (existing) { Object.assign(existing, { url: p.request.url, method: p.request.method }); } else { const rec = { url: p.request.url, method: p.request.method, type: p.type || "Other", status: 0, t: Date.now() }; log.list.push(rec); log.byId.set(p.requestId, rec); if (log.list.length > 2000) { const gone = log.list.splice(0, log.list.length - 2000); for (const [id, r] of log.byId) if (gone.includes(r)) log.byId.delete(id); } } break; } case "Network.responseReceived": { const rec = networkLog.get(tabId)?.byId.get(p.requestId); if (rec) Object.assign(rec, { status: p.response.status, mimeType: p.response.mimeType, type: p.type || rec.type }); break; } case "Network.loadingFailed": { const rec = networkLog.get(tabId)?.byId.get(p.requestId); if (rec) rec.failed = p.canceled ? "canceled" : p.errorText || "failed"; break; } case "Page.javascriptDialogOpening": openDialogs.set(tabId, { type: p.type, message: p.message }); break; case "Page.javascriptDialogClosed": openDialogs.delete(tabId); break; } }); // --------------------------------------------------------------------------- // Content script // --------------------------------------------------------------------------- async function content(tabId, type, payload = {}) { const msg = { __ocb: true, type, ...payload }; let resp; try { resp = await chrome.tabs.sendMessage(tabId, msg); } catch { try { await chrome.scripting.executeScript({ target: { tabId }, files: ["content.js"] }); } catch (e) { const url = (await chrome.tabs.get(tabId).catch(() => ({}))).url || ""; throw new Error(`Cannot access this page${url ? ` (${url})` : ""}: ${e.message}`); } resp = await chrome.tabs.sendMessage(tabId, msg); } if (resp?.error) throw new Error(resp.error); return resp?.result; } // --------------------------------------------------------------------------- // Screenshots // --------------------------------------------------------------------------- const imageStore = new Map(); // imageId -> {data, mime, t} const IMAGE_TTL_MS = 5 * 60 * 1000; function storeImage(data, mime = "image/jpeg") { const now = Date.now(); for (const [k, v] of imageStore) if (now - v.t > IMAGE_TTL_MS) imageStore.delete(k); let imageId = "ss_"; while (imageId.length < 12) imageId += "abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random() * 36)]; imageStore.set(imageId, { data, mime, t: now }); while (imageStore.size > 20) imageStore.delete(imageStore.keys().next().value); return imageId; } async function viewport(tabId) { const r = await cdp(tabId, "Runtime.evaluate", { expression: "JSON.stringify([innerWidth, innerHeight, devicePixelRatio, visualViewport?.pageLeft ?? scrollX, visualViewport?.pageTop ?? scrollY])", returnByValue: true }); const [w, h, dpr, sx, sy] = JSON.parse(r.result.value); return { w, h, dpr: dpr > 0 ? dpr : 1, sx, sy }; } // --------------------------------------------------------------------------- // Agent overlay (glow border + cursor, drawn by the content script) // --------------------------------------------------------------------------- const overlayTabs = new Set(); // tabs currently showing the overlay async function overlayCall(tabId, op, extra = {}) { try { return await content(tabId, "overlay", { op, ...extra }); } catch { return null; // restricted pages (chrome://, the Web Store) can't show it } } async function overlayActive(tabId) { if (await overlayCall(tabId, "active")) overlayTabs.add(tabId); } // Glide the visible cursor to (x, y) (CSS px) before the real input is // dispatched. async function overlayMove(tabId, x, y) { if (await overlayCall(tabId, "move", { x, y })) overlayTabs.add(tabId); } async function overlayOff(tabIds) { for (const id of tabIds) { overlayTabs.delete(id); await overlayCall(id, "off"); } } // --------------------------------------------------------------------------- // Screenshot frame // --------------------------------------------------------------------------- // Like the official extension, a screenshot is the viewport at device // resolution, shrunk to the largest size that fits the model's image budget // (1568 tiles of 28x28 px). Coordinates the agent passes are in that image's // frame and are mapped back to CSS px here. const TILE = 28; const TILE_BUDGET = 1568; function fitBudget(w, h) { const fits = (W, H) => Math.ceil(W / TILE) * Math.ceil(H / TILE) <= TILE_BUDGET; if (fits(Math.round(w), Math.round(h))) return { w: Math.round(w), h: Math.round(h) }; for (let H = Math.floor(h); H > 0; H--) { const W = Math.round((H * w) / h); if (fits(W, H)) return { w: W, h: H }; } return { w: 1, h: 1 }; } // vp -> { w, h } of the screenshot frame, and k = frame px per CSS px. function frameOf(vp) { const f = fitBudget(vp.w * vp.dpr, vp.h * vp.dpr); return { ...f, k: f.w / vp.w }; } const toCss = (frame, x, y) => ({ x: Math.round(x / frame.k), y: Math.round(y / frame.k) }); // Capture a CSS-px region of the viewport as an outW x outH jpeg. The // official extension takes its glow out for each capture, which makes the // glow blink on every screenshot; here the overlay is left as it is, so the // image shows the glow and cursor too. async function capture(tabId, { clip, outW, outH } = {}) { const vp = await viewport(tabId); const region = clip || { x: 0, y: 0, width: vp.w, height: vp.h }; if (!outW) { const { k } = frameOf(vp); outW = Math.round(region.width * k); outH = Math.round(region.height * k); } // Capture the viewport as it is on screen and crop/scale it here. Asking // Chrome for a clipped or scaled capture makes it re-render the page at // that scale, and that render flashes on screen for a frame: the page // visibly flickered on every screenshot. const raw = ( await cdp(tabId, "Page.captureScreenshot", { format: "jpeg", quality: 92, optimizeForSpeed: true, captureBeyondViewport: false }) ).data; const bmp = await createImageBitmap(await (await fetch(`data:image/jpeg;base64,${raw}`)).blob()); const px = bmp.width / vp.w; // image px per CSS px const canvas = new OffscreenCanvas(outW, outH); const ctx = canvas.getContext("2d"); ctx.imageSmoothingQuality = "high"; ctx.drawImage(bmp, region.x * px, region.y * px, region.width * px, region.height * px, 0, 0, outW, outH); bmp.close(); const encode = async (quality) => bytesToBase64(new Uint8Array(await (await canvas.convertToBlob({ type: "image/jpeg", quality })).arrayBuffer())); let data = await encode(0.55); if (data.length > 900000) data = await encode(0.35); return { data, vp, outW, outH }; } // --------------------------------------------------------------------------- // Input // --------------------------------------------------------------------------- let isBraveCached = null; const isBrave = async () => (isBraveCached ??= (await detectBrowser()) === "Brave"); // Brave withholds the debugger ack for synthetic mouse events and drops // press/release sent while an earlier one is un-acked, so those are always // awaited; moves and wheels only wait a short bounded window. async function mouse(tabId, type, x, y, opts = {}) { const params = { type, x, y, button: opts.button || (type === "mouseMoved" ? "none" : "left"), buttons: opts.buttons ?? 0, clickCount: opts.clickCount || (type === "mouseMoved" ? 0 : 1), modifiers: opts.modifiers || 0, ...(type === "mouseWheel" ? { deltaX: opts.deltaX || 0, deltaY: opts.deltaY || 0 } : {}) }; const send = cdp(tabId, "Input.dispatchMouseEvent", params); if (type === "mousePressed" || type === "mouseReleased" || ((type === "mouseMoved") && (await isBrave()))) { await send; return; } await Promise.race([send.catch(() => {}), sleep((await isBrave()) ? 250 : 50)]); } async function click(tabId, x, y, { button = "left", clickCount = 1, modifiers = 0 } = {}) { await mouse(tabId, "mouseMoved", x, y, { modifiers }); const brave = await isBrave(); const buttons = button === "right" ? 2 : button === "middle" ? 4 : 1; for (let i = 1; i <= clickCount; i++) { if (brave) await sleep(50); await mouse(tabId, "mousePressed", x, y, { button, clickCount: i, modifiers, buttons }); if (brave) await sleep(50); await mouse(tabId, "mouseReleased", x, y, { button, clickCount: i, modifiers }); } } async function pressKey(tabId, parsed, isMac) { const commands = isMac ? macEditingCommands(parsed) : undefined; const base = { key: parsed.key, code: parsed.code, windowsVirtualKeyCode: parsed.keyCode, nativeVirtualKeyCode: parsed.keyCode, modifiers: parsed.modifiers }; await cdp(tabId, "Input.dispatchKeyEvent", { ...base, type: parsed.text ? "keyDown" : "rawKeyDown", ...(parsed.text ? { text: parsed.text, unmodifiedText: parsed.text } : {}), ...(commands ? { commands } : {}) }); await cdp(tabId, "Input.dispatchKeyEvent", { ...base, type: "keyUp" }); if (await isBrave()) await sleep(30); } async function typeText(tabId, text) { for (const ch of text) { if (ch === "\n" || ch === "\r") { await pressKey(tabId, parseCombo("Enter"), false); continue; } if (ch === "\t") { await pressKey(tabId, parseCombo("Tab"), false); continue; } // Real keydown/keyup around each character (pages that listen for keys // see them), with the character itself inserted exactly once. const d = charDescriptor(ch); const ev = d && { key: ch, code: d.code, windowsVirtualKeyCode: d.keyCode, modifiers: d.shift ? 8 : 0 }; if (ev) await cdp(tabId, "Input.dispatchKeyEvent", { ...ev, type: "rawKeyDown" }); await cdp(tabId, "Input.insertText", { text: ch }); if (ev) await cdp(tabId, "Input.dispatchKeyEvent", { ...ev, type: "keyUp" }); } } // --------------------------------------------------------------------------- // GIF recording (per session) // --------------------------------------------------------------------------- const recordings = new Map(); // session -> {recording, frames: []} const MAX_FRAMES = 300; function recState(session) { let r = recordings.get(session); if (!r) recordings.set(session, (r = { recording: false, frames: [] })); return r; } async function recordFrame(session, tabId, action, existing) { const r = recordings.get(session); if (!r?.recording) return; try { const shot = existing || (await capture(tabId)); r.frames.push({ data: shot.data, w: shot.outW, h: shot.outH, action, t: Date.now() }); if (r.frames.length > MAX_FRAMES) r.frames.shift(); } catch {} } function bytesToBase64(bytes) { let bin = ""; for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000)); return btoa(bin); } // Drop a file onto the page at (x, y), as a user dragging it in would. async function dropFile(tabId, path, x, y) { const data = { items: [], files: [path], dragOperationsMask: 1 }; for (const type of ["dragEnter", "dragOver", "drop"]) { await cdp(tabId, "Input.dispatchDragEvent", { type, x, y, data, modifiers: 0 }); } } async function attachFileToRef(tabId, ref, files) { const mark = await content(tabId, "markElement", { ref }); if (!mark?.ok) throw new Error(`No element found for ${ref}. Run read_page or find again for fresh refs.`); try { if (!mark.isFileInput) throw new Error(`${ref} is a <${mark.tag}>, not a file input (). read_page/find can locate hidden file inputs.`); const doc = await cdp(tabId, "DOM.getDocument", { depth: 0 }); const q = await cdp(tabId, "DOM.querySelector", { nodeId: doc.root.nodeId, selector: "[data-ocb-target]" }); if (!q?.nodeId) throw new Error(`Could not resolve the file input for ${ref}.`); await cdp(tabId, "DOM.setFileInputFiles", { nodeId: q.nodeId, files }); } finally { await content(tabId, "unmarkElement").catch(() => {}); } } // --------------------------------------------------------------------------- // Tools // --------------------------------------------------------------------------- class ToolError extends Error {} const ok = (text, extra = []) => ({ content: [{ type: "text", text }, ...extra] }); const NO_TAB = "Couldn't determine which page this action targets. Re-read tabs_context_mcp and try again."; const noRef = (ref) => `No element found with reference: "${ref}". The element may have been removed from the page.`; async function requireTab(session, tabId) { if (typeof tabId !== "number" || !Number.isFinite(tabId) || !(await inGroup(session, tabId))) throw new ToolError(NO_TAB); const dialog = openDialogs.get(tabId); if (dialog) { throw new ToolError( `A JavaScript ${dialog.type} dialog is open in tab ${tabId} ("${String(dialog.message).slice(0, 200)}") and blocks the page. Ask the user to dismiss it in the browser.` ); } await ensureAttached(tabId).catch(() => {}); await overlayActive(tabId); } // Where an action lands, in CSS px (for input) and in the screenshot frame // (for GIF frames, which are captured at frame size). async function resolveTarget(tabId, args, frame) { if (args.ref) { const r = await content(tabId, "refCoordinates", { ref: args.ref }); if (!r || !r.reachable) throw new ToolError(noRef(args.ref)); return { x: r.x, y: r.y, fx: Math.round(r.x * frame.k), fy: Math.round(r.y * frame.k) }; } if (Array.isArray(args.coordinate) && args.coordinate.length === 2) { const [fx, fy] = args.coordinate.map(Number); return { ...toCss(frame, fx, fy), fx, fy }; } return null; } const tools = { async tabs_context_mcp(args, session) { const g = await ensureGroup(session, !!args.createIfEmpty); if (!g) return ok("No MCP tab group exists for this session. Use createIfEmpty: true to create one."); return ok(contextJson(g.tabs, g.groupId)); }, async tabs_create_mcp(_args, session) { const g = await ensureGroup(session, true); let tab; if (g.created) { tab = g.tabs[0]; } else { tab = await chrome.tabs.create({ windowId: g.tabs[0].windowId, active: false }); await chrome.tabs.group({ tabIds: [tab.id], groupId: g.groupId }); } return { ...ok(`Created new tab. Tab ID: ${tab.id}`), executedTabId: tab.id }; }, async tabs_close_mcp(args, session) { const tabId = Number(args.tabId); if (!(await inGroup(session, tabId))) throw new ToolError(NO_TAB); try { await chrome.debugger.detach({ tabId }); } catch {} attached.delete(tabId); overlayTabs.delete(tabId); await chrome.tabs.remove(tabId); const tabs = await groupTabs(session); return ok(`Closed tab ${tabId}. ${tabs.length ? `${tabs.length} tab(s) remain.` : "Group is now empty (auto-removed)."}`); }, async navigate(args, session) { const { url, tabId } = args; await requireTab(session, tabId); if (url === "back" || url === "forward") { const nav = await cdp(tabId, "Page.getNavigationHistory"); const target = nav.entries[nav.currentIndex + (url === "back" ? -1 : 1)]; if (!target) throw new ToolError(`Cannot go ${url}: no ${url} history entry.`); await cdp(tabId, "Page.navigateToHistoryEntry", { entryId: target.id }); } else { let target = String(url || "").trim(); if (!/^[a-z][a-z0-9+.-]*:/i.test(target)) target = "https://" + target.replace(/^\/+/, ""); try { new URL(target); } catch { throw new ToolError(`Invalid URL: "${url}".`); } await chrome.tabs.update(tabId, { url: target }); } // Wait for the load to finish (bounded; a slow page still returns). await new Promise((resolve) => { let done = false; const finish = () => { if (done) return; done = true; chrome.tabs.onUpdated.removeListener(listener); resolve(); }; const listener = (id, info) => { if (id === tabId && info.status === "complete") finish(); }; chrome.tabs.onUpdated.addListener(listener); setTimeout(finish, 15000); setTimeout(async () => { const t = await chrome.tabs.get(tabId).catch(() => null); if (t?.status === "complete") finish(); }, 300); }); const tab = await chrome.tabs.get(tabId); await ensureAttached(tabId).catch(() => {}); await overlayActive(tabId); // the new document needs its own overlay await recordFrame(session, tabId, { kind: "navigate", label: `Navigated to ${tab.url}` }); return ok(`Navigated to ${tab.url}`); }, async computer(args, session) { const { action, tabId } = args; await requireTab(session, tabId); const modifiers = parseModifiers(args.modifiers); const label = args.action_summary || null; const frame = action === "wait" || action === "type" || action === "key" ? null : frameOf(await viewport(tabId)); const point = ["left_click", "right_click", "double_click", "triple_click", "hover", "scroll"].includes(action) ? await resolveTarget(tabId, args, frame) : null; const at = (p) => (args.ref ? `element ${args.ref}` : `(${p.fx}, ${p.fy})`); switch (action) { case "screenshot": { const scale = args.scale ? Math.min(1, Math.max(0.1, Number(args.scale))) : 1; const shot = await capture(tabId, { outW: Math.round(frame.w * scale), outH: Math.round(frame.h * scale) }); const imageId = storeImage(shot.data); await recordFrame(session, tabId, { kind: "screenshot" }, scale < 1 ? undefined : shot); const text = scale < 1 ? `Successfully captured screenshot (${shot.outW}x${shot.outH}, jpeg) - ID: ${imageId} — ${scale}-scale view; coordinate frame: ${frame.w}x${frame.h}.` : `Successfully captured screenshot (${shot.outW}x${shot.outH}, jpeg) - ID: ${imageId}`; return ok(text, [{ type: "image", data: shot.data, mimeType: "image/jpeg" }]); } case "zoom": { if (!Array.isArray(args.region) || args.region.length !== 4) throw new ToolError("region [x0, y0, x1, y1] is required for zoom."); const [x0, y0, x1, y1] = args.region.map(Number); if (!(x1 > x0 && y1 > y0)) throw new ToolError("region must have x1 > x0 and y1 > y0."); const a = toCss(frame, x0, y0); const b = toCss(frame, x1, y1); const clip = { x: a.x, y: a.y, width: b.x - a.x, height: b.y - a.y }; // The region at the display's full resolution, within the image budget. const vp = await viewport(tabId); const full = fitBudget(clip.width * vp.dpr, clip.height * vp.dpr); const scale = args.scale ? Math.min(1, Math.max(0.1, Number(args.scale))) : 1; const shot = await capture(tabId, { clip, outW: Math.round(full.w * scale), outH: Math.round(full.h * scale) }); return ok( `Successfully captured zoomed screenshot of region (${x0},${y0}) to (${x1},${y1}) - ${shot.outW}x${shot.outH} pixels`, [{ type: "image", data: shot.data, mimeType: "image/jpeg" }] ); } case "left_click": case "right_click": case "double_click": case "triple_click": { if (!point) throw new ToolError(`coordinate (or ref) is required for ${action}.`); const opts = { button: action === "right_click" ? "right" : "left", clickCount: action === "double_click" ? 2 : action === "triple_click" ? 3 : 1, modifiers }; await overlayMove(tabId, point.x, point.y); await click(tabId, point.x, point.y, opts); const verb = { left_click: "Clicked", right_click: "Clicked", double_click: "Double-clicked", triple_click: "Triple-clicked" }[action]; await recordFrame(session, tabId, { kind: "click", x: point.fx, y: point.fy, label: label || `${verb} at (${point.fx}, ${point.fy})` }); return ok(`${verb} ${args.ref ? "on" : "at"} ${at(point)}`); } case "hover": { if (!point) throw new ToolError("coordinate (or ref) is required for hover."); await overlayMove(tabId, point.x, point.y); await mouse(tabId, "mouseMoved", point.x, point.y, { modifiers }); await sleep(await isBrave() ? 200 : 50); await recordFrame(session, tabId, { kind: "hover", x: point.fx, y: point.fy, label: label || "Hover" }); return ok(`Hovered ${args.ref ? "over" : "at"} ${at(point)}`); } case "type": { if (typeof args.text !== "string" || !args.text) throw new ToolError("text is required for type."); await typeText(tabId, args.text); await recordFrame(session, tabId, { kind: "type", label: label || `Typed "${args.text.slice(0, 40)}"` }); return ok(`Typed "${args.text}"`); } case "key": { if (typeof args.text !== "string" || !args.text.trim()) throw new ToolError("text is required for key."); const combos = args.text.trim().split(/\s+/); const parsed = combos.map((c) => [c, parseCombo(c)]); const bad = parsed.find(([, p]) => !p); if (bad) throw new ToolError(`Unknown key: "${bad[0]}".`); const zoom = parsed.find(([, p]) => isZoomShortcut(p)); if (zoom) { throw new ToolError(`Page zoom shortcuts like "${zoom[0]}" are not supported. Use the zoom action to magnify a region of the page instead.`); } const repeat = Math.min(Math.max(1, Math.floor(Number(args.repeat) || 1)), 100); const isMac = (await platform()) === "mac"; for (let r = 0; r < repeat; r++) for (const [, p] of parsed) await pressKey(tabId, p, isMac); await recordFrame(session, tabId, { kind: "key", label: label || `Pressed ${args.text}` }); const n = combos.length; return ok(`Pressed ${n} key${n > 1 ? "s" : ""}: ${args.text}${repeat > 1 ? ` (repeated ${repeat} times)` : ""}`); } case "scroll": { if (!point) throw new ToolError("coordinate is required for scroll."); const dir = args.scroll_direction || "down"; if (!["up", "down", "left", "right"].includes(dir)) throw new ToolError(`Invalid scroll_direction: ${dir}`); const ticks = Math.min(Math.max(1, Number(args.scroll_amount) || 3), 10); await overlayMove(tabId, point.x, point.y); await mouse(tabId, "mouseMoved", point.x, point.y); await mouse(tabId, "mouseWheel", point.x, point.y, { modifiers, deltaX: dir === "left" ? -100 * ticks : dir === "right" ? 100 * ticks : 0, deltaY: dir === "up" ? -100 * ticks : dir === "down" ? 100 * ticks : 0 }); await sleep(await isBrave() ? 300 : 150); const out = ok(`Scrolled ${dir} by ${ticks} ticks at ${at(point)}`); try { const shot = await withTimeout(capture(tabId), 6000, "post-scroll screenshot"); out.content.push({ type: "image", data: shot.data, mimeType: "image/jpeg" }); await recordFrame(session, tabId, { kind: "scroll", x: point.fx, y: point.fy, label: label || `Scrolled ${dir}` }, shot); } catch {} return out; } case "scroll_to": { if (!args.ref) throw new ToolError("ref is required for scroll_to."); const r = await content(tabId, "scrollToRef", { ref: args.ref }); if (!r?.ok) throw new ToolError(noRef(args.ref)); await sleep(100); return ok(`Scrolled to element with reference: ${args.ref}`); } case "wait": { const s = Math.min(Math.max(0, Number(args.duration) || 1), 10); await sleep(s * 1000); return ok(`Waited for ${s} second${s === 1 ? "" : "s"}`); } case "left_click_drag": { if (!Array.isArray(args.start_coordinate) || !Array.isArray(args.coordinate)) { throw new ToolError("start_coordinate and coordinate are required for left_click_drag."); } const [fsx, fsy] = args.start_coordinate.map(Number); const [fex, fey] = args.coordinate.map(Number); const { x: sx, y: sy } = toCss(frame, fsx, fsy); const { x: ex, y: ey } = toCss(frame, fex, fey); await overlayMove(tabId, sx, sy); await mouse(tabId, "mouseMoved", sx, sy, { modifiers }); await mouse(tabId, "mousePressed", sx, sy, { modifiers, buttons: 1 }); // The visible cursor travels with the drag. const glide = overlayMove(tabId, ex, ey); const steps = 12; for (let i = 1; i <= steps; i++) { await mouse(tabId, "mouseMoved", sx + ((ex - sx) * i) / steps, sy + ((ey - sy) * i) / steps, { modifiers, buttons: 1, button: "left" }); await sleep(20); } await glide; await mouse(tabId, "mouseReleased", ex, ey, { modifiers }); await recordFrame(session, tabId, { kind: "drag", sx: fsx, sy: fsy, x: fex, y: fey, label: label || "Dragged" }); return ok(`Dragged from (${fsx}, ${fsy}) to (${fex}, ${fey})`); } default: throw new ToolError(`Unknown computer action: ${action}`); } }, async read_page(args, session) { await requireTab(session, args.tabId); const r = await content(args.tabId, "readPage", { options: { filter: args.filter, depth: args.depth, max_chars: args.max_chars, ref_id: args.ref_id } }); if (r?.error) throw new ToolError(r.error); let text = r?.tree || ""; try { const vp = await viewport(args.tabId); text += `\n\nViewport: ${vp.w}x${vp.h}`; } catch {} return ok(text); }, async get_page_text(args, session) { await requireTab(session, args.tabId); const d = await content(args.tabId, "getPageText"); return ok(`Title: ${d.title}\nURL: ${d.url}\nSource element: <${d.sourceTag}>\n---\n${d.text}`); }, async find(args, session) { await requireTab(session, args.tabId); if (!args.query) throw new ToolError("query is required."); const { results, total } = await content(args.tabId, "find", { query: args.query }); if (!results.length) throw new ToolError(`No elements matching "${args.query}" were found on this page.`); let text = `Found ${total} matching element${total === 1 ? "" : "s"}${total > 20 ? " (showing the best 20; use a more specific query)" : ""}\n`; for (const r of results) { const why = r.label && r.label !== r.name ? `the ${r.role} labeled "${r.label}"` : `the ${r.role}${r.name ? ` "${r.name}"` : ""}`; text += `\n- ${r.ref}: ${r.role}${r.name ? ` "${r.name}"` : ""}${r.type ? ` (${r.type})` : ""} - This is ${why}, matching "${args.query}"`; } return ok(text); }, async form_input(args, session) { await requireTab(session, args.tabId); const r = await content(args.tabId, "setFormValue", { ref: args.ref, value: args.value }); if (r?.error) throw new ToolError(r.error); await recordFrame(session, args.tabId, { kind: "form", label: args.action_summary || `Set ${args.ref}` }); return ok(r.message); }, async javascript_tool(args, session) { await requireTab(session, args.tabId); if (typeof args.text !== "string" || !args.text.trim()) throw new ToolError("text (the code to run) is required."); // replMode: top-level await and `let` redeclaration, last expression is // the result — the same semantics as the DevTools console. const r = await cdp(args.tabId, "Runtime.evaluate", { expression: args.text, replMode: true, awaitPromise: true, returnByValue: true, userGesture: true }, 30000); if (r.exceptionDetails) { const d = r.exceptionDetails; throw new ToolError(`JavaScript execution error: ${d.exception?.description || d.text || "Uncaught exception"}`); } const v = r.result; if (v.type === "undefined") return ok("undefined"); if (v.value !== undefined) return ok(typeof v.value === "string" ? v.value : JSON.stringify(v.value, null, 2) ?? String(v.value)); if (v.unserializableValue) return ok(v.unserializableValue); return ok(v.description || v.type); }, async file_upload(args, session) { await requireTab(session, args.tabId); await attachFileToRef(args.tabId, args.ref, args.paths); return ok(`Uploaded ${args.paths.length === 1 ? args.paths[0] : `${args.paths.length} files`} to ${args.ref}.`); }, async upload_image(args, session) { await requireTab(session, args.tabId); const img = imageStore.get(args.imageId); if (!img || Date.now() - img.t > IMAGE_TTL_MS) { imageStore.delete(args.imageId); throw new ToolError(`Image ${args.imageId} not found or expired. Take a new screenshot right before uploading.`); } if (!!args.ref === !!args.coordinate) throw new ToolError("Provide either ref or coordinate, not both."); const filename = args.filename || "image.png"; let data = img.data; let mime = img.mime; // Screenshots are JPEG; give the file the format its name promises. if (/\.png$/i.test(filename) && mime !== "image/png") { const bmp = await createImageBitmap(await (await fetch(`data:${mime};base64,${data}`)).blob()); const c = new OffscreenCanvas(bmp.width, bmp.height); c.getContext("2d").drawImage(bmp, 0, 0); data = bytesToBase64(new Uint8Array(await (await c.convertToBlob({ type: "image/png" })).arrayBuffer())); mime = "image/png"; } const path = await nativeRequest({ type: "write_temp_file", filename, dataUrl: data }); if (args.ref) { await attachFileToRef(args.tabId, args.ref, [path]); return ok(`Uploaded ${filename} (${args.imageId}) to ${args.ref}.`); } const [fx, fy] = args.coordinate.map(Number); const { x, y } = toCss(frameOf(await viewport(args.tabId)), fx, fy); await dropFile(args.tabId, path, x, y); return ok(`Dropped ${filename} (${args.imageId}) at (${fx}, ${fy}).`); }, async read_console_messages(args, session) { await requireTab(session, args.tabId); await ensureAttached(args.tabId); const origin = originOf((await chrome.tabs.get(args.tabId)).url); let msgs = (consoleLog.get(args.tabId) || []).filter((m) => !m.origin || m.origin === origin); if (args.onlyErrors) msgs = msgs.filter((m) => m.level === "error" || m.level === "exception"); if (args.pattern) { let re; try { re = new RegExp(args.pattern, "i"); } catch { throw new ToolError(`Invalid regex pattern: ${args.pattern}`); } msgs = msgs.filter((m) => re.test(m.text)); } const limit = Math.max(1, Number(args.limit) || 100); msgs = msgs.slice(-limit); if (args.clear) consoleLog.set(args.tabId, []); if (!msgs.length) return ok(`No console messages found${args.pattern ? ` matching pattern "${args.pattern}"` : ""}.`); const LEVEL = { warn: "WARNING", exception: "EXCEPTION" }; const time = (t) => new Date(t).toTimeString().slice(0, 8); const items = msgs.map( (m, i) => `[${i + 1}] [${time(m.t)}] [${LEVEL[m.level] || m.level.toUpperCase()}]${m.location ? ` (${m.location})` : ""}\n${m.text}` ); return ok(`Found ${msgs.length} console message${msgs.length === 1 ? "" : "s"}:\n\n${items.join("\n\n")}`); }, async read_network_requests(args, session) { await requireTab(session, args.tabId); await ensureAttached(args.tabId); networkTracked.add(args.tabId); let list = networkLog.get(args.tabId)?.list || []; if (args.urlPattern) list = list.filter((r) => r.url.includes(args.urlPattern)); const limit = Math.max(1, Number(args.limit) || 100); list = list.slice(-limit); if (args.clear) networkLog.delete(args.tabId); if (!list.length) { return ok( `No network requests found for this tab${args.urlPattern ? ` matching "${args.urlPattern}"` : ""}.\n\n` + "Note: Network tracking starts when this tool is first called. If the page loaded before calling this tool, " + "you may need to refresh the page or perform actions that trigger network requests." ); } const items = list.map((r, i) => { let t = `${i + 1}. url: ${r.url.startsWith("data:") ? "data:" : r.url}\n method: ${r.method}`; if (r.status) t += `\n statusCode: ${r.status}`; else if (r.failed) t += `\n error: ${r.failed}`; return t; }); return ok(`Found ${list.length} network request${list.length === 1 ? "" : "s"}:\n\n${items.join("\n\n")}`); }, async resize_window(args, session) { await requireTab(session, args.tabId); const width = Math.round(Number(args.width)); const height = Math.round(Number(args.height)); if (!(width > 0 && height > 0)) throw new ToolError("width and height must be positive numbers."); const tab = await chrome.tabs.get(args.tabId); let win = await chrome.windows.get(tab.windowId); if (win.state !== "normal") { await chrome.windows.update(tab.windowId, { state: "normal" }).catch(() => {}); for (let i = 0; i < 20 && win.state !== "normal"; i++) { await sleep(100); win = await chrome.windows.get(tab.windowId); } } await chrome.windows.update(tab.windowId, { width, height }); let vp = null; for (let i = 0; i < 10; i++) { await sleep(80); try { vp = await viewport(args.tabId); } catch {} } const after = await chrome.windows.get(tab.windowId); let note = ""; if (Math.abs(after.width - width) > 8 || Math.abs(after.height - height) > 8) { note = ` — NOTE: the window manager kept it at ${after.width}x${after.height} (full-screen, tiled or snapped windows refuse resizes).`; } return ok(`Resized window to ${width}x${height} (window is ${after.width}x${after.height}); viewport is now ${vp ? `${vp.w}x${vp.h}` : "unknown"}.${note}`); }, async gif_creator(args, session) { await requireTab(session, args.tabId); const r = recState(session); switch (args.action) { case "start_recording": r.recording = true; return ok(`Started recording (${r.frames.length} existing frame${r.frames.length === 1 ? "" : "s"} kept). Take a screenshot now to capture the initial state.`); case "stop_recording": r.recording = false; return ok(`Stopped recording. ${r.frames.length} frame${r.frames.length === 1 ? "" : "s"} captured.`); case "clear": r.frames = []; return ok("Discarded all recorded frames."); case "export": { if (!r.frames.length) throw new ToolError("No frames recorded. Start recording and take screenshots/actions first."); const bytes = await encodeGif(r.frames, args.options || {}); const filename = (args.filename || `recording-${Date.now()}.gif`).replace(/[\\/:*?"<>|]/g, "_"); const b64 = bytesToBase64(bytes); const kb = Math.round(bytes.length / 1024); if (Array.isArray(args.coordinate) && args.coordinate.length === 2) { const path = await nativeRequest({ type: "write_temp_file", filename, dataUrl: b64 }); const { x, y } = toCss(frameOf(await viewport(args.tabId)), ...args.coordinate.map(Number)); await dropFile(args.tabId, path, x, y); return ok(`Exported ${r.frames.length} frames (${kb} KB) and dropped ${filename} at (${x}, ${y}).`); } if (!args.download) throw new ToolError("For export, set download: true or provide a coordinate to drop the GIF on."); const downloadId = await chrome.downloads.download({ url: `data:image/gif;base64,${b64}`, filename, saveAs: false, conflictAction: "uniquify" }); let file = filename; for (let i = 0; i < 20; i++) { const [item] = await chrome.downloads.search({ id: downloadId }); if (item?.state === "complete") { file = item.filename; break; } await sleep(100); } return ok(`Exported ${r.frames.length} frames (${kb} KB). Downloaded to ${file}.`); } default: throw new ToolError(`Unknown gif_creator action: ${args.action}`); } }, // The official extension's shortcuts are saved prompts run in its own side // panel. opencode has no such panel, so there are never any shortcuts. async shortcuts_list(args, session) { await requireTab(session, args.tabId); return ok(JSON.stringify({ message: "No shortcuts found", shortcuts: [] }, null, 2)); }, async shortcuts_execute(args, session) { await requireTab(session, args.tabId); throw new ToolError(`Shortcut "${args.command || args.shortcutId || ""}" not found. Use shortcuts_list to see available shortcuts (there are none in this browser).`); } }; // Clients may fire several tool calls at once (opencode runs a model's // parallel calls concurrently). Two clicks interleaving their mouse events on // one page lose both, so each session's calls run one at a time, in arrival // order. Different sessions still run side by side. const sessionQueues = new Map(); // session -> tail promise function handleToolRequest(id, tool, args, session) { const prev = sessionQueues.get(session) || Promise.resolve(); const run = prev.then(() => runToolRequest(id, tool, args, session)); sessionQueues.set(session, run); run.finally(() => { if (sessionQueues.get(session) === run) sessionQueues.delete(session); }); } async function runToolRequest(id, tool, args, session) { const handler = tools[tool]; let result; try { if (!handler) throw new ToolError(`Unknown tool: ${tool}`); result = await handler(args, session); if (tool !== "shortcuts_execute") { const executed = result.executedTabId ?? (["tabs_context_mcp", "tabs_close_mcp"].includes(tool) ? null : args.tabId); delete result.executedTabId; result.context = await contextBlock(session, executed).catch(() => undefined); } } catch (e) { const msg = String(e?.message || e); result = { content: [{ type: "text", text: e instanceof ToolError ? msg : `${tool} failed: ${msg}` }], isError: true }; } post({ id, type: "tool_response", result }); } // --------------------------------------------------------------------------- connectNative();