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
complete runtime v2 public API and e2e coverage
Autee1f7fe0b91e1
diff --git a/docs/runtime-v2-architecture.md b/docs/runtime-v2-architecture.mdindex 76ba79a..f041f45 100644--- a/docs/runtime-v2-architecture.md+++ b/docs/runtime-v2-architecture.md@@ -90,6 +90,7 @@ CDP session、事件缓冲、dialog 状态和 Network domain 状态都按 target"usedLabels": ["p1", "p2"],"releasedLabels": [],"initialized": true,+ "handoffBaseline": null,"unmanagedTargets": {"USER_TARGET": "unknown"},@@ -130,6 +131,8 @@ CDP session、事件缓冲、dialog 状态和 Network domain 状态都按 target- 第一次观察一个 space 时,已有 tab 记为 `unknown`,不会猜测它们由谁创建。- 在 Agent 持续控制该 space 时,后来出现的新 tab 会自动加入账本。- 用户控制期间不做自动收编。+- `handOff()` 在交出控制前记录当时的 tab 集合。claim/takeover 后第一次盘点把+ 用户期间新增的 tab 记为 `unknown`,然后恢复 Agent 新 tab 的自动收编。不同 space 使用不同文件。多个进程同时写同一 space 不受支持,可能last-writer-wins。如果未来需要支持,必须使用文件锁或 CAS;不维护只能发现@@ -210,6 +213,7 @@ task.spaceId;task.name;task.ownership;task.page(label);+task.userPage();await task.listPages();await task.openPage(url, { as, timeout });@@ -223,6 +227,8 @@ await task.cdp(method, params, { timeout });````spaceId` 是新版名称。`id` 仅作为已有脚本的兼容别名保留,不进入新版 Skill。+`userPage()` 返回 claim/takeover 完成时用户正在看的 tab;它是边界快照,不是+实时 active-page 查询。用户页仍未受管时,必须先 `adopt()` 才能操作。`finish()` 保留浏览器空间给用户,`close()` 关闭空间;两者成功后都会删除该space 的 Page 标签状态。@@ -270,7 +276,12 @@ worker。返回值为:```js{- (ok, status, statusText, url, headers, body);+ ok,+ status,+ statusText,+ url,+ headers,+ body,}```@@ -389,6 +400,9 @@ await page.evaluate(TaskSpace 提供 `handOff()` 和毫秒制 `waitForControl()`。用户明确要求恢复后,`takeOverTaskSpace(spaceId)` 直接返回新的 TaskSpace;接管 user-owned 或inactive space 时,`claimTaskSpace(spaceId)` 也直接返回 TaskSpace。+claim 以及确实从用户控制返回 Agent 的 takeover,会捕获用户当时激活的 tab,+并完成一次边界盘点。对已由 Agent 控制的 space 重复 takeover,不会重新归类+现有 tab。结束时调用 `task.finish()` 保留浏览器空间,或调用 `task.close()` 关闭空间。`claimTaskSpace()` 和 `takeOverTaskSpace()` 是取得对象前的入口。旧的@@ -417,19 +431,20 @@ SDK 路径不经过 CLI 的 execute 包装,因此在进程生命周期事件claim/takeover 入口;其余旧名称只对已有脚本和显式 legacy 查询可见。不要为了复用新版实现而悄悄改变旧 helper 行为。+V2 API 的签名、options 校验、默认 help manifest 和+`skills/ego-browser/references/api.md` 来自同一份+`package/ego-browser/src/public-api-schema.ts`。旧 helper 继续注入;需要查看时用+`help("legacy")` 或 `help("legacy", "click")`。+站点 site skills 暂时继续使用 legacy surface,后续再按 Page 能力注入方式迁移。-## 11. 剩余工作--下一阶段按下面顺序进行:+## 11. 实施状态-1. 用一份公共 API schema 生成参数校验、`help()` manifest 和 SKILL API- 参考。-2. 默认 help/SKILL 隐藏旧全局 helper,同时保留运行时兼容层和显式 legacy- help。-3. 完成用户页面边界 API。-4. 更新 site skills,再补完整的 v2 真实任务回归。+公共 API schema、默认 V2 help、显式 legacy help、生成式 API 参考和用户页面+边界已经实现。真实 Ego Lite E2E 已覆盖兼容接口、TaskSpace/Page、多 space、+popup 盘点兜底、键鼠、CDP、snapshot 和视觉链路。site skills 暂时保持 legacy+surface,不属于本阶段。不在当前范围内:@@ -448,7 +463,9 @@ claim/takeover 入口;其余旧名称只对已有脚本和显式 legacy 查询- 跨 space 操作按 gate 串行并落到正确 space。- 页面预算在创建前拒绝,错误给出可执行的 close/goto 建议。- 首次存在的 unknown tab 不被自动收编;Agent 控制期间的新 tab 会被收编。-- popup 立即出现和延迟出现两条路径都能进入账本。+- handoff 期间用户新开的 tab 在 takeover 后保持 unknown;`userPage()` 返回边界+ 时激活的 tab。+- popup 可由动作回执立即收编;即使动作回执漏记,后续盘点也会补回账本。- `Page.close()` 确认 tab 消失后才删除标签,最后 tab 有 anchor。- screenshot、evaluate、fetch、键盘和鼠标都操作并激活指定 Page。- 底层键鼠不安装动作探针,高层动作仍能返回导航和 popup 回执。@@ -456,4 +473,6 @@ claim/takeover 入口;其余旧名称只对已有脚本和显式 legacy 查询- snapshot 始终返回全量并标明来源,不接受 `diff`。- 旧格式账本能读取,并在下一次写入时删掉过期字段。- 1.2.3 代表性脚本原样通过。-- `npm test`、真实浏览器 E2E 和 site-skill validation 全绿。+- 默认 help 只展示 V2;显式 legacy help 仍可查询旧 helper。+- API 参考与公共 schema 保持同步。+- `npm test` 和真实浏览器 E2E 全绿。diff --git a/package/ego-browser/package.json b/package/ego-browser/package.jsonindex 1138482..3befa9c 100644--- a/package/ego-browser/package.json+++ b/package/ego-browser/package.json@@ -9,11 +9,13 @@"scripts": {"clean": "rm -rf dist artifacts","build": "node scripts/build.mjs",+ "generate:api-docs": "npm run build && node scripts/generate-api-reference.mjs",+ "check:api-docs": "node scripts/generate-api-reference.mjs --check","e2e": "node scripts/run-real-browser-e2e.mjs","prepare": "if [ \"$CI\" = \"true\" ]; then exit 0; fi; cd ../.. && lefthook install","style:check": "prettier --check","typecheck": "tsc --noEmit",- "test": "npm run build && npm run typecheck && node --test \"src/**/*.test.mjs\" \"test/*.test.js\"",+ "test": "npm run build && npm run check:api-docs && npm run typecheck && node --test \"src/**/*.test.mjs\" \"test/*.test.js\"","validate:learnings": "npm run build && EGO_BROWSER_AGENT_WORKSPACE=../../skills/ego-browser node dist/scripts/validate-site-skills.js","validate:site-skills": "npm run build && EGO_BROWSER_AGENT_WORKSPACE=../../skills/ego-browser node dist/scripts/validate-site-skills.js"},diff --git a/package/ego-browser/scripts/generate-api-reference.mjs b/package/ego-browser/scripts/generate-api-reference.mjsnew file mode 100644index 0000000..643ee27--- /dev/null+++ b/package/ego-browser/scripts/generate-api-reference.mjs@@ -0,0 +1,32 @@+import { readFile, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { format } from "prettier";++import { publicApiMarkdown } from "../dist/src/public-api-schema.js";++const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));+const outputPath = join(+ dirname(dirname(packageRoot)),+ "skills",+ "ego-browser",+ "references",+ "api.md",+);+const expected = await format(publicApiMarkdown(), { parser: "markdown" });++if (process.argv.includes("--check")) {+ let actual = "";+ try {+ actual = await readFile(outputPath, "utf8");+ } catch (error) {+ if (error?.code !== "ENOENT") throw error;+ }+ if (actual !== expected) {+ throw new Error(+ "skills/ego-browser/references/api.md is stale; run npm run generate:api-docs",+ );+ }+} else {+ await writeFile(outputPath, expected, "utf8");+}diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjsindex ace2786..3b6fa0a 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/helper-surface.mjs@@ -53,6 +53,18 @@ export function helperSurfaceCase() {assertEqual(typeof globalThis[name], "function", "helper is installed: " + name);}assertEqual(typeof globalThis.newTab, "undefined", "internal newTab is not exposed");+ const defaultHelp = help();+ assertIncludes(defaultHelp, "TaskSpace.openPage", "default help presents the v2 object API");+ assertIncludes(+ help("click"),+ "Legacy helper hidden from default help",+ "default help hides callable legacy helpers"+ );+ assertIncludes(+ help("legacy", "click"),+ "click",+ "legacy help remains explicitly available"+ );const helpText = help("missingHelperForE2E");assertIncludes(helpText, "Unknown helper", "help reports unknown helper names");`;diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjsindex dbe7323..591165d 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs@@ -1,6 +1,6 @@import { environmentCase } from "./environment.mjs";import { helperSurfaceCase } from "./helper-surface.mjs";-import { taskSpaceCase } from "./task-space.mjs";+import { crossSpaceV2Case, taskSpaceCase } from "./task-space.mjs";import { navigationCase } from "./navigation.mjs";import { observationCase } from "./observation.mjs";import { pointerCase } from "./pointer.mjs";@@ -34,6 +34,7 @@ export const e2eCases = [{ name: "environment initialization", body: environmentCase },{ name: "helper surface", body: helperSurfaceCase },{ name: "task spaces and control", body: taskSpaceCase },+ { name: "v2 cross-space routing", body: crossSpaceV2Case },{ name: "navigation helpers", body: navigationCase },{ name: "observation helpers", body: observationCase },{ name: "pointer and scroll helpers", body: pointerCase },diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjsindex e45dd7f..74a3df3 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/observation.mjs@@ -124,18 +124,21 @@ export function observationCase() {/* iframe interaction — evaluate JS inside the iframe */cliLog(JSON.stringify({ observationStep: "iframe" }));- const frameTarget = await iframeTarget("/frame.html");- if (frameTarget) {- const iframeMarkerText = await js(- "return document.querySelector('#iframe-marker')?.textContent",- frameTarget- );- assertEqual(iframeMarkerText, "iframe target", "js evaluates inside iframe using targetId");-- const iframeTitle = await js("return document.title", frameTarget);- assertEqual(iframeTitle, "ego-lite iframe", "js reads iframe page title via targetId");- } else {- cliLog(JSON.stringify({ iframeWarning: "iframe target not available, skipping iframe tests" }));+ let frameTarget = null;+ const iframeDeadline = Date.now() + 3_000;+ while (!frameTarget && Date.now() <= iframeDeadline) {+ frameTarget = await iframeTarget("/frame.html");+ if (!frameTarget) await wait(0.05);}+ assert(frameTarget, "iframeTarget discovers the cross-site iframe target");++ const iframeMarkerText = await js(+ "return document.querySelector('#iframe-marker')?.textContent",+ frameTarget+ );+ assertEqual(iframeMarkerText, "iframe target", "js evaluates inside iframe using targetId");++ const iframeTitle = await js("return document.title", frameTarget);+ assertEqual(iframeTitle, "ego-lite iframe", "js reads iframe page title via targetId");`;}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.mjsindex a769835..d0eb3ed 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@@ -490,11 +490,15 @@ export function pageActionsAndPopupCase() {});await source.mouse.move(innerScrollPoint.x, innerScrollPoint.y);await source.mouse.wheel(0, 120);- await new Promise((resolve) => setTimeout(resolve, 100));- assert(- await source.evaluate("document.querySelector('#inner-scroll').scrollTop > 0"),- "page.mouse.wheel scrolls the inner container under the current pointer"- );+ let innerScrolled = false;+ for (let attempt = 0; attempt < 20; attempt += 1) {+ innerScrolled = await source.evaluate(+ "document.querySelector('#inner-scroll').scrollTop > 0"+ );+ if (innerScrolled) break;+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ assert(innerScrolled, "page.mouse.wheel scrolls the inner container under the current pointer");assertEqual((await currentTab()).targetId, source.targetId, "Page mouse methods keep their Page active");await source.evaluate(() => {@@ -550,6 +554,21 @@ export function pageActionsAndPopupCase() {"agent","the popup is recorded as agent-created");++ // Simulate the action-receipt window missing this otherwise real popup.+ // listPages must discover the live target independently and restore a+ // managed label; popup lifecycle cannot depend on the short receipt diff.+ const ledgerPath = join(+ process.env.EGO_BROWSER_STATE_DIR,+ "space-" + task.spaceId + ".json"+ );+ const ledger = JSON.parse(await readFile(ledgerPath, "utf8"));+ delete ledger.pages[popup.label];+ await writeFile(ledgerPath, JSON.stringify(ledger));+ const afterReconcile = await task.listPages();+ const reconciledPopup = afterReconcile.find((item) => item.targetId === popup.targetId);+ assert(Boolean(reconciledPopup?.label), "listPages adopts a popup missed by action receipts");+ assertEqual(reconciledPopup.openedBy, "agent", "the reconciled popup keeps Agent origin");assert(unknownBefore.every((targetId) => inventory.find((item) => item.targetId === targetId)?.label === undefined@@ -562,7 +581,7 @@ export function pageActionsAndPopupCase() {"an adopted popup can exceed the budget and backpressure later openPage calls");- await task.page(popup.label).close();+ await reconciledPopup.page.close();await source.close();await comparison.close();await budgetFiller.close();diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjsindex 954dcef..baaa8e9 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/pointer.mjs@@ -84,16 +84,11 @@ export function pointerCase() {"return el?.closest?.('#inner-scroll')?.id || el?.id || '';");assertEqual(innerHit, "inner-scroll", "nested scroll container is under the wheel target");- const innerWheelDispatched = await allowWheelDispatch(- "scroll nested container",- () => scroll(innerCenter.x, innerCenter.y, { dy: 350 })+ await scroll(innerCenter.x, innerCenter.y, { dy: 350 });+ await waitForJsCondition(+ "document.querySelector('#inner-scroll').scrollTop > 0",+ "scroll targets nested scroll containers");- if (innerWheelDispatched) {- await waitForJsCondition(- "document.querySelector('#inner-scroll').scrollTop > 0",- "scroll targets nested scroll containers"- );- }cliLog(JSON.stringify({ pointerStep: "page wheel" }));await resetHome();@@ -102,17 +97,13 @@ export function pointerCase() {"return { x: Math.min(Math.max(rect.left + 20, 10), innerWidth - 10), y: Math.min(Math.max(rect.top + 20, 10), innerHeight - 10) };");const beforeWheel = await pageInfo();- const wheelDispatched = await allowWheelDispatch("scroll wheel", () =>- scroll(wheelPoint.x, wheelPoint.y, { dy: 300 })- );- if (wheelDispatched) {- await waitForJsCondition(- "scrollY > " + JSON.stringify(beforeWheel.sy),- "scroll wheel moves the page down"- );- const afterWheel = await pageInfo();- assert(afterWheel.sy > beforeWheel.sy, "scroll wheel moves the page down");- }+ await scroll(wheelPoint.x, wheelPoint.y, { dy: 300 });+ await waitForJsCondition(+ "scrollY > " + JSON.stringify(beforeWheel.sy),+ "scroll wheel moves the page down"+ );+ const afterWheel = await pageInfo();+ assert(afterWheel.sy > beforeWheel.sy, "scroll wheel moves the page down");await resetHome();const objectWheelPoint = await js(@@ -120,17 +111,13 @@ export function pointerCase() {"return { x: Math.min(Math.max(rect.left + 30, 10), innerWidth - 10), y: Math.min(Math.max(rect.top + 30, 10), innerHeight - 10) };");const beforeObjectWheel = await pageInfo();- const objectWheelDispatched = await allowWheelDispatch("scroll object options", () =>- scroll({ x: objectWheelPoint.x, y: objectWheelPoint.y, dy: 120 })- );- if (objectWheelDispatched) {- await waitForJsCondition(- "scrollY > " + JSON.stringify(beforeObjectWheel.sy),- "scroll object options move the page down"- );- const afterObjectWheel = await pageInfo();- assert(afterObjectWheel.sy > beforeObjectWheel.sy, "scroll object options move the page down");- }+ await scroll({ x: objectWheelPoint.x, y: objectWheelPoint.y, dy: 120 });+ await waitForJsCondition(+ "scrollY > " + JSON.stringify(beforeObjectWheel.sy),+ "scroll object options move the page down"+ );+ const afterObjectWheel = await pageInfo();+ assert(afterObjectWheel.sy > beforeObjectWheel.sy, "scroll object options move the page down");cliLog(JSON.stringify({ pointerStep: "dom scroll helpers" }));await resetHome();diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjsindex 51956e9..c290672 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/runtime.mjs@@ -128,7 +128,7 @@ export function runtimeCase() {"js reports page exceptions");- const helpText = help("click", "fillInput");+ const helpText = help("legacy", "click", "fillInput");assertIncludes(helpText, "click", "help returns helper documentation");assertIncludes(helpText, "fillInput", "help returns multiple helper docs");diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjsindex bbfdf96..18d5a2b 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/task-space.mjs@@ -21,7 +21,7 @@ export function taskSpaceCase() {assertEqual(switchedByNumericString.id, task.id, "switchTaskSpace selects by numeric string id");await waitForAgentControl(taskName, { interval: 0.1, timeout: 3 });- await takeOverTaskSpace(taskName);+ await takeOverTaskSpace();await waitForAgentControl(taskName, { interval: 0.1, timeout: 3 });const scratch = await newTaskSpace(taskName + " scratch");@@ -82,8 +82,52 @@ export function taskSpaceCase() {await handOffTaskSpace();await takeOverTaskSpace();await waitForAgentControl(taskName, { interval: 0.1, timeout: 5 });- await handOffTaskSpace(taskName);- await takeOverTaskSpace(taskName);- await waitForAgentControl(taskName, { interval: 0.1, timeout: 5 });+ const v2Task = await taskSpace(taskName + " v2 lifecycle");+ await v2Task.openPage(baseUrl + "/secondary?v2-lifecycle=handoff");+ await v2Task.handOff();+ const resumedTask = await takeOverTaskSpace(v2Task.spaceId);+ await resumedTask.waitForControl({ interval: 100, timeout: 5_000 });+ const boundaryPage = resumedTask.userPage();+ assert(Boolean(boundaryPage), "takeover captures the tab active at the user boundary");+ const closeSpaceId = resumedTask.spaceId;+ await resumedTask.close();+ for (let attempt = 0; attempt < 20; attempt += 1) {+ if (!(await listTaskSpaces()).some((space) => space.id === closeSpaceId)) break;+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ assert(+ !(await listTaskSpaces()).some((space) => space.id === closeSpaceId),+ "task.close removes the v2 task space"+ );++ const finishTask = await taskSpace(taskName + " v2 finish");+ await finishTask.openPage(baseUrl + "/secondary?v2-lifecycle=finish");+ const finishSpaceId = finishTask.spaceId;+ await finishTask.finish();+ assert(+ (await listTaskSpaces()).some((space) => space.id === finishSpaceId),+ "task.finish keeps the browser space for the user"+ );+ const reclaimedFinishedTask = await claimTaskSpace(finishSpaceId);+ await reclaimedFinishedTask.close();+ `;+}++export function crossSpaceV2Case() {+ return `+ const firstTask = await taskSpace(taskName + " gate first");+ const firstPage = await firstTask.openPage(baseUrl + "/?space=first");+ const secondTask = await taskSpace(taskName + " gate second");+ const secondPage = await secondTask.openPage(baseUrl + "/secondary?space=second");++ const [firstInfo, secondInfo] = await Promise.all([+ firstPage.info(),+ secondPage.info(),+ ]);+ assertIncludes(firstInfo.url, "space=first", "cross-space gate keeps the first request in its space");+ assertIncludes(secondInfo.url, "space=second", "cross-space gate keeps the second request in its space");++ await firstTask.close();+ await secondTask.close();`;}diff --git a/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs b/package/ego-browser/scripts/real-browser-e2e/ego-source.mjsindex 6f56547..7c3b1eb 100644--- a/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/ego-source.mjs@@ -108,20 +108,6 @@ export function egoSource(body, context) {throw new Error(message + detail + ": condition stayed false, last value " + JSON.stringify(last));}- async function allowWheelDispatch(label, fn) {- try {- await fn();- return true;- } catch (error) {- const message = error?.message || String(error);- if (/Input\\.dispatchMouseEvent|CDP request timed out: Input\\.dispatchMouseEvent/.test(message)) {- cliLog(JSON.stringify({ inputDispatchWarning: { label, message } }));- return false;- }- throw error;- }- }-async function setStableViewport() {await cdp("Page.bringToFront").catch(() => {});await cdp("Emulation.clearDeviceMetricsOverride").catch(() => {});diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjsindex ed7c7d3..d871991 100644--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs@@ -14,6 +14,7 @@ export async function closeFixtureServer(fixtureServer) {}export async function startFixtureServer(taskName) {+ let crossSiteBaseUrl = "";const fixtureServer = createServer((req, res) => {const url = new URL(req.url || "/", "http://127.0.0.1");if (url.pathname === "/healthz") {@@ -149,7 +150,7 @@ export async function startFixtureServer(taskName) {}if (url.pathname === "/frame.html") {res.writeHead(200, { "content-type": "text/html" });- res.end(pageHtml("frame"));+ res.end(pageHtml("frame", { iframeUrl: null }));return;}if (url.pathname === "/nav-target") {@@ -184,7 +185,7 @@ export async function startFixtureServer(taskName) {return;}res.writeHead(200, { "content-type": "text/html" });- res.end(pageHtml("home"));+ res.end(pageHtml("home", { iframeUrl: `${crossSiteBaseUrl}/frame.html` }));});await new Promise((resolve, reject) => {@@ -192,13 +193,14 @@ export async function startFixtureServer(taskName) {fixtureServer.listen(0, "127.0.0.1", () => resolve());});const address = fixtureServer.address();+ crossSiteBaseUrl = `http://localhost:${address.port}`;return {server: fixtureServer,baseUrl: `http://127.0.0.1:${address.port}`,};}-function pageHtml(kind) {+function pageHtml(kind, { iframeUrl = "/frame.html" } = {}) {const title =kind === "nav-target"? "ego-lite nav target"@@ -307,7 +309,7 @@ function pageHtml(kind) {</div><div id="delayed">Delayed element</div><div id="never-visible" style="display:none">Never visible</div>- <iframe id="fixture-frame" src="/frame.html"></iframe>+ ${iframeUrl ? `<iframe id="fixture-frame" src="${iframeUrl}"></iframe>` : ""}<div id="inner-scroll"><div id="inner-scroll-content">Inner scroll marker</div></div><section id="scroll-area"><div id="bottom-marker">Bottom marker</div></section><label>Email input <input id="email-input" type="email" value="[email protected]"></label>diff --git a/package/ego-browser/src/browser-runtime.ts b/package/ego-browser/src/browser-runtime.tsindex cdf07fb..d7b64d0 100644--- a/package/ego-browser/src/browser-runtime.ts+++ b/package/ego-browser/src/browser-runtime.ts@@ -141,8 +141,10 @@ export async function browserCdp(timeoutMs = RESPONSE_TIMEOUT_MS,) {// Test mock: cdpOverride bypasses everything including session injection.+ // Include the effective timeout so tests can verify timing contracts without+ // waiting for a real CDP deadline.if (state.cdpOverride) {- return state.cdpOverride(method, params, sessionId);+ return state.cdpOverride(method, params, sessionId, timeoutMs);}const explicit = sessionId !== undefined;let effective = sessionId;diff --git a/package/ego-browser/src/driver/pointer.test.mjs b/package/ego-browser/src/driver/pointer.test.mjsindex f842762..c3b5e3f 100644--- a/package/ego-browser/src/driver/pointer.test.mjs+++ b/package/ego-browser/src/driver/pointer.test.mjs@@ -73,8 +73,8 @@ test("scroll defaults to scrolling down (positive deltaY, DOM wheel convention)"// scroll, matching scrollBy / scrollToBottomUntil.const calls = [];const restore = setOverrides({- cdpOverride(method, params) {- calls.push({ method, params });+ cdpOverride(method, params, sessionId, timeoutMs) {+ calls.push({ method, params, sessionId, timeoutMs });return {};},});@@ -87,6 +87,11 @@ test("scroll defaults to scrolling down (positive deltaY, DOM wheel convention)"assert.equal(calls[0].method, "Input.dispatchMouseEvent");assert.equal(calls[0].params.deltaY, 300);assert.equal(calls[0].params.deltaX, 0);+ assert.equal(+ calls[0].timeoutMs,+ 15_000,+ "wheel dispatch uses the normal CDP timeout instead of a fragile one-second deadline",+ );});test("scroll falls back to DOM scrolling only when wheel dispatch is unsupported", async () => {diff --git a/package/ego-browser/src/driver/pointer.ts b/package/ego-browser/src/driver/pointer.tsindex 8b7c36b..9170d9a 100644--- a/package/ego-browser/src/driver/pointer.ts+++ b/package/ego-browser/src/driver/pointer.ts@@ -486,7 +486,10 @@ export async function scroll(deltaY: options.dy ?? 300,};try {- await browserCdp("Input.dispatchMouseEvent", params, undefined, 1000);+ // Chromium may acknowledge wheel input only after the compositor has+ // processed it. Use the normal CDP deadline; retrying a timed-out wheel is+ // unsafe because the original event may still be applied later.+ await browserCdp("Input.dispatchMouseEvent", params);} catch (error) {// Degrade to DOM scrolling only when the target genuinely cannot dispatch// wheel events. Everything else (timeouts, "user is controlling", sessiondiff --git a/package/ego-browser/src/help-runtime.ts b/package/ego-browser/src/help-runtime.tsindex d64ebd1..24cb83d 100644--- a/package/ego-browser/src/help-runtime.ts+++ b/package/ego-browser/src/help-runtime.ts@@ -2,6 +2,12 @@ import { readFileSync } from "node:fs";import { fileURLToPath } from "node:url";import { parse } from "acorn";+import {+ PUBLIC_API_SCHEMA,+ publicApiEntry,+ type PublicApiEntry,+} from "./public-api-schema.js";+type ParamInfo = {name: string;type: string | null;@@ -11,33 +17,61 @@ type ParamInfo = {default: string | null;};-type HelperDoc = {+export type HelperDoc = {name: string;signature: string;description: string | null;params: ParamInfo[];returns: string | null;async: boolean;+ public?: boolean;};let cache: Map<string, HelperDoc> | null = null;-export function help(helpers: Record<string, unknown>, ...names: string[]): HelperDoc | HelperDoc[] | string {+export function help(+ helpers: Record<string, unknown>,+ ...names: string[]+): HelperDoc | HelperDoc[] | string {const docs = getDocsMap();if (names.length === 0) {- const all = [...docs.values()].filter((d) => d.name in helpers);- return all;+ return PUBLIC_API_SCHEMA.map(publicEntryToHelpDoc);+ }+ if (names[0] === "legacy") {+ if (names.length === 1) {+ return [...docs.values()].filter(+ (doc) => doc.name in helpers && !publicApiEntry(doc.name),+ );+ }+ return helpLegacyNames(docs, names.slice(1));}if (names.length === 1) {- const doc = docs.get(names[0]);- if (!doc) return `Unknown helper: ${names[0]}`;- return doc;+ const publicEntry = findPublicEntry(names[0]);+ if (publicEntry) return publicEntryToHelpDoc(publicEntry);+ if (names[0] in helpers) {+ return `Legacy helper hidden from default help: ${names[0]}. Use help("legacy", "${names[0]}").`;+ }+ return `Unknown helper: ${names[0]}`;}- return names.map((n) => docs.get(n) || { name: n, signature: n, description: null, params: [], returns: null, async: false });+ return names.map((name) => {+ const publicEntry = findPublicEntry(name);+ if (publicEntry) return publicEntryToHelpDoc(publicEntry);+ return {+ name,+ signature: name,+ description: `Legacy helper hidden from default help. Use help("legacy", "${name}").`,+ params: [],+ returns: null,+ async: false,+ };+ });}export function formatHelp(doc: HelperDoc): string {const lines: string[] = [];+ if (doc.public) {+ lines.push(doc.name, "");+ }if (doc.description) {lines.push(doc.description);}@@ -46,7 +80,9 @@ export function formatHelp(doc: HelperDoc): string {const type = p.type ? `: ${p.type}` : "";const desc = p.description ? ` — ${p.description}` : "";const def = p.default ? ` (default: ${p.default})` : "";- lines.push(`@param ${p.rest ? "..." : ""}${p.name}${opt}${type}${desc}${def}`);+ lines.push(+ `@param ${p.rest ? "..." : ""}${p.name}${opt}${type}${desc}${def}`,+ );}if (doc.returns) {lines.push(`@returns ${doc.returns}`);@@ -69,7 +105,7 @@ function getDocsMap(): Map<string, HelperDoc> {ecmaVersion: "latest",sourceType: "module",onComment: comments,- locations: true+ locations: true,});} catch {return cache;@@ -92,11 +128,13 @@ function getDocsMap(): Map<string, HelperDoc> {const params = extractParams(node, parsed);const isAsync = node.async === true;- const paramSig = params.map((p) => {- const rest = p.rest ? "..." : "";- const opt = p.optional ? "?" : "";- return `${rest}${p.name}${opt}`;- }).join(", ");+ const paramSig = params+ .map((p) => {+ const rest = p.rest ? "..." : "";+ const opt = p.optional ? "?" : "";+ return `${rest}${p.name}${opt}`;+ })+ .join(", ");const retStr = parsed?.returns || (isAsync ? "Promise<...>" : null);const signature = `${name}(${paramSig})${retStr ? ` → ${retStr}` : ""}`;@@ -106,7 +144,7 @@ function getDocsMap(): Map<string, HelperDoc> {description: parsed?.description || null,params,returns: retStr,- async: isAsync+ async: isAsync,});});@@ -120,6 +158,51 @@ function getDocsMap(): Map<string, HelperDoc> {return cache;}+function helpLegacyNames(+ docs: Map<string, HelperDoc>,+ names: string[],+): HelperDoc | HelperDoc[] | string {+ const resolved = names+ .map((name) => docs.get(name))+ .filter(Boolean) as HelperDoc[];+ if (resolved.length !== names.length) {+ const missing = names.find((name) => !docs.has(name));+ return `Unknown legacy helper: ${missing}`;+ }+ return resolved.length === 1 ? resolved[0] : resolved;+}++function findPublicEntry(name: string): PublicApiEntry | undefined {+ const normalized = name+ .replace(/^task\./, "TaskSpace.")+ .replace(/^page\./, "Page.");+ return publicApiEntry(normalized);+}++function publicEntryToHelpDoc(entry: PublicApiEntry): HelperDoc {+ const options = entry.options+ ? Object.entries(entry.options)+ .map(([name, specification]) => {+ const values = specification.values+ ? ` (${specification.values.join(" | ")})`+ : "";+ return `${name}${values}: ${specification.description}`;+ })+ .join(" ")+ : "";+ return {+ name: entry.name,+ signature: entry.signature,+ description: options+ ? `${entry.summary} Options: ${options}`+ : entry.summary,+ params: [],+ returns: null,+ async: entry.signature.startsWith("await "),+ public: true,+ };+}+function readSelf(): string | null {try {const selfPath = fileURLToPath(import.meta.url);@@ -131,11 +214,15 @@ function readSelf(): string | null {function walkFunctions(node: any, visitor: (node: any) => void) {if (!node || typeof node !== "object") return;- if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression") {+ if (+ node.type === "FunctionDeclaration" ||+ node.type === "FunctionExpression"+ ) {visitor(node);}for (const key of Object.keys(node)) {- if (key === "type" || key === "loc" || key === "start" || key === "end") continue;+ if (key === "type" || key === "loc" || key === "start" || key === "end")+ continue;const child = node[key];if (Array.isArray(child)) {for (const item of child) {@@ -147,7 +234,10 @@ function walkFunctions(node: any, visitor: (node: any) => void) {}}-function walkAliases(node: any, visitor: (name: string, target: string) => void) {+function walkAliases(+ node: any,+ visitor: (name: string, target: string) => void,+) {if (!node || typeof node !== "object") return;if (node.type === "VariableDeclaration") {for (const decl of node.declarations || []) {@@ -157,7 +247,8 @@ function walkAliases(node: any, visitor: (name: string, target: string) => void)}}for (const key of Object.keys(node)) {- if (key === "type" || key === "loc" || key === "start" || key === "end") continue;+ if (key === "type" || key === "loc" || key === "start" || key === "end")+ continue;const child = node[key];if (Array.isArray(child)) {for (const item of child) {@@ -181,14 +272,18 @@ function extractParams(node: any, jsdoc: ParsedJSDoc | null): ParamInfo[] {return {...info,type: jsdocParam?.type || null,- description: jsdocParam?.description || null+ description: jsdocParam?.description || null,};});}type ParsedJSDoc = {description: string | null;- params: Array<{ name: string; type: string | null; description: string | null }>;+ params: Array<{+ name: string;+ type: string | null;+ description: string | null;+ }>;returns: string | null;};@@ -199,10 +294,16 @@ function parseJSDoc(raw: string): ParsedJSDoc {let returns: string | null = null;for (const line of lines) {- const paramMatch = line.match(/^@param\s+(?:\{([^}]*)\}\s+)?(\[?\w+\]?)(?:(?:\s+[-–—]\s*|\s+)(.+))?\s*$/);+ const paramMatch = line.match(+ /^@param\s+(?:\{([^}]*)\}\s+)?(\[?\w+\]?)(?:(?:\s+[-–—]\s*|\s+)(.+))?\s*$/,+ );if (paramMatch) {const name = paramMatch[2].replace(/^\[|\]$/g, "");- params.push({ name, type: paramMatch[1] || null, description: paramMatch[3] || null });+ params.push({+ name,+ type: paramMatch[1] || null,+ description: paramMatch[3] || null,+ });continue;}const returnsMatch = line.match(/^@returns?\s+(?:\{([^}]*)\}\s*)?(.*)/);@@ -217,11 +318,16 @@ function parseJSDoc(raw: string): ParsedJSDoc {return {description: descLines.join(" ").trim() || null,params,- returns+ returns,};}-function resolveParam(node: any): { name: string; optional: boolean; rest: boolean; default: string | null } {+function resolveParam(node: any): {+ name: string;+ optional: boolean;+ rest: boolean;+ default: string | null;+} {if (node.type === "RestElement") {const inner = resolveParam(node.argument);return { ...inner, rest: true, optional: true };@@ -235,7 +341,9 @@ function resolveParam(node: any): { name: string; optional: boolean; rest: boolereturn { name: node.name, optional: false, rest: false, default: null };}if (node.type === "ObjectPattern") {- const props = (node.properties || []).map((p: any) => p.key?.name || "?").join(", ");+ const props = (node.properties || [])+ .map((p: any) => p.key?.name || "?")+ .join(", ");return { name: `{${props}}`, optional: false, rest: false, default: null };}if (node.type === "ArrayPattern") {diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjsindex ac056ae..3c3888c 100644--- a/package/ego-browser/src/helpers.test.mjs+++ b/package/ego-browser/src/helpers.test.mjs@@ -242,7 +242,9 @@ test("newTaskSpace creates and selects an agent task space", async () => {{async createTaskSpace(name) {calls.push(["createTaskSpace", name]);- return { taskId: name, id: 7, name, ownership: "agent" };+ // Ego Lite's create result may omit ownership even though creation by+ // this API always produces an Agent-owned space.+ return { taskId: name, id: 7, name };},useTaskSpace(taskId) {calls.push(["useTaskSpace", taskId]);@@ -424,6 +426,10 @@ test("claimTaskSpace returns a TaskSpace after claiming and selecting", async ()calls.push(["useTaskSpace", taskId]);return taskId;},+ async listTabs() {+ calls.push(["listTabs"]);+ return { tabs: [] };+ },},async () => {const task = await claimTaskSpace("checkout-flow");@@ -441,6 +447,8 @@ test("claimTaskSpace returns a TaskSpace after claiming and selecting", async ()["listTaskSpaces"],["claimTaskSpace", 7, "checkout-flow"],["useTaskSpace", 7],+ ["useTaskSpace", 7],+ ["listTabs"],]);});@@ -467,6 +475,10 @@ test("takeOverTaskSpace returns a TaskSpace when a space is specified", async ()async takeOverTaskSpace() {calls.push(["takeOverTaskSpace"]);},+ async listTabs() {+ calls.push(["listTabs"]);+ return { tabs: [] };+ },},async () => {const task = await takeOverTaskSpace(7);@@ -475,6 +487,48 @@ test("takeOverTaskSpace returns a TaskSpace when a space is specified", async ()assert.equal(typeof task.openPage, "function");},);+ assert.deepEqual(calls, [+ ["listTaskSpaces"],+ ["useTaskSpace", 7],+ ["takeOverTaskSpace"],+ ["useTaskSpace", 7],+ ["listTabs"],+ ]);+});++test("takeOverTaskSpace does not invent a user boundary when Agent already controls the space", async () => {+ const calls = [];+ await withEgo(+ {+ async listTaskSpaces() {+ calls.push(["listTaskSpaces"]);+ return {+ taskSpaces: [+ {+ taskId: "checkout-flow",+ id: 7,+ name: "checkout-flow",+ ownership: "agent",+ },+ ],+ };+ },+ async useTaskSpace(id) {+ calls.push(["useTaskSpace", id]);+ },+ async takeOverTaskSpace() {+ calls.push(["takeOverTaskSpace"]);+ },+ async listTabs() {+ calls.push(["listTabs"]);+ return { tabs: [] };+ },+ },+ async () => {+ const task = await takeOverTaskSpace(7);+ assert.equal(task.userPage(), undefined);+ },+ );assert.deepEqual(calls, [["listTaskSpaces"],["useTaskSpace", 7],diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.tsindex bac8803..b073174 100644--- a/package/ego-browser/src/helpers.ts+++ b/package/ego-browser/src/helpers.ts@@ -13,7 +13,10 @@ import * as observe from "./driver/observe.js";import * as waits from "./driver/waits.js";import * as files from "./driver/files.js";import { browserFetch, serverFetch } from "./http.js";-import { createTaskSpaceHandle } from "./page-model.js";+import {+ captureTaskSpaceUserBoundary,+ createTaskSpaceHandle,+} from "./page-model.js";import {loadBrowserToolSource,loadLearnedContext,@@ -149,7 +152,13 @@ export async function newTaskSpace(name) {throw new Error("newTaskSpace returned an invalid task space");}taskSpaceNumericId(created, "newTaskSpace");- return selectTaskSpace(ego, created, "newTaskSpace");+ // The native create response currently omits ownership on some Ego Lite+ // builds. Creation through this Agent API is itself authoritative.+ return selectTaskSpace(+ ego,+ { ...created, ownership: created.ownership || "agent" },+ "newTaskSpace",+ );}/**@@ -204,7 +213,9 @@ export async function taskSpace(nameOrId) {export async function claimTaskSpace(nameOrId) {const space = await findTaskSpace(nameOrId);const claimed = await claimResolvedTaskSpace(space, "claimTaskSpace");- return createTaskSpaceHandle({ ...claimed, ownership: "agent" });+ const task = createTaskSpaceHandle({ ...claimed, ownership: "agent" });+ await captureTaskSpaceUserBoundary(task);+ return task;}async function claimResolvedTaskSpace(space, op = "claimTaskSpace") {@@ -337,7 +348,14 @@ export async function takeOverTaskSpace(nameOrId?: string | number) {}assertNoEgoError(await ego.takeOverTaskSpace(), "takeOverTaskSpace");if (descriptor) {- return createTaskSpaceHandle({ ...descriptor, ownership: "agent" });+ const task = createTaskSpaceHandle({ ...descriptor, ownership: "agent" });+ // Repeatedly ensuring control over an already agent-controlled space is a+ // no-op, not a user interaction boundary. Only delegated spaces can have+ // gained tabs through user activity since the Agent last controlled them.+ if (descriptor.ownership === "agentDelegatedToUser") {+ await captureTaskSpaceUserBoundary(task);+ }+ return task;}}diff --git a/package/ego-browser/src/page-ledger.test.mjs b/package/ego-browser/src/page-ledger.test.mjsindex c61ec6a..c5d6a5f 100644--- a/package/ego-browser/src/page-ledger.test.mjs+++ b/package/ego-browser/src/page-ledger.test.mjs@@ -65,6 +65,7 @@ test("writes use a complete atomic ledger document", async () => {usedLabels: ["p1"],releasedLabels: [],initialized: true,+ handoffBaseline: null,unmanagedTargets: {},pages: {p1: {@@ -230,6 +231,35 @@ test("reconciliation protects the first control baseline and adopts later agent});});+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"]);++ const secondRound = new PageLedgerStore({ rootDir });+ const afterTakeover = await secondRound.reconcile(+ 8,+ ["target-agent", "target-user"],+ { autoAdoptNew: true },+ );++ assert.equal(afterTakeover.handoffBaseline, null);+ assert.equal(afterTakeover.unmanagedTargets["target-user"], "unknown");+ assert.deepEqual(afterTakeover.pages, {+ p1: { targetId: "target-agent", openedBy: "agent" },+ });++ const laterAgentPopup = await secondRound.reconcile(+ 8,+ ["target-agent", "target-user", "target-popup"],+ { autoAdoptNew: true },+ );+ assert.equal(laterAgentPopup.pages.p2.targetId, "target-popup");+ assert.equal(laterAgentPopup.pages.p2.openedBy, "agent");+ });+});+test("an explicitly unmanaged anchor is not adopted during reconciliation", async () => {await withTempLedger(async (rootDir) => {const store = new PageLedgerStore({ rootDir });diff --git a/package/ego-browser/src/page-ledger.ts b/package/ego-browser/src/page-ledger.tsindex 41171aa..61b0463 100644--- a/package/ego-browser/src/page-ledger.ts+++ b/package/ego-browser/src/page-ledger.ts@@ -20,6 +20,7 @@ export type PageLedger = {usedLabels: string[];releasedLabels: string[];initialized: boolean;+ handoffBaseline: string[] | null;unmanagedTargets: Record<string, PageOrigin>;pages: Record<string, PageLedgerEntry>;};@@ -35,6 +36,7 @@ type AddPageOptions = {type ReconcileOptions = {autoAdoptNew?: boolean;+ afterUserControl?: boolean;};/**@@ -177,6 +179,28 @@ 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);+ await this.#update(spaceId, (ledger) => {+ ledger.handoffBaseline = targetIds;+ });+ }++ /** 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;+ });+ }+async reconcile(spaceId: number,liveTargetIds: Iterable<string>,@@ -198,12 +222,18 @@ export class PageLedgerStore {(targetId) => !knownTargets.has(targetId),);const needsInitialization = !current.initialized;+ const protectsUserTabs =+ options.afterUserControl || current.handoffBaseline !== null;const shouldAdopt =- current.initialized && options.autoAdoptNew && newTargets.length > 0;+ current.initialized &&+ options.autoAdoptNew &&+ !protectsUserTabs &&+ newTargets.length > 0;if (!hasMissingPage &&!hasMissingUnmanaged &&!needsInitialization &&+ !protectsUserTabs &&!shouldAdopt) {return current;@@ -233,6 +263,14 @@ export class PageLedgerStore {ledger.unmanagedTargets[targetId] = "unknown";}ledger.initialized = true;+ ledger.handoffBaseline = null;+ return;+ }+ if (protectsUserTabs) {+ for (const targetId of untracked) {+ ledger.unmanagedTargets[targetId] = "unknown";+ }+ ledger.handoffBaseline = null;return;}if (!options.autoAdoptNew) return;@@ -306,6 +344,7 @@ function emptyLedger(spaceId: number): PageLedger {usedLabels: [],releasedLabels: [],initialized: false,+ handoffBaseline: null,unmanagedTargets: {},pages: {},};@@ -336,6 +375,7 @@ function validateLedger(// instead of silently adopting pre-existing user tabs.const releasedLabels = stored.releasedLabels ?? [];const initialized = stored.initialized ?? false;+ const handoffBaseline = stored.handoffBaseline ?? null;const unmanagedTargets = stored.unmanagedTargets ?? {};if (stored.spaceId !== expectedSpaceId ||@@ -351,6 +391,11 @@ function validateLedger(Object.hasOwn(stored.pages || {}, label),) ||typeof initialized !== "boolean" ||+ (handoffBaseline !== null &&+ (!Array.isArray(handoffBaseline) ||+ handoffBaseline.some(+ (targetId) => typeof targetId !== "string" || targetId.length === 0,+ ))) ||!unmanagedTargets ||typeof unmanagedTargets !== "object" ||Array.isArray(unmanagedTargets) ||@@ -388,6 +433,8 @@ function validateLedger(usedLabels: [...stored.usedLabels],releasedLabels: [...releasedLabels],initialized,+ handoffBaseline:+ handoffBaseline === null ? null : [...new Set(handoffBaseline)],unmanagedTargets: { ...unmanagedTargets },pages,};diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjsindex 46a85cb..c488a5c 100644--- a/package/ego-browser/src/page-model.test.mjs+++ b/package/ego-browser/src/page-model.test.mjs@@ -6,7 +6,10 @@ import { join } from "node:path";import { NativeOperationGate } from "../dist/src/native-gate.js";import { PageLedgerStore } from "../dist/src/page-ledger.js";-import { createTaskSpaceHandle } from "../dist/src/page-model.js";+import {+ captureTaskSpaceUserBoundary,+ createTaskSpaceHandle,+} from "../dist/src/page-model.js";import { PageRefRegistry } from "../dist/src/page-ref-registry.js";async function withFixture(fn) {@@ -328,6 +331,10 @@ function createFixture(rootDir) {rootDir,services,tabs,+ addExternalTab(targetId, url, { active = false } = {}) {+ tabs.set(targetId, { targetId, url, title: url, active });+ if (active) activeTarget = targetId;+ },openPopupOnNextClick(url) {popupOnNextClick = url;},@@ -423,6 +430,23 @@ test("TaskSpace.waitForControl times out in milliseconds and validates options",});});+test("v2 methods reject option fields that are absent from the public schema", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ await assert.rejects(+ () => task.openPage("https://example.test/unknown", { reuse: true }),+ /task\.openPage received unknown option: reuse/,+ );+ assert.equal(fixture.tabs.size, 0, "validation runs before creating a tab");++ const page = await task.openPage("https://example.test/options");+ await assert.rejects(+ () => page.click("button", { force: true }),+ /page\.click received unknown option: force/,+ );+ });+});+test("TaskSpace uses spaceId and owns handoff, finish, and close", async () => {await withFixture(async (fixture) => {const lifecycleCalls = [];@@ -469,6 +493,55 @@ test("TaskSpace uses spaceId and owns handoff, finish, and close", async () => {});});+test("handoff preserves user-created tabs as unknown and captures the active user page", async () => {+ await withFixture(async (fixture) => {+ const firstRound = taskForRound(fixture, "round-a", {+ async handOffTaskSpace() {},+ });+ const agentPage = await firstRound.openPage("https://example.test/agent");+ await firstRound.handOff();+ assert.equal(agentPage.label, "p1");+ fixture.addExternalTab("target-user", "https://example.test/user-created", {+ active: true,+ });++ const afterTakeover = taskForRound(fixture, "round-b");+ await captureTaskSpaceUserBoundary(afterTakeover);+ const userPage = afterTakeover.userPage();+ assert(userPage, "takeover captures the tab the user was viewing");+ assert.equal(userPage.targetId, "target-user");+ assert.equal(userPage.openedBy, "unknown");++ const inventory = await afterTakeover.listPages();+ const userItem = inventory.find((item) => item.targetId === "target-user");+ assert.equal(userItem.label, undefined);+ assert.equal(userItem.openedBy, "unknown");++ fixture.addExternalTab("target-popup", "https://example.test/agent-popup");+ const reconciled = await afterTakeover.listPages();+ assert.equal(+ reconciled.find((item) => item.targetId === "target-popup").openedBy,+ "agent",+ );+ });+});++test("failed native handoff removes the pending user-control boundary", async () => {+ await withFixture(async (fixture) => {+ const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });+ const task = taskForRound(fixture, "round-a", {+ ledger,+ async handOffTaskSpace() {+ throw new Error("native handoff failed");+ },+ });+ await task.openPage("https://example.test/agent");++ await assert.rejects(() => task.handOff(), /native handoff failed/);+ assert.equal((await ledger.read(7)).handoffBaseline, null);+ });+});+test("TaskSpace keeps Page state when native finish fails", async () => {await withFixture(async (fixture) => {const ledger = new PageLedgerStore({ rootDir: fixture.rootDir });@@ -797,8 +870,8 @@ test("Page fetch validates its JSON options and millisecond timeout", async () =/does not accept options.signal/,);await assert.rejects(- () => page.fetch("/api/text", cyclic),- /options must be JSON-serializable/,+ () => page.fetch("/api/text", { headers: cyclic }),+ /headers must be an object with string values/,);});});diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex f4583eb..4d149d2 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -59,6 +59,7 @@ import {type PageOrigin,} from "./page-ledger.js";import { PageRefRegistry } from "./page-ref-registry.js";+import { validatePublicApiOptions } from "./public-api-schema.js";import { parseRef, type RefMap } from "./ref-map.js";import { state } from "./state.js";@@ -172,10 +173,15 @@ type LedgerPort = {targetId: string,openedBy?: PageOrigin,): Promise<void>;+ beginUserControl(+ spaceId: number,+ liveTargetIds: Iterable<string>,+ ): Promise<void>;+ cancelUserControl(spaceId: number): Promise<void>;reconcile(spaceId: number,liveTargetIds: Iterable<string>,- options?: { autoAdoptNew?: boolean },+ options?: { autoAdoptNew?: boolean; afterUserControl?: boolean },): Promise<PageLedger>;};@@ -275,6 +281,7 @@ class PageMouse {y: number,options: PageMouseClickOptions = {},): Promise<PageActionReceipt> {+ validatePublicApiOptions("Page.mouse.click", options);const receipt = await this.#runObserved((services, sessionId) =>clickPointInPage(services,@@ -297,6 +304,7 @@ class PageMouse {y: number,options: PageMouseMoveOptions = {},): Promise<void> {+ validatePublicApiOptions("Page.mouse.move", options);await this.#run((services, sessionId) =>moveMouseInPage(services, sessionId, this.#x, this.#y, x, y, {...options,@@ -310,6 +318,7 @@ class PageMouse {}async down(options: PageMouseButtonOptions = {}): Promise<void> {+ validatePublicApiOptions("Page.mouse.down", options);const button = options.button ?? "left";const nextButtons = this.#buttons | mouseButtonMask(button);await this.#run((services, sessionId) =>@@ -329,6 +338,7 @@ class PageMouse {}async up(options: PageMouseButtonOptions = {}): Promise<void> {+ validatePublicApiOptions("Page.mouse.up", options);const button = options.button ?? "left";const nextButtons = this.#buttons & ~mouseButtonMask(button);await this.#run((services, sessionId) =>@@ -395,6 +405,7 @@ class PageKeyboard {chord: string,options: PageKeyboardPressOptions = {},): Promise<PageActionReceipt> {+ validatePublicApiOptions("Page.keyboard.press", options);return (await this.#controller.press(chord, options)) as PageActionReceipt;}@@ -406,6 +417,7 @@ class PageKeyboard {text: string,options: PageKeyboardTypeOptions = {},): Promise<void> {+ validatePublicApiOptions("Page.keyboard.type", options);await this.#controller.type(text, options);}}@@ -426,6 +438,7 @@ class PageBudgetError extends Error {let defaultLedger: PageLedgerStore | undefined;const defaultPageRefs = new PageRefRegistry();const unmanagedPageConstructorToken = Symbol("UnmanagedPage");+const captureUserBoundaryToken = Symbol("captureUserBoundary");const defaultGate: OperationGate = {withSpace: defaultWithSpace,@@ -539,6 +552,16 @@ export function createTaskSpaceHandle(return new TaskSpace(descriptor, services);}+/**+ * Capture the active tab at a claim/takeover boundary before Agent actions can+ * change it. This is called by the helper layer and is not injected directly.+ */+export async function captureTaskSpaceUserBoundary(+ task: TaskSpace,+): Promise<void> {+ await task.captureUserBoundary(captureUserBoundaryToken);+}+class TaskSpace {readonly taskId?: string | number;readonly id: number;@@ -547,6 +570,7 @@ class TaskSpace {readonly ownership?: string;readonly recentTabTitles?: string[];readonly #services: PageModelServices;+ #userPage?: Page | UnmanagedPage;constructor(descriptor: TaskSpaceDescriptor, services: PageModelServices) {this.taskId = descriptor.taskId;@@ -567,6 +591,37 @@ class TaskSpace {return new Page(this, label, this.#services);}+ /** The tab active at the most recent claim/takeover boundary, if any. */+ userPage(): Page | UnmanagedPage | undefined {+ return this.#userPage;+ }++ async captureUserBoundary(token: symbol): Promise<void> {+ if (token !== captureUserBoundaryToken) {+ throw new TypeError(+ "the user-page boundary is captured automatically by claim/takeover",+ );+ }+ await this.#services.gate.withSpace(this.id, async () => {+ const tabs = await this.#services.listTabs();+ if (tabs.length === 0) {+ this.#userPage = undefined;+ return;+ }+ const ledger = await this.#services.ledger.reconcile(+ this.id,+ tabs.map((tab) => tab.targetId),+ { autoAdoptNew: false, afterUserControl: true },+ );+ const active = tabs.find((tab) => tab.active);+ this.#userPage = active+ ? pageInventory(this, this.#services, ledger, tabs).find(+ (item) => item.targetId === active.targetId,+ )?.page+ : undefined;+ });+ }+async listPages(): Promise<PageInventoryItem[]> {return this.#services.gate.withSpace(this.id, async () => {const { ledger, tabs } = await this.#reconcilePages();@@ -576,7 +631,7 @@ class TaskSpace {/** Wait until this space is controllable without taking control from the user. */async waitForControl(options: WaitForControlOptions = {}): Promise<void> {- assertPlainOptions(options, "task.waitForControl");+ validatePublicApiOptions("TaskSpace.waitForControl", options);const intervalMs = options.interval ?? CONTROL_POLL_INTERVAL_MS;const timeoutMs = options.timeout ?? CONTROL_WAIT_TIMEOUT_MS;assertPositiveMilliseconds(intervalMs, "interval");@@ -599,9 +654,19 @@ 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, () =>- this.#services.handOffTaskSpace(),- );+ 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),+ );+ try {+ await this.#services.handOffTaskSpace();+ } catch (error) {+ await this.#services.ledger.cancelUserControl(this.spaceId);+ throw error;+ }+ });}/** Finish the task, keep its browser space for the user, and drop Page state. */@@ -626,7 +691,7 @@ class TaskSpace {params: Record<string, unknown> = {},options: CdpOptions = {},): Promise<any> {- assertCdpCall(method, params, options);+ assertCdpCall("TaskSpace.cdp", method, params, options);if (!method.startsWith("Target.") && !method.startsWith("Browser.")) {throw new TypeError("task.cdp only supports Target. and Browser. commands",@@ -645,6 +710,7 @@ class TaskSpace {page: UnmanagedPage,options: AdoptPageOptions = {},): Promise<Page> {+ validatePublicApiOptions("TaskSpace.adopt", options);assertUnmanagedPage(page);if (page.spaceId !== this.id) {throw new Error(@@ -708,6 +774,7 @@ class TaskSpace {options: OpenPageOptions = {},): Promise<Page> {assertUrl(url);+ validatePublicApiOptions("TaskSpace.openPage", options);const timeoutMs = options.timeout ?? 15_000;assertTimeout(timeoutMs);return this.#services.gate.withSpace(this.id, async () => {@@ -865,6 +932,7 @@ class Page {options: PageGotoOptions = {},): Promise<PageActionReceipt> {assertUrl(url);+ validatePublicApiOptions("Page.goto", options);const timeoutMs = options.timeout ?? 15_000;assertTimeout(timeoutMs);const page = await this.#resolve();@@ -887,12 +955,15 @@ class Page {}async snapshot(options: PageSnapshotOptions = {}): Promise<string> {- if (!options || typeof options !== "object" || Array.isArray(options)) {- throw new TypeError("page.snapshot options must be an object");- }- if (Object.hasOwn(options, "diff")) {+ 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 () => {await this.#activate(page.targetId);@@ -970,7 +1041,7 @@ class Page {params: Record<string, unknown> = {},options: CdpOptions = {},): Promise<any> {- assertCdpCall(method, params, options);+ assertCdpCall("Page.cdp", method, params, options);const page = await this.#resolve();return this.#services.gate.withPage(page, async ({ sessionId }) => {await this.#activate(page.targetId);@@ -993,6 +1064,7 @@ class Page {selector: string,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 }) => {@@ -1012,6 +1084,7 @@ class Page {state: "load" | "networkidle",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 }) => {@@ -1033,14 +1106,17 @@ class Page {}async screenshot(options: PageScreenshotOptions = {}): Promise<string> {- if (!options || typeof options !== "object" || Array.isArray(options)) {- throw new TypeError("page.screenshot options must be an object");- }- if (Object.hasOwn(options, "full")) {+ 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");@@ -1065,6 +1141,7 @@ class Page {selector: string,options: PageClickOptions = {},): Promise<PageActionReceipt> {+ validatePublicApiOptions("Page.click", options);return this.#runAction(selector, (sessionId, refMap) =>clickInPage(this.#services,@@ -1081,6 +1158,7 @@ class Page {selector: string,options: Omit<PageClickOptions, "clickCount"> = {},): Promise<PageActionReceipt> {+ validatePublicApiOptions("Page.dblclick", options);return this.#runAction(selector, (sessionId, refMap) =>clickInPage(this.#services,@@ -1097,6 +1175,7 @@ class Page {selector: string,options: PageHoverOptions = {},): Promise<PageActionReceipt> {+ validatePublicApiOptions("Page.hover", options);return this.#runAction(selector, (sessionId, refMap) =>hoverInPage(this.#services,@@ -1114,6 +1193,7 @@ class Page {targetSelector: string,options: PageDragAndDropOptions = {},): Promise<PageActionReceipt> {+ validatePublicApiOptions("Page.dragAndDrop", options);return this.#runAction([sourceSelector, targetSelector],(sessionId, refMap) =>@@ -1134,6 +1214,7 @@ class Page {value: string,options: PageFillOptions = {},): Promise<PageActionReceipt> {+ validatePublicApiOptions("Page.fill", options);return this.#runAction(selector, (sessionId, refMap) =>fillInPage(this.#services, sessionId, refMap, selector, value, options),);@@ -1152,6 +1233,7 @@ class Page {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");}@@ -1717,14 +1799,17 @@ function pageFetchPayload(url: string,options: PageFetchOptions,): PageFetchPayload {- if (!options || typeof options !== "object" || Array.isArray(options)) {- throw new TypeError("page.fetch options must be an object");- }- if (Object.hasOwn(options, "signal")) {+ 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 {@@ -1875,13 +1960,8 @@ function assertPositiveMilliseconds(value: number, name: string): void {}}-function assertPlainOptions(value: unknown, name: string): void {- if (!value || typeof value !== "object" || Array.isArray(value)) {- throw new TypeError(`${name} options must be an object`);- }-}-function assertCdpCall(+ apiName: "Page.cdp" | "TaskSpace.cdp",method: string,params: Record<string, unknown>,options: CdpOptions,@@ -1892,9 +1972,7 @@ function assertCdpCall(if (!params || typeof params !== "object" || Array.isArray(params)) {throw new TypeError("cdp params must be an object");}- if (!options || typeof options !== "object" || Array.isArray(options)) {- throw new TypeError("cdp options must be an object");- }+ validatePublicApiOptions(apiName, options);if (options.timeout !== undefined) assertTimeout(options.timeout);}diff --git a/package/ego-browser/src/public-api-schema.test.mjs b/package/ego-browser/src/public-api-schema.test.mjsnew file mode 100644index 0000000..17406b6--- /dev/null+++ b/package/ego-browser/src/public-api-schema.test.mjs@@ -0,0 +1,56 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ PUBLIC_API_SCHEMA,+ publicApiMarkdown,+ validatePublicApiOptions,+} from "../dist/src/public-api-schema.js";++test("the public API schema contains the v2 entry points and object methods", () => {+ const names = new Set(PUBLIC_API_SCHEMA.map((entry) => entry.name));+ for (const name of [+ "taskSpace",+ "claimTaskSpace",+ "takeOverTaskSpace",+ "TaskSpace.spaceId",+ "TaskSpace.userPage",+ "TaskSpace.openPage",+ "Page.snapshot",+ "Page.targetId",+ "Page.keyboard.press",+ ]) {+ assert(names.has(name), `missing public API schema entry: ${name}`);+ }+});++test("schema-driven option validation rejects unknown and invalid fields", () => {+ validatePublicApiOptions("Page.click", {+ button: "left",+ clickCount: 2,+ delay: 0,+ });++ assert.throws(+ () => validatePublicApiOptions("Page.click", { trial: true }),+ /unknown option: trial/,+ );+ assert.throws(+ () => validatePublicApiOptions("Page.goto", { timeout: 0 }),+ /timeout must be a positive number of milliseconds/,+ );+ assert.throws(+ () => validatePublicApiOptions("Page.click", { button: "primary" }),+ /button must be one of left, middle, right/,+ );+});++test("the generated reference contains signatures and option descriptions", () => {+ const markdown = publicApiMarkdown();+ assert.match(+ markdown,+ /`await task\.openPage\(url, \{ as\?, timeout\? \}\)`/,+ );+ assert.match(markdown, /`as` — Permanent Page label\.<br>`timeout`/);+ assert.match(markdown, /Open and durably label a new Page/);+});diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.tsnew file mode 100644index 0000000..b026f1f--- /dev/null+++ b/package/ego-browser/src/public-api-schema.ts@@ -0,0 +1,628 @@+export type PublicApiOptionKind =+ | "boolean"+ | "clip"+ | "finiteNumber"+ | "nonNegativeNumber"+ | "object"+ | "positiveInteger"+ | "positiveMilliseconds"+ | "string"+ | "stringRecord"+ | "point";++export type PublicApiOption = {+ description: string;+ kind: PublicApiOptionKind;+ values?: readonly string[];+};++export type PublicApiEntry = {+ name: string;+ signature: string;+ summary: string;+ options?: Record<string, PublicApiOption>;+};++const option = (+ kind: PublicApiOptionKind,+ description: string,+ values?: readonly string[],+): PublicApiOption => ({ kind, description, values });++const timeout = option(+ "positiveMilliseconds",+ "Maximum duration in milliseconds.",+);+const delay = option("nonNegativeNumber", "Input delay in milliseconds.");+const button = option("string", "Mouse button.", ["left", "middle", "right"]);+const position = option(+ "point",+ "CSS-pixel offset from the element's top-left corner.",+);++/**+ * Single source of truth for the v2 surface shown to Agents. Runtime option+ * validation, default help, and the generated Markdown reference all consume+ * this schema. Legacy helpers intentionally remain outside it.+ */+export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [+ {+ name: "taskSpace",+ signature: "await taskSpace(nameOrId)",+ summary: "Reuse or create an Agent-owned task space and return TaskSpace.",+ },+ {+ name: "claimTaskSpace",+ signature: "await claimTaskSpace(spaceId)",+ summary:+ "Claim a user-owned or inactive space after user approval and return TaskSpace.",+ },+ {+ name: "takeOverTaskSpace",+ signature: "await takeOverTaskSpace(spaceId)",+ summary:+ "Resume an Agent-owned space after user approval and return TaskSpace.",+ },+ {+ name: "TaskSpace.spaceId",+ signature: "task.spaceId",+ summary: "Stable numeric identifier for this task space.",+ },+ {+ name: "TaskSpace.name",+ signature: "task.name",+ summary: "Human-readable task-space name.",+ },+ {+ name: "TaskSpace.ownership",+ signature: "task.ownership",+ summary: "Ownership state captured when this TaskSpace was created.",+ },+ {+ name: "TaskSpace.page",+ signature: "task.page(label)",+ summary: "Create a lazy Page handle for a durable page label.",+ },+ {+ name: "TaskSpace.userPage",+ signature: "task.userPage()",+ summary:+ "Return the tab active at the claim/takeover boundary, when one was captured.",+ },+ {+ name: "TaskSpace.listPages",+ signature: "await task.listPages()",+ summary: "List managed Pages and unmanaged tabs in this space.",+ },+ {+ name: "TaskSpace.openPage",+ signature: "await task.openPage(url, { as?, timeout? })",+ summary: "Open and durably label a new Page.",+ options: {+ as: option("string", "Permanent Page label."),+ timeout,+ },+ },+ {+ name: "TaskSpace.adopt",+ signature: "await task.adopt(unmanagedPage, { as? })",+ summary: "Bring an unmanaged tab under the Page lifecycle.",+ options: { as: option("string", "Permanent Page label.") },+ },+ {+ name: "TaskSpace.release",+ signature: "await task.release(label)",+ summary: "Stop managing a user or unknown-origin Page without closing it.",+ },+ {+ name: "TaskSpace.waitForControl",+ signature: "await task.waitForControl({ interval?, timeout? })",+ summary: "Wait for Agent control without taking it from the user.",+ options: {+ interval: option(+ "positiveMilliseconds",+ "Polling interval in milliseconds.",+ ),+ timeout,+ },+ },+ {+ name: "TaskSpace.handOff",+ signature: "await task.handOff()",+ summary: "Give control of this space to the user.",+ },+ {+ name: "TaskSpace.finish",+ signature: "await task.finish()",+ summary: "Finish the task and keep the browser space for the user.",+ },+ {+ name: "TaskSpace.close",+ signature: "await task.close()",+ summary: "Close the task space.",+ },+ {+ name: "TaskSpace.cdp",+ signature: "await task.cdp(method, params?, { timeout? })",+ summary: "Send a Target or Browser domain CDP command.",+ options: { timeout },+ },+ {+ name: "Page.label",+ signature: "page.label",+ summary: "Durable Page label used to restore the tab across rounds.",+ },+ {+ name: "Page.spaceId",+ signature: "page.spaceId",+ summary: "Numeric identifier of the Page's task space.",+ },+ {+ name: "Page.openedBy",+ signature: "page.openedBy",+ summary: "Conservative origin attribution for this Page.",+ },+ {+ name: "Page.targetId",+ signature: "page.targetId",+ summary:+ "Internal browser target identifier for advanced Target-domain CDP only.",+ },+ {+ name: "Page.goto",+ signature: "await page.goto(url, { timeout? })",+ summary: "Navigate this Page in place.",+ options: { timeout },+ },+ {+ name: "Page.snapshot",+ signature:+ "await page.snapshot({ scope?, includeActionMarks?, includeStableLocator? })",+ summary: "Return a full semantic snapshot with Page provenance.",+ options: {+ scope: option("string", "Snapshot scope.", [+ "full_page",+ "only_within_viewport",+ ]),+ includeActionMarks: option("boolean", "Include action marks."),+ includeStableLocator: option("boolean", "Include stable locators."),+ },+ },+ {+ name: "Page.screenshot",+ signature: "await page.screenshot({ path?, fullPage?, clip?, raw? })",+ summary: "Capture this Page to a PNG file.",+ options: {+ path: option("string", "Absolute output path."),+ fullPage: option("boolean", "Capture the full scrollable page."),+ clip: option("clip", "CSS-pixel clipping rectangle."),+ raw: option("boolean", "Bypass device-pixel-ratio correction."),+ },+ },+ {+ name: "Page.url",+ signature: "await page.url()",+ summary: "Read this Page's current URL.",+ },+ {+ name: "Page.title",+ signature: "await page.title()",+ summary: "Read this Page's current title.",+ },+ {+ name: "Page.info",+ signature: "await page.info()",+ summary: "Read URL, title, viewport, scroll, and dialog state.",+ },+ {+ name: "Page.evaluate",+ signature: "await page.evaluate(fnOrString, argument?)",+ summary: "Run JavaScript in this Page with JSON-serializable data.",+ },+ {+ name: "Page.fetch",+ signature: "await page.fetch(url, options?)",+ summary: "Run window.fetch in this Page and return a structured response.",+ options: {+ timeout,+ method: option("string", "HTTP method."),+ headers: option("stringRecord", "Request headers."),+ body: option("string", "Request body."),+ cache: option("string", "Fetch cache mode.", [+ "default",+ "no-store",+ "reload",+ "no-cache",+ "force-cache",+ "only-if-cached",+ ]),+ credentials: option("string", "Fetch credentials mode.", [+ "omit",+ "same-origin",+ "include",+ ]),+ integrity: option("string", "Subresource integrity value."),+ keepalive: option("boolean", "Allow the request to outlive the page."),+ mode: option("string", "Fetch request mode.", [+ "cors",+ "no-cors",+ "same-origin",+ ]),+ redirect: option("string", "Redirect handling mode.", [+ "follow",+ "error",+ "manual",+ ]),+ referrer: option("string", "Request referrer."),+ referrerPolicy: option("string", "Request referrer policy."),+ },+ },+ {+ name: "Page.cdp",+ signature: "await page.cdp(method, params?, { timeout? })",+ summary: "Send a CDP command through this Page's target session.",+ options: { timeout },+ },+ {+ name: "Page.waitForSelector",+ signature: "await page.waitForSelector(selector, { timeout?, state? })",+ summary: "Wait for an element state in this Page.",+ options: {+ timeout,+ state: option("string", "Required element state.", [+ "attached",+ "detached",+ "visible",+ "hidden",+ ]),+ },+ },+ {+ name: "Page.waitForLoadState",+ signature: "await page.waitForLoadState(state, { timeout?, idleMs? })",+ summary: "Wait for load or network-idle state.",+ options: {+ timeout,+ idleMs: option(+ "positiveMilliseconds",+ "Required network-idle window in milliseconds.",+ ),+ },+ },+ {+ name: "Page.events",+ signature: "await page.events()",+ summary: "Read and clear CDP events buffered for this Page.",+ },+ {+ name: "Page.click",+ signature:+ "await page.click(selector, { button?, clickCount?, delay?, position? })",+ summary: "Click an element with native CDP input.",+ options: {+ button,+ clickCount: option("positiveInteger", "Number of clicks."),+ delay,+ position,+ },+ },+ {+ name: "Page.dblclick",+ signature: "await page.dblclick(selector, { button?, delay?, position? })",+ summary: "Double-click an element with native CDP input.",+ options: { button, delay, position },+ },+ {+ name: "Page.hover",+ signature: "await page.hover(selector, { position? })",+ summary: "Move the mouse over an element.",+ options: { position },+ },+ {+ name: "Page.dragAndDrop",+ signature:+ "await page.dragAndDrop(source, target, { button?, sourcePosition?, targetPosition? })",+ summary: "Drag from one element to another.",+ options: {+ button,+ sourcePosition: position,+ targetPosition: position,+ },+ },+ {+ name: "Page.fill",+ signature: "await page.fill(selector, value, { clearFirst? })",+ summary: "Focus and fill an input-like element.",+ options: {+ clearFirst: option("boolean", "Clear the current value before filling."),+ },+ },+ {+ name: "Page.setInputFiles",+ signature: "await page.setInputFiles(selector, pathOrPaths)",+ summary: "Set files on a file input.",+ },+ {+ name: "Page.scrollBy",+ signature: "await page.scrollBy(deltaY, { deltaX?, behavior? })",+ summary: "Scroll this Page by CSS-pixel deltas.",+ options: {+ deltaX: option("finiteNumber", "Horizontal CSS-pixel delta."),+ behavior: option("string", "Scroll behavior.", [+ "auto",+ "instant",+ "smooth",+ ]),+ },+ },+ {+ name: "Page.close",+ signature: "await page.close()",+ summary: "Close this Page after confirming its tab disappeared.",+ },+ {+ name: "Page.mouse.click",+ signature: "await page.mouse.click(x, y, { button?, clickCount?, delay? })",+ summary: "Click CSS-pixel coordinates with native CDP input.",+ options: {+ button,+ clickCount: option("positiveInteger", "Number of clicks."),+ delay,+ },+ },+ {+ name: "Page.mouse.move",+ signature: "await page.mouse.move(x, y, { steps? })",+ summary: "Move the mouse to CSS-pixel coordinates.",+ options: { steps: option("positiveInteger", "Number of movement steps.") },+ },+ {+ name: "Page.mouse.down",+ signature: "await page.mouse.down({ button?, clickCount? })",+ summary: "Press a mouse button at the current Page position.",+ options: {+ button,+ clickCount: option(+ "positiveInteger",+ "Click count reported to the page.",+ ),+ },+ },+ {+ name: "Page.mouse.up",+ signature: "await page.mouse.up({ button?, clickCount? })",+ summary: "Release a mouse button at the current Page position.",+ options: {+ button,+ clickCount: option(+ "positiveInteger",+ "Click count reported to the page.",+ ),+ },+ },+ {+ name: "Page.mouse.wheel",+ signature: "await page.mouse.wheel(deltaX, deltaY)",+ summary: "Send a wheel event at the current Page position.",+ },+ {+ name: "Page.keyboard.down",+ signature: "await page.keyboard.down(key)",+ summary: "Press and hold a keyboard key.",+ },+ {+ name: "Page.keyboard.up",+ signature: "await page.keyboard.up(key)",+ summary: "Release a keyboard key.",+ },+ {+ name: "Page.keyboard.press",+ signature: "await page.keyboard.press(chord, { delay? })",+ summary: "Press and release a key or portable shortcut chord.",+ options: { delay },+ },+ {+ name: "Page.keyboard.type",+ signature: "await page.keyboard.type(text, { delay? })",+ summary: "Type text using physical keys where possible.",+ options: { delay },+ },+ {+ name: "Page.keyboard.insertText",+ signature: "await page.keyboard.insertText(text)",+ summary: "Insert text without synthesizing key presses.",+ },+] as const;++const entriesByName = new Map(+ PUBLIC_API_SCHEMA.map((entry) => [entry.name, entry]),+);++export function publicApiEntry(name: string): PublicApiEntry | undefined {+ return entriesByName.get(name);+}++/** Validate an option object using the same schema shown in help and docs. */+export function validatePublicApiOptions(name: string, value: unknown): void {+ const entry = publicApiEntry(name);+ if (!entry?.options) {+ throw new Error(`public API schema has no options for ${name}`);+ }+ if (!value || typeof value !== "object" || Array.isArray(value)) {+ throw new TypeError(`${displayName(name)} options must be an object`);+ }+ for (const [key, optionValue] of Object.entries(value)) {+ const specification = entry.options[key];+ if (!specification) {+ throw new TypeError(+ `${displayName(name)} received unknown option: ${key}`,+ );+ }+ if (optionValue === undefined) continue;+ validateOptionValue(displayName(name), key, optionValue, specification);+ }+}++export function publicApiMarkdown(): string {+ const groups = new Map<string, PublicApiEntry[]>();+ for (const entry of PUBLIC_API_SCHEMA) {+ const group = entry.name.startsWith("TaskSpace.")+ ? "TaskSpace"+ : entry.name.startsWith("Page.mouse.")+ ? "Page.mouse"+ : entry.name.startsWith("Page.keyboard.")+ ? "Page.keyboard"+ : entry.name.startsWith("Page.")+ ? "Page"+ : "Entry points";+ const entries = groups.get(group) || [];+ entries.push(entry);+ groups.set(group, entries);+ }++ const lines = [+ "# ego-browser v2 API reference",+ "",+ "Generated from `package/ego-browser/src/public-api-schema.ts`.",+ ];+ for (const [group, entries] of groups) {+ lines.push(+ "",+ `## ${group}`,+ "",+ "| API | Options | Purpose |",+ "| --- | --- | --- |",+ );+ for (const entry of entries) {+ const options = entry.options+ ? Object.entries(entry.options)+ .map(([name, specification]) => {+ const values = specification.values+ ? ` (${specification.values.join(", ")})`+ : "";+ return `\`${name}\`${values} — ${specification.description}`;+ })+ .join("<br>")+ : "—";+ lines.push(`| \`${entry.signature}\` | ${options} | ${entry.summary} |`);+ }+ }+ return `${lines.join("\n").trimEnd()}\n`;+}++function displayName(name: string): string {+ return name.replace(/^TaskSpace/, "task").replace(/^Page/, "page");+}++function validateOptionValue(+ apiName: string,+ optionName: string,+ value: unknown,+ specification: PublicApiOption,+): void {+ let valid = false;+ switch (specification.kind) {+ case "boolean":+ valid = typeof value === "boolean";+ break;+ case "clip":+ valid = isClip(value);+ break;+ case "finiteNumber":+ valid = typeof value === "number" && Number.isFinite(value);+ break;+ 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;+ case "positiveMilliseconds":+ valid = typeof value === "number" && Number.isFinite(value) && value > 0;+ break;+ case "string":+ valid = typeof value === "string";+ break;+ case "stringRecord":+ valid =+ isPlainObject(value) &&+ Object.values(value).every((item) => typeof item === "string");+ break;+ case "point":+ valid = isPoint(value);+ break;+ }+ if (!valid) {+ if (specification.kind === "positiveMilliseconds") {+ throw new TypeError(+ `${optionName} must be a positive number of milliseconds`,+ );+ }+ if (specification.kind === "nonNegativeNumber") {+ throw new TypeError(`${apiName} ${optionName} must be non-negative`);+ }+ if (specification.kind === "positiveInteger") {+ throw new TypeError(+ `${apiName} ${optionName} must be a positive integer`,+ );+ }+ if (specification.kind === "stringRecord") {+ throw new TypeError(+ `${apiName} ${optionName} must be an object with string values`,+ );+ }+ throw new TypeError(+ `${apiName} ${optionName} must be ${specification.kind}`,+ );+ }+ if (specification.values && !specification.values.includes(value as string)) {+ throw new TypeError(+ `${apiName} ${optionName} must be one of ${specification.values.join(", ")}`,+ );+ }+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function isPoint(value: unknown): boolean {+ if (!isPlainObject(value)) return false;+ const keys = Object.keys(value);+ return (+ keys.length === 2 &&+ keys.includes("x") &&+ keys.includes("y") &&+ typeof value.x === "number" &&+ Number.isFinite(value.x) &&+ typeof value.y === "number" &&+ Number.isFinite(value.y)+ );+}++function isClip(value: unknown): boolean {+ if (!isPlainObject(value)) return false;+ const keys = Object.keys(value);+ const allowed = new Set(["x", "y", "width", "height", "scale"]);+ return (+ keys.every((key) => allowed.has(key)) &&+ typeof value.x === "number" &&+ Number.isFinite(value.x) &&+ typeof value.y === "number" &&+ Number.isFinite(value.y) &&+ typeof value.width === "number" &&+ Number.isFinite(value.width) &&+ value.width > 0 &&+ typeof value.height === "number" &&+ Number.isFinite(value.height) &&+ value.height > 0 &&+ (value.scale === undefined ||+ (typeof value.scale === "number" &&+ Number.isFinite(value.scale) &&+ value.scale > 0))+ );+}diff --git a/package/ego-browser/src/real-browser-fixture.test.mjs b/package/ego-browser/src/real-browser-fixture.test.mjsnew file mode 100644index 0000000..4892bd4--- /dev/null+++ b/package/ego-browser/src/real-browser-fixture.test.mjs@@ -0,0 +1,38 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ closeFixtureServer,+ startFixtureServer,+} from "../scripts/real-browser-e2e/fixture.mjs";++test("the real-browser fixture uses a non-recursive cross-site iframe", async () => {+ const fixture = await startFixtureServer("fixture contract test");+ try {+ const homeHtml = await fetch(fixture.baseUrl).then((response) =>+ response.text(),+ );+ const iframeSrc = homeHtml.match(+ /<iframe id="fixture-frame" src="([^"]+)"/,+ )?.[1];++ assert.ok(iframeSrc, "the home fixture exposes its iframe URL");+ assert.notEqual(+ new URL(iframeSrc).hostname,+ new URL(fixture.baseUrl).hostname,+ "the iframe must be cross-site so Chromium exposes an OOPIF target",+ );++ const frameHtml = await fetch(iframeSrc).then((response) =>+ response.text(),+ );+ assert.match(frameHtml, /id="iframe-marker"/);+ assert.doesNotMatch(+ frameHtml,+ /id="fixture-frame"/,+ "the frame fixture must not recursively embed itself",+ );+ } finally {+ await closeFixtureServer(fixture.server);+ }+});diff --git a/package/ego-browser/src/taskspace-e2e.test.mjs b/package/ego-browser/src/taskspace-e2e.test.mjsindex 4f7d6e2..29b3628 100644--- a/package/ego-browser/src/taskspace-e2e.test.mjs+++ b/package/ego-browser/src/taskspace-e2e.test.mjs@@ -76,6 +76,11 @@ class FakeEgo {space.ownership = "agent";return { ...space };}++ async listTabs() {+ this.calls.push(["listTabs"]);+ return { tabs: [] };+ }}async function runTaskspaceScript(ego, code) {@@ -211,6 +216,8 @@ test("taskspace e2e claims and selects an existing user-owned task space", async["listTaskSpaces"],["claimTaskSpace", 7, "checkout-flow"],["useTaskSpace", 7],+ ["useTaskSpace", 7],+ ["listTabs"],]);});@@ -265,7 +272,8 @@ test("cli e2e exposes the unified helperContext surface (help present, internals`cliLog(JSON.stringify({helpType: typeof help,- helpResultType: typeof help("click"),+ publicHelp: help("TaskSpace.openPage"),+ legacyHint: help("click"),newTabType: typeof newTab,helperContextType: typeof helperContext,loadAgentHelpersType: typeof loadAgentHelpers@@ -276,7 +284,10 @@ test("cli e2e exposes the unified helperContext surface (help present, internalsassert.equal(result.exitCode, 0);assert.deepEqual(firstJsonLine(result.stdout), {helpType: "function",- helpResultType: "string",+ publicHelp:+ "TaskSpace.openPage\n\nOpen and durably label a new Page. Options: as: Permanent Page label. timeout: Maximum duration in milliseconds.\n\nawait task.openPage(url, { as?, timeout? })",+ legacyHint:+ 'Legacy helper hidden from default help: click. Use help("legacy", "click").',newTabType: "undefined",helperContextType: "undefined",loadAgentHelpersType: "undefined",diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.mdindex b78985b..079ab3a 100644--- a/skills/ego-browser/SKILL.md+++ b/skills/ego-browser/SKILL.md@@ -8,6 +8,7 @@ description: ego-browser (ego lite) is a real Chromium browser designed from theego 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`.## Run browser scripts@@ -63,6 +64,7 @@ task.spaceId;task.name;task.ownership;task.page(label);+task.userPage();await task.listPages();await task.openPage(url, { as, timeout });@@ -297,8 +299,11 @@ When the user must act in the browser, call `await task.handOff()`, end the curr```jsconst spaceId = 7;const task = await takeOverTaskSpace(spaceId);+const userPage = task.userPage();```+`task.userPage()` is the tab that was active when claim/takeover completed. It may be an unmanaged user tab; adopt it before operating it. Use `listPages()` for the current active state after Agent actions begin.+Use `task.waitForControl({ interval, timeout })` only when the user already knows what to do and the current script must wait in place. It waits for control but never takes it.Only claim a user-owned or inactive space when the user explicitly asks you to do so:diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.mdnew file mode 100644index 0000000..5f2d687--- /dev/null+++ b/skills/ego-browser/references/api.md@@ -0,0 +1,79 @@+# ego-browser v2 API reference++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. |++## TaskSpace++| API | Options | Purpose |+| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |+| `task.spaceId` | — | Stable numeric identifier for this task space. |+| `task.name` | — | Human-readable task-space name. |+| `task.ownership` | — | Ownership state captured when this TaskSpace was created. |+| `task.page(label)` | — | Create a lazy Page handle for a durable page label. |+| `task.userPage()` | — | Return the tab active at the claim/takeover boundary, when one was captured. |+| `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.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. |+| `await task.close()` | — | Close the task space. |+| `await task.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a Target or Browser domain CDP command. |++## Page++| API | Options | Purpose |+| --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |+| `page.label` | — | Durable Page label used to restore the tab across rounds. |+| `page.spaceId` | — | Numeric identifier of the Page's task space. |+| `page.openedBy` | — | Conservative origin attribution for this Page. |+| `page.targetId` | — | Internal browser target identifier for advanced Target-domain CDP only. |+| `await page.goto(url, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Navigate this Page in place. |+| `await page.snapshot({ scope?, includeActionMarks?, includeStableLocator? })` | `scope` (full_page, only_within_viewport) — Snapshot scope.<br>`includeActionMarks` — Include action marks.<br>`includeStableLocator` — Include stable locators. | Return a full semantic snapshot with Page provenance. |+| `await page.screenshot({ path?, fullPage?, clip?, raw? })` | `path` — Absolute output path.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`raw` — Bypass device-pixel-ratio correction. | Capture this Page to a PNG file. |+| `await page.url()` | — | Read this Page's current URL. |+| `await page.title()` | — | Read this Page's current title. |+| `await page.info()` | — | Read URL, title, viewport, scroll, and dialog state. |+| `await page.evaluate(fnOrString, argument?)` | — | Run JavaScript in this Page with JSON-serializable data. |+| `await page.fetch(url, options?)` | `timeout` — Maximum duration in milliseconds.<br>`method` — HTTP method.<br>`headers` — Request headers.<br>`body` — Request body.<br>`cache` (default, no-store, reload, no-cache, force-cache, only-if-cached) — Fetch cache mode.<br>`credentials` (omit, same-origin, include) — Fetch credentials mode.<br>`integrity` — Subresource integrity value.<br>`keepalive` — Allow the request to outlive the page.<br>`mode` (cors, no-cors, same-origin) — Fetch request mode.<br>`redirect` (follow, error, manual) — Redirect handling mode.<br>`referrer` — Request referrer.<br>`referrerPolicy` — Request referrer policy. | Run window.fetch in this Page and return a structured response. |+| `await page.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a CDP command through this Page's target session. |+| `await page.waitForSelector(selector, { timeout?, state? })` | `timeout` — Maximum duration in milliseconds.<br>`state` (attached, detached, visible, hidden) — Required element state. | Wait for an element state in this Page. |+| `await page.waitForLoadState(state, { timeout?, idleMs? })` | `timeout` — Maximum duration in milliseconds.<br>`idleMs` — Required network-idle window in milliseconds. | Wait for load or network-idle state. |+| `await page.events()` | — | Read and clear CDP events buffered for this Page. |+| `await page.click(selector, { button?, clickCount?, delay?, position? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner. | Click an element with native CDP input. |+| `await page.dblclick(selector, { button?, delay?, position? })` | `button` (left, middle, right) — Mouse button.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner. | Double-click an element with native CDP input. |+| `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.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. |++## Page.mouse++| API | Options | Purpose |+| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- |+| `await page.mouse.click(x, y, { button?, clickCount?, delay? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds. | Click CSS-pixel coordinates with native CDP input. |+| `await page.mouse.move(x, y, { steps? })` | `steps` — Number of movement steps. | Move the mouse to CSS-pixel coordinates. |+| `await page.mouse.down({ button?, clickCount? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Click count reported to the page. | Press a mouse button at the current Page position. |+| `await page.mouse.up({ button?, clickCount? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Click count reported to the page. | Release a mouse button at the current Page position. |+| `await page.mouse.wheel(deltaX, deltaY)` | — | Send a wheel event at the current Page position. |++## Page.keyboard++| API | Options | Purpose |+| ---------------------------------------------- | -------------------------------------- | --------------------------------------------------- |+| `await page.keyboard.down(key)` | — | Press and hold a keyboard key. |+| `await page.keyboard.up(key)` | — | Release a keyboard key. |+| `await page.keyboard.press(chord, { delay? })` | `delay` — Input delay in milliseconds. | Press and release a key or portable shortcut chord. |+| `await page.keyboard.type(text, { delay? })` | `delay` — Input delay in milliseconds. | Type text using physical keys where possible. |+| `await page.keyboard.insertText(text)` | — | Insert text without synthesizing key presses. |