Search by

adachsoft / web-browser-contract

Arkadiusz Adach

Driver-agnostic contract for controlling a web browser: tabs, navigation, page snapshots with element refs, screenshots, actions and an irreversible-action safety guard.

Package info

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

Issues

pkg:composer/adachsoft/web-browser-contract

Statistics

Installs: 20

Dependents: 2

Suggesters: 0

Stars: 0

v0.1.0 2026-11-28 11:08 UTC

This package is auto-updated.

Last update: 2026-11-28 10:08:26 UTC


README

Driver-agnostic contract (interfaces, DTOs, value objects, enums, collections, exceptions) for controlling a real web browser the way a human does: managing tabs, opening URLs, reading pages as text plus an accessibility tree with element refs, taking screenshots for vision models and acting on elements (click, type, select, check, upload, press key, scroll).

The package contains no driver code. Known implementations:

  • adachsoft/web-browser-cdp: Chrome DevTools Protocol driver,
  • adachsoft/web-browser-tool: AI agent tool built on this contract.

Requirements

  • PHP 8.3 or higher
  • adachsoft/collection

Installation

composer require adachsoft/web-browser-contract

Concepts

  • WebBrowserInterface: the browser session. It lists tabs, opens new tabs, attaches to existing tabs and closes tabs. A tab opened through openTab() is owned by the session, and ownership must survive process restarts (for example, separate agent tool calls), so implementations persist it. closeTab() closes owned tabs only and throws TabNotOwnedException for any other tab, so the user's own tabs are never closed.
  • BrowserTabInterface: one tab. It covers navigation (openUrl, waitFor), reading (readPage, screenshot) and actions on elements (click, type, selectOptions, setChecked, uploadFiles, pressKey, scroll). It also handles JavaScript dialogs (getPendingDialog, handleDialog).
  • Action results: every action returns an ActionResultDto with urlBefore, urlAfter, navigated, newTabId (set when the action opened a popup or tab), dialogOpened and, when the dialog was answered during the action, handledDialog + dialogAction.
  • Element refs: readPage() returns a PageSnapshotDto. Its accessibilityTree is a compact text view (for example - button "Save" [ref=e12]) and its elements hold the same nodes as PageElementDto objects. Actions take an ElementRefVo from the snapshot, not a CSS selector. A ref used after the page has changed may throw StaleElementReferenceException. Read the page again to get fresh refs.
  • Timeouts: every operation accepts a TimeoutVo through an argument or an options DTO. null means the implementation default, and that default must be finite.
  • Irreversible actions: see Safety.

Usage

use AdachSoft\WebBrowserContract\Collections\SelectOptionVoCollection;
use AdachSoft\WebBrowserContract\Contracts\WebBrowserInterface;
use AdachSoft\WebBrowserContract\Dto\ActionOptionsDto;
use AdachSoft\WebBrowserContract\Dto\ReadPageOptionsDto;
use AdachSoft\WebBrowserContract\Dto\ScreenshotOptionsDto;
use AdachSoft\WebBrowserContract\Dto\WaitConditionDto;
use AdachSoft\WebBrowserContract\Enums\ImageFormatEnum;
use AdachSoft\WebBrowserContract\Exceptions\WebBrowserExceptionInterface;
use AdachSoft\WebBrowserContract\ValueObjects\ElementRefVo;
use AdachSoft\WebBrowserContract\ValueObjects\IrreversibleConsentVo;
use AdachSoft\WebBrowserContract\ValueObjects\KeyVo;
use AdachSoft\WebBrowserContract\ValueObjects\SelectOptionVo;
use AdachSoft\WebBrowserContract\ValueObjects\TimeoutVo;
use AdachSoft\WebBrowserContract\ValueObjects\UrlVo;

/** @var WebBrowserInterface $browser */
$browser = ...; // e.g. a CDP implementation

