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(cli): publish as browsentic, and install the extension with one command
Shahriare7e7feedbefe
diff --git a/.gitignore b/.gitignoreindex 3bf7324..3292460 100644--- a/.gitignore+++ b/.gitignore@@ -32,6 +32,12 @@ web-ext.config.ts.timestamp-*mcp/bin/mcp/lib/+# Staged by mcp/scripts/stage-extension.mjs at prepack time: a copy of the root+# dist/chrome-mv3 build, because npm's `files` cannot reference paths above the package+# root. Regenerated on every pack, never committed. `files` still packs it, the same way+# mcp/dist packs despite the `dist/` rule above.+mcp/extension/+# Secrets & environment.env.env.*diff --git a/mcp/LICENSE b/mcp/LICENSEnew file mode 100644index 0000000..fc7c4dd--- /dev/null+++ b/mcp/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Shahriar++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/mcp/README.md b/mcp/README.mdnew file mode 100644index 0000000..8580378--- /dev/null+++ b/mcp/README.md@@ -0,0 +1,82 @@+# browsentic++Hand your real, logged-in browser to the AI agent you already run.++Browsentic is a browser extension plus a local daemon. The extension opens a side panel beside+whatever tab you are on; the daemon runs on loopback and wakes the agent CLI you already have+installed. There is no hosted relay, no API key, and no headless browser — it drives the tab you+are already signed in to.++This package carries both halves: the daemon, and the extension build that `browsentic setup`+installs onto disk.++## Install++```sh+npx browsentic setup+```++That installs the extension, starts the daemon and prints a pairing code. Two steps are left, and+both happen inside the browser, so only you can do them:++1. Open `chrome://extensions`, turn on **Developer mode**, press **Load unpacked**, and choose the+ folder the command printed (`~/browsentic/extension/chrome-mv3`).+2. Open the Browsentic popup and paste the pairing code.++Then open the side panel and say what you want.++To update later:++```sh+npx browsentic@latest update+```++The extension installs to a stable path on purpose, so an update keeps the same extension ID and+your browser stays paired. Press ↻ on the Browsentic card afterwards to pick up the new build.++## Requirements++- Node.js 20 or newer+- Chrome, or another Chromium browser+- One agent CLI on your `PATH`: `claude`, `codex` or `agy`++## Commands++| | |+| --- | --- |+| `browsentic setup` | install the extension, start the daemon, print a pairing code |+| `browsentic update` | refresh the installed extension and restart the daemon |+| `browsentic pair` | issue a fresh single-use code |+| `browsentic status` | daemon, extension and agent state |+| `browsentic sessions` | list paired browsers |+| `browsentic revoke` | unpair one browser, or all of them |+| `browsentic agent` | choose which agent runs the side panel |+| `browsentic logs` | tail the daemon log |+| `browsentic mcp` | serve MCP over stdio |++`browsentic help` lists the rest.++## Using it from an MCP client++Optional. The side panel needs none of this — it is for people who would rather drive the browser+from a terminal.++```sh+npm i -g browsentic+claude mcp add browsentic -- browsentic mcp+```++Any MCP client works: Claude Code, Codex, Cursor, Zed, Claude Desktop. One daemon owns the browser+link, so several can share the same paired browser at once.++Prefer a global install over `npx` here. An `npx` command re-resolves on every client start and can+quietly pull a newer daemon than the extension you have loaded.++## Documentation++Full documentation lives at **[browsentic.com/docs](https://browsentic.com/docs/)**, including the+[security model](https://browsentic.com/security/), the+[tool reference](https://browsentic.com/docs/reference/tools/) and the+[architecture](https://browsentic.com/docs/internals/).++Source: [github.com/imshaikot/browsentic](https://github.com/imshaikot/browsentic) · MITdiff --git a/mcp/package.json b/mcp/package.jsonindex 6035741..cc46694 100644--- a/mcp/package.json+++ b/mcp/package.json@@ -1,36 +1,54 @@{- "name": "@browsentic/mcp",+ "name": "browsentic","version": "0.3.1",- "description": "MCP server and local daemon that drive the Browsentic browser extension",+ "description": "Hand your real, logged-in browser to the AI agent you already run. Installs the browser extension, runs the local daemon, and speaks MCP.","type": "module","license": "MIT","packageManager": "[email protected]",+ "homepage": "https://browsentic.com",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/imshaikot/browsentic.git",+ "directory": "mcp"+ },+ "bugs": "https://github.com/imshaikot/browsentic/issues",+ "keywords": [+ "browser-automation",+ "chrome-extension",+ "ai-agent",+ "agentic-browsing",+ "mcp",+ "model-context-protocol",+ "claude-code"+ ],"engines": {"node": ">=20"},"bin": {+ "browsentic": "dist/cli.js","browsentic-mcp": "dist/cli.js","browsentic-mcpd": "dist/daemon-main.js"},"files": [- "dist",+ "dist/**/*.js",+ "extension","skills",- "README.md"+ "README.md",+ "LICENSE"],"scripts": {"build": "tsup","dev": "tsup --watch",- "compile": "tsc --noEmit"- },- "dependencies": {- "@modelcontextprotocol/sdk": "^1.29.0",- "ws": "^8.21.1",- "zod": "^4.4.3"+ "compile": "tsc --noEmit",+ "prepack": "node scripts/stage-extension.mjs"},"devDependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0","@types/node": "^26.1.1","@types/ws": "^8.18.1","tsup": "^8.5.1",- "typescript": "^7.0.2"+ "typescript": "^7.0.2",+ "ws": "^8.21.1",+ "zod": "^4.4.3"}}diff --git a/mcp/scripts/stage-extension.mjs b/mcp/scripts/stage-extension.mjsnew file mode 100644index 0000000..fd0cece--- /dev/null+++ b/mcp/scripts/stage-extension.mjs@@ -0,0 +1,74 @@+#!/usr/bin/env node+// Copies the built extension into the package so it can ship in the npm tarball.+//+// npm's `files` allowlist cannot reference paths above the package root, and the extension+// builds to <repo>/dist/chrome-mv3 — a sibling of mcp/, not a descendant. So it has to be+// staged inward before packing.+//+// This runs as `prepack`, which means it runs for `npm pack` and `npm publish` alike, so a+// maintainer packing locally gets exactly what CI publishes. It stages and validates only;+// it never builds. Building from here would mean shelling out to the vendored Yarn from+// inside an npm lifecycle script, which is fragile and would diverge from CI.+//+// Every failure below is fatal on purpose. A tarball that is merely missing its extension,+// or carrying a stale one, installs cleanly and fails much later in someone else's browser.+import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++const PKG = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')+const SOURCE = path.join(PKG, '..', 'dist', 'chrome-mv3')+const TARGET = path.join(PKG, 'extension', 'chrome-mv3')++const die = (message, hint) => {+ console.error(`\nstage-extension: ${message}`)+ if (hint) console.error(` ${hint}`)+ console.error()+ process.exit(1)+}++const manifestPath = path.join(SOURCE, 'manifest.json')+if (!existsSync(manifestPath)) {+ die(+ `no extension build at ${SOURCE}`,+ 'The npm package cannot ship without it. Run `yarn build` at the repository root first.',+ )+}++if (!existsSync(path.join(PKG, 'dist', 'cli.js'))) {+ die('no daemon build at mcp/dist/cli.js', 'Run `yarn mcp:build` first.')+}++// The one that actually bites: publishing a new daemon beside a stale extension. It installs+// fine, then reports a drifted manifest hash from inside the user's browser, where the cause+// is invisible. WXT stamps the manifest from the root package.json at build time, so a+// mismatch means the extension was not rebuilt after the version bump.+const built = JSON.parse(readFileSync(manifestPath, 'utf8')).version+const declared = JSON.parse(readFileSync(path.join(PKG, 'package.json'), 'utf8')).version+if (built !== declared) {+ die(+ `the built extension is ${built} but this package is ${declared}`,+ 'Rebuild the extension after bumping the version: `yarn build` at the repository root.',+ )+}++rmSync(path.join(PKG, 'extension'), { recursive: true, force: true })+mkdirSync(path.dirname(TARGET), { recursive: true })+cpSync(SOURCE, TARGET, { recursive: true })++const bytes = (dir) =>+ readdirSync(dir, { withFileTypes: true }).reduce((total, entry) => {+ const full = path.join(dir, entry.name)+ return total + (entry.isDirectory() ? bytes(full) : statSync(full).size)+ }, 0)++const count = (dir) =>+ readdirSync(dir, { withFileTypes: true }).reduce(+ (total, entry) => total + (entry.isDirectory() ? count(path.join(dir, entry.name)) : 1),+ 0,+ )++console.log(+ `stage-extension: extension/chrome-mv3 — ${count(TARGET)} files, ` ++ `${(bytes(TARGET) / 1024 / 1024).toFixed(2)} MB, manifest v${built}`,+)diff --git a/mcp/src/agent/runners/index.ts b/mcp/src/agent/runners/index.tsindex e193eb8..1db958f 100644--- a/mcp/src/agent/runners/index.ts+++ b/mcp/src/agent/runners/index.ts@@ -24,9 +24,16 @@ export const RUNNERS: Record<AgentKind, Runner> = {const cliPath = join(dirname(fileURLToPath(import.meta.url)), 'cli.js');-/** The stdio MCP server every agent talks to — this same package, pointed back at the daemon. */+/**+ * The stdio MCP server every agent talks to — this same package, pointed back at the daemon.+ *+ * The `mcp` argument is load-bearing. Bare invocation only serves MCP when the binary was+ * called as `browsentic-mcp`; called any other way it prints help, which an agent would read+ * as a broken handshake. BROWSENTIC_AGENT_RUN separately forces serving, so this is belt and+ * braces, but the explicit argument is the one that says what is meant.+ */export function mcpServerFor(runId: string): McpServer {- return { command: process.execPath, args: [cliPath], env: { BROWSENTIC_AGENT_RUN: runId } };+ return { command: process.execPath, args: [cliPath, 'mcp'], env: { BROWSENTIC_AGENT_RUN: runId } };}export interface SelectedRunner {diff --git a/mcp/src/cli.ts b/mcp/src/cli.tsindex 51f0cc4..a455ddf 100644--- a/mcp/src/cli.ts+++ b/mcp/src/cli.ts@@ -4,51 +4,73 @@ import { describeActions } from '@/lib/actions/registry';import { AGENTS, AGENT_KINDS, isAgentKind } from '@/lib/agents/catalog';import { RESERVED_ACTIONS } from '@/lib/actions/reserved';import { assertToolNamesRoundTrip, toolNameFor } from '@/lib/actions/tool-names';-import { join } from 'node:path';+import { basename, join } from 'node:path';import { agentSkills } from './agent/agent-skills';import { forgetGrants, listGrants } from './agent/approvals';import { readAgentConfig } from './agent/config';import { loadSkills, skillDirNames, uploadedSkillsDir } from './agent/skills';import { ensureDaemon, probeExisting } from './ensure-daemon';+import { install, InstallError, readStamp } from './install';import { clearLockfile, isRunning, logPath, readLockfile } from './lockfile';import { log } from './log';+import { extensionDir } from './paths';import { RemoteBridge } from './remote-bridge';import { createMcpServer } from './server';import pkg from '../package.json';-const USAGE = `browsentic-mcp ${pkg.version} — MCP access to your browser via the Browsentic extension-- browsentic-mcp serve MCP over stdio (what an MCP client runs)- browsentic-mcp pair issue a one-time code to type into the extension- browsentic-mcp sessions list paired browsers- browsentic-mcp revoke [origin] unpair one browser, or all of them- browsentic-mcp agent show which agent runs the side panel, and which are installed- browsentic-mcp agent <name> switch to claude, codex or antigravity- browsentic-mcp agent setup <name> let Browsentic fix what that agent still needs- browsentic-mcp tools print the bundled tool manifest (no browser needed)- browsentic-mcp skills list the skills the agent can route to, and where they came from- browsentic-mcp approvals list the “always on this site” approvals you have granted- browsentic-mcp approvals clear [host] forget them, all of them or one site's- browsentic-mcp status show daemon and extension connection state- browsentic-mcp stop stop the background daemon- browsentic-mcp restart stop the daemon and bring up a fresh one- browsentic-mcp logs print the daemon log- browsentic-mcp token print the control token (for MCP clients, not the browser)- browsentic-mcp --version print the version--The extension connects to nothing until you pair it:- 1. run "browsentic-mcp pair"- 2. open the Browsentic popup, paste the code, press Connect--Register with Claude Code: claude mcp add browsentic -- npx -y @browsentic/mcp+const USAGE = `browsentic ${pkg.version} — hand your real browser to the agent you already run++ browsentic setup install the extension, start the daemon, print a pairing code+ browsentic update refresh the installed extension and restart the daemon+ browsentic pair issue a one-time code to type into the extension+ browsentic status daemon, extension and agent state+ browsentic sessions list paired browsers+ browsentic revoke [origin] unpair one browser, or all of them++ browsentic agent show which agent runs the side panel, and which are installed+ browsentic agent <name> switch to claude, codex or antigravity+ browsentic agent fix <name> let Browsentic fix what that agent still needs++ browsentic skills list the skills the agent can route to, and where they came from+ browsentic approvals list the “always on this site” approvals you have granted+ browsentic approvals clear [host] forget them, all of them or one site's+ browsentic tools print the bundled tool manifest (no browser needed)+ browsentic logs print the daemon log+ browsentic stop stop the background daemon+ browsentic restart stop the daemon and bring up a fresh one+ browsentic token print the control token (for MCP clients, not the browser)+ browsentic --version print the version++Getting started: browsentic setup++For MCP clients+ browsentic mcp serve MCP over stdio — what a client runs, not what you type+ claude mcp add browsentic -- browsentic mcp`;+// `browsentic mcp` is the MCP server. The legacy `browsentic-mcp` bin keeps serving on bare+// invocation, because an MCP client config is literally {"command": "browsentic-mcp"} with no+// arguments, and those must keep working. The extension strip matters on Windows, where npm+// writes browsentic-mcp.cmd.+const invokedAs = basename(process.argv[1] ?? '').replace(/\.(?:js|cjs|mjs|exe|cmd|ps1)$/i, '');+const servesBare = invokedAs === 'browsentic-mcp' || !!process.env.BROWSENTIC_AGENT_RUN;+const [command] = process.argv.slice(2);switch (command) {case undefined:+ if (servesBare) await serve();+ else console.log(USAGE);+ break;+ case 'mcp':await serve();break;+ case 'setup':+ await setup(process.argv.slice(3));+ break;+ case 'update':+ await setup(['--no-pair', '--restart', ...process.argv.slice(3)]);+ break;case 'pair':await pair();break;@@ -170,6 +192,17 @@ async function showStatus(): Promise<void> {await bridge.close();const active = agents.runners.find((runner) => runner.kind === agents.active);console.log(`daemon: running on 127.0.0.1:${status.port} (pid ${lock.pid}, v${status.daemonVersion})`);++ // "Updated the CLI, never reloaded the extension" is the failure this reports. Without it+ // the only symptom is a drifted manifest, which names no cause the user can act on.+ const stamp = readStamp(extensionDir());+ if (stamp) {+ const stale = status.connected && status.extensionVersion !== stamp.version;+ console.log(+ `installed: v${stamp.version} at ${extensionDir()}` ++ (stale ? ' — press ↻ at chrome://extensions to load it' : ''),+ );+ }console.log(`extension: ${status.connected ? `connected (v${status.extensionVersion})` : 'not connected'}`);console.log(`agent: ${AGENTS[agents.active].label} — ${active?.ready ? active.version ?? 'ready' : active?.problem?.message ?? 'unavailable'}`,@@ -178,7 +211,7 @@ async function showStatus(): Promise<void> {console.log(`paired: ${status.pairedBrowsers || 'none'}${status.pairingPending ? ' (a pairing code is outstanding)' : ''}`,);- if (!status.pairedBrowsers) console.log('\nRun "browsentic-mcp pair" to connect your browser.');+ if (!status.pairedBrowsers) console.log('\nRun "browsentic setup" to install the extension, or "browsentic pair" if it is already loaded.');}function stop(): void {@@ -227,18 +260,128 @@ async function pair(): Promise<void> {const { code, expiresAt } = await bridge.pair();await bridge.close();const minutes = Math.round((expiresAt - Date.now()) / 60_000);- const grouped = `${code.slice(0, 4)}-${code.slice(4)}`;- console.log(`\n Pairing code: ${grouped}\n`);+ console.log(`\n Pairing code: ${groupCode(code)}\n`);console.log(` Open the Browsentic popup, paste it, and press Connect.`);console.log(` Expires in ${minutes} minutes and works once.\n`);}+/**+ * The extension strips the dash back out; it is there to make the code readable aloud.+ *+ * A function declaration, not a const arrow: the switch at the top of this file invokes+ * commands before execution reaches the bottom, so anything they call has to be hoisted.+ */+function groupCode(code: string): string {+ return `${code.slice(0, 4)}-${code.slice(4)}`;+}++/**+ * Install the extension, bring up the daemon, and hand back a pairing code. The two steps+ * left after this happen inside the browser, so only the user can do them.+ */+async function setup(argv: string[]): Promise<void> {+ const flag = (name: string) => argv.includes(`--${name}`);+ const valueOf = (name: string) => {+ const at = argv.indexOf(`--${name}`);+ return at === -1 ? undefined : argv[at + 1];+ };++ const browser = valueOf('browser') ?? 'chrome';+ if (browser === 'firefox') {+ console.log(`+ Firefox is not supported by this command yet.++ Release Firefox refuses unsigned extensions, and an add-on loaded through+ about:debugging is discarded when the browser restarts, so there is nothing+ useful to install. A signed build distributed through addons.mozilla.org is+ the fix, and it is not ready.++ Developer Edition and Nightly can load dist/firefox-mv2 from the source+ repository with xpinstall.signatures.required set to false.+`);+ process.exit(1);+ }+ if (browser !== 'chrome') {+ console.error(`Unknown browser "${browser}". Supported: chrome`);+ process.exit(1);+ }++ const dir = extensionDir(valueOf('dir'));+ const json = flag('json');++ let result;+ try {+ result = install(dir, flag('force'));+ } catch (error) {+ if (error instanceof InstallError) {+ console.error(`\n ${error.message}`);+ if (error.hint) console.error(` ${error.hint}`);+ console.error();+ process.exit(1);+ }+ throw error;+ }++ // Restart first, then read the lockfile. A daemon that keeps running holds the previous+ // build's action registry in memory, which surfaces later as an unexplained manifest drift.+ // Reading the lock before the restart would also report the pid that just went away.+ if (flag('restart')) await restart();+ const lock = await ensureDaemon();++ let code: string | undefined;+ let alreadyPaired = false;+ if (!flag('no-pair')) {+ const bridge = await RemoteBridge.connect(lock.port, lock.token);+ const sessions = await bridge.sessions();+ alreadyPaired = sessions.some((session) => session.origin.startsWith('chrome-extension://'));+ if (!alreadyPaired) code = (await bridge.pair()).code;+ await bridge.close();+ }++ if (json) {+ console.log(+ JSON.stringify(+ { version: result.version, extensionDir: dir, daemon: { port: lock.port, pid: lock.pid }, alreadyPaired, pairingCode: code },+ null,+ 2,+ ),+ );+ return;+ }++ const state = result.alreadyCurrent ? 'already current' : `${result.changed} file(s) written`;+ console.log(`\n Browsentic ${result.version}\n`);+ console.log(` ✓ Extension ${dir}`);+ console.log(` ${state}`);+ console.log(` ✓ Daemon 127.0.0.1:${lock.port} (pid ${lock.pid})\n`);++ if (alreadyPaired) {+ console.log(` This browser is already paired. Press ↻ on the Browsentic card at`);+ console.log(` chrome://extensions to pick up this build, and you are done.\n`);+ return;+ }++ console.log(` Two steps are left. Both happen inside the browser, so only you can do them.\n`);+ console.log(` 1. Open chrome://extensions`);+ console.log(` Turn on Developer mode, press "Load unpacked", and choose:\n`);+ console.log(` ${dir}\n`);+ // Chrome refuses chrome:// URLs given on the command line, so there is no opening this for+ // them. The folder picker shortcut is the next best thing, and it is where people stall.+ if (process.platform === 'darwin') console.log(` In the folder picker press ⇧⌘G and paste that path.\n`);+ if (code) {+ console.log(` 2. Open the Browsentic popup and paste this code:\n`);+ console.log(` ${groupCode(code)}\n`);+ console.log(` Single use, expires in 10 minutes. Need another? "browsentic pair"\n`);+ }+ console.log(` Then open the side panel and say what you want.\n`);+}+async function showSessions(): Promise<void> {const bridge = await connect();const sessions = await bridge.sessions();await bridge.close();if (!sessions.length) {- return console.log('No paired browsers. Run "browsentic-mcp pair" to add one.');+ return console.log('No paired browsers. Run "browsentic setup" to add one.');}for (const session of sessions) {console.log(`${session.connected ? '●' : '○'} ${session.origin}`);@@ -247,8 +390,10 @@ async function showSessions(): Promise<void> {}async function chooseAgent(first?: string, second?: string): Promise<void> {- const setup = first === 'setup';- const named = setup ? second : first;+ // Renamed to "fix" because `browsentic setup` now means something else entirely. The old+ // spelling stays as an undocumented alias for one release.+ const grant = first === 'fix' || first === 'setup';+ const named = grant ? second : first;if (named !== undefined && !isAgentKind(named)) {console.error(`Unknown agent "${named}". Pick one of: ${AGENT_KINDS.join(', ')}`);process.exit(1);@@ -256,7 +401,7 @@ async function chooseAgent(first?: string, second?: string): Promise<void> {const kind = isAgentKind(named) ? named : undefined;const bridge = await connect();- const state = await bridge.agent(kind && (setup ? { grant: kind } : { set: kind }));+ const state = await bridge.agent(kind && (grant ? { grant: kind } : { set: kind }));await bridge.close();for (const runner of state.runners) {@@ -267,7 +412,7 @@ async function chooseAgent(first?: string, second?: string): Promise<void> {if (runner.problem) {console.log(` ${runner.problem.message}`);if (runner.problem.fix) console.log(` ${runner.problem.fix}`);- if (runner.problem.grantable) console.log(` Fix it with "browsentic-mcp agent setup ${runner.kind}".`);+ if (runner.problem.grantable) console.log(` Fix it with "browsentic agent fix ${runner.kind}".`);}}console.log(`\nThe side panel runs on ${AGENTS[state.active].label}.`);@@ -278,7 +423,7 @@ async function revoke(origin?: string): Promise<void> {const revoked = await bridge.revoke(origin);await bridge.close();if (!revoked) return console.log(origin ? `No session for ${origin}.` : 'Nothing to revoke.');- console.log(`Revoked ${revoked} session(s). Pair again with "browsentic-mcp pair".`);+ console.log(`Revoked ${revoked} session(s). Pair again with "browsentic pair".`);}async function connect(): Promise<RemoteBridge> {@@ -309,5 +454,5 @@ function manageApprovals(sub?: string, host?: string): void {}console.log(`${grants.length} standing approval${grants.length === 1 ? '' : 's'} — these no longer ask:\n`);for (const grant of grants) console.log(` ${grant.action.padEnd(24)} on ${grant.host.padEnd(28)} since ${grant.at.slice(0, 10)}`);- console.log('\nRemove one site with "browsentic-mcp approvals clear <host>", or all with "approvals clear".');+ console.log('\nRemove one site with "browsentic approvals clear <host>", or all with "approvals clear".');}diff --git a/mcp/src/install.ts b/mcp/src/install.tsnew file mode 100644index 0000000..b4f2dbd--- /dev/null+++ b/mcp/src/install.ts@@ -0,0 +1,146 @@+import { createHash } from 'node:crypto';+import {+ chmodSync,+ existsSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ renameSync,+ rmSync,+ statSync,+ writeFileSync,+} from 'node:fs';+import { join, relative } from 'node:path';+import { installStampPath, packagedExtension, type InstallStamp } from './paths.js';++export interface InstallResult {+ dir: string;+ version: string;+ source: 'package' | 'repo';+ files: number;+ changed: number;+ alreadyCurrent: boolean;+}++/** Every file under `dir`, as paths relative to it. */+function walk(dir: string, base = dir): string[] {+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {+ const full = join(dir, entry.name);+ return entry.isDirectory() ? walk(full, base) : [relative(base, full)];+ });+}++const hash = (path: string) => createHash('sha256').update(readFileSync(path)).digest('hex');++function sameContent(a: string, b: string): boolean {+ try {+ if (statSync(a).size !== statSync(b).size) return false;+ return hash(a) === hash(b);+ } catch {+ return false;+ }+}++export function readStamp(dir: string): InstallStamp | null {+ try {+ return JSON.parse(readFileSync(installStampPath(dir), 'utf8')) as InstallStamp;+ } catch {+ return null;+ }+}++export class InstallError extends Error {+ constructor(message: string, readonly hint?: string) {+ super(message);+ }+}++/**+ * Copy the packaged extension into `dir`, replacing files one at a time.+ *+ * Not a directory swap. Renaming the old tree aside leaves the path briefly non-existent, and+ * a browser that starts in that window disables the extension and drops it from the profile,+ * forcing the user through "Load unpacked" again. Renaming over a *file* is atomic on every+ * platform and stays safe while another process holds the old inode open, which gives the same+ * guarantee at the granularity that actually matters.+ */+export function install(dir: string, force = false): InstallResult {+ const packaged = packagedExtension();+ if (!packaged) {+ throw new InstallError(+ 'this build carries no extension payload',+ 'Reinstall with `npm i -g browsentic`, or run `yarn build` if you are in a source checkout.',+ );+ }++ const manifestPath = join(packaged.dir, 'manifest.json');+ const version = JSON.parse(readFileSync(manifestPath, 'utf8')).version as string;++ const stamp = readStamp(dir);+ if (!force && stamp?.version === version && existsSync(manifestPath)) {+ return {+ dir,+ version,+ source: packaged.source,+ files: stamp.files,+ changed: 0,+ alreadyCurrent: true,+ };+ }++ const sources = walk(packaged.dir);+ mkdirSync(dir, { recursive: true, mode: 0o755 });++ // Leftovers from a run that died mid-copy.+ for (const stale of walk(dir).filter((f) => /\.tmp-\d+$/.test(f))) {+ rmSync(join(dir, stale), { force: true });+ }++ // The manifest goes last. If this dies partway through, the old manifest is left pointing at+ // a superset of the files present, which a browser loads without complaint. The reverse (a+ // new manifest naming files that are not there yet) is a broken extension.+ const ordered = [...sources.filter((f) => f !== 'manifest.json'), 'manifest.json'];++ let changed = 0;+ for (const rel of ordered) {+ const from = join(packaged.dir, rel);+ const to = join(dir, rel);+ if (!force && sameContent(from, to)) continue;++ mkdirSync(join(to, '..'), { recursive: true, mode: 0o755 });+ const tmp = `${to}.tmp-${process.pid}`;+ try {+ writeFileSync(tmp, readFileSync(from), { mode: 0o644 });+ chmodSync(tmp, 0o644);+ renameSync(tmp, to);+ changed++;+ } catch (error) {+ rmSync(tmp, { force: true });+ const code = (error as NodeJS.ErrnoException).code;+ if (code === 'EBUSY' || code === 'EPERM' || code === 'EACCES') {+ throw new InstallError(+ `the browser is holding ${rel} open`,+ 'Disable the Browsentic card at chrome://extensions (or quit the browser), then run `browsentic update` again.',+ );+ }+ throw error;+ }+ }++ // Anything the new build dropped. After the manifest, for the same reason.+ const wanted = new Set(sources);+ for (const rel of walk(dir)) {+ if (wanted.has(rel) || rel === '.browsentic-install.json') continue;+ rmSync(join(dir, rel), { force: true });+ }++ const record: InstallStamp = {+ version,+ installedAt: new Date().toISOString(),+ source: packaged.source,+ files: sources.length,+ };+ writeFileSync(installStampPath(dir), `${JSON.stringify(record, null, 2)}\n`, { mode: 0o644 });++ return { dir, version, source: packaged.source, files: sources.length, changed, alreadyCurrent: false };+}diff --git a/mcp/src/lockfile.ts b/mcp/src/lockfile.tsindex 4ecb3ae..1e64cba 100644--- a/mcp/src/lockfile.ts+++ b/mcp/src/lockfile.ts@@ -1,8 +1,10 @@import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { homedir } from 'node:os';import { join } from 'node:path';+import { stateDir } from './paths.js';-export const stateDir = process.env.BROWSENTIC_HOME ?? join(homedir(), '.browsentic');+// stateDir moved to paths.ts once the extension install needed a second root. Re-exported+// here because most of the package already imports it from this module.+export { stateDir };export const lockfilePath = join(stateDir, 'daemon.json');export const logPath = join(stateDir, 'daemon.log');diff --git a/mcp/src/paths.ts b/mcp/src/paths.tsnew file mode 100644index 0000000..38fd54b--- /dev/null+++ b/mcp/src/paths.ts@@ -0,0 +1,63 @@+import { existsSync } from 'node:fs';+import { homedir } from 'node:os';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++/**+ * The private half: lockfile, pairing keys, config, approvals, logs. Mode 0700 throughout,+ * and relocatable, because tests and sandboxes need somewhere else to put it.+ */+export const stateDir = process.env.BROWSENTIC_HOME ?? join(homedir(), '.browsentic');++/**+ * The visible half: skills, recordings, screenshots, and the unpacked extension. Things you+ * are meant to open, read and edit. Deliberately NOT relocatable by BROWSENTIC_HOME.+ */+export const userDir = join(homedir(), 'browsentic');++/**+ * Where `browsentic setup` installs the extension for the browser to load.+ *+ * Two properties of this path are load-bearing, and both are easy to break:+ *+ * - **It never carries a version.** Chrome derives an unpacked extension's ID from the+ * absolute path of its directory, and the daemon binds each session key to the resulting+ * `chrome-extension://<id>` origin. A versioned path would hand out a new identity on+ * every update and silently unpair the browser.+ * - **It does not live under stateDir.** stateDir moves with BROWSENTIC_HOME, which would+ * make the extension ID hostage to an environment variable. It is also a dotfolder, and+ * Chrome's "Load unpacked" dialog is the native folder picker, which hides those.+ */+export function extensionDir(override?: string): string {+ return override ?? join(userDir, 'extension', 'chrome-mv3');+}++/** Records what `install()` last wrote, so `status` can report installed-versus-loaded. */+export function installStampPath(dir: string): string {+ return join(dir, '.browsentic-install.json');+}++export interface InstallStamp {+ version: string;+ installedAt: string;+ source: 'package' | 'repo';+ files: number;+}++/**+ * The extension build this CLI ships or sits beside, in preference order:+ *+ * 1. `<pkg>/extension/chrome-mv3` — staged into the tarball at prepack time. This is what an+ * `npm i` or `npx` install has, and it mirrors how bundled skills already resolve+ * (see agent/skills.ts).+ * 2. `<repo>/dist/chrome-mv3` — a source checkout, i.e. `yarn mcp:link` or running+ * `node mcp/dist/cli.js` directly.+ */+export function packagedExtension(): { dir: string; source: 'package' | 'repo' } | null {+ const here = dirname(fileURLToPath(import.meta.url));+ const candidates = [+ { dir: join(here, '..', 'extension', 'chrome-mv3'), source: 'package' as const },+ { dir: join(here, '..', '..', 'dist', 'chrome-mv3'), source: 'repo' as const },+ ];+ return candidates.find((c) => existsSync(join(c.dir, 'manifest.json'))) ?? null;+}diff --git a/mcp/tsconfig.json b/mcp/tsconfig.jsonindex f76a575..4b3cc8c 100644--- a/mcp/tsconfig.json+++ b/mcp/tsconfig.json@@ -15,7 +15,13 @@"skipLibCheck": true,"noEmit": true,"paths": {- "@/*": ["../*"]+ "@/*": ["../*"],+ // lib/actions/** lives at the repository root and would otherwise resolve the root's+ // own zod, putting two copies of the same 4.4.3 release (~450 KB) into the bundle.+ // Pin both halves at the copy that actually runs. Verify with `esbuild --analyze`:+ // only `node_modules/zod/...` should appear, never `../node_modules/zod/...`.+ "zod": ["./node_modules/zod"],+ "zod/*": ["./node_modules/zod/*"]}},"include": ["src/**/*", "../lib/actions/**/*", "../lib/skills/**/*"]diff --git a/mcp/tsup.config.ts b/mcp/tsup.config.tsindex db6f8e1..19e78cb 100644--- a/mcp/tsup.config.ts+++ b/mcp/tsup.config.ts@@ -7,7 +7,42 @@ export default defineConfig({platform: 'node',outDir: 'dist',clean: true,++ // No code splitting, deliberately. ws is CommonJS and calls require() for node builtins+ // at runtime; esbuild's ESM output replaces that with a shim which throws unless a real+ // `require` is in scope. The banner below supplies one, but a banner only lands on entry+ // files, and with splitting the shim ends up in a shared chunk the banner never reaches.+ // Two self-contained entries cost ~200 KB of duplication and remove the whole problem.+ splitting: false,++ // Everything is inlined, so the published package has zero runtime dependencies and+ // `npx browsentic` downloads one tarball and runs. The closure is nine packages: zod,+ // ajv, ajv-formats, ws, the MCP SDK, fast-uri, zod-to-json-schema, json-schema-traverse+ // and fast-deep-equal. Express, hono, jose and undici never enter it, because only+ // server/index.js and server/stdio.js are imported from the SDK.+ //+ // The three runtime deps therefore live in devDependencies. Moving one back into+ // dependencies would put its whole tree (~33 MB) back in front of every install, which+ // is what the node_modules assertion in the release workflow guards against.+ noExternal: [/.*/],++ // ws requires bufferutil and utf-8-validate inside try/catch. Neither is installed, so+ // esbuild emits a runtime throw that ws's own catch swallows before falling back to its+ // JS paths. That is exactly what happens today. Nothing to fix here.+ //+ // Not minified on purpose either: ~/.browsentic/daemon.log is the only debugging surface+ // this product has, and readable frames in it are worth more than the ~80 KB gzipped.sourcemap: true,tsconfig: 'tsconfig.json',- banner: { js: '#!/usr/bin/env node' },++ // esbuild's require shim uses the real `require` when one is in scope and throws when it+ // is not. ESM has none, so create it. This is what lets bundled CommonJS (ws, and ajv+ // under the MCP SDK) reach node builtins at runtime.+ banner: {+ js: [+ '#!/usr/bin/env node',+ "import { createRequire as __browsenticCreateRequire } from 'node:module';",+ 'const require = __browsenticCreateRequire(import.meta.url);',+ ].join('\n'),+ },});diff --git a/mcp/yarn.lock b/mcp/yarn.lockindex 302822d..00e9fed 100644--- a/mcp/yarn.lock+++ b/mcp/yarn.lock@@ -5,23 +5,6 @@ __metadata:version: 10cacheKey: 10c0-"@browsentic/mcp@workspace:.":- version: 0.0.0-use.local- resolution: "@browsentic/mcp@workspace:."- dependencies:- "@modelcontextprotocol/sdk": "npm:^1.29.0"- "@types/node": "npm:^26.1.1"- "@types/ws": "npm:^8.18.1"- tsup: "npm:^8.5.1"- typescript: "npm:^7.0.2"- ws: "npm:^8.21.1"- zod: "npm:^4.4.3"- bin:- browsentic-mcp: dist/cli.js- browsentic-mcpd: dist/daemon-main.js- languageName: unknown- linkType: soft-"@esbuild/aix-ppc64@npm:0.27.7":version: 0.27.7resolution: "@esbuild/aix-ppc64@npm:0.27.7"@@ -719,6 +702,24 @@ __metadata:languageName: nodelinkType: hard+"browsentic@workspace:.":+ version: 0.0.0-use.local+ resolution: "browsentic@workspace:."+ dependencies:+ "@modelcontextprotocol/sdk": "npm:^1.29.0"+ "@types/node": "npm:^26.1.1"+ "@types/ws": "npm:^8.18.1"+ tsup: "npm:^8.5.1"+ typescript: "npm:^7.0.2"+ ws: "npm:^8.21.1"+ zod: "npm:^4.4.3"+ bin:+ browsentic: dist/cli.js+ browsentic-mcp: dist/cli.js+ browsentic-mcpd: dist/daemon-main.js+ languageName: unknown+ linkType: soft+"bundle-require@npm:^5.1.0":version: 5.1.0resolution: "bundle-require@npm:5.1.0"