From ee5b79570c7aca6ad8e1d9340014de23968bef9d Mon Sep 17 00:00:00 2001 From: ner Date: Wed, 25 Nov 2026 18:46:48 +0200 Subject: [PATCH] Initial import: opencode Chrome extension + native host (browser MCP bridge) --- .gitignore | 26 + LICENSE | 73 ++ README.md | 125 ++ extension/background.js | 1281 ++++++++++++++++++++ extension/connect.html | 10 + extension/connect.js | 13 + extension/content.js | 599 ++++++++++ extension/gif.js | 124 ++ extension/icons/icon128.png | Bin 0 -> 1101 bytes extension/icons/icon16.png | Bin 0 -> 174 bytes extension/icons/icon48.png | Bin 0 -> 386 bytes extension/keyboard.js | 174 +++ extension/manifest.json | 40 + extension/popup.html | 11 + extension/popup.js | 22 + extension/ui.css | 16 + extension/vendor/gifenc.LICENSE.md | 21 + extension/vendor/gifenc.js | 1 + host/endpoint.js | 162 +++ host/instructions.md | 72 ++ host/mcp-server.js | 224 ++++ host/native-host.js | 248 ++++ host/package-lock.json | 1689 +++++++++++++++++++++++++++ host/package.json | 17 + host/parent-watch.js | 165 +++ host/test/bridge.test.mjs | 219 ++++ host/tool-definitions.js | 557 +++++++++ host/tool-runtime.js | 296 +++++ install.sh | 170 +++ packaging/build-pkg.sh | 87 ++ packaging/distribution.xml | 24 + packaging/llama-provider.json | 86 ++ packaging/native-host | 5 + packaging/resources/conclusion.html | 13 + packaging/resources/welcome.html | 11 + packaging/scripts-llama/postinstall | 10 + packaging/scripts-main/postinstall | 32 + packaging/setup | 9 + packaging/uninstall | 17 + packaging/user-setup.mjs | 148 +++ scripts/configure-opencode.mjs | 48 + 41 files changed, 6845 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 extension/background.js create mode 100644 extension/connect.html create mode 100644 extension/connect.js create mode 100644 extension/content.js create mode 100644 extension/gif.js create mode 100644 extension/icons/icon128.png create mode 100644 extension/icons/icon16.png create mode 100644 extension/icons/icon48.png create mode 100644 extension/keyboard.js create mode 100644 extension/manifest.json create mode 100644 extension/popup.html create mode 100644 extension/popup.js create mode 100644 extension/ui.css create mode 100644 extension/vendor/gifenc.LICENSE.md create mode 100644 extension/vendor/gifenc.js create mode 100644 host/endpoint.js create mode 100644 host/instructions.md create mode 100644 host/mcp-server.js create mode 100644 host/native-host.js create mode 100644 host/package-lock.json create mode 100644 host/package.json create mode 100644 host/parent-watch.js create mode 100644 host/test/bridge.test.mjs create mode 100644 host/tool-definitions.js create mode 100644 host/tool-runtime.js create mode 100755 install.sh create mode 100755 packaging/build-pkg.sh create mode 100644 packaging/distribution.xml create mode 100644 packaging/llama-provider.json create mode 100755 packaging/native-host create mode 100644 packaging/resources/conclusion.html create mode 100644 packaging/resources/welcome.html create mode 100755 packaging/scripts-llama/postinstall create mode 100755 packaging/scripts-main/postinstall create mode 100755 packaging/setup create mode 100755 packaging/uninstall create mode 100644 packaging/user-setup.mjs create mode 100644 scripts/configure-opencode.mjs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..862d52a --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +node_modules/ +host/native-host-wrapper.sh +host/native-host-wrapper.bat +host/com.opencode.browser.json +.env +*.log +.DS_Store +.wrangler/ + +# signing key + packaged build (never commit the key) +extension.pem +extension.crx + +# benchmark research data (486MB base64 trajectories, frames, logs) — not extension code +benchmark/data/ +benchmark/environments/ +benchmark/logs/ +benchmark/throttle_evidence/ +benchmark/__pycache__/ + +# personal research data — never commit +DO_NOT_COMMIT/ + +# installer build output +build/ +dist/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5ecc88c --- /dev/null +++ b/LICENSE @@ -0,0 +1,73 @@ +# PolyForm Noncommercial License 1.0.0 + + + +## Acceptance + +In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses. + +## Copyright License + +The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license). + +## Distribution License + +The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license). + +## Notices + +You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example: + +> Required Notice: Copyright Yoyodyne, Inc. (http://example.com) + +## Changes and New Works License + +The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose. + +## Patent License + +The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software. + +## Noncommercial Purposes + +Any noncommercial purpose is a permitted purpose. + +## Personal Uses + +Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose. + +## Noncommercial Organizations + +Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding. + +## Fair Use + +You may have "fair use" rights for the software under the law. These terms do not limit them. + +## No Other Rights + +These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses. + +## Patent Defense + +If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company. + +## Violations + +The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately. + +## No Liability + +***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.*** + +## Definitions + +The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms. + +**You** refers to the individual or entity agreeing to these terms. + +**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect. + +**Your licenses** are all the licenses granted to you for the software under these terms. + +**Use** means anything you do with the software requiring one of your licenses. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a105bc4 --- /dev/null +++ b/README.md @@ -0,0 +1,125 @@ +# opencode (Chrome extension) + +Gives [opencode](https://opencode.ai) the same browser tools as Anthropic's +Claude in Chrome: the same 22 MCP tools, with the same names, parameters and +behaviour, driving your real Chrome (logged-in profile, real tabs) through an +extension. + +Fork of [noemica-io/open-claude-in-chrome](https://github.com/noemica-io/open-claude-in-chrome), +reworked for opencode. **License: PolyForm Noncommercial 1.0.0** (inherited +from upstream, see `LICENSE`): personal/non-commercial use only. + +## How it works + +``` +opencode ──stdio MCP──▶ host/mcp-server.js ──unix socket──▶ native host ──native messaging──▶ extension ──CDP──▶ tabs +``` + +- Each browser with the extension runs its own native host, which opens a + socket and descriptor in `~/.config/opencode-browser/run/`. The MCP server + finds browsers there, which is what `list_connected_browsers`, + `select_browser` and `switch_browser` work on. +- Each opencode session (one MCP server process) gets its own tab group: a + background tab at the end of the window you are using, so your own tab stays + in front (focus emulation keeps the background tab rendering). A session's + calls run one at a time, in order, even when the model issues them in + parallel. +- While the agent works in a tab, the page shows the official extension's + overlay: a pulsing orange glow around the edges and an orange cursor that + glides to each click, hover, scroll or drag. Unlike the official extension, + which takes the glow out for every screenshot (so it blinks), the overlay is + left alone and shows in the agent's screenshots. It stays until the session + ends. +- Screenshots use the official frame: the viewport at device resolution, + shrunk to fit the image budget (1568 tiles of 28 px). Coordinates the agent + passes are in that frame. Tool output text (Tab Context blocks, batch labels, + `read_page` lines, console and network listings, errors) follows the official + extension's wording; it was compared side by side with it. +- `browser_batch`, `navigate` without a `tabId`, the browser-selection tools, + `file_upload` path checks and `save_to_disk` are handled in the MCP server; + everything else runs in the extension. + +## Install + +Requires Node.js 18+. + +```sh +./install.sh --opencode +``` + +This registers the native host for Chrome, Chrome Beta/Canary, Chrome for +Testing, Chromium, Edge, Brave, Vivaldi and Arc (wherever installed), copies the +host to `~/Library/Application Support/opencode-browser/host` (macOS won't let a +browser run it from `~/Documents`), and adds this to +`~/.config/opencode/opencode.json` (after backing it up): + +```json +"mcp": { "chrome": { "type": "local", "command": ["", "/host/mcp-server.js"], "timeout": 150000 } }, +"instructions": ["/host/instructions.md"] +``` + +Then, in each browser: `chrome://extensions` → Developer mode → **Load +unpacked** → select `extension/`. The ID is fixed by the manifest key: +`ilgnnaeidkbcbnklkmjllflfkmendiib`. The toolbar popup should say +"Connected"; you can rename the browser there. + +`./install.sh --uninstall` removes the native host registrations. + +### macOS installer (.pkg) + +For another Mac, build a self-contained installer (no Node.js needed there): + +```sh +packaging/build-pkg.sh # dist/opencode-browser-.pkg (universal) +packaging/build-pkg.sh --arch arm64 # smaller, Apple silicon only +``` + +It installs a Node.js runtime, the MCP server and native host (bundled with +esbuild) and the extension into `/Library/Application Support/opencode-browser`. +It then registers the native host (system-wide for Chrome, and per user for the +other browsers) and adds the `chrome` MCP server to the logged-in user's +`~/.config/opencode/opencode.json`. An optional component, on by default, +adds the `llama.cpp` provider and makes it the default model when none is set. +The last installer page explains how to load the extension. The package is +unsigned: open it with right-click → Open, or System Settings → Privacy & +Security → Open Anyway. + +On the installed Mac, `…/opencode-browser/setup [--llama]` repeats the per-user +setup for another account, and `sudo …/opencode-browser/uninstall` removes it. + +## Tools + +`tabs_context_mcp`, `tabs_create_mcp`, `tabs_close_mcp`, `navigate`, +`computer` (click/type/key/scroll/drag/hover/screenshot/zoom/scroll_to/wait), +`read_page`, `get_page_text`, `find`, `form_input`, `javascript_tool`, +`file_upload`, `upload_image`, `read_console_messages`, +`read_network_requests`, `resize_window`, `gif_creator`, `shortcuts_list`, +`shortcuts_execute`, `list_connected_browsers`, `select_browser`, +`switch_browser`, `browser_batch`. In opencode they appear as `chrome_`. + +Differences from the official extension: + +- No per-site permission prompts and no site blocklist. Use opencode's own + `permission` config if you want approval before browser actions. +- `find` uses scored keyword/role matching in the page, not a language model, + so its one-line explanations are templated. +- Shortcuts are an official side-panel feature: `shortcuts_list` is always + empty. +- The GIF watermark says "opencode". + +## Development + +```sh +cd host && npm test # host + MCP server against a simulated extension +``` + +- After changing `extension/`, reload it in `chrome://extensions`. A browser + restart alone can keep running the cached service worker if the version is + unchanged. +- After changing `host/native-host.js` or `host/endpoint.js`, re-run + `./install.sh` (the browser runs the installed copy), then reload the + extension. +- Changes to `host/mcp-server.js` and friends take effect in the next opencode + session. +- Logs: `~/.config/opencode-browser/host.log` (native host exits), + `server-exits.log` (MCP server). diff --git a/extension/background.js b/extension/background.js new file mode 100644 index 0000000..9a80fc0 --- /dev/null +++ b/extension/background.js @@ -0,0 +1,1281 @@ +// 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(); diff --git a/extension/connect.html b/extension/connect.html new file mode 100644 index 0000000..70e4cf1 --- /dev/null +++ b/extension/connect.html @@ -0,0 +1,10 @@ + +Connect opencode? + +

