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(daemon): let the browser start a daemon that is down, through a native messaging host that setup registers and pairing keeps current
Shahriar00e898def8d9
diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex 38268d2..cbcd0bf 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -28,6 +28,7 @@ Those three answer most questions. The daemon log also lives at `~/.browsentic/d| "Microphone access is blocked" | The microphone was refused for the extension | Press **Allow microphone**, then click the icon at the left of that tab's address bar and set **Microphone** to **Allow** || "This browser has no speech service" | Brave and some Chromium builds ship speech recognition without a transcription service behind it | Type instead, or use Chrome or Edge for dictation || `EXTENSION_OFFLINE` | Browser closed, or not paired | Open the browser; `browsentic sessions` to check pairing |+| After a reboot the panel stays offline until you run a command | The browser has no helper registered to start the daemon | Run `browsentic setup` once. `browsentic status` then lists the browsers under `wake-up:` || "Load unpacked" cannot see `~/browsentic` | A Flatpak or Snap browser, sandboxed away from your home directory. Snap Chromium is the Ubuntu default | Grant it: `flatpak override --user --filesystem=~/browsentic com.google.Chrome`. Or install somewhere the sandbox can read: `browsentic setup --dir ~/snap/chromium/common/browsentic-extension` || The folder picker does not show `~/browsentic` | It is there; some pickers open elsewhere by default | macOS: press ⇧⌘G and paste the path. Linux: Ctrl+L || Updated with `npx`, but the browser still runs the old build | Chrome never auto-reloads an unpacked extension | `browsentic status` names both versions. Press ↻ on the Browsentic card |diff --git a/docs/internals/state.md b/docs/internals/state.mdindex 7291bb7..d76e57c 100644--- a/docs/internals/state.md+++ b/docs/internals/state.md@@ -11,6 +11,7 @@ Nothing lives in the repository.├── config.json optional, hand-written├── approvals.json 0600 "always on this site" grants, one action + host per entry├── models.json 0600 each agent CLI's own model list, as last read+├── native-host/ the helper a browser launches to start the daemon├── daemon.log run starts, routed skills, every tool call and its outcome├── skills/ hand-written skill overrides├── cli/ macOS app only: the command, the daemon, bundled skills, the extension payload@@ -32,6 +33,7 @@ Nothing lives in the repository.| `config.json` | You, and the agent picker | Re-read before every run — no restart needed. [Reference](../guide/configuration.md) || `approvals.json` | **Always on ‹host›** | One action + host per entry. Only short-circuits a `confirm` || `models.json` | The daemon, reading each agent CLI's model list | A cache: deleting it only means the lists are read again. A failed read keeps the last list that read cleanly |+| `native-host/` | `browsentic setup` | A launcher that runs this CLI with the `PATH` setup saw. Each browser gets a manifest in its own `NativeMessagingHosts` folder (a registry key on Windows) naming the extension origins allowed to use it; pairing adds the new one. `browsentic uninstall` removes both || `cli/`, `bin/`, `runtime/` | [Browsentic.app](../guide/mac-app.md) | Replaced whole on every app update. `cli/.browsentic-app.json` is what makes `installKind()` answer `app`, which turns the npm self-update off || `daemon.log` | The daemon | `browsentic logs`. Local [instant commands](../guide/features/instant-commands.md) never appear here, by design |diff --git a/src/daemon/cli.ts b/src/daemon/cli.tsindex 26aa85c..157f284 100644--- a/src/daemon/cli.ts+++ b/src/daemon/cli.ts@@ -7,6 +7,7 @@ import { RESERVED_ACTIONS } from '@/lib/actions/reserved';import { assertToolNamesRoundTrip, toolNameFor } from '@/lib/actions/tool-names';import { formatWhen } from '@/lib/format-when';import { basename, join } from 'node:path';+import { fileURLToPath } from 'node:url';import { agentSkills } from './agent/agent-skills';import { forgetGrants, listGrants } from './agent/approvals';import { clearDownloads, downloadDir, storedDownloads } from './downloads';@@ -17,6 +18,7 @@ import { install, InstallError, readStamp } from './install';import { logPath, readLockfile } from './lockfile';import { log } from './log';import { installKind } from './npx';+import { installNativeHost, registeredBrowsers, removeNativeHost, serveNativeHost } from './native-host';import { extensionDir } from './paths';import { RELEASES_PAGE, signedAddonAttached, signedAddonUrl } from './firefox-addon';import { RemoteBridge } from './remote-bridge';@@ -92,6 +94,9 @@ switch (command) {case 'uninstall':await uninstall(process.argv.slice(3));break;+ case 'native-host':+ await serveNativeHost(ensureDaemon);+ break;case 'pair':await pair();break;@@ -218,8 +223,11 @@ function printSkills(): void {async function showStatus(): Promise<void> {const lock = await probeExisting();+ const waking = registeredBrowsers();+ const wake = `wake-up: ${waking.length ? `${waking.join(', ')} can start the daemon` : 'not registered — run "browsentic setup"'}`;if (!lock) {console.log('daemon: not running');+ console.log(wake);console.log('extension: unknown (start an MCP client, or run a tool, to launch the daemon)');return;}@@ -229,6 +237,7 @@ 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})`);+ console.log(wake);// "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.@@ -309,6 +318,12 @@ async function pair(): Promise<void> {* 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 wakeLine(browsers: string[]): string {+ return browsers.length+ ? `✓ Wake-up ${browsers.join(', ')} can start the daemon when it is down`+ : '· Wake-up no supported browser found, so start the daemon yourself after a reboot';+}+function groupCode(code: string): string {return `${code.slice(0, 4)}-${code.slice(4)}`;}@@ -364,6 +379,7 @@ async function setup(argv: string[]): Promise<void> {// Reading the lock before the restart would also report the pid that just went away.if (flag('restart')) await restart();const lock = await ensureDaemon();+ const wake = installNativeHost(fileURLToPath(import.meta.url));// --no-pair means mint no code, not learn nothing: `update` still has to know whether this// browser is paired, because that decides whether what is left to do is "load unpacked" or@@ -377,7 +393,14 @@ async function setup(argv: string[]): Promise<void> {if (json) {console.log(JSON.stringify(- { version: result.version, extensionDir: dir, daemon: { port: lock.port, pid: lock.pid }, alreadyPaired, pairingCode: code },+ {+ version: result.version,+ extensionDir: dir,+ daemon: { port: lock.port, pid: lock.pid },+ nativeHost: wake,+ alreadyPaired,+ pairingCode: code,+ },null,2,),@@ -389,7 +412,8 @@ async function setup(argv: string[]): Promise<void> {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`);+ console.log(` ✓ Daemon 127.0.0.1:${lock.port} (pid ${lock.pid})`);+ console.log(` ${wakeLine(wake.browsers)}\n`);if (alreadyPaired) {console.log(` This browser is already paired. Press ↻ on the Browsentic card at`);@@ -424,6 +448,7 @@ async function setup(argv: string[]): Promise<void> {async function setupFirefox({ json, restart: fresh, pair }: { json: boolean; restart: boolean; pair: boolean }): Promise<void> {if (fresh) await restart();const lock = await ensureDaemon();+ const wake = installNativeHost(fileURLToPath(import.meta.url));const bridge = await RemoteBridge.connect(lock.port, lock.token);const sessions = await bridge.sessions();const alreadyPaired = sessions.some((session) => session.origin.startsWith('moz-extension://'));@@ -436,7 +461,15 @@ async function setupFirefox({ json, restart: fresh, pair }: { json: boolean; resif (json) {console.log(JSON.stringify(- { version: pkg.version, firefoxAddon: addon, attached, daemon: { port: lock.port, pid: lock.pid }, alreadyPaired, pairingCode: code },+ {+ version: pkg.version,+ firefoxAddon: addon,+ attached,+ daemon: { port: lock.port, pid: lock.pid },+ nativeHost: wake,+ alreadyPaired,+ pairingCode: code,+ },null,2,),@@ -445,7 +478,8 @@ async function setupFirefox({ json, restart: fresh, pair }: { json: boolean; res}console.log(`\n Browsentic ${pkg.version}\n`);- console.log(` ✓ Daemon 127.0.0.1:${lock.port} (pid ${lock.pid})\n`);+ console.log(` ✓ Daemon 127.0.0.1:${lock.port} (pid ${lock.pid})`);+ console.log(` ${wakeLine(wake.browsers)}\n`);if (alreadyPaired) {console.log(` This Firefox is already paired, and it picks up each new build on its own —`);@@ -498,6 +532,8 @@ async function uninstall(argv: string[]): Promise<void> {console.log(' This removes:\n');for (const daemon of daemons) console.log(` daemon 127.0.0.1:${daemon.port}, pid ${daemon.pid}`);+ const waking = registeredBrowsers();+ if (waking.length) console.log(` wake-up the native host registered with ${waking.join(', ')}`);for (const removal of plan.removals) {console.log(` ${removal.label.padEnd(11)} ${removal.path}`);console.log(` ${removal.holds}${removal.keep ? ' — keeping skills/' : ''}`);@@ -560,6 +596,9 @@ async function uninstall(argv: string[]): Promise<void> {if (stopped.length) console.log(` ✓ Daemon stopped (pid ${stopped.map((daemon) => daemon.pid).join(', ')})`);for (const daemon of stubborn) console.log(` ✗ Daemon pid ${daemon.pid} would not exit — kill it by hand`);+ const unregistered = removeNativeHost();+ if (unregistered.length) console.log(` ✓ Wake-up unregistered from ${unregistered.length} place${unregistered.length === 1 ? '' : 's'}`);+for (const outcome of removeAll(plan.removals)) {if (!outcome.removed) console.log(` ✗ ${outcome.removal.path} — ${outcome.error}`);else if (outcome.kept.length) console.log(` ✓ Emptied ${outcome.removal.path} — kept ${outcome.kept.join(', ')}/`);diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.tsindex 2bdbbd5..ec7b7b9 100644--- a/src/daemon/daemon.ts+++ b/src/daemon/daemon.ts@@ -60,6 +60,7 @@ import { loadSkills } from './agent/skills';import { commitStaging, discardStaging } from './agent/site-map-store';import type { Bridge, BridgeStatus, ControlMessage, ControlRequest, Described, SessionSummary } from './control';import { ExtensionLink } from './extension-link';+import { refreshNativeHost } from './native-host';import {ANYWHERE,INJECT_ACTION,@@ -307,6 +308,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):const session = createSession(install);sealedSessionKey = await sealSessionKey(secret, transcript, session.key);log(`paired ${install.browser ?? install.origin} (extension ${hello.extensionVersion})`);+ refreshNativeHost();} else if (hello.auth?.kind === 'session') {const session = await matchSession(proven.proof, transcript, install);if (!session) {diff --git a/src/daemon/native-host.test.ts b/src/daemon/native-host.test.tsnew file mode 100644index 0000000..85a307a--- /dev/null+++ b/src/daemon/native-host.test.ts@@ -0,0 +1,119 @@+import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { beforeEach, describe, expect, it } from 'vitest';+import {+ NATIVE_HOST_NAME,+ decodeNativeMessage,+ encodeNativeMessage,+ hostManifest,+ hostTargets,+ installNativeHost,+ launcherScript,+ nativeHostDir,+ registeredBrowsers,+ removeNativeHost,+ unpackedExtensionOrigin,+} from './native-host';+import { extensionDir } from './paths';++describe('unpackedExtensionOrigin', () => {+ it('names the folder the way Chrome does', () => {+ expect(unpackedExtensionOrigin('/Users/shahriar/browsentic/extension/chrome-mv3')).toBe(+ 'chrome-extension://pplbfkdfiimmogofmehpibbmldcefgpc/',+ );+ });+});++describe('hostTargets', () => {+ it('points each browser at its own manifest folder, or its registry key on Windows', () => {+ const mac = hostTargets('darwin', '/Users/me').find((target) => target.browser === 'Edge');+ expect(mac?.manifestDir).toBe('/Users/me/Library/Application Support/Microsoft Edge/NativeMessagingHosts');+ const linux = hostTargets('linux', '/home/me').find((target) => target.browser === 'Firefox');+ expect(linux).toMatchObject({ family: 'firefox', manifestDir: '/home/me/.mozilla/native-messaging-hosts' });+ const windows = hostTargets('win32').find((target) => target.browser === 'Chrome');+ expect(windows?.registryKey).toBe(`HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\${NATIVE_HOST_NAME}`);+ });+});++describe('hostManifest', () => {+ it('lets Chromium in by origin and Firefox by add-on id', () => {+ expect(hostManifest('chromium', '/x/launcher', ['chrome-extension://abc/'])).toMatchObject({+ name: NATIVE_HOST_NAME,+ type: 'stdio',+ path: '/x/launcher',+ allowed_origins: ['chrome-extension://abc/'],+ });+ expect(hostManifest('firefox', '/x/launcher', [])).toMatchObject({ allowed_extensions: ['[email protected]'] });+ });+});++describe('launcherScript', () => {+ it('pins node, the CLI and PATH, and falls back to npx once the CLI moves', () => {+ const script = launcherScript({+ platform: 'darwin',+ cliPath: "/Users/o'neil/cli.js",+ nodePath: '/opt/node/bin/node',+ pathEnv: '/opt/node/bin:/usr/bin',+ });+ expect(script.split('\n')).toEqual([+ '#!/bin/sh',+ "PATH='/opt/node/bin:/usr/bin'",+ 'export PATH',+ "NODE='/opt/node/bin/node'",+ '[ -x "$NODE" ] || NODE=node',+ "CLI='/Users/o'\\''neil/cli.js'",+ 'if [ -f "$CLI" ]; then exec "$NODE" "$CLI" native-host "$@"; fi',+ 'exec npx --yes browsentic native-host "$@"',+ '',+ ]);+ });++ it('writes a batch file on Windows', () => {+ const script = launcherScript({ platform: 'win32', cliPath: 'C:\\b\\cli.js', nodePath: 'C:\\node.exe', pathEnv: 'C:\\bin' });+ expect(script).toContain('"C:\\node.exe" "C:\\b\\cli.js" native-host %*');+ expect(script).toContain('call npx --yes browsentic native-host %*');+ });+});++describe('the message frame', () => {+ it('round-trips a message and waits for a whole one', () => {+ const frame = encodeNativeMessage({ op: 'ensure' });+ expect(frame.readUInt32LE(0)).toBe(frame.length - 4);+ expect(decodeNativeMessage(frame)).toEqual({ op: 'ensure' });+ expect(decodeNativeMessage(frame.subarray(0, frame.length - 1))).toBeUndefined();+ });+});++describe('registering the host', () => {+ const chromeHome = join(homedir(), '.config', 'google-chrome');+ const manifest = join(chromeHome, 'NativeMessagingHosts', `${NATIVE_HOST_NAME}.json`);++ beforeEach(() => {+ removeNativeHost('linux');+ rmSync(chromeHome, { recursive: true, force: true });+ mkdirSync(chromeHome, { recursive: true });+ });++ it('registers with the browsers that are installed, letting in the unpacked extension', () => {+ const installed = installNativeHost('/opt/browsentic/dist/cli.js', 'linux');++ expect(installed.browsers).toEqual(['Chrome']);+ expect(statSync(installed.launcher).mode & 0o777).toBe(0o755);+ expect(JSON.parse(readFileSync(manifest, 'utf8'))).toMatchObject({+ path: installed.launcher,+ allowed_origins: [unpackedExtensionOrigin(extensionDir())],+ });+ expect(registeredBrowsers('linux')).toEqual(['Chrome']);+ });++ it('removes every trace on uninstall', () => {+ installNativeHost('/opt/browsentic/dist/cli.js', 'linux');++ removeNativeHost('linux');++ expect(existsSync(manifest)).toBe(false);+ expect(existsSync(nativeHostDir)).toBe(false);+ expect(registeredBrowsers('linux')).toEqual([]);+ });+});diff --git a/src/daemon/native-host.ts b/src/daemon/native-host.tsnew file mode 100644index 0000000..e0e3d14--- /dev/null+++ b/src/daemon/native-host.ts@@ -0,0 +1,276 @@+/**+ * Lets the browser start the daemon. Chrome, Edge, Brave and Firefox each launch a program+ * registered as a native messaging host when the extension asks for it; ours only makes sure+ * a daemon is running and exits. The registration lists the exact extension origins allowed+ * to launch it, recomputed on every setup and every pairing.+ */++import { execFileSync } from 'node:child_process';+import { NATIVE_HOST_NAME } from '@/lib/actions/protocol';+import { createHash } from 'node:crypto';+import { chmodSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { listSessions } from './auth-store';+import { readAgentConfig } from './agent/config';+import { stateDir } from './lockfile';+import { log } from './log';+import { extensionDir } from './paths';++export { NATIVE_HOST_NAME };+export const FIREFOX_ADDON_ID = '[email protected]';++type Family = 'chromium' | 'firefox';++export interface HostTarget {+ browser: string;+ family: Family;+ /** Where the browser keeps its profile; the host is only registered where the browser is installed. */+ home: string;+ /** macOS and Linux read the manifest from this directory. */+ manifestDir?: string;+ /** Windows reads the manifest path from this registry key. */+ registryKey?: string;+}++const MAC_BROWSERS: [string, Family, string][] = [+ ['Chrome', 'chromium', 'Google/Chrome'],+ ['Chrome for Testing', 'chromium', 'Google/Chrome for Testing'],+ ['Chromium', 'chromium', 'Chromium'],+ ['Edge', 'chromium', 'Microsoft Edge'],+ ['Brave', 'chromium', 'BraveSoftware/Brave-Browser'],+ ['Vivaldi', 'chromium', 'Vivaldi'],+ ['Arc', 'chromium', 'Arc/User Data'],+ ['Firefox', 'firefox', 'Mozilla'],+];++const LINUX_BROWSERS: [string, Family, string, string][] = [+ ['Chrome', 'chromium', '.config/google-chrome', '.config/google-chrome/NativeMessagingHosts'],+ ['Chromium', 'chromium', '.config/chromium', '.config/chromium/NativeMessagingHosts'],+ ['Edge', 'chromium', '.config/microsoft-edge', '.config/microsoft-edge/NativeMessagingHosts'],+ ['Brave', 'chromium', '.config/BraveSoftware/Brave-Browser', '.config/BraveSoftware/Brave-Browser/NativeMessagingHosts'],+ ['Vivaldi', 'chromium', '.config/vivaldi', '.config/vivaldi/NativeMessagingHosts'],+ ['Firefox', 'firefox', '.mozilla', '.mozilla/native-messaging-hosts'],+];++const WINDOWS_BROWSERS: [string, Family, string][] = [+ ['Chrome', 'chromium', 'Google\\Chrome'],+ ['Chromium', 'chromium', 'Chromium'],+ ['Edge', 'chromium', 'Microsoft\\Edge'],+ ['Brave', 'chromium', 'BraveSoftware\\Brave-Browser'],+ ['Firefox', 'firefox', 'Mozilla'],+];++export function hostTargets(platform: NodeJS.Platform = process.platform, home = homedir()): HostTarget[] {+ if (platform === 'darwin') {+ const support = join(home, 'Library', 'Application Support');+ return MAC_BROWSERS.map(([browser, family, dir]) => ({+ browser,+ family,+ home: join(support, dir),+ manifestDir: join(support, dir, 'NativeMessagingHosts'),+ }));+ }+ if (platform === 'win32') {+ return WINDOWS_BROWSERS.map(([browser, family, vendor]) => ({+ browser,+ family,+ home: '',+ registryKey: `HKCU\\Software\\${vendor}\\NativeMessagingHosts\\${NATIVE_HOST_NAME}`,+ }));+ }+ return LINUX_BROWSERS.map(([browser, family, dir, manifests]) => ({+ browser,+ family,+ home: join(home, dir),+ manifestDir: join(home, manifests),+ }));+}++/** Chrome names an unpacked extension after its folder: the SHA-256 of the path, spelled in a–p. */+export function unpackedExtensionOrigin(dir: string): string {+ const hex = createHash('sha256').update(dir).digest('hex').slice(0, 32);+ const id = [...hex].map((digit) => String.fromCharCode(97 + parseInt(digit, 16))).join('');+ return `chrome-extension://${id}/`;+}++const asOrigin = (origin: string) => (origin.endsWith('/') ? origin : `${origin}/`);++export function allowedOrigins(platform: NodeJS.Platform = process.platform): string[] {+ const paired = listSessions()+ .map((session) => session.origin)+ .filter((origin) => origin.startsWith('chrome-extension://'));+ const unpacked = platform === 'win32' ? [] : [unpackedExtensionOrigin(extensionDir(readAgentConfig().extensionDir))];+ return [...new Set([...unpacked, ...paired].map(asOrigin))].sort();+}++export function hostManifest(family: Family, launcher: string, origins: readonly string[]): Record<string, unknown> {+ return {+ name: NATIVE_HOST_NAME,+ description: 'Starts the Browsentic daemon when the browser needs it',+ path: launcher,+ type: 'stdio',+ ...(family === 'firefox' ? { allowed_extensions: [FIREFOX_ADDON_ID] } : { allowed_origins: origins }),+ };+}++const shellQuote = (value: string) => `'${value.replace(/'/g, `'\\''`)}'`;++export function launcherScript(options: {+ platform: NodeJS.Platform;+ cliPath: string;+ nodePath: string;+ pathEnv: string;+}): string {+ const { platform, cliPath, nodePath, pathEnv } = options;+ if (platform === 'win32') {+ return [+ '@echo off',+ `set "PATH=${pathEnv}"`,+ `if exist "${cliPath}" (`,+ ` "${nodePath}" "${cliPath}" native-host %*`,+ ') else (',+ ' call npx --yes browsentic native-host %*',+ ')',+ '',+ ].join('\r\n');+ }+ return [+ '#!/bin/sh',+ `PATH=${shellQuote(pathEnv)}`,+ 'export PATH',+ `NODE=${shellQuote(nodePath)}`,+ '[ -x "$NODE" ] || NODE=node',+ `CLI=${shellQuote(cliPath)}`,+ 'if [ -f "$CLI" ]; then exec "$NODE" "$CLI" native-host "$@"; fi',+ 'exec npx --yes browsentic native-host "$@"',+ '',+ ].join('\n');+}++export const nativeHostDir = join(stateDir, 'native-host');+export const launcherPath = (platform: NodeJS.Platform = process.platform) =>+ join(nativeHostDir, platform === 'win32' ? 'browsentic-native-host.cmd' : 'browsentic-native-host');++export interface HostInstall {+ launcher: string;+ browsers: string[];+}++function register(targets: HostTarget[], launcher: string, origins: readonly string[]): string[] {+ const registered: string[] = [];+ for (const target of targets) {+ const manifest = `${JSON.stringify(hostManifest(target.family, launcher, origins), null, 2)}\n`;+ try {+ if (target.registryKey) {+ const file = join(nativeHostDir, `${target.family}.json`);+ writeFileSync(file, manifest);+ execFileSync('reg', ['add', target.registryKey, '/ve', '/t', 'REG_SZ', '/d', file, '/f'], { stdio: 'ignore' });+ } else if (target.manifestDir && existsSync(target.home)) {+ mkdirSync(target.manifestDir, { recursive: true });+ writeFileSync(join(target.manifestDir, `${NATIVE_HOST_NAME}.json`), manifest);+ } else continue;+ registered.push(target.browser);+ } catch (error) {+ log(`native host: could not register for ${target.browser}: ${String(error)}`);+ }+ }+ return registered;+}++export function installNativeHost(cliPath: string, platform: NodeJS.Platform = process.platform): HostInstall {+ const launcher = launcherPath(platform);+ mkdirSync(nativeHostDir, { recursive: true, mode: 0o700 });+ writeFileSync(launcher, launcherScript({ platform, cliPath, nodePath: process.execPath, pathEnv: process.env.PATH ?? '' }));+ if (platform !== 'win32') chmodSync(launcher, 0o755);+ return { launcher, browsers: register(hostTargets(platform), launcher, allowedOrigins(platform)) };+}++/** A newly paired browser has to be let in; the launcher stays as setup wrote it. */+export function refreshNativeHost(platform: NodeJS.Platform = process.platform): void {+ const launcher = launcherPath(platform);+ if (!existsSync(launcher)) return;+ register(hostTargets(platform), launcher, allowedOrigins(platform));+}++export function removeNativeHost(platform: NodeJS.Platform = process.platform): string[] {+ const removed: string[] = [];+ for (const target of hostTargets(platform)) {+ try {+ if (target.registryKey) {+ execFileSync('reg', ['delete', target.registryKey, '/f'], { stdio: 'ignore' });+ removed.push(target.registryKey);+ continue;+ }+ const manifest = join(target.manifestDir!, `${NATIVE_HOST_NAME}.json`);+ if (!existsSync(manifest)) continue;+ rmSync(manifest, { force: true });+ removed.push(manifest);+ } catch {+ continue;+ }+ }+ if (existsSync(nativeHostDir)) {+ rmSync(nativeHostDir, { recursive: true, force: true });+ removed.push(nativeHostDir);+ }+ return removed;+}++export function registeredBrowsers(platform: NodeJS.Platform = process.platform): string[] {+ if (!existsSync(launcherPath(platform))) return [];+ return hostTargets(platform)+ .filter((target) =>+ target.registryKey+ ? existsSync(join(nativeHostDir, `${target.family}.json`))+ : existsSync(join(target.manifestDir!, `${NATIVE_HOST_NAME}.json`)),+ )+ .map((target) => target.browser);+}++export function encodeNativeMessage(value: unknown): Buffer {+ const body = Buffer.from(JSON.stringify(value), 'utf8');+ const head = Buffer.alloc(4);+ head.writeUInt32LE(body.length, 0);+ return Buffer.concat([head, body]);+}++export function decodeNativeMessage(buffer: Buffer): unknown | undefined {+ if (buffer.length < 4) return undefined;+ const length = buffer.readUInt32LE(0);+ if (buffer.length < 4 + length) return undefined;+ try {+ return JSON.parse(buffer.subarray(4, 4 + length).toString('utf8'));+ } catch {+ return null;+ }+}++function readNativeMessage(input: NodeJS.ReadableStream): Promise<unknown> {+ return new Promise((resolve) => {+ let held = Buffer.alloc(0);+ const done = (value: unknown) => {+ input.removeAllListeners('data');+ resolve(value);+ };+ input.on('data', (chunk: Buffer) => {+ held = Buffer.concat([held, chunk]);+ const message = decodeNativeMessage(held);+ if (message !== undefined) done(message);+ });+ input.on('end', () => done(null));+ });+}++export async function serveNativeHost(ensure: () => Promise<{ port: number }>): Promise<void> {+ const message = (await readNativeMessage(process.stdin)) as { op?: unknown } | null;+ const reply =+ message?.op === 'ensure'+ ? await ensure()+ .then((lock) => ({ ok: true, port: lock.port }))+ .catch((error) => ({ ok: false, error: String(error) }))+ : { ok: false, error: 'Expected {"op":"ensure"}.' };+ log(`native host: ${reply.ok ? 'daemon ready' : `could not start the daemon — ${'error' in reply ? reply.error : ''}`}`);+ await new Promise<void>((resolve) => process.stdout.write(encodeNativeMessage(reply), () => resolve()));+}+diff --git a/src/lib/actions/protocol.ts b/src/lib/actions/protocol.tsindex 02cc067..57f32e7 100644--- a/src/lib/actions/protocol.ts+++ b/src/lib/actions/protocol.ts@@ -17,6 +17,9 @@ export const EXTERNAL_RUN_ID = 'external';export const DAEMON_PORTS = [8765, 8766, 8767] as const;+/** The native messaging host the extension asks to start the daemon when no port answers. */+export const NATIVE_HOST_NAME = 'com.browsentic.daemon';+export interface ActionInvocation {channel: typeof ACTION_CHANNEL;action: string;diff --git a/src/lib/bridge/native-wake.ts b/src/lib/bridge/native-wake.tsnew file mode 100644index 0000000..2402f1e--- /dev/null+++ b/src/lib/bridge/native-wake.ts@@ -0,0 +1,15 @@+import { browser } from 'wxt/browser';+import { NATIVE_HOST_NAME } from '@/lib/actions/protocol';++const WAKE_EVERY_MS = 60_000;++let lastAttempt = 0;++/** Asks the browser to run the registered host, which starts a daemon if none is up. False when nothing is registered. */+export async function wakeDaemon(): Promise<boolean> {+ const now = Date.now();+ if (now - lastAttempt < WAKE_EVERY_MS) return false;+ lastAttempt = now;+ const reply = await browser.runtime.sendNativeMessage(NATIVE_HOST_NAME, { op: 'ensure' }).catch(() => null);+ return (reply as { ok?: unknown } | null)?.ok === true;+}diff --git a/src/lib/bridge/socket.ts b/src/lib/bridge/socket.tsindex 99be0a8..db39edd 100644--- a/src/lib/bridge/socket.ts+++ b/src/lib/bridge/socket.ts@@ -32,6 +32,7 @@ import type { SkillDraft } from '@/lib/skills/format';import type { SiteMapDraft } from '@/lib/skills/site-map';import { identify } from './identity';import { invokeForHarness } from './invoke';+import { wakeDaemon } from './native-wake';export const DAEMON_STATE_KEY = 'browsentic/daemon';export const RECONNECT_ALARM = 'browsentic/reconnect';@@ -42,6 +43,7 @@ const MAX_DELAY_MS = 30_000;const STABLE_AFTER_MS = 30_000;const HANDSHAKE_TIMEOUT_MS = 5_000;const PAIRING_TIMEOUT_MS = 20_000;+const WOKEN_RETRY_MS = 500;/** The secret itself stays here; only a proof derived from it ever reaches the socket. */interface Credential {@@ -477,7 +479,13 @@ function giveUp(credential: Credential, refusal?: Refusal): void {return;}settlePairing({ ok: false, error: refusal?.reason ?? 'No Browsentic daemon is running.' });- if (credential.kind === 'session') scheduleRetry(credential);+ if (credential.kind !== 'session') return;+ if (refusal) return scheduleRetry(credential);+ void wakeDaemon().then((woken) => {+ if (!woken) return scheduleRetry(credential);+ clearTimeout(reconnectTimer);+ reconnectTimer = setTimeout(() => dial(credential, 0), WOKEN_RETRY_MS);+ });}function transcriptOf(attempt: Attempt): Transcript {diff --git a/wxt.config.ts b/wxt.config.tsindex d6ec446..9c50ba2 100644--- a/wxt.config.ts+++ b/wxt.config.ts@@ -25,7 +25,7 @@ export default defineConfig({description: 'Reimagine browsing as agentic — driven by the AI agent you already run, in your own logged-in browser.',permissions: ['storage', 'unlimitedStorage', 'activeTab', 'contextMenus', 'alarms', 'scripting',- 'notifications', 'downloads',+ 'notifications', 'downloads', 'nativeMessaging',// Firefox has no sidePanel or debugger permission, and addons.mozilla.org flags each name it does not know....(browser === 'firefox' ? [] : ['sidePanel', 'debugger']),],