Search by

adachsoft / web-browser-tool

Arkadiusz Adach

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.

Package info

gitlab.com/a.adach/web-browser-tool

Issues

pkg:composer/adachsoft/web-browser-tool

Statistics

Installs: 15

Dependents: 0

Suggesters: 0

Stars: 0

v0.1.1 2026-11-28 11:56 UTC

This package is auto-updated.

Last update: 2026-11-28 10:56:58 UTC


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 as adachsoft/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.

OperationOptionsResult
list_tabsnonetabs (tab_id, url, title, opened_by_tool, active, current), current_tab_id
open_taburl?, wait_until? (load, domcontentloaded, networkidle)a new tab owned by the tool, which becomes the current tab
activate_tabtab_idbrings the tab to front and makes it current
close_tabtab_id?closes a tab opened by the tool; the user's tabs are never closed
open_urlurl, wait_until?navigates the current tab, or opens a new tab when none is selected; returns url, title, http_status
wait_forexactly one of text, text_gone, selector, url, load_statemet: true, or a timeout error
read_pageinclude_text?, include_tree?, interactive_only?, root_ref?, max_chars?text, accessibility_tree (lines like - button "Save" [ref=e12]), element_count, truncated, hint
screenshotfull_page?, ref?, format? (png, jpeg), max_width?, quality?mime_type, width, height, plus the image as tool media
clickrefaction result
typeref, text, clear? (default true)action result
selectref, values (list or string), match_by? (label, value)action result
set_checkedref, checkedaction result
upload_filesref, paths (absolute, inside upload_allowed_directories)action result
press_keykey (for example Enter, Escape, Control+a), ref?action result
scrollref (scroll into view) and/or direction + pixels? (default 600)action result
get_pending_dialognonedialog (type, message, default_prompt, page_url) or null
handle_dialogaction (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_typeCause
invalid_inputunknown operation, missing or invalid option, invalid URL / ref / key / path
no_tab_selectedno tab_id and no current tab
tab_not_ownednavigation or action on a user's tab, or closing a user's tab
tab_not_foundthe tab no longer exists
consent_requiredirreversible action without consent_reference (not performed)
upload_not_alloweduploads disabled or file outside upload_allowed_directories
browser_unavailablethe 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_errordriver 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

  1. Own tabs only. open_tab opens a new tab owned by the tool. Navigation and element actions run only on tabs opened by the tool (unless allow_actions_on_user_tabs is true). Reading (read_page, screenshot, wait_for, get_pending_dialog) and activate_tab work on any tab. close_tab never closes the user's tabs (the contract driver enforces this too).
  2. Irreversible actions need consent. Before every action the tool classifies it with an IrreversibleActionPolicyInterface (the contract's IrreversibleActionGuard). An irreversible action without options.consent_reference is not sent to the driver. The tool returns error_type: "consent_required" with the reason, the target element and a hint telling the model to stop and get the user's approval. consent_reference must be a non-empty string naming the user's decision (for example task1301_c7). It is passed to the driver as IrreversibleConsentVo, so a driver with its own policy enforces the same rule.
  3. Default policy (DefaultIrreversibleActionPolicy, Polish + English heuristic):

    • click on 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 in DefaultIrreversibleActionPolicy::DEFAULT_KEYWORDS,
    • click on a ref that is not in the latest read_page snapshot of that tab (fail-safe). After an action that navigates, the snapshot is dropped, so call read_page again,
    • press_key Enter / 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 confirm or beforeunload dialog; accepting an alert / prompt whose message contains a keyword. dialog_response.action = accept on an action is checked as accepting a confirm dialog, 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_keywords replaces it, extra_irreversible_keywords extends it), or the whole policy can be replaced by passing your own IrreversibleActionPolicyInterface to WebBrowserToolFactory. Policies that also implement IrreversibleActionExplainerInterface provide the reason in consent_required errors. Note: cookie banners with "Accept all" are classified as irreversible; use a "Reject" / "Only necessary" button or get consent.

  4. Uploads are restricted. upload_files accepts only absolute paths inside upload_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.
  5. 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

KeyDefaultDescription
default_timeout_seconds30timeout of operations without timeout_seconds
navigation_timeout_seconds60default timeout of open_tab / open_url
max_timeout_seconds300maximum timeout_seconds accepted from the model
read_page_max_chars20000default character limit of text and tree in read_page
read_page_max_chars_limit100000maximum max_chars
screenshot_max_width1280default screenshot width limit
screenshot_max_width_limit2560maximum max_width
screenshot_formatpngpng or jpeg
upload_allowed_directories[]absolute directories allowed for upload_files; empty disables uploads
allow_actions_on_user_tabsfalseallow navigation and actions on tabs not opened by the tool
irreversible_keywordsdefault listreplaces 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