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
feat(ego-browser): add profile and text locator support
Aute93d7f56dae2e
diff --git a/docs/runtime-v2-architecture.md b/docs/runtime-v2-architecture.mdindex d34c8fc..fae1577 100644--- a/docs/runtime-v2-architecture.md+++ b/docs/runtime-v2-architecture.md@@ -216,6 +216,11 @@ Agent 创建的页面不能 release,必须显式 close,避免制造无人管```jsconst task = await taskSpace(nameOrId);+const availableProfiles = await profiles();+const profiledTask = await taskSpace(uniqueName, {+ profileId: availableProfiles[0].id,+});+task.spaceId;task.name;task.ownership;@@ -234,6 +239,11 @@ await task.close();await task.cdp(method, params, { timeout });```+不传 `profileId` 时,`taskSpace()` 保持原来的复用或创建行为。显式指定+`profileId` 时只允许创建新的命名空间;同名空间已经存在或传入数字+`spaceId` 都会报错,避免在无法核实 Profile 的情况下复用错误身份。+`profiles()` 返回的 `id` 才是创建参数,显示名称不保证唯一。+`spaceId` 是新版名称。`id` 仅作为已有脚本的兼容别名保留,不进入新版 Skill。`userPage()` 返回 claim/takeover 完成时用户正在看的 tab;它是边界快照,不是实时 active-page 查询。用户页仍未受管时,必须先 `adopt()` 才能操作。@@ -292,6 +302,10 @@ CSS selector 会在 document 和每一层 open shadow root 中查找,因而 Sh节点也可以通过 `loc=css:` 或 raw CSS 操作。selector 应描述元素在自身 tree scope内的结构;XPath 和 closed shadow root 不跨 shadow boundary。+`text=...` 按页面文本定位最小的匹配元素。未加引号时会归一化空白、忽略大小写+并做子串匹配;`text="..."` 使用大小写敏感的精确匹配。文本定位同样搜索 open+shadow root;存在多个匹配时拒绝操作,不自动选择第一个。+文件上传不操作系统文件选择器。已有 file input 时,`setInputFiles()` 直接设置文件;网站点击后才创建 input 时,先建立 `waitForFileChooser()`,再点击并通过返回的 chooser 设置文件。普通输入动作意外打开 chooser 时,runtime 会在系统@@ -488,8 +502,8 @@ V2 API 的签名、options 校验、默认 help manifest 和## 11. 实施状态-公共 API schema、默认 V2 help、显式 legacy help、生成式 API 参考和用户页面-边界已经实现。真实 Ego Lite E2E 已覆盖兼容接口、TaskSpace/Page、多 space、+公共 API schema、默认 V2 help、显式 legacy help、生成式 API 参考、Profile 选择和+用户页面边界已经实现。真实 Ego Lite E2E 已覆盖兼容接口、TaskSpace/Page、多 space、popup 盘点兜底、键鼠、CDP、snapshot 和视觉链路。site skills 暂时保持 legacysurface,不属于本阶段。@@ -508,6 +522,7 @@ surface,不属于本阶段。- 多轮凭标签取回同一 Page,`goto()` 不增加 tab。- 多个 Page 的 session、事件和同号 ref 不串页。- 跨 space 操作按 gate 串行并落到正确 space。+- 显式 Profile 只创建新空间;同名复用、数字 ID 和不存在的 Profile 均安全失败。- 页面预算在创建前拒绝,错误给出可执行的 close/goto 建议。- `pages()` 只返回受管 Page;`tabs()` 还返回未受管 tab,二者都会先完成盘点。- `waitForTimeout()` 校验毫秒参数,不激活 Page,也不阻塞其他 space 的操作。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 5d79b9d..a703e2b 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@@ -1,6 +1,7 @@export function helperSurfaceCase() {return `const expectedHelpers = [+ "profiles","listTaskSpaces","switchTaskSpace","newTaskSpace",@@ -57,6 +58,7 @@ export function helperSurfaceCase() {assertIncludes(defaultHelp, "TaskSpace.openPage", "default help presents the v2 object API");assertIncludes(defaultHelp, "TaskSpace.pages", "default help presents managed Pages");assertIncludes(defaultHelp, "TaskSpace.tabs", "default help presents tab inventory");+ assertIncludes(defaultHelp, "profiles", "default help presents browser profile selection");assertIncludes(defaultHelp, "Page.waitForTimeout", "default help presents fixed waits");assertIncludes(help("TaskSpace.listPages"),diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjsindex 530f69d..62f9041 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,7 @@import { environmentCase } from "./environment.mjs";import { helperSurfaceCase } from "./helper-surface.mjs";import { crossSpaceV2Case, taskSpaceCase } from "./task-space.mjs";+import { profileSelectionCase } from "./profile-selection.mjs";import { navigationCase } from "./navigation.mjs";import { observationCase } from "./observation.mjs";import { pointerCase } from "./pointer.mjs";@@ -17,6 +18,7 @@ import { pageMediaPlaybackCase } from "./page-media-playback.mjs";import { pageScrolledScreenshotCase } from "./page-screenshot.mjs";import { pageSnapshotLocatorCase } from "./page-snapshot-locators.mjs";import { pageShadowDomCase } from "./page-shadow-dom.mjs";+import { pageTextLocatorCase } from "./page-text-locators.mjs";import { pageLoadStatesCase } from "./page-load-states.mjs";import { runtimeCase } from "./runtime.mjs";import { runtimeRegressionCase } from "./runtime-regression.mjs";@@ -46,6 +48,7 @@ export const e2eCases = [{ name: "environment initialization", body: environmentCase },{ name: "helper surface", body: helperSurfaceCase },{ name: "task spaces and control", body: taskSpaceCase },+ { name: "TaskSpace profile selection", body: profileSelectionCase },{ name: "v2 cross-space routing", body: crossSpaceV2Case },{ name: "navigation helpers", body: navigationCase },{ name: "observation helpers", body: observationCase },@@ -91,6 +94,7 @@ export const e2eCases = [{ name: "Page scrolled screenshot", body: pageScrolledScreenshotCase },{ name: "Page snapshot locator quality", body: pageSnapshotLocatorCase },{ name: "Page open Shadow DOM locators", body: pageShadowDomCase },+ { name: "Page text locators", body: pageTextLocatorCase },{ name: "Page load states", body: pageLoadStatesCase },{ name: "v1 and v2 action parity", body: v1V2ActionParityCase },{ name: "portable keyboard workflow", body: portableKeyboardWorkflowCase },diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-text-locators.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-text-locators.mjsnew file mode 100644index 0000000..0e1c276--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-text-locators.mjs@@ -0,0 +1,63 @@+export function pageTextLocatorCase() {+ return `+ const task = await taskSpace(taskName);+ const page = await task.openPage(baseUrl + "/?page=text-locators", {+ as: "text-locators",+ });+ try {+ await page.evaluate(() => {+ const region = document.createElement("section");+ region.innerHTML =+ '<button id="normalized-text" type="button">Save\\n <span>changes</span></button>' ++ '<button id="exact-text" type="button"><span>Exact action</span></button>';+ document.body.append(region);+ document.querySelector("#normalized-text").addEventListener("click", () => {+ document.querySelector("#normalized-text").dataset.clicked = "true";+ });+ document.querySelector("#exact-text").addEventListener("click", () => {+ document.querySelector("#exact-text").dataset.clicked = "true";+ });+ });++ await page.click("text=save changes");+ assertEqual(+ await page.evaluate(() => document.querySelector("#normalized-text").dataset.clicked),+ "true",+ "text locator normalizes whitespace and matches case-insensitively"+ );++ await page.click('text="Exact action"');+ assertEqual(+ await page.evaluate(() => document.querySelector("#exact-text").dataset.clicked),+ "true",+ "quoted text locator uses exact case-sensitive text"+ );++ await page.waitForSelector("text=Hover zone", {+ state: "visible",+ timeout: 2_000,+ });++ await page.click("text=Shadow action");+ assertEqual(+ await page.evaluate(() =>+ document+ .querySelector("#shadow-fixture")+ .shadowRoot.querySelector("nested-shadow-fixture")+ .shadowRoot.querySelector("#shadow-action")+ .dataset.clicked+ ),+ "true",+ "text locator searches nested open shadow roots"+ );++ await assertRejects(+ () => page.click("text=Duplicate action"),+ "matched 2 elements",+ "ambiguous text locator fails instead of choosing a target"+ );+ } finally {+ await page.close();+ }+ `;+}diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/profile-selection.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/profile-selection.mjsnew file mode 100644index 0000000..ee96927--- /dev/null+++ b/package/ego-browser/scripts/real-browser-e2e/cases/profile-selection.mjs@@ -0,0 +1,66 @@+export function profileSelectionCase() {+ return `+ const availableProfiles = await profiles();+ assert(availableProfiles.length > 0, "profiles returns at least one browser profile");+ assert(+ availableProfiles.every(+ (profile) =>+ typeof profile.id === "string" &&+ profile.id.length > 0 &&+ typeof profile.name === "string" &&+ typeof profile.isDefault === "boolean"+ ),+ "profiles returns complete profile descriptors"+ );+ assertEqual(+ new Set(availableProfiles.map((profile) => profile.id)).size,+ availableProfiles.length,+ "profiles returns unique profile ids"+ );++ const selectedProfile =+ availableProfiles.find((profile) => !profile.isDefault) || availableProfiles[0];+ const explicitName = taskName + " explicit profile";+ const explicitTask = await taskSpace(explicitName, {+ profileId: selectedProfile.id,+ });+ try {+ const page = await explicitTask.openPage(baseUrl + "/?profile=explicit", {+ as: "profile-check",+ });+ assertEqual(+ await page.title(),+ "ego-lite helper e2e",+ "the selected Profile TaskSpace is operable"+ );++ await assertRejects(+ () => taskSpace(explicitName, { profileId: selectedProfile.id }),+ "already exists",+ "explicit profile selection never reuses a same-name TaskSpace"+ );+ await assertRejects(+ () => taskSpace(explicitTask.spaceId, { profileId: selectedProfile.id }),+ "new task-space name",+ "profile selection cannot be applied while resuming a numeric space id"+ );+ } finally {+ await explicitTask.close();+ }++ let missingProfileId = "__ego_browser_missing_profile__";+ while (availableProfiles.some((profile) => profile.id === missingProfileId)) {+ missingProfileId += "_";+ }+ const invalidName = taskName + " invalid profile";+ await assertRejects(+ () => taskSpace(invalidName, { profileId: missingProfileId }),+ "Profile not found",+ "an unknown profile is reported by Ego Lite"+ );+ assert(+ !(await listTaskSpaces()).some((space) => space.name === invalidName),+ "an unknown profile does not leave a TaskSpace"+ );+ `;+}diff --git a/package/ego-browser/src/driver/element-ops.ts b/package/ego-browser/src/driver/element-ops.tsindex 2566814..082f62e 100644--- a/package/ego-browser/src/driver/element-ops.ts+++ b/package/ego-browser/src/driver/element-ops.ts@@ -4,8 +4,8 @@ import { resolveElementObjectId } from "../element-resolver.js";/*** Resolve any selector form to a CDP Runtime objectId handle.- * Accepts @ref / ref=N, loc=css:/loc=role:/loc=href:, xpath=, and raw CSS —- * the same surface as the pointer/observe helpers, via the unified resolver.+ * Accepts @ref / ref=N, loc=css:/loc=role:/loc=href:, text=, xpath=, and raw+ * CSS — the same surface as the pointer/observe helpers, via the unified resolver.* Refreshes the RefMap on demand when the input is a ref and the map is empty.* @param {string} selectorOrRef Selector or ref string.* @returns {Promise<{objectId: string, sessionId?: string}>}diff --git a/package/ego-browser/src/element-resolver.test.mjs b/package/ego-browser/src/element-resolver.test.mjsindex 5f4f88c..da5aac6 100644--- a/package/ego-browser/src/element-resolver.test.mjs+++ b/package/ego-browser/src/element-resolver.test.mjs@@ -142,3 +142,68 @@ test("CSS locators search nested open shadow roots", async () => {assert.deepEqual(point, { x: 12, y: 34, sessionId: undefined });});++test("text locators normalize whitespace and search nested open shadow roots", async () => {+ const cdp = new FakeCDP(async (method, params) => {+ if (method === "Runtime.evaluate") {+ assert.match(params.expression, /shadowRoot/);+ assert.match(params.expression, /replace\(\/\\s\+\/g, " "\)/);+ assert.match(params.expression, /toLowerCase\(\)\s*\.includes/);+ assert.match(params.expression, /INPUT/);+ return { result: { value: { x: 20, y: 30 } } };+ }+ return {};+ });++ const point = await resolveElementCenter(+ cdp,+ undefined,+ new RefMap(),+ "text=Save changes",+ );++ assert.deepEqual(point, { x: 20, y: 30, sessionId: undefined });+});++test("quoted text locators use exact case-sensitive matching", async () => {+ const cdp = new FakeCDP(async (method, params) => {+ if (method === "Runtime.evaluate") {+ assert.match(params.expression, /mode: "exact"/);+ assert.match(params.expression, /=== expected/);+ return { result: { value: { x: 40, y: 50 } } };+ }+ return {};+ });++ const point = await resolveElementCenter(+ cdp,+ undefined,+ new RefMap(),+ 'text="Save changes"',+ );++ assert.deepEqual(point, { x: 40, y: 50, sessionId: undefined });+});++test("ambiguous text locators fail permanently instead of choosing one match", async () => {+ const cdp = new FakeCDP(async (method) => {+ if (method === "Runtime.evaluate") {+ return {+ result: {+ value: { error: "Locator text=Save matched 2 elements" },+ },+ };+ }+ return {};+ });++ await assert.rejects(+ () => resolveElementCenter(cdp, undefined, new RefMap(), "text=Save"),+ (error) => {+ assert.ok(error instanceof ElementResolutionError);+ assert.equal(error.kind, "permanent");+ assert.match(error.message, /matched 2 elements/);+ return true;+ },+ );+});diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.tsindex 594c0a8..c6cf746 100644--- a/package/ego-browser/src/element-resolver.ts+++ b/package/ego-browser/src/element-resolver.ts@@ -448,6 +448,9 @@ function buildLocatorFindJs(locator) {if (locator.kind === "css") {return buildCssFindJs(locator.selector);}+ if (locator.kind === "text") {+ return `(() => ${textElementsJs(locator)}[0] || null)()`;+ }return `(() => ${hrefElementsJs(locator.href)}[0] || null)()`;}@@ -455,6 +458,9 @@ function buildLocatorCountJs(locator) {if (locator.kind === "css") {return buildCssCountJs(locator.selector);}+ if (locator.kind === "text") {+ return `(() => ${textElementsJs(locator)}.length)()`;+ }return `(() => ${hrefElementsJs(locator.href)}.length)()`;}@@ -481,6 +487,81 @@ function hrefElementsJs(href) {})`;}+function textElementsJs(locator) {+ return `(() => {+ ${OPEN_SHADOW_QUERY_HELPER}+ const spec = {+ mode: ${JSON.stringify(locator.mode)},+ text: ${JSON.stringify(locator.text)}+ };+ const normalize = (value) =>+ String(value ?? "").replace(/\\s+/g, " ").trim();+ const expected = normalize(spec.text);+ const excludedTags = new Set([+ "HEAD",+ "NOSCRIPT",+ "SCRIPT",+ "STYLE",+ "TEMPLATE",+ "TITLE"+ ]);+ const elements = __egoQueryAllOpenShadow("*").filter(+ (element) => !excludedTags.has(element.tagName)+ );++ function fullText(element) {+ const type = String(element.getAttribute?.("type") || "").toLowerCase();+ if (element.tagName === "INPUT" && (type === "button" || type === "submit")) {+ return normalize(element.value);+ }+ return normalize(element.textContent);+ }++ function immediateText(element) {+ const type = String(element.getAttribute?.("type") || "").toLowerCase();+ if (element.tagName === "INPUT" && (type === "button" || type === "submit")) {+ return normalize(element.value);+ }+ return normalize(+ [...element.childNodes]+ .filter((node) => node.nodeType === Node.TEXT_NODE)+ .map((node) => node.nodeValue)+ .join(" ")+ );+ }++ function matches(element) {+ if (spec.mode === "exact") return immediateText(element) === expected;+ return fullText(element)+ .toLowerCase()+ .includes(expected.toLowerCase());+ }++ function isComposedDescendant(ancestor, node) {+ let current = node;+ while (current) {+ if (current === ancestor) return true;+ if (current.parentElement) {+ current = current.parentElement;+ continue;+ }+ const root = current.getRootNode?.();+ current = root instanceof ShadowRoot ? root.host : null;+ }+ return false;+ }++ const matchesByText = elements.filter(matches);+ return matchesByText.filter(+ (element) =>+ !matchesByText.some(+ (other) =>+ other !== element && isComposedDescendant(element, other)+ )+ );+ })()`;+}+// CSS locators from the native snapshot can point into an open shadow tree.// Query every reachable tree scope so those locators have the same meaning// when an action reuses them. XPath deliberately keeps document-only semantics.@@ -545,6 +626,22 @@ function parseLocator(input) {const href = value.slice(5);return href ? { kind: "href", href, raw: value } : null;}+ if (value.startsWith("text=")) {+ const body = value.slice(5).trim();+ if (!body) return null;+ const quoted =+ (body.startsWith('"') && body.endsWith('"')) ||+ (body.startsWith("'") && body.endsWith("'"));+ const text = quoted ? parseLocatorName(body) : body;+ return normalizeText(text)+ ? {+ kind: "text",+ mode: quoted ? "exact" : "substring",+ text,+ raw: value,+ }+ : null;+ }const roleMatch = /^role:([A-Za-z0-9_-]+)\[name=(.+)\]$/.exec(value);if (roleMatch) {return {@@ -572,6 +669,12 @@ function parseLocatorName(raw) {return trimmed;}+function normalizeText(value) {+ return String(value ?? "")+ .replace(/\s+/g, " ")+ .trim();+}+function boxModelCenter(model: any = {}) {const content = model.content || [];if (content.length < 8) {diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjsindex 70df008..35efdf9 100644--- a/package/ego-browser/src/helpers.test.mjs+++ b/package/ego-browser/src/helpers.test.mjs@@ -9,6 +9,7 @@ import {newTaskSpace,helperContext,listTaskSpaces,+ profiles,taskSpace,useOrCreateTaskSpace,switchTaskSpace,@@ -95,9 +96,43 @@ test("listTaskSpaces throws on binding error objects", async () => {);});+test("profiles returns the browser profiles exposed by Ego Lite", async () => {+ const expected = [+ { id: "Default", name: "Personal", isDefault: true },+ { id: "Profile 2", name: "Work", isDefault: false },+ ];+ await withEgo(+ {+ async listProfiles() {+ return { profiles: expected };+ },+ },+ async () => {+ assert.deepEqual(await profiles(), expected);+ },+ );+});++test("profiles rejects malformed native results", async () => {+ await withEgo(+ {+ async listProfiles() {+ return { profiles: [{ id: "Default", name: "Personal" }] };+ },+ },+ async () => {+ await assert.rejects(+ () => profiles(),+ /profiles expected entries with id, name, and isDefault/,+ );+ },+ );+});+test("taskspace helper surface exposes public helpers including claimTaskSpace", () => {const context = helperContext();assert.equal(typeof context.taskSpace, "function");+ assert.equal(typeof context.profiles, "function");assert.equal(typeof context.listTaskSpaces, "function");assert.equal(typeof context.switchTaskSpace, "function");assert.equal(typeof context.newTaskSpace, "function");@@ -151,6 +186,104 @@ test("taskSpace returns the new object model for a resolved space", async () =>);});+test("taskSpace creates a new space with an explicit browser profile", async () => {+ const calls = [];+ await withEgo(+ {+ async listTaskSpaces() {+ calls.push(["listTaskSpaces"]);+ return { taskSpaces: [] };+ },+ async createTaskSpace(name, profileId) {+ calls.push(["createTaskSpace", name, profileId]);+ return { taskId: name, id: 8, name };+ },+ useTaskSpace(id) {+ calls.push(["useTaskSpace", id]);+ return id;+ },+ },+ async () => {+ const task = await taskSpace("work research", { profileId: "Profile 2" });+ assert.equal(task.spaceId, 8);+ assert.equal(task.name, "work research");+ },+ );+ assert.deepEqual(calls, [+ ["listTaskSpaces"],+ ["createTaskSpace", "work research", "Profile 2"],+ ["useTaskSpace", 8],+ ]);+});++test("taskSpace does not reuse an existing name when a profile is explicit", async () => {+ const calls = [];+ await withEgo(+ {+ async listTaskSpaces() {+ calls.push(["listTaskSpaces"]);+ return {+ taskSpaces: [+ {+ taskId: "work research",+ id: 7,+ name: "work research",+ ownership: "agent",+ },+ ],+ };+ },+ async createTaskSpace(name, profileId) {+ calls.push(["createTaskSpace", name, profileId]);+ return { taskId: name, id: 8, name };+ },+ useTaskSpace(id) {+ calls.push(["useTaskSpace", id]);+ return id;+ },+ },+ async () => {+ await assert.rejects(+ () => taskSpace("work research", { profileId: "Profile 2" }),+ /profileId only applies when creating a new task space.*already exists/,+ );+ },+ );+ assert.deepEqual(calls, [["listTaskSpaces"]]);+});++test("taskSpace rejects profile selection when resuming a numeric space id", async () => {+ await withEgo(+ {+ async listTaskSpaces() {+ throw new Error("must not inspect spaces");+ },+ },+ async () => {+ await assert.rejects(+ () => taskSpace(7, { profileId: "Profile 2" }),+ /profileId can only be used with a new task-space name/,+ );+ },+ );+});++test("taskSpace rejects empty profile ids before calling Ego Lite", async () => {+ await withEgo(+ {+ async listTaskSpaces() {+ throw new Error("must not inspect spaces");+ },+ },+ async () => {+ await assert.rejects(+ () => taskSpace("work research", { profileId: "" }),+ /taskSpace profileId must be a non-empty string/,+ );+ },+ );+});+test("switchTaskSpace selects a matching task space", async () => {const calls = [];await withEgo(diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.tsindex d1253a5..4c4f883 100644--- a/package/ego-browser/src/helpers.ts+++ b/package/ego-browser/src/helpers.ts@@ -5,6 +5,7 @@ import { pathToFileURL } from "node:url";import { setOverrides, state } from "./state.js";import { invokeEgo, isEgoUserControlError } from "./ego-errors.js";import { help as helpRuntime, formatHelp } from "./help-runtime.js";+import { validatePublicApiOptions } from "./public-api-schema.js";import { cdp, decodeUnserializableJsValue, js } from "./cdp-eval.js";import * as pointer from "./driver/pointer.js";import * as keyboard from "./driver/keyboard.js";@@ -86,6 +87,33 @@ export async function listTaskSpaces() {);}+/**+ * List browser profiles that may be selected when creating a task space.+ * Profile ids are stable locators; display names are not guaranteed unique.+ * @returns {Promise<Array<{id:string,name:string,isDefault:boolean}>>}+ */+export async function profiles() {+ const ego = globalThis.ego;+ if (!ego || typeof ego.listProfiles !== "function") {+ throw new Error("profiles requires ego.listProfiles");+ }+ const result = await invokeEgo("profiles", () => ego.listProfiles());+ if (+ !Array.isArray(result?.profiles) ||+ !result.profiles.every(+ (profile) =>+ profile &&+ typeof profile.id === "string" &&+ profile.id.length > 0 &&+ typeof profile.name === "string" &&+ typeof profile.isDefault === "boolean",+ )+ ) {+ throw new Error("profiles expected entries with id, name, and isDefault");+ }+ return result.profiles;+}+/** Task space ownership policy (`ownership`: "agent" | "agentDelegatedToUser" | "user").* "agent" and "agentDelegatedToUser" are both agent-owned (see isAgentOwned) — the@@ -138,15 +166,22 @@ export async function switchTaskSpace(nameOrId) {/*** Create an agent-owned task space and select it for the current Node invocation.* @param {string} name Task space name.+ * @param {string} [profileId] Profile id returned by profiles().* @returns {Promise<{taskId:string,id:number,name:string,createdBy?:string,ownership?:string,recentTabTitles?:string[]}>}*/-export async function newTaskSpace(name) {+export async function newTaskSpace(name, profileId?: string) {const ego = globalThis.ego;if (!ego || typeof ego.createTaskSpace !== "function") {throw new Error("newTaskSpace requires ego.createTaskSpace");}+ // Do not pass an explicit undefined: older native bindings reject extra+ // arguments, while newer builds accept profileId as the second argument.const created = normalizeTaskSpace(- await invokeEgo("newTaskSpace", () => ego.createTaskSpace(name)),+ await invokeEgo("newTaskSpace", () =>+ profileId === undefined+ ? ego.createTaskSpace(name)+ : ego.createTaskSpace(name, profileId),+ ),);if (!created) {throw new Error("newTaskSpace returned an invalid task space");@@ -196,10 +231,31 @@ export async function useOrCreateTaskSpace(nameOrId) {* Return the v2 object handle for an existing task space, or create the space* when a string name does not exist.* @param {string|number} nameOrId Task space name or numeric id.+ * @param {{profileId?:string}} [options] Creation options for a new named space.* @returns {Promise<import('./page-model.js').TaskSpace>}*/-export async function taskSpace(nameOrId) {- const descriptor = await useOrCreateTaskSpace(nameOrId);+export async function taskSpace(+ nameOrId,+ options: { profileId?: string } = {},+) {+ validatePublicApiOptions("taskSpace", options);+ const { profileId } = options;+ if (profileId === undefined) {+ const descriptor = await useOrCreateTaskSpace(nameOrId);+ return createTaskSpaceHandle(descriptor);+ }+ if (typeof nameOrId !== "string") {+ throw new TypeError(+ "taskSpace profileId can only be used with a new task-space name",+ );+ }+ const existing = findMatchingTaskSpace(await listTaskSpaces(), nameOrId);+ if (existing) {+ throw new Error(+ `taskSpace profileId only applies when creating a new task space; ${JSON.stringify(nameOrId)} already exists`,+ );+ }+ const descriptor = await newTaskSpace(nameOrId, profileId);return createTaskSpaceHandle(descriptor);}@@ -541,6 +597,7 @@ export function helperContext(extra: any = {}) {runSiteTool,runSiteBrowserTool,learnContext,+ profiles,listTaskSpaces,switchTaskSpace,newTaskSpace,diff --git a/package/ego-browser/src/public-api-schema.test.mjs b/package/ego-browser/src/public-api-schema.test.mjsindex 62edfc2..9781e6f 100644--- a/package/ego-browser/src/public-api-schema.test.mjs+++ b/package/ego-browser/src/public-api-schema.test.mjs@@ -10,6 +10,7 @@ import {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 [+ "profiles","taskSpace","claimTaskSpace","takeOverTaskSpace",@@ -30,12 +31,17 @@ test("the public API schema contains the v2 entry points and object methods", ()});test("schema-driven option validation rejects unknown and invalid fields", () => {+ validatePublicApiOptions("taskSpace", { profileId: "Profile 2" });validatePublicApiOptions("Page.click", {button: "left",clickCount: 2,delay: 0,});+ assert.throws(+ () => validatePublicApiOptions("taskSpace", { profileId: "" }),+ /taskSpace profileId must be a non-empty string/,+ );assert.throws(() => validatePublicApiOptions("Page.click", { trial: true }),/unknown option: trial/,@@ -52,6 +58,8 @@ test("schema-driven option validation rejects unknown and invalid fields", () =>test("the generated reference contains signatures and option descriptions", () => {const markdown = publicApiMarkdown();+ assert.match(markdown, /`await profiles\(\)`/);+ assert.match(markdown, /`await taskSpace\(nameOrId, \{ profileId\? \}\)`/);assert.match(markdown,/`await task\.openPage\(url, \{ as\?, timeout\? \}\)`/,diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.tsindex 22c73f4..e88c602 100644--- a/package/ego-browser/src/public-api-schema.ts+++ b/package/ego-browser/src/public-api-schema.ts@@ -3,6 +3,7 @@ export type PublicApiOptionKind =| "clip"| "finiteNumber"| "nonNegativeNumber"+ | "nonEmptyString"| "positiveInteger"| "positiveMilliseconds"| "string"@@ -45,10 +46,22 @@ const position = option(* this schema. Legacy helpers intentionally remain outside it.*/export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [+ {+ name: "profiles",+ signature: "await profiles()",+ summary: "List browser profiles available for new task spaces.",+ },{name: "taskSpace",- signature: "await taskSpace(nameOrId)",- summary: "Reuse or create an Agent-owned task space and return TaskSpace.",+ signature: "await taskSpace(nameOrId, { profileId? })",+ summary:+ "Reuse or create an Agent-owned task space; profileId applies only to a new named space.",+ options: {+ profileId: option(+ "nonEmptyString",+ "Browser profile id returned by profiles(); new spaces only.",+ ),+ },},{name: "claimTaskSpace",@@ -568,6 +581,9 @@ function validateOptionValue(case "nonNegativeNumber":valid = typeof value === "number" && Number.isFinite(value) && value >= 0;break;+ case "nonEmptyString":+ valid = typeof value === "string" && value.length > 0;+ break;case "positiveInteger":valid = Number.isInteger(value) && (value as number) > 0;break;@@ -595,6 +611,11 @@ function validateOptionValue(if (specification.kind === "nonNegativeNumber") {throw new TypeError(`${apiName} ${optionName} must be non-negative`);}+ if (specification.kind === "nonEmptyString") {+ throw new TypeError(+ `${apiName} ${optionName} must be a non-empty string`,+ );+ }if (specification.kind === "positiveInteger") {throw new TypeError(`${apiName} ${optionName} must be a positive integer`,diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.mdindex c47e5e3..59463b1 100644--- a/skills/ego-browser/SKILL.md+++ b/skills/ego-browser/SKILL.md@@ -5,59 +5,75 @@ description: ego-browser (ego lite) is a real Chromium browser designed from the# ego-browser-ego lite is a real desktop browser based on Chromium. Agents operate real pages in isolated task spaces; pages use the user's actual login state and cookies and produce real downloads, dialogs, and new tabs. Obtain a `TaskSpace` with `taskSpace()`, then obtain or create a `Page` from it. Start every page operation from its `Page`. Page methods address their own page and activate it automatically when interaction requires it, so do not maintain a "current tab" or switch tabs manually.+Ego Lite is a real Chromium browser where Agents work in isolated task spaces+while reusing the user's login state. Obtain a `TaskSpace` with `taskSpace()`,+then operate each tab through its `Page`.-For installation, connection, or runtime problems, read `references/install.md`.-For exact signatures and option fields, read `references/api.md`.+For installation, connection, or runtime problems, read+`references/install.md`. Normal browser work should not require the API+reference; use `help()` or `references/api.md` only for uncommon options.## Run browser scripts-Use Bash to execute browser scripts through a heredoc:+Run JavaScript through a heredoc:```bashego-browser nodejs <<'EOF'-const task = await taskSpace('inspect example page')-const page = await task.openPage('https://example.com', {- as: 'main',- timeout: 20_000,-})--console.log(JSON.stringify({ taskSpaceId: task.spaceId, page: page.label }))-console.log(await page.snapshot())+const task = await taskSpace("inspect example page");+const page = await task.openPage("https://example.com", { as: "main" });++console.log({ taskSpaceId: task.spaceId, page: page.label });+console.log(await page.snapshot());EOF```-The heredoc runs in Node.js. Use `document` and `window` only inside `page.evaluate()`. All APIs are preloaded; do not import Playwright, launch another browser, or create a `.js` file first.+The heredoc runs in Node.js and all browser APIs are preloaded. Use `document`+and `window` only inside `page.evaluate()`; do not import Playwright, launch+another browser, or create a temporary script file first.-When the user explicitly asks for ego-browser, run the first real browser command immediately. Do not preflight the CLI, Node version, or package metadata; diagnose only after that command fails.+When the user explicitly asks for ego-browser, run the first real browser+command immediately. Diagnose the CLI or installation only if that command+fails. Console output is returned together when the script round finishes.-Use `console.log/info/warn/error` for output. Output appears only after the entire script round finishes, so do not treat intermediate logs as live progress signals.+## Spaces, rounds, and pages-## Task spaces and script rounds--- Use one task space for one user goal. Use more than one only when the task clearly needs separate identities, login states, or browsing contexts. In the first round, call `taskSpace(name)` with a short goal name. In later rounds, prefer the numeric `task.spaceId` returned by the first round.-- Every heredoc starts a new Node.js process. Task spaces, tabs, and Page labels survive across rounds; ordinary JavaScript variables do not.-- Print `task.spaceId` and the important Page labels in the first round. Resume the same space instead of opening a new one after failures or follow-up requests.-- Put all observation, action, and verification that the current script can complete into one round. End a round only when the model needs to reassess, the user must intervene, or the current process cannot recover.-- All `TaskSpace` and `Page` time values use milliseconds.+- Complete the user's goal within one task space. Use multiple spaces only when+ the user explicitly requests different profiles.+- Every heredoc starts a new Node.js process. Task spaces, tabs, and Page labels+ survive across rounds; JavaScript variables do not.+- In the first round, use a short goal name and print `task.spaceId`. In later+ rounds, resume that numeric ID and restore Pages by label.+- Reuse a Page with `goto()` instead of opening a new Page for every URL.+- All time values are milliseconds.```js// First roundconst task = await taskSpace("collect release notes");const page = await task.openPage("https://example.com", { as: "source" });console.log({ taskSpaceId: task.spaceId, page: page.label });++// Later round+const resumed = await taskSpace(7);+const source = resumed.page("source");+await source.goto("https://example.com/releases");```+When the user explicitly requests a browser profile, select its unique id while+creating a new, uniquely named space:+```js-// Later round-const task = await taskSpace(7);-const page = task.page("source");-await page.goto("https://example.com/releases");+const matches = (await profiles()).filter((item) => item.name === "Work");+if (matches.length !== 1)+ throw new Error("Work profile is missing or ambiguous");+const task = await taskSpace("work account research", {+ profileId: matches[0].id,+});```-## Manage pages+Profile display names may be duplicated. Pass the returned `id`; `profileId`+cannot change or resume an existing space.-`TaskSpace` provides these APIs:+The common TaskSpace surface is:```jstask.spaceId;@@ -78,99 +94,146 @@ await task.close();await task.cdp(method, params, { timeout });```-Follow these page-management rules:+Pages receive permanent labels such as `p1` automatically; `{ as }` chooses a+meaningful label. A space manages at most eight Pages by default. If the budget+is reached, close a temporary Page or navigate an existing one.-- Reuse an existing Page by default. Call `page.goto()` to open another URL in the same Page. Call `task.openPage()` only when pages truly need to remain side by side.-- Pages receive permanent `p1`, `p2`, and similar labels automatically. Pass `{ as }` to choose a label. Closed labels are never reused.-- Each space manages at most eight pages by default. On `EGO_PAGE_BUDGET_REACHED`, close temporary pages or reuse an existing Page with `goto()`; do not bypass the budget.-- `task.pages()` returns only managed Page handles. It is async because it reconciles live browser tabs before returning.-- `task.tabs()` returns the complete tab inventory, including managed Pages and unmanaged tabs. An `UnmanagedPage` without a `label` exposes identity information only. Call `task.adopt(item.page, { as })` before observing or operating it.-- Use `task.release(label)` only to return an unknown-origin page to the user while keeping its tab open. Close Agent-created pages with `page.close()`.-- `page.close()` resolves only after the tab has actually disappeared. If close fails, the Page label remains valid and the operation can be retried safely.--`openPage()` defaults to a `15_000` ms timeout. A custom `as` label must start with a letter and may contain letters, numbers, `_`, or `-`, up to 64 characters. `waitForControl()` defaults to `{ interval: 20_000, timeout: 600_000 }`; it waits but never takes control.--`task.ownership` is the ownership captured when the TaskSpace handle was created. `page.openedBy` is `"agent"` or `"unknown"`; treat `"unknown"` as user-owned for lifecycle decisions.--Each `tabs()` item has `{ label?, page, targetId, title, url, active, openedBy }`. Use `task.page(label)` to resume a known Page, `pages()` to iterate managed Pages, and `tabs()` to discover active or unmanaged tabs:+`task.pages()` returns managed Pages. `task.tabs()` returns every tab in the+space as `{ label?, page, targetId, title, url, active, openedBy }`. A tab+without a label is unmanaged and cannot be operated until adopted:```js-const items = await task.tabs();-const active = items.find((item) => item.active);+const active = (await task.tabs()).find((item) => item.active);if (active && !active.label) {- const adopted = await task.adopt(active.page, { as: "user" });- console.log({ page: adopted.label, url: await adopted.url() });+ const page = await task.adopt(active.page, { as: "user" });+ console.log({ page: page.label, url: await page.url() });}```-New tabs opened by high-level actions receive labels automatically and may appear in the action receipt:+Use `release(label)` only to return an unknown-origin Page to the user while+keeping its tab open. Close Agent-created Pages with `page.close()`.+`task.ownership` and `page.openedBy` are conservative snapshots; treat an+`openedBy` value of `"unknown"` as user-owned for lifecycle decisions.++## Page operations++The methods below use Playwright-style names and option shapes where they+overlap. Ego-browser is not the full Playwright API and has no Locator API; use+only the methods listed here.```js-const receipt = await page.click('a[target="_blank"]');-for (const popup of receipt.popups ?? []) {- const popupPage = task.page(popup.label);- await popupPage.waitForURL(/\/expected-path(?:[?#]|$)/, { timeout: 10_000 });- console.log({ popup: popup.label, url: await popupPage.url() });-}-```+page.label;+page.spaceId;+page.openedBy;+page.targetId;++await page.goto(url, { timeout });+await page.snapshot({ scope, includeActionMarks, includeStableLocator });+await page.screenshot({ path, fullPage, clip, raw });+await page.url();+await page.title();+await page.info();+await page.events();+await page.evaluate(fnOrString, argument);+await page.fetch(url, options);+await page.cdp(method, params, { timeout });++await page.waitForURL(urlOrRegExp, { timeout });+await page.waitForSelector(selector, { timeout, state });+await page.waitForLoadState(state, { timeout, idleMs });+await page.waitForTimeout(timeout);++await page.click(selector, { button, clickCount, delay, position });+await page.dblclick(selector, { button, delay, position });+await page.hover(selector, { position });+await page.dragAndDrop(source, target, {+ button,+ sourcePosition,+ targetPosition,+});+await page.fill(selector, value, { clearFirst });+await page.scrollBy(deltaY, { deltaX, behavior });+await page.setInputFiles(selector, pathOrPaths);+const chooserPromise = page.waitForFileChooser({ timeout });+await page.close();-The receipt confirms that the popup target was adopted; its first navigation may-still be at `about:blank`. Use `waitForURL()` when the destination matters. A-popup that propagates slowly will be discovered by the next `pages()`, `tabs()`,-or `openPage()` call, or when the task resumes in a later round.+await page.mouse.click(x, y, { button, clickCount, delay });+await page.mouse.move(x, y, { steps });+await page.mouse.down({ button, clickCount });+await page.mouse.up({ button, clickCount });+await page.mouse.wheel(deltaX, deltaY);-## Choose an interaction path+await page.keyboard.down(key);+await page.keyboard.up(key);+await page.keyboard.press(chord, { delay });+await page.keyboard.type(text, { delay });+await page.keyboard.insertText(text);+```-Use the semantic path first. Use the visual path when the page relies mainly on canvas, rich text, or virtualized UI. Use CDP only when the Page API does not cover the required capability.+Use `help("Page.click")` or `help("TaskSpace.openPage")` when an uncommon+option or exact default matters.-### 1. Semantic path: snapshot + selector/ref+### Semantic pages: snapshot and selectors-Use `page.snapshot()` first for ordinary DOM pages. It returns full-page semantic text with Page and space provenance. Each ref belongs only to the Page that produced it.+For an ordinary DOM page, start with `page.snapshot()`. It returns semantic+text containing refs and stable locators:```js-const text = await page.snapshot();-console.log(text);-// For a node shown as [ref=21, ...], pass @21 or ref=21 without the brackets.+const page = task.page("main");+console.log(await page.snapshot());++// Suppose the snapshot shows [ref=21] on an email field and+// loc=role:button[name='Sign in'] on a button.+await page.fill("@21", "[email protected]");+await page.click("loc=role:button[name='Sign in']");+await page.waitForSelector("loc=css:#account-home");+await page.click("text=Save changes");+await page.click("button.save");```-Page actions accept these selectors:+Element actions accept:-- refs such as `@21`, or the `ref=21` portion displayed by snapshot-- stable `loc=css:`, `loc=role:`, and `loc=href:` values returned by snapshot+- snapshot refs such as `@21` or `ref=21`+- `text=...` for page content+- `loc=css:`, `loc=role:`, and `loc=href:` locators shown by snapshot or written directly- `xpath=...`- raw CSS selectors-CSS selectors search the document and every nested open shadow root. Write the-selector for the element's own tree scope; XPath and closed shadow roots do not-cross a shadow boundary.+Unquoted text locators normalize whitespace, ignore case, and match a substring;+quote the value for an exact, case-sensitive match, such as+`text="Save changes"`. They select the smallest matching element and reject an+ambiguous match.-Snapshot node labels such as `button` and `textbox` are accessibility roles,-not necessarily HTML tag names. Use the current `@N` for an immediate action,-prefer a generated `loc=role:` for semantic reuse, and use CSS only when the-actual DOM structure is known.+Snapshot labels such as `button` and `textbox` are accessibility roles, not+necessarily HTML tag names. Use the current ref for an immediate action and a+generated locator for reuse. CSS searches the document and nested open shadow+roots; XPath and closed shadow roots do not cross shadow boundaries.-Use an `@N` ref only with the Page that produced it. Take another snapshot after navigation, a substantial DOM change, or raw CDP, and before using refs in a later round. Prefer a stable locator for long-lived reuse.+A ref belongs only to the Page that produced it. Take another snapshot after+navigation, a substantial DOM change, raw CDP, or before reusing a ref in a+later round.-### 2. Visual path: screenshot + mouse/keyboard+### Visual pages: screenshot, mouse, and keyboard-Use the visual path first for canvas, rich-text editors, spreadsheets, maps, and virtualized interfaces. Load and inspect the screenshot with an image-viewing tool. Before entering a large amount of content, perform one tiny write probe and inspect another screenshot to confirm that it landed in the correct place.+Use a screenshot with mouse and keyboard operations for canvas, rich-text,+spreadsheets, maps, and other interfaces that lack useful DOM semantics:```jsconst path = await page.screenshot({ path: "/absolute/path/before.png" });--await page.mouse.move(420, 260);await page.mouse.click(420, 260);await page.keyboard.type("hello");console.log({ screenshot: path });```-Coordinates use CSS pixels. A Page object starts with mouse position `(0, 0)` in each round.--Use `ControlOrMeta+A/C/V/Z` for portable editing shortcuts. For document start and end, use `Meta+ArrowUp` / `Meta+ArrowDown` on macOS and `Control+Home` / `Control+End` on Windows.+Inspect the screenshot with an image-viewing tool. Coordinates use CSS pixels.+Keyboard names and `+`-separated chords follow Playwright syntax; use+`ControlOrMeta` for portable shortcuts. Low-level mouse and keyboard methods+do not return action receipts, so verify their effect explicitly.-### 3. Page JavaScript and CDP+### Page JavaScript and CDP-Use `page.evaluate()` for bulk extraction, complex DOM processing, or in-page state. The function accepts one JSON-serializable argument and must return a JSON-serializable value.+Use `page.evaluate()` for bulk extraction or complex in-page work. It accepts+one JSON-serializable argument and must return a JSON-serializable value:```jsconst rows = await page.evaluate(@@ -183,147 +246,60 @@ const rows = await page.evaluate();```-Use CDP only for capabilities missing from the Page API:--- `page.cdp()` sends Page, Runtime, DOM, Network, Input, and similar commands to that Page's session.-- `task.cdp()` is only for the Target and Browser domains.-- Every CDP call returns a Promise and defaults to `timeout: 15_000`. Set another millisecond timeout when needed and handle rejection.--`page.targetId` is the browser's internal tab identifier. Read it only when directly calling a `Target.*` CDP command that requires `targetId`. Use Page objects and labels for ordinary page operations, and do not save a target ID across rounds.--Raw CDP may change document or session state. Do not reuse refs created before the call; take another snapshot first.--## Page methods and options+Use `page.cdp()` only for Page, Runtime, DOM, Network, Input, and similar+commands missing from the Page API. Use `task.cdp()` for Target and Browser+commands. Raw CDP invalidates existing refs. `page.targetId` is for advanced+`Target.*` commands only; do not persist it across rounds.-Unknown option fields are rejected. All time values are milliseconds.+## Action results, popups, and dialogs-Page identity and inspection:+High-level navigation, selector actions, `mouse.click()`, and+`keyboard.press()` return a lightweight receipt. New tabs are adopted and may+appear in `receipt.popups`:```js-page.label;-page.spaceId;-page.openedBy;-page.targetId;--await page.url();-await page.title();-await page.info();-await page.events();+const receipt = await page.click('a[target="_blank"]');+for (const popup of receipt.popups ?? []) {+ const popupPage = task.page(popup.label);+ await popupPage.waitForURL(/\/expected-path(?:[?#]|$)/, { timeout: 10_000 });+}```-`page.info()` returns `{ url, title, w, h, sx, sy, pw, ph }`, or `{ dialog }` while a JavaScript dialog is pending. `page.events()` reads and clears pending CDP events for this Page only.--Navigation, observation, JavaScript, waits, files, and CDP:--```js-await page.goto(url, { timeout });-await page.snapshot({ scope, includeActionMarks, includeStableLocator });-await page.screenshot({- path,- fullPage,- clip: { x, y, width, height, scale },- raw,-});-await page.evaluate(fnOrString, argument);-await page.fetch(url, options);-await page.cdp(method, params, { timeout });-await page.waitForURL(urlOrRegExp, { timeout });-await page.waitForTimeout(timeout);-await page.waitForSelector(selector, { timeout, state });-await page.waitForLoadState(state, { timeout, idleMs });-await page.setInputFiles(selector, pathOrPaths);-const chooserPromise = page.waitForFileChooser({ timeout });-await page.click(selector);-const chooser = await chooserPromise;-await chooser.setFiles(pathOrPaths);-await page.scrollBy(deltaY, { deltaX, behavior });-await page.close();-```+A popup may initially be `about:blank`; wait for its URL when the destination+matters. Slowly propagating popups appear on the next `pages()` or `tabs()`+reconciliation.-- `goto()` defaults to `timeout: 15_000`.-- `waitForURL()` accepts an exact URL string or a `RegExp`, defaults to- `timeout: 10_000`, and does not activate the Page.-- `waitForTimeout()` waits a fixed number of milliseconds without activating- the Page. Use it only for debugging or brief visual stabilization; prefer a- URL, selector, load-state, or application-state wait in normal flows.-- `snapshot()` defaults to `{ scope: "full_page", includeActionMarks: true, includeStableLocator: true }`. `scope` is `"full_page"` or `"only_within_viewport"`; there is no `diff` option.-- Omit `screenshot()`'s `path` to receive a temporary PNG path; provided paths should be absolute. `clip.scale` is optional and positive. `raw` defaults to `false`; set it only for uncorrected device-pixel output.-- `evaluate()` accepts a function with at most one JSON-serializable argument, or a string expression with no argument. Its return value must also be JSON-serializable.-- Raw `page.cdp()` invalidates existing refs.-- `waitForSelector()` defaults to `timeout: 10_000`.-- `waitForLoadState()` accepts `"domcontentloaded"`, `"load"`, and `"networkidle"`, defaults to `timeout: 10_000`, and uses `idleMs: 500` for network idle.-- Use `setInputFiles()` with an existing file input, its label, or a container around it. It accepts absolute paths; `[]` clears the selection without opening a system dialog.-- If the site creates the file input only after a click, call `waitForFileChooser()` before the click, as shown above. `chooser.isMultiple()` reports whether it accepts multiple files. A chooser opened unexpectedly by `click()`, `dblclick()`, `mouse.click()`, or `keyboard.press()` is cancelled before the system dialog appears.-- `scrollBy()` defaults to `{ deltaX: 0, behavior: "auto" }`. `behavior` is `"auto"`, `"instant"`, or `"smooth"`.--Element actions:+A synchronous JavaScript dialog may appear as `receipt.dialog` or in+`page.info()`. Handle it before continuing:```js-await page.click(selector, { button, clickCount, delay, position: { x, y } });-await page.dblclick(selector, { button, delay, position: { x, y } });-await page.hover(selector, { position: { x, y } });-await page.dragAndDrop(source, target, {- button,- sourcePosition: { x, y },- targetPosition: { x, y },-});-await page.fill(selector, value, { clearFirst });+await page.cdp("Page.handleJavaScriptDialog", { accept: true });+// Use accept: false to dismiss it.```-Pointer actions and `fill()` update Ego Lite's visible Agent cursor. `fill()`-does not synthesize a mouse event just for the cursor hint. Bare-`page.keyboard` calls do not move the cursor because they have no target-element; click or fill an explicit element first when that visual context-matters.--High-level `goto()`, selector actions, `mouse.click()`, and `keyboard.press()` return lightweight receipts:--```js-const receipt = await page.click("#submit");-console.log(receipt.popups ?? []);-```+After an action, verify the expected URL, selector, snapshot, screenshot, file,+or application state. Prefer state-based waits over `waitForTimeout()`.-Receipts report newly opened Pages and may report a synchronous JavaScript dialog-when Ego Lite keeps Agent control. A dialog receipt has `{ dialog }`; handle it with-`page.cdp("Page.handleJavaScriptDialog", { accept: true })` or `accept: false`-before continuing. The dialog command uses the existing Page session without-activating the Page again. After any other action, confirm navigation and page-changes with `url()`, `waitForSelector()`, `info()`, `snapshot()`, a screenshot,-an export, or a readback.+## Files and requests-Mouse and keyboard primitives:+Set an existing file input directly with absolute paths:```js-await page.mouse.click(x, y, { button, clickCount, delay });-await page.mouse.move(x, y, { steps });-await page.mouse.down({ button, clickCount });-await page.mouse.up({ button, clickCount });-await page.mouse.wheel(deltaX, deltaY);--await page.keyboard.down(key);-await page.keyboard.up(key);-await page.keyboard.press(chord, { delay });-await page.keyboard.type(text, { delay });-await page.keyboard.insertText(text);+await page.setInputFiles("input[type=file]", ["/absolute/path/report.pdf"]);```-Keyboard key names and `+`-separated chords follow Playwright syntax. Modifier-names (`Alt`, `Control`, `Meta`, `Shift`, and `ControlOrMeta`) are-case-insensitive; other key names remain case-sensitive. Use `ControlOrMeta`-for portable shortcuts.--Low-level `mouse.move/down/up/wheel`, `keyboard.down/up/type/insertText`, and `scrollBy()` do not return an action receipt; verify their effect explicitly.--For exact details of one method, use runtime help. Read `references/api.md` for the generated complete reference. Do not invent methods or options.+If the site creates the input only after a click, start waiting first:```js-console.log(help("Page.click"));-console.log(help("TaskSpace.openPage"));+const chooserPromise = page.waitForFileChooser({ timeout: 10_000 });+await page.click("button.upload");+const chooser = await chooserPromise;+await chooser.setFiles("/absolute/path/report.pdf");```-## Requests--Use `page.fetch()` to request resources from the Page context. It uses the Page's relative URL, cookies, CORS, and service worker and returns `{ ok, status, statusText, url, headers, body }`:+Use `page.fetch()` for requests that need the Page's relative URL, cookies,+CORS, or service worker. It returns+`{ ok, status, statusText, url, headers, body }`:```jsconst response = await page.fetch("/api/items", {@@ -332,51 +308,38 @@ const response = await page.fetch("/api/items", {body: JSON.stringify({ limit: 20 }),timeout: 10_000,});--console.log({- ok: response.ok,- status: response.status,- headers: response.headers,- body: response.body,-});```-`page.fetch()` defaults to `timeout: 20_000` and does not accept `signal`. `headers` must map strings to strings, and `body` must be a string. It supports `method`, `headers`, `body`, `cache`, `credentials`, `mode`, `redirect`, `integrity`, `keepalive`, `referrer`, and `referrerPolicy`; read `references/api.md` for their accepted values.--Use the standard Node.js `fetch()` for background requests that do not need Page cookies or CORS semantics.--## Wait, recover, and verify+Use standard Node.js `fetch()` for background requests that do not need Page+browser semantics.-- Decide how to verify the result before triggering an action. Verify with `waitForSelector()`, `waitForLoadState()`, action receipts, `page.url()`, `page.info()`, or the target page's state. Do not use `waitForTimeout()` instead of checking a state the Page can expose.-- When page structure is unknown, observe it in one focused pass, then perform related actions in one script round. Do not retry similar selectors across many rounds.-- A single-element action must identify one clear target. On zero matches, inspect the page, overlays, dialogs, and load state. On multiple matches, use a more specific locator.-- After a failure, take one targeted snapshot, screenshot, or state reading before changing approach. Do not repeat nearly identical actions.-- When `page.info()` returns `{ dialog: ... }`, accept it with `page.cdp('Page.handleJavaScriptDialog', { accept: true })` or reject it with `{ accept: false }` before continuing.-- When `page.info()` reports `w: 0` or `h: 0`, stop coordinate and screenshot actions, restore a real viewport, and verify again.+## User control and completion-## User control and task completion+Stop immediately when the user takes control, or when the space is inactive or+not assigned to the Agent. Do not retry or route around the stop. Browser+permission prompts, device choosers, and JavaScript dialogs can cause the same+handoff; ask the user to handle them instead of taking control back+automatically.-Stop immediately when the user takes control, or when the space is inactive or not assigned to the Agent. Do not retry or route around the stop. Resume control only after the user explicitly asks to continue.--Browser permission prompts, device choosers, and JavaScript dialogs can cause the same handoff. Ask the user to handle or review the prompt; never grant, deny, or take control back automatically.--When the user must act in the browser, call `await task.handOff()`, end the current round, and tell the user what to do. After the user confirms, resume the original space in the next round:+When the user must act in the browser, call `await task.handOff()`, end the+round, and explain what they should do. After the user confirms, resume the+same space:```js-const spaceId = 7;-const task = await takeOverTaskSpace(spaceId);+const task = await takeOverTaskSpace(7);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 `tabs()` 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:+`userPage` may be unmanaged; adopt it before operating it. Use+`waitForControl()` only when the user already knows what to do and the current+script must wait in place. Claim a user-owned or inactive space only when the+user explicitly asks:```js-const spaceId = 7;-const task = await claimTaskSpace(spaceId);+const task = await claimTaskSpace(7);```-After verifying the final result, call `task.close()` at the end of the current round by default. Call `task.finish()` only when the user asks to keep the pages, must continue on the result page, or the result cannot be delivered through a URL, file, or summary. Use a separate completion round only when the choice depends on user confirmation. Do not claim that the space ended or closed until the method resolves.+After verifying the result, call `task.close()` by default. Use+`task.finish()` only when the user asks to keep the pages, must continue from+the result page, or the result cannot be delivered through a URL, file, or+summary. Do not report completion until the chosen method resolves.diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.mdindex 01297c2..4cd87c9 100644--- a/skills/ego-browser/references/api.md+++ b/skills/ego-browser/references/api.md@@ -6,13 +6,14 @@ High-level Page actions return a receipt that may contain `popups` or a synchron## 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. |-| `fileChooser.isMultiple()` | — | Report whether the chooser accepts multiple files. |-| `await fileChooser.setFiles(pathOrPaths)` | — | Set files on an intercepted chooser without a system dialog. |+| API | Options | Purpose |+| ------------------------------------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |+| `await profiles()` | — | List browser profiles available for new task spaces. |+| `await taskSpace(nameOrId, { profileId? })` | `profileId` — Browser profile id returned by profiles(); new spaces only. | Reuse or create an Agent-owned task space; profileId applies only to a new named space. |+| `await claimTaskSpace(spaceId)` | — | Claim a user-owned or inactive space after user approval and return TaskSpace. |+| `await takeOverTaskSpace(spaceId)` | — | Resume an Agent-owned space after user approval and return TaskSpace. |+| `fileChooser.isMultiple()` | — | Report whether the chooser accepts multiple files. |+| `await fileChooser.setFiles(pathOrPaths)` | — | Set files on an intercepted chooser without a system dialog. |## TaskSpace