An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(actions): add the message protocol, page host, and typed client
Shahriaree31bdf41c93
diff --git a/lib/actions/client.ts b/lib/actions/client.tsnew file mode 100644index 0000000..b583dd8--- /dev/null+++ b/lib/actions/client.ts@@ -0,0 +1,105 @@+import { browser } from 'wxt/browser';+import type { ScriptPublicPath } from 'wxt/utils/inject-script';+import type { z } from 'zod';+import type { Action } from './core';+import { ACTION_CHANNEL, failure, type ActionResult } from './protocol';++/** Make the input argument optional only when every field of the action's schema is optional. */+type InputArgs<I extends z.ZodType> = {} extends z.input<I> ? [input?: z.input<I>] : [input: z.input<I>];++/** Chrome's wording for "no listener was there" — the message never reached a page. */+const NO_RECEIVER = 'Receiving end does not exist';++/**+ * Actions that may be re-sent automatically after healing a tab. "No listener" is not only+ * the stranded-tab state — it is also any tab mid-navigation, after the new document commits+ * and before its content script runs. A heal in that window injects into the *new* page, so+ * an automatic retry must be safe against a document the caller never saw: these either only+ * read, or act on the tab rather than page content. Everything that clicks, types, selects+ * or submits is deliberately absent — after a heal the caller has to look again first.+ */+const RETRY_AFTER_HEAL = new Set(['page.getPageInfo', 'page.extractText', 'page.waitForElement', 'page.navigate']);++/** Invoke an action inside a tab's page from any extension context. */+export async function invokeInTab<I extends z.ZodType = z.ZodType, O = unknown>(+ tabId: number,+ action: Action<I, O> | string,+ ...[input]: InputArgs<I>+): Promise<ActionResult<O>> {+ const name = typeof action === 'string' ? action : action.name;+ const send = async () =>+ (await browser.tabs.sendMessage(tabId, { channel: ACTION_CHANNEL, action: name, input })) as ActionResult<O>;++ try {+ return await send();+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ if (!message.includes(NO_RECEIVER)) return unreachable(message);+ // Usually a stranded tab — one opened before this extension version loaded, which+ // declared content scripts never reach. Heal it either way; what happens next depends+ // on whether re-running the action against a possibly-changed page can misfire.+ if (!(await injectContentScript(tabId))) return unreachable(message);+ if (!RETRY_AFTER_HEAL.has(name)) {+ return failure(+ 'TAB_UNREACHABLE',+ 'This tab had no content script; one has just been injected and the tab is reachable now. ' ++ 'Take a fresh page.getPageInfo snapshot — the page may have changed — then retry the action.',+ );+ }+ try {+ return await send();+ } catch (retryError) {+ const detail = retryError instanceof Error ? retryError.message : String(retryError);+ // Not unreachable(): injection succeeding proves the page allows content scripts.+ return failure('TAB_UNREACHABLE', `${detail} — the content script was injected but the page still did not answer`);+ }+ }+}++/** Invoke an action in the currently active tab. */+export async function invokeInActiveTab<I extends z.ZodType = z.ZodType, O = unknown>(+ action: Action<I, O> | string,+ ...[input]: InputArgs<I>+): Promise<ActionResult<O>> {+ const [tab] = await browser.tabs.query({ active: true, currentWindow: true });+ if (tab?.id == null) return failure('NO_ACTIVE_TAB', 'No active tab to control');+ return invokeInTab(tab.id, action, ...([input] as InputArgs<I>));+}++/** A hung document must not park the injection until `document_idle` past the daemon's budget. */+const INJECT_TIMEOUT_MS = 5_000;++/**+ * Put this extension's own content script into a tab that is missing it. The file list comes+ * from the built manifest, so it stays correct however the bundler names things. False means+ * the page genuinely does not allow content scripts (chrome://, the Web Store), or the tab was+ * too slow to inject into — injection is best-effort, and the original failure stands.+ *+ * `injectImmediately` runs the script without waiting for the document to be idle; a still+ * bounded timeout guards the rest, since a mid-navigation tab can reject the call until the+ * new document commits. Without both, a slow page could stall the caller — and every daemon+ * invocation it is nested in — well past the 30s per-action timeout.+ */+export async function injectContentScript(tabId: number): Promise<boolean> {+ // The manifest reports plain paths; executeScript's type wants its branded path strings.+ const files = (browser.runtime.getManifest().content_scripts ?? []).flatMap(+ (script) => script.js ?? [],+ ) as ScriptPublicPath[];+ if (!files.length) return false;+ try {+ await withTimeout(browser.scripting.executeScript({ target: { tabId }, files, injectImmediately: true }));+ return true;+ } catch {+ return false;+ }+}++function withTimeout<T>(promise: Promise<T>): Promise<T> {+ return Promise.race([+ promise,+ new Promise<never>((_, reject) => setTimeout(() => reject(new Error('injection timed out')), INJECT_TIMEOUT_MS)),+ ]);+}++const unreachable = (detail: string): ActionResult<never> =>+ failure('TAB_UNREACHABLE', `${detail} — the page may not allow content scripts`);diff --git a/lib/actions/host.ts b/lib/actions/host.tsnew file mode 100644index 0000000..9a69d60--- /dev/null+++ b/lib/actions/host.ts@@ -0,0 +1,12 @@+import { browser } from 'wxt/browser';+import { dispatch } from './dispatch';+import { isActionInvocation } from './protocol';++/** Listen for action invocations in this page — the content-script side of the bridge. */+export function exposeActions() {+ browser.runtime.onMessage.addListener((message, _sender, sendResponse) => {+ if (!isActionInvocation(message)) return;+ void dispatch(message.action, message.input).then(sendResponse);+ return true;+ });+}diff --git a/lib/actions/index.ts b/lib/actions/index.tsnew file mode 100644index 0000000..d3602b4--- /dev/null+++ b/lib/actions/index.ts@@ -0,0 +1,8 @@+export * from './core';+export * from './protocol';+export * from './manifest';+export * from './tool-names';+export { actions, describeActions } from './registry';+export { dispatch } from './dispatch';+export { invokeInTab, invokeInActiveTab } from './client';+export { exposeActions } from './host';diff --git a/lib/actions/protocol.ts b/lib/actions/protocol.tsnew file mode 100644index 0000000..809a670--- /dev/null+++ b/lib/actions/protocol.ts@@ -0,0 +1,138 @@+import type { ToolDescriptor } from './manifest';++export const ACTION_CHANNEL = 'voicelink/action';+export const BRIDGE_CHANNEL = 'voicelink/bridge';++/** Bumped whenever the socket frames below change shape incompatibly. */+export const SOCKET_PROTOCOL_VERSION = 3;++/** Loopback ports the daemon binds, in order; the extension probes the same list. */+export const DAEMON_PORTS = [8765, 8766, 8767] as const;++/** Sent to a tab's content script to run one action there. */+export interface ActionInvocation {+ channel: typeof ACTION_CHANNEL;+ action: string;+ input?: unknown;+}++/** Sent to the background worker by extension pages. */+export type BridgeRequest =+ | { channel: typeof BRIDGE_CHANNEL; op: 'describe' }+ | { channel: typeof BRIDGE_CHANNEL; op: 'invoke'; action: string; input?: unknown }+ | { channel: typeof BRIDGE_CHANNEL; op: 'pair'; token: string }+ | { channel: typeof BRIDGE_CHANNEL; op: 'disconnect' }+ // Summarize a stored file: the worker reads its bytes from storage, runs the daemon+ // round-trip, and writes the summary back to the file index. Only the id crosses here.+ | { channel: typeof BRIDGE_CHANNEL; op: 'analyzeFile'; fileId: string };++export type ActionResult<T = unknown> =+ | { ok: true; data: T }+ | { ok: false; error: { code: string; message: string } };++/**+ * One step of an agent run, streamed from the daemon to whichever extension page is watching.+ * Lives here rather than in `mcp/` because both ends render it — the daemon emits, the side+ * panel draws — and a second copy would drift.+ */+export type RunEvent =+ /** The router picked a skill; the loop is about to start. */+ | { kind: 'started'; skill: string }+ | { kind: 'text'; delta: string }+ | { kind: 'tool'; toolId: string; action: string; input: unknown }+ /** The action needs the user's blessing before it runs; answer with a `decision` frame. */+ | { kind: 'approval'; toolId: string; action: string; input: unknown }+ | { kind: 'toolResult'; toolId: string; ok: boolean; summary: string }+ | { kind: 'done'; stopReason: string }+ | { kind: 'error'; code: string; message: string };++/**+ * How the extension proves it may drive the browser. A `pairingToken` is the one-time code+ * from `voicelink-mcp pair`, exchanged for a long-lived `sessionKey` that later connects reuse.+ *+ * This travels in the `hello` frame rather than an `Authorization` header because the browser+ * WebSocket API cannot set request headers — and a frame keeps the credential out of the URL,+ * so it never reaches a log or a process list.+ */+export type SocketAuth = { pairingToken: string } | { sessionKey: string };++/**+ * Frames on the daemon socket. The extension dials out because an MV3 service worker+ * cannot listen, so the daemon is the server and drives every invocation.+ */+export type SocketFrame =+ | {+ t: 'hello';+ protocolVersion: number;+ extensionVersion: string;+ manifestHash: string;+ auth: SocketAuth;+ }+ | {+ t: 'welcome';+ daemonVersion: string;+ manifestHash: string;+ manifestInSync: boolean;+ /** Present only on the connect that redeemed a pairing token — store it and reuse it. */+ sessionKey?: string;+ }+ | { t: 'unauthorized'; reason: string; retryable: boolean }+ | { t: 'describe'; id: string }+ | { t: 'manifest'; id: string; tools: ToolDescriptor[] }+ | { t: 'invoke'; id: string; action: string; input?: unknown }+ | { t: 'result'; id: string; result: ActionResult }+ | { t: 'ping'; id: string }+ | { t: 'pong'; id: string }+ // The agent harness. These four run the other way: the extension asks the daemon to think,+ // and the daemon answers by invoking actions back down the same socket.+ | { t: 'instruct'; id: string; text: string }+ | { t: 'cancel'; id: string }+ | { t: 'decision'; id: string; toolId: string; allow: boolean }+ | { t: 'reset' }+ | { t: 'run'; id: string; event: RunEvent }+ // A file the user attached in the extension, sent for one-shot summarization; the daemon+ // answers with a `fileSummary` carrying the same `id`. `content` is base64. This runs+ // outside the agent conversation — no skill, no browser tools, no single-run lock.+ | { t: 'analyzeFile'; id: string; name: string; mime: string; size: number; content: string }+ | { t: 'fileSummary'; id: string; result: ActionResult<{ summary: string }> };++/** Frames the extension sends unprompted, rather than as a reply to a daemon request. */+export const EXTENSION_REQUEST_FRAMES = ['instruct', 'cancel', 'decision', 'reset', 'analyzeFile'] as const;++export type ExtensionRequest = Extract<SocketFrame, { t: (typeof EXTENSION_REQUEST_FRAMES)[number] }>;++export function isExtensionRequest(frame: SocketFrame): frame is ExtensionRequest {+ return (EXTENSION_REQUEST_FRAMES as readonly string[]).includes(frame.t);+}++export function parseFrame(raw: string): SocketFrame | null {+ try {+ const frame = JSON.parse(raw);+ return typeof frame?.t === 'string' ? (frame as SocketFrame) : null;+ } catch {+ return null;+ }+}++export const success = <T>(data: T): ActionResult<T> => ({ ok: true, data });++export const failure = (code: string, message: string): ActionResult<never> => ({+ ok: false,+ error: { code, message },+});++export function isActionInvocation(message: unknown): message is ActionInvocation {+ return isOnChannel(message, ACTION_CHANNEL) && typeof (message as ActionInvocation).action === 'string';+}++export function isBridgeRequest(message: unknown): message is BridgeRequest {+ return isOnChannel(message, BRIDGE_CHANNEL);+}++function isOnChannel(message: unknown, channel: string): boolean {+ return (+ typeof message === 'object' &&+ message !== null &&+ (message as { channel?: unknown }).channel === channel+ );+}