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.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
fix: handle Ego Lite user-control handoffs
Aute07ef34d9b9de
diff --git a/docs/local-runtime-development.md b/docs/local-runtime-development.mdindex 0b7a0b9..aa6b787 100644--- a/docs/local-runtime-development.md+++ b/docs/local-runtime-development.md@@ -15,8 +15,8 @@ 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`.+Ego Lite must be installed and onboarding must be complete. The examples below+assume that `ego-browser` on `PATH` belongs to Ego Lite.From the repository root:@@ -59,9 +59,11 @@ 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.+Ego Lite CLI with `--sdk-path`. On macOS it prefers the app's stable+`Versions/Current` helper path, so another installed Ego product cannot silently+take over the test. Set `EGO_BROWSER_REAL_E2E_CLI` to use another installation.+This is the preferred end-to-end compatibility check. `npm test` remains useful+for repository tests but does not replace the real-browser check.The command is self-contained: it starts its own local fixture server, creates auniquely named temporary task space, and cleans both up. No manual SDK linking,@@ -80,6 +82,8 @@ support.- **`ego-browser` not found:** finish Ego Lite onboarding and add its CLIdirectory, commonly `~/.local/bin`, to `PATH`.+- **Multiple Ego products are installed:** set `EGO_BROWSER_REAL_E2E_CLI` to+ the intended Ego Lite helper. The E2E output prints the selected CLI path.- **`--sdk-path` unsupported:** update Ego Lite to a build that supports loadingan external runtime.- **Changes are not visible:** rebuild and confirm that the absolute SDK pathdiff --git a/docs/native-bindings-api.md b/docs/native-bindings-api.mdindex 100d160..1526554 100644--- a/docs/native-bindings-api.md+++ b/docs/native-bindings-api.md@@ -265,69 +265,38 @@ error object:}```-`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:+`error_code` is `'EGO_TASK_SPACE_USER_IN_CONTROL'`. For this code, `error` is a+stable reason key rather than display text. Current keys are:```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.+notifications+location+camera+microphone+pan_tilt_zoom_microphone+midi+bluetooth+usb+serial+hid+protocol_handler+fallback_site_dialog_required_notice+manual_takeover```-Example when a notifications prompt caused the handoff:+For example, a location prompt returns:```js{- error: 'A browser permission prompt for notifications has appeared. Control of this browser space has been handed over.',+ error: 'location',error_code: 'EGO_TASK_SPACE_USER_IN_CONTROL',}```+Callers should use `error_code` to identify the control boundary, then use the+reason key to choose guidance. Unknown reason keys must fall back to generic+user-control guidance.+## Snapshot### `await ego.snapshot(options?)`@@ -733,6 +702,9 @@ message: stringerror_code: string```+The callback does not include the reason key. A user-control send failure+therefore identifies the control boundary, not the permission that caused it.+Assign a function to receive errors. Assigning any non-function value clears thecallback. Errors are delivered asynchronously through the Node event loop.diff --git a/docs/runtime-v2-architecture.md b/docs/runtime-v2-architecture.mdindex 878355c..d34c8fc 100644--- a/docs/runtime-v2-architecture.md+++ b/docs/runtime-v2-architecture.md@@ -384,12 +384,11 @@ popup 回执:状态确认。popup 回执只表示 target 已收编;首次导航可能仍停留在 `about:blank`,需要目的 URL 时由调用方显式等待。-同步 JavaScript dialog 会阻塞触发它的 CDP 输入响应。Runtime 收到-`Page.javascriptDialogOpening` 后会中断该输入等待,让高层动作立即返回-`{ dialog }`;dialog 本身保持打开,由调用方随后 accept 或 dismiss。这样不会依赖-15 秒 CDP 超时,也不会让双击或连续输入在 dialog 关闭后继续执行剩余步骤。-`Page.handleJavaScriptDialog` 直接使用该 Page 已有的 session,不会在 dialog 打开时-重复激活页面;Ego Lite 可能把这种重复激活解释为用户接管。+同步 JavaScript dialog 可能让 Ego Lite 把空间交给用户,触发动作随即 hard stop。+Agent 不会自动接管;用户处理完并明确要求继续后,下一轮再调用+`takeOverTaskSpace()`。dialog 事件缓存不跨 Node 进程持久化。原生没有交出控制权+时,Runtime 仍可中断被 dialog 阻塞的输入,并把 `{ dialog }` 放进动作回执,由同一+轮脚本 accept 或 dismiss。底层原语不安装动作探针,也不等待 50ms 反馈窗口:@@ -439,6 +438,12 @@ await page.evaluate(- 不把 unknown 页面推断成 Agent 页面。- 错误由统一 hard-stop 输出处理,避免循环脚本反复打印同一接管提示。+定位、摄像头或麦克风等权限弹窗也会触发这条边界。Ego Lite 在普通 native 调用+的 `error` 或 rejected Error 的 `message` 中返回 `location`、`camera` 等原因键;+运行时先看稳定的 `error_code`,再解析原因键,未知原因统一回退到通用提示。+CDP 本地发送失败没有原因字段,运行时只做一次 native 状态探测,再拒绝本轮所有+在途 CDP 请求。Agent 不会自动允许权限,也不会自动夺回控制权。+TaskSpace 提供 `handOff()` 和毫秒制 `waitForControl()`。用户明确要求恢复后,`takeOverTaskSpace(spaceId)` 直接返回新的 TaskSpace;接管 user-owned 或inactive space 时,`claimTaskSpace(spaceId)` 也直接返回 TaskSpace。@@ -514,8 +519,8 @@ surface,不属于本阶段。- screenshot、evaluate、fetch、键盘和鼠标都操作并激活指定 Page。- 页面动作不安装观察探针;高层动作仍能返回 popup 回执。- `keyboard.press()` 产生 native/trusted 输入;新版不暴露 synthetic dispatch。-- 同步 alert、confirm、prompt 不会让触发动作等待到 CDP timeout;动作回执带 dialog,- accept/dismiss 后页面脚本能继续执行。+- 同步 dialog 不会退化成 CDP timeout:原生保留控制权时动作回执带 dialog;原生交出+ 控制权时本轮 hard stop,用户处理完成并明确允许后才能 takeover。- `dragAndDrop()` 不只发出起止事件,还能把简单的 pointer-driven 元素实际拖到目标区域;`mouse.down/move/up` 能在 Canvas 上保持按键状态并连续绘制曲线和折线。- Page 操作可以控制真实 `<video>` 和 `<audio>` 播放:开始后时间会推进,暂停、跳转、diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjsindex 34d7c5b..530f69d 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs@@ -9,7 +9,10 @@ import { keyboardRegressionCase } from "./keyboard-regression.mjs";import { pageKeyboardInterfaceCase } from "./page-keyboard.mjs";import { pageClickHitTargetCase } from "./page-click-hit-target.mjs";import { pageDragAndDrawCase } from "./page-drag-and-draw.mjs";-import { pageJavaScriptDialogsCase } from "./page-dialogs.mjs";+import {+ pageJavaScriptDialogHandoffCase,+ pageJavaScriptDialogRecoveryCase,+} from "./page-dialogs.mjs";import { pageMediaPlaybackCase } from "./page-media-playback.mjs";import { pageScrolledScreenshotCase } from "./page-screenshot.mjs";import { pageSnapshotLocatorCase } from "./page-snapshot-locators.mjs";@@ -73,7 +76,17 @@ export const e2eCases = [{ name: "page actions and popup adoption", body: pageActionsAndPopupCase },{ name: "Page click hit target", body: pageClickHitTargetCase },{ name: "Page drag and canvas drawing", body: pageDragAndDrawCase },- { name: "Page JavaScript dialogs", body: pageJavaScriptDialogsCase },+ {+ name: "Page JavaScript dialog handoff",+ body: pageJavaScriptDialogHandoffCase,+ expectedTermination: true,+ markerName: "dialog-hard-stop.json",+ expectedOutput: "The page has displayed a dialog that requires review.",+ },+ {+ name: "Page JavaScript dialog recovery",+ body: pageJavaScriptDialogRecoveryCase,+ },{ name: "Page media playback", body: pageMediaPlaybackCase },{ name: "Page scrolled screenshot", body: pageScrolledScreenshotCase },{ name: "Page snapshot locator quality", body: pageSnapshotLocatorCase },diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjsindex 864b12f..5cfb322 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-dialogs.mjs@@ -1,110 +1,51 @@-export function pageJavaScriptDialogsCase() {+export function pageJavaScriptDialogHandoffCase() {return `const task = await taskSpace(taskName);const page = await task.openPage(baseUrl + "/?page-dialogs=" + Date.now(), {as: "page-dialogs",});- try {await page.evaluate(() => {- const controls = document.createElement("section");- controls.innerHTML =- '<button id="dialog-alert">Alert</button>' +- '<button id="dialog-confirm">Confirm</button>' +- '<button id="dialog-prompt">Prompt</button>' +- '<output id="dialog-result">idle</output>';- document.body.prepend(controls);-- const result = controls.querySelector("#dialog-result");- const record = (value) => {- result.textContent = value;- result.dataset.value = value;- };-- controls.querySelector("#dialog-alert").addEventListener("click", () => {+ const button = document.createElement("button");+ button.id = "dialog-alert";+ button.textContent = "Alert";+ const result = document.createElement("output");+ result.id = "dialog-result";+ result.textContent = "idle";+ button.addEventListener("click", () => {alert("Alert from real E2E");- record("alert:continued");- });- controls.querySelector("#dialog-confirm").addEventListener("click", () => {- record("confirm:" + confirm("Confirm from real E2E"));- });- controls.querySelector("#dialog-prompt").addEventListener("click", () => {- record("prompt:" + prompt("Prompt from real E2E", "initial answer"));+ result.textContent = "alert:continued";+ result.dataset.value = "alert:continued";});+ document.body.prepend(button, result);});- async function openDialog(selector, expectedType, expectedMessage) {- const startedAt = Date.now();- const receipt = await page.click(selector);- assert(- Date.now() - startedAt < 5_000,- expectedType + " action returns before the CDP timeout"- );- assertEqual(receipt.dialog?.type, expectedType, expectedType + " receipt reports its type");- assertEqual(- receipt.dialog?.message,- expectedMessage,- expectedType + " receipt reports its message"- );-- const info = await page.info();- assertEqual(info.dialog?.type, expectedType, expectedType + " remains pending for the caller");- assertEqual(- info.dialog?.message,- expectedMessage,- expectedType + " is readable while the page JavaScript is blocked"- );- return receipt.dialog;- }-- async function assertAgentStillControls(stage) {- const pages = await task.pages();- assert(- pages.some((candidate) => candidate.label === page.label),- stage + " keeps the E2E task space under Agent control"- );- }-- await openDialog("#dialog-alert", "alert", "Alert from real E2E");- await page.cdp("Page.handleJavaScriptDialog", { accept: true });- await page.waitForSelector('[data-value="alert:continued"]', { timeout: 2_000 });- await assertAgentStillControls("handling alert");+ await writeFile(+ join(tempDir, "dialog-hard-stop.json"),+ JSON.stringify({ label: page.label, targetId: page.targetId })+ );- await openDialog("#dialog-confirm", "confirm", "Confirm from real E2E");- await page.cdp("Page.handleJavaScriptDialog", { accept: false });- await page.waitForSelector('[data-value="confirm:false"]', { timeout: 2_000 });- await assertAgentStillControls("handling confirm");+ // Ego Lite hands the space to the user as soon as the site opens the dialog.+ // The hard-stop output terminates this script before click() can return.+ await page.click("#dialog-alert");+ `;+}- const promptDialog = await openDialog(- "#dialog-prompt",- "prompt",- "Prompt from real E2E"+export function pageJavaScriptDialogRecoveryCase() {+ return `+ const saved = JSON.parse(+ await readFile(join(tempDir, "dialog-hard-stop.json"), "utf8"));- assertEqual(- promptDialog.defaultPrompt,- "initial answer",- "prompt receipt reports the default text"+ // This is test-only simulation of the user explicitly asking the Agent to+ // resume. Production code never takes control back automatically.+ const task = await takeOverTaskSpace(taskName);+ const page = task.page(saved.label);++ await page.close();+ assertEqual(page.targetId, saved.targetId, "takeover restores the dialog Page");+ assert(+ !(await task.pages()).some((candidate) => candidate.label === saved.label),+ "recovery closes the blocked dialog Page");- await page.cdp("Page.handleJavaScriptDialog", {- accept: true,- promptText: "replacement answer",- });- await page.waitForSelector('[data-value="prompt:replacement answer"]', {- timeout: 2_000,- });- await assertAgentStillControls("handling prompt");- assertEqual(- await page.evaluate("document.querySelector('#dialog-result').textContent"),- "prompt:replacement answer",- "page JavaScript continues after the prompt is handled"- );-- } finally {- const pending = await page.info().catch(() => null);- if (pending?.dialog) {- await page.cdp("Page.handleJavaScriptDialog", { accept: false }).catch(() => {});- }- await page.close().catch(() => {});- }`;}diff --git a/package/ego-browser/scripts/real-browser-e2e/ego-browser-cli.mjs b/package/ego-browser/scripts/real-browser-e2e/ego-browser-cli.mjsnew file mode 100644index 0000000..6f16910--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/ego-browser-cli.mjs@@ -0,0 +1,18 @@+import { existsSync } from "node:fs";++export const MACOS_EGO_LITE_CLI =+ "/Applications/ego lite.app/Contents/Frameworks/ego Framework.framework/Versions/Current/Helpers/ego-browser";++export function resolveEgoBrowserCli({+ configured = process.env.EGO_BROWSER_REAL_E2E_CLI,+ platform = process.platform,+ pathExists = existsSync,+} = {}) {+ if (typeof configured === "string" && configured.trim()) {+ return configured.trim();+ }+ if (platform === "darwin" && pathExists(MACOS_EGO_LITE_CLI)) {+ return MACOS_EGO_LITE_CLI;+ }+ return "ego-browser";+}diff --git a/package/ego-browser/scripts/real-browser-e2e/run-command.mjs b/package/ego-browser/scripts/real-browser-e2e/run-command.mjsindex 36c789c..8af1585 100644--- a/package/ego-browser/scripts/real-browser-e2e/run-command.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/run-command.mjs@@ -25,10 +25,10 @@ export function runCommand(command, args, options = {}) {if (settled) return;settled = true;if (timer) clearTimeout(timer);- if (error.code === "ENOENT" && command === "ego-browser") {+ if (error.code === "ENOENT" && options.egoBrowserSdkPath) {reject(new Error(- "ego-browser command not found; install/open ego lite before running real browser e2e",+ `Ego Lite CLI not found at ${command}; install/open Ego Lite or set EGO_BROWSER_REAL_E2E_CLI`,),);return;diff --git a/package/ego-browser/scripts/real-browser-e2e/runner.mjs b/package/ego-browser/scripts/real-browser-e2e/runner.mjsindex 866eafb..9921b30 100644--- a/package/ego-browser/scripts/real-browser-e2e/runner.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/runner.mjs@@ -4,6 +4,7 @@ import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";import { e2eCases } from "./cases/index.mjs";+import { resolveEgoBrowserCli } from "./ego-browser-cli.mjs";import { egoSource } from "./ego-source.mjs";import { closeFixtureServer, startFixtureServer } from "./fixture.mjs";import { runCommand } from "./run-command.mjs";@@ -14,6 +15,7 @@ const egoBrowserSdkPath = join(packageDir, "dist", "out", "index.js");const egoBrowserArgs = ["nodejs", "--sdk-path", egoBrowserSdkPath];export async function runRealBrowserE2e() {+ const egoBrowserCli = resolveEgoBrowserCli();const keepTaskSpace =process.env.EGO_BROWSER_REAL_E2E_KEEP === "1" ||process.env.EGO_BROWSER_REAL_E2E_KEEP === "true";@@ -43,7 +45,7 @@ export async function runRealBrowserE2e() {const startedAt = Date.now();try {const { stdout, stderr } = await runCommand(- "ego-browser",+ egoBrowserCli,egoBrowserArgs,{cwd: packageDir,@@ -78,6 +80,7 @@ export async function runRealBrowserE2e() {body,markerName,timeoutMs = 45000,+ expectedOutput,) {console.log(`-- ${name}`);const source = egoSource(body, {@@ -86,8 +89,9 @@ export async function runRealBrowserE2e() {});const startedAt = Date.now();let commandError;+ let commandResult;try {- await runCommand("ego-browser", egoBrowserArgs, {+ commandResult = await runCommand(egoBrowserCli, egoBrowserArgs, {cwd: packageDir,egoBrowserSdkPath,input: source,@@ -99,9 +103,25 @@ export async function runRealBrowserE2e() {const durationMs = Date.now() - startedAt;try {- if (!commandError) {+ if (!commandError && !expectedOutput) {throw new Error("the browser script completed instead of terminating");}+ if (expectedOutput) {+ const output = [+ commandResult?.stdout,+ commandResult?.stderr,+ commandError?.stdout,+ commandError?.stderr,+ commandError?.message,+ ]+ .filter(Boolean)+ .join("\n");+ if (!output.includes(expectedOutput)) {+ throw new Error(+ `the browser script did not report the expected hard stop: ${expectedOutput}`,+ );+ }+ }// The marker is written only after openPage() has returned. Its presence// distinguishes the intended hard stop from an unrelated startup error.await stat(join(tempDir, markerName));@@ -130,6 +150,7 @@ export async function runRealBrowserE2e() {testCase.body(),testCase.markerName,testCase.timeoutMs,+ testCase.expectedOutput,);return;}@@ -199,6 +220,7 @@ export async function runRealBrowserE2e() {console.log("== E2E (real browser helpers) ==");console.log(`fixture: ${context.baseUrl}`);console.log(`task: ${taskName}`);+ console.log(`cli: ${egoBrowserCli}`);console.log(`sdk: ${egoBrowserSdkPath}`);for (const testCase of e2eCases) await maybeRunTestCase(testCase);diff --git a/package/ego-browser/src/browser-runtime.test.mjs b/package/ego-browser/src/browser-runtime.test.mjsindex eac70c2..25804b4 100644--- a/package/ego-browser/src/browser-runtime.test.mjs+++ b/package/ego-browser/src/browser-runtime.test.mjs@@ -71,6 +71,202 @@ test("browserCdp rejects the in-flight request via onSendCDPMessageError", async}});+test("a non-user-control CDP failure does not run the permission probe", async () => {+ const previous = globalThis.ego;+ let probes = 0;+ const runtime = {+ async setAgentTaskState() {+ probes += 1;+ return undefined;+ },+ sendCDPMessage() {+ queueMicrotask(() => {+ runtime.onSendCDPMessageError(+ "The task space is inactive.",+ "EGO_TASK_SPACE_INACTIVE",+ );+ });+ },+ };+ globalThis.ego = runtime;++ try {+ await assert.rejects(+ () => browserCdp("Browser.getVersion", {}, undefined, 1000),+ (error) => {+ assert.equal(error.error_code, "EGO_TASK_SPACE_INACTIVE");+ assert.match(error.message, /no longer assigned to the agent/);+ return true;+ },+ );+ assert.equal(probes, 0);+ } finally {+ invalidateSession();+ if (previous === undefined) delete globalThis.ego;+ else globalThis.ego = previous;+ }+});++test("a user-control CDP failure probes the native permission reason before rejecting", async () => {+ const previous = globalThis.ego;+ let probes = 0;+ const runtime = {+ async setAgentTaskState() {+ probes += 1;+ return {+ error: "microphone",+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",+ };+ },+ sendCDPMessage() {+ queueMicrotask(() => {+ runtime.onSendCDPMessageError(+ "The task is under user control.",+ "EGO_TASK_SPACE_USER_IN_CONTROL",+ );+ });+ },+ };+ globalThis.ego = runtime;++ try {+ await assert.rejects(+ () => browserCdp("Browser.getVersion", {}, undefined, 1000),+ (error) => {+ assert.equal(error.error_code, "EGO_TASK_SPACE_USER_IN_CONTROL");+ assert.match(error.message, /microphone access/);+ return true;+ },+ );+ assert.equal(probes, 1);+ } finally {+ invalidateSession();+ if (previous === undefined) delete globalThis.ego;+ else globalThis.ego = previous;+ }+});++test("concurrent user-control CDP failures share one permission probe", async () => {+ const previous = globalThis.ego;+ let probes = 0;+ let finishProbe;+ const runtime = {+ setAgentTaskState() {+ probes += 1;+ return new Promise((resolve) => {+ finishProbe = resolve;+ });+ },+ sendCDPMessage() {+ queueMicrotask(() => {+ runtime.onSendCDPMessageError(+ "The task is under user control.",+ "EGO_TASK_SPACE_USER_IN_CONTROL",+ );+ });+ },+ };+ globalThis.ego = runtime;++ try {+ const requests = [+ browserCdp("Browser.getVersion", {}, undefined, 1000),+ browserCdp("Browser.getBrowserCommandLine", {}, undefined, 1000),+ ];+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(probes, 1);+ finishProbe({+ error: "camera",+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",+ });+ const results = await Promise.allSettled(requests);+ assert.deepEqual(+ results.map((result) => result.status),+ ["rejected", "rejected"],+ );+ for (const result of results) {+ assert.match(result.reason.message, /camera access/);+ }+ } finally {+ invalidateSession();+ if (previous === undefined) delete globalThis.ego;+ else globalThis.ego = previous;+ }+});++test("a failed permission probe falls back to generic user-control guidance", async () => {+ const previous = globalThis.ego;+ const runtime = {+ async setAgentTaskState() {+ throw new Error("probe transport failed");+ },+ sendCDPMessage() {+ queueMicrotask(() => {+ runtime.onSendCDPMessageError(+ "The task is under user control.",+ "EGO_TASK_SPACE_USER_IN_CONTROL",+ );+ });+ },+ };+ globalThis.ego = runtime;++ try {+ await assert.rejects(+ () => browserCdp("Browser.getVersion", {}, undefined, 1000),+ (error) => {+ assert.match(error.message, /The user has taken control/);+ assert.doesNotMatch(error.message, /probe transport failed/);+ return true;+ },+ );+ } finally {+ invalidateSession();+ if (previous === undefined) delete globalThis.ego;+ else globalThis.ego = previous;+ }+});++test("a recovered probe allows a later takeover to be detected", async () => {+ const previous = globalThis.ego;+ let probes = 0;+ const runtime = {+ async setAgentTaskState() {+ probes += 1;+ if (probes === 1) return undefined;+ return {+ error: "location",+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",+ };+ },+ sendCDPMessage() {+ queueMicrotask(() => {+ runtime.onSendCDPMessageError(+ "The task is under user control.",+ "EGO_TASK_SPACE_USER_IN_CONTROL",+ );+ });+ },+ };+ globalThis.ego = runtime;++ try {+ await assert.rejects(+ () => browserCdp("Browser.getVersion", {}, undefined, 1000),+ /The task is under user control/,+ );+ await assert.rejects(+ () => browserCdp("Browser.getVersion", {}, undefined, 1000),+ /location access/,+ );+ assert.equal(probes, 2);+ } finally {+ invalidateSession();+ if (previous === undefined) delete globalThis.ego;+ else globalThis.ego = previous;+ }+});+test("CDP events are drained only by the target session that received them", async () => {const previous = globalThis.ego;let nextSession = 1;diff --git a/package/ego-browser/src/browser-runtime.ts b/package/ego-browser/src/browser-runtime.tsindex 921b08b..f92b241 100644--- a/package/ego-browser/src/browser-runtime.ts+++ b/package/ego-browser/src/browser-runtime.ts@@ -1,5 +1,9 @@import { state } from "./state.js";-import { assertNoEgoError, buildEgoError } from "./ego-errors.js";+import {+ buildEgoError,+ invokeEgo,+ isEgoUserControlError,+} from "./ego-errors.js";const RESPONSE_TIMEOUT_MS = 15000;const SESSION_TTL_MS = 2000;@@ -21,6 +25,9 @@ const browserEvents = [];const targetStates = new Map();const sessionTargets = new Map();let defaultTargetId = null;+let userControlProbeState: "idle" | "probing" | "stopped" = "idle";+let userControlStopError: (Error & { error_code?: string }) | null = null;+let userControlProbeGeneration = 0;/*** Signals that a modal JavaScript dialog prevented a CDP command from@@ -190,7 +197,7 @@ function rawCdp(} catch (error) {clearTimeout(timer);pending.delete(id);- reject(error);+ reject(buildEgoError(error));}});}@@ -268,7 +275,9 @@ export async function ensureSession(requestedTargetId = undefined) {let targetId = requestedTargetId;if (!targetId) {- const result = assertNoEgoError(await browserEgo().listTabs());+ const result: any = await invokeEgo("listTabs", () =>+ browserEgo().listTabs(),+ );const tabs = result?.tabs || result?.targetInfos || [];const preferred = state.preferredTargetId? tabs.find((tab) => tab.targetId === state.preferredTargetId)@@ -320,6 +329,7 @@ export function invalidateSession(targetId = undefined) {}browserEvents.length = 0;defaultTargetId = null;+ resetUserControlProbe();}export function setPreferredTarget(targetId) {@@ -483,20 +493,97 @@ async function enablePageEvents(sessionId) {}}-// Local send failures for ego.sendCDPMessage() arrive here (task inactive,-// user-controlled, not selected/claimed, host gone) instead of as a CDP-// response, so the matching request would otherwise sit until the 15s timeout.-// The callback carries no request id; these failures are task-level (every-// in-flight send fails the same way), so reject all pending requests, routing-// the stable code through buildEgoError to use the ego-browser-owned wording.+// Local send failures for ego.sendCDPMessage() arrive here instead of as a CDP+// response. The callback carries no request id, so task-level failures reject+// every pending request. User-control failures first probe the native task state:+// the CDP callback does not carry the permission reason, while ordinary native+// calls may do so on newer Ego Lite builds.function handleSendError(message, error_code) {if (pending.size === 0) return;- const error = buildEgoError({ error: message, error_code });++ if (error_code !== "EGO_TASK_SPACE_USER_IN_CONTROL") {+ rejectAllPending(buildEgoError({ error: message, error_code }));+ return;+ }+ if (userControlProbeState === "stopped" && userControlStopError) {+ rejectAllPending(userControlStopError);+ return;+ }+ if (userControlProbeState === "probing") return;++ userControlProbeState = "probing";+ const generation = ++userControlProbeGeneration;+ void probeUserControlReason(message, error_code, generation);+}++async function probeUserControlReason(+ message: string,+ error_code: string,+ generation: number,+): Promise<void> {+ const fallback = { error: message, error_code };+ const runtime = browserEgo();+ if (typeof runtime.setAgentTaskState !== "function") {+ stopForUserControl(fallback, generation);+ return;+ }++ try {+ const result = await runtime.setAgentTaskState("Waiting for the user");+ if (generation !== userControlProbeGeneration) return;+ if (isEgoUserControlError(result)) {+ stopForUserControl(result, generation);+ return;+ }+ if (result && typeof result === "object" && "error" in result) {+ stopForUserControl(fallback, generation);+ return;+ }++ // Control came back between the failed send and the probe. The original+ // command still failed, but it must not create a new global hard stop.+ userControlProbeState = "idle";+ userControlStopError = null;+ rejectAllPending(nativeSendError(message, error_code));+ } catch (error) {+ if (generation !== userControlProbeGeneration) return;+ stopForUserControl(+ isEgoUserControlError(error) ? error : fallback,+ generation,+ );+ }+}++function stopForUserControl(errorLike: unknown, generation: number): void {+ if (generation !== userControlProbeGeneration) return;+ userControlStopError = buildEgoError(errorLike);+ userControlProbeState = "stopped";+ rejectAllPending(userControlStopError);+}++function rejectAllPending(error: Error): void {const entries = [...pending.values()];pending.clear();for (const entry of entries) entry.reject(error);}+function nativeSendError(+ message: string,+ error_code: string,+): Error & { error_code?: string } {+ const error: Error & { error_code?: string } = new Error(+ message || error_code || "CDP send failed",+ );+ if (error_code) error.error_code = error_code;+ return error;+}++function resetUserControlProbe(): void {+ userControlProbeGeneration += 1;+ userControlProbeState = "idle";+ userControlStopError = null;+}+function handleMessage(message) {let data;try {@@ -514,6 +601,11 @@ function handleMessage(message) {entry.reject(new Error(data.error.message || data.error));return;}+ if (userControlProbeState === "stopped") {+ // A successful command proves control has returned. Re-arm detection so a+ // later, separate takeover can run its own reason probe.+ resetUserControlProbe();+ }entry.resolve(data);return;}diff --git a/package/ego-browser/src/driver/nav.ts b/package/ego-browser/src/driver/nav.tsindex 80e6c67..2dcbad3 100644--- a/package/ego-browser/src/driver/nav.ts+++ b/package/ego-browser/src/driver/nav.ts@@ -8,7 +8,7 @@ import {setPreferredTarget,} from "../browser-runtime.js";import { cdp, js } from "../cdp-eval.js";-import { assertNoEgoError } from "../ego-errors.js";+import { invokeEgo } from "../ego-errors.js";import { state } from "../state.js";import { waitForDocumentLoad } from "./load.js";@@ -106,7 +106,7 @@ export async function listTabs(options: ListTabsOptions = {},): Promise<TabInfo[]> {const includeChrome = options.includeChrome ?? true;- const result = assertNoEgoError(await browserEgo().listTabs(), "listTabs");+ const result = await invokeEgo("listTabs", () => browserEgo().listTabs());const tabs = result.tabs || [];return tabs.filter(@@ -156,7 +156,7 @@ export async function switchTab(target: string | { targetId: string }) {* @returns {Promise<string>} New target id.*/export async function newTab(url = "about:blank") {- const result = assertNoEgoError(await browserEgo().createTab(url), "newTab");+ const result = await invokeEgo("newTab", () => browserEgo().createTab(url));if (!result.targetId) {throw new Error("newTab returned no targetId");}diff --git a/package/ego-browser/src/driver/observe.ts b/package/ego-browser/src/driver/observe.tsindex b7a1305..9e0c69a 100644--- a/package/ego-browser/src/driver/observe.ts+++ b/package/ego-browser/src/driver/observe.ts@@ -11,7 +11,7 @@ import {isBrowserRuntime,pendingDialog,} from "../browser-runtime.js";-import { buildEgoError } from "../ego-errors.js";+import { invokeEgo } from "../ego-errors.js";import { resolveElementCenter } from "../element-resolver.js";import {browserRefMap,@@ -45,17 +45,9 @@ export async function drainEvents() {}export async function snapshot(options: SnapshotOptions = {}) {- let result;- try {- result = await browserEgo().snapshot(options);- } catch (err) {- // ego.snapshot rejects directly (it never resolves with { error }), so it never- // reached buildEgoError — the single birthplace that records a hard stop for the- // output sink and swaps native wording for ego-browser's owned guidance. Route the- // rejection through it so a swallowed snapshot hard stop collapses like every other- // ego error instead of leaking repeated native text.- throw buildEgoError(err, "snapshot");- }+ const result: any = await invokeEgo("snapshot", () =>+ browserEgo().snapshot(options),+ );browserSnapshotRefsToRefMap(browserRefMap, result.refs || []);return result;}diff --git a/package/ego-browser/src/ego-errors.test.mjs b/package/ego-browser/src/ego-errors.test.mjsindex 6b9f8df..48c569e 100644--- a/package/ego-browser/src/ego-errors.test.mjs+++ b/package/ego-browser/src/ego-errors.test.mjs@@ -2,13 +2,86 @@ import test from "node:test";import assert from "node:assert/strict";import {- assertNoEgoError,egoErrorCode,+ invokeEgo,isEgoErrorCode,isEgoUserControlError,resolveEgoError,} from "../dist/src/ego-errors.js";+test("invokeEgo recognizes a permission reason from a resolved native error", async () => {+ await assert.rejects(+ () =>+ invokeEgo("task.listTabs", () =>+ Promise.resolve({+ error: "location",+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",+ }),+ ),+ (error) => {+ assert.equal(error.error_code, "EGO_TASK_SPACE_USER_IN_CONTROL");+ assert.match(+ error.message,+ /^task\.listTabs: A browser permission prompt/,+ );+ assert.match(error.message, /location access/);+ assert.match(error.message, /takeOverTaskSpace\(spaceId\)/);+ return true;+ },+ );+});++test("invokeEgo recognizes a permission reason from a rejected native call", async () => {+ const nativeError = Object.assign(new Error("camera"), {+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",+ });+ await assert.rejects(+ () => invokeEgo("snapshot", () => Promise.reject(nativeError)),+ (error) => {+ assert.equal(error.error_code, "EGO_TASK_SPACE_USER_IN_CONTROL");+ assert.match(error.message, /^snapshot: A browser permission prompt/);+ assert.match(error.message, /camera access/);+ return true;+ },+ );+});++test("user-control reason lookup ignores inherited object properties", () => {+ const { message } = resolveEgoError({+ error: "constructor",+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",+ });+ assert.match(message, /The user has taken control/);+ assert.doesNotMatch(message, /constructor/);+});++test("unknown user-control reasons fall back without exposing the raw key", () => {+ const { message } = resolveEgoError({+ error: "future_permission_reason",+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",+ });+ assert.match(message, /The user has taken control/);+ assert.doesNotMatch(message, /future_permission_reason/);+});++test("invokeEgo preserves non-user-control native failures", async () => {+ await assert.rejects(+ () =>+ invokeEgo("snapshot", () =>+ Promise.reject(+ Object.assign(new Error("snapshot renderer failed"), {+ error_code: "EGO_SNAPSHOT_FAILED",+ }),+ ),+ ),+ (error) => {+ assert.equal(error.error_code, "EGO_SNAPSHOT_FAILED");+ assert.equal(error.message, "snapshot: snapshot renderer failed");+ return true;+ },+ );+});+test("egoErrorCode extracts the code from every error shape", () => {// resolved { error, error_code } objectassert.equal(@@ -128,39 +201,39 @@ test("isEgoUserControlError keys on the stable code, not wording", () => {);});-test("assertNoEgoError resolves the message via the code and attaches error_code", () => {- try {- assertNoEgoError(- {+test("invokeEgo resolves native error objects and attaches error_code", async () => {+ await assert.rejects(+ () =>+ invokeEgo("listTabs", () => ({error: "Task space not selected",error_code: "EGO_TASK_SPACE_NOT_SELECTED",- },- "listTabs",- );- assert.fail("expected assertNoEgoError to throw");- } catch (err) {- assert.equal(err.message, "listTabs: Task space not selected");- assert.equal(err.error_code, "EGO_TASK_SPACE_NOT_SELECTED");- }-});--test("assertNoEgoError omits the prefix when no op is given", () => {- try {- assertNoEgoError({- error: "The task space is inactive: 10",- error_code: "EGO_TASK_SPACE_INACTIVE",- });- assert.fail("expected assertNoEgoError to throw");- } catch (err) {- // No op given, so no "<op>: " prefix — the owned block starts the message.- assert.match(err.message, /^The user has taken control/);- assert.match(err.message, /claimTaskSpace\(spaceId\)/);- assert.doesNotMatch(err.message, /\b10\b/);- assert.equal(err.error_code, "EGO_TASK_SPACE_INACTIVE");- }-});--test("assertNoEgoError passes through results with no error", () => {+ })),+ (error) => {+ assert.equal(error.message, "listTabs: Task space not selected");+ assert.equal(error.error_code, "EGO_TASK_SPACE_NOT_SELECTED");+ return true;+ },+ );+});++test("invokeEgo normalizes synchronous native throws", async () => {+ const nativeError = Object.assign(new Error("native setup failed"), {+ error_code: "EGO_OPERATION_FAILED",+ });+ await assert.rejects(+ () =>+ invokeEgo("createTab", () => {+ throw nativeError;+ }),+ (error) => {+ assert.equal(error.message, "createTab: native setup failed");+ assert.equal(error.error_code, "EGO_OPERATION_FAILED");+ return true;+ },+ );+});++test("invokeEgo passes through successful results", async () => {const ok = { tabs: [] };- assert.equal(assertNoEgoError(ok, "listTabs"), ok);+ assert.equal(await invokeEgo("listTabs", () => ok), ok);});diff --git a/package/ego-browser/src/ego-errors.ts b/package/ego-browser/src/ego-errors.tsindex a4f0c83..c0edc41 100644--- a/package/ego-browser/src/ego-errors.ts+++ b/package/ego-browser/src/ego-errors.ts@@ -64,6 +64,47 @@ const EGO_ERROR_MESSAGES: Partial<Record<EgoErrorCode, string>> = {].join("\n"),};+const USER_CONTROL_GUIDANCE =+ EGO_ERROR_MESSAGES.EGO_TASK_SPACE_USER_IN_CONTROL as string;++const USER_CONTROL_REASON_MESSAGES = Object.freeze({+ notifications: permissionPrompt("notifications"),+ location: permissionPrompt("location access"),+ camera: permissionPrompt("camera access"),+ microphone: permissionPrompt("microphone access"),+ pan_tilt_zoom_microphone: permissionPrompt(+ "camera control and microphone access",+ ),+ midi: permissionPrompt("MIDI device access"),+ bluetooth: userPromptGuidance(+ "A browser device chooser for Bluetooth has appeared.",+ ),+ usb: userPromptGuidance("A browser device chooser for USB has appeared."),+ serial: userPromptGuidance(+ "A browser port chooser for serial access has appeared.",+ ),+ hid: userPromptGuidance("A browser device chooser for HID has appeared."),+ protocol_handler: permissionPrompt("protocol handler registration"),+ fallback_site_dialog_required_notice: userPromptGuidance(+ "The page has displayed a dialog that requires review.",+ ),+ manual_takeover: USER_CONTROL_GUIDANCE,+});++function permissionPrompt(access: string): string {+ return userPromptGuidance(+ `A browser permission prompt for ${access} has appeared.`,+ );+}++function userPromptGuidance(firstLine: string): string {+ return [+ firstLine,+ "The user now controls this task space. Wait for the user to handle the prompt.",+ "Resume only after the user confirms, using takeOverTaskSpace(spaceId).",+ ].join("\n");+}+/** Type guard for codes this build knows about. */export function isEgoErrorCode(value: unknown): value is EgoErrorCode {return (@@ -103,13 +144,27 @@ export function resolveEgoError(err: unknown): {} {const code = egoErrorCode(err);const message =- (isEgoErrorCode(code) ? EGO_ERROR_MESSAGES[code] : undefined) ??+ (code === "EGO_TASK_SPACE_USER_IN_CONTROL"+ ? resolveUserControlMessage(err)+ : isEgoErrorCode(code)+ ? EGO_ERROR_MESSAGES[code]+ : undefined) ??nativeErrorText(err) ??code ??"Unknown ego error";return { code, message };}+function resolveUserControlMessage(err: unknown): string {+ const nativeText = nativeErrorText(err);+ if (nativeText && Object.hasOwn(USER_CONTROL_REASON_MESSAGES, nativeText)) {+ return USER_CONTROL_REASON_MESSAGES[+ nativeText as keyof typeof USER_CONTROL_REASON_MESSAGES+ ];+ }+ return USER_CONTROL_GUIDANCE;+}+/** Whether an ego error means the task is currently under user control. */export function isEgoUserControlError(err: unknown): boolean {return egoErrorCode(err) === "EGO_TASK_SPACE_USER_IN_CONTROL";@@ -127,17 +182,11 @@ function isEgoHardStopCode(code: string | undefined): boolean {);}-/** Whether an ego error is a hard stop the agent must not retry or route around. */-export function isEgoHardStopError(err: unknown): boolean {- return isEgoHardStopCode(egoErrorCode(err));-}-/*** Build an Error carrying the resolved message and stable error_code from any ego* error shape. `op`, when given, prefixes the message with the failing operation.- * Shared by assertNoEgoError (which throws it) and the CDP-send failure path (which- * rejects pending requests with it) so every ego failure surfaces an identical- * Error shape.+ * Shared by invokeEgo and the CDP-send failure path so every ego failure surfaces+ * an identical Error shape.*/export function buildEgoError(err: unknown,@@ -145,8 +194,8 @@ export function buildEgoError(): Error & { error_code?: string } {const { code, message } = resolveEgoError(err);if (isEgoHardStopCode(code)) {- // buildEgoError is the single birthplace of every ego error — assertNoEgoError and- // the CDP-send failure path both route through it — so recording the hard stop here+ // buildEgoError is the single birthplace of every ego error — invokeEgo and the+ // CDP-send failure path both route through it — so recording the hard stop here// catches it even when the agent's own try/catch later swallows the thrown Error.// The op-less owned message is the one the agent should see, regardless of which// operation surfaced it.@@ -159,7 +208,21 @@ export function buildEgoError(return error;}-export function assertNoEgoError(result, op?: string) {+/**+ * Invoke a native binding and normalize synchronous throws, rejected Promises, and+ * resolved `{ error, error_code }` objects. Control-wait probes intentionally bypass+ * this helper because observing user control is their expected result, not a hard stop.+ */+export async function invokeEgo<T>(+ op: string,+ invoke: () => T | Promise<T>,+): Promise<T> {+ let result: T;+ try {+ result = await invoke();+ } catch (error) {+ throw buildEgoError(error, op);+ }if (result &&typeof result === "object" &&diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.tsindex b073174..d1253a5 100644--- a/package/ego-browser/src/helpers.ts+++ b/package/ego-browser/src/helpers.ts@@ -3,7 +3,7 @@ import { join } from "node:path";import { pathToFileURL } from "node:url";import { setOverrides, state } from "./state.js";-import { assertNoEgoError, isEgoUserControlError } from "./ego-errors.js";+import { invokeEgo, isEgoUserControlError } from "./ego-errors.js";import { help as helpRuntime, formatHelp } from "./help-runtime.js";import { cdp, decodeUnserializableJsValue, js } from "./cdp-eval.js";import * as pointer from "./driver/pointer.js";@@ -82,7 +82,7 @@ export async function listTaskSpaces() {throw new Error("listTaskSpaces requires ego.listTaskSpaces");}return normalizeTaskSpaces(- assertNoEgoError(await ego.listTaskSpaces(), "listTaskSpaces"),+ await invokeEgo("listTaskSpaces", () => ego.listTaskSpaces()),);}@@ -146,7 +146,7 @@ export async function newTaskSpace(name) {throw new Error("newTaskSpace requires ego.createTaskSpace");}const created = normalizeTaskSpace(- assertNoEgoError(await ego.createTaskSpace(name), "newTaskSpace"),+ await invokeEgo("newTaskSpace", () => ego.createTaskSpace(name)),);if (!created) {throw new Error("newTaskSpace returned an invalid task space");@@ -225,7 +225,7 @@ async function claimResolvedTaskSpace(space, op = "claimTaskSpace") {}const id = taskSpaceNumericId(space, op);const claimed = normalizeTaskSpace(- assertNoEgoError(await ego.claimTaskSpace(id, space.name), op),+ await invokeEgo(op, () => ego.claimTaskSpace(id, space.name)),);if (!claimed) {throw new Error(`${op} returned an invalid task space`);@@ -238,7 +238,7 @@ async function selectTaskSpace(ego, space, op: string) {if (!ego || typeof ego.useTaskSpace !== "function") {throw new Error(`${op} requires ego.useTaskSpace`);}- assertNoEgoError(await ego.useTaskSpace(taskSpaceNumericId(space, op)), op);+ await invokeEgo(op, () => ego.useTaskSpace(taskSpaceNumericId(space, op)));return space;}@@ -293,7 +293,7 @@ export async function completeTaskSpace(if (typeof ego.completeTaskSpace !== "function") {throw new Error("completeTaskSpace requires ego.completeTaskSpace");}- assertNoEgoError(await ego.completeTaskSpace(), "completeTaskSpace");+ await invokeEgo("completeTaskSpace", () => ego.completeTaskSpace());} else {if (match.ownership === "user") {await claimResolvedTaskSpace(match, "completeTaskSpace");@@ -303,7 +303,7 @@ export async function completeTaskSpace(if (typeof ego.closeTaskSpace !== "function") {throw new Error("completeTaskSpace requires ego.closeTaskSpace");}- assertNoEgoError(await ego.closeTaskSpace(), "completeTaskSpace");+ await invokeEgo("completeTaskSpace", () => ego.closeTaskSpace());}return { done: true };}@@ -327,7 +327,7 @@ export async function handOffTaskSpace(nameOrId?: string | number) {}await selectTaskSpace(ego, match, "handOffTaskSpace");}- assertNoEgoError(await ego.handOffTaskSpace(), "handOffTaskSpace");+ await invokeEgo("handOffTaskSpace", () => ego.handOffTaskSpace());return { done: true };}@@ -346,7 +346,7 @@ export async function takeOverTaskSpace(nameOrId?: string | number) {descriptor = await findTaskSpace(nameOrId);await selectTaskSpace(ego, descriptor, "takeOverTaskSpace");}- assertNoEgoError(await ego.takeOverTaskSpace(), "takeOverTaskSpace");+ await invokeEgo("takeOverTaskSpace", () => ego.takeOverTaskSpace());if (descriptor) {const task = createTaskSpaceHandle({ ...descriptor, ownership: "agent" });// Repeatedly ensuring control over an already agent-controlled space is adiff --git a/package/ego-browser/src/native-gate.ts b/package/ego-browser/src/native-gate.tsindex a641035..a5539e5 100644--- a/package/ego-browser/src/native-gate.ts+++ b/package/ego-browser/src/native-gate.ts@@ -1,5 +1,5 @@import { browserEgo, ensureSession } from "./browser-runtime.js";-import { assertNoEgoError } from "./ego-errors.js";+import { invokeEgo } from "./ego-errors.js";type SpaceScope = {spaceId: number;@@ -100,7 +100,7 @@ const defaultGate = new NativeOperationGate({if (typeof ego.useTaskSpace !== "function") {throw new Error("withSpace requires ego.useTaskSpace");}- assertNoEgoError(await ego.useTaskSpace(spaceId), "withSpace");+ await invokeEgo("withSpace", () => ego.useTaskSpace(spaceId));},ensureSession,});diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex b9371a8..441fe0a 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -56,7 +56,7 @@ import {type PageWaitForSelectorOptions,type PageWaitForURLOptions,} from "./driver/page-waits.js";-import { assertNoEgoError, isEgoUserControlError } from "./ego-errors.js";+import { invokeEgo, isEgoUserControlError } from "./ego-errors.js";import {withPage as defaultWithPage,withSpace as defaultWithSpace,@@ -463,9 +463,8 @@ const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {gate: defaultGate,pageRefs: defaultPageRefs,async createTab(url) {- const result = assertNoEgoError(- await browserEgo().createTab(url),- "task.openPage",+ const result = await invokeEgo("task.openPage", () =>+ browserEgo().createTab(url),);const targetId = result?.targetId || result?.result?.targetId;if (typeof targetId !== "string" || targetId.length === 0) {@@ -474,9 +473,8 @@ const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {return targetId;},async listTabs() {- const result = assertNoEgoError(- await browserEgo().listTabs(),- "task.listTabs",+ const result = await invokeEgo("task.listTabs", () =>+ browserEgo().listTabs(),);return result?.tabs || result?.targetInfos || [];},@@ -496,21 +494,21 @@ const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {if (typeof ego.handOffTaskSpace !== "function") {throw new Error("task.handOff requires ego.handOffTaskSpace");}- assertNoEgoError(await ego.handOffTaskSpace(), "task.handOff");+ await invokeEgo("task.handOff", () => ego.handOffTaskSpace());},async completeTaskSpace() {const ego = browserEgo();if (typeof ego.completeTaskSpace !== "function") {throw new Error("task.finish requires ego.completeTaskSpace");}- assertNoEgoError(await ego.completeTaskSpace(), "task.finish");+ await invokeEgo("task.finish", () => ego.completeTaskSpace());},async closeTaskSpace() {const ego = browserEgo();if (typeof ego.closeTaskSpace !== "function") {throw new Error("task.close requires ego.closeTaskSpace");}- assertNoEgoError(await ego.closeTaskSpace(), "task.close");+ await invokeEgo("task.close", () => ego.closeTaskSpace());},async cdp(method, params = {}, sessionId, timeoutMs) {const response = await browserCdp(method, params, sessionId, timeoutMs);@@ -519,7 +517,9 @@ const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {async showAgentMousePosition(x, y) {const ego = browserEgo();if (typeof ego.animationHighlightMouseToPosition !== "function") return;- await ego.animationHighlightMouseToPosition(x, y);+ await invokeEgo("page.mouse.move", () =>+ ego.animationHighlightMouseToPosition(x, y),+ );},snapshot: snapshotRaw,screenshot: captureScreenshotForSession,diff --git a/package/ego-browser/src/real-browser-runner.test.mjs b/package/ego-browser/src/real-browser-runner.test.mjsnew file mode 100644index 0000000..eb8077f--- /dev/null+++ b/package/ego-browser/src/real-browser-runner.test.mjs@@ -0,0 +1,39 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ MACOS_EGO_LITE_CLI,+ resolveEgoBrowserCli,+} from "../scripts/real-browser-e2e/ego-browser-cli.mjs";++test("real-browser E2E honors an explicit Ego Lite CLI", () => {+ assert.equal(+ resolveEgoBrowserCli({+ configured: "/custom/ego-lite/ego-browser",+ platform: "darwin",+ pathExists: () => true,+ }),+ "/custom/ego-lite/ego-browser",+ );+});++test("real-browser E2E prefers the stable Ego Lite app path on macOS", () => {+ assert.equal(+ resolveEgoBrowserCli({+ configured: "",+ platform: "darwin",+ pathExists: (path) => path === MACOS_EGO_LITE_CLI,+ }),+ MACOS_EGO_LITE_CLI,+ );+});++test("real-browser E2E falls back to PATH when no app-specific CLI exists", () => {+ assert.equal(+ resolveEgoBrowserCli({+ platform: "linux",+ pathExists: () => false,+ }),+ "ego-browser",+ );+});diff --git a/package/ego-browser/src/run-output-sink.test.mjs b/package/ego-browser/src/run-output-sink.test.mjsindex 5cee704..aa3f52b 100644--- a/package/ego-browser/src/run-output-sink.test.mjs+++ b/package/ego-browser/src/run-output-sink.test.mjs@@ -5,15 +5,18 @@ import { runMain } from "../dist/src/run.js";// A minimal native ego whose only method reports a hard stop, the same shape the real// bindings return when the user holds (or has not handed over) the task space. The-// `listTaskSpaces` helper lifts it through assertNoEgoError -> buildEgoError, which is+// `listTaskSpaces` helper lifts it through invokeEgo -> buildEgoError, which is// where the sink is told a hard stop occurred.-function hardStopEgo(error_code) {+function hardStopEgo(+ error_code,+ error = "native wording that should never reach the agent",+) {return {calls: 0,async listTaskSpaces() {this.calls += 1;return {- error: "native wording that should never reach the agent",+ error,error_code,};},@@ -144,6 +147,24 @@ test("a swallowed user-control hard stop discards all output and prints the guidassert.ok(ego.calls >= 3, "every iteration should have hit the hard stop");});+test("a permission hard stop discards business output and keeps its specific guidance", async () => {+ const ego = hardStopEgo("EGO_TASK_SPACE_USER_IN_CONTROL", "camera");+ const result = await runScript(+ `+ console.log("before permission");+ try { await listTaskSpaces(); } catch {}+ console.log("after permission");+ `,+ ego,+ );++ assert.equal(result.exitCode, 0);+ assert.match(result.stdout, /camera access/);+ assert.match(result.stdout, /takeOverTaskSpace\(spaceId\)/);+ assert.doesNotMatch(result.stdout, /before permission|after permission/);+ assert.equal(result.stdout.match(/camera access/g).length, 1);+});+test("an inactive / unassigned task space is also a hard stop", async () => {const ego = hardStopEgo("EGO_TASK_SPACE_INACTIVE");const result = await runScript(@@ -166,7 +187,7 @@ test("an inactive / unassigned task space is also a hard stop", async () => {test("a swallowed snapshot hard stop (rejected, not resolved) also collapses to one message", async () => {// snapshot rejects directly instead of resolving with { error }, so it bypasses- // assertNoEgoError; the collapse only works if snapshot() rebuilds it via buildEgoError.+ // invokeEgo; the collapse only works if snapshot() rebuilds it via buildEgoError.const ego = snapshotHardStopEgo("EGO_TASK_SPACE_USER_IN_CONTROL");const result = await runScript(`diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.mdindex b220410..c47e5e3 100644--- a/skills/ego-browser/SKILL.md+++ b/skills/ego-browser/SKILL.md@@ -283,8 +283,8 @@ const receipt = await page.click("#submit");console.log(receipt.popups ?? []);```-Receipts report newly opened Pages and synchronous JavaScript dialogs. A dialog-receipt has `{ dialog }`; handle it with+Receipts report newly opened Pages and may report a synchronous JavaScript dialog+when Ego Lite keeps Agent control. A dialog receipt has `{ dialog }`; handle it with`page.cdp("Page.handleJavaScriptDialog", { accept: true })` or `accept: false`before continuing. The dialog command uses the existing Page session withoutactivating the Page again. After any other action, confirm navigation and page@@ -358,6 +358,8 @@ Use the standard Node.js `fetch()` for background requests that do not need PageStop immediately when the user takes control, or when the space is inactive or not assigned to the Agent. Do not retry or route around the stop. Resume control only after the user explicitly asks to continue.+Browser permission prompts, device choosers, and JavaScript dialogs can cause the same handoff. Ask the user to handle or review the prompt; never grant, deny, or take control back automatically.+When the user must act in the browser, call `await task.handOff()`, end the current round, and tell the user what to do. After the user confirms, resume the original space in the next round:```js