Skip to content

The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.

finalize v2 runtime workflows and documentation

Aute220c2a433818
diff --git a/.claude/skills/ego-lite-simplify b/.claude/skills/ego-lite-simplify
new file mode 120000
index 0000000..c318146
--- /dev/null
+++ b/.claude/skills/ego-lite-simplify
@@ -0,0 +1 @@
+../../skills/ego-lite-simplify
\ No newline at end of file
diff --git a/.codex/skills/ego-lite-simplify b/.codex/skills/ego-lite-simplify
new file mode 120000
index 0000000..c318146
--- /dev/null
+++ b/.codex/skills/ego-lite-simplify
@@ -0,0 +1 @@
+../../skills/ego-lite-simplify
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 2930d40..220caaa 100644
--- a/.gitignore
+++ b/.gitignore
@@ -80,3 +80,6 @@ test-e2e/
test/
# Translated skill (local only)
skills/ego-browser/SKILL.zh.md
+
+# Local documentation workbench and research notes
+skills/ego-browser/workbench/
diff --git a/docs/local-runtime-development.md b/docs/local-runtime-development.md
new file mode 100644
index 0000000..7c27ea7
--- /dev/null
+++ b/docs/local-runtime-development.md
@@ -0,0 +1,82 @@
+# Use a Local Runtime with Ego Lite
+
+Ego Lite installs the `ego-browser` CLI and provides the native browser bridge.
+This repository builds the JavaScript runtime that the CLI can load for a
+single command:
+
+```text
+Installed Ego Lite CLI
+ -> --sdk-path
+ -> local dist/out/index.js
+ -> Ego Lite and Chromium
+```
+
+The override is temporary. It does not modify the installed application.
+
+## Build
+
+Ego Lite must be installed, onboarding must be complete, and `ego-browser` must
+be available on `PATH`.
+
+From the repository root:
+
+```bash
+cd package/ego-browser
+npm ci
+npm run build
+```
+
+The runtime is written to `package/ego-browser/dist/out/index.js`. Run
+`npm run build` again after changing runtime source code.
+
+## Run with the local runtime
+
+Use the CLI installed by Ego Lite and pass the absolute bundle path:
+
+```bash
+cd package/ego-browser
+
+ego-browser nodejs --sdk-path "$PWD/dist/out/index.js" <<'EOF'
+if (!globalThis.ego) throw new Error('Ego Lite native bindings are unavailable')
+process.stdout.write('Local runtime loaded successfully\n')
+EOF
+```
+
+For browser automation, keep the same command and write the heredoc using the
+API documented by the current checkout in `skills/ego-browser/SKILL.md`.
+
+Every manual invocation needs `--sdk-path`; it is not a persistent setting.
+Do not use `npm link` or replace files inside the Ego Lite application bundle.
+The installed CLI is still required to provide the native browser environment.
+
+## Verify against the real browser
+
+Run the real-browser E2E suite:
+
+```bash
+cd package/ego-browser
+npm run e2e
+```
+
+The suite builds the current worktree and automatically runs it through the
+installed CLI with `--sdk-path`. This is the preferred end-to-end compatibility
+check. `npm test` remains useful for repository tests but does not replace the
+real-browser check.
+
+## Keep the Skill aligned
+
+The Skill describes the APIs implemented by the runtime. When an agent is used,
+load `skills/ego-browser/SKILL.md` from the same checkout as the bundle. A Skill
+from another release may generate helper calls that the local runtime does not
+support.
+
+## Troubleshooting
+
+- **`ego-browser` not found:** finish Ego Lite onboarding and add its CLI
+ directory, commonly `~/.local/bin`, to `PATH`.
+- **`--sdk-path` unsupported:** update Ego Lite to a build that supports loading
+ an external runtime.
+- **Changes are not visible:** rebuild and confirm that the absolute SDK path
+ points to the intended checkout.
+- **Browser APIs are missing:** align the Skill with the checkout, then run
+ `npm run e2e` to check app/runtime compatibility.
diff --git a/docs/native-bindings-api.md b/docs/native-bindings-api.md
new file mode 100644
index 0000000..100d160
--- /dev/null
+++ b/docs/native-bindings-api.md
@@ -0,0 +1,859 @@
+# Ego Lite Native Bindings API Reference
+
+This document describes the low-level `globalThis.ego` API injected into the
+`ego-browser nodejs` environment by the installed Ego Lite application.
+
+These bindings are provided by Ego Lite, not implemented by this repository.
+Their availability is determined by the installed Ego Lite build and is
+independent of the Git tag or branch used to build the local `ego-browser`
+runtime.
+
+The runtime in this repository consumes these bindings and may expose only a
+subset of them through its higher-level helpers. Agent automation should
+normally follow `skills/ego-browser/SKILL.md`; runtime maintainers may access
+`globalThis.ego` directly when working with the native bridge.
+
+## Runtime Model
+
+Most methods return a `Promise` and route work to the browser-side
+`NodeClient`. Promise results are converted from browser-side `base::Value`
+objects, so result shapes can follow the command implementation that handled the
+request.
+
+Task-scoped APIs operate on the current task context. Select that context with
+`ego.useTaskSpace(id)` inside the script. `id` is the numeric task-space id
+reported by `ego.createTaskSpace()`, `ego.claimTaskSpace()`, or
+`ego.listTaskSpaces()`. Selecting a task only updates the current Node
+invocation; it does not create, claim, or validate the browser-side task space.
+
+Profiles are selected when a task space is created, not through
+`ego.useTaskSpace()`. Call `ego.listProfiles()` to discover the available
+profiles, then pass the selected profile's `id` to
+`ego.createTaskSpace(name, profileId)`. Existing task-scoped APIs continue to
+operate on the profile that owns the selected task space.
+
+Task-space result objects currently expose both a numeric locator and a
+user-visible name:
+
+```js
+{
+ id: 7, // numeric unique task-space locator
+ taskId: 'checkout-flow', // same value as name
+ name: 'checkout-flow', // user-visible display name
+}
+```
+
+Use `id` when calling APIs that operate on an existing task space. `taskId` is a
+display-name compatibility field and should not be used as a locator.
+
+If no task context is available, task-scoped APIs resolve to an error object or
+reject depending on the underlying operation. Regular task commands usually
+resolve an object like
+`{ error: "Task space not selected", error_code: "EGO_TASK_SPACE_NOT_SELECTED" }`;
+`ego.snapshot()` rejects with an `Error` whose `error_code` property is set.
+
+When a task has been handed off to the user, browser-mutating automation calls
+are blocked until the agent takes the task back. The affected APIs are
+`ego.createTab()`, `ego.listTabs()`, `ego.snapshot()`, `ego.closeTaskSpace()`,
+`ego.completeTaskSpace()`, `ego.animationHighlightMouseToPosition()`,
+`ego.setAgentTaskState()`, and raw CDP sends through `ego.sendCDPMessage()`.
+Most of these APIs resolve an error object with `error` and `error_code` fields;
+`ego.snapshot()` rejects with an `Error` containing `error_code`; raw CDP sends
+report the failure through `ego.onSendCDPMessageError`.
+
+## Error Codes
+
+Browser-side failures expose a stable `error_code` in addition to a human-readable
+message. Promise-returning APIs use one of these shapes:
+
+```js
+{ error: 'Task space not selected', error_code: 'EGO_TASK_SPACE_NOT_SELECTED' }
+```
+
+or, for rejected operations:
+
+```js
+try {
+ await ego.snapshot();
+} catch (error) {
+ console.log(error.message);
+ console.log(error.error_code);
+}
+```
+
+Argument validation failures throw `TypeError` with
+`error_code: 'EGO_INVALID_ARGUMENT'`.
+
+Known error codes:
+
+```text
+EGO_BROWSER_UNAVAILABLE
+EGO_CDP_CHANNEL_UNAVAILABLE
+EGO_CDP_SEND_FAILED
+EGO_INVALID_ARGUMENT
+EGO_INVALID_RESULT_PAYLOAD
+EGO_OPERATION_FAILED
+EGO_PROFILE_NOT_FOUND
+EGO_RESULT_CONVERSION_FAILED
+EGO_SNAPSHOT_FAILED
+EGO_TASK_HOST_DISCONNECTED
+EGO_TASK_SPACE_INACTIVE
+EGO_TASK_SPACE_NOT_FOUND
+EGO_TASK_SPACE_NOT_SELECTED
+EGO_TASK_SPACE_UNAVAILABLE
+EGO_TASK_SPACE_USER_IN_CONTROL
+EGO_WEB_CONTENTS_UNAVAILABLE
+```
+
+All async callbacks are bounced through the Node event loop before JS is
+invoked. Scripts can safely `await` these APIs and allow the process to exit
+after pending requests settle.
+
+## Task Context
+
+### `ego.useTaskSpace(id)`
+
+Selects the task context for subsequent task-scoped helper calls in the current
+Node invocation. This is a synchronous local selection only.
+
+```js
+const id = ego.useTaskSpace(task.id);
+```
+
+Arguments:
+
+```text
+id: number
+```
+
+Returns the selected `id` synchronously.
+
+Throws `TypeError` when `id` is missing, not a number, or extra arguments are
+provided. The thrown error has `error_code: 'EGO_INVALID_ARGUMENT'`.
+
+Use `ego.createTaskSpace(name)` to create a new agent-owned task space. Use
+`ego.claimTaskSpace(id, name?)` to take ownership of an existing user-owned space
+before selecting it.
+
+## Profiles
+
+Profiles determine which browser identity, cookies, storage, and login state a
+new task space inherits. Profile selection only applies when creating the task
+space. After creation, select the returned task-space `id` with
+`ego.useTaskSpace(task.id)` as usual.
+
+Profile APIs are available when the installed Ego Lite build exposes them,
+even if the checked-out repository runtime does not yet provide equivalent
+higher-level helper methods.
+
+### `await ego.listProfiles()`
+
+Lists the profiles that may be used by `ego.createTaskSpace()`.
+
+```js
+const result = await ego.listProfiles();
+for (const profile of result.profiles) {
+ console.log(profile.id, profile.name, profile.isDefault);
+}
+```
+
+Arguments: none.
+
+Returns:
+
+```js
+{
+ profiles: [
+ {
+ id: 'Profile 2',
+ name: 'Work',
+ isDefault: false,
+ },
+ {
+ id: 'Default',
+ name: 'Personal',
+ isDefault: true,
+ },
+ ],
+}
+```
+
+Field meanings:
+
+```text
+id:
+ Locator accepted by ego.createTaskSpace(name, profileId), for example
+ "Default" or "Profile 2".
+
+name:
+ User-visible profile name. It may be duplicated and is not a locator.
+
+isDefault:
+ True for the profile selected when profileId is omitted. This does not
+ necessarily mean that id is "Default".
+```
+
+The result contains available regular profiles. The internal Ego authentication
+profile is not exposed.
+
+Throws `TypeError` when any argument is passed. The thrown error has
+`error_code: 'EGO_INVALID_ARGUMENT'`.
+
+To create a task space with a profile, pass `profile.id` to
+`ego.createTaskSpace(name, profileId)`. See the Task Spaces section for the
+complete call and error handling.
+
+## Tabs
+
+### `await ego.createTab(url)`
+
+Creates a tab in the current task space.
+
+```js
+const tab = await ego.createTab('https://example.com/');
+console.log(tab.targetId);
+```
+
+Arguments:
+
+```text
+url: string
+```
+
+Returns a browser-side result object. Current task implementations return a
+tab descriptor containing at least `targetId` when creation succeeds.
+
+Throws `TypeError` when `url` is missing or not a string.
+The thrown error has `error_code: 'EGO_INVALID_ARGUMENT'`.
+
+### `await ego.listTabs()`
+
+Lists tabs in the current task space.
+
+```js
+const result = await ego.listTabs();
+for (const tab of result.tabs) {
+ console.log(tab.index, tab.title, tab.url, tab.active);
+}
+```
+
+Arguments: none.
+
+Typical result:
+
+```js
+{
+ tabs: [
+ {
+ index: 0,
+ targetId: '...',
+ url: 'https://example.com/',
+ title: 'Example',
+ active: true,
+ },
+ ],
+}
+```
+
+If the current task has been handed off to the user, the promise resolves to an
+error object:
+
+```js
+{
+ error: 'The task is under user control...',
+ error_code: 'EGO_TASK_SPACE_USER_IN_CONTROL',
+}
+```
+
+`error_code` is always `'EGO_TASK_SPACE_USER_IN_CONTROL'`. The `error` string
+describes why control was handed over. Permission prompts, device choosers, and
+required page dialogs use one of these messages:
+
+```text
+Notifications:
+ A browser permission prompt for notifications has appeared. Control of this
+ browser space has been handed over.
+
+Location (including approximate):
+ A browser permission prompt for location, precise or approximate, has
+ appeared. Control of this browser space has been handed over.
+
+Camera:
+ A browser permission prompt for camera access has appeared. Control of this
+ browser space has been handed over.
+
+Microphone:
+ A browser permission prompt for microphone access has appeared. Control of
+ this browser space has been handed over.
+
+Pan-Tilt-Zoom + Microphone:
+ A browser permission prompt for camera control and microphone access has
+ appeared. Control of this browser space has been handed over.
+
+MIDI:
+ A browser permission prompt for MIDI device access has appeared. Control of
+ this browser space has been handed over.
+
+Bluetooth:
+ A browser device chooser for Bluetooth has appeared. Control of this browser
+ space has been handed over.
+
+USB:
+ A browser device chooser for USB has appeared. Control of this browser space
+ has been handed over.
+
+Serial:
+ A browser port chooser for serial access has appeared. Control of this
+ browser space has been handed over.
+
+HID:
+ A browser device chooser for HID has appeared. Control of this browser space
+ has been handed over.
+
+Protocol Handler:
+ A browser permission prompt for protocol handler registration has appeared.
+ Control of this browser space has been handed over.
+
+Fallback — site dialog / required notice:
+ The page has displayed a dialog that requires review. Control of this browser
+ space has been handed over.
+```
+
+Example when a notifications prompt caused the handoff:
+
+```js
+{
+ error: 'A browser permission prompt for notifications has appeared. Control of this browser space has been handed over.',
+ error_code: 'EGO_TASK_SPACE_USER_IN_CONTROL',
+}
+```
+
+## Snapshot
+
+### `await ego.snapshot(options?)`
+
+Captures a structured snapshot for the current task space.
+
+```js
+const snapshot = await ego.snapshot({
+ scope: 'only_within_viewport',
+ includeActionMarks: true,
+ interactiveOnly: true,
+ includeStableLocator: true,
+ maxResultLength: 4000,
+});
+
+console.log(snapshot.content);
+console.log(snapshot.refs);
+```
+
+Arguments:
+
+```text
+options?: object
+```
+
+Supported options:
+
+```text
+scope:
+ 'full_page' Capture the full page. This is the default.
+ 'only_within_viewport' Capture only the viewport.
+
+includeActionMarks: boolean
+ Include action markers in the textual snapshot.
+
+interactiveOnly: boolean
+ Limit output to interactive elements.
+
+includeStableLocator: boolean
+ Include reusable locator hints on refs when available.
+
+maxResultLength: number
+ Maximum result content length. Zero or omitted means unlimited.
+```
+
+Result:
+
+```js
+{
+ content: '...',
+ refs: [
+ {
+ backendNodeId: 17,
+ role: 'button',
+ name: 'Continue',
+ loc: 'role:button[name=Continue]', // only when available
+ },
+ ],
+}
+```
+
+If the browser side reports a snapshot error, the promise rejects with an
+`Error`. The `message` contains the human-readable error, and `error_code`
+contains a stable code such as `EGO_SNAPSHOT_FAILED`,
+`EGO_TASK_SPACE_NOT_SELECTED`, `EGO_TASK_SPACE_NOT_FOUND`,
+`EGO_TASK_SPACE_USER_IN_CONTROL`, or `EGO_WEB_CONTENTS_UNAVAILABLE`.
+
+## Task Spaces
+
+### `await ego.listTaskSpaces()`
+
+Lists known task spaces.
+
+```js
+const spaces = await ego.listTaskSpaces();
+for (const space of spaces.taskSpaces) {
+ console.log(space.id, space.name, space.ownership);
+}
+```
+
+Arguments: none.
+
+Returns:
+
+```js
+{
+ taskSpaces: [
+ {
+ taskId: 'checkout-flow',
+ id: 7,
+ name: 'checkout-flow',
+ createdBy: 'agent',
+ ownership: 'agent',
+ recentTabTitles: ['Checkout', 'Cart'],
+ },
+ ],
+}
+```
+
+Throws `TypeError` when any argument is passed.
+The thrown error has `error_code: 'EGO_INVALID_ARGUMENT'`.
+
+### `await ego.createTaskSpace(name, profileId?)`
+
+Creates an agent-owned task space by name, optionally using a specific profile.
+
+```js
+const { profiles } = await ego.listProfiles();
+const profile = profiles.find(item => !item.isDefault) ?? profiles[0];
+if (!profile) {
+ throw new Error('No available profile');
+}
+
+const taskName = `profile-demo-${Date.now()}`;
+const task = await ego.createTaskSpace(taskName, profile.id);
+if (task.error) {
+ throw new Error(`${task.error} (${task.error_code})`);
+}
+ego.useTaskSpace(task.id);
+console.log(JSON.stringify({ profile, task }, null, 2));
+```
+
+Arguments:
+
+```text
+name: string, non-empty
+profileId?: string
+ Unique profile id returned by ego.listProfiles(). If omitted, empty, or
+ "default", the currently active/last-used regular profile is selected.
+```
+
+Returns:
+
+```js
+{
+ taskId: 'checkout-flow',
+ id: 7,
+ name: 'checkout-flow',
+}
+```
+
+Throws `TypeError` when `name` is missing, not a string, or empty; when
+`profileId` is present but not a string; or when extra arguments are provided.
+The thrown error has `error_code: 'EGO_INVALID_ARGUMENT'`.
+
+If `profileId` does not identify an available profile, the promise resolves to:
+
+```js
+{
+ error: 'Profile not found',
+ error_code: 'EGO_PROFILE_NOT_FOUND',
+}
+```
+
+If the browser cannot create a task space, the promise resolves to an error
+object:
+
+```js
+{
+ error: 'No active browser',
+ error_code: 'EGO_BROWSER_UNAVAILABLE',
+}
+```
+
+### `await ego.claimTaskSpace(id, name?)`
+
+Claims an existing space by numeric id and turns it into an agent-owned task
+space. Pass `name` to rename the space while claiming it.
+
+```js
+const spaces = await ego.listTaskSpaces();
+const checkout = spaces.taskSpaces.find(space => space.name === 'checkout-flow');
+const task = await ego.claimTaskSpace(checkout.id, 'checkout-flow');
+ego.useTaskSpace(task.id);
+```
+
+Arguments:
+
+```text
+id: number
+name?: string
+```
+
+Returns:
+
+```js
+{
+ taskId: 'checkout-flow',
+ id: 7,
+ name: 'checkout-flow',
+}
+```
+
+Throws `TypeError` when `id` is missing or not a number, when `name` is present
+but not a string, or when extra arguments are provided. The thrown error has
+`error_code: 'EGO_INVALID_ARGUMENT'`.
+
+If the space does not exist or cannot be claimed, the promise resolves to an
+error object. Error messages identify the numeric id that was used for lookup:
+
+```js
+{
+ error: 'Task space not found: 7',
+ error_code: 'EGO_TASK_SPACE_NOT_FOUND',
+}
+```
+
+`claimTaskSpace()` does not select the task context by itself. Call
+`ego.useTaskSpace(task.id)` after a successful claim before using task-scoped
+helpers.
+
+### `await ego.closeTaskSpace()`
+
+Closes the current task space and removes the task-owned browser state.
+
+```js
+await ego.closeTaskSpace();
+```
+
+Arguments: none.
+
+Returns a browser-side status value, currently a string such as
+`"<id> task space closed."` on success, or an error object if the task does
+not exist. Error objects include `error` and `error_code`.
+
+Throws `TypeError` when any argument is passed. The thrown error has
+`error_code: 'EGO_INVALID_ARGUMENT'`.
+
+### `await ego.completeTaskSpace()`
+
+Completes the current task space by removing agent task state while leaving the
+space open as a normal space.
+
+```js
+await ego.completeTaskSpace();
+```
+
+Arguments: none.
+
+Returns a browser-side status value, currently a string such as
+`"<id> task space completed."` on success, or an error object if the task
+does not exist. Error objects include `error` and `error_code`.
+
+Throws `TypeError` when any argument is passed. The thrown error has
+`error_code: 'EGO_INVALID_ARGUMENT'`.
+
+## Task Control
+
+### `await ego.handOffTaskSpace()`
+
+Transfers the current task space to user control.
+
+```js
+await ego.handOffTaskSpace();
+```
+
+Arguments: none.
+
+Returns the browser-side status value from the handoff operation.
+Current implementations return a string such as
+`"<id> has been handed off to the user."`.
+
+Throws `TypeError` when any argument is passed. The thrown error has
+`error_code: 'EGO_INVALID_ARGUMENT'`.
+
+### `await ego.takeOverTaskSpace()`
+
+Returns the current task space to agent control.
+
+```js
+await ego.takeOverTaskSpace();
+```
+
+Arguments: none.
+
+Returns the browser-side status value from the takeover operation.
+Current implementations return a string such as
+`"<id> has been taken over by the agent."`.
+
+Throws `TypeError` when any argument is passed. The thrown error has
+`error_code: 'EGO_INVALID_ARGUMENT'`.
+
+### `await ego.setAgentTaskState(state)`
+
+Updates the user-visible agent progress text for the current task space.
+
+```js
+await ego.setAgentTaskState('Waiting for checkout page');
+```
+
+Arguments:
+
+```text
+state: string
+```
+
+Returns the browser-side status value from the task state update. Current
+implementations return a string such as `"<id> state updated."`.
+
+Throws `TypeError` when `state` is missing, not a string, or extra arguments are
+provided. The thrown error has `error_code: 'EGO_INVALID_ARGUMENT'`.
+
+## UI Helpers
+
+### `await ego.animationHighlightMouseToPosition(x, y)`
+
+Shows an animated highlight at the given screen position for the current task
+space.
+
+```js
+await ego.animationHighlightMouseToPosition(120, 240);
+```
+
+Arguments:
+
+```text
+x: number
+y: number
+```
+
+Returns the browser-side status value from the highlight operation. Current
+implementations return a string such as `"<id> mouse highlight shown."`.
+
+Throws `TypeError` when either coordinate is missing, not a number, or extra
+arguments are provided. The thrown error has
+`error_code: 'EGO_INVALID_ARGUMENT'`.
+
+## Chrome DevTools Protocol
+
+### `ego.sendCDPMessage(message)`
+
+Sends a raw CDP message through the Node CDP channel. The message must already
+be JSON-encoded. The current task must be selected with `ego.useTaskSpace(id)`,
+and its ownership must be `agent`. If the task is missing, inactive, delegated
+to the user, or unavailable, the message is not sent and
+`ego.onSendCDPMessageError` receives the reconstructed error message and code.
+
+```js
+const task = await ego.createTaskSpace('cdp-demo');
+ego.useTaskSpace(task.id);
+ego.sendCDPMessage(JSON.stringify({
+ id: 1,
+ method: 'Runtime.enable',
+}));
+```
+
+Arguments:
+
+```text
+message: string
+```
+
+Returns `undefined`.
+
+Throws `TypeError` when `message` is missing or not a string, or when the CDP
+channel is not connected. The thrown error has `error_code` set to
+`EGO_INVALID_ARGUMENT` for invalid arguments or `EGO_CDP_CHANNEL_UNAVAILABLE`
+when the channel is missing.
+
+Notes:
+
+```text
+Raw CDP user-control checks use the task selected by ego.useTaskSpace(id).
+If no task has been selected, the send fails with EGO_TASK_SPACE_NOT_SELECTED.
+```
+
+### `ego.onCDPMessage`
+
+Property used to receive raw CDP messages from the browser side.
+
+```js
+ego.onCDPMessage = message => {
+ const event = JSON.parse(message);
+ console.log(event.method);
+};
+```
+
+Assign a function to receive messages. Assigning any non-function value clears
+the callback. Incoming messages are delivered asynchronously through the Node
+event loop.
+
+### `ego.onSendCDPMessageError`
+
+Property used to receive local send failures for `ego.sendCDPMessage()`.
+
+```js
+ego.onSendCDPMessageError = (message, error_code) => {
+ console.error(message, error_code);
+};
+
+const task = await ego.createTaskSpace('cdp-version');
+ego.useTaskSpace(task.id);
+ego.sendCDPMessage(JSON.stringify({
+ id: 2,
+ method: 'Browser.getVersion',
+}));
+```
+
+Arguments delivered to the callback:
+
+```text
+message: string
+error_code: string
+```
+
+Assign a function to receive errors. Assigning any non-function value clears the
+callback. Errors are delivered asynchronously through the Node event loop.
+
+This callback is used for failures that happen before the message reaches CDP,
+including:
+
+```text
+- the task is currently under user control
+- no task space has been selected
+- the selected task space does not exist
+- the selected task space has not been claimed by the agent
+- the browser-side CDP agent host is no longer available
+```
+
+User-control example:
+
+```js
+const task = await ego.createTaskSpace('user-control-demo');
+ego.useTaskSpace(task.id);
+await ego.handOffTaskSpace();
+
+const result = await ego.createTab('https://example.com/');
+console.log(result.error);
+console.log(result.error_code); // "EGO_TASK_SPACE_USER_IN_CONTROL"
+
+try {
+ await ego.snapshot();
+} catch (error) {
+ console.log(error.message);
+ console.log(error.error_code); // "EGO_TASK_SPACE_USER_IN_CONTROL"
+}
+
+ego.onSendCDPMessageError = (message, error_code) => {
+ console.log(message);
+ console.log(error_code); // "EGO_TASK_SPACE_USER_IN_CONTROL"
+};
+ego.sendCDPMessage(JSON.stringify({
+ id: 1,
+ method: 'Browser.getVersion',
+}));
+
+await ego.takeOverTaskSpace();
+```
+
+## Complete Example
+
+```js
+const { profiles } = await ego.listProfiles();
+const profile = profiles.find(item => !item.isDefault) ?? profiles[0];
+if (!profile) {
+ throw new Error('No available profile');
+}
+
+const task = await ego.createTaskSpace('checkout-flow', profile.id);
+if (task.error) {
+ throw new Error(`${task.error} (${task.error_code})`);
+}
+ego.useTaskSpace(task.id);
+
+await ego.createTab('https://example.com/');
+await ego.setAgentTaskState('Reading page');
+
+const snapshot = await ego.snapshot({
+ scope: 'only_within_viewport',
+ includeActionMarks: true,
+ interactiveOnly: true,
+});
+
+console.log(snapshot.content);
+
+await ego.completeTaskSpace();
+```
+
+## Native API Compatibility Notes
+
+### Profile-aware task-space creation
+
+- Added `ego.listProfiles()`, which returns available profiles as
+ `{id, name, isDefault}`.
+- `ego.createTaskSpace(name)` now accepts an optional profile locator:
+ `ego.createTaskSpace(name, profileId?)`.
+- Profile display names are not accepted as locators because they are not
+ unique. Callers must pass the `id` returned by `ego.listProfiles()`.
+- Omitting `profileId`, passing an empty string, or passing `"default"` selects
+ the current default regular profile.
+- Unknown profile ids resolve an error object with
+ `error_code: 'EGO_PROFILE_NOT_FOUND'`.
+
+### Task-space ids are numeric locators
+
+- `ego.useTaskSpace(taskId)` changed to `ego.useTaskSpace(id)`.
+ `id` is a numeric task-space locator returned by task-space APIs.
+
+- `ego.claimTaskSpace(name)` changed to `ego.claimTaskSpace(id, name?)`.
+ The first argument identifies an existing task space by numeric id. `name` is
+ optional and renames the task space when provided.
+
+- Task-space result objects now distinguish locator and display fields:
+
+ ```js
+ {
+ id: 7,
+ taskId: 'checkout-flow',
+ name: 'checkout-flow',
+ }
+ ```
+
+ Use `id` for API calls. `taskId` is currently the same value as `name` and is
+ retained as a display-name compatibility field.
+
+- Task-scoped examples now select task spaces with `task.id`, including
+ `createTab`, `listTabs`, `snapshot`, `closeTaskSpace`,
+ `completeTaskSpace`, `handOffTaskSpace`, `takeOverTaskSpace`,
+ `setAgentTaskState`, `animationHighlightMouseToPosition`, and raw CDP sends.
+
+- Browser-side operation messages now identify task spaces by numeric id, for
+ example `"<id> task space completed."`, `"<id> state updated."`, and
+ `"Task space not found: <id>"`.
+
+### Error codes
+
+- Browser-side error results now include a stable `error_code` string.
+- `ego.snapshot()` rejects with an `Error` whose `error_code` property is set.
+- `ego.onSendCDPMessageError` receives `(message, error_code)`.
diff --git a/docs/runtime-v2-architecture.md b/docs/runtime-v2-architecture.md
index f041f45..53be704 100644
--- a/docs/runtime-v2-architecture.md
+++ b/docs/runtime-v2-architecture.md
@@ -90,7 +90,7 @@ CDP session、事件缓冲、dialog 状态和 Network domain 状态都按 target
"usedLabels": ["p1", "p2"],
"releasedLabels": [],
"initialized": true,
- "handoffBaseline": null,
+ "userControlPending": false,
"unmanagedTargets": {
"USER_TARGET": "unknown"
},
@@ -110,8 +110,8 @@ CDP session、事件缓冲、dialog 状态和 Network domain 状态都按 target
`openPage()`、`adopt()`、`release()` 和 `close()` 在 await 返回前完成写入。写入
使用临时文件和 atomic rename,避免留下半个 JSON 文件。
-旧开发版本写入的 `version`、`writerRound`、`openedAt`、`lastUsedAt` 和
-`touchedAt` 会被读取兼容,并在下一次写入时删除。
+旧开发版本写入的 `version`、`writerRound`、`handoffBaseline`、`openedAt`、
+`lastUsedAt` 和 `touchedAt` 会被读取兼容,并在下一次写入时删除。
### 4.2 标签
@@ -131,8 +131,9 @@ CDP session、事件缓冲、dialog 状态和 Network domain 状态都按 target
- 第一次观察一个 space 时,已有 tab 记为 `unknown`,不会猜测它们由谁创建。
- 在 Agent 持续控制该 space 时,后来出现的新 tab 会自动加入账本。
- 用户控制期间不做自动收编。
-- `handOff()` 在交出控制前记录当时的 tab 集合。claim/takeover 后第一次盘点把
- 用户期间新增的 tab 记为 `unknown`,然后恢复 Agent 新 tab 的自动收编。
+- `handOff()` 在交出控制前记录一个待处理的用户控制边界。claim/takeover 后
+ 第一次盘点把尚未登记的 tab 记为 `unknown`,然后恢复 Agent 新 tab 的自动
+ 收编。
不同 space 使用不同文件。多个进程同时写同一 space 不受支持,可能
last-writer-wins。如果未来需要支持,必须使用文件锁或 CAS;不维护只能发现
@@ -177,7 +178,7 @@ const adopted = await task.adopt(unknown.page, { as: "reference" });
`UnmanagedPage` 只有身份信息,不能直接导航、点击或关闭。调用 `adopt()` 后才
获得完整 Page。
-`release(label)` 只允许归还 user/unknown 页面,并保持浏览器 tab 打开。
+`release(label)` 只允许归还来源为 `unknown` 的页面,并保持浏览器 tab 打开。
Agent 创建的页面不能 release,必须显式 close,避免制造无人管理的 tab。
### 5.4 Popup
@@ -262,6 +263,10 @@ await page.hover(selector, options)
await page.dragAndDrop(source, target, options)
await page.fill(selector, value, options)
await page.setInputFiles(selector, path)
+const chooserPromise = page.waitForFileChooser({ timeout })
+await page.click(selector)
+const chooser = await chooserPromise
+await chooser.setFiles(path)
await page.scrollBy(deltaY, { deltaX, behavior })
await page.close()
```
@@ -270,6 +275,11 @@ await page.close()
options 中;`fullPage` 表示捕获完整页面。`waitForSelector()` 的 `state` 支持
`attached`、`detached`、`visible` 和 `hidden`,默认是 `visible`。
+文件上传不操作系统文件选择器。已有 file input 时,`setInputFiles()` 直接设置
+文件;网站点击后才创建 input 时,先建立 `waitForFileChooser()`,再点击并通过
+返回的 chooser 设置文件。普通输入动作意外打开 chooser 时,runtime 会在系统
+弹窗出现前取消,并提示改用这两个接口。
+
`page.fetch()` 是 Ego 提供的便利扩展,不是 Playwright 方法。它在目标页面内
执行 `window.fetch()`,因此使用该页面的相对 URL、Cookie、CORS 和 service
worker。返回值为:
@@ -340,18 +350,16 @@ Page 对象只在当前脚本轮次内存在,因此鼠标位置不会跨轮保
### 7.2 高层动作回执
`goto()`、selector action、`mouse.click()` 和 `keyboard.press()` 返回轻量
-回执:
+popup 回执:
```js
{
- navigation?: { from, to },
- domChanged?: true,
popups?: [{ label, targetId }]
}
```
-为了生成回执,高层动作会短暂观察 URL、表单状态、DOM mutation 和 tab
-变化。观察失败不会阻止实际动作。
+高层动作只比较动作前后的 tab 列表,不向页面安装观察脚本。导航、表单和 DOM
+结果应通过 `url()`、`waitForSelector()`、`snapshot()` 或读取页面状态确认。
底层原语不安装动作探针,也不等待 50ms 反馈窗口:
@@ -468,7 +476,7 @@ surface,不属于本阶段。
- popup 可由动作回执立即收编;即使动作回执漏记,后续盘点也会补回账本。
- `Page.close()` 确认 tab 消失后才删除标签,最后 tab 有 anchor。
- screenshot、evaluate、fetch、键盘和鼠标都操作并激活指定 Page。
-- 底层键鼠不安装动作探针,高层动作仍能返回导航和 popup 回执。
+- 页面动作不安装观察探针;高层动作仍能返回 popup 回执。
- `keyboard.press()` 产生 native/trusted 输入;新版不暴露 synthetic dispatch。
- snapshot 始终返回全量并标明来源,不接受 `diff`。
- 旧格式账本能读取,并在下一次写入时删掉过期字段。
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
index d0eb3ed..7acc4ef 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
@@ -310,6 +310,34 @@ export function pageBasicOperationsCase() {
"fixture-upload.txt,fixture-upload-two.txt",
"page.setInputFiles attaches multiple files in the addressed page"
);
+ await first.setInputFiles("label[for=file-input]", uploadPath);
+ assertEqual(
+ await first.evaluate("document.querySelector('#file-input').files[0].name"),
+ "fixture-upload.txt",
+ "page.setInputFiles follows a label to its file input"
+ );
+
+ await assertRejects(
+ () => first.click("#dynamic-file-button"),
+ "page.waitForFileChooser",
+ "an unhandled file chooser is cancelled before a system dialog opens"
+ );
+ assertEqual(
+ await first.evaluate("document.querySelector('[data-dynamic-upload]').files.length"),
+ 0,
+ "cancelling an unhandled chooser does not select a file"
+ );
+
+ const chooserPromise = first.waitForFileChooser({ timeout: 2_000 });
+ await first.click("#dynamic-file-button");
+ const chooser = await chooserPromise;
+ assertEqual(chooser.isMultiple(), true, "dynamic file chooser reports multiple mode");
+ await chooser.setFiles([uploadPath, uploadPathTwo]);
+ assertEqual(
+ await first.evaluate("Array.from(document.querySelector('[data-dynamic-upload]').files).map(file => file.name).join(',')"),
+ "fixture-upload.txt,fixture-upload-two.txt",
+ "page.waitForFileChooser uploads without a system dialog"
+ );
assertEqual((await currentTab()).targetId, first.targetId, "Page keyboard and file methods keep their Page active");
const screenshotPath = join(tempDir, "page-api-first.png");
@@ -326,9 +354,8 @@ export function pageBasicOperationsCase() {
);
const navigationReceipt = await first.click("#nav-link");
- assertIncludes(navigationReceipt.navigation.from, "page-api=first", "click receipt reports the source URL");
- assertIncludes(navigationReceipt.navigation.to, "/nav-target", "click receipt reports the destination URL");
- assertEqual(navigationReceipt.domChanged, true, "navigation is reported as a document change");
+ assertEqual(Object.keys(navigationReceipt).length, 0, "an action without a popup returns an empty receipt");
+ assertIncludes(await first.url(), "/nav-target", "the navigation is verified from page state");
await first.close();
await second.close();
@@ -360,7 +387,7 @@ export function pageActionsAndPopupCase() {
});
});
const fillReceipt = await source.fill("#text-input", "page-filled");
- assertEqual(fillReceipt.domChanged, true, "page.fill reports its form-state change");
+ assertEqual(Object.keys(fillReceipt).length, 0, "page.fill returns no receipt without a popup");
assertEqual(await source.evaluate("document.querySelector('#text-input').value"), "page-filled", "page.fill writes into the addressed page");
assert(
(await source.evaluate("window.__pageFillEvents")).some(
diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
index d871991..842664a 100644
--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
@@ -288,7 +288,10 @@ function pageHtml(kind, { iframeUrl = "/frame.html" } = {}) {
<label>Text input <input id="text-input" value="initial"></label>
<label>Append input <input id="append-input" value="base"></label>
<label>Text area <textarea id="text-area">seed</textarea></label>
- <label>File input <input id="file-input" type="file" multiple></label>
+ <label for="file-input">File input</label>
+ <input id="file-input" type="file" multiple hidden>
+ <button id="dynamic-file-button" type="button">Choose files dynamically</button>
+ <div id="dynamic-file-container"></div>
<div id="file-name"></div>
<div id="key-log"></div>
<label>Dropdown <select id="dropdown">
@@ -398,6 +401,14 @@ function pageHtml(kind, { iframeUrl = "/frame.html" } = {}) {
document.querySelector("#file-name").textContent =
Array.from(event.target.files).map((file) => file.name).join(",");
});
+ document.querySelector("#dynamic-file-button").addEventListener("click", () => {
+ const input = document.createElement("input");
+ input.type = "file";
+ input.multiple = true;
+ input.dataset.dynamicUpload = "true";
+ document.querySelector("#dynamic-file-container").replaceChildren(input);
+ input.click();
+ });
/* value inputs (email/number) — track input/change for fillInput regressions */
for (const id of ["email-input", "number-input"]) {
diff --git a/package/ego-browser/src/browser-runtime.test.mjs b/package/ego-browser/src/browser-runtime.test.mjs
index 454591b..c8b479b 100644
--- a/package/ego-browser/src/browser-runtime.test.mjs
+++ b/package/ego-browser/src/browser-runtime.test.mjs
@@ -5,6 +5,7 @@ import {
browserCdp,
drainBrowserEvents,
drainPageEvents,
+ prepareFileChooser,
} from "../dist/src/browser-runtime.js";
// Gap A: ensureSession() calls the raw listTabs binding to attach a session.
@@ -170,3 +171,77 @@ test("page event drains exclude unscoped browser events", async () => {
else globalThis.ego = previous;
}
});
+
+test("file chooser interception suppresses the native picker and returns its input", async () => {
+ const previous = globalThis.ego;
+ const calls = [];
+ const runtime = {
+ sendCDPMessage(payload) {
+ const request = JSON.parse(payload);
+ calls.push(request);
+ const result =
+ request.method === "Target.attachToTarget"
+ ? { sessionId: "session-upload" }
+ : {};
+ queueMicrotask(() => {
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result }));
+ });
+ },
+ emit(event) {
+ runtime.onCDPMessage(JSON.stringify(event));
+ },
+ };
+ globalThis.ego = runtime;
+
+ try {
+ const attached = await browserCdp("Target.attachToTarget", {
+ targetId: "target-upload",
+ flatten: true,
+ });
+ const sessionId = attached.result.sessionId;
+ const interception = prepareFileChooser(sessionId, {
+ timeoutMs: 1_000,
+ cancel: true,
+ });
+ await interception.ready;
+
+ runtime.emit({
+ sessionId,
+ method: "Page.fileChooserOpened",
+ params: {
+ backendNodeId: 42,
+ frameId: "frame-upload",
+ mode: "selectMultiple",
+ },
+ });
+ assert.equal((await interception.event).backendNodeId, 42);
+ await interception.dispose();
+
+ assert(
+ calls.some(
+ (call) =>
+ call.method === "Page.setInterceptFileChooserDialog" &&
+ call.params.enabled === true,
+ ),
+ );
+ assert(
+ calls.some(
+ (call) =>
+ call.method === "DOM.setFileInputFiles" &&
+ call.params.backendNodeId === 42 &&
+ call.params.files.length === 0,
+ ),
+ "the safety interceptor cancels the chooser with an empty file list",
+ );
+ assert(
+ calls.some(
+ (call) =>
+ call.method === "Page.setInterceptFileChooserDialog" &&
+ call.params.enabled === false,
+ ),
+ );
+ } finally {
+ if (previous === undefined) delete globalThis.ego;
+ else globalThis.ego = previous;
+ }
+});
diff --git a/package/ego-browser/src/browser-runtime.ts b/package/ego-browser/src/browser-runtime.ts
index d7b64d0..ac5cb18 100644
--- a/package/ego-browser/src/browser-runtime.ts
+++ b/package/ego-browser/src/browser-runtime.ts
@@ -17,11 +17,23 @@ const targetStates = new Map();
const sessionTargets = new Map();
let defaultTargetId = null;
+export type FileChooserOpenedEvent = {
+ backendNodeId: number;
+ frameId?: string;
+ mode?: "selectSingle" | "selectMultiple";
+};
+
+export type FileChooserInterception = {
+ ready: Promise<void>;
+ event: Promise<FileChooserOpenedEvent>;
+ peek(): FileChooserOpenedEvent | undefined;
+ dispose(reason?: Error): Promise<void>;
+};
+
function targetState(targetId) {
let target = targetStates.get(targetId);
if (!target) {
target = {
- targetId,
sessionId: null,
sessionAt: 0,
sessionInflight: null,
@@ -29,6 +41,7 @@ function targetState(targetId) {
pageEventsEnabled: false,
networkDomainEnabled: false,
pendingDialog: null,
+ fileChooserInterception: null,
};
targetStates.set(targetId, target);
}
@@ -40,7 +53,7 @@ function registerSession(targetId, sessionId) {
if (target.sessionId === sessionId) {
target.sessionAt = Date.now();
sessionTargets.set(sessionId, targetId);
- return target;
+ return;
}
if (target.sessionId && target.sessionId !== sessionId) {
sessionTargets.delete(target.sessionId);
@@ -51,12 +64,15 @@ function registerSession(targetId, sessionId) {
target.networkDomainEnabled = false;
target.pendingDialog = null;
sessionTargets.set(sessionId, targetId);
- return target;
}
function clearTargetSession(targetId, { remove = false } = {}) {
const target = targetStates.get(targetId);
if (!target) return;
+ rejectFileChooserInterception(
+ target,
+ new Error("file chooser session was detached"),
+ );
if (target.sessionId) {
sessionTargets.delete(target.sessionId);
}
@@ -72,6 +88,7 @@ function clearTargetSession(targetId, { remove = false } = {}) {
target.pageEventsEnabled = false;
target.networkDomainEnabled = false;
target.pendingDialog = null;
+ target.fileChooserInterception = null;
}
function capEvents(events) {
@@ -297,6 +314,104 @@ export function isNetworkDomainEnabled(sessionId) {
: false;
}
+/**
+ * Suppress the operating-system file picker and observe the next chooser in
+ * one Page session. The caller owns the short-lived interception and must
+ * dispose it after setting files or completing an input action.
+ */
+export function prepareFileChooser(
+ sessionId: string,
+ { timeoutMs, cancel }: { timeoutMs: number; cancel: boolean },
+): FileChooserInterception {
+ const targetId = sessionTargets.get(sessionId);
+ const target = targetId ? targetStates.get(targetId) : undefined;
+ if (!target) {
+ throw new Error("cannot intercept a file chooser without a Page session");
+ }
+ if (target.fileChooserInterception) {
+ throw new Error("this Page is already waiting for a file chooser");
+ }
+
+ let observed: FileChooserOpenedEvent | undefined;
+ let resolveEvent!: (event: FileChooserOpenedEvent) => void;
+ let rejectEvent!: (error: Error) => void;
+ const event = new Promise<FileChooserOpenedEvent>((resolve, reject) => {
+ resolveEvent = resolve;
+ rejectEvent = reject;
+ });
+ // A safety interceptor normally consumes peek() instead of awaiting event.
+ // Attach a rejection observer so disposal never creates an unhandled promise.
+ void event.catch(() => {});
+
+ const interception: any = {
+ cancelPromise: undefined,
+ event,
+ reject: rejectEvent,
+ resolve(value: FileChooserOpenedEvent) {
+ if (observed) return;
+ observed = value;
+ clearTimeout(interception.timer);
+ resolveEvent(value);
+ if (cancel) {
+ // An empty file list completes the intercepted chooser without opening
+ // the native picker or changing the input's current selection.
+ interception.cancelPromise = rawCdp(
+ "DOM.setFileInputFiles",
+ { files: [], backendNodeId: value.backendNodeId },
+ sessionId,
+ ).catch(() => {});
+ }
+ },
+ peek() {
+ return observed;
+ },
+ async dispose(reason?: Error) {
+ if (target.fileChooserInterception !== interception) return;
+ target.fileChooserInterception = null;
+ clearTimeout(interception.timer);
+ if (!observed && reason) rejectEvent(reason);
+ await interception.ready.catch(() => {});
+ await interception.cancelPromise;
+ await rawCdp(
+ "Page.setInterceptFileChooserDialog",
+ { enabled: false },
+ sessionId,
+ ).catch(() => {});
+ },
+ };
+ target.fileChooserInterception = interception;
+ interception.ready = rawCdp(
+ "Page.setInterceptFileChooserDialog",
+ { enabled: true },
+ sessionId,
+ )
+ .then(() => {
+ interception.timer = setTimeout(() => {
+ const error: any = new Error(
+ `page.waitForFileChooser timed out after ${timeoutMs}ms`,
+ );
+ error.code = "EGO_FILE_CHOOSER_TIMEOUT";
+ if (target.fileChooserInterception === interception) {
+ target.fileChooserInterception = null;
+ rejectEvent(error);
+ void rawCdp(
+ "Page.setInterceptFileChooserDialog",
+ { enabled: false },
+ sessionId,
+ ).catch(() => {});
+ }
+ }, timeoutMs);
+ })
+ .catch((error) => {
+ if (target.fileChooserInterception === interception) {
+ target.fileChooserInterception = null;
+ }
+ rejectEvent(error);
+ throw error;
+ });
+ return interception;
+}
+
async function enablePageEvents(sessionId) {
const targetId = sessionId ? sessionTargets.get(sessionId) : undefined;
const target = targetId ? targetStates.get(targetId) : undefined;
@@ -372,12 +487,22 @@ function handleMessage(message) {
if (target) target.pendingDialog = data.params || {};
} else if (data.method === "Page.javascriptDialogClosed") {
if (target) target.pendingDialog = null;
+ } else if (data.method === "Page.fileChooserOpened") {
+ target?.fileChooserInterception?.resolve(data.params || {});
}
const events = target ? target.events : browserEvents;
events.push(data);
capEvents(events);
}
+function rejectFileChooserInterception(target, error: Error) {
+ const interception = target.fileChooserInterception;
+ if (!interception) return;
+ target.fileChooserInterception = null;
+ clearTimeout(interception.timer);
+ interception.reject(error);
+}
+
export function browserSnapshotRefsToRefMap(refMap, refs = []) {
refMap.clear();
for (const ref of refs) {
diff --git a/package/ego-browser/src/driver/page-actions.ts b/package/ego-browser/src/driver/page-actions.ts
index 8b2d85f..49e3448 100644
--- a/package/ego-browser/src/driver/page-actions.ts
+++ b/package/ego-browser/src/driver/page-actions.ts
@@ -71,14 +71,7 @@ export async function clickInPage(
): Promise<void> {
assertPageSelector(selector);
const button = options.button ?? "left";
- if (!(["left", "middle", "right"] as string[]).includes(button)) {
- throw new TypeError(`page.click received unsupported button: ${button}`);
- }
const clickCount = options.clickCount ?? 1;
- if (!Number.isInteger(clickCount) || clickCount < 1) {
- throw new TypeError("page.click clickCount must be a positive integer");
- }
- assertDelay(options.delay, "page.click");
const target = await resolveElementObjectId(
cdpAdapter(services),
sessionId,
@@ -150,9 +143,6 @@ export async function fillInPage(
throw new TypeError("page.fill value must be a string");
}
const clearFirst = options.clearFirst ?? true;
- if (typeof clearFirst !== "boolean") {
- throw new TypeError("page.fill clearFirst must be a boolean");
- }
const resolved = await resolveElementObjectId(
cdpAdapter(services),
@@ -335,7 +325,7 @@ export async function dragAndDropInPage(
target.objectId,
options.targetPosition,
);
- const button = assertMouseButton(options.button ?? "left");
+ const button = options.button ?? "left";
const buttons = pressedButtons(button);
await dispatchMouseEvent(services, source.sessionId, {
type: "mouseMoved",
@@ -393,14 +383,8 @@ export async function clickPointInPage(
baseButtons = 0,
): Promise<void> {
assertPoint(x, y, "page.mouse.click");
- const button = assertMouseButton(options.button ?? "left");
+ const button = options.button ?? "left";
const clickCount = options.clickCount ?? 1;
- if (!Number.isInteger(clickCount) || clickCount < 1) {
- throw new TypeError(
- "page.mouse.click clickCount must be a positive integer",
- );
- }
- assertDelay(options.delay, "page.mouse.click");
const buttons = pressedButtons(button);
await dispatchMouseEvent(services, sessionId, {
type: "mouseMoved",
@@ -447,9 +431,6 @@ export async function moveMouseInPage(
): Promise<void> {
assertPoint(x, y, "page.mouse.move");
const steps = options.steps ?? 1;
- if (!Number.isInteger(steps) || steps < 1) {
- throw new TypeError("page.mouse.move steps must be a positive integer");
- }
for (let step = 1; step <= steps; step += 1) {
await dispatchMouseEvent(services, sessionId, {
type: "mouseMoved",
@@ -473,11 +454,8 @@ export async function mouseButtonInPage(
modifiers = 0,
): Promise<MouseButton> {
assertPoint(x, y, `page.mouse.${type === "mousePressed" ? "down" : "up"}`);
- const button = assertMouseButton(options.button ?? "left");
+ const button = options.button ?? "left";
const clickCount = options.clickCount ?? 1;
- if (!Number.isInteger(clickCount) || clickCount < 1) {
- throw new TypeError("page.mouse clickCount must be a positive integer");
- }
await dispatchMouseEvent(services, sessionId, {
type,
x,
@@ -629,19 +607,6 @@ function assertPoint(x: number, y: number, operation: string): void {
}
}
-function assertDelay(value: unknown, operation: string): void {
- if (value !== undefined && (!Number.isFinite(value) || Number(value) < 0)) {
- throw new TypeError(`${operation} delay must be a non-negative number`);
- }
-}
-
-function assertMouseButton(button: string): MouseButton {
- if (!(<string[]>["left", "middle", "right"]).includes(button)) {
- throw new TypeError(`unsupported mouse button: ${button}`);
- }
- return button as MouseButton;
-}
-
export function mouseButtonMask(button: MouseButton): number {
return pressedButtons(button);
}
diff --git a/package/ego-browser/src/driver/page-input.ts b/package/ego-browser/src/driver/page-input.ts
index 6c1ea69..3f1d371 100644
--- a/package/ego-browser/src/driver/page-input.ts
+++ b/package/ego-browser/src/driver/page-input.ts
@@ -6,6 +6,20 @@ import { type KeyboardServices } from "./keyboard.js";
type PageInputServices = KeyboardServices;
+const RESOLVE_FILE_INPUT_SOURCE = `function resolveFileInputForUpload() {
+ const isFileInput = (element) =>
+ element instanceof HTMLInputElement && element.type === "file";
+ if (isFileInput(this)) return this;
+ if (this instanceof HTMLLabelElement && isFileInput(this.control)) {
+ return this.control;
+ }
+ const descendant = this.querySelector?.('input[type="file"]');
+ if (isFileInput(descendant)) return descendant;
+ throw new TypeError(
+ "page.setInputFiles requires a file input, its label, or a container with a file input",
+ );
+}`;
+
/** Set one or more local files on an input in one explicit Page session. */
export async function setInputFilesInPage(
services: PageInputServices,
@@ -14,33 +28,87 @@ export async function setInputFilesInPage(
selector: string,
path: string | string[],
): Promise<void> {
- const files = Array.isArray(path) ? path : [path];
- if (
- files.length === 0 ||
- files.some(
- (file) =>
- typeof file !== "string" || file.length === 0 || !isAbsolute(file),
- )
- ) {
- throw new TypeError("page.setInputFiles requires absolute file paths");
- }
+ const files = normalizeFilePaths(path, "page.setInputFiles");
const resolved = await resolveElementObjectId(
cdpAdapter(services),
sessionId,
refMap,
selector,
);
+ let inputObjectId: string | undefined;
try {
- await services.cdp(
- "DOM.setFileInputFiles",
- { files, objectId: resolved.objectId },
+ const input = await services.cdp(
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: RESOLVE_FILE_INPUT_SOURCE,
+ objectId: resolved.objectId,
+ returnByValue: false,
+ awaitPromise: false,
+ },
+ resolved.sessionId,
+ );
+ if (input?.exceptionDetails) {
+ throw new TypeError(
+ input.exceptionDetails.exception?.description ||
+ input.exceptionDetails.text ||
+ "page.setInputFiles could not resolve a file input",
+ );
+ }
+ inputObjectId = input?.result?.objectId;
+ if (!inputObjectId) {
+ throw new TypeError("page.setInputFiles could not resolve a file input");
+ }
+ await setFilesOnBackendNode(
+ services,
resolved.sessionId,
+ files,
+ undefined,
+ inputObjectId,
);
} finally {
+ if (inputObjectId && inputObjectId !== resolved.objectId) {
+ await releaseObject(services, resolved.sessionId, inputObjectId);
+ }
await releaseObject(services, resolved.sessionId, resolved.objectId);
}
}
+/** Validate local file paths without touching the operating-system chooser. */
+export function normalizeFilePaths(
+ path: string | string[],
+ methodName: string,
+): string[] {
+ const files = Array.isArray(path) ? path : [path];
+ if (
+ files.some(
+ (file) =>
+ typeof file !== "string" || file.length === 0 || !isAbsolute(file),
+ )
+ ) {
+ throw new TypeError(`${methodName} requires absolute file paths`);
+ }
+ return files;
+}
+
+/** Set files using the file input identity supplied by a chooser event. */
+export async function setFilesOnBackendNode(
+ services: PageInputServices,
+ sessionId: string,
+ files: string[],
+ backendNodeId?: number,
+ objectId?: string,
+): Promise<void> {
+ await services.cdp(
+ "DOM.setFileInputFiles",
+ {
+ files,
+ ...(backendNodeId === undefined ? {} : { backendNodeId }),
+ ...(objectId === undefined ? {} : { objectId }),
+ },
+ sessionId,
+ );
+}
+
function cdpAdapter(services: PageInputServices) {
return {
sendRaw(method, params, sessionId) {
diff --git a/package/ego-browser/src/driver/page-keyboard.ts b/package/ego-browser/src/driver/page-keyboard.ts
index 4b65e41..81a6c49 100644
--- a/package/ego-browser/src/driver/page-keyboard.ts
+++ b/package/ego-browser/src/driver/page-keyboard.ts
@@ -88,7 +88,6 @@ export class PageKeyboardController {
chord: string,
options: PageKeyboardPressOptions = {},
): Promise<unknown> {
- assertDelay(options.delay, "page.keyboard.press");
const tokens = splitChord(chord);
return this.#runObserved(async (sessionId) => {
const pressed: string[] = [];
@@ -128,7 +127,6 @@ export class PageKeyboardController {
options: PageKeyboardTypeOptions = {},
): Promise<unknown> {
assertText(text, "page.keyboard.type");
- assertDelay(options.delay, "page.keyboard.type");
return this.#run(async (sessionId) => {
for (const character of text) {
if (keyboardLayout.has(character)) {
@@ -277,12 +275,6 @@ function assertText(
}
}
-function assertDelay(value: unknown, operation: string): void {
- if (value !== undefined && (!Number.isFinite(value) || Number(value) < 0)) {
- throw new TypeError(`${operation} delay must be a non-negative number`);
- }
-}
-
function buildKeyboardLayout(): Map<string, KeyDefinition> {
const entries: Record<string, LayoutEntry> = {
Escape: { keyCode: 27, key: "Escape" },
diff --git a/package/ego-browser/src/driver/page-waits.ts b/package/ego-browser/src/driver/page-waits.ts
index 878e6e5..f4a7e99 100644
--- a/package/ego-browser/src/driver/page-waits.ts
+++ b/package/ego-browser/src/driver/page-waits.ts
@@ -44,13 +44,7 @@ export async function waitForSelectorInPage(
);
}
const timeoutMs = options.timeout ?? 10_000;
- assertPositiveMilliseconds(timeoutMs);
const state = options.state ?? "visible";
- if (!["attached", "detached", "visible", "hidden"].includes(state)) {
- throw new TypeError(
- "page.waitForSelector state must be one of attached, detached, visible, or hidden",
- );
- }
const deadline = services.now() + timeoutMs;
while (services.now() <= deadline) {
@@ -118,13 +112,11 @@ export async function waitForLoadStateInPage(
);
}
const timeoutMs = options.timeout ?? 10_000;
- assertPositiveMilliseconds(timeoutMs);
if (state === "load") {
await waitForDocumentLoad(services, sessionId, timeoutMs);
return;
}
const idleMs = options.idleMs ?? 500;
- assertPositiveMilliseconds(idleMs, "idleMs");
await waitForNetworkIdle(services, sessionId, timeoutMs, idleMs);
}
@@ -203,9 +195,3 @@ function cdpAdapter(services: PageWaitServices) {
},
};
}
-
-function assertPositiveMilliseconds(value: number, name = "timeout"): void {
- if (!Number.isFinite(value) || value <= 0) {
- throw new TypeError(`${name} must be a positive number of milliseconds`);
- }
-}
diff --git a/package/ego-browser/src/index.ts b/package/ego-browser/src/index.ts
index 989f660..bf1631b 100644
--- a/package/ego-browser/src/index.ts
+++ b/package/ego-browser/src/index.ts
@@ -102,13 +102,16 @@ export function installEgoSdk(
target.ego.helpers = installed;
target.ego.learnings = {};
if (!(target.ego as Record<symbol, unknown>)[EGO_WRAPPED]) {
+ const taskSelection: { spaceId?: unknown } = {};
wrapCreateTab(target.ego);
- wrapInvalidating(target.ego, [
- "useTaskSpace",
- "closeTaskSpace",
- "createTaskSpace",
- "claimTaskSpace",
- ]);
+ wrapUseTaskSpace(target.ego, taskSelection);
+ wrapInvalidating(
+ target.ego,
+ ["closeTaskSpace", "createTaskSpace", "claimTaskSpace"],
+ () => {
+ taskSelection.spaceId = undefined;
+ },
+ );
Object.defineProperty(target.ego, EGO_WRAPPED, {
value: true,
enumerable: false,
@@ -144,11 +147,16 @@ function isDirectCli() {
);
}
-function wrapInvalidating(ego: EgoRuntime, methodNames: string[]) {
+function wrapInvalidating(
+ ego: EgoRuntime,
+ methodNames: string[],
+ resetSelection: () => void = () => {},
+) {
for (const name of methodNames) {
const original = ego[name];
if (typeof original !== "function") continue;
const after = () => {
+ resetSelection();
invalidateSession();
clearPreferredTarget();
};
@@ -166,6 +174,32 @@ function wrapInvalidating(ego: EgoRuntime, methodNames: string[]) {
}
}
+function wrapUseTaskSpace(ego: EgoRuntime, selection: { spaceId?: unknown }) {
+ // File chooser waits and other event subscriptions span multiple Page calls.
+ // Re-selecting the same space must preserve their CDP session; changing the
+ // space still invalidates every session because native routing is global.
+ const original = ego.useTaskSpace;
+ if (typeof original !== "function") return;
+ const after = (spaceId: unknown, value: unknown) => {
+ if (value && typeof value === "object" && Object.hasOwn(value, "error")) {
+ return value;
+ }
+ if (selection.spaceId !== spaceId) {
+ invalidateSession();
+ clearPreferredTarget();
+ selection.spaceId = spaceId;
+ }
+ return value;
+ };
+ ego.useTaskSpace = function (...args: unknown[]) {
+ const result = original.apply(this, args);
+ if (result && typeof result.then === "function") {
+ return result.then((value) => after(args[0], value));
+ }
+ return after(args[0], result);
+ };
+}
+
function wrapCreateTab(ego: EgoRuntime) {
const original = ego.createTab;
if (typeof original !== "function") return;
diff --git a/package/ego-browser/src/page-ledger.test.mjs b/package/ego-browser/src/page-ledger.test.mjs
index c5d6a5f..b87a660 100644
--- a/package/ego-browser/src/page-ledger.test.mjs
+++ b/package/ego-browser/src/page-ledger.test.mjs
@@ -65,7 +65,7 @@ test("writes use a complete atomic ledger document", async () => {
usedLabels: ["p1"],
releasedLabels: [],
initialized: true,
- handoffBaseline: null,
+ userControlPending: false,
unmanagedTargets: {},
pages: {
p1: {
@@ -120,6 +120,64 @@ test("old ledger metadata is accepted and removed on the next write", async () =
});
});
+test("old handoff baselines migrate to a pending user-control boundary", async () => {
+ await withTempLedger(async (rootDir) => {
+ const path = join(rootDir, "space-13.json");
+ await writeFile(
+ path,
+ JSON.stringify({
+ spaceId: 13,
+ nextLabel: 2,
+ usedLabels: ["p1"],
+ releasedLabels: [],
+ initialized: true,
+ handoffBaseline: ["target-agent"],
+ unmanagedTargets: {},
+ pages: {
+ p1: { targetId: "target-agent", openedBy: "agent" },
+ },
+ }),
+ );
+ const store = new PageLedgerStore({ rootDir });
+
+ const restored = await store.read(13);
+ assert.equal(restored.userControlPending, true);
+
+ await store.reconcile(13, ["target-agent", "target-user"], {
+ autoAdoptNew: true,
+ });
+ const persisted = JSON.parse(await readFile(path, "utf8"));
+ assert.equal(persisted.userControlPending, false);
+ assert.equal(Object.hasOwn(persisted, "handoffBaseline"), false);
+ assert.equal(persisted.unmanagedTargets["target-user"], "unknown");
+ });
+});
+
+test("legacy user origins are read conservatively as unknown", async () => {
+ await withTempLedger(async (rootDir) => {
+ const path = join(rootDir, "space-14.json");
+ await writeFile(
+ path,
+ JSON.stringify({
+ spaceId: 14,
+ nextLabel: 2,
+ usedLabels: ["p1"],
+ releasedLabels: [],
+ initialized: true,
+ unmanagedTargets: { "target-unmanaged": "user" },
+ pages: {
+ p1: { targetId: "target-managed", openedBy: "user" },
+ },
+ }),
+ );
+
+ const restored = await new PageLedgerStore({ rootDir }).read(14);
+
+ assert.equal(restored.pages.p1.openedBy, "unknown");
+ assert.equal(restored.unmanagedTargets["target-unmanaged"], "unknown");
+ });
+});
+
test("release removes a managed page without making its label reusable", async () => {
await withTempLedger(async (rootDir) => {
const store = new PageLedgerStore({ rootDir });
@@ -235,7 +293,7 @@ test("tabs opened during handoff remain unknown after takeover", async () => {
await withTempLedger(async (rootDir) => {
const firstRound = new PageLedgerStore({ rootDir });
await firstRound.addPage(8, "target-agent");
- await firstRound.beginUserControl(8, ["target-agent"]);
+ await firstRound.beginUserControl(8);
const secondRound = new PageLedgerStore({ rootDir });
const afterTakeover = await secondRound.reconcile(
@@ -244,7 +302,7 @@ test("tabs opened during handoff remain unknown after takeover", async () => {
{ autoAdoptNew: true },
);
- assert.equal(afterTakeover.handoffBaseline, null);
+ assert.equal(afterTakeover.userControlPending, false);
assert.equal(afterTakeover.unmanagedTargets["target-user"], "unknown");
assert.deepEqual(afterTakeover.pages, {
p1: { targetId: "target-agent", openedBy: "agent" },
diff --git a/package/ego-browser/src/page-ledger.ts b/package/ego-browser/src/page-ledger.ts
index 61b0463..06473a4 100644
--- a/package/ego-browser/src/page-ledger.ts
+++ b/package/ego-browser/src/page-ledger.ts
@@ -3,7 +3,7 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
-export type PageOrigin = "agent" | "user" | "unknown";
+export type PageOrigin = "agent" | "unknown";
export type PageLedgerEntry = {
targetId: string;
@@ -20,7 +20,7 @@ export type PageLedger = {
usedLabels: string[];
releasedLabels: string[];
initialized: boolean;
- handoffBaseline: string[] | null;
+ userControlPending: boolean;
unmanagedTargets: Record<string, PageOrigin>;
pages: Record<string, PageLedgerEntry>;
};
@@ -164,7 +164,7 @@ export class PageLedgerStore {
openedBy: PageOrigin = "unknown",
): Promise<void> {
assertTargetId(targetId);
- if (!["agent", "user", "unknown"].includes(openedBy)) {
+ if (!["agent", "unknown"].includes(openedBy)) {
throw new TypeError(`invalid unmanaged page origin: ${openedBy}`);
}
await this.#update(spaceId, (ledger) => {
@@ -179,25 +179,17 @@ export class PageLedgerStore {
});
}
- /**
- * Persist the tab set visible immediately before control is handed to the
- * user. A later process can then preserve newly observed tabs as unknown.
- */
- async beginUserControl(
- spaceId: number,
- liveTargetIds: Iterable<string>,
- ): Promise<void> {
- const targetIds = [...new Set(liveTargetIds)];
- targetIds.forEach(assertTargetId);
+ /** Mark the next reconciliation as crossing a user-control boundary. */
+ async beginUserControl(spaceId: number): Promise<void> {
await this.#update(spaceId, (ledger) => {
- ledger.handoffBaseline = targetIds;
+ ledger.userControlPending = true;
});
}
/** Roll back a boundary marker when the native handoff itself fails. */
async cancelUserControl(spaceId: number): Promise<void> {
await this.#update(spaceId, (ledger) => {
- ledger.handoffBaseline = null;
+ ledger.userControlPending = false;
});
}
@@ -223,7 +215,7 @@ export class PageLedgerStore {
);
const needsInitialization = !current.initialized;
const protectsUserTabs =
- options.afterUserControl || current.handoffBaseline !== null;
+ options.afterUserControl || current.userControlPending;
const shouldAdopt =
current.initialized &&
options.autoAdoptNew &&
@@ -263,14 +255,14 @@ export class PageLedgerStore {
ledger.unmanagedTargets[targetId] = "unknown";
}
ledger.initialized = true;
- ledger.handoffBaseline = null;
+ ledger.userControlPending = false;
return;
}
if (protectsUserTabs) {
for (const targetId of untracked) {
ledger.unmanagedTargets[targetId] = "unknown";
}
- ledger.handoffBaseline = null;
+ ledger.userControlPending = false;
return;
}
if (!options.autoAdoptNew) return;
@@ -344,7 +336,7 @@ function emptyLedger(spaceId: number): PageLedger {
usedLabels: [],
releasedLabels: [],
initialized: false,
- handoffBaseline: null,
+ userControlPending: false,
unmanagedTargets: {},
pages: {},
};
@@ -369,13 +361,16 @@ function validateLedger(
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error(`invalid page ledger ${path}: expected an object`);
}
- const stored = value as PageLedger;
+ const stored = value as PageLedger & { handoffBaseline?: unknown };
// Defaults keep ledgers written by earlier runtimes readable. They start
// uninitialized so the first new runtime observes a safe control baseline
// instead of silently adopting pre-existing user tabs.
const releasedLabels = stored.releasedLabels ?? [];
const initialized = stored.initialized ?? false;
- const handoffBaseline = stored.handoffBaseline ?? null;
+ const legacyHandoffBaseline = stored.handoffBaseline;
+ const userControlPending =
+ stored.userControlPending ??
+ (legacyHandoffBaseline !== undefined && legacyHandoffBaseline !== null);
const unmanagedTargets = stored.unmanagedTargets ?? {};
if (
stored.spaceId !== expectedSpaceId ||
@@ -391,9 +386,11 @@ function validateLedger(
Object.hasOwn(stored.pages || {}, label),
) ||
typeof initialized !== "boolean" ||
- (handoffBaseline !== null &&
- (!Array.isArray(handoffBaseline) ||
- handoffBaseline.some(
+ typeof userControlPending !== "boolean" ||
+ (legacyHandoffBaseline !== undefined &&
+ legacyHandoffBaseline !== null &&
+ (!Array.isArray(legacyHandoffBaseline) ||
+ legacyHandoffBaseline.some(
(targetId) => typeof targetId !== "string" || targetId.length === 0,
))) ||
!unmanagedTargets ||
@@ -425,21 +422,33 @@ function validateLedger(
`invalid page ledger ${path}: target ${page.targetId} is both managed and unmanaged`,
);
}
- pages[label] = { targetId: page.targetId, openedBy: page.openedBy };
+ pages[label] = {
+ targetId: page.targetId,
+ openedBy: normalizePageOrigin(page.openedBy),
+ };
}
+ const normalizedUnmanagedTargets = Object.fromEntries(
+ Object.entries(unmanagedTargets).map(([targetId, openedBy]) => [
+ targetId,
+ normalizePageOrigin(openedBy),
+ ]),
+ );
return {
spaceId: stored.spaceId,
nextLabel: stored.nextLabel,
usedLabels: [...stored.usedLabels],
releasedLabels: [...releasedLabels],
initialized,
- handoffBaseline:
- handoffBaseline === null ? null : [...new Set(handoffBaseline)],
- unmanagedTargets: { ...unmanagedTargets },
+ userControlPending,
+ unmanagedTargets: normalizedUnmanagedTargets,
pages,
};
}
+function normalizePageOrigin(value: unknown): PageOrigin {
+ return value === "agent" ? "agent" : "unknown";
+}
+
function cloneLedger(ledger: PageLedger): PageLedger {
return structuredClone(ledger);
}
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index c488a5c..3f32fb4 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -28,6 +28,9 @@ function createFixture(rootDir) {
let selectedSpace = null;
let activeTarget = null;
let popupOnNextClick = null;
+ let fileChooserOnNextClick = null;
+ let activeFileChooserWaiter = null;
+ let systemFileChooserOpened = false;
let timeoutNextMouseDispatch = false;
let rejectNextClickPoint = false;
let navigateOnNextClickUrl = null;
@@ -36,6 +39,8 @@ function createFixture(rootDir) {
let nowMs = 1_000;
const pageEvents = new Map();
const networkSessions = new Set();
+ const sessionOverrides = new Map();
+ const sessionTargets = new Map();
function openPendingPopup() {
if (!popupOnNextClick) return;
@@ -51,7 +56,12 @@ function createFixture(rootDir) {
async function ensureTargetSession(targetId) {
assert(tabs.has(targetId), `unknown target ${targetId}`);
calls.push(["ensureSession", targetId]);
- return `session:${targetId}`;
+ const sessionId = sessionOverrides.get(targetId) || `session:${targetId}`;
+ sessionTargets.set(sessionId, targetId);
+ return sessionId;
+ }
+ function targetForSession(sessionId) {
+ return sessionTargets.get(sessionId) || sessionId?.slice("session:".length);
}
const gate = new NativeOperationGate({
async selectSpace(spaceId) {
@@ -83,27 +93,14 @@ function createFixture(rootDir) {
if (timeoutMs !== undefined) call.push(timeoutMs);
calls.push(call);
if (method === "Page.navigate") {
- const targetId = sessionId.slice("session:".length);
+ const targetId = targetForSession(sessionId);
tabs.get(targetId).url = params.url;
tabs.get(targetId).title = params.url;
return { frameId: "frame-1" };
}
if (method === "Runtime.evaluate") {
- const targetId = sessionId?.slice("session:".length);
+ const targetId = targetForSession(sessionId);
const tab = tabs.get(targetId);
- if (params.expression.includes("__egoBrowserActionProbes")) {
- return {
- result: {
- type: "object",
- value: {
- url: tab.url,
- documentToken: `document:${tab.url}`,
- controlHash: "controls",
- mutations: 0,
- },
- },
- };
- }
if (params.expression === "globalThis") {
return {
result: {
@@ -161,6 +158,15 @@ function createFixture(rootDir) {
return { result: { type: "string", value: "complete" } };
}
if (method === "Runtime.callFunctionOn") {
+ if (params.functionDeclaration.includes("resolveFileInputForUpload")) {
+ const targetId = targetForSession(sessionId);
+ return {
+ result: {
+ type: "object",
+ objectId: `file-input:${targetId}`,
+ },
+ };
+ }
if (params.functionDeclaration.includes("fillPreparation")) {
return { result: { type: "string", value: "needsinput" } };
}
@@ -230,7 +236,7 @@ function createFixture(rootDir) {
};
}
if (method === "DOM.resolveNode") {
- const targetId = sessionId.slice("session:".length);
+ const targetId = targetForSession(sessionId);
return {
object: {
type: "object",
@@ -259,8 +265,16 @@ function createFixture(rootDir) {
throw new Error("CDP request timed out: Input.dispatchMouseEvent");
}
if (params.type === "mouseReleased") {
+ if (fileChooserOnNextClick) {
+ if (activeFileChooserWaiter) {
+ activeFileChooserWaiter.emit(fileChooserOnNextClick);
+ } else {
+ systemFileChooserOpened = true;
+ }
+ fileChooserOnNextClick = null;
+ }
if (navigateOnNextClickUrl) {
- const targetId = sessionId.slice("session:".length);
+ const targetId = targetForSession(sessionId);
tabs.get(targetId).url = navigateOnNextClickUrl;
tabs.get(targetId).title = navigateOnNextClickUrl;
navigateOnNextClickUrl = null;
@@ -304,6 +318,34 @@ function createFixture(rootDir) {
pendingDialog() {
return null;
},
+ prepareFileChooser(sessionId, { timeoutMs, cancel }) {
+ calls.push(["prepareFileChooser", sessionId, { timeoutMs, cancel }]);
+ let observed;
+ let resolveEvent;
+ let rejectEvent;
+ const event = new Promise((resolve, reject) => {
+ resolveEvent = resolve;
+ rejectEvent = reject;
+ });
+ const waiter = {
+ ready: Promise.resolve(),
+ event,
+ peek: () => observed,
+ emit(value) {
+ observed = value;
+ resolveEvent(value);
+ },
+ async dispose(reason) {
+ calls.push(["disposeFileChooser", sessionId, reason?.message]);
+ if (activeFileChooserWaiter === waiter) {
+ activeFileChooserWaiter = null;
+ }
+ if (!observed && reason) rejectEvent(reason);
+ },
+ };
+ activeFileChooserWaiter = waiter;
+ return waiter;
+ },
drainEvents(sessionId) {
const events = pageEvents.get(sessionId) || [];
pageEvents.set(sessionId, []);
@@ -338,6 +380,14 @@ function createFixture(rootDir) {
openPopupOnNextClick(url) {
popupOnNextClick = url;
},
+ openFileChooserOnNextClick(options = {}) {
+ fileChooserOnNextClick = {
+ backendNodeId: options.backendNodeId ?? 71,
+ frameId: options.frameId ?? "frame-1",
+ mode: options.mode ?? "selectSingle",
+ };
+ },
+ systemFileChooserOpened: () => systemFileChooserOpened,
timeoutNextMouseDispatch() {
timeoutNextMouseDispatch = true;
},
@@ -351,6 +401,9 @@ function createFixture(rootDir) {
elementPresent = present;
elementVisible = visible;
},
+ setSession(targetId, sessionId) {
+ sessionOverrides.set(targetId, sessionId);
+ },
emitPageEvent(targetId, method, params = {}) {
const sessionId = `session:${targetId}`;
const events = pageEvents.get(sessionId) || [];
@@ -364,7 +417,7 @@ function taskForRound(fixture, roundId, overrides = {}) {
return createTaskSpaceHandle(
{ id: 7, name: "research", ownership: "agent" },
{
- ledger: new PageLedgerStore({ rootDir: fixture.rootDir, roundId }),
+ ledger: new PageLedgerStore({ rootDir: fixture.rootDir }),
...fixture.services,
...overrides,
},
@@ -450,10 +503,7 @@ test("v2 methods reject option fields that are absent from the public schema", a
test("TaskSpace uses spaceId and owns handoff, finish, and close", async () => {
await withFixture(async (fixture) => {
const lifecycleCalls = [];
- const ledger = new PageLedgerStore({
- rootDir: fixture.rootDir,
- roundId: "lifecycle",
- });
+ const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });
const services = {
ledger,
async handOffTaskSpace() {
@@ -538,7 +588,7 @@ test("failed native handoff removes the pending user-control boundary", async ()
await task.openPage("https://example.test/agent");
await assert.rejects(() => task.handOff(), /native handoff failed/);
- assert.equal((await ledger.read(7)).handoffBaseline, null);
+ assert.equal((await ledger.read(7)).userControlPending, false);
});
});
@@ -582,13 +632,7 @@ test("a page label restores in a new round and goto reuses its target", async ()
fixture.tabs.get("target-1").url,
"https://example.test/second",
);
- assert.deepEqual(receipt, {
- navigation: {
- from: "https://example.test/first",
- to: "https://example.test/second",
- },
- domChanged: true,
- });
+ assert.deepEqual(receipt, {});
assert.match(
await restored.snapshot(),
/\[p1 .*space "research"\(7\).*\]\nsnapshot:https:\/\/example\.test\/second/,
@@ -663,7 +707,7 @@ test("snapshot activates the addressed page, not whichever tab was current", asy
});
});
-test("snapshot reports its source and rejects the removed round-local diff option", async () => {
+test("snapshot reports its source and rejects options absent from the schema", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
const page = await task.openPage("https://example.test/before");
@@ -674,7 +718,7 @@ test("snapshot reports its source and rejects the removed round-local diff optio
);
await assert.rejects(
() => page.snapshot({ diff: true }),
- /page\.snapshot does not support diff/,
+ /page\.snapshot received unknown option: diff/,
);
});
});
@@ -867,7 +911,7 @@ test("Page fetch validates its JSON options and millisecond timeout", async () =
);
await assert.rejects(
() => page.fetch("/api/text", { signal: {} }),
- /does not accept options.signal/,
+ /page\.fetch received unknown option: signal/,
);
await assert.rejects(
() => page.fetch("/api/text", { headers: cyclic }),
@@ -963,19 +1007,24 @@ test("Page fill uses its target session and reports no popup when none opened",
});
});
-test("Page action receipts report navigation and obvious document changes", async () => {
+test("Page action receipts do not inject observation probes", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
const page = await task.openPage("https://example.test/before");
fixture.navigateOnNextClick("https://example.test/after");
+ fixture.calls.length = 0;
- assert.deepEqual(await page.click("#navigate"), {
- navigation: {
- from: "https://example.test/before",
- to: "https://example.test/after",
- },
- domChanged: true,
- });
+ assert.deepEqual(await page.click("#navigate"), {});
+ assert.equal(await page.url(), "https://example.test/after");
+ assert.equal(
+ fixture.calls.some(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Runtime.evaluate" &&
+ params.expression.includes("__egoBrowserActionProbes"),
+ ),
+ false,
+ );
});
});
@@ -1460,6 +1509,121 @@ test("Page keyboard omits synthetic dispatch while file input stays target-scope
});
});
+test("Page.setInputFiles resolves labels without opening a system chooser", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.openPage("https://example.test/upload");
+
+ await page.setInputFiles("label[for=upload]", [
+ "/tmp/one.txt",
+ "/tmp/two.txt",
+ ]);
+
+ const resolveCall = fixture.calls.find(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Runtime.callFunctionOn" &&
+ params.functionDeclaration.includes("resolveFileInputForUpload"),
+ );
+ assert(resolveCall, "the resolved element is normalized to its file input");
+ const uploadCall = fixture.calls.find(
+ ([kind, method]) => kind === "cdp" && method === "DOM.setFileInputFiles",
+ );
+ assert.deepEqual(uploadCall[2], {
+ files: ["/tmp/one.txt", "/tmp/two.txt"],
+ objectId: `file-input:${page.targetId}`,
+ });
+ assert.equal(fixture.systemFileChooserOpened(), false);
+
+ await page.setInputFiles("#upload", []);
+ const uploadCalls = fixture.calls.filter(
+ ([kind, method]) => kind === "cdp" && method === "DOM.setFileInputFiles",
+ );
+ assert.deepEqual(uploadCalls.at(-1)[2].files, []);
+ });
+});
+
+test("Page.waitForFileChooser handles a dynamically created file input", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.openPage("https://example.test/dynamic-upload");
+ fixture.openFileChooserOnNextClick({
+ backendNodeId: 91,
+ mode: "selectMultiple",
+ });
+
+ const chooserPromise = page.waitForFileChooser({ timeout: 1_234 });
+ await page.click("#open-upload");
+ const chooser = await chooserPromise;
+ assert.equal(chooser.isMultiple(), true);
+ await chooser.setFiles(["/tmp/one.txt", "/tmp/two.txt"]);
+
+ const prepared = fixture.calls.find(
+ ([kind]) => kind === "prepareFileChooser",
+ );
+ assert.deepEqual(prepared, [
+ "prepareFileChooser",
+ `session:${page.targetId}`,
+ { timeoutMs: 1_234, cancel: false },
+ ]);
+ const uploadCall = fixture.calls.find(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "DOM.setFileInputFiles" &&
+ params.backendNodeId === 91,
+ );
+ assert.deepEqual(uploadCall[2].files, ["/tmp/one.txt", "/tmp/two.txt"]);
+ assert.equal(fixture.systemFileChooserOpened(), false);
+ });
+});
+
+test("FileChooser.setFiles uses the current Page session after reconnect", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.openPage("https://example.test/dynamic-upload");
+ fixture.openFileChooserOnNextClick({ backendNodeId: 92 });
+
+ const chooserPromise = page.waitForFileChooser();
+ await page.click("#open-upload");
+ const chooser = await chooserPromise;
+ fixture.setSession(page.targetId, "fresh-upload-session");
+
+ await chooser.setFiles("/tmp/fresh.txt");
+
+ const uploadCall = fixture.calls.find(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "DOM.setFileInputFiles" &&
+ params.backendNodeId === 92,
+ );
+ assert.equal(uploadCall[3], "fresh-upload-session");
+ });
+});
+
+test("unhandled file choosers are cancelled before a system dialog appears", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.openPage("https://example.test/upload-guard");
+ fixture.openFileChooserOnNextClick();
+
+ await assert.rejects(
+ () => page.click("#open-upload"),
+ (error) => {
+ assert.equal(error.code, "EGO_FILE_CHOOSER_OPENED");
+ assert.match(error.message, /page\.setInputFiles/);
+ assert.match(error.message, /page\.waitForFileChooser/);
+ return true;
+ },
+ );
+
+ const prepared = fixture.calls.find(
+ ([kind]) => kind === "prepareFileChooser",
+ );
+ assert.equal(prepared[2].cancel, true);
+ assert.equal(fixture.systemFileChooserOpened(), false);
+ });
+});
+
test("Page and TaskSpace CDP commands preserve their intended scope", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index 4d149d2..0ebbc39 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -6,7 +6,10 @@ import {
invalidateSession,
isNetworkDomainEnabled,
pendingDialog,
+ prepareFileChooser,
setPreferredTarget,
+ type FileChooserInterception,
+ type FileChooserOpenedEvent,
} from "./browser-runtime.js";
import { runtimeValue } from "./cdp-eval.js";
import {
@@ -34,7 +37,11 @@ import {
type PageMouseClickOptions,
type PageMouseMoveOptions,
} from "./driver/page-actions.js";
-import { setInputFilesInPage } from "./driver/page-input.js";
+import {
+ normalizeFilePaths,
+ setFilesOnBackendNode,
+ setInputFilesInPage,
+} from "./driver/page-input.js";
import {
PageKeyboardController,
type PageKeyboardPressOptions,
@@ -101,6 +108,10 @@ type WaitForControlOptions = {
timeout?: number;
};
+type PageWaitForFileChooserOptions = {
+ timeout?: number;
+};
+
export type PageFetchOptions = {
timeout?: number;
method?: string;
@@ -173,10 +184,7 @@ type LedgerPort = {
targetId: string,
openedBy?: PageOrigin,
): Promise<void>;
- beginUserControl(
- spaceId: number,
- liveTargetIds: Iterable<string>,
- ): Promise<void>;
+ beginUserControl(spaceId: number): Promise<void>;
cancelUserControl(spaceId: number): Promise<void>;
reconcile(
spaceId: number,
@@ -216,6 +224,10 @@ type PageModelServices = {
sessionId: string,
): Promise<string>;
pendingDialog(sessionId: string): Record<string, unknown> | null;
+ prepareFileChooser(
+ sessionId: string,
+ options: { timeoutMs: number; cancel: boolean },
+ ): FileChooserInterception;
drainEvents(sessionId: string): any[];
isNetworkDomainEnabled(sessionId: string): boolean;
ensureSession(targetId: string): Promise<string>;
@@ -239,8 +251,6 @@ export type PageInventoryItem = {
export type PageActionReceipt = {
popups?: Array<{ label: string; targetId: string }>;
- navigation?: { from: string; to: string };
- domChanged?: true;
};
const PAGE_CLOSE_CONFIRM_TIMEOUT_MS = 2_000;
@@ -510,6 +520,7 @@ const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {
snapshot: snapshotRaw,
screenshot: captureScreenshotForSession,
pendingDialog,
+ prepareFileChooser,
drainEvents: drainPageEvents,
isNetworkDomainEnabled,
ensureSession,
@@ -634,8 +645,6 @@ class TaskSpace {
validatePublicApiOptions("TaskSpace.waitForControl", options);
const intervalMs = options.interval ?? CONTROL_POLL_INTERVAL_MS;
const timeoutMs = options.timeout ?? CONTROL_WAIT_TIMEOUT_MS;
- assertPositiveMilliseconds(intervalMs, "interval");
- assertPositiveMilliseconds(timeoutMs, "timeout");
const deadline = this.#services.now() + timeoutMs;
while (true) {
@@ -655,11 +664,8 @@ class TaskSpace {
/** Give control of this task space to the user while keeping Page state. */
async handOff(): Promise<void> {
await this.#services.gate.withSpace(this.spaceId, async () => {
- const { tabs } = await this.#reconcilePages();
- await this.#services.ledger.beginUserControl(
- this.spaceId,
- tabs.map((tab) => tab.targetId),
- );
+ await this.#reconcilePages();
+ await this.#services.ledger.beginUserControl(this.spaceId);
try {
await this.#services.handOffTaskSpace();
} catch (error) {
@@ -747,7 +753,7 @@ class TaskSpace {
}
/**
- * Stop managing a user or unknown-origin page without closing its browser tab.
+ * Stop managing an unknown-origin page without closing its browser tab.
* Agent-created pages must be closed so they cannot become untracked orphans.
*/
async release(label: string): Promise<UnmanagedPage> {
@@ -776,7 +782,6 @@ class TaskSpace {
assertUrl(url);
validatePublicApiOptions("TaskSpace.openPage", options);
const timeoutMs = options.timeout ?? 15_000;
- assertTimeout(timeoutMs);
return this.#services.gate.withSpace(this.id, async () => {
const { ledger, tabs } = await this.#reconcilePages();
const managedCount = Object.keys(ledger.pages).length;
@@ -876,6 +881,57 @@ class UnmanagedPage {
}
}
+type ArmedFileChooser = {
+ page: PageTarget;
+ interception: FileChooserInterception;
+};
+
+type PendingFileChooser = {
+ arm: Promise<ArmedFileChooser>;
+};
+
+/** A file chooser intercepted before Chromium can open a native dialog. */
+class FileChooser {
+ readonly #services: PageModelServices;
+ readonly #page: PageTarget;
+ readonly #event: FileChooserOpenedEvent;
+ readonly #interception: FileChooserInterception;
+ #handled = false;
+
+ constructor(
+ services: PageModelServices,
+ armed: ArmedFileChooser,
+ event: FileChooserOpenedEvent,
+ ) {
+ this.#services = services;
+ this.#page = armed.page;
+ this.#interception = armed.interception;
+ this.#event = event;
+ }
+
+ isMultiple(): boolean {
+ return this.#event.mode === "selectMultiple";
+ }
+
+ async setFiles(path: string | string[]): Promise<void> {
+ if (this.#handled) throw new Error("this file chooser was already handled");
+ const files = normalizeFilePaths(path, "fileChooser.setFiles");
+ this.#handled = true;
+ try {
+ await this.#services.gate.withPage(this.#page, async ({ sessionId }) => {
+ await setFilesOnBackendNode(
+ this.#services,
+ sessionId,
+ files,
+ this.#event.backendNodeId,
+ );
+ });
+ } finally {
+ await this.#interception.dispose();
+ }
+ }
+}
+
class Page {
readonly label: string;
readonly spaceId: number;
@@ -885,7 +941,7 @@ class Page {
readonly #spaceName: string;
#targetId?: string;
#openedBy?: PageOrigin;
- #closed = false;
+ #pendingFileChooser?: PendingFileChooser;
constructor(
task: TaskSpace,
@@ -934,7 +990,6 @@ class Page {
assertUrl(url);
validatePublicApiOptions("Page.goto", options);
const timeoutMs = options.timeout ?? 15_000;
- assertTimeout(timeoutMs);
const page = await this.#resolve();
const { receipt } = await this.#runActionBoundary(
page,
@@ -955,14 +1010,6 @@ class Page {
}
async snapshot(options: PageSnapshotOptions = {}): Promise<string> {
- if (
- options &&
- typeof options === "object" &&
- !Array.isArray(options) &&
- Object.hasOwn(options, "diff")
- ) {
- throw new TypeError("page.snapshot does not support diff");
- }
validatePublicApiOptions("Page.snapshot", options);
const page = await this.#resolve();
return this.#services.gate.withPage(page, async () => {
@@ -1065,7 +1112,6 @@ class Page {
options: PageWaitForSelectorOptions = {},
): Promise<true> {
validatePublicApiOptions("Page.waitForSelector", options);
- if (options.timeout !== undefined) assertTimeout(options.timeout);
const page = await this.#resolve();
return this.#services.gate.withPage(page, async ({ sessionId }) => {
await this.#activate(page.targetId);
@@ -1085,7 +1131,6 @@ class Page {
options: PageWaitForLoadStateOptions = {},
): Promise<void> {
validatePublicApiOptions("Page.waitForLoadState", options);
- if (options.timeout !== undefined) assertTimeout(options.timeout);
const page = await this.#resolve();
return this.#services.gate.withPage(page, async ({ sessionId }) => {
await this.#activate(page.targetId);
@@ -1106,24 +1151,11 @@ class Page {
}
async screenshot(options: PageScreenshotOptions = {}): Promise<string> {
- if (
- options &&
- typeof options === "object" &&
- !Array.isArray(options) &&
- Object.hasOwn(options, "full")
- ) {
- throw new TypeError(
- "page.screenshot uses fullPage instead of the v1 full option",
- );
- }
validatePublicApiOptions("Page.screenshot", options);
const { path, fullPage, ...captureOptions } = options;
if (path !== undefined && (typeof path !== "string" || path.length === 0)) {
throw new TypeError("page.screenshot path must be a non-empty string");
}
- if (fullPage !== undefined && typeof fullPage !== "boolean") {
- throw new TypeError("page.screenshot fullPage must be a boolean");
- }
const page = await this.#resolve();
return this.#services.gate.withPage(page, async ({ sessionId }) => {
await this.#activate(page.targetId);
@@ -1142,15 +1174,18 @@ class Page {
options: PageClickOptions = {},
): Promise<PageActionReceipt> {
validatePublicApiOptions("Page.click", options);
- return this.#runAction(selector, (sessionId, refMap) =>
- clickInPage(
- this.#services,
- sessionId,
- refMap,
- selector,
- options,
- this.keyboard.modifierMask(),
- ),
+ return this.#runAction(
+ selector,
+ (sessionId, refMap) =>
+ clickInPage(
+ this.#services,
+ sessionId,
+ refMap,
+ selector,
+ options,
+ this.keyboard.modifierMask(),
+ ),
+ true,
);
}
@@ -1159,15 +1194,18 @@ class Page {
options: Omit<PageClickOptions, "clickCount"> = {},
): Promise<PageActionReceipt> {
validatePublicApiOptions("Page.dblclick", options);
- return this.#runAction(selector, (sessionId, refMap) =>
- clickInPage(
- this.#services,
- sessionId,
- refMap,
- selector,
- { ...options, clickCount: 2 },
- this.keyboard.modifierMask(),
- ),
+ return this.#runAction(
+ selector,
+ (sessionId, refMap) =>
+ clickInPage(
+ this.#services,
+ sessionId,
+ refMap,
+ selector,
+ { ...options, clickCount: 2 },
+ this.keyboard.modifierMask(),
+ ),
+ true,
);
}
@@ -1229,19 +1267,54 @@ class Page {
);
}
+ waitForFileChooser(
+ options: PageWaitForFileChooserOptions = {},
+ ): Promise<FileChooser> {
+ validatePublicApiOptions("Page.waitForFileChooser", options);
+ const timeoutMs = options.timeout ?? 10_000;
+ if (this.#pendingFileChooser) {
+ throw new Error("this Page is already waiting for a file chooser");
+ }
+
+ const pending: PendingFileChooser = {
+ arm: (async () => {
+ const page = await this.#resolve();
+ return this.#services.gate.withPage(page, async ({ sessionId }) => {
+ await this.#activate(page.targetId);
+ const interception = this.#services.prepareFileChooser(sessionId, {
+ timeoutMs,
+ cancel: false,
+ });
+ await interception.ready;
+ return { page, interception };
+ });
+ })(),
+ };
+ this.#pendingFileChooser = pending;
+ return (async () => {
+ let armed: ArmedFileChooser | undefined;
+ try {
+ armed = await pending.arm;
+ const event = await armed.interception.event;
+ return new FileChooser(this.#services, armed, event);
+ } catch (error) {
+ if (armed) await armed.interception.dispose(asError(error));
+ throw error;
+ } finally {
+ if (this.#pendingFileChooser === pending) {
+ this.#pendingFileChooser = undefined;
+ }
+ }
+ })();
+ }
+
async scrollBy(
deltaY: number,
options: { deltaX?: number; behavior?: ScrollBehavior } = {},
): Promise<{ x: number; y: number }> {
validatePublicApiOptions("Page.scrollBy", options);
- if (!Number.isFinite(deltaY) || !Number.isFinite(options.deltaX ?? 0)) {
- throw new TypeError("page.scrollBy requires finite pixel deltas");
- }
- if (
- options.behavior !== undefined &&
- !["auto", "instant", "smooth"].includes(options.behavior)
- ) {
- throw new TypeError(`page.scrollBy received unsupported behavior`);
+ if (!Number.isFinite(deltaY)) {
+ throw new TypeError("page.scrollBy requires a finite deltaY");
}
return this.#runValueAction((sessionId) =>
evaluateInSession<{ x: number; y: number }>(
@@ -1273,7 +1346,6 @@ class Page {
if (!live) {
await this.#services.ledger.closePage(this.spaceId, this.label);
this.#services.pageRefs.clear(page.targetId);
- this.#closed = true;
throw new Error(`page ${this.label} was closed`);
}
if (tabs.length <= 1) {
@@ -1314,12 +1386,10 @@ class Page {
this.#services.invalidateSession(page.targetId);
this.#services.pageRefs.clear(page.targetId);
await this.#services.ledger.closePage(this.spaceId, this.label);
- this.#closed = true;
});
}
async #resolve(): Promise<PageTarget> {
- if (this.#closed) throw new Error(`page ${this.label} was closed`);
const entry = await this.#services.ledger.getPage(this.spaceId, this.label);
this.#targetId = entry.targetId;
this.#openedBy = entry.openedBy;
@@ -1357,6 +1427,7 @@ class Page {
async #runAction(
selector: string | string[],
operation: (sessionId: string, refMap: RefMap) => Promise<void>,
+ guardFileChooser = false,
): Promise<PageActionReceipt> {
const page = await this.#resolve();
const selectors = Array.isArray(selector) ? selector : [selector];
@@ -1366,6 +1437,7 @@ class Page {
const refMap = await this.#refMapForAction(page, ...selectors);
await operation(sessionId, refMap);
},
+ guardFileChooser,
);
return receipt;
}
@@ -1388,7 +1460,7 @@ class Page {
operation: (sessionId: string) => Promise<void>,
): Promise<PageActionReceipt> {
const page = await this.#resolve();
- const { receipt } = await this.#runActionBoundary(page, operation);
+ const { receipt } = await this.#runActionBoundary(page, operation, true);
return receipt;
}
@@ -1409,17 +1481,31 @@ class Page {
async #runActionBoundary<T>(
page: PageTarget,
operation: (sessionId: string) => Promise<T>,
+ guardFileChooser = false,
): Promise<{ value: T; receipt: PageActionReceipt }> {
+ const explicitFileChooser = guardFileChooser
+ ? this.#pendingFileChooser
+ : undefined;
+ if (explicitFileChooser) {
+ const armed = await explicitFileChooser.arm;
+ if (armed.page.targetId !== page.targetId) {
+ throw new Error("file chooser waiter belongs to a different Page");
+ }
+ }
return this.#services.gate.withPage(page, async ({ sessionId }) => {
await this.#activate(page.targetId);
+ const fileChooserGuard =
+ guardFileChooser && !explicitFileChooser
+ ? this.#services.prepareFileChooser(sessionId, {
+ timeoutMs: 1_000,
+ cancel: true,
+ })
+ : undefined;
try {
+ await fileChooserGuard?.ready;
const before = new Set(
(await this.#services.listTabs()).map((tab) => tab.targetId),
);
- const observation = await startActionObservation(
- this.#services,
- sessionId,
- );
let actionError: unknown;
let value: T | undefined;
try {
@@ -1432,11 +1518,6 @@ class Page {
// settle covers native tab-list propagation without turning this into a
// navigation wait or silently changing the page's active state.
await this.#services.sleep(50);
- const observedAfter = await finishActionObservation(
- this.#services,
- sessionId,
- observation,
- );
let popupError: unknown;
const popups: Array<{ label: string; targetId: string }> = [];
try {
@@ -1454,13 +1535,18 @@ class Page {
popupError = error;
}
+ if (fileChooserGuard?.peek()) {
+ throw unhandledFileChooserError();
+ }
+
if (actionError) throw actionError;
if (popupError) throw popupError;
return {
value: value as T,
- receipt: actionReceipt(observation, observedAfter, popups),
+ receipt: popups.length > 0 ? { popups } : {},
};
} finally {
+ await fileChooserGuard?.dispose();
this.#services.pageRefs.clear(page.targetId);
}
});
@@ -1512,144 +1598,6 @@ class Page {
}
}
-type ActionObservation = {
- id: string;
- url: string;
- documentToken: string;
- controlHash: number;
- mutations?: number;
-};
-
-async function startActionObservation(
- services: PageModelServices,
- sessionId: string,
-): Promise<ActionObservation | undefined> {
- const id = `action_${services.now()}_${Math.random().toString(16).slice(2)}`;
- try {
- const response = await services.cdp(
- "Runtime.evaluate",
- {
- expression: `(() => {
- const id = ${JSON.stringify(id)};
- const hashControls = () => {
- let hash = 2166136261;
- const values = Array.from(document.querySelectorAll('input,textarea,select'))
- .map((element) => [element.value, element.checked, element.selectedIndex].join(':'))
- .join('|');
- for (let index = 0; index < values.length; index += 1) {
- hash = Math.imul(hash ^ values.charCodeAt(index), 16777619);
- }
- return hash >>> 0;
- };
- const probe = { mutations: 0 };
- probe.observer = new MutationObserver((records) => {
- probe.mutations += records.length;
- });
- if (document.documentElement) {
- probe.observer.observe(document.documentElement, {
- attributes: true,
- childList: true,
- characterData: true,
- subtree: true,
- });
- }
- globalThis.__egoBrowserActionProbes ||= Object.create(null);
- globalThis.__egoBrowserActionProbes[id] = probe;
- return {
- url: location.href,
- documentToken: String(performance.timeOrigin),
- controlHash: hashControls(),
- };
- })()`,
- returnByValue: true,
- awaitPromise: false,
- },
- sessionId,
- );
- const value = response?.result?.value;
- if (!value || typeof value.url !== "string") return undefined;
- return { id, ...value };
- } catch {
- // Receipts are feedback only. A page that blocks observation must not make
- // the requested action fail.
- return undefined;
- }
-}
-
-async function finishActionObservation(
- services: PageModelServices,
- sessionId: string,
- before: ActionObservation | undefined,
-): Promise<ActionObservation | undefined> {
- if (!before) return undefined;
- try {
- const response = await services.cdp(
- "Runtime.evaluate",
- {
- expression: `(() => {
- const id = ${JSON.stringify(before.id)};
- const hashControls = () => {
- let hash = 2166136261;
- const values = Array.from(document.querySelectorAll('input,textarea,select'))
- .map((element) => [element.value, element.checked, element.selectedIndex].join(':'))
- .join('|');
- for (let index = 0; index < values.length; index += 1) {
- hash = Math.imul(hash ^ values.charCodeAt(index), 16777619);
- }
- return hash >>> 0;
- };
- const probes = globalThis.__egoBrowserActionProbes;
- const probe = probes?.[id];
- let mutations = 0;
- if (probe) {
- mutations = probe.mutations + probe.observer.takeRecords().length;
- probe.observer.disconnect();
- delete probes[id];
- }
- return {
- url: location.href,
- documentToken: String(performance.timeOrigin),
- controlHash: hashControls(),
- mutations,
- };
- })()`,
- returnByValue: true,
- awaitPromise: false,
- },
- sessionId,
- );
- const value = response?.result?.value;
- if (!value || typeof value.url !== "string") return undefined;
- return { id: before.id, ...value };
- } catch {
- return undefined;
- }
-}
-
-function actionReceipt(
- before: ActionObservation | undefined,
- after: ActionObservation | undefined,
- popups: Array<{ label: string; targetId: string }>,
-): PageActionReceipt {
- const receipt: PageActionReceipt = {};
- if (before && after) {
- const navigated =
- before.url !== after.url || before.documentToken !== after.documentToken;
- if (navigated) {
- receipt.navigation = { from: before.url, to: after.url };
- }
- if (
- navigated ||
- (after.mutations ?? 0) > 0 ||
- before.controlHash !== after.controlHash
- ) {
- receipt.domChanged = true;
- }
- }
- if (popups.length > 0) receipt.popups = popups;
- return receipt;
-}
-
function snapshotSourceHeader(input: {
currentLabel: string;
currentTargetId: string;
@@ -1799,19 +1747,8 @@ function pageFetchPayload(
url: string,
options: PageFetchOptions,
): PageFetchPayload {
- if (
- options &&
- typeof options === "object" &&
- !Array.isArray(options) &&
- Object.hasOwn(options, "signal")
- ) {
- throw new TypeError(
- "page.fetch does not accept options.signal; use timeout in milliseconds",
- );
- }
validatePublicApiOptions("Page.fetch", options);
const { timeout = 20_000, ...requestOptions } = options;
- assertTimeout(timeout);
return {
url,
options: serializeJsonValue(
@@ -1950,14 +1887,18 @@ function assertUrl(url: string): void {
}
}
-function assertTimeout(timeout: number | undefined): void {
- if (timeout !== undefined) assertPositiveMilliseconds(timeout, "timeout");
+function asError(value: unknown): Error {
+ return value instanceof Error ? value : new Error(String(value));
}
-function assertPositiveMilliseconds(value: number, name: string): void {
- if (!Number.isFinite(value) || value <= 0) {
- throw new TypeError(`${name} must be a positive number of milliseconds`);
- }
+function unhandledFileChooserError(): Error & { code: string } {
+ const error = new Error(
+ "This action opened a file chooser, which was cancelled before the system dialog appeared. " +
+ "Use page.setInputFiles() for an existing file input, or call " +
+ "page.waitForFileChooser() before the action when the input is created dynamically.",
+ ) as Error & { code: string };
+ error.code = "EGO_FILE_CHOOSER_OPENED";
+ return error;
}
function assertCdpCall(
@@ -1973,7 +1914,6 @@ function assertCdpCall(
throw new TypeError("cdp params must be an object");
}
validatePublicApiOptions(apiName, options);
- if (options.timeout !== undefined) assertTimeout(options.timeout);
}
async function waitForTargetToDisappear(
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index b026f1f..5cc1fce 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -3,7 +3,6 @@ export type PublicApiOptionKind =
| "clip"
| "finiteNumber"
| "nonNegativeNumber"
- | "object"
| "positiveInteger"
| "positiveMilliseconds"
| "string"
@@ -112,7 +111,7 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
{
name: "TaskSpace.release",
signature: "await task.release(label)",
- summary: "Stop managing a user or unknown-origin Page without closing it.",
+ summary: "Stop managing an unknown-origin Page without closing it.",
},
{
name: "TaskSpace.waitForControl",
@@ -340,7 +339,23 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
{
name: "Page.setInputFiles",
signature: "await page.setInputFiles(selector, pathOrPaths)",
- summary: "Set files on a file input.",
+ summary: "Set files on a file input without opening the system chooser.",
+ },
+ {
+ name: "Page.waitForFileChooser",
+ signature: "page.waitForFileChooser({ timeout? })",
+ summary: "Wait for a dynamically created file chooser.",
+ options: { timeout },
+ },
+ {
+ name: "FileChooser.isMultiple",
+ signature: "fileChooser.isMultiple()",
+ summary: "Report whether the chooser accepts multiple files.",
+ },
+ {
+ name: "FileChooser.setFiles",
+ signature: "await fileChooser.setFiles(pathOrPaths)",
+ summary: "Set files on an intercepted chooser without a system dialog.",
},
{
name: "Page.scrollBy",
@@ -534,10 +549,6 @@ function validateOptionValue(
case "nonNegativeNumber":
valid = typeof value === "number" && Number.isFinite(value) && value >= 0;
break;
- case "object":
- valid =
- Boolean(value) && typeof value === "object" && !Array.isArray(value);
- break;
case "positiveInteger":
valid = Number.isInteger(value) && (value as number) > 0;
break;
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index 079ab3a..11bee69 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -8,7 +8,7 @@ description: ego-browser (ego lite) is a real Chromium browser designed from the
ego lite is a real desktop browser based on Chromium. Agents operate real pages in isolated task spaces; pages use the user's actual login state and cookies and produce real downloads, dialogs, and new tabs. Obtain a `TaskSpace` with `taskSpace()`, then obtain or create a `Page` from it. Start every page operation from its `Page`. Page methods address their own page and activate it automatically when interaction requires it, so do not maintain a "current tab" or switch tabs manually.
For installation, connection, or runtime problems, read `references/install.md`.
-For exact v2 signatures and option fields, read `references/api.md`.
+For exact signatures and option fields, read `references/api.md`.
## Run browser scripts
@@ -52,7 +52,7 @@ console.log({ taskSpaceId: task.spaceId, page: page.label });
// Later round
const task = await taskSpace(7);
const page = task.page("source");
-await page.goto("https://example.com/releases", { timeout: 15_000 });
+await page.goto("https://example.com/releases");
```
## Manage pages
@@ -83,9 +83,24 @@ Follow these page-management rules:
- Pages receive permanent `p1`, `p2`, and similar labels automatically. Pass `{ as }` to choose a label. Closed labels are never reused.
- Each space manages at most eight pages by default. On `EGO_PAGE_BUDGET_REACHED`, close temporary pages or reuse an existing Page with `goto()`; do not bypass the budget.
- `task.listPages()` returns managed and unmanaged tabs. An `UnmanagedPage` without a `label` exposes identity information only. Call `task.adopt(item.page, { as })` before observing or operating it.
-- Use `task.release(label)` only to return a user-created or unknown-origin page to the user while keeping its tab open. Close Agent-created pages with `page.close()`.
+- Use `task.release(label)` only to return an unknown-origin page to the user while keeping its tab open. Close Agent-created pages with `page.close()`.
- `page.close()` resolves only after the tab has actually disappeared. If close fails, the Page label remains valid and the operation can be retried safely.
+`openPage()` defaults to a `15_000` ms timeout. A custom `as` label must start with a letter and may contain letters, numbers, `_`, or `-`, up to 64 characters. `waitForControl()` defaults to `{ interval: 20_000, timeout: 600_000 }`; it waits but never takes control.
+
+`task.ownership` is the ownership captured when the TaskSpace handle was created. `page.openedBy` is `"agent"` or `"unknown"`; treat `"unknown"` as user-owned for lifecycle decisions.
+
+Each `listPages()` item has `{ label?, page, targetId, title, url, active, openedBy }`. Use `task.page(label)` to resume a known Page; use `listPages()` to discover active or unmanaged tabs:
+
+```js
+const items = await task.listPages();
+const active = items.find((item) => item.active);
+if (active && !active.label) {
+ const adopted = await task.adopt(active.page, { as: "user" });
+ console.log({ page: adopted.label, url: await adopted.url() });
+}
+```
+
New tabs opened by high-level actions receive labels automatically and may appear in the action receipt:
```js
@@ -126,10 +141,7 @@ Use an `@N` ref only with the Page that produced it. Take another snapshot after
Use the visual path first for canvas, rich-text editors, spreadsheets, maps, and virtualized interfaces. Load and inspect the screenshot with an image-viewing tool. Before entering a large amount of content, perform one tiny write probe and inspect another screenshot to confirm that it landed in the correct place.
```js
-const path = await page.screenshot({
- path: "/absolute/path/before.png",
- fullPage: false,
-});
+const path = await page.screenshot({ path: "/absolute/path/before.png" });
await page.mouse.move(420, 260);
await page.mouse.click(420, 260);
@@ -137,7 +149,7 @@ await page.keyboard.type("hello");
console.log({ screenshot: path });
```
-Coordinates use CSS pixels. A Page object starts with mouse position `(0, 0)` in each round. Call `mouse.move()` to place the mouse over the intended scroll area before calling `mouse.wheel()`.
+Coordinates use CSS pixels. A Page object starts with mouse position `(0, 0)` in each round.
Use `ControlOrMeta+A/C/V/Z` for portable editing shortcuts. For document start and end, use `Meta+ArrowUp` / `Meta+ArrowDown` on macOS and `Control+Home` / `Control+End` on Windows.
@@ -160,21 +172,35 @@ Use CDP only for capabilities missing from the Page API:
- `page.cdp()` sends Page, Runtime, DOM, Network, Input, and similar commands to that Page's session.
- `task.cdp()` is only for the Target and Browser domains.
-- Every CDP call returns a Promise. Set `{ timeout }` and handle rejection.
+- Every CDP call returns a Promise and defaults to `timeout: 15_000`. Set another millisecond timeout when needed and handle rejection.
`page.targetId` is the browser's internal tab identifier. Read it only when directly calling a `Target.*` CDP command that requires `targetId`. Use Page objects and labels for ordinary page operations, and do not save a target ID across rounds.
Raw CDP may change document or session state. Do not reuse refs created before the call; take another snapshot first.
-## Page API
+## Page methods and options
+
+Unknown option fields are rejected. All time values are milliseconds.
-Common Page APIs:
+Page identity and inspection:
```js
page.label;
page.spaceId;
page.openedBy;
+page.targetId;
+await page.url();
+await page.title();
+await page.info();
+await page.events();
+```
+
+`page.info()` returns `{ url, title, w, h, sx, sy, pw, ph }`, or `{ dialog }` while a JavaScript dialog is pending. `page.events()` reads and clears pending CDP events for this Page only.
+
+Navigation, observation, JavaScript, waits, files, and CDP:
+
+```js
await page.goto(url, { timeout });
await page.snapshot({ scope, includeActionMarks, includeStableLocator });
await page.screenshot({
@@ -183,29 +209,34 @@ await page.screenshot({
clip: { x, y, width, height, scale },
raw,
});
-await page.url();
-await page.title();
-await page.info();
-await page.evaluate(fnOrString, arg);
-await page.fetch(url, {
- timeout,
- method,
- headers,
- body,
- cache,
- credentials,
- integrity,
- keepalive,
- mode,
- redirect,
- referrer,
- referrerPolicy,
-});
+await page.evaluate(fnOrString, argument);
+await page.fetch(url, options);
await page.cdp(method, params, { timeout });
await page.waitForSelector(selector, { timeout, state });
-await page.waitForLoadState("load" | "networkidle", { timeout, idleMs });
-await page.events();
+await page.waitForLoadState(state, { timeout, idleMs });
+await page.setInputFiles(selector, pathOrPaths);
+const chooserPromise = page.waitForFileChooser({ timeout });
+await page.click(selector);
+const chooser = await chooserPromise;
+await chooser.setFiles(pathOrPaths);
+await page.scrollBy(deltaY, { deltaX, behavior });
+await page.close();
+```
+
+- `goto()` defaults to `timeout: 15_000`.
+- `snapshot()` defaults to `{ scope: "full_page", includeActionMarks: true, includeStableLocator: true }`. `scope` is `"full_page"` or `"only_within_viewport"`; there is no `diff` option.
+- Omit `screenshot()`'s `path` to receive a temporary PNG path; provided paths should be absolute. `clip.scale` is optional and positive. `raw` defaults to `false`; set it only for uncorrected device-pixel output.
+- `evaluate()` accepts a function with at most one JSON-serializable argument, or a string expression with no argument. Its return value must also be JSON-serializable.
+- Raw `page.cdp()` invalidates existing refs.
+- `waitForSelector()` defaults to `timeout: 10_000`.
+- `waitForLoadState()` accepts only `"load"` and `"networkidle"`, defaults to `timeout: 10_000`, and uses `idleMs: 500` for network idle.
+- Use `setInputFiles()` with an existing file input, its label, or a container around it. It accepts absolute paths; `[]` clears the selection without opening a system dialog.
+- If the site creates the file input only after a click, call `waitForFileChooser()` before the click, as shown above. `chooser.isMultiple()` reports whether it accepts multiple files. A chooser opened unexpectedly by `click()`, `dblclick()`, `mouse.click()`, or `keyboard.press()` is cancelled before the system dialog appears.
+- `scrollBy()` defaults to `{ deltaX: 0, behavior: "auto" }`. `behavior` is `"auto"`, `"instant"`, or `"smooth"`.
+
+Element actions:
+```js
await page.click(selector, { button, clickCount, delay, position: { x, y } });
await page.dblclick(selector, { button, delay, position: { x, y } });
await page.hover(selector, { position: { x, y } });
@@ -215,33 +246,18 @@ await page.dragAndDrop(source, target, {
targetPosition: { x, y },
});
await page.fill(selector, value, { clearFirst });
-await page.setInputFiles(selector, pathOrPaths);
-await page.scrollBy(deltaY, { deltaX, behavior });
-await page.close();
```
-Every option field is optional. `snapshot()` defaults to the full page with action marks and stable locators; `scope` accepts `full_page` or `only_within_viewport`. `screenshot()` defaults to the current viewport. `clip` uses CSS pixels. `raw` bypasses device-pixel-ratio correction and should normally remain `false`.
-
-Element actions default to the element center, the left mouse button, and one click. `position`, `sourcePosition`, and `targetPosition` are CSS-pixel offsets from the element's top-left corner. `button` accepts `left`, `middle`, or `right`. `fill()` clears the existing value by default. `scrollBy()` behavior accepts `auto`, `instant`, or `smooth`.
-
-`waitForSelector()` state accepts `attached`, `detached`, `visible`, or `hidden` and defaults to `visible`. A timed-out wait rejects.
-
-`page.events()` reads and clears pending events for that Page only.
-
High-level `goto()`, selector actions, `mouse.click()`, and `keyboard.press()` return lightweight receipts:
```js
const receipt = await page.click("#submit");
-console.log({
- navigatedTo: receipt.navigation?.to,
- domChanged: receipt.domChanged === true,
- popups: receipt.popups ?? [],
-});
+console.log(receipt.popups ?? []);
```
-Receipts are supporting evidence, not final verification. After an action, confirm the intended result with `url()`, `info()`, `snapshot()`, a screenshot, an export, or a readback.
+Receipts only report newly opened Pages. After an action, confirm navigation and page changes with `url()`, `waitForSelector()`, `info()`, `snapshot()`, a screenshot, an export, or a readback.
-Mouse and keyboard APIs:
+Mouse and keyboard primitives:
```js
await page.mouse.click(x, y, { button, clickCount, delay });
@@ -257,7 +273,16 @@ await page.keyboard.type(text, { delay });
await page.keyboard.insertText(text);
```
-Mouse and keyboard coordinates use CSS pixels, and `delay` uses milliseconds. Mouse actions default to a single left click, and `steps` defaults to `1`. Keyboard `delay` is the interval between key down and key up, or between characters.
+Keyboard key names and `+`-separated chords follow Playwright syntax. Use `ControlOrMeta` for portable shortcuts.
+
+Low-level `mouse.move/down/up/wheel`, `keyboard.down/up/type/insertText`, and `scrollBy()` do not return an action receipt; verify their effect explicitly.
+
+For exact details of one method, use runtime help. Read `references/api.md` for the generated complete reference. Do not invent methods or options.
+
+```js
+console.log(help("Page.click"));
+console.log(help("TaskSpace.openPage"));
+```
## Requests
@@ -279,7 +304,9 @@ console.log({
});
```
-Non-2xx responses do not reject automatically; check `ok` and `status`. Use the standard Node.js `fetch()` for background requests that do not need Page cookies or CORS semantics.
+`page.fetch()` defaults to `timeout: 20_000` and does not accept `signal`. `headers` must map strings to strings, and `body` must be a string. It supports `method`, `headers`, `body`, `cache`, `credentials`, `mode`, `redirect`, `integrity`, `keepalive`, `referrer`, and `referrerPolicy`; read `references/api.md` for their accepted values.
+
+Use the standard Node.js `fetch()` for background requests that do not need Page cookies or CORS semantics.
## Wait, recover, and verify
@@ -313,4 +340,4 @@ const spaceId = 7;
const task = await claimTaskSpace(spaceId);
```
-Call `task.close()` by default when the task is complete. Call `task.finish()` only when the user asks to keep the pages, must continue on the result page, or the result cannot be delivered through a URL, file, or summary. Run completion in its own round after verifying the final result. Do not claim that the space ended or closed until the method resolves.
+After verifying the final result, call `task.close()` at the end of the current round by default. Call `task.finish()` only when the user asks to keep the pages, must continue on the result page, or the result cannot be delivered through a URL, file, or summary. Use a separate completion round only when the choice depends on user confirmation. Do not claim that the space ended or closed until the method resolves.
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index 5f2d687..ca7b595 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -4,11 +4,13 @@ Generated from `package/ego-browser/src/public-api-schema.ts`.
## Entry points
-| API | Options | Purpose |
-| ---------------------------------- | ------- | ------------------------------------------------------------------------------ |
-| `await taskSpace(nameOrId)` | — | Reuse or create an Agent-owned task space and return TaskSpace. |
-| `await claimTaskSpace(spaceId)` | — | Claim a user-owned or inactive space after user approval and return TaskSpace. |
-| `await takeOverTaskSpace(spaceId)` | — | Resume an Agent-owned space after user approval and return TaskSpace. |
+| API | Options | Purpose |
+| ----------------------------------------- | ------- | ------------------------------------------------------------------------------ |
+| `await taskSpace(nameOrId)` | — | Reuse or create an Agent-owned task space and return TaskSpace. |
+| `await claimTaskSpace(spaceId)` | — | Claim a user-owned or inactive space after user approval and return TaskSpace. |
+| `await takeOverTaskSpace(spaceId)` | — | Resume an Agent-owned space after user approval and return TaskSpace. |
+| `fileChooser.isMultiple()` | — | Report whether the chooser accepts multiple files. |
+| `await fileChooser.setFiles(pathOrPaths)` | — | Set files on an intercepted chooser without a system dialog. |
## TaskSpace
@@ -22,7 +24,7 @@ Generated from `package/ego-browser/src/public-api-schema.ts`.
| `await task.listPages()` | — | List managed Pages and unmanaged tabs in this space. |
| `await task.openPage(url, { as?, timeout? })` | `as` — Permanent Page label.<br>`timeout` — Maximum duration in milliseconds. | Open and durably label a new Page. |
| `await task.adopt(unmanagedPage, { as? })` | `as` — Permanent Page label. | Bring an unmanaged tab under the Page lifecycle. |
-| `await task.release(label)` | — | Stop managing a user or unknown-origin Page without closing it. |
+| `await task.release(label)` | — | Stop managing an unknown-origin Page without closing it. |
| `await task.waitForControl({ interval?, timeout? })` | `interval` — Polling interval in milliseconds.<br>`timeout` — Maximum duration in milliseconds. | Wait for Agent control without taking it from the user. |
| `await task.handOff()` | — | Give control of this space to the user. |
| `await task.finish()` | — | Finish the task and keep the browser space for the user. |
@@ -54,7 +56,8 @@ Generated from `package/ego-browser/src/public-api-schema.ts`.
| `await page.hover(selector, { position? })` | `position` — CSS-pixel offset from the element's top-left corner. | Move the mouse over an element. |
| `await page.dragAndDrop(source, target, { button?, sourcePosition?, targetPosition? })` | `button` (left, middle, right) — Mouse button.<br>`sourcePosition` — CSS-pixel offset from the element's top-left corner.<br>`targetPosition` — CSS-pixel offset from the element's top-left corner. | Drag from one element to another. |
| `await page.fill(selector, value, { clearFirst? })` | `clearFirst` — Clear the current value before filling. | Focus and fill an input-like element. |
-| `await page.setInputFiles(selector, pathOrPaths)` | — | Set files on a file input. |
+| `await page.setInputFiles(selector, pathOrPaths)` | — | Set files on a file input without opening the system chooser. |
+| `page.waitForFileChooser({ timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for a dynamically created file chooser. |
| `await page.scrollBy(deltaY, { deltaX?, behavior? })` | `deltaX` — Horizontal CSS-pixel delta.<br>`behavior` (auto, instant, smooth) — Scroll behavior. | Scroll this Page by CSS-pixel deltas. |
| `await page.close()` | — | Close this Page after confirming its tab disappeared. |
diff --git a/skills/ego-browser/references/install.md b/skills/ego-browser/references/install.md
index 0a2bed8..36efd4c 100644
--- a/skills/ego-browser/references/install.md
+++ b/skills/ego-browser/references/install.md
@@ -2,7 +2,7 @@
Read this file only when ego lite isn't installed yet, or when the user asks to install ego lite. For day-to-day browser work, go back to `SKILL.md`.
-The ego-browser skill depends on the ego lite browser: the `ego-browser` command is provided by the ego lite app. Once ego lite is installed and you've gone through onboarding once, the environment is ready and there are no further environment issues.
+The ego-browser skill depends on the ego lite browser: the `ego-browser` command is provided by the ego lite app. Once ego lite is installed and you've completed onboarding, no additional setup is normally needed.
ego lite website: https://lite.ego.app/
@@ -49,7 +49,7 @@ Once the command exists, verify the runtime with a minimal heredoc:
```bash
ego-browser nodejs <<'EOF'
-cliLog('ego-browser ready')
+console.log('ego-browser ready')
EOF
```
@@ -57,7 +57,7 @@ Printing `ego-browser ready` means the environment is ready.
## After that, return to the original task
-Once the environment is ready, return to the user's original task and continue with the task space flow in `SKILL.md` — start from `useOrCreateTaskSpace(name)` and proceed as usual.
+Once the environment is ready, return to the user's original task and continue with the task space flow in `SKILL.md` — start from `taskSpace(name)` and proceed as usual.
## Troubleshooting
diff --git a/skills/ego-lite-simplify/SKILL.md b/skills/ego-lite-simplify/SKILL.md
new file mode 100644
index 0000000..1f5a08d
--- /dev/null
+++ b/skills/ego-lite-simplify/SKILL.md
@@ -0,0 +1,73 @@
+---
+name: ego-lite-simplify
+description: Find and implement evidence-backed simplifications in the ego-lite repository. Use when reviewing the codebase for dead code, duplicated state or APIs, speculative abstractions, unnecessary compatibility layers, hand-written infrastructure, excessive tests or documentation, or when the user asks to reduce code size or maintenance complexity without hiding behavior changes.
+---
+
+# Simplify ego-lite
+
+Reduce concepts and maintenance surface, not just line count. Prefer a few well-proven deletions over a long list of guesses.
+
+## Establish the contract
+
+1. Read `AGENTS.md` and the design document that owns the affected behavior.
+2. Inspect `git status` and preserve unrelated user changes.
+3. Decide whether the request is an audit or an authorized implementation. Do not turn a cleanup into a product decision without making the behavior change explicit.
+4. Identify the relevant boundary before judging code:
+ - `globalThis.ego` is supplied by the closed-source app; `docs/native-bindings-api.md` documents that external contract.
+ - The runtime has direct CLI and embedded SDK startup paths.
+ - Public agent APIs must stay aligned across implementation, tests, `help()`, and `skills/ego-browser/SKILL.md`.
+ - Browser state can outlive the short Node.js process.
+
+## Find strong candidates
+
+Start with production areas carrying the most state, branching, or public surface. Look for:
+
+- Exports, helpers, events, options, fallbacks, packages, or state fields with no production consumer.
+- Tests or documentation that are the only consumers of behavior that is no longer required.
+- Multiple representations of the same page, task-space, session, ref, lifecycle, or output state.
+- Pass-through layers that add vocabulary but no policy, isolation, or test seam.
+- Compatibility code that is unnecessary on an explicitly breaking branch.
+- Generality with no current product use, such as unsupported concurrency modes or unused extension points.
+- Special cases, rollback paths, or validation that exist only to protect a removable surface.
+- Hand-written parsers, queues, retry logic, or utilities that a Node.js built-in or healthy dependency can replace with less total code.
+
+Do not count moving logic into a wrapper as simplification. Estimate the net result: implementation, tests, docs, public names, state transitions, and special cases removed minus new glue and dependencies added.
+
+## Prove each candidate
+
+Use `rg` first. Search exact symbols, method forms, event names, configuration keys, error codes, protocol strings, and dynamic registration points. Read the callers rather than relying only on static-analysis output.
+
+Classify evidence as:
+
+- **Production:** `package/ego-browser/src`, runtime scripts, build and loader paths, and shipped site learnings.
+- **Contract:** public JSDoc consumed by `help()`, `skills/ego-browser/SKILL.md`, architecture documents, and native binding behavior.
+- **Non-production:** tests, fixtures, snapshots, comments, and historical or draft documents.
+- **Ambiguous:** examples and development scripts; inspect how they are invoked before deciding.
+
+Reject or downgrade a candidate when a real production caller exists, the native contract is uncertain, the change merely relocates complexity, or the deletion requires unrelated churn. A small local cleanup may be implemented directly; a behavior or API decision belongs in the owning design document first.
+
+## Report before broad removal
+
+For an audit, present each worthwhile candidate with:
+
+- The surface to remove or fold.
+- Call-site and contract evidence.
+- The user-visible behavior change, or “none”.
+- What complexity disappears and what replacement remains.
+- Confidence, risks, and the smallest verification needed.
+
+Call out candidates that require a user decision separately from behavior-preserving cleanups.
+
+## Implement safely
+
+Follow spec-driven TDD when changing code:
+
+1. Update or add a characterization test when existing behavior must remain.
+2. Update the owning design or API contract before an intentional behavior change.
+3. Remove the implementation and its now-obsolete tests, fixtures, exports, JSDoc, help entries, and skill documentation together.
+4. Keep comments in English and explain only non-obvious constraints.
+5. Prefer deleting a state or transition over adding another abstraction around it.
+
+Run the narrowest relevant checks first. From `package/ego-browser/`, use `npm test` for runtime changes, `npm run e2e` for real task-space/browser behavior, and `npm run validate:site-skills` for learning changes. Finish with `git diff --check` and report any verification that could not run.
+
+Never edit generated build output as the source of a simplification. Never remove a defensive path until its trust or lifecycle boundary is understood.
diff --git a/skills/ego-lite-simplify/agents/openai.yaml b/skills/ego-lite-simplify/agents/openai.yaml
new file mode 100644
index 0000000..7848c1d
--- /dev/null
+++ b/skills/ego-lite-simplify/agents/openai.yaml
@@ -0,0 +1,4 @@
+interface:
+ display_name: "Simplify ego-lite"
+ short_description: "Find and remove unnecessary ego-lite complexity"
+ default_prompt: "Use $ego-lite-simplify to find evidence-backed ways to reduce this repository’s code and maintenance surface."