The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
fix(ego-browser): structured resolution errors and handle release contract
0x05c148da4f640
diff --git a/package/ego-browser/artifacts/ego-browser/index.js b/package/ego-browser/artifacts/ego-browser/index.jsindex 07911f9..1e7eb88 100755--- a/package/ego-browser/artifacts/ego-browser/index.js+++ b/package/ego-browser/artifacts/ego-browser/index.js@@ -7161,12 +7161,29 @@ function refSortKey(refId) {return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER;}+class ElementResolutionError extends Error {+ kind;+ constructor(message, kind) {+ super(message);+ this.name = "ElementResolutionError";+ this.kind = kind;+ }+}+function exceptionText(result) {+ const d = result?.exceptionDetails;+ return d?.exception?.description || d?.text || "evaluation error";+}+function matchCountKind(message) {+ const m = /matched (\d+)/.exec(message);+ const n = m ? Number(m[1]) : 0;+ return n > 1 ? "permanent" : "transient";+}async function resolveElementCenter(cdp, sessionId, refMap, selectorOrRef, iframeSessions = new Map()) {const refId = parseRef(selectorOrRef);if (refId) {const entry = refMap.get(refId);if (!entry) {- throw new Error(`Unknown ref: ${refId}`);+ throw new ElementResolutionError(`Unknown ref: ${refId}`, "transient");}const effectiveSessionId = resolveFrameSession(entry.frameId, sessionId, iframeSessions);if (entry.backendNodeId !== undefined && entry.backendNodeId !== null) {@@ -7191,9 +7208,12 @@ async function resolveElementCenter(cdp, sessionId, refMap, selectorOrRef, iframreturnByValue: true,awaitPromise: false}, sessionId);+ if (result.exceptionDetails) {+ throw new ElementResolutionError(`Invalid selector: ${selectorOrRef}: ${exceptionText(result)}`, "permanent");+ }const value = result.result?.value;if (typeof value?.x !== "number" || typeof value?.y !== "number") {- throw new Error(`Element not found: ${selectorOrRef}`);+ throw new ElementResolutionError(`Element not found: ${selectorOrRef}`, "transient");}return { x: value.x, y: value.y, sessionId };}@@ -7202,7 +7222,7 @@ async function resolveElementObjectId(cdp, sessionId, refMap, selectorOrRef, ifrif (refId) {const entry = refMap.get(refId);if (!entry) {- throw new Error(`Unknown ref: ${refId}`);+ throw new ElementResolutionError(`Unknown ref: ${refId}`, "transient");}const effectiveSessionId = resolveFrameSession(entry.frameId, sessionId, iframeSessions);if (entry.backendNodeId !== undefined && entry.backendNodeId !== null) {@@ -7224,7 +7244,7 @@ async function resolveElementObjectId(cdp, sessionId, refMap, selectorOrRef, ifrconst result = await send(cdp, "DOM.resolveNode", { backendNodeId, objectGroup: "ego-browser" }, effectiveSessionId);const objectId = result.object?.objectId;if (!objectId) {- throw new Error(`No objectId for ref ${refId}`);+ throw new ElementResolutionError(`No objectId for ref ${refId}`, "permanent");}return { objectId, sessionId: effectiveSessionId };}@@ -7235,11 +7255,15 @@ async function resolveElementObjectId(cdp, sessionId, refMap, selectorOrRef, ifrconst result = await send(cdp, "Runtime.evaluate", {expression: buildFindElementJs(selectorOrRef),returnByValue: false,- awaitPromise: false+ awaitPromise: false,+ objectGroup: "ego-browser"}, sessionId);+ if (result.exceptionDetails) {+ throw new ElementResolutionError(`Invalid selector: ${selectorOrRef}: ${exceptionText(result)}`, "permanent");+ }const objectId = result.result?.objectId;if (!objectId) {- throw new Error(`Element not found: ${selectorOrRef}`);+ throw new ElementResolutionError(`Element not found: ${selectorOrRef}`, "transient");}return { objectId, sessionId };}@@ -7263,12 +7287,15 @@ async function resolveLocatorCenter(cdp, sessionId, locator) {returnByValue: true,awaitPromise: false}, sessionId);+ if (result.exceptionDetails) {+ throw new ElementResolutionError(`Invalid selector: ${locator.raw}: ${exceptionText(result)}`, "permanent");+ }const value = result.result?.value;if (value?.error) {- throw new Error(value.error);+ throw new ElementResolutionError(value.error, matchCountKind(value.error));}if (typeof value?.x !== "number" || typeof value?.y !== "number") {- throw new Error(`Element not found: ${locator.raw}`);+ throw new ElementResolutionError(`Element not found: ${locator.raw}`, "transient");}return { x: value.x, y: value.y, sessionId };}@@ -7278,22 +7305,26 @@ async function resolveLocatorObjectId(cdp, sessionId, locator) {const result = await send(cdp, "DOM.resolveNode", { backendNodeId, objectGroup: "ego-browser" }, sessionId);const objectId = result.object?.objectId;if (!objectId) {- throw new Error(`No objectId for locator ${locator.raw}`);+ throw new ElementResolutionError(`No objectId for locator ${locator.raw}`, "permanent");}return { objectId, sessionId };}const count = await locatorCount(cdp, sessionId, locator);- if (count !== 1) {- throw new Error(`Locator ${locator.raw} matched ${count} elements`);+ if (count === 0) {+ throw new ElementResolutionError(`Locator ${locator.raw} matched 0 elements`, "transient");+ }+ if (count > 1) {+ throw new ElementResolutionError(`Locator ${locator.raw} matched ${count} elements`, "permanent");}const result = await send(cdp, "Runtime.evaluate", {expression: buildLocatorFindJs(locator),returnByValue: false,- awaitPromise: false+ awaitPromise: false,+ objectGroup: "ego-browser"}, sessionId);const objectId = result.result?.objectId;if (!objectId) {- throw new Error(`Element not found: ${locator.raw}`);+ throw new ElementResolutionError(`Element not found: ${locator.raw}`, "transient");}return { objectId, sessionId };}@@ -7303,6 +7334,9 @@ async function locatorCount(cdp, sessionId, locator) {returnByValue: true,awaitPromise: false}, sessionId);+ if (result.exceptionDetails) {+ throw new ElementResolutionError(`Invalid selector: ${locator.raw}: ${exceptionText(result)}`, "permanent");+ }return Number(result.result?.value || 0);}async function findBackendNodeIdByRoleName(cdp, sessionId, role, name, nth = undefined, frameId = undefined, iframeSessions = new Map()) {@@ -7319,13 +7353,13 @@ async function findBackendNodeIdByRoleName(cdp, sessionId, role, name, nth = und}if (matchCount === nthIndex) {if (node.backendDOMNodeId === undefined || node.backendDOMNodeId === null) {- throw new Error(`AX node has no backendDOMNodeId for role=${role} name=${name}`);+ throw new ElementResolutionError(`AX node has no backendDOMNodeId for role=${role} name=${name}`, "permanent");}return node.backendDOMNodeId;}matchCount += 1;}- throw new Error(`Could not locate element with role=${role} name=${name}`);+ throw new ElementResolutionError(`Could not locate element with role=${role} name=${name}`, "transient");}async function findUniqueBackendNodeIdByRoleName(cdp, sessionId, role, name) {const result = await send(cdp, "Accessibility.getFullAXTree", {}, sessionId);@@ -7338,12 +7372,15 @@ async function findUniqueBackendNodeIdByRoleName(cdp, sessionId, role, name) {matches.push(node);}}- if (matches.length !== 1) {- throw new Error(`Locator role:${role}[name=${JSON.stringify(name)}] matched ${matches.length} elements`);+ if (matches.length === 0) {+ throw new ElementResolutionError(`Locator role:${role}[name=${JSON.stringify(name)}] matched 0 elements`, "transient");+ }+ if (matches.length > 1) {+ throw new ElementResolutionError(`Locator role:${role}[name=${JSON.stringify(name)}] matched ${matches.length} elements`, "permanent");}const backendNodeId = matches[0].backendDOMNodeId;if (backendNodeId === undefined || backendNodeId === null) {- throw new Error(`AX node has no backendDOMNodeId for role=${role} name=${name}`);+ throw new ElementResolutionError(`AX node has no backendDOMNodeId for role=${role} name=${name}`, "permanent");}return backendNodeId;}@@ -7494,6 +7531,72 @@ async function ensureRefMapForRef(selectorOrRef) {}}+/**+ * 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.+ * 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}>}+ */+async function resolveHandle(selectorOrRef) {+ await ensureRefMapForRef(selectorOrRef);+ return resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);+}+/**+ * Release a Runtime objectId handle. Best-effort: swallows "already gone"+ * errors (stale handle, lost session, destroyed context).+ * @param {string} objectId Runtime remote object id to release.+ * @param {string} [sessionId] Session that owns the handle.+ * @returns {Promise<void>}+ */+async function releaseHandle(objectId, sessionId) {+ if (!objectId)+ return;+ try {+ await cdp("Runtime.releaseObject", { objectId }, sessionId);+ }+ catch {+ // Handle/session already invalid; releasing is best-effort.+ }+}+/**+ * Resolve a handle, run fn(handle), then release the handle — even if fn throws.+ * @param {string} selectorOrRef Selector or ref string.+ * @param {(handle: {objectId: string, sessionId?: string}) => Promise<any>} fn Callback bound to the resolved handle.+ * @returns {Promise<any>} Whatever fn returns.+ */+async function withHandle(selectorOrRef, fn) {+ const handle = await resolveHandle(selectorOrRef);+ try {+ return await fn(handle);+ }+ finally {+ await releaseHandle(handle.objectId, handle.sessionId);+ }+}+/**+ * Resolve an element and call a function on it via Runtime.callFunctionOn,+ * with the element bound as `this`. The resolved handle is released afterward;+ * the returned objectId is already freed and must not be reused.+ * @param {string} selectorOrRef Selector or ref string.+ * @param {string} functionDeclaration Function source whose `this` is the element.+ * @param {Array<unknown>} [args=[]] Arguments passed by value.+ * @returns {Promise<{result: any, objectId: string, sessionId?: string}>}+ */+async function resolveAndCall(selectorOrRef, functionDeclaration, args = []) {+ return withHandle(selectorOrRef, async ({ objectId, sessionId }) => {+ const result = await cdp("Runtime.callFunctionOn", {+ functionDeclaration,+ objectId,+ arguments: args.map((value) => ({ value })),+ returnByValue: true,+ awaitPromise: false+ }, sessionId);+ return { result, objectId, sessionId };+ });+}+async function drainEvents() {return drainBrowserEvents();}@@ -7527,21 +7630,21 @@ async function elementCenter(selectorOrRef) {return resolveElementCenter({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);}async function fillElement(selectorOrRef, value) {- await ensureRefMapForRef(selectorOrRef);- const resolved = await resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);- await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function() { this.focus(); }",- objectId: resolved.objectId,- returnByValue: true,- awaitPromise: false- }, resolved.sessionId);- await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function() { this.select && this.select(); this.value = ''; this.dispatchEvent(new Event('input', { bubbles: true })); }",- objectId: resolved.objectId,- returnByValue: true,- awaitPromise: false- }, resolved.sessionId);- await cdp("Input.insertText", { text: String(value) });+ await withHandle(selectorOrRef, async ({ objectId, sessionId }) => {+ await cdp("Runtime.callFunctionOn", {+ functionDeclaration: "function() { this.focus(); }",+ objectId,+ returnByValue: true,+ awaitPromise: false+ }, sessionId);+ await cdp("Runtime.callFunctionOn", {+ functionDeclaration: "function() { this.select && this.select(); this.value = ''; this.dispatchEvent(new Event('input', { bubbles: true })); }",+ objectId,+ returnByValue: true,+ awaitPromise: false+ }, sessionId);+ await cdp("Input.insertText", { text: String(value) });+ });}async function captureScreenshot(path = join(tmpdir(), "ego-browser-shot.png"), options = {}) {const full = options.full ?? false;@@ -7577,15 +7680,16 @@ async function captureScreenshot(path = join(tmpdir(), "ego-browser-shot.png"),return path;}async function evaluateBrowserElement(selectorOrRef, functionDeclaration, args) {- const resolved = await resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);- const response = await cdp("Runtime.callFunctionOn", {- functionDeclaration,- objectId: resolved.objectId,- arguments: [{ objectId: resolved.objectId }, ...args.map((value) => ({ value }))],- returnByValue: true,- awaitPromise: true- }, resolved.sessionId);- return remoteValue(response);+ return withHandle(selectorOrRef, async ({ objectId, sessionId }) => {+ const response = await cdp("Runtime.callFunctionOn", {+ functionDeclaration,+ objectId,+ arguments: [{ objectId }, ...args.map((value) => ({ value }))],+ returnByValue: true,+ awaitPromise: true+ }, sessionId);+ return remoteValue(response);+ });}function remoteValue(response) {const result = response.result || {};@@ -7920,19 +8024,6 @@ var pointer = /*#__PURE__*/Object.freeze({scrollToBottomUntil: scrollToBottomUntil});-/**- * 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.- * 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}>}- */-async function resolveHandle(selectorOrRef) {- await ensureRefMapForRef(selectorOrRef);- return resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);-}-/*** Sleep for a fixed number of seconds.* @param {number} [seconds=1.0] Seconds to wait.@@ -7961,21 +8052,34 @@ async function waitForElement(selector, options = {}) {const deadline = state.now() + timeout * 1000;const visibilityFn = "function(){if(typeof this.checkVisibility==='function')return this.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(this);return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0';}";while (state.now() < deadline) {+ let handle;+ try {+ handle = await resolveHandle(selector);+ }+ catch (err) {+ if (err instanceof ElementResolutionError && err.kind === "transient") {+ await state.sleep(300);+ continue; // not found / not ready yet — keep polling.+ }+ throw err; // permanent (bad selector / ambiguous) or unknown error — fail loud.+ }try {- const { objectId, sessionId } = await resolveHandle(selector);if (!visible)return true;const response = await cdp("Runtime.callFunctionOn", {functionDeclaration: visibilityFn,- objectId,+ objectId: handle.objectId,returnByValue: true,awaitPromise: false- }, sessionId);+ }, handle.sessionId);if (response.result?.value)return true;}catch {- // element not yet resolvable; keep polling.+ // visibility check failed (element raced away); treat as not-ready, keep polling.+ }+ finally {+ await releaseHandle(handle.objectId, handle.sessionId);}await state.sleep(300);}@@ -8086,28 +8190,29 @@ async function fillInput(selector, text, options = {}) {if (timeout > 0 && !await waitForElement(selector, { timeout })) {throw new Error(`fillInput: element not found: ${JSON.stringify(selector)}`);}- const { objectId, sessionId } = await resolveHandle(selector);- await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function(){this.focus(); if(typeof this.select==='function') this.select();}",- objectId,- returnByValue: true,- awaitPromise: false- }, sessionId);- if (clearFirst) {+ await withHandle(selector, async ({ objectId, sessionId }) => {await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function(){this.value=''; this.dispatchEvent(new Event('input',{bubbles:true}));}",+ functionDeclaration: "function(){this.focus(); if(typeof this.select==='function') this.select();}",objectId,returnByValue: true,awaitPromise: false}, sessionId);- }- await cdp("Input.insertText", { text }, sessionId);- await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function(){this.dispatchEvent(new Event('input',{bubbles:true})); this.dispatchEvent(new Event('change',{bubbles:true}));}",- objectId,- returnByValue: true,- awaitPromise: false- }, sessionId);+ if (clearFirst) {+ await cdp("Runtime.callFunctionOn", {+ functionDeclaration: "function(){this.value=''; this.dispatchEvent(new Event('input',{bubbles:true}));}",+ objectId,+ returnByValue: true,+ awaitPromise: false+ }, sessionId);+ }+ await cdp("Input.insertText", { text }, sessionId);+ await cdp("Runtime.callFunctionOn", {+ functionDeclaration: "function(){this.dispatchEvent(new Event('input',{bubbles:true})); this.dispatchEvent(new Event('change',{bubbles:true}));}",+ objectId,+ returnByValue: true,+ awaitPromise: false+ }, sessionId);+ });}/*** Focus an element and dispatch a DOM KeyboardEvent in page JavaScript.@@ -8118,17 +8223,8 @@ async function fillInput(selector, text, options = {}) {* @returns {Promise<void>}*/async function dispatchKey(selector, key = "Enter", event = "keypress") {- const keyCodes = { Enter: 13, Tab: 9, Escape: 27, Backspace: 8, " ": 32, ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40 };- const keyCode = keyCodes[key] || (key.length === 1 ? key.codePointAt(0) : 0);- const { code } = keyDefinition(key);- const { objectId, sessionId } = await resolveHandle(selector);- await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function(keyCode, key, code, event){this.focus(); this.dispatchEvent(new KeyboardEvent(event,{key,code,keyCode,which:keyCode,bubbles:true}));}",- objectId,- arguments: [{ value: keyCode }, { value: key }, { value: code }, { value: event }],- returnByValue: true,- awaitPromise: false- }, sessionId);+ const { vk, code } = keyDefinition(key);+ await resolveAndCall(selector, "function(keyCode, key, code, event){this.focus(); this.dispatchEvent(new KeyboardEvent(event,{key,code,keyCode,which:keyCode,bubbles:true}));}", [vk, key, code, event]);}var keyboard = /*#__PURE__*/Object.freeze({@@ -8147,8 +8243,9 @@ var keyboard = /*#__PURE__*/Object.freeze({*/async function uploadFile(selector, path) {const files = Array.isArray(path) ? path : [path];- const { objectId, sessionId } = await resolveHandle(selector);- await cdp("DOM.setFileInputFiles", { files, objectId }, sessionId);+ await withHandle(selector, async ({ objectId, sessionId }) => {+ await cdp("DOM.setFileInputFiles", { files, objectId }, sessionId);+ });}var files = /*#__PURE__*/Object.freeze({diff --git a/package/ego-browser/src/driver/element-ops.ts b/package/ego-browser/src/driver/element-ops.tsindex 21c3395..2566814 100644--- a/package/ego-browser/src/driver/element-ops.ts+++ b/package/ego-browser/src/driver/element-ops.ts@@ -15,22 +15,55 @@ export async function resolveHandle(selectorOrRef) {return resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);}+/**+ * Release a Runtime objectId handle. Best-effort: swallows "already gone"+ * errors (stale handle, lost session, destroyed context).+ * @param {string} objectId Runtime remote object id to release.+ * @param {string} [sessionId] Session that owns the handle.+ * @returns {Promise<void>}+ */+export async function releaseHandle(objectId, sessionId) {+ if (!objectId) return;+ try {+ await cdp("Runtime.releaseObject", { objectId }, sessionId);+ } catch {+ // Handle/session already invalid; releasing is best-effort.+ }+}++/**+ * Resolve a handle, run fn(handle), then release the handle — even if fn throws.+ * @param {string} selectorOrRef Selector or ref string.+ * @param {(handle: {objectId: string, sessionId?: string}) => Promise<any>} fn Callback bound to the resolved handle.+ * @returns {Promise<any>} Whatever fn returns.+ */+export async function withHandle(selectorOrRef, fn) {+ const handle = await resolveHandle(selectorOrRef);+ try {+ return await fn(handle);+ } finally {+ await releaseHandle(handle.objectId, handle.sessionId);+ }+}+/*** Resolve an element and call a function on it via Runtime.callFunctionOn,- * with the element bound as `this`.+ * with the element bound as `this`. The resolved handle is released afterward;+ * the returned objectId is already freed and must not be reused.* @param {string} selectorOrRef Selector or ref string.* @param {string} functionDeclaration Function source whose `this` is the element.* @param {Array<unknown>} [args=[]] Arguments passed by value.* @returns {Promise<{result: any, objectId: string, sessionId?: string}>}*/export async function resolveAndCall(selectorOrRef, functionDeclaration, args = []) {- const { objectId, sessionId } = await resolveHandle(selectorOrRef);- const result = await cdp("Runtime.callFunctionOn", {- functionDeclaration,- objectId,- arguments: args.map((value) => ({ value })),- returnByValue: true,- awaitPromise: false- }, sessionId);- return { result, objectId, sessionId };+ return withHandle(selectorOrRef, async ({ objectId, sessionId }) => {+ const result = await cdp("Runtime.callFunctionOn", {+ functionDeclaration,+ objectId,+ arguments: args.map((value) => ({ value })),+ returnByValue: true,+ awaitPromise: false+ }, sessionId);+ return { result, objectId, sessionId };+ });}diff --git a/package/ego-browser/src/driver/files.ts b/package/ego-browser/src/driver/files.tsindex 7251de9..046a411 100644--- a/package/ego-browser/src/driver/files.ts+++ b/package/ego-browser/src/driver/files.ts@@ -1,5 +1,5 @@import { cdp } from "../cdp-eval.js";-import { resolveHandle } from "./element-ops.js";+import { withHandle } from "./element-ops.js";/*** Set files on a file input.@@ -9,6 +9,7 @@ import { resolveHandle } from "./element-ops.js";*/export async function uploadFile(selector, path) {const files = Array.isArray(path) ? path : [path];- const { objectId, sessionId } = await resolveHandle(selector);- await cdp("DOM.setFileInputFiles", { files, objectId }, sessionId);+ await withHandle(selector, async ({ objectId, sessionId }) => {+ await cdp("DOM.setFileInputFiles", { files, objectId }, sessionId);+ });}diff --git a/package/ego-browser/src/driver/keyboard.ts b/package/ego-browser/src/driver/keyboard.tsindex dd7770b..7e22b8e 100644--- a/package/ego-browser/src/driver/keyboard.ts+++ b/package/ego-browser/src/driver/keyboard.ts@@ -1,5 +1,5 @@import { cdp } from "../cdp-eval.js";-import { resolveHandle, resolveAndCall } from "./element-ops.js";+import { withHandle, resolveAndCall } from "./element-ops.js";import { waitForElement } from "./waits.js";type FillInputOptions = {@@ -74,28 +74,29 @@ export async function fillInput(selector, text, options: FillInputOptions = {})if (timeout > 0 && !await waitForElement(selector, { timeout })) {throw new Error(`fillInput: element not found: ${JSON.stringify(selector)}`);}- const { objectId, sessionId } = await resolveHandle(selector);- await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function(){this.focus(); if(typeof this.select==='function') this.select();}",- objectId,- returnByValue: true,- awaitPromise: false- }, sessionId);- if (clearFirst) {+ await withHandle(selector, async ({ objectId, sessionId }) => {await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function(){this.value=''; this.dispatchEvent(new Event('input',{bubbles:true}));}",+ functionDeclaration: "function(){this.focus(); if(typeof this.select==='function') this.select();}",objectId,returnByValue: true,awaitPromise: false}, sessionId);- }- await cdp("Input.insertText", { text }, sessionId);- await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function(){this.dispatchEvent(new Event('input',{bubbles:true})); this.dispatchEvent(new Event('change',{bubbles:true}));}",- objectId,- returnByValue: true,- awaitPromise: false- }, sessionId);+ if (clearFirst) {+ await cdp("Runtime.callFunctionOn", {+ functionDeclaration: "function(){this.value=''; this.dispatchEvent(new Event('input',{bubbles:true}));}",+ objectId,+ returnByValue: true,+ awaitPromise: false+ }, sessionId);+ }+ await cdp("Input.insertText", { text }, sessionId);+ await cdp("Runtime.callFunctionOn", {+ functionDeclaration: "function(){this.dispatchEvent(new Event('input',{bubbles:true})); this.dispatchEvent(new Event('change',{bubbles:true}));}",+ objectId,+ returnByValue: true,+ awaitPromise: false+ }, sessionId);+ });}/**@@ -107,12 +108,10 @@ export async function fillInput(selector, text, options: FillInputOptions = {})* @returns {Promise<void>}*/export async function dispatchKey(selector, key = "Enter", event = "keypress") {- const keyCodes = { Enter: 13, Tab: 9, Escape: 27, Backspace: 8, " ": 32, ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40 };- const keyCode = keyCodes[key] || (key.length === 1 ? key.codePointAt(0) : 0);- const { code } = keyDefinition(key);+ const { vk, code } = keyDefinition(key);await resolveAndCall(selector,"function(keyCode, key, code, event){this.focus(); this.dispatchEvent(new KeyboardEvent(event,{key,code,keyCode,which:keyCode,bubbles:true}));}",- [keyCode, key, code, event]+ [vk, key, code, event]);}diff --git a/package/ego-browser/src/driver/observe.ts b/package/ego-browser/src/driver/observe.tsindex 7ea3270..2ba2599 100644--- a/package/ego-browser/src/driver/observe.ts+++ b/package/ego-browser/src/driver/observe.ts@@ -5,7 +5,8 @@ import { state } from "../state.js";import { cdp, js } from "../cdp-eval.js";import { pageInfo } from "./nav.js";import { browserEgo, browserSnapshotRefsToRefMap, drainBrowserEvents } from "../browser-runtime.js";-import { resolveElementCenter, resolveElementObjectId } from "../element-resolver.js";+import { resolveElementCenter } from "../element-resolver.js";+import { withHandle } from "./element-ops.js";import { browserRefMap, ensureRefMapForRef, registerSnapshotForRefRefresh } from "../ref-state.js";type SnapshotOptions = {@@ -68,21 +69,21 @@ export async function elementCenter(selectorOrRef) {}export async function fillElement(selectorOrRef, value) {- await ensureRefMapForRef(selectorOrRef);- const resolved = await resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);- await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function() { this.focus(); }",- objectId: resolved.objectId,- returnByValue: true,- awaitPromise: false- }, resolved.sessionId);- await cdp("Runtime.callFunctionOn", {- functionDeclaration: "function() { this.select && this.select(); this.value = ''; this.dispatchEvent(new Event('input', { bubbles: true })); }",- objectId: resolved.objectId,- returnByValue: true,- awaitPromise: false- }, resolved.sessionId);- await cdp("Input.insertText", { text: String(value) });+ await withHandle(selectorOrRef, async ({ objectId, sessionId }) => {+ await cdp("Runtime.callFunctionOn", {+ functionDeclaration: "function() { this.focus(); }",+ objectId,+ returnByValue: true,+ awaitPromise: false+ }, sessionId);+ await cdp("Runtime.callFunctionOn", {+ functionDeclaration: "function() { this.select && this.select(); this.value = ''; this.dispatchEvent(new Event('input', { bubbles: true })); }",+ objectId,+ returnByValue: true,+ awaitPromise: false+ }, sessionId);+ await cdp("Input.insertText", { text: String(value) });+ });}export async function captureScreenshot(path = join(tmpdir(), "ego-browser-shot.png"), options: CaptureScreenshotOptions = {}) {@@ -118,15 +119,16 @@ export async function captureScreenshot(path = join(tmpdir(), "ego-browser-shot.}async function evaluateBrowserElement(selectorOrRef, functionDeclaration, args) {- const resolved = await resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);- const response = await cdp("Runtime.callFunctionOn", {- functionDeclaration,- objectId: resolved.objectId,- arguments: [{ objectId: resolved.objectId }, ...args.map((value) => ({ value }))],- returnByValue: true,- awaitPromise: true- }, resolved.sessionId);- return remoteValue(response);+ return withHandle(selectorOrRef, async ({ objectId, sessionId }) => {+ const response = await cdp("Runtime.callFunctionOn", {+ functionDeclaration,+ objectId,+ arguments: [{ objectId }, ...args.map((value) => ({ value }))],+ returnByValue: true,+ awaitPromise: true+ }, sessionId);+ return remoteValue(response);+ });}function remoteValue(response) {diff --git a/package/ego-browser/src/driver/waits.ts b/package/ego-browser/src/driver/waits.tsindex f4e8485..f2a68d9 100644--- a/package/ego-browser/src/driver/waits.ts+++ b/package/ego-browser/src/driver/waits.ts@@ -1,6 +1,7 @@import { state } from "../state.js";import { cdp } from "../cdp-eval.js";-import { resolveHandle } from "./element-ops.js";+import { resolveHandle, releaseHandle } from "./element-ops.js";+import { ElementResolutionError } from "../element-resolver.js";import { type WaitForLoadOptions, waitForDocumentLoad } from "./load.js";import { drainEvents } from "./observe.js";@@ -44,18 +45,29 @@ export async function waitForElement(selector: string, options: WaitForElementOpconst deadline = state.now() + timeout * 1000;const visibilityFn = "function(){if(typeof this.checkVisibility==='function')return this.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(this);return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0';}";while (state.now() < deadline) {+ let handle;+ try {+ handle = await resolveHandle(selector);+ } catch (err) {+ if (err instanceof ElementResolutionError && err.kind === "transient") {+ await state.sleep(300);+ continue; // not found / not ready yet — keep polling.+ }+ throw err; // permanent (bad selector / ambiguous) or unknown error — fail loud.+ }try {- const { objectId, sessionId } = await resolveHandle(selector);if (!visible) return true;const response = await cdp("Runtime.callFunctionOn", {functionDeclaration: visibilityFn,- objectId,+ objectId: handle.objectId,returnByValue: true,awaitPromise: false- }, sessionId);+ }, handle.sessionId);if (response.result?.value) return true;} catch {- // element not yet resolvable; keep polling.+ // visibility check failed (element raced away); treat as not-ready, keep polling.+ } finally {+ await releaseHandle(handle.objectId, handle.sessionId);}await state.sleep(300);}diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.tsindex 0ccdc8b..61c8625 100644--- a/package/ego-browser/src/element-resolver.ts+++ b/package/ego-browser/src/element-resolver.ts@@ -1,11 +1,31 @@import { parseRef } from "./ref-map.js";+export class ElementResolutionError extends Error {+ kind: "transient" | "permanent";+ constructor(message: string, kind: "transient" | "permanent") {+ super(message);+ this.name = "ElementResolutionError";+ this.kind = kind;+ }+}++function exceptionText(result: any) {+ const d = result?.exceptionDetails;+ return d?.exception?.description || d?.text || "evaluation error";+}++function matchCountKind(message: string): "transient" | "permanent" {+ const m = /matched (\d+)/.exec(message);+ const n = m ? Number(m[1]) : 0;+ return n > 1 ? "permanent" : "transient";+}+export async function resolveElementCenter(cdp, sessionId, refMap, selectorOrRef, iframeSessions = new Map()) {const refId = parseRef(selectorOrRef);if (refId) {const entry = refMap.get(refId);if (!entry) {- throw new Error(`Unknown ref: ${refId}`);+ throw new ElementResolutionError(`Unknown ref: ${refId}`, "transient");}const effectiveSessionId = resolveFrameSession(entry.frameId, sessionId, iframeSessions);if (entry.backendNodeId !== undefined && entry.backendNodeId !== null) {@@ -31,9 +51,12 @@ export async function resolveElementCenter(cdp, sessionId, refMap, selectorOrRefreturnByValue: true,awaitPromise: false}, sessionId);+ if (result.exceptionDetails) {+ throw new ElementResolutionError(`Invalid selector: ${selectorOrRef}: ${exceptionText(result)}`, "permanent");+ }const value = result.result?.value;if (typeof value?.x !== "number" || typeof value?.y !== "number") {- throw new Error(`Element not found: ${selectorOrRef}`);+ throw new ElementResolutionError(`Element not found: ${selectorOrRef}`, "transient");}return { x: value.x, y: value.y, sessionId };}@@ -43,7 +66,7 @@ export async function resolveElementObjectId(cdp, sessionId, refMap, selectorOrRif (refId) {const entry = refMap.get(refId);if (!entry) {- throw new Error(`Unknown ref: ${refId}`);+ throw new ElementResolutionError(`Unknown ref: ${refId}`, "transient");}const effectiveSessionId = resolveFrameSession(entry.frameId, sessionId, iframeSessions);if (entry.backendNodeId !== undefined && entry.backendNodeId !== null) {@@ -64,7 +87,7 @@ export async function resolveElementObjectId(cdp, sessionId, refMap, selectorOrRconst result = await send(cdp, "DOM.resolveNode", { backendNodeId, objectGroup: "ego-browser" }, effectiveSessionId);const objectId = result.object?.objectId;if (!objectId) {- throw new Error(`No objectId for ref ${refId}`);+ throw new ElementResolutionError(`No objectId for ref ${refId}`, "permanent");}return { objectId, sessionId: effectiveSessionId };}@@ -77,11 +100,15 @@ export async function resolveElementObjectId(cdp, sessionId, refMap, selectorOrRconst result = await send(cdp, "Runtime.evaluate", {expression: buildFindElementJs(selectorOrRef),returnByValue: false,- awaitPromise: false+ awaitPromise: false,+ objectGroup: "ego-browser"}, sessionId);+ if (result.exceptionDetails) {+ throw new ElementResolutionError(`Invalid selector: ${selectorOrRef}: ${exceptionText(result)}`, "permanent");+ }const objectId = result.result?.objectId;if (!objectId) {- throw new Error(`Element not found: ${selectorOrRef}`);+ throw new ElementResolutionError(`Element not found: ${selectorOrRef}`, "transient");}return { objectId, sessionId };}@@ -107,12 +134,15 @@ async function resolveLocatorCenter(cdp, sessionId, locator) {returnByValue: true,awaitPromise: false}, sessionId);+ if (result.exceptionDetails) {+ throw new ElementResolutionError(`Invalid selector: ${locator.raw}: ${exceptionText(result)}`, "permanent");+ }const value = result.result?.value;if (value?.error) {- throw new Error(value.error);+ throw new ElementResolutionError(value.error, matchCountKind(value.error));}if (typeof value?.x !== "number" || typeof value?.y !== "number") {- throw new Error(`Element not found: ${locator.raw}`);+ throw new ElementResolutionError(`Element not found: ${locator.raw}`, "transient");}return { x: value.x, y: value.y, sessionId };}@@ -123,22 +153,26 @@ async function resolveLocatorObjectId(cdp, sessionId, locator) {const result = await send(cdp, "DOM.resolveNode", { backendNodeId, objectGroup: "ego-browser" }, sessionId);const objectId = result.object?.objectId;if (!objectId) {- throw new Error(`No objectId for locator ${locator.raw}`);+ throw new ElementResolutionError(`No objectId for locator ${locator.raw}`, "permanent");}return { objectId, sessionId };}const count = await locatorCount(cdp, sessionId, locator);- if (count !== 1) {- throw new Error(`Locator ${locator.raw} matched ${count} elements`);+ if (count === 0) {+ throw new ElementResolutionError(`Locator ${locator.raw} matched 0 elements`, "transient");+ }+ if (count > 1) {+ throw new ElementResolutionError(`Locator ${locator.raw} matched ${count} elements`, "permanent");}const result = await send(cdp, "Runtime.evaluate", {expression: buildLocatorFindJs(locator),returnByValue: false,- awaitPromise: false+ awaitPromise: false,+ objectGroup: "ego-browser"}, sessionId);const objectId = result.result?.objectId;if (!objectId) {- throw new Error(`Element not found: ${locator.raw}`);+ throw new ElementResolutionError(`Element not found: ${locator.raw}`, "transient");}return { objectId, sessionId };}@@ -149,6 +183,9 @@ async function locatorCount(cdp, sessionId, locator) {returnByValue: true,awaitPromise: false}, sessionId);+ if (result.exceptionDetails) {+ throw new ElementResolutionError(`Invalid selector: ${locator.raw}: ${exceptionText(result)}`, "permanent");+ }return Number(result.result?.value || 0);}@@ -166,13 +203,13 @@ async function findBackendNodeIdByRoleName(cdp, sessionId, role, name, nth = und}if (matchCount === nthIndex) {if (node.backendDOMNodeId === undefined || node.backendDOMNodeId === null) {- throw new Error(`AX node has no backendDOMNodeId for role=${role} name=${name}`);+ throw new ElementResolutionError(`AX node has no backendDOMNodeId for role=${role} name=${name}`, "permanent");}return node.backendDOMNodeId;}matchCount += 1;}- throw new Error(`Could not locate element with role=${role} name=${name}`);+ throw new ElementResolutionError(`Could not locate element with role=${role} name=${name}`, "transient");}async function findUniqueBackendNodeIdByRoleName(cdp, sessionId, role, name) {@@ -186,12 +223,15 @@ async function findUniqueBackendNodeIdByRoleName(cdp, sessionId, role, name) {matches.push(node);}}- if (matches.length !== 1) {- throw new Error(`Locator role:${role}[name=${JSON.stringify(name)}] matched ${matches.length} elements`);+ if (matches.length === 0) {+ throw new ElementResolutionError(`Locator role:${role}[name=${JSON.stringify(name)}] matched 0 elements`, "transient");+ }+ if (matches.length > 1) {+ throw new ElementResolutionError(`Locator role:${role}[name=${JSON.stringify(name)}] matched ${matches.length} elements`, "permanent");}const backendNodeId = matches[0].backendDOMNodeId;if (backendNodeId === undefined || backendNodeId === null) {- throw new Error(`AX node has no backendDOMNodeId for role=${role} name=${name}`);+ throw new ElementResolutionError(`AX node has no backendDOMNodeId for role=${role} name=${name}`, "permanent");}return backendNodeId;}