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(agents): stop a Claude Code run whose browser tools did not start, rather than let it answer without the page, and close its web search and fetch rows as their results come back
Shahriar9c426623e1e6
diff --git a/src/daemon/agent/runners/claude.test.ts b/src/daemon/agent/runners/claude.test.tsindex 43790ef..05b0a7f 100644--- a/src/daemon/agent/runners/claude.test.ts+++ b/src/daemon/agent/runners/claude.test.ts@@ -192,13 +192,32 @@ describe('reading the stream', () => {expect(read('tool-loop.hand-written.jsonl', 'tool')).toEqual([]);});- test('its own web tools are announced under the ids Claude gave them', () => {- expect(read('web-search.hand-written.jsonl', 'tool')).toEqual([+ test('its own web tools are announced under the ids Claude gave them, and closed as their results come back', () => {+ expect(read('web-search.hand-written.jsonl').filter(([signal]) => signal === 'tool' || signal === 'toolResult')).toEqual([['tool', 'toolu_ws', 'WebSearch'],['tool', 'toolu_wf', 'WebFetch'],+ ['toolResult', 'toolu_ws', true],+ ['toolResult', 'toolu_wf', false],]);});+ // Claude Code carries on without a server that failed, and its model answers without ever seeing the page.+ test('browser tools that did not start stop the run, in the words a Codex run uses', () => {+ expect(read('2.1.283-mcp-failed.jsonl').slice(0, 2)).toEqual([+ ['session', '9160ef97-27f3-45bb-aaee-3024305cbc0c'],+ [+ 'fail',+ 'AGENT_FAILED',+ 'Claude Code could not start Browsentic\'s browser tools, so this run could not reach the page. Run "browsentic restart", then send the message again.',+ ],+ ]);+ });++ test('a browser server still starting, or one that connected, is no failure', () => {+ const init = (status: string) => ({ type: 'system', subtype: 'init', session_id: 's-1', mcp_servers: [{ name: 'browsentic', status }] });+ expect([readLines(init('pending')), readLines(init('connected'))]).toEqual([[['session', 's-1']], [['session', 's-1']]]);+ });+test('nothing a subagent says, calls or spends reaches the run', () => {expect(read('subagent.hand-written.jsonl')).toEqual([['session', 'c41a9e07-2f65-4b18-93d0-6e7a2b1c8f45'],@@ -277,6 +296,12 @@ describe('what a failed start is explained as', () => {});});+// Measured against 2.1.283 (`--system-prompt-snapshot`, on by default): a resume is sent the first turn's+// --append-system-prompt, whatever a later turn passes.+test('keeps the prompt its session began with, so the daemon carries what changed in the message', () => {+ expect(claudeRunner.keepsFirstPrompt).toBe(true);+});+test("the user's own skills are listed from ~/.claude/skills", () => {expect(claudeRunner.skillDirs?.()).toEqual([join(homedir(), '.claude', 'skills')]);});diff --git a/src/daemon/agent/runners/claude.ts b/src/daemon/agent/runners/claude.tsindex 93211f6..dbc5f2d 100644--- a/src/daemon/agent/runners/claude.ts+++ b/src/daemon/agent/runners/claude.ts@@ -3,7 +3,7 @@ import { homedir } from 'node:os';import { join } from 'node:path';import { stateDir } from '../../lockfile';import { log } from '../../log';-import { effortOf, parseJsonLine } from './util';+import { browserToolsDidNotStart, effortOf, parseJsonLine } from './util';import type { JsonContext, Plan, Runner, StreamContext, StreamReader, StreamSink } from './types';export const MCP_SERVER_NAME = 'browsentic';@@ -50,8 +50,22 @@ interface UsageLine {output_tokens?: number;}+/** A server still `pending` may yet connect; anything else but `connected` never will this run. */+const STARTING = ['connected', 'pending'];+type StreamLine =- | { type: 'system'; subtype?: string; session_id?: string; tools?: string[] }+ | {+ type: 'system';+ subtype?: string;+ session_id?: string;+ tools?: string[];+ mcp_servers?: { name?: string; status?: string }[];+ }+ | {+ type: 'user';+ parent_tool_use_id?: string | null;+ message?: { content?: string | { type?: string; tool_use_id?: string; is_error?: boolean }[] };+ }| {type: 'stream_event';parent_tool_use_id?: string | null;@@ -77,6 +91,9 @@ export const claudeRunner: Runner = {versionArgs: ['--version'],efforts: ['low', 'medium', 'high', 'xhigh', 'max'],opens: ['text', 'pdf', 'image'],+ // Claude Code records the system prompt on a session's first request and resends that record on every+ // resume, whatever --append-system-prompt says (`--system-prompt-snapshot`, on by default in 2.1.283).+ keepsFirstPrompt: true,workspace: () => stateDir,@@ -122,6 +139,9 @@ export const claudeRunner: Runner = {let generated = 0;let counted = false;+ // Its own web tools are the only rows this reader opens, so only their results close one.+ const opened = new Set<string>();+const promptOf = (usage: UsageLine) =>(usage.input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);@@ -141,8 +161,24 @@ export const claudeRunner: Runner = {if (message.session_id) sink.session(message.session_id);const builtins = (message.tools ?? []).filter((tool) => !tool.startsWith('mcp__'));log(`claude session ${message.session_id} up, built-ins: ${builtins.join(', ') || 'none'}`);+ const browser = message.mcp_servers?.find((server) => server.name === MCP_SERVER_NAME);+ // Claude Code carries on without a server that failed, and the model answers without the page.+ if (browser?.status && !STARTING.includes(browser.status)) {+ log(`claude session ${message.session_id}: the ${MCP_SERVER_NAME} server is ${browser.status}`);+ return sink.fail('AGENT_FAILED', browserToolsDidNotStart('Claude Code'));+ }+ }+ return;++ case 'user': {+ if (message.parent_tool_use_id || !Array.isArray(message.message?.content)) return;+ for (const block of message.message.content) {+ if (block.type !== 'tool_result' || !block.tool_use_id || !opened.has(block.tool_use_id)) continue;+ opened.delete(block.tool_use_id);+ sink.toolResult(block.tool_use_id, block.is_error !== true);}return;+ }case 'stream_event': {if (message.parent_tool_use_id) return;@@ -152,7 +188,10 @@ export const claudeRunner: Runner = {}if (event?.type === 'content_block_start' && event.content_block?.type === 'tool_use') {const name = event.content_block.name ?? 'tool';- if (WEB_TOOLS.includes(name)) sink.tool(event.content_block.id ?? randomUUID(), name);+ if (!WEB_TOOLS.includes(name)) return;+ const id = event.content_block.id ?? randomUUID();+ opened.add(id);+ sink.tool(id, name);}if (event?.type === 'message_start') prompt = promptOf(event.message?.usage ?? {});if (event?.type === 'message_delta' && event.usage) report(event.usage, sink);diff --git a/src/daemon/agent/runners/fixtures/README.md b/src/daemon/agent/runners/fixtures/README.mdindex 6a2d71e..4e61a95 100644--- a/src/daemon/agent/runners/fixtures/README.md+++ b/src/daemon/agent/runners/fixtures/README.md@@ -10,7 +10,8 @@ What each agent CLI printed on stdout, one event per line, for the reader testscommands emptied. OpenCode's were recorded through the runner's own plan with the model providerreplaced by a local stand-in, so the model's words are scripted and its URL is 127.0.0.1 — all but`free-tier`, which the real Zen endpoint answered and which lost only its `cf-ray` and- `cf-placement` headers; paths became `/Users/you`.+ `cf-placement` headers; paths became `/Users/you`. Codex's `web-search`, `shell` and `two-calls`+ and Claude Code's `mcp-failed` were recorded the same way, each saying so in its first line.- `<case>.hand-written.jsonl` was written from the reader code, for streams a contained run cannotproduce or a CLI that was not installed. Its first line says so.diff --git a/src/daemon/agent/runners/fixtures/claude/2.1.283-mcp-failed.jsonl b/src/daemon/agent/runners/fixtures/claude/2.1.283-mcp-failed.jsonlnew file mode 100644index 0000000..79541d7--- /dev/null+++ b/src/daemon/agent/runners/fixtures/claude/2.1.283-mcp-failed.jsonl@@ -0,0 +1,11 @@+# Recorded from Claude Code 2.1.283 with a local stand-in for the API and the browsentic server's command pointing nowhere: it reports the server failed, then answers anyway.+{"type":"system","subtype":"init","cwd":"/Users/you/.browsentic","session_id":"9160ef97-27f3-45bb-aaee-3024305cbc0c","tools":[],"mcp_servers":[{"name":"browsentic","status":"failed","source":"dynamic"}],"model":"claude-sonnet-5","permissionMode":"default","slash_commands":[],"terminal_slash_commands":[],"apiKeySource":"ANTHROPIC_API_KEY","claude_code_version":"2.1.283","output_style":"default","agents":[],"skills":[],"plugins":[],"capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","msg_lifecycle_v1","mcp_read_resource_v1","mcp_tool_ui_meta_v1"],"analytics_disabled":true,"product_feedback_disabled":true,"uuid":"c170ed1f-4c68-4188-9fad-d85b84800af4","memory_paths":{},"messaging_socket_path":"/tmp/cc-socks/99817.sock","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","per_turn_effort_active":false,"view_mode":"default"}+{"type":"system","subtype":"status","status":"requesting","session_id":"9160ef97-27f3-45bb-aaee-3024305cbc0c","uuid":"e5d043ab-44f9-4fb7-9922-a7a6217547c9"}+{"type":"stream_event","event":{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-sonnet-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":5,"output_tokens":1}}},"session_id":"9160ef97-27f3-45bb-aaee-3024305cbc0c","parent_tool_use_id":null,"uuid":"21a1fbae-49e5-49ab-9441-d0897a7717b5","ttft_ms":2}+{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}},"session_id":"9160ef97-27f3-45bb-aaee-3024305cbc0c","parent_tool_use_id":null,"uuid":"03d67486-248d-45a8-8c20-27fdecb5a61e"}+{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}},"session_id":"9160ef97-27f3-45bb-aaee-3024305cbc0c","parent_tool_use_id":null,"uuid":"6bf9d1d0-1bd9-4991-9d88-ec5c93662d43"}+{"type":"assistant","message":{"id":"msg_1","type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"model":"claude-sonnet-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":5,"output_tokens":1},"context_management":null},"parent_tool_use_id":null,"session_id":"9160ef97-27f3-45bb-aaee-3024305cbc0c","uuid":"f7c72847-d4af-41c0-941f-2c90d2f162f4","timestamp":"2026-09-27T11:23:17.445Z"}+{"type":"stream_event","event":{"type":"content_block_stop","index":0},"session_id":"9160ef97-27f3-45bb-aaee-3024305cbc0c","parent_tool_use_id":null,"uuid":"94d6bd3d-0049-491c-8d05-4e928d27a68d"}+{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":1}},"session_id":"9160ef97-27f3-45bb-aaee-3024305cbc0c","parent_tool_use_id":null,"uuid":"13570f41-a32d-475a-9e47-368e21a48a17"}+{"type":"stream_event","event":{"type":"message_stop"},"session_id":"9160ef97-27f3-45bb-aaee-3024305cbc0c","parent_tool_use_id":null,"uuid":"2dc56bcc-97ef-4959-9097-17360a60e19e"}+{"duration_api_ms":18,"stop_reason":"end_turn","session_id":"9160ef97-27f3-45bb-aaee-3024305cbc0c","total_cost_usd":1.9999999999999998e-05,"usage":{"input_tokens":5,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":1,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"modelUsage":{"claude-sonnet-5":{"inputTokens":5,"outputTokens":1,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":1.9999999999999998e-05,"contextWindow":200000,"maxOutputTokens":64000,"thinkingTokens":0,"canonicalModel":"claude-sonnet-5","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"is_error":false,"num_turns":1,"subtype":"success","api_error_status":null,"result":"ok","ttft_ms":22,"type":"result","duration_ms":37,"uuid":"6e4ff518-fcb1-4dbf-94ce-0196f1b60ae7","ttft_stream_ms":21,"time_to_request_ms":19,"first_content_frame_ms":21,"queued_turn_count":0,"result_index":0}diff --git a/src/daemon/agent/runners/fixtures/claude/web-search.hand-written.jsonl b/src/daemon/agent/runners/fixtures/claude/web-search.hand-written.jsonlindex 5f7cb9d..eaf709b 100644--- a/src/daemon/agent/runners/fixtures/claude/web-search.hand-written.jsonl+++ b/src/daemon/agent/runners/fixtures/claude/web-search.hand-written.jsonl@@ -1,4 +1,4 @@-# Hand-written from claude.ts's reader, not recorded. A research run: Claude's own WebSearch and WebFetch are tools the daemon cannot see, so the reader announces them.+# Hand-written from claude.ts's reader, not recorded. A research run: Claude's own WebSearch and WebFetch are tools the daemon cannot see, so the reader announces them and closes each from its result; the browser tool's result is the daemon's to report.{"type":"system","subtype":"init","session_id":"7d3f1c20-8b4a-4e59-a6d2-0c9e1f3b5a77","tools":["WebSearch","WebFetch","mcp__browsentic__page_getPageInfo"],"model":"claude-sonnet-5"}{"type":"stream_event","parent_tool_use_id":null,"event":{"type":"message_start","message":{"usage":{"input_tokens":400,"cache_read_input_tokens":6000,"cache_creation_input_tokens":0,"output_tokens":1}}}}{"type":"stream_event","parent_tool_use_id":null,"event":{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_ws","name":"WebSearch"}}}@@ -8,6 +8,7 @@{"type":"stream_event","parent_tool_use_id":null,"event":{"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_mcp","name":"mcp__browsentic__page_getPageInfo"}}}{"type":"stream_event","parent_tool_use_id":null,"event":{"type":"content_block_stop","index":2}}{"type":"stream_event","parent_tool_use_id":null,"event":{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":90}}}+{"type":"user","parent_tool_use_id":null,"message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_ws","content":"3 results"},{"type":"tool_result","tool_use_id":"toolu_wf","is_error":true,"content":"fetch failed"},{"type":"tool_result","tool_use_id":"toolu_mcp","content":"{}"}]}}{"type":"stream_event","parent_tool_use_id":null,"event":{"type":"message_start","message":{"usage":{"input_tokens":3000,"cache_read_input_tokens":6400,"cache_creation_input_tokens":0,"output_tokens":1}}}}{"type":"stream_event","parent_tool_use_id":null,"event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Their docs list three plans."}}}{"type":"stream_event","parent_tool_use_id":null,"event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":20}}}