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): route every run through guardrails and the chosen agent
Shahriar061159026182
diff --git a/mcp/src/agent/service.ts b/mcp/src/agent/service.tsindex 5ecaf48..c69fbba 100644--- a/mcp/src/agent/service.ts+++ b/mcp/src/agent/service.ts@@ -10,13 +10,27 @@ import {type RunEvent,} from '@/lib/actions/protocol';import { READ_SITEMAP_ACTION } from '@/lib/actions/reserved';+import { activeRunner, AGENTS, type AgentKind } from '@/lib/agents/catalog';import { SAVE_SITE_MAP_ACTION, SITE_MAPPER_SKILL, validateSiteMapReport } from '@/lib/skills/site-map';+import {+ blocked,+ decide,+ declined,+ describe as describeDecision,+ normalizeHost,+ policyFrom,+ scopeFor,+ summary as summarizeDecision,+ type Policy,+ type Scope,+} from '../guardrails';import { log } from '../log';+import { isGranted, rememberGrant } from './approvals';import { readAgentConfig, siteMapSettings, type AgentConfig } from './config';-import { needsApproval } from './effects';import { gateMappingInvoke, noteMappingResult, type MapRun } from './mapping';import { buildSystemPrompt } from './prompt';import { RunError, runInstruction } from './runner';+import { agentState } from './runners';import {discardStaging,mapTargetFor,@@ -42,13 +56,23 @@ export interface AgentSessionDeps {interface ActiveRun {id: string;config: AgentConfig;+ policy: Policy;+ scope: Scope;abort: AbortController;- pending: Map<string, (allow: boolean) => void>;+ pending: Map<string, (answer: Decision) => void>;+ /** Host of the tab this run started on — what "this site" means on an approval card. */+ site?: string;map?: MapRun;}+interface Decision {+ allow: boolean;+ remember?: boolean;+}+export class AgentSession {- private claudeSession: string | null = null;+ /** The conversation the current agent is holding open. Switching agents drops it. */+ private held: { agent: AgentKind; sessionId: string } | null = null;private active: ActiveRun | null = null;constructor(private readonly deps: AgentSessionDeps) {}@@ -62,10 +86,10 @@ export class AgentSession {this.cancel(request.id);return;case 'decision':- this.active?.pending.get(request.toolId)?.(request.allow);+ this.active?.pending.get(request.toolId)?.({ allow: request.allow, remember: request.remember });return;case 'reset':- this.claudeSession = null;+ this.held = null;log('agent conversation reset');return;}@@ -104,15 +128,21 @@ export class AgentSession {return result;}- if (needsApproval(run.config.requireApproval, action, input)) {- emit({ kind: 'approval', toolId, action, input });- if (!(await this.awaitDecision(run, toolId))) {+ const decision = decide({ action, input, caller: 'agent', scope: run.scope }, run.policy);+ if (decision.effect === 'deny') {+ log(`agent run ${runId} blocked ${action}: ${describeDecision(decision)}`);+ emit({ kind: 'toolResult', toolId, ok: false, summary: `blocked: ${summarizeDecision(decision)}` });+ return blocked(decision);+ }+ if (decision.effect === 'confirm' && !(run.site && isGranted(action, run.site))) {+ emit({ kind: 'approval', toolId, action, input, site: run.site });+ const answer = await this.awaitDecision(run, toolId);+ if (!answer.allow) {+ log(`agent run ${runId} declined ${action}: ${describeDecision(decision)}`);emit({ kind: 'toolResult', toolId, ok: false, summary: 'declined by the user' });- return failure(- 'DECLINED',- 'The user declined this action. Do not retry it and do not try to achieve the same effect another way. Tell the user it was declined and stop.',- );+ return declined();}+ if (answer.remember && run.site) rememberGrant(action, run.site, new Date().toISOString());}const result = await this.deps.invoke(action, input);@@ -123,7 +153,7 @@ export class AgentSession {dispose(): void {if (this.active) this.cancel(this.active.id);- this.claudeSession = null;+ this.held = null;}private async start(runId: string, instruction: string, context?: RunContext): Promise<void> {@@ -160,9 +190,38 @@ export class AgentSession {}const overlayNames = routed.overlays.map((overlay) => overlay.name);- const run: ActiveRun = { id: runId, config, abort: new AbortController(), pending: new Map() };+ const policy = policyFrom(config.guardrails, config.requireApproval);+ const scope = scopeFor({+ url: context?.url,+ tabId: context?.tabId,+ instruction: text,+ extraHosts: config.guardrails?.hosts,+ pinTab: true,+ });+ const run: ActiveRun = {+ id: runId,+ config,+ policy,+ scope,+ site: siteOf(context?.url),+ abort: new AbortController(),+ pending: new Map(),+ };this.active = run;+ // Claim the slot before probing, so a second instruction still meets RUN_IN_PROGRESS.+ const runner = activeRunner(await agentState(config));+ if (!runner?.ready) {+ const problem = runner?.problem;+ if (this.active === run) this.active = null;+ log(`agent run ${runId} refused: ${AGENTS[config.agent].label} is not ready`);+ return emit({+ kind: 'error',+ code: problem?.code ?? 'AGENT_MISSING',+ message: `${AGENTS[config.agent].label} cannot run. ${problem?.message ?? 'It is not available.'}${problem?.fix ? ` ${problem.fix}` : ''}`,+ });+ }+let built: { prompt: string; dropped: string[] };let instructionText = routed.text;try {@@ -196,10 +255,9 @@ export class AgentSession {);emit({ kind: 'started', skill: routed.base.name, overlays: [...overlayNames, ...built.dropped.map((n) => `${n} (too large — not applied)`)] });- const supplied = mapping ? null : validSessionId(context?.claudeSessionId);- const known = supplied ?? this.claudeSession;- const resume = !mapping && known !== null;- const sessionId = mapping ? randomUUID() : (known ?? randomUUID());+ const held = this.held?.agent === config.agent ? this.held.sessionId : null;+ const supplied = mapping ? null : sessionFrom(context, config.agent);+ const resuming = mapping ? null : (supplied ?? held);const budget = run.map ? setTimeout(() => run.abort.abort(), run.map.settings.timeoutMs) : undefined;try {@@ -209,15 +267,15 @@ export class AgentSession {systemPrompt: built.prompt,research: run.map ? run.map.settings.research : false,config: run.config,- sessionId,- resume,+ sessionId: resuming,signal: run.abort.signal,emit,});- if (outcome.established) this.claudeSession = sessionId;if (!mapping) {- if (outcome.established) emit({ kind: 'session', claudeSessionId: sessionId });- else if (supplied) emit({ kind: 'session', claudeSessionId: null });+ this.held = outcome.sessionId ? { agent: config.agent, sessionId: outcome.sessionId } : null;+ if (outcome.sessionId !== resuming) {+ emit({ kind: 'session', agent: config.agent, agentSessionId: outcome.sessionId });+ }}log(`agent run ${runId} finished (${outcome.stopReason})`);emit({ kind: 'done', stopReason: outcome.stopReason });@@ -328,26 +386,35 @@ export class AgentSession {return;}const cancelled = this.active;- for (const [, settle] of cancelled.pending) settle(false);+ for (const [, settle] of cancelled.pending) settle({ allow: false });cancelled.pending.clear();cancelled.abort.abort();this.active = null;log(`agent run ${runId} cancelled`);}- private awaitDecision(run: ActiveRun, toolId: string): Promise<boolean> {- if (run.abort.signal.aborted) return Promise.resolve(false);+ private awaitDecision(run: ActiveRun, toolId: string): Promise<Decision> {+ if (run.abort.signal.aborted) return Promise.resolve({ allow: false });return new Promise((resolve) => {- const settle = (allow: boolean) => {+ const settle = (answer: Decision) => {run.pending.delete(toolId);- resolve(allow);+ resolve(answer);};run.pending.set(toolId, settle);- run.abort.signal.addEventListener('abort', () => settle(false), { once: true });+ run.abort.signal.addEventListener('abort', () => settle({ allow: false }), { once: true });});}}+function siteOf(url?: string): string | undefined {+ if (!url) return undefined;+ try {+ return normalizeHost(new URL(url).hostname) ?? undefined;+ } catch {+ return undefined;+ }+}+function explicitlyAsked(text: string): boolean {return /^@site-mapper\b/i.test(text.trim());}@@ -421,10 +488,13 @@ function recordingsBlock(recordings: SavedRecording[] | undefined): string | undconst flatten = (text: string) => text.replace(/\s+/g, ' ').trim();-const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+/** Agents name their own sessions: UUIDs, thread ids, conversation ids. Accept any tame token. */+const SESSION_ID = /^[A-Za-z0-9._:-]{6,200}$/;-function validSessionId(id: string | undefined): string | null {- return typeof id === 'string' && UUID.test(id) ? id : null;+function sessionFrom(context: RunContext | undefined, agent: AgentKind): string | null {+ if (context?.agent !== agent) return null;+ const id = context.agentSessionId;+ return typeof id === 'string' && SESSION_ID.test(id) ? id : null;}function fetchedBlock(origin: string, index: SiteIndex): string {diff --git a/mcp/src/control.ts b/mcp/src/control.tsindex 32d330a..13c441a 100644--- a/mcp/src/control.ts+++ b/mcp/src/control.ts@@ -1,5 +1,6 @@import type { ActionResult } from '@/lib/actions/protocol';import type { ToolDescriptor } from '@/lib/actions/manifest';+import type { AgentKind, AgentState } from '@/lib/agents/catalog';export interface BridgeStatus {connected: boolean;@@ -26,7 +27,8 @@ export type ControlRequest =| { id: string; op: 'invoke'; action: string; input?: unknown; runId?: string }| { id: string; op: 'pair' }| { id: string; op: 'sessions' }- | { id: string; op: 'revoke'; origin?: string };+ | { id: string; op: 'revoke'; origin?: string }+ | { id: string; op: 'agent'; set?: AgentKind; grant?: AgentKind };export type ControlMessage =| { id: string; op: 'describe'; tools: ToolDescriptor[] }@@ -35,6 +37,7 @@ export type ControlMessage =| { id: string; op: 'pair'; code: string; expiresAt: number }| { id: string; op: 'sessions'; sessions: SessionSummary[] }| { id: string; op: 'revoke'; revoked: number }+ | { id: string; op: 'agent'; state: AgentState }| { event: 'manifest-changed' };export interface Bridge {diff --git a/mcp/src/daemon.ts b/mcp/src/daemon.tsindex 706fbc7..bbd3fbc 100644--- a/mcp/src/daemon.ts+++ b/mcp/src/daemon.ts@@ -8,36 +8,64 @@ import {SOCKET_PROTOCOL_VERSION,failure,parseFrame,+ success,type ActionResult,type RunEvent,+ type SocketFrame,} from '@/lib/actions/protocol';import { hashManifest } from '@/lib/actions/manifest';import { describeActions } from '@/lib/actions/registry';import { RESERVED_PREFIX } from '@/lib/actions/reserved';+import { AGENTS, isAgentKind, type AgentState } from '@/lib/agents/catalog';import { saveScreenshot } from './screenshots';+import {+ clientProof,+ isNonce,+ newNonce,+ pairingSecret,+ sameProof,+ sealSessionKey,+ serverProof,+ type Transcript,+} from '@/lib/actions/handshake';import {consumePairing,createPairing,createSession,hasPendingPairing,listSessions,+ pendingPairings,revokeSessions,- validateSession,+ sessionFor,+ touchSession,} from './auth-store';import { AgentSession } from './agent/service';import { summarizeFile } from './agent/analyze';import { analyzeRecording } from './agent/recording';import { nameSession } from './agent/title';-import { readAgentConfig } from './agent/config';+import { readAgentConfig, writeActiveAgent } from './agent/config';+import { agentState, grantRunner } from './agent/runners';import { deleteSiteMap, deleteSkill, saveSkill } from './agent/skill-store';import { commitStaging, discardStaging } from './agent/site-map-store';import type { Bridge, BridgeStatus, ControlMessage, ControlRequest, SessionSummary } from './control';import { ExtensionLink } from './extension-link';+import {+ ANYWHERE,+ blocked,+ decide,+ describe as describeDecision,+ policyFrom,+ summary as summarizeDecision,+} from './guardrails';import { log } from './log';import { readLockfile, writeLockfile, clearLockfile, type Lockfile } from './lockfile';+type AgentFrame = Extract<SocketFrame, { t: 'agentState' | 'setAgent' | 'grantAgent' }>;+const IDLE_EXIT_MS = 30 * 60 * 1000;+const HANDSHAKE_TIMEOUT_MS = 10_000;const EXTENSION_ORIGIN = /^(chrome|moz|safari-web)-extension:\/\//;+const LOOPBACK_HOST = /^(127\.0\.0\.1|\[::1\]|localhost)(:\d+)?$/i;export interface DaemonOptions {version: string;@@ -58,7 +86,7 @@ function persistScreenshot(if (action !== 'page.screenshot' || !result.ok) return result;const args = (input ?? {}) as { save?: unknown; filename?: unknown };const data = result.data as { dataUrl?: unknown } | null;- if ((args.save === false && !saveTo) || typeof data?.dataUrl !== 'string') return result;+ if ((args.save !== true && !saveTo) || typeof data?.dataUrl !== 'string') return result;try {const savedTo = saveScreenshot(data.dataUrl, {dir: saveTo?.dir,@@ -86,16 +114,20 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):const manifestListeners = new Set<() => void>();let idleTimer: ReturnType<typeof setTimeout> | null = null;- const previous = readLockfile();const lock: Lockfile = {pid: process.pid,port: 0,- token: previous?.token ?? randomBytes(24).toString('base64url'),+ // Fresh per daemon, so a token that leaked once does not stay valid for every future daemon.+ token: randomBytes(24).toString('base64url'),protocolVersion: SOCKET_PROTOCOL_VERSION,daemonVersion: version,};const http = createServer((req, res) => {+ if (!fromLoopback(req)) {+ res.writeHead(403).end();+ return;+ }if (req.url?.startsWith('/health')) {res.writeHead(200, { 'content-type': 'application/json' });res.end(JSON.stringify({ ok: true, pid: process.pid, version, connected: !!link?.isOpen }));@@ -121,6 +153,10 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):scheduleIdleExit();function authorize(req: IncomingMessage): 'extension' | 'control' | null {+ if (!fromLoopback(req)) {+ log(`rejected host ${req.headers.host}`);+ return null;+ }const origin = req.headers.origin;if (origin && EXTENSION_ORIGIN.test(origin)) return 'extension';if (origin) {@@ -142,6 +178,13 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):}function acceptExtension(ws: WebSocket, req: IncomingMessage): void {+ void greet(ws, req).catch((error) => {+ log('extension handshake failed', error);+ ws.close(1011, 'handshake failed');+ });+ }++ async function greet(ws: WebSocket, req: IncomingMessage): Promise<void> {const reject = (reason: string, retryable: boolean) => {log(`rejected extension: ${reason}`);try {@@ -151,114 +194,185 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):ws.close(4401, 'unauthorized');};- ws.once('message', async (raw) => {- const hello = parseFrame(String(raw));- if (hello?.t !== 'hello') {- log('extension sent no hello frame; closing');- ws.close(1002, 'expected hello');- return;+ const hello = await nextFrame(ws);+ if (hello?.t !== 'hello') {+ log('extension sent no hello frame; closing');+ ws.close(1002, 'expected hello');+ return;+ }+ if (hello.protocolVersion !== SOCKET_PROTOCOL_VERSION) {+ log(`extension protocol v${hello.protocolVersion} != daemon v${SOCKET_PROTOCOL_VERSION}; closing`);+ ws.close(1002, `protocol version mismatch: daemon speaks v${SOCKET_PROTOCOL_VERSION}`);+ return;+ }+ if (!isNonce(hello.nonce)) {+ log('extension hello carried no nonce; closing');+ ws.close(1002, 'expected a nonce');+ return;+ }++ const transcript: Transcript = {+ protocolVersion: SOCKET_PROTOCOL_VERSION,+ extensionVersion: hello.extensionVersion,+ manifestHash: hello.manifestHash,+ clientNonce: hello.nonce,+ serverNonce: newNonce(),+ };+ ws.send(JSON.stringify({ t: 'challenge', nonce: transcript.serverNonce }));++ const proven = await nextFrame(ws);+ if (proven?.t !== 'prove') {+ log('extension sent no proof; closing');+ ws.close(1002, 'expected a proof');+ return;+ }++ const origin = req.headers.origin!;+ let secret: string;+ let sealedSessionKey: string | undefined;+ if (hello.auth?.kind === 'pair') {+ const matched = await matchPairing(proven.proof, transcript);+ if (!matched) {+ return reject('That pairing code is wrong or expired. Run "browsentic-mcp pair" for a new one.', true);}- if (hello.protocolVersion !== SOCKET_PROTOCOL_VERSION) {- log(`extension protocol v${hello.protocolVersion} != daemon v${SOCKET_PROTOCOL_VERSION}; closing`);- ws.close(1002, `protocol version mismatch: daemon speaks v${SOCKET_PROTOCOL_VERSION}`);- return;+ consumePairing(matched.code);+ secret = matched.secret;+ const session = createSession(origin, hello.extensionVersion);+ sealedSessionKey = await sealSessionKey(secret, transcript, session.key);+ log(`paired ${origin} (extension ${hello.extensionVersion})`);+ } else if (hello.auth?.kind === 'session') {+ const session = sessionFor(origin);+ if (!session || !sameProof(proven.proof, await clientProof(session.key, transcript))) {+ return reject('This browser is no longer paired. Run "browsentic-mcp pair" to pair again.', false);}+ touchSession(origin);+ secret = session.key;+ } else {+ return reject('That hello named no credential to prove.', false);+ }++ await settle(ws, hello, origin, transcript, secret, sealedSessionKey);+ }- const origin = req.headers.origin!;- const auth = hello.auth;- let issuedKey: string | undefined;- if (auth && 'pairingToken' in auth) {- if (!consumePairing(auth.pairingToken)) {- return reject('That pairing code is wrong or expired. Run "browsentic-mcp pair" for a new one.', true);+ async function matchPairing(+ proof: unknown,+ transcript: Transcript,+ ): Promise<{ code: string; secret: string } | null> {+ for (const code of pendingPairings()) {+ const secret = await pairingSecret(code, transcript);+ if (sameProof(proof, await clientProof(secret, transcript))) return { code, secret };+ }+ return null;+ }++ async function settle(+ ws: WebSocket,+ hello: Extract<SocketFrame, { t: 'hello' }>,+ origin: string,+ transcript: Transcript,+ secret: string,+ sealedSessionKey?: string,+ ): Promise<void> {+ link?.close('superseded by a newer connection');+ agent?.dispose();+ manifestInSync = hello.manifestHash === bundledHash;+ const accepted = new ExtensionLink(+ ws,+ { ...hello, origin },+ (closing) => {+ if (link !== closing) return;+ link = null;+ agent?.dispose();+ agent = null;+ log('extension disconnected');+ scheduleIdleExit();+ },+ (request, source) => {+ if (request.t === 'analyzeFile') {+ void summarizeFile(request, readAgentConfig())+ .then((result) => source.send({ t: 'fileSummary', id: request.id, result }))+ .catch((error) =>+ source.send({ t: 'fileSummary', id: request.id, result: failure('AGENT_FAILED', String(error)) }),+ );+ return;}- issuedKey = createSession(origin, hello.extensionVersion).key;- log(`paired ${origin} (extension ${hello.extensionVersion})`);- } else if (auth && 'sessionKey' in auth) {- if (!validateSession(auth.sessionKey, origin)) {- return reject('This browser is no longer paired. Run "browsentic-mcp pair" to pair again.', false);+ if (request.t === 'nameSession') {+ void nameSession(request, readAgentConfig())+ .then((result) => source.send({ t: 'sessionName', id: request.id, result }))+ .catch((error) =>+ source.send({ t: 'sessionName', id: request.id, result: failure('AGENT_FAILED', String(error)) }),+ );+ return;}- } else {- return reject('No pairing token or session key supplied.', false);- }+ if (request.t === 'analyzeRecording') {+ void analyzeRecording(request, readAgentConfig())+ .then((result) => source.send({ t: 'recordingWorkflow', id: request.id, result }))+ .catch((error) =>+ source.send({+ t: 'recordingWorkflow',+ id: request.id,+ result: failure('AGENT_FAILED', String(error)),+ }),+ );+ return;+ }+ if (request.t === 'agentState' || request.t === 'setAgent' || request.t === 'grantAgent') {+ void settleAgent(request).then((state) =>+ source.send({ t: 'agentInfo', id: request.id, result: state }),+ );+ return;+ }+ if (request.t === 'saveSkill') {+ return source.send({ t: 'skillResult', id: request.id, result: saveSkill(request.skill) });+ }+ if (request.t === 'deleteSkill') {+ return source.send({ t: 'skillResult', id: request.id, result: deleteSkill(request.name) });+ }+ if (request.t === 'deleteSiteMap') {+ return source.send({ t: 'skillResult', id: request.id, result: deleteSiteMap(request.name) });+ }+ if (request.t === 'activateSiteMap') {+ const result = commitStaging(request.stagingId, request.exactHost === true);+ return source.send({+ t: 'skillResult',+ id: request.id,+ result: result.ok ? { ok: true, data: { name: result.data.name, path: result.data.path } } : result,+ });+ }+ if (request.t === 'discardSiteMap') {+ return source.send({ t: 'skillResult', id: request.id, result: discardStaging(request.stagingId) });+ }+ session(source).handle(request);+ },+ );+ link = accepted;+ log(`extension ${hello.extensionVersion} connected from ${origin} (manifest ${manifestInSync ? 'in sync' : 'DRIFTED'})`);+ const welcome = { daemonVersion: version, manifestHash: bundledHash, manifestInSync, sealedSessionKey };+ accepted.send({ t: 'welcome', ...welcome, proof: await serverProof(secret, transcript, welcome) });+ scheduleIdleExit();+ void pushAgentState(accepted);+ if (manifestInSync) restoreBundledManifest();+ else await adoptExtensionManifest(accepted);+ }- link?.close('superseded by a newer connection');- agent?.dispose();- manifestInSync = hello.manifestHash === bundledHash;- const accepted = new ExtensionLink(- ws,- { ...hello, origin },- (closing) => {- if (link !== closing) return;- link = null;- agent?.dispose();- agent = null;- log('extension disconnected');- scheduleIdleExit();- },- (request, source) => {- if (request.t === 'analyzeFile') {- void summarizeFile(request, readAgentConfig())- .then((result) => source.send({ t: 'fileSummary', id: request.id, result }))- .catch((error) =>- source.send({ t: 'fileSummary', id: request.id, result: failure('AGENT_FAILED', String(error)) }),- );- return;- }- if (request.t === 'nameSession') {- void nameSession(request, readAgentConfig())- .then((result) => source.send({ t: 'sessionName', id: request.id, result }))- .catch((error) =>- source.send({ t: 'sessionName', id: request.id, result: failure('AGENT_FAILED', String(error)) }),- );- return;- }- if (request.t === 'analyzeRecording') {- void analyzeRecording(request, readAgentConfig())- .then((result) => source.send({ t: 'recordingWorkflow', id: request.id, result }))- .catch((error) =>- source.send({- t: 'recordingWorkflow',- id: request.id,- result: failure('AGENT_FAILED', String(error)),- }),- );- return;- }- if (request.t === 'saveSkill') {- return source.send({ t: 'skillResult', id: request.id, result: saveSkill(request.skill) });- }- if (request.t === 'deleteSkill') {- return source.send({ t: 'skillResult', id: request.id, result: deleteSkill(request.name) });- }- if (request.t === 'deleteSiteMap') {- return source.send({ t: 'skillResult', id: request.id, result: deleteSiteMap(request.name) });- }- if (request.t === 'activateSiteMap') {- const result = commitStaging(request.stagingId, request.exactHost === true);- return source.send({- t: 'skillResult',- id: request.id,- result: result.ok ? { ok: true, data: { name: result.data.name, path: result.data.path } } : result,- });- }- if (request.t === 'discardSiteMap') {- return source.send({ t: 'skillResult', id: request.id, result: discardStaging(request.stagingId) });- }- session(source).handle(request);- },- );- link = accepted;- log(`extension ${hello.extensionVersion} connected from ${origin} (manifest ${manifestInSync ? 'in sync' : 'DRIFTED'})`);- accepted.send({- t: 'welcome',- daemonVersion: version,- manifestHash: bundledHash,- manifestInSync,- sessionKey: issuedKey,- });- scheduleIdleExit();- if (!manifestInSync) await adoptExtensionManifest(accepted);- });+ async function settleAgent(request: AgentFrame): Promise<ActionResult<AgentState>> {+ if (request.t !== 'agentState' && !isAgentKind(request.agent)) {+ return failure('INVALID_INPUT', `"${String(request.agent)}" is not an agent Browsentic knows.`);+ }+ if (request.t === 'setAgent') {+ writeActiveAgent(request.agent);+ // The held conversation belongs to the agent that just left; the next turn starts fresh.+ agent?.handle({ t: 'reset' });+ log(`agent set to ${AGENTS[request.agent].label}`);+ }+ if (request.t === 'grantAgent') await grantRunner(request.agent);+ const refresh = request.t !== 'agentState' || request.refresh === true;+ return success(await agentState(readAgentConfig(), { refresh }));+ }++ async function pushAgentState(target: ExtensionLink): Promise<void> {+ const state = await agentState(readAgentConfig());+ if (target.isOpen) target.send({ t: 'agentInfo', id: '', result: success(state) });}function session(source: ExtensionLink): AgentSession {@@ -277,6 +391,20 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):}tools = reported;log(`adopted ${reported.length} tools from the extension (bundled list was ${bundled.length})`);+ announceManifest();+ }++ // An adopted list outlives the connection that justified it, so a reloaded extension that+ // agrees with us again would otherwise keep being served the drifted list until the daemon+ // restarts — the recovery direction of "the newer side wins".+ function restoreBundledManifest(): void {+ if (tools === bundled) return;+ tools = bundled;+ log(`extension back in sync; serving the bundled ${bundled.length} tools again`);+ announceManifest();+ }++ function announceManifest(): void {for (const listener of manifestListeners) listener();broadcast({ event: 'manifest-changed' });}@@ -316,6 +444,21 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):if (request.op === 'sessions') {return send(ws, { id: request.id, op: 'sessions', sessions: sessionSummaries() });}+ if (request.op === 'agent') {+ const changed = request.set ?? request.grant;+ if (changed && !isAgentKind(changed)) {+ return send(ws, { id: request.id, op: 'agent', state: await agentState(readAgentConfig()) });+ }+ if (request.set) {+ writeActiveAgent(request.set);+ agent?.handle({ t: 'reset' });+ log(`control ${client} set the agent to ${AGENTS[request.set].label}`);+ }+ if (request.grant) await grantRunner(request.grant);+ const state = await agentState(readAgentConfig(), { refresh: !!changed });+ if (changed && link?.isOpen) void pushAgentState(link);+ return send(ws, { id: request.id, op: 'agent', state });+ }if (request.op === 'revoke') {const target = request.origin;const revoked = revokeSessions((session) => !target || session.origin === target);@@ -386,6 +529,23 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):if (target?.isOpen) target.send({ t: 'run', id: EXTERNAL_RUN_ID, event });};tell({ kind: 'tool', toolId, action, input, source: 'external' });++ // An external MCP client has no run and no approval channel, so it is unscoped and+ // its confirms resolve through the policy's `unattended` setting.+ const config = readAgentConfig();+ const decision = decide(+ { action, input, caller: 'external', scope: ANYWHERE },+ policyFrom(config.guardrails, config.requireApproval),+ );+ if (decision.effect === 'deny') {+ log(`external ${client} → ${action} blocked: ${describeDecision(decision)}`);+ tell({ kind: 'toolResult', toolId, ok: false, summary: `blocked: ${summarizeDecision(decision)}` });+ return blocked(decision);+ }+ if (decision.matched.length) {+ log(`external ${client} → ${action} waived: ${describeDecision(decision)}`);+ }+const result = await invoke(action, input);log(`external ${client} → ${action} ${result.ok ? 'ok' : result.error.code}`);tell({@@ -458,6 +618,27 @@ function listen(http: Server): Promise<number> {});}+/**+ * A page rebound to 127.0.0.1 by its own DNS still arrives with the attacker's `Host`, so this is+ * the second lock on the door the `Origin` check already guards.+ */+function fromLoopback(req: IncomingMessage): boolean {+ return LOOPBACK_HOST.test(req.headers.host ?? '');+}++function nextFrame(ws: WebSocket): Promise<SocketFrame | null> {+ return new Promise((resolve) => {+ const settle = (frame: SocketFrame | null) => {+ clearTimeout(timer);+ ws.off('message', onMessage);+ resolve(frame);+ };+ const onMessage = (raw: unknown) => settle(parseFrame(String(raw)));+ const timer = setTimeout(() => settle(null), HANDSHAKE_TIMEOUT_MS);+ ws.once('message', onMessage);+ });+}+function refuseUpgrade(socket: Duplex, reason: string): void {socket.write(`HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\nX-Browsentic-Reason: ${reason}\r\n\r\n`);socket.destroy();diff --git a/mcp/src/ensure-daemon.ts b/mcp/src/ensure-daemon.tsindex c8f2220..e068290 100644--- a/mcp/src/ensure-daemon.ts+++ b/mcp/src/ensure-daemon.ts@@ -37,22 +37,30 @@ export async function ensureDaemon(): Promise<Lockfile> {export async function probeExisting(): Promise<Lockfile | null> {const lock = readLockfile();- if (lock && isRunning(lock.pid) && (await isHealthy(lock.port))) return lock;+ if (lock && isRunning(lock.pid) && (await healthyPid(lock.port)) === lock.pid) return lock;+ // The control token is minted per daemon, so a daemon found on another port is only reachable+ // through the lockfile it wrote itself — which its pid identifies.for (const port of DAEMON_PORTS) {- if (port !== lock?.port && (await isHealthy(port)) && lock) return { ...lock, port };+ if (port === lock?.port) continue;+ const pid = await healthyPid(port);+ if (pid === null) continue;+ const current = readLockfile();+ if (current?.pid === pid) return current;}return null;}-async function isHealthy(port: number): Promise<boolean> {+async function healthyPid(port: number): Promise<number | null> {try {const response = await fetch(`http://127.0.0.1:${port}/health`, {signal: AbortSignal.timeout(1_000),});- return response.ok;+ if (!response.ok) return null;+ const health = (await response.json()) as { pid?: unknown };+ return typeof health.pid === 'number' ? health.pid : null;} catch {- return false;+ return null;}}diff --git a/mcp/src/remote-bridge.ts b/mcp/src/remote-bridge.tsindex 8dbe292..24d3e95 100644--- a/mcp/src/remote-bridge.ts+++ b/mcp/src/remote-bridge.ts@@ -4,6 +4,7 @@ import { awaitMonitor } from '@/lib/actions/page/await-monitor';import { startMonitor } from '@/lib/actions/page/start-monitor';import { failure, type ActionResult } from '@/lib/actions/protocol';import type { ToolDescriptor } from '@/lib/actions/manifest';+import type { AgentKind, AgentState } from '@/lib/agents/catalog';import { AWAIT_DEFAULT_TIMEOUT_MS } from '@/lib/monitor/events';import type { Bridge, BridgeStatus, ControlMessage, ControlRequest, SessionSummary } from './control';@@ -61,6 +62,12 @@ export class RemoteBridge implements Bridge {return reply && 'sessions' in reply ? reply.sessions : [];}+ async agent(change?: { set?: AgentKind; grant?: AgentKind }): Promise<AgentState> {+ const reply = await this.request({ id: randomUUID(), op: 'agent', ...change });+ if (reply && 'state' in reply) return reply.state;+ throw new Error('The Browsentic daemon did not answer about its agent');+ }+async revoke(origin?: string): Promise<number> {const reply = await this.request({ id: randomUUID(), op: 'revoke', origin });return reply && 'revoked' in reply ? reply.revoked : 0;diff --git a/mcp/src/server.ts b/mcp/src/server.tsindex 8d341ab..4347543 100644--- a/mcp/src/server.ts+++ b/mcp/src/server.ts@@ -8,7 +8,9 @@ import {import type { ActionResult } from '@/lib/actions/protocol';import { RESERVED_ACTIONS, RESERVED_PREFIX, SAVE_SITE_MAP_ACTION } from '@/lib/actions/reserved';import { actionNameFor, assertToolNamesRoundTrip, toolNameFor } from '@/lib/actions/tool-names';+import { readAgentConfig } from './agent/config';import type { Bridge } from './control';+import { IMAGE_NOTE, fence, fenceTag, policyFrom, shouldFence } from './guardrails';import { log } from './log';const STATUS_TOOL = toolNameFor(`${RESERVED_PREFIX}status`);@@ -106,6 +108,12 @@ const SAVE_SITE_MAP_TOOL = {};export function createMcpServer(bridge: Bridge, version: string, opts: { agentRun?: boolean } = {}): Server {+ // Page text is marked as data on the way out, for every client — the system prompt+ // that says so only reaches Browsentic's own runs. The tag is per-process so a page+ // cannot author a closing marker.+ const policy = policyFrom(readAgentConfig().guardrails);+ const tag = fenceTag();+const server = new Server({ name: 'browsentic', version },{@@ -114,8 +122,9 @@ export function createMcpServer(bridge: Bridge, version: string, opts: { agentRu'Controls the user’s browser through the Browsentic extension. Tools act on the active tab. ' +'Start with page_getPageInfo (or the browsentic://page/diagram resource) to learn what is on the page and ' +'get stable selectors, then target elements by selector or visible text. ' +- 'page_screenshot saves every capture to disk unless you pass save: false, and reports the file as savedTo. ' +- 'Always show the user the screenshot itself — read savedTo back so the image renders — and include that path in your reply.',+ 'page_screenshot hands the image back to you in the result and writes nothing to disk, so captures you take to see ' ++ 'the page for yourself leave no files behind. Pass save: true only when the user asked for a picture they can keep; ' ++ 'then read the returned savedTo path back so the image renders, and include that path in your reply.',},);@@ -142,8 +151,10 @@ export function createMcpServer(bridge: Bridge, version: string, opts: { agentRuserver.setRequestHandler(CallToolRequestSchema, async ({ params }) => {if (params.name === STATUS_TOOL) return render(await status(bridge));- const result = await bridge.invoke(actionNameFor(params.name), params.arguments ?? {});- return params.name === SCREENSHOT_TOOL ? renderScreenshot(result) : render(result);+ const action = actionNameFor(params.name);+ const result = await bridge.invoke(action, params.arguments ?? {});+ if (params.name === SCREENSHOT_TOOL) return renderScreenshot(result);+ return render(result, shouldFence(action, policy) ? tag : undefined);});server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources: [...RESOURCES] }));@@ -153,15 +164,19 @@ export function createMcpServer(bridge: Bridge, version: string, opts: { agentRuconst resource = RESOURCES.find((candidate) => candidate.uri === uri);if (!resource) throw new Error(`Unknown resource: ${uri}`);+ // Resources are read straight into the client's context, so they are fenced the+ // same way tool results are.+ const wrap = (body: string) => (policy.fence.enabled ? fence(body, tag) : body);+if (uri === 'browsentic://page/text') {const result = await bridge.invoke('page.extractText', { format: 'text' });- return text(uri, resource.mimeType, unwrap(result, (data) => String((data as { content: string }).content)));+ return text(uri, resource.mimeType, wrap(unwrap(result, (data) => String((data as { content: string }).content))));}const result = await bridge.invoke('page.getPageInfo', { maxPerKind: uri === 'browsentic://page/diagram' ? 1 : 30 });if (uri === 'browsentic://page/diagram') {- return text(uri, resource.mimeType, unwrap(result, (data) => String((data as PageInfo).layout.diagram)));+ return text(uri, resource.mimeType, wrap(unwrap(result, (data) => String((data as PageInfo).layout.diagram))));}- return text(uri, resource.mimeType, unwrap(result, (data) => JSON.stringify(data, null, 2)));+ return text(uri, resource.mimeType, wrap(unwrap(result, (data) => JSON.stringify(data, null, 2))));});bridge.onManifestChanged(() => {@@ -187,16 +202,20 @@ async function status(bridge: Bridge) {}const monitors = await activeMonitors(bridge);const page = await bridge.invoke('page.getPageInfo', { maxPerKind: 1 });- if (page.ok) {- return { ok: true as const, data: { ...base, activeTab: (page.data as PageInfo).document, ...monitors } };- }+ const hints = [+ base.manifestInSync+ ? ''+ : 'The extension is running an older build than the daemon, so your tool list came from the extension and is stale — capabilities that exist in this repository may be missing entirely. You cannot fix this yourself: tell the user to run `yarn build && yarn mcp:build` and then press Reload on Browsentic at chrome://extensions. Do not improvise around a tool you think should exist.',+ page.ok ? '' : `Cannot read the active tab (${page.error.code}). Use page_navigate to open an http(s) page first.`,+ ].filter(Boolean);+return {ok: true as const,data: {...base,- activeTab: null,+ activeTab: page.ok ? (page.data as PageInfo).document : null,...monitors,- hint: `Cannot read the active tab (${page.error.code}). Use page_navigate to open an http(s) page first.`,+ ...(hints.length ? { hint: hints.join(' ') } : {}),},};}@@ -232,6 +251,7 @@ function renderScreenshot(result: ActionResult) {const [mimeType, base64] = splitDataUrl(data.dataUrl);const notes = [+ IMAGE_NOTE,`Captured ${data.width}×${data.height} ${data.format ?? 'image'}.`,data.truncated ? 'The page was taller than the capture limit, so the bottom is cut off.' : '',data.savedTo@@ -255,9 +275,14 @@ function splitDataUrl(dataUrl: string): [mimeType: string, base64: string] {return match ? [match[1], match[2]] : ['image/png', ''];}-function render(result: ActionResult) {+/**+ * `fenceWith` marks the payload as untrusted page data. Failures are left bare: they+ * are daemon-authored and the run preamble teaches the agent to read `CODE: message`.+ */+function render(result: ActionResult, fenceWith?: string) {if (result.ok) {- return { content: [{ type: 'text' as const, text: JSON.stringify(result.data, null, 2) }] };+ const body = JSON.stringify(result.data, null, 2);+ return { content: [{ type: 'text' as const, text: fenceWith ? fence(body, fenceWith) : body }] };}return {isError: true,