adachsoft / web-browser-contract
Driver-agnostic contract for controlling a web browser: tabs, navigation, page snapshots with element refs, screenshots, actions and an irreversible-action safety guard.
Requires
- php: ^8.3
- adachsoft/collection: ^3.0
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
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 throughopenTab()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 throwsTabNotOwnedExceptionfor 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
ActionResultDtowithurlBefore,urlAfter,navigated,newTabId(set when the action opened a popup or tab),dialogOpenedand, when the dialog was answered during the action,handledDialog+dialogAction. - Element refs:
readPage()returns aPageSnapshotDto. ItsaccessibilityTreeis a compact text view (for example- button "Save" [ref=e12]) and itselementshold the same nodes asPageElementDtoobjects. Actions take anElementRefVofrom the snapshot, not a CSS selector. A ref used after the page has changed may throwStaleElementReferenceException. Read the page again to get fresh refs. - Timeouts: every operation accepts a
TimeoutVothrough an argument or an options DTO.nullmeans 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:
IrreversibleActionPolicyInterface::classify(BrowserActionDto): ActionRiskEnumdecides whether an action isREVERSIBLEorIRREVERSIBLE. ABrowserActionDtocarries 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 chooseIRREVERSIBLEwhen unsure.ActionOptionsDto::$irreversibleConsent(IrreversibleConsentVo) is the explicit consent for one action. Its reference names the user's decision, for example a task comment id.IrreversibleActionGuard::assertAllowed($action, $options)throwsIrreversibleActionNotConfirmedExceptionwhen the policy saysIRREVERSIBLEand 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.
| Exception | When |
|---|---|
InvalidInputException | Invalid VO/DTO data |
BrowserUnavailableException | The browser cannot be reached, or the connection was lost |
TabNotFoundException | The tab does not exist (anymore) |
TabNotOwnedException | Closing a tab the session did not open |
NavigationFailedException | A navigation failed (DNS, connection, aborted) |
TimeoutException | An operation exceeded its timeout (timeoutMs) |
ElementNotFoundException | The ref (or an option or root ref) does not exist |
StaleElementReferenceException | The ref comes from an outdated snapshot |
ElementNotInteractableException | The element is disabled, hidden, covered or of the wrong kind |
IrreversibleActionNotConfirmedException | An irreversible action was attempted without consent |
DialogNotFoundException | handleDialog() was called while no dialog is open |
BrowserOperationFailedException | Any 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