try {
    $tab = $browser->openTab(new UrlVo('https://example.com/form'));
    $tab->waitFor(WaitConditionDto::forText('Contact form', TimeoutVo::fromSeconds(15)));

    $snapshot = $tab->readPage(new ReadPageOptionsDto(interactiveOnly: true));
    echo $snapshot->accessibilityTree;
    // - textbox "Name" [ref=e3]
    // - combobox "Country" [ref=e4]
    // - checkbox "Subscribe" [ref=e5]
    // - button "Send" [ref=e6]

    $tab->type(new ElementRefVo('e3'), 'Jane Doe');
    $tab->selectOptions(new ElementRefVo('e4'), new SelectOptionVoCollection([new SelectOptionVo('Poland')]));
    $tab->setChecked(new ElementRefVo('e5'), false);

    // Irreversible: needs explicit consent when the implementation runs with a policy.
    $result = $tab->click(new ElementRefVo('e6'), new ActionOptionsDto(
        timeout: TimeoutVo::fromSeconds(10),
        irreversibleConsent: new IrreversibleConsentVo('task42_c3: user approved sending the form'),
    ));

    if ($result->navigated) {
        $tab->waitFor(WaitConditionDto::forText('Thank you'));
    }

    $tab->pressKey(new KeyVo('Escape'));
    $browser->closeTab($tab->getTabId());
} catch (WebBrowserExceptionInterface $exception) {
    echo 'Browser operation failed: ' . $exception->getMessage();
}

Tabs

foreach ($browser->listTabs() as $tabInfo) {
    printf("%s %s %s\n", $tabInfo->tabId->value, $tabInfo->openedBySession ? '[own]' : '[user]', $tabInfo->url);
}

$tab = $browser->getTab($tabInfo->tabId); // attach to an existing tab
$tab->activate();                          // bring it to front

Screenshots for vision models

ScreenshotDto holds everything needed to send the image to a vision model as image content: the raw bytes, mimeType(), toBase64(), toDataUri() and the width / height after downscaling.

$screenshot = $tab->screenshot(new ScreenshotOptionsDto(
    fullPage: false,               // viewport (default) or the whole page
    ref: new ElementRefVo('e6'),   // optional: one element only
    format: ImageFormatEnum::JPEG, // PNG by default
    maxWidth: 1024,                // downscale to cut token cost
    quality: 70,                   // JPEG only
));

$mime = $screenshot->mimeType(); // "image/jpeg"
$base64 = $screenshot->toBase64();

JavaScript dialogs

Panels often guard deletions or submissions with confirm(). When an action reports dialogOpened, read the dialog and answer it. Accepting a dialog goes through the irreversible-action guard (ActionTypeEnum::DIALOG_ACCEPT, with BrowserActionDto::$dialog set), so it needs a consent when the policy classifies it as irreversible.

$dialog = $tab->getPendingDialog(); // ?DialogDto: type (alert|confirm|prompt|beforeunload), message, defaultPrompt
if ($dialog !== null) {
    $tab->handleDialog(DialogActionEnum::DISMISS);
    // or: $tab->handleDialog(DialogActionEnum::ACCEPT, null, new ActionOptionsDto(irreversibleConsent: $consent));
    // prompt: $tab->handleDialog(DialogActionEnum::ACCEPT, 'answer', $options);
}

Answering a dialog as part of the action

Some drivers can answer a dialog only in the session that saw it open (with CDP, a later process cannot answer it). Give the answer in advance with ActionOptionsDto::$dialogResponse; the driver answers a dialog opened by the action and reports it in ActionResultDto::$handledDialog / $dialogAction. With expectedMessage the dialog is answered only when its message contains that text; otherwise it stays pending (ActionResultDto::hasPendingDialog()). Accepting is checked by the irreversible-action guard (DIALOG_ACCEPT) with the consent from the same options.

$result = $tab->click($deleteRef, new ActionOptionsDto(
    irreversibleConsent: new IrreversibleConsentVo('task1301_c7: delete draft'),
    dialogResponse: DialogResponseDto::accept(expectedMessage: 'Really delete'),
));
$result->handledDialog?->message; // "Really delete?"
$result->dialogAction;            // DialogActionEnum::ACCEPT

Waiting

WaitConditionDto::forText('Saved');
WaitConditionDto::forTextGone('Saving...');
WaitConditionDto::forSelector('form#app-content');
WaitConditionDto::forLoadState(LoadStateEnum::NETWORK_IDLE);
WaitConditionDto::forUrl('/app-content');

Safety: irreversible actions

Submitting, publishing, deleting, paying and accepting terms must happen only after the user has given explicit consent. The contract provides a minimal mechanism for this:

  1. IrreversibleActionPolicyInterface::classify(BrowserActionDto): ActionRiskEnum decides whether an action is REVERSIBLE or IRREVERSIBLE. A BrowserActionDto carries the action type, the ref, the target element from the latest snapshot (role and accessible name), the value, the page URL and, for dialog actions, the dialog. The contract ships no default heuristic; the tool layer provides it. A policy should choose IRREVERSIBLE when unsure.
  2. ActionOptionsDto::$irreversibleConsent (IrreversibleConsentVo) is the explicit consent for one action. Its reference names the user's decision, for example a task comment id.
  3. IrreversibleActionGuard::assertAllowed($action, $options) throws IrreversibleActionNotConfirmedException when the policy says IRREVERSIBLE and no consent is present. It returns the classification for audit logs.

Implementations configured with a policy must run the guard before every action and must not execute an action the guard rejects. The tool layer decides when to attach a consent, and does so only when the user has approved that specific action.

use AdachSoft\WebBrowserContract\Safety\IrreversibleActionGuard;

$guard = new IrreversibleActionGuard($policy);
$guard->assertAllowed(new BrowserActionDto(ActionTypeEnum::CLICK, $ref, $snapshot->findElement($ref), pageUrl: $snapshot->url), $options);

Exceptions

Every exception implements WebBrowserExceptionInterface.

ExceptionWhen
InvalidInputExceptionInvalid VO/DTO data
BrowserUnavailableExceptionThe browser cannot be reached, or the connection was lost
TabNotFoundExceptionThe tab does not exist (anymore)
TabNotOwnedExceptionClosing a tab the session did not open
NavigationFailedExceptionA navigation failed (DNS, connection, aborted)
TimeoutExceptionAn operation exceeded its timeout (timeoutMs)
ElementNotFoundExceptionThe ref (or an option or root ref) does not exist
StaleElementReferenceExceptionThe ref comes from an outdated snapshot
ElementNotInteractableExceptionThe element is disabled, hidden, covered or of the wrong kind
IrreversibleActionNotConfirmedExceptionAn irreversible action was attempted without consent
DialogNotFoundExceptionhandleDialog() was called while no dialog is open
BrowserOperationFailedExceptionAny other failure

Architecture

  • Contracts: WebBrowserInterface, BrowserTabInterface, IrreversibleActionPolicyInterface
  • Dto: TabInfoDto, NavigateOptionsDto, NavigationResultDto, WaitConditionDto, ReadPageOptionsDto, PageSnapshotDto, PageElementDto, ScreenshotOptionsDto, ScreenshotDto, ActionOptionsDto, ActionResultDto, ScrollRequestDto, BrowserActionDto, DialogDto, DialogResponseDto
  • ValueObjects: TimeoutVo, TabIdVo, UrlVo (http, https, about, file), ElementRefVo, KeyVo, FilePathVo (absolute path), SelectOptionVo, IrreversibleConsentVo
  • Enums: LoadStateEnum, WaitConditionTypeEnum, ActionTypeEnum, ActionRiskEnum, ScrollDirectionEnum, OptionMatchEnum, ImageFormatEnum, DialogTypeEnum, DialogActionEnum
  • Collections: TabInfoCollection, PageElementCollection, FilePathVoCollection, SelectOptionVoCollection
  • Safety: IrreversibleActionGuard
  • Exceptions: see the table above

Examples

Additional usage examples are available in docs/examples, including a basic browser session using a driver implementation.

Testing

composer test

License

MIT