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(agent): Claude Code, OpenCode and Mistral Vibe runs list the core tools and reach the grouped ones through browsentic_use, whose guide says how, so the less common schemas stop riding along on every turn
Shahriar19527320e093
diff --git a/docs/guide/features/page-actions.md b/docs/guide/features/page-actions.mdindex b7d05fc..d0999a3 100644--- a/docs/guide/features/page-actions.md+++ b/docs/guide/features/page-actions.md@@ -4,6 +4,11 @@ The 52 page tools the agent uses to read, click, type, move between tabs and scrnot name them in an instruction, since the agent picks the tool, but knowing what exists tells youwhat is worth asking for.+On Claude Code, OpenCode and Mistral Vibe, the less common ones (captchas, theming, diagnostics,+monitors and timers, downloads, dragging) stay out of the agent's tool list until a page calls for+them, because those agents send the model every tool's description on every turn. The agent opens their+guide when it needs one, and they then work exactly as the others do.+Every parameter is in [reference/tools.md](../../reference/tools.md).---diff --git a/docs/guide/features/skills.md b/docs/guide/features/skills.mdindex 06249fb..0296ca6 100644--- a/docs/guide/features/skills.md+++ b/docs/guide/features/skills.md@@ -35,6 +35,11 @@ One bundled skill is never the base: `page-scripting` rides along with whicheverpicked, and only when the composer's **Live tool** switch is on (see[Page actions](page-actions.md#repeating-a-job-and-doing-what-no-tool-covers)).+Five of these also open mid-run, when the page calls for what they teach: `captcha`,+`page-theming`, `page-diagnostics`, `monitor-progress` and `scheduled-jobs`. The agent opens one as+a guide with `browsentic_openSkill`, which hands it the skill and the tools that go with it, and+your own copy of the skill is the one it gets.+Typing `/` at the start of the composer opens a picker over every kind of skill described below,with skills for the current site first, so you do not have to remember names. Picking a Browsentic skill inserts its `@name`for you.diff --git a/docs/internals/agent-runs.md b/docs/internals/agent-runs.mdindex a8b81fe..0094471 100644--- a/docs/internals/agent-runs.md+++ b/docs/internals/agent-runs.md@@ -118,6 +118,20 @@ Codex also cuts any tool result at 10,000 tokens by default, a limit its model c`// @exec: {"max_output_tokens": 25000}`; only the prompt can ask for that, so it does. It alsoasks for page reads in pieces.+**Three CLIs send every tool they are given on every turn, so their runs list only the core.**+Claude Code (whose own `ToolSearch` is denied), Mistral Vibe and OpenCode declare+`Runner.delivery: 'on-demand'`. For their runs `offerFor` names every+[grouped action](registry.md) in `onDemand`, which the describe reply carries beside `withheld`, and+the tool host leaves those off the list and adds `browsentic_use`. The agent finds them through+`browsentic_openSkill`, whose description and the server's instructions carry one line per group,+and the guide it opens says to call them through `browsentic_use`. That call reaches+`invokeForRun()` with the action itself, so its approval, guardrails, phone gate, step in the panel+and rendered result are the ones the tool's own call would get. The set depends only on the runner,+the browser's actions and the phone, never on the message, so a conversation's list stays the same+from one turn to the next. Vibe and OpenCode are not granted the grouped tools by name, since they+never see them. Every other CLI is `listed`: it already keeps schemas out of the model's context+until they are looked up, and a second level of lookup would only lose the schema-checked call.+**A CLI with limits on a tool call declares them** (`Runner.limits`), and the daemon works insidethem so the run does not have to discover them. Cursor abandons a call at 60 s (the MCP SDK'sdefault request timeout, which it never overrides) and puts text over 40,000 bytes in a file the run@@ -169,7 +183,7 @@ Code 2.1.283) with a stand-in model endpoint| | Claude Code | Codex (app-server, the default) | Codex (`exec`) || --- | --- | --- | --- |-| Browser tools in the model's list | all of them | all of them, from the first request; a code-mode model gets each declared inside `exec` | deferred behind `tool_search`; a code-mode model reaches them only inside `exec`, and the prompt says so |+| Browser tools in the model's list | the core, with the rest through `browsentic_openSkill` and `browsentic_use` | all of them, from the first request; a code-mode model gets each declared inside `exec` | deferred behind `tool_search`; a code-mode model reaches them only inside `exec`, and the prompt says so || The user's own MCP servers | kept out by `--strict-mcp-config` | switched off one by one in the thread's config, from the list `config/read` gives; one that starts anyway stops the run | kept out by `--ignore-user-config`: a `-c` merges into `config.toml`, so `mcp_servers={}` cleared nothing, and keys on the user's own `browsentic` entry (an `enabled_tools` list) landed on the run's || The user's defaults | `settings.json` applies | the whole of `config.toml` except its MCP servers: model, provider, profile | the `model` and `model_reasoning_effort` at the top of `config.toml`, carried over by hand; nothing else in the file || Shell and disk | denied by name | `features.shell_tool=false` and `features.view_image=false` on its argv; `apply_patch` as on `exec` | `features.shell_tool=false` and `features.view_image=false`, which remove the tools from every model and every sub-agent; `apply_patch` has no switch and the read-only sandbox refuses its writes |diff --git a/docs/internals/registry.md b/docs/internals/registry.mdindex 9b1aba7..9c8087d 100644--- a/docs/internals/registry.md+++ b/docs/internals/registry.md@@ -27,7 +27,9 @@ export const clickElement = defineAction({An action that only some tasks need also names its `group`: `captcha`, `theming`, `diagnostics`,`monitoring`, `downloads` or `drag`. [`src/lib/actions/groups.ts`](../../src/lib/actions/groups.ts)gives each group its line in the index and the skills that teach it, and `browsentic_openSkill`-opens a group as one guide. Ungrouped actions are the core. The group never leaves the daemon's+opens a group as one guide. Ungrouped actions are the core. A side-panel run on a CLI that sends+every schema on every turn lists only the core and calls the grouped ones through `browsentic_use`+([Agent runs](agent-runs.md#runners)). The group never leaves the daemon'sown copy of the registry, so it changes neither the descriptors nor the manifest hash.`describeActions()` turns that array into tool descriptors by converting each zod schema to JSON@@ -83,7 +85,8 @@ spawned inside an agent run.`browsentic_status` is not in the registry either: the MCP server answers it directly by combiningdaemon state with a one-element `page.getPageInfo` and the current monitor list. Nor is`browsentic_openSkill`, which the MCP server answers from the groups, the skills in effect (a-user's own copy of a skill wins) and the tools this caller is offered.+user's own copy of a skill wins) and the tools this caller is offered, nor `browsentic_use`, which+it unwraps to the page action named and invokes as that action's own tool would.---diff --git a/docs/reference/errors.md b/docs/reference/errors.mdindex e14465e..d315206 100644--- a/docs/reference/errors.md+++ b/docs/reference/errors.md@@ -36,7 +36,9 @@ run, and the message carries the *fix*. In the **Origin** column, Daemon is Brow| `ACTION_FAILED` | Action | `execute()` threw, e.g. `back` with no history || `PICK_CANCELLED` | Content script | The user dismissed A-Eye without pointing at anything, or a newer pick took over the lens. **Terminal**: ask in words rather than asking them to point again || `NO_FOCUS_SHOT` | Daemon | `browsentic_focusShot` was called on a run whose instruction carried no A-Eye pick, so there is no picture to show |-| `UNKNOWN_ACTION` | Registry / daemon | Tool-registry skew, or a reserved action reached from outside |+| `UNKNOWN_ACTION` | Registry / daemon | Tool-registry skew, a reserved action reached from outside, or a `browsentic_use` call naming no page tool, answered with the list of guides |+| `UNKNOWN_SKILL` | Daemon | `browsentic_openSkill` was given a name no guide answers to. The message lists the guides |+| `UNAVAILABLE` | Daemon | None of a guide's tools are offered to this caller: captcha and diagnostics outside a Chromium browser on a computer, or a guide the phone cannot run |## Diagnosticsdiff --git a/docs/reference/tools.md b/docs/reference/tools.mdindex d738fc4..cd65404 100644--- a/docs/reference/tools.md+++ b/docs/reference/tools.md@@ -15,14 +15,15 @@ human-readable copy; `yarn daemon:manifest` prints the machine listing (see**Names.** An action is namespaced with dots, a tool with underscores: action `page.fillInput` ispublished as tool `page_fillInput`. The mapping is mechanical, so this page names each tool onceand the action is implied. Actions under the reserved `browsentic.` prefix are daemon verbs, not-registry actions. Of those, `browsentic_status` and `browsentic_openSkill` are always tools, and+registry actions. Of those, `browsentic_status` and `browsentic_openSkill` are always tools,+`browsentic_use` is one in the side-panel runs that reach the less common tools on demand, and`browsentic_saveSiteMap` becomes one in mapping runs only.Tools by group:| Group | Tools || --- | --- |-| [Status and guides](#status-and-guides) | `browsentic_status`, `browsentic_openSkill` |+| [Status and guides](#status-and-guides) | `browsentic_status`, `browsentic_openSkill`, `browsentic_use` || [Reading](#reading) | `page_getPageInfo`, `page_extractText`, `page_waitForElement`, `page_findProgress`, `page_findSearch`, `page_pickElement`, `page_screenshot` || [Acting](#acting) | `page_clickElement`, `page_trustedClick`, `page_findCaptcha`, `page_solveCaptcha`, `page_hoverElement`, `page_dragElement`, `page_focusInput`, `page_fillInput`, `page_typeText`, `page_selectOption`, `page_selectText`, `page_pressKey`, `page_submitForm`, `page_highlightElement` || [Scripting](#scripting) | `page_injectCode`, `page_runCode` |@@ -82,6 +83,20 @@ only the tools this caller is offered and names the rest; one with nothing to of| --- | --- | --- | --- || `name` | string | required | The guide to open. The name of its skill (`page-theming`) or of one of its tools (`page_applyTheme`) opens it too |+### browsentic_use++Run a page tool that is not in this caller's tool list, by name. A side-panel run on Claude Code,+OpenCode or Mistral Vibe lists only the core tools, because those CLIs send the description of every+tool they are given on every turn. The tools of the guides above are left off its list, and the+agent calls them through `browsentic_use` once a guide, a skill or a result has named one. The call+goes the way the tool's own call would: the same approvals, guardrails, blocked sites and steps in+the panel, and the same result. Every other caller lists every tool and is not offered this one.++| Parameter | Type | Default | Purpose |+| --- | --- | --- | --- |+| `action` | string | required | The tool to run: `page_dragElement`, `page.dragElement` and `dragElement` all name it. Anything that is not a page tool is answered with `UNKNOWN_ACTION` and the list of guides |+| `input` | object | `{}` | Its parameters, as its own schema has them. A JSON string of the object is taken too. Input the tool refuses comes back as `INVALID_INPUT` with its schema |+---## Readingdiff --git a/src/daemon/agent/runners/claude.ts b/src/daemon/agent/runners/claude.tsindex b2b9702..bca9294 100644--- a/src/daemon/agent/runners/claude.ts+++ b/src/daemon/agent/runners/claude.ts@@ -94,6 +94,8 @@ export const claudeRunner: Runner = {// 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,+ // ToolSearch is denied, so every listed schema rides along on every turn.+ delivery: 'on-demand',workspace: () => stateDir,diff --git a/src/daemon/agent/runners/opencode.ts b/src/daemon/agent/runners/opencode.tsindex bd54845..6eb1de0 100644--- a/src/daemon/agent/runners/opencode.ts+++ b/src/daemon/agent/runners/opencode.ts@@ -74,6 +74,7 @@ export const opencodeRunner: Runner = {// Passed as --variant, whose names each model defines; a model ignores one it lacks.efforts: ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'],endsOnExit: true,+ delivery: 'on-demand',workspace: (mode: RunMode) => join(stateDir, 'agents', 'opencode', mode),diff --git a/src/daemon/agent/runners/types.ts b/src/daemon/agent/runners/types.tsindex 859a43f..ed94daf 100644--- a/src/daemon/agent/runners/types.ts+++ b/src/daemon/agent/runners/types.ts@@ -33,6 +33,13 @@ export interface Plan {prepare?: string[][];}+/**+ * `listed`: every tool in the run's list, for a CLI that keeps schemas out of the model's context+ * until it looks one up. `on-demand`: the grouped tools are left off the list and called through+ * browsentic_use, for a CLI that sends every schema it is given on every turn.+ */+export type ToolDelivery = 'listed' | 'on-demand';+/** What a CLI does to every tool call, which the daemon has to work inside of. */export interface CallLimits {/** The CLI abandons a call that takes longer than this, whatever it is waiting on. */@@ -144,6 +151,8 @@ export interface Runner {keepsFirstPrompt?: boolean;/** Limits this CLI puts on a browser tool call; unset where it waits and takes whatever comes. */limits?: CallLimits;+ /** How a run's less common browser tools reach the model; `listed` when unsaid. */+ delivery?: ToolDelivery;json(context: JsonContext): Plan;/** What a one-shot of this CLI is known to open when handed a file. Text alone when unsaid. */opens?: readonly FileKind[];diff --git a/src/daemon/agent/runners/vibe.ts b/src/daemon/agent/runners/vibe.tsindex e1fa774..c01a20c 100644--- a/src/daemon/agent/runners/vibe.ts+++ b/src/daemon/agent/runners/vibe.ts@@ -38,6 +38,7 @@ export const vibeRunner: Runner = {versionArgs: ['--version'],efforts: [],endsOnExit: true,+ delivery: 'on-demand',workspace: (mode: RunMode) => join(stateDir, 'agents', 'vibe', mode),diff --git a/src/daemon/agent/service.test.ts b/src/daemon/agent/service.test.tsindex fe1cd4b..0122b02 100644--- a/src/daemon/agent/service.test.ts+++ b/src/daemon/agent/service.test.ts@@ -5,23 +5,31 @@ import { FOCUS_SHOT_ACTION } from '@/lib/actions/reserved';import type { RunEvent } from '@/lib/actions/protocol';import { failure, success } from '@/lib/actions/protocol';import { profilePath } from '../profile';+import { grouped } from '../tool-groups';import { configPath } from './config';import { stubCli } from './runners/fixtures/support';import { AgentSession } from './service';import { hashManifest } from '@/lib/actions/manifest';import { describeActions } from '@/lib/actions/registry';-import { PHONE_TOOLS } from '@/lib/phone/features';+import { PHONE_TOOLS, phoneOffers } from '@/lib/phone/features';import type { PhoneContext } from '@/lib/phone/types';+import { AGENT_KINDS, type AgentKind } from '@/lib/agents/catalog';const CODE_TOOLS = ['page.injectCode', 'page.runCode'];+/** Only the named agent can be found, so the readiness probe starts none of the CLIs installed on this machine. */+const onlyAgent = (agent: AgentKind, bin: string) => ({+ agent,+ agents: Object.fromEntries(AGENT_KINDS.map((kind) => [kind, { bin: kind === agent ? bin : `/nonexistent/${kind}` }])),+});+let session: AgentSession;let ended: string[];beforeEach(() => {// No agent to find, so every run is refused once it has been admitted — after its offer can be read.mkdirSync(dirname(configPath), { recursive: true });- writeFileSync(configPath, JSON.stringify({ claudeBin: '/nonexistent/claude' }));+ writeFileSync(configPath, JSON.stringify(onlyAgent('claude', '/nonexistent/claude')));ended = [];session = new AgentSession({invoke: async () => failure('EXTENSION_OFFLINE', 'no browser'),@@ -64,7 +72,7 @@ describe('what a phone run is offered', () => {});test('a desktop run beside it is offered what it always was', async () => {- expect(await offerTo('d', { sessionId: 's2' })).toEqual({ withheld: CODE_TOOLS, reserved: [FOCUS_SHOT_ACTION] });+ expect(await offerTo('d', { sessionId: 's2' })).toEqual({ withheld: CODE_TOOLS, reserved: [FOCUS_SHOT_ACTION], onDemand: names.filter(grouped) });});test('a phone run leaves the tool list the browser describes, and so its hash, as it was', async () => {@@ -95,8 +103,8 @@ describe("what a run's tool list holds", () => {test('the page-code tools only with Live tool on, and the pick’s screenshot either way', async () => {expect([await offerTo('a', { sessionId: 's1' }), await offerTo('b', { sessionId: 's2', liveTools: true })]).toEqual([- { withheld: CODE_TOOLS, reserved: [FOCUS_SHOT_ACTION] },- { withheld: [], reserved: [FOCUS_SHOT_ACTION] },+ { withheld: CODE_TOOLS, reserved: [FOCUS_SHOT_ACTION], onDemand: [] },+ { withheld: [], reserved: [FOCUS_SHOT_ACTION], onDemand: [] },]);});@@ -109,10 +117,74 @@ describe("what a run's tool list holds", () => {});});+describe('the tools a run reaches on demand', () => {+ const names = describeActions('chromium').map(({ name }) => name);++ beforeEach(() => {+ session = new AgentSession({+ invoke: async () => failure('EXTENSION_OFFLINE', 'no browser'),+ emit: (runId: string, event: RunEvent) => void (event.kind === 'error' && ended.push(runId)),+ draft: () => {},+ actionNames: () => names,+ });+ });++ test('are the grouped ones, on a CLI that sends every schema it is given on every turn, and the same for every message', async () => {+ const first = await offerTo('a', { sessionId: 's1' });+ const next = await offerTo('b', { sessionId: 's1', liveTools: true });+ expect([first?.onDemand, next?.onDemand]).toEqual([names.filter(grouped), names.filter(grouped)]);+ });++ test('are none on a CLI that looks a schema up only when it needs one', async () => {+ writeFileSync(configPath, JSON.stringify(onlyAgent('codex', '/nonexistent/codex')));+ expect((await offerTo('c', { sessionId: 's1' }))?.onDemand).toEqual([]);+ });++ test('on the phone, are only the grouped ones the phone runs', async () => {+ const offer = await offerTo('p', { sessionId: 's1', phone: PHONE });+ expect([offer?.onDemand, offer?.onDemand.filter((name) => offer.withheld.includes(name))]).toEqual([+ names.filter((name) => grouped(name) && phoneOffers(name)),+ [],+ ]);+ });++ test('are not granted by name to a CLI that is told every tool it may call, and the tool that runs them is', async () => {+ const dir = `${dirname(configPath)}/vibe-grants`;+ rmSync(dir, { recursive: true, force: true });+ mkdirSync(dir, { recursive: true });+ const vibe = stubCli(+ join(dir, 'vibe'),+ `const fs = require('node:fs');+if (process.argv[2] === '--version') {+ console.log('2.25.5');+ process.exit(0);+}+fs.copyFileSync('.vibe/config.toml', ${JSON.stringify(`${dir}/config.toml`)});`,+ );+ writeFileSync(configPath, JSON.stringify(onlyAgent('vibe', vibe)));+ const done: string[] = [];+ const granting = new AgentSession({+ invoke: async () => failure('EXTENSION_OFFLINE', 'no browser'),+ emit: (runId: string, event: RunEvent) => void ((event.kind === 'done' || event.kind === 'error') && done.push(runId)),+ draft: () => {},+ actionNames: () => names,+ });+ granting.handle({ t: 'instruct', id: 'v', text: 'click Sign in', context: { sessionId: 's1' } });+ await vi.waitFor(() => expect(done).toContain('v'), { timeout: 5_000 });+ granting.dispose();++ const granted = [...readFileSync(`${dir}/config.toml`, 'utf8').matchAll(/^\[tools\."browsentic_(.+)"\]$/gm)].map((match) => match[1]);+ expect({+ grouped: granted.filter((tool) => grouped(tool.replace('_', '.'))),+ own: ['page_clickElement', 'browsentic_openSkill', 'browsentic_use'].filter((tool) => granted.includes(tool)),+ }).toEqual({ grouped: [], own: ['page_clickElement', 'browsentic_openSkill', 'browsentic_use'] });+ });+});+describe('answering a captcha', () => {test('asks once, then lets the rest of that run’s rounds through without asking again', async () => {const agent = stubCli(join(dirname(configPath), 'agent-that-waits'), 'setTimeout(() => {}, 30_000);');- writeFileSync(configPath, JSON.stringify({ claudeBin: agent }));+ writeFileSync(configPath, JSON.stringify(onlyAgent('claude', agent)));const events: RunEvent[] = [];const invoked: string[] = [];const waiting = new AgentSession({@@ -146,7 +218,7 @@ describe('answering a captcha', () => {describe('an approval, on an agent that abandons a call before the user answers', () => {const tracked = async (agent: 'cursor' | 'claude') => {const bin = stubCli(join(dirname(configPath), `${agent}-that-waits`), 'setTimeout(() => {}, 30_000);');- writeFileSync(configPath, JSON.stringify(agent === 'cursor' ? { agent, agents: { cursor: { bin } } } : { claudeBin: bin }));+ writeFileSync(configPath, JSON.stringify(onlyAgent(agent, bin)));const events: RunEvent[] = [];const invoked: [string, unknown][] = [];const running = new AgentSession({@@ -242,7 +314,7 @@ describe('an approval, on an agent that abandons a call before the user answers'describe('a wait inside a call, on an agent that abandons a call at 60 s', () => {const invokedWith = async (agent: 'cursor' | 'claude', action: string, input: unknown) => {const bin = stubCli(join(dirname(configPath), `${agent}-that-waits`), 'setTimeout(() => {}, 30_000);');- writeFileSync(configPath, JSON.stringify(agent === 'cursor' ? { agent, agents: { cursor: { bin } } } : { claudeBin: bin }));+ writeFileSync(configPath, JSON.stringify(onlyAgent(agent, bin)));let seen: unknown;const running = new AgentSession({invoke: async (_action, given) => {@@ -299,7 +371,7 @@ process.stdin.on('data', (chunk) => (heard += chunk)).on('end', () => {console.log(JSON.stringify({ type: 'result', subtype: 'success', is_error: false, stop_reason: 'end_turn', result: 'ok' }));});`,);- writeFileSync(configPath, JSON.stringify({ claudeBin: agent }));+ writeFileSync(configPath, JSON.stringify(onlyAgent('claude', agent)));const done: string[] = [];const turns = new AgentSession({invoke: async () => failure('EXTENSION_OFFLINE', 'no browser'),@@ -349,7 +421,7 @@ process.stdin.on('data', (chunk) => (heard += chunk)).on('end', () => {console.log(JSON.stringify({ type: 'result', subtype: 'success', is_error: false, stop_reason: 'end_turn', result: 'ok' }));});`,);- writeFileSync(configPath, JSON.stringify({ claudeBin: agent }));+ writeFileSync(configPath, JSON.stringify(onlyAgent('claude', agent)));const saveProfile = (email: string) =>writeFileSync(profilePath, JSON.stringify({ fields: { email }, details: [], instructions: 'Always choose the cheapest shipping.' }));const done: string[] = [];@@ -410,7 +482,7 @@ process.stdin.on('data', (chunk) => (heard += chunk)).on('end', () => {console.log(JSON.stringify({ type: 'result', subtype: 'success', is_error: false, stop_reason: 'end_turn', result: 'ok' }));});`,);- writeFileSync(configPath, JSON.stringify({ claudeBin: agent }));+ writeFileSync(configPath, JSON.stringify(onlyAgent('claude', agent)));const done: string[] = [];const turns = new AgentSession({invoke: async () => failure('EXTENSION_OFFLINE', 'no browser'),diff --git a/src/daemon/agent/service.ts b/src/daemon/agent/service.tsindex c74fd68..591b7c7 100644--- a/src/daemon/agent/service.ts+++ b/src/daemon/agent/service.ts@@ -44,6 +44,7 @@ import {} from '../guardrails';import { log } from '../log';import { readProfile } from '../profile';+import { grouped } from '../tool-groups';import { resolveAgentSkill } from './agent-skills';import { isGranted, rememberGrant } from './approvals';import { maxConcurrentRuns, readAgentConfig, siteMapSettings, type AgentConfig } from './config';@@ -199,23 +200,31 @@ export class AgentSession {* What a run's tool list should hold. A tool the run would only be refused is left* out: its schema is re-sent on every turn, and listing it invites the call.*/- offerFor(runId: string): { withheld: string[]; reserved: string[] } | null {+ offerFor(runId: string): { withheld: string[]; reserved: string[]; onDemand: string[] } | null {const run = this.runs.get(runId);if (!run) return null;const codeListed = run.liveTools || (run.sessionId !== undefined && this.codeListed.has(run.sessionId));const codeWithheld = codeListed ? [] : [INJECT_ACTION, RUN_CODE_ACTION];+ const offered = (withheld: string[]) => this.onDemand(run).filter((name) => !withheld.includes(name));if (run.phone) {const offPhone = this.deps.actionNames().filter((name) => !phoneOffers(name));- return { withheld: [...new Set([...offPhone, ...codeWithheld])], reserved: [FOCUS_SHOT_ACTION] };+ const withheld = [...new Set([...offPhone, ...codeWithheld])];+ return { withheld, reserved: [FOCUS_SHOT_ACTION], onDemand: offered(withheld) };}return {withheld: codeWithheld,// A mapping run never resumes a conversation, so its tool can come and go. A pick// comes and goes between the messages of one, so the tool that shows it stays.reserved: [...(run.map ? [SAVE_SITE_MAP_ACTION] : []), FOCUS_SHOT_ACTION],+ onDemand: offered(codeWithheld),};}+ /** The grouped actions a run calls through browsentic_use, when its CLI would send their schemas on every turn. */+ private onDemand(run: ActiveRun): string[] {+ return RUNNERS[run.config.agent].delivery === 'on-demand' ? this.deps.actionNames().filter(grouped) : [];+ }+/** `signal` aborts when the caller stops waiting for this call, so nothing it asked for outlives it. */async invokeForRun(runId: string, action: string, input?: unknown, signal?: AbortSignal): Promise<ActionResult> {const run = this.runs.get(runId);@@ -566,6 +575,7 @@ export class AgentSession {const allowance = run.map ? run.map.settings.timeoutMs : run.scheduled ? TASK_RUN_MAX_MS : undefined;const budget = allowance ? setTimeout(() => run.abort.abort(), allowance) : undefined;+ const onDemand = this.onDemand(run);try {const outcome = await runInstruction({@@ -576,7 +586,7 @@ export class AgentSession {research: run.map ? run.map.settings.research : false,config: run.config,sessionId: resuming,- mcpTools: agentRunToolNames(this.deps.actionNames()),+ mcpTools: agentRunToolNames(this.deps.actionNames().filter((name) => !onDemand.includes(name))),signal: run.abort.signal,emit,});diff --git a/src/daemon/control.ts b/src/daemon/control.tsindex f4d4dde..27bf437 100644--- a/src/daemon/control.ts+++ b/src/daemon/control.ts@@ -59,7 +59,7 @@ export type ControlRequest =| { id: string; op: 'android'; launch?: string; url?: string; watch?: boolean; peek?: boolean };export type ControlMessage =- | { id: string; op: 'describe'; tools: ToolDescriptor[]; reserved?: string[]; withheld?: ToolDescriptor[] }+ | { id: string; op: 'describe'; tools: ToolDescriptor[]; reserved?: string[]; withheld?: ToolDescriptor[]; onDemand?: string[] }| { id: string; op: 'status'; status: BridgeStatus }| { id: string; op: 'invoke'; result: ActionResult }| { id: string; op: 'working' }@@ -84,6 +84,11 @@ export interface Described {* them out of sight up front; a call to one while it is withheld is refused.*/withheld?: ToolDescriptor[];+ /**+ * Actions in `tools` this run calls through browsentic_use rather than from its tool list, found+ * through the guides. A caller that does not know the field lists them as it always has.+ */+ onDemand?: string[];}export interface Bridge {diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.tsindex cb758c1..da7c307 100644--- a/src/daemon/daemon.ts+++ b/src/daemon/daemon.ts@@ -787,6 +787,7 @@ export async function startDaemon({ version, idleExit = true, android = androidOtools: running[0].tools.filter(({ name }) => !withheld(name)),reserved: offer.reserved,withheld: running[0].tools.filter(({ name }) => withheld(name)),+ onDemand: offer.onDemand,};}diff --git a/src/daemon/remote-bridge.test.ts b/src/daemon/remote-bridge.test.tsindex 51c46c7..f68131f 100644--- a/src/daemon/remote-bridge.test.ts+++ b/src/daemon/remote-bridge.test.ts@@ -62,9 +62,12 @@ describe('connecting to the daemon', () => {describe('asking the daemon', () => {test('the tools it describes', async () => {- const tools = [{ name: 'page.getPageInfo', description: 'Read the page', inputSchema: {} }];- answer = ({ id }) => ({ id, op: 'describe', tools, reserved: ['browsentic.focusShot'] });- expect(await bridge.describe()).toEqual({ tools, reserved: ['browsentic.focusShot'] });+ const tools = [+ { name: 'page.getPageInfo', description: 'Read the page', inputSchema: {} },+ { name: 'page.dragElement', description: 'Drag', inputSchema: {} },+ ];+ answer = ({ id }) => ({ id, op: 'describe', tools, reserved: ['browsentic.focusShot'], onDemand: ['page.dragElement'] });+ expect(await bridge.describe()).toEqual({ tools, reserved: ['browsentic.focusShot'], onDemand: ['page.dragElement'] });});test('an action, stamped with the run it belongs to', async () => {diff --git a/src/daemon/remote-bridge.ts b/src/daemon/remote-bridge.tsindex 07305e5..4515911 100644--- a/src/daemon/remote-bridge.ts+++ b/src/daemon/remote-bridge.ts@@ -36,7 +36,7 @@ export class RemoteBridge implements Bridge {async describe(): Promise<Described> {const reply = await this.request({ id: randomUUID(), op: 'describe', runId: this.runId });- return reply && 'tools' in reply ? { tools: reply.tools, reserved: reply.reserved, withheld: reply.withheld } : { tools: [] };+ return reply && 'tools' in reply ? { tools: reply.tools, reserved: reply.reserved, withheld: reply.withheld, onDemand: reply.onDemand } : { tools: [] };}async invoke(action: string, input?: unknown, signal?: AbortSignal): Promise<ActionResult> {diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.tsindex f956368..7930c24 100644--- a/src/daemon/server.test.ts+++ b/src/daemon/server.test.ts@@ -13,6 +13,7 @@ import { configPath } from './agent/config';import type { Bridge, BridgeStatus } from './control';import { FENCE_NOTE, IMAGE_NOTE } from './guardrails';import { stateDir } from './lockfile';+import { grouped } from './tool-groups';import { createMcpServer } from './server';const KEY = 'sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWxYz012345';@@ -21,12 +22,18 @@ const PNG = 'data:image/png;base64,iVBORw0KGgo=';type Answer = (action: string, input: unknown) => ActionResult;/** A bridge that answers each action from a table, and remembers what it was asked. */-function fakeBridge(answers: Record<string, ActionResult> | Answer = {}, status: Partial<BridgeStatus> = {}, tools: ToolDescriptor[] = describeActions(), reserved?: string[]) {+function fakeBridge(+ answers: Record<string, ActionResult> | Answer = {},+ status: Partial<BridgeStatus> = {},+ tools: ToolDescriptor[] = describeActions(),+ reserved?: string[],+ onDemand?: string[],+) {const asked: [string, unknown][] = [];const listeners: (() => void)[] = [];const answer: Answer = typeof answers === 'function' ? answers : (action) => answers[action] ?? failure('UNKNOWN_ACTION', action);const bridge: Bridge = {- describe: async () => ({ tools, reserved }),+ describe: async () => ({ tools, reserved, onDemand }),invoke: async (action, input) => {asked.push([action, input]);return answer(action, input);@@ -98,6 +105,17 @@ describe('the tool list', () => {}).toEqual({ opener: true, chromium: true, kept: true });});+ test('a run that reaches the grouped tools on demand lists the rest, then the tool that runs those', async () => {+ const onDemand = describeActions().filter((action) => grouped(action.name)).map((action) => action.name);+ const { tools } = await (await connect(fakeBridge({}, {}, describeActions(), [], onDemand).bridge, { agentRun: true })).listTools();+ expect(tools.map((tool) => tool.name)).toEqual([+ ...describeActions().filter((action) => !onDemand.includes(action.name)).map((action) => toolNameFor(action.name)),+ 'browsentic_status',+ 'browsentic_openSkill',+ 'browsentic_use',+ ]);+ });+test('a reserved tool is listed only when the daemon offers it to this caller', async () => {const offered = (reserved: string[]) => fakeBridge({}, {}, describeActions(), reserved).bridge;const names = async (bridge: Bridge) => (await (await connect(bridge, { agentRun: true })).listTools()).tools.slice(-2).map((tool) => tool.name);@@ -328,6 +346,15 @@ describe('a guide', () => {);});+ test('tells a run that reaches its tools on demand to call them through browsentic_use', async () => {+ const onDemand = describeActions().filter((action) => grouped(action.name)).map((action) => action.name);+ const client = await connect(fakeBridge({}, {}, describeActions(), [], onDemand).bridge);+ const [text] = texts(await call(client, 'browsentic_openSkill', { name: 'drag' }));+ expect(text.split('\n\n')[2]).toBe(+ 'They are not in your tool list. Call each through browsentic_use, its name as action and its parameters as input: {"action": "page_dragElement", "input": {...}}.',+ );+ });+test('monitoring teaches watching and timers, in that order, and lists all eight tools', async () => {const [text] = texts(await open('monitoring'));expect({diff --git a/src/daemon/tool-groups.ts b/src/daemon/tool-groups.tsindex 844d46e..3de1a9d 100644--- a/src/daemon/tool-groups.ts+++ b/src/daemon/tool-groups.ts@@ -2,7 +2,7 @@ import { TOOL_GROUPS, type ToolGroupName } from '@/lib/actions/groups';import type { ToolDescriptor } from '@/lib/actions/manifest';import { failure, success, type ActionResult } from '@/lib/actions/protocol';import { actions } from '@/lib/actions/registry';-import { OPEN_SKILL_TOOL, toolNameFor } from '@/lib/actions/tool-names';+import { OPEN_SKILL_TOOL, toolNameFor, USE_TOOL } from '@/lib/actions/tool-names';import type { Skill } from './agent/skills';const GROUP_NAMES = Object.keys(TOOL_GROUPS) as ToolGroupName[];@@ -19,6 +19,8 @@ export const GROUPS_NOTE =`Less common capabilities each have a guide, opened with ${OPEN_SKILL_TOOL}: how to go about it, then its tools with their ` +`input schemas. Open one when the page calls for it:\n${GROUP_INDEX}`;+export const grouped = (action: string) => actions.get(action)?.group !== undefined;+/** A page action the registry knows, named as an action, as its tool, or bare: page.dragElement, page_dragElement, dragElement. */export function pageActionNamed(name: string): string | undefined {const action = `page.${name.trim().replace(/^page[._]/, '')}`;@@ -37,8 +39,16 @@ export function groupNamed(name: string): ToolGroupName | undefined {);}-/** The group's skills, then each of its tools this caller is offered, with the schema to call it by. */-export function groupGuide(group: ToolGroupName, offered: readonly ToolDescriptor[], skills: readonly Skill[]): ActionResult<string> {+/**+ * The group's skills, then each of its tools this caller is offered, with the schema to call it by,+ * and how: by name, or through browsentic_use for tools left off this caller's list.+ */+export function groupGuide(+ group: ToolGroupName,+ offered: readonly ToolDescriptor[],+ onDemand: readonly string[],+ skills: readonly Skill[],+): ActionResult<string> {const members = membersOf(group).map((action) => action.name);const tools = offered.filter((tool) => members.includes(tool.name));const missing = members.filter((name) => !tools.some((tool) => tool.name === name)).map(toolNameFor);@@ -55,7 +65,10 @@ export function groupGuide(group: ToolGroupName, offered: readonly ToolDescripto`# The ${group} guide`,...bodies,'## Its tools',- 'Call them by name, as you would any other tool.',+ tools.some((tool) => onDemand.includes(tool.name))+ ? `They are not in your tool list. Call each through ${USE_TOOL}, its name as action and its parameters as input: ` ++ `{"action": "${toolNameFor(tools[0].name)}", "input": {...}}.`+ : 'Call them by name, as you would any other tool.',...tools.map((tool) => `### ${toolNameFor(tool.name)}\n${tool.description}\nInput schema: ${JSON.stringify(tool.inputSchema)}`),...(missing.length ? [`Not offered in this run: ${missing.join(', ')}.`] : []),].join('\n\n'),diff --git a/src/daemon/tool-host.ts b/src/daemon/tool-host.tsindex 7e3e283..ca3f08a 100644--- a/src/daemon/tool-host.ts+++ b/src/daemon/tool-host.ts@@ -28,6 +28,22 @@ const OPEN_SKILL = {},};+const USE = {+ name: USE_TOOL,+ description:+ `Run a browser action that is not in your tool list. A guide from ${OPEN_SKILL_TOOL} gives each one with its input schema, ` ++ 'and a skill or a result may name one, as page.solveCaptcha or page_dragElement: call it here, with that name as action and ' ++ 'its parameters as input. It runs and answers exactly as a tool of its own would.',+ inputSchema: {+ type: 'object' as const,+ properties: {+ action: { type: 'string', description: 'The action to run, e.g. page_dragElement.' },+ input: { type: 'object', description: 'Its parameters, as its input schema lays them out. Leave it out when there are none.' },+ },+ required: ['action'],+ },+};+const FOCUS_SHOT_TOOL = {name: toolNameFor(FOCUS_SHOT_ACTION),description:@@ -159,7 +175,8 @@ export function toolHost(bridge: Bridge, { agentRun = false, resultBytes, policyconst openSkill = async ({ name }: Record<string, unknown>): Promise<ToolReply> => {const group = typeof name === 'string' ? groupNamed(name) : undefined;if (!group) return render(failure('UNKNOWN_SKILL', `There is no guide named "${String(name ?? '')}". The guides are:\n${GROUP_INDEX}`));- const guide = groupGuide(group, (await bridge.describe()).tools, loadSkills());+ const { tools, onDemand = [] } = await bridge.describe();+ const guide = groupGuide(group, tools, onDemand, loadSkills());return guide.ok ? { content: [{ type: 'text', text: guide.data }] } : render(guide);};@@ -194,11 +211,16 @@ export function toolHost(bridge: Bridge, { agentRun = false, resultBytes, policyreturn {async list() {- const { tools: actions, reserved = agentRun ? RESERVED_TOOLS.map((tool) => tool.action) : [], withheld = [] } = await bridge.describe();+ const {+ tools: actions,+ reserved = agentRun ? RESERVED_TOOLS.map((tool) => tool.action) : [],+ withheld = [],+ onDemand = [],+ } = await bridge.describe();assertToolNamesRoundTrip([...actions.map((action) => action.name), ...RESERVED_ACTIONS]);return {tools: [- ...actions.map(listed),+ ...actions.filter((action) => !onDemand.includes(action.name)).map(listed),{name: STATUS_TOOL,description:@@ -206,6 +228,7 @@ export function toolHost(bridge: Bridge, { agentRun = false, resultBytes, policyinputSchema: { type: 'object' as const, properties: {}, additionalProperties: false },},OPEN_SKILL,+ ...(onDemand.length ? [USE] : []),...RESERVED_TOOLS.filter((tool) => reserved.includes(tool.action)).map((tool) => tool.descriptor),],withheld: withheld.map(listed),