Use this browser for opencode?

+

An opencode session asked to choose a browser for automation. Connect to let it control tabs in this browser.

+ + +
+ + diff --git a/extension/connect.js b/extension/connect.js new file mode 100644 index 0000000..3bffcdb --- /dev/null +++ b/extension/connect.js @@ -0,0 +1,13 @@ +const params = new URLSearchParams(location.search); +const requestId = params.get("request"); +const nameInput = document.getElementById("name"); +nameInput.value = params.get("name") || ""; + +async function answer(accepted) { + await chrome.runtime.sendMessage({ type: "connect_answer", requestId, accepted, name: nameInput.value.trim() }); + window.close(); +} + +document.getElementById("yes").addEventListener("click", () => answer(true)); +document.getElementById("no").addEventListener("click", () => answer(false)); +nameInput.addEventListener("keydown", (e) => e.key === "Enter" && answer(true)); diff --git a/extension/content.js b/extension/content.js new file mode 100644 index 0000000..2cf76d8 --- /dev/null +++ b/extension/content.js @@ -0,0 +1,599 @@ +// Content script: accessibility tree (read_page), element refs, natural +// language element search (find), form filling, page text, and point/ref +// geometry for the background worker. Runs in the extension's isolated world. + +(function () { + if (window.__ocbContentLoaded) return; + window.__ocbContentLoaded = true; + + // --- Element refs --- + // Stable per page: an element keeps its ref across calls, held weakly so a + // removed element can be garbage collected. + let refCounter = 0; + const elementMap = {}; // ref -> WeakRef + const reverseMap = new WeakMap(); // Element -> ref + + function getOrAssignRef(el) { + const existing = reverseMap.get(el); + if (existing && elementMap[existing]?.deref() === el) return existing; + const ref = `ref_${++refCounter}`; + elementMap[ref] = new WeakRef(el); + reverseMap.set(el, ref); + return ref; + } + + function resolveRef(ref) { + const el = elementMap[ref]?.deref(); + if (!el) { + delete elementMap[ref]; + return null; + } + return el; + } + + // --- Roles and names --- + // Matches what the official extension prints: HTML-derived roles (no + // separate searchbox/spinbutton/slider), "generic" for everything without + // one, and names in its order (placeholder before