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
fix(daemon): on macOS a browser's native host starts the Bridge through launchd, so it no longer inherits the browser's quarantine and Gatekeeper stops refusing the library OpenCode unpacks; a starting Bridge deletes the quarantined copies an older one left behind
Shahriar5c845c0c9623
diff --git a/src/daemon/cli.ts b/src/daemon/cli.tsindex 81fe02b..cb1f28e 100644--- a/src/daemon/cli.ts+++ b/src/daemon/cli.ts@@ -154,7 +154,7 @@ switch (command) {break;case 'native-host':await serveNativeHost({- ensure: (caller) => ensureDaemon({ outsideJob: caller?.family === 'firefox' }),+ ensure: (caller) => ensureDaemon({ outsideJob: caller?.family === 'firefox', outsideBrowser: true }),held: wakeHeld,mode: () => pairingMode(),version: pkg.version,diff --git a/src/daemon/daemon-main.ts b/src/daemon/daemon-main.tsindex 6ed63de..73cbc9d 100644--- a/src/daemon/daemon-main.ts+++ b/src/daemon/daemon-main.ts@@ -2,6 +2,7 @@ import { startAndroid } from './android/service';import { startDaemon } from './daemon';import { log } from './log';import pkg from './package.json';+import { dropQuarantinedBunLibraries } from './quarantine';const daemon = await startDaemon({version: pkg.version,@@ -13,6 +14,10 @@ const daemon = await startDaemon({process.exit(1);});+if (process.platform === 'darwin') {+ for (const file of dropQuarantinedBunLibraries()) log(`removed ${file}, a library an agent unpacked while the Bridge ran quarantined`);+}+for (const signal of ['SIGINT', 'SIGTERM'] as const) {process.on(signal, () => {void daemon.stop().then(() => process.exit(0));diff --git a/src/daemon/ensure-daemon.ts b/src/daemon/ensure-daemon.tsindex 2359f36..60da4be 100644--- a/src/daemon/ensure-daemon.ts+++ b/src/daemon/ensure-daemon.ts@@ -5,6 +5,7 @@ import { dirname, join } from 'node:path';import { clearLockfile, holdWake, isRunning, readLockfile, stateDir, type Lockfile } from './lockfile';import { log } from './log';import { daemonPorts } from './ports';+import { startBridgeJob } from './quarantine';import { runBridgeTask } from './windows-task';const SPAWN_TIMEOUT_MS = 8_000;@@ -17,6 +18,8 @@ export const daemonMainPath = () => join(dirname(fileURLToPath(import.meta.url))export interface EnsureOptions {/** Start it through Task Scheduler: the caller runs in a job that dies with it (Firefox's native host on Windows). */outsideJob?: boolean;+ /** Start it through launchd: the caller is a browser's native host, quarantined on macOS (see quarantine.ts). */+ outsideBrowser?: boolean;}/**@@ -67,17 +70,21 @@ function readStartLock(): [number, number] {}/** One the task started is waited for, never doubled by one spawned in the job that is about to die. */-async function spawnDaemon({ outsideJob = false }: EnsureOptions): Promise<Lockfile> {+async function spawnDaemon({ outsideJob = false, outsideBrowser = false }: EnsureOptions): Promise<Lockfile> {if (outsideJob && process.platform === 'win32' && runBridgeTask()) {log('no daemon reachable; starting one through Task Scheduler');return cameUp();}- log('no daemon reachable; spawning one');const env: NodeJS.ProcessEnv = { ...process.env };delete env.BROWSENTIC_AGENT_RUN;delete env.CLAUDECODE;delete env.CLAUDE_CODE_ENTRYPOINT;delete env.NODE_NO_WARNINGS;+ if (outsideBrowser && process.platform === 'darwin' && startBridgeJob(process.execPath, daemonMainPath(), env)) {+ log('no daemon reachable; starting one through launchd');+ return cameUp();+ }+ log('no daemon reachable; spawning one');const child = spawn(process.execPath, [daemonMainPath()], {detached: true,stdio: 'ignore',diff --git a/src/daemon/quarantine.test.ts b/src/daemon/quarantine.test.tsnew file mode 100644index 0000000..3718563--- /dev/null+++ b/src/daemon/quarantine.test.ts@@ -0,0 +1,111 @@+import { spawnSync } from 'node:child_process';+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, join } from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { BRIDGE_JOB, bridgeJobPlist, dropQuarantinedBunLibraries, startBridgeJob, type Launchd } from './quarantine';++const onMac = process.platform === 'darwin';++describe('the launchd job that starts the Bridge outside the browser', () => {+ let loaded: { plist: string; label: string; existed: boolean }[];+ const jobs: Launchd = {+ load: (file, label) => void loaded.push({ plist: readFileSync(file, 'utf8'), label, existed: existsSync(file) }),+ };++ beforeEach(() => {+ loaded = [];+ });++ it('runs the daemon once, now, with the environment it is handed', () => {+ expect(startBridgeJob('/opt/node/bin/node', '/Users/me/cli/dist/daemon-main.js', { PATH: '/opt/homebrew/bin:/usr/bin', TOKEN: 'a&b<c>' }, jobs)).toBe(true);++ expect(loaded).toHaveLength(1);+ const [{ plist, label, existed }] = loaded;+ expect(existed).toBe(true);+ expect(label).toBe(BRIDGE_JOB);+ expect(label).toMatch(/^com\.browsentic\.bridge\.[0-9a-f]{8}$/);+ expect(plist).toContain('<array><string>/opt/node/bin/node</string><string>/Users/me/cli/dist/daemon-main.js</string></array>');+ expect(plist).toContain('<key>PATH</key><string>/opt/homebrew/bin:/usr/bin</string>');+ expect(plist).toContain('<key>TOKEN</key><string>a&b<c></string>');+ expect(plist).toContain('<key>RunAtLoad</key><true/>');+ expect(plist).not.toContain('KeepAlive');+ });++ it('leaves no property list behind, holding the environment, once launchd has it', () => {+ startBridgeJob('/node', '/daemon-main.js', { SECRET: 'x' }, jobs);++ expect(loaded[0].existed).toBe(true);+ expect(readdirSync(join(process.env.BROWSENTIC_HOME!, 'native-host'))).not.toContain('bridge-job.plist');+ });++ it('keeps the browser’s own launchd service and bundle out of the job', () => {+ const plist = bridgeJobPlist('/node', '/daemon-main.js', {+ HOME: '/Users/me',+ XPC_SERVICE_NAME: 'application.com.google.Chrome.1234.5678',+ XPC_FLAGS: '0x0',+ __CFBundleIdentifier: 'com.google.Chrome',+ });++ expect(plist).toContain('<key>HOME</key><string>/Users/me</string>');+ expect(plist).not.toContain('XPC_');+ expect(plist).not.toContain('Chrome');+ });++ it('says so when launchd refuses it, so the caller spawns the Bridge itself', () => {+ const refusing: Launchd = {+ load: () => {+ throw new Error('Bootstrap failed: 5: Input/output error');+ },+ };++ expect(startBridgeJob('/node', '/daemon-main.js', {}, refusing)).toBe(false);+ expect(readFileSync(join(process.env.BROWSENTIC_HOME!, 'daemon.log'), 'utf8')).toContain('could not start the Bridge through launchd');+ });++ it.runIf(onMac)('is a property list launchd can read', () => {+ const dir = mkdtempSync(join(tmpdir(), 'browsentic-plist-'));+ const file = join(dir, 'job.plist');+ writeFileSync(file, bridgeJobPlist('/node', '/daemon-main.js', { ODD: '"quoted" & <tagged> \'single\'' }));++ try {+ expect(spawnSync('plutil', ['-lint', file], { encoding: 'utf8' }).stdout).toContain('OK');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++describe('libraries a Bun-built agent unpacked while the Bridge ran quarantined', () => {+ let dir: string;+ const uid = 501;+ const touch = (...names: string[]) => names.forEach((name) => writeFileSync(join(dir, name), ''));++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'browsentic-bun-'));+ });++ afterEach(() => rmSync(dir, { recursive: true, force: true }));++ it('removes this user’s quarantined ones and leaves everything else', () => {+ touch('.bun-501-1d98d107b4c544c0.dylib', '.bun-501-aaaaaaaaaaaaaaaa.node', '.bun-502-bbbbbbbbbbbbbbbb.dylib', 'libsomething.dylib');+ const marked = new Set(['.bun-501-1d98d107b4c544c0.dylib', '.bun-502-bbbbbbbbbbbbbbbb.dylib', 'libsomething.dylib']);++ const dropped = dropQuarantinedBunLibraries({ dir, uid, quarantined: (file) => marked.has(basename(file)) });++ expect(dropped).toEqual([join(dir, '.bun-501-1d98d107b4c544c0.dylib')]);+ expect(readdirSync(dir).sort()).toEqual(['.bun-501-aaaaaaaaaaaaaaaa.node', '.bun-502-bbbbbbbbbbbbbbbb.dylib', 'libsomething.dylib']);+ });++ it('finds nothing to do in a folder that is not there', () => {+ expect(dropQuarantinedBunLibraries({ dir: join(dir, 'gone'), uid, quarantined: () => true })).toEqual([]);+ });++ it.runIf(onMac)('reads the quarantine flag macOS set', () => {+ touch('.bun-501-cccccccccccccccc.dylib', '.bun-501-dddddddddddddddd.dylib');+ spawnSync('/usr/bin/xattr', ['-w', 'com.apple.quarantine', '0081;6ae24f49;Chrome;', join(dir, '.bun-501-cccccccccccccccc.dylib')]);++ expect(dropQuarantinedBunLibraries({ dir, uid })).toEqual([join(dir, '.bun-501-cccccccccccccccc.dylib')]);+ expect(readdirSync(dir)).toEqual(['.bun-501-dddddddddddddddd.dylib']);+ });+});diff --git a/src/daemon/quarantine.ts b/src/daemon/quarantine.tsnew file mode 100644index 0000000..3a65618--- /dev/null+++ b/src/daemon/quarantine.ts@@ -0,0 +1,126 @@+/**+ * A browser on macOS runs its native hosts quarantined, and every process a quarantined one starts is+ * quarantined too. A Bridge the host spawned would mark each file it and its agent CLIs write as+ * downloaded by the browser, and Gatekeeper refuses any of those that is code and not notarized, such+ * as the library OpenCode unpacks into the temporary folder before loading it. A Bridge that launchd+ * starts is no child of the browser and writes its files unmarked.+ */++import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { stateDir } from './lockfile';+import { log } from './log';++/** One per Bridge home, so that a scratch Bridge never boots out the real one. */+export const BRIDGE_JOB = `com.browsentic.bridge.${createHash('sha256').update(stateDir).digest('hex').slice(0, 8)}`;++export interface Launchd {+ /** Loads the job afresh, which starts it. Throws when launchd refuses it. */+ load(plistFile: string, label: string): void;+}++const launchctl = (args: string[]) => {+ const { status, stderr } = spawnSync('/bin/launchctl', args, { encoding: 'utf8' });+ if (status !== 0) throw new Error(stderr.trim() || `launchctl ${args[0]} exited with ${status}`);+};++export const launchd: Launchd = {+ load: (plistFile, label) => {+ const domain = `gui/${process.getuid?.()}`;+ try {+ launchctl(['bootout', `${domain}/${label}`]);+ } catch {+ // Not loaded: no Bridge was started this way since login.+ }+ launchctl(['bootstrap', domain, plistFile]);+ },+};++const escapeXml = (value: string) => value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+const plistString = (value: string) => `<string>${escapeXml(value)}</string>`;++/** Name the browser's own launchd service and bundle, which this job is not. */+const namesTheBrowser = (key: string) => key.startsWith('XPC_') || key === '__CFBundleIdentifier';++/**+ * Runs once, as it loads, with the host's environment, and leaves what it started running when it+ * exits, as the detached spawn it stands in for does. Interactive spares it the CPU and I/O+ * throttling launchd gives a job of no declared type.+ */+export function bridgeJobPlist(nodePath: string, daemonMain: string, env: NodeJS.ProcessEnv): string {+ const variables = Object.entries(env)+ .filter((entry): entry is [string, string] => entry[1] !== undefined && !namesTheBrowser(entry[0]))+ .map(([key, value]) => ` <key>${escapeXml(key)}</key>${plistString(value)}`);+ return [+ '<?xml version="1.0" encoding="UTF-8"?>',+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',+ '<plist version="1.0">',+ '<dict>',+ ` <key>Label</key>${plistString(BRIDGE_JOB)}`,+ ` <key>ProgramArguments</key><array>${plistString(nodePath)}${plistString(daemonMain)}</array>`,+ ' <key>EnvironmentVariables</key>',+ ' <dict>',+ ...variables,+ ' </dict>',+ ' <key>RunAtLoad</key><true/>',+ ' <key>AbandonProcessGroup</key><true/>',+ ' <key>ProcessType</key><string>Interactive</string>',+ '</dict>',+ '</plist>',+ '',+ ].join('\n');+}++export function startBridgeJob(nodePath: string, daemonMain: string, env: NodeJS.ProcessEnv, jobs: Launchd = launchd): boolean {+ const dir = join(stateDir, 'native-host');+ const file = join(dir, 'bridge-job.plist');+ try {+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ writeFileSync(file, bridgeJobPlist(nodePath, daemonMain, env), { mode: 0o600 });+ jobs.load(file, BRIDGE_JOB);+ return true;+ } catch (error) {+ log(`native host: could not start the Bridge through launchd: ${String(error)}`);+ return false;+ } finally {+ rmSync(file, { force: true });+ }+}++const hasQuarantine = (file: string) =>+ spawnSync('/usr/bin/xattr', ['-p', 'com.apple.quarantine', file], { stdio: 'ignore' }).status === 0;++export interface BunLibraries {+ dir?: string;+ uid?: number;+ quarantined?: (file: string) => boolean;+}++/**+ * Bun-built CLIs, OpenCode among them, unpack their native libraries into the temporary folder as+ * `.bun-<uid>-<hash>.<ext>` and reuse that copy on every later start. One unpacked under a quarantined+ * Bridge stays quarantined, and Gatekeeper refuses it with a dialog at each start until it is gone.+ */+export function dropQuarantinedBunLibraries({ dir = tmpdir(), uid = process.getuid?.() ?? 0, quarantined = hasQuarantine }: BunLibraries = {}): string[] {+ let names: string[];+ try {+ names = readdirSync(dir);+ } catch {+ return [];+ }+ const dropped: string[] = [];+ for (const name of names.filter((entry) => entry.startsWith(`.bun-${uid}-`))) {+ const file = join(dir, name);+ if (!quarantined(file)) continue;+ try {+ rmSync(file, { force: true });+ dropped.push(file);+ } catch {+ continue;+ }+ }+ return dropped;+}