adachsoft / web-browser-tool
AI agent tool (adachsoft/ai-tool-call SPI adapter) for operating a real web browser like a human: tabs, navigation, page reading with element refs, screenshots, form actions and consent-gated irreversible actions.
Requires
- php: ^8.3
- ext-mbstring: *
- adachsoft/ai-tool-call: ^2.3
- adachsoft/web-browser-contract: ^0.1
Requires (Dev)
- adachsoft/php-code-style: ^0.8.0
- friendsofphp/php-cs-fixer: ^3.95
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^13
- rector/rector: ^2.9
- symplify/phpstan-rules: ^14.19
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
AI agent tool (an adachsoft/ai-tool-call SPI adapter) for operating a real web browser like a human: managing tabs, opening URLs, reading pages as text plus an accessibility tree with element refs, taking screenshots for vision models and filling forms. Irreversible actions (submit, publish, delete, pay, accept terms) are refused unless the call names the user's explicit consent.
The tool depends only on adachsoft/web-browser-contract. The concrete browser driver (for example adachsoft/web-browser-cdp, Chrome DevTools Protocol) is plugged in through a driver factory.
Requirements
- PHP 8.3 or higher,
ext-mbstring adachsoft/ai-tool-call^2.3 (tool media support, used for screenshots)adachsoft/web-browser-contract- a driver implementing
WebBrowserInterface, such asadachsoft/web-browser-cdp
Installation
composer require adachsoft/web-browser-tool
Usage
use AdachSoft\AiToolCall\SPI\Collection\ConfigMap;
use AdachSoft\AiToolCall\SPI\Collection\KeyValueMap;
use AdachSoft\AiToolCall\SPI\Dto\ToolCallRequestDto;
use AdachSoft\WebBrowserTool\Tool\WebBrowserToolFactory;
$factory = new WebBrowserToolFactory($driverFactory); // WebBrowserDriverFactoryInterface, see "Plugging in a driver"
$tool = $factory->create(new ConfigMap([
'upload_allowed_directories' => ['/mnt/d/builds'],
'driver' => ['endpoint' => 'http://127.0.0.1:9222'], // passed to the driver factory as is
]));
$result = $tool->callTool(new ToolCallRequestDto('web_browser', new KeyValueMap([
'operation' => 'open_tab',
'options' => ['url' => 'https://play.google.com/console'],
])));
$result->result; // KeyValueMap: {ok: true, operation: "open_tab", tab: {...}, current_tab_id: "..."}
$result->media; // ToolMediaCollection: one image for "screenshot", empty otherwise
With a framework container, register WebBrowserToolFactory as an ai-tool-call SPI factory (in AiDevTeam, a service tagged ai_tool.spi_factory) and bind WebBrowserDriverFactoryInterface to the driver adapter.
Operations
There is one tool, web_browser, with a required operation and an options object. Every operation also accepts tab_id (default: the current tab) and timeout_seconds.
| Operation | Options | Result |
|---|---|---|
list_tabs | none | tabs (tab_id, url, title, opened_by_tool, active, current), current_tab_id |
open_tab | url?, wait_until? (load, domcontentloaded, networkidle) | a new tab owned by the tool, which becomes the current tab |
activate_tab | tab_id | brings the tab to front and makes it current |
close_tab | tab_id? | closes a tab opened by the tool; the user's tabs are never closed |
open_url | url, wait_until? | navigates the current tab, or opens a new tab when none is selected; returns url, title, http_status |
wait_for | exactly one of text, text_gone, selector, url, load_state | met: true, or a timeout error |
read_page | include_text?, include_tree?, interactive_only?, root_ref?, max_chars? | text, accessibility_tree (lines like - button "Save" [ref=e12]), element_count, truncated, hint |
screenshot | full_page?, ref?, format? (png, jpeg), max_width?, quality? | mime_type, width, height, plus the image as tool media |
click | ref | action result |
type | ref, text, clear? (default true) | action result |
select | ref, values (list or string), match_by? (label, value) | action result |
set_checked | ref, checked | action result |
upload_files | ref, paths (absolute, inside upload_allowed_directories) | action result |
press_key | key (for example Enter, Escape, Control+a), ref? | action result |
scroll | ref (scroll into view) and/or direction + pixels? (default 600) | action result |
get_pending_dialog | none | dialog (type, message, default_prompt, page_url) or null |
handle_dialog | action (accept, dismiss), prompt_text? | action result plus dialog |
Every action also accepts consent_reference (see Safety model).
click, press_key, type, select and set_checked also accept dialog_response, which answers a JavaScript dialog opened by the action:
{"operation": "click", "options": {"ref": "e7", "dialog_response": {"action": "dismiss", "expected_message": "Leave site"}}}
action is accept or dismiss. prompt_text is used only when accepting a prompt dialog. With expected_message, the driver answers only when the dialog message contains that text; otherwise the dialog stays pending. Without dialog_response, the dialog stays pending and you answer it with handle_dialog. Accepting through dialog_response requires consent_reference, because the tool cannot see the dialog before the action and treats it as a confirm().
An action result contains risk (reversible or irreversible), consent_reference, url_before, url_after, navigated, new_tab_id, dialog_opened, handled_dialog (type and message of the dialog answered during the action, or null), dialog_action (accept, dismiss or null) and, when useful, a hint (for example "the page changed; call read_page to get fresh refs").
Reading pages
read_page returns the visible text and the accessibility tree. The model acts on elements by the refs from the tree. The text and the tree are each limited to max_chars (default read_page_max_chars = 20000, upper limit read_page_max_chars_limit). Truncated output ends with [... truncated] and the result has truncated: true and a hint to narrow the read with root_ref, interactive_only or include_text: false.
Screenshots
screenshot returns the image as ToolMediaDto(mimeType, base64Data, filename) in ToolCallResultDto::$media (ai-tool-call 2.3). adachsoft/ai-agent attaches it as image content after the JSON result, so vision models can see it. By default the image is downscaled to 1280 px width (screenshot_max_width) to limit tokens. Some providers (for example Moonshot) do not accept images in tool results.
Errors
Expected failures never throw. They are returned as results:
{"ok": false, "operation": "click", "error_type": "stale_element_reference", "message": "...", "hint": "The page changed since the last read_page. Call read_page again and use fresh refs."}
error_type | Cause |
|---|---|
invalid_input | unknown operation, missing or invalid option, invalid URL / ref / key / path |
no_tab_selected | no tab_id and no current tab |
tab_not_owned | navigation or action on a user's tab, or closing a user's tab |
tab_not_found | the tab no longer exists |
consent_required | irreversible action without consent_reference (not performed) |
upload_not_allowed | uploads disabled or file outside upload_allowed_directories |
browser_unavailable | the driver cannot reach the browser |
navigation_failed, timeout (with timeout_ms), element_not_found, stale_element_reference, element_not_interactable, dialog_not_found, browser_operation_failed, browser_error | driver exceptions from the contract |
Only unexpected internal errors (bugs) raise ToolExecutionException. Invalid factory configuration raises ToolConfigurationException.
Every operation runs with a finite timeout: timeout_seconds when given (up to max_timeout_seconds), otherwise default_timeout_seconds (30 s) or navigation_timeout_seconds (60 s) for open_tab / open_url.
Safety model
- Own tabs only.
open_tabopens a new tab owned by the tool. Navigation and element actions run only on tabs opened by the tool (unlessallow_actions_on_user_tabsistrue). Reading (read_page,screenshot,wait_for,get_pending_dialog) andactivate_tabwork on any tab.close_tabnever closes the user's tabs (the contract driver enforces this too). - Irreversible actions need consent. Before every action the tool classifies it with an
IrreversibleActionPolicyInterface(the contract'sIrreversibleActionGuard). An irreversible action withoutoptions.consent_referenceis not sent to the driver. The tool returnserror_type: "consent_required"with the reason, the target element and a hint telling the model to stop and get the user's approval.consent_referencemust be a non-empty string naming the user's decision (for exampletask1301_c7). It is passed to the driver asIrreversibleConsentVo, so a driver with its own policy enforces the same rule. Default policy (
DefaultIrreversibleActionPolicy, Polish + English heuristic):clickon an element whose accessible name contains a keyword. Matching uses whole words, ignores case and Polish diacritics, so "Wdroż" matches "wdróż". Default keywords include: wyślij, prześlij (covers "Prześlij do sprawdzenia"), opublikuj, usuń, zapłać, kup, akceptuję, zgadzam się, wdróż, potwierdź, zatwierdź, submit (covers "Submit for review"), send, publish, delete, remove, pay, buy, purchase, place order, accept, I agree, roll out, rollout, deploy, confirm, discard. The full list is inDefaultIrreversibleActionPolicy::DEFAULT_KEYWORDS,clickon a ref that is not in the latestread_pagesnapshot of that tab (fail-safe). After an action that navigates, the snapshot is dropped, so callread_pageagain,press_keyEnter / Space on a keyword element, without a target, or on an unknown target; Enter in a text field other than a search / filter field (it may submit the form),- accepting a
confirmorbeforeunloaddialog; accepting analert/promptwhose message contains a keyword.dialog_response.action = accepton an action is checked as accepting aconfirmdialog, so it always needs consent with the default policy, - typing, selecting, checking, uploading, scrolling and dismissing dialogs are reversible.
The keyword list is configurable (
irreversible_keywordsreplaces it,extra_irreversible_keywordsextends it), or the whole policy can be replaced by passing your ownIrreversibleActionPolicyInterfacetoWebBrowserToolFactory. Policies that also implementIrreversibleActionExplainerInterfaceprovide thereasoninconsent_requirederrors. Note: cookie banners with "Accept all" are classified as irreversible; use a "Reject" / "Only necessary" button or get consent.- Uploads are restricted.
upload_filesaccepts only absolute paths insideupload_allowed_directories. The check resolves..and symlinks. With no directories configured, uploads are disabled, so the agent cannot send arbitrary local files (keys, credentials) to a website. - No secrets in the tool. The tool never logs in. The browser profile used by the driver holds the sessions.
The snapshot used for classification lives in the tool instance (memory). A new tool instance, for example in a new process, knows no elements until its first read_page, so clicks before that require consent.
Configuration
| Key | Default | Description |
|---|---|---|
default_timeout_seconds | 30 | timeout of operations without timeout_seconds |
navigation_timeout_seconds | 60 | default timeout of open_tab / open_url |
max_timeout_seconds | 300 | maximum timeout_seconds accepted from the model |
read_page_max_chars | 20000 | default character limit of text and tree in read_page |
read_page_max_chars_limit | 100000 | maximum max_chars |
screenshot_max_width | 1280 | default screenshot width limit |
screenshot_max_width_limit | 2560 | maximum max_width |
screenshot_format | png | png or jpeg |
upload_allowed_directories | [] | absolute directories allowed for upload_files; empty disables uploads |
allow_actions_on_user_tabs | false | allow navigation and actions on tabs not opened by the tool |
irreversible_keywords | default list | replaces the keyword list of the default policy |
extra_irreversible_keywords | [] | keywords added to the list |
driver | {} | passed to WebBrowserDriverFactoryInterface::create() |
Plugging in a driver
Implement WebBrowserDriverFactoryInterface in the driver package or in the application:
use AdachSoft\WebBrowserContract\Contracts\WebBrowserInterface;
use AdachSoft\WebBrowserTool\Driver\WebBrowserDriverFactoryInterface;
final class CdpDriverFactory implements WebBrowserDriverFactoryInterface
{
public function create(array $config): WebBrowserInterface
{
// $config is the "driver" section of the tool configuration
return CdpWebBrowser::connect($config['endpoint'] ?? 'http://127.0.0.1:9222'); // driver-specific
}
}
$factory = new WebBrowserToolFactory(new CdpDriverFactory());
The tool calls create() lazily, on the first operation, and reuses the browser for later calls of the same tool instance. If the browser is not running, the operation returns browser_unavailable and tool registration is not affected. For an already created driver instance (DI, tests) use StaticWebBrowserDriverFactory.
The driver is expected to follow the contract: persistent tab ownership, refs from readPage(), finite default timeouts, translation of upload paths (for example WSL /mnt/d/... to D:\...) and, optionally, its own IrreversibleActionGuard.
Development
composer install
composer test # PHPUnit
composer stan # PHPStan
composer cs:check # PHP CS Fixer
Tests use an in-memory fake WebBrowserInterface (tests/Fake).
License
MIT