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
Refine tab helper surface
Aute9c6a75383db7
diff --git a/package/ego-browser/README.md b/package/ego-browser/README.mdindex d571d8c..88ea460 100644--- a/package/ego-browser/README.md+++ b/package/ego-browser/README.md@@ -68,7 +68,7 @@ src/pointer.ts click, hover, drag, scroll, scrollByobserve.ts snapshot, captureScreenshot, elementCenterkeyboard.ts typeText, pressKey, fillInput, dispatchKey- nav.ts tabs, gotoUrl, openOrReuseTab+ nav.ts tabs, gotoUrl, openOrReuseTab, closeTabload.ts waitForLoad and load orchestrationwaits.ts waitForElement, waitForNetworkIdle, waitfiles.ts uploadFilediff --git a/package/ego-browser/src/driver/nav.test.mjs b/package/ego-browser/src/driver/nav.test.mjsindex 3f6f499..c12f20a 100644--- a/package/ego-browser/src/driver/nav.test.mjs+++ b/package/ego-browser/src/driver/nav.test.mjs@@ -2,7 +2,8 @@ import test from "node:test";import assert from "node:assert/strict";import { browserCdp, invalidateSession, pendingDialog } from "../../dist/src/browser-runtime.js";-import { listTabs, newTab, pageInfo } from "../../dist/src/driver/nav.js";+import { listTabs, newTab, pageInfo, closeTab } from "../../dist/src/driver/nav.js";+import { setOverrides, state } from "../../dist/src/state.js";function withEgo(ego, fn) {const previous = globalThis.ego;@@ -110,6 +111,69 @@ test("newTab throws when the binding returns no targetId", async () => {});});+test("closeTab closes an explicit target and returns its id", async () => {+ const calls = [];+ const restore = setOverrides({+ cdpOverride(method, params, sessionId) {+ calls.push({ method, params, sessionId });+ return { success: true };+ }+ });+ try {+ assert.equal(await closeTab("target-2"), "target-2");+ } finally {+ restore();+ }++ assert.deepEqual(calls, [+ {+ method: "Target.closeTarget",+ params: { targetId: "target-2" },+ sessionId: undefined+ }+ ]);+});++test("closeTab closes the current tab and invalidates matching session state", async () => {+ const calls = [];+ await withEgo({+ async listTabs() {+ return {+ tabs: [+ { targetId: "target-1", active: true, title: "Example", url: "https://example.com/" }+ ]+ };+ }+ }, async () => {+ const restore = setOverrides({+ cdpOverride(method, params, sessionId) {+ calls.push({ method, params, sessionId });+ return { success: true };+ },+ sessionId: "session-1",+ sessionTargetId: "target-1",+ sessionAt: Date.now(),+ preferredTargetId: "target-1"+ });+ try {+ assert.equal(await closeTab(), "target-1");+ assert.equal(state.sessionId, null);+ assert.equal(state.sessionTargetId, null);+ assert.equal(state.preferredTargetId, null);+ } finally {+ restore();+ }+ });++ assert.deepEqual(calls, [+ {+ method: "Target.closeTarget",+ params: { targetId: "target-1" },+ sessionId: undefined+ }+ ]);+});+test("browser runtime enables Page events and tracks pending native dialogs", async () => {await withCdpRuntime(async ({ runtime, sent }) => {await browserCdp("Runtime.evaluate", { expression: "document.title" });diff --git a/package/ego-browser/src/driver/nav.ts b/package/ego-browser/src/driver/nav.tsindex 01636d7..e73955c 100644--- a/package/ego-browser/src/driver/nav.ts+++ b/package/ego-browser/src/driver/nav.ts@@ -1,4 +1,4 @@-import { browserEgo, ensureSession, invalidateSession, isBrowserRuntime, pendingDialog, setPreferredTarget } from "../browser-runtime.js";+import { browserEgo, clearPreferredTarget, ensureSession, invalidateSession, isBrowserRuntime, pendingDialog, setPreferredTarget } from "../browser-runtime.js";import { cdp, js } from "../cdp-eval.js";import { state } from "../state.js";import { waitForDocumentLoad } from "./load.js";@@ -32,6 +32,8 @@ type OpenOrReuseTabOptions = {settle?: number;};+type TabTarget = string | { targetId: string };+/*** Navigate the current tab to a URL using CDP Page.navigate.* @param {string} url Absolute or browser-supported URL to load.@@ -158,6 +160,26 @@ export async function openOrReuseTab(url: string, options: OpenOrReuseTabOptionsreturn { targetId, url, title: "", active: true, reused: false };}+/**+ * Close a browser tab by target id, tab object, or the current tab when omitted.+ * @param {string|{targetId:string}} [target] Target id or tab-like object. Defaults to the current tab.+ * @returns {Promise<string>} Closed target id.+ */+export async function closeTab(target: TabTarget | undefined = undefined) {+ const targetId = target === undefined+ ? (await currentTab()).targetId+ : typeof target === "object" ? target.targetId : target;+ if (!targetId) {+ throw new Error("closeTab requires a targetId");+ }+ await cdp("Target.closeTarget", { targetId });+ invalidateSession();+ if (state.preferredTargetId === targetId) {+ clearPreferredTarget();+ }+ return targetId;+}+/*** Ensure the active harness session points at a real, non-internal page tab.* @returns {Promise<{targetId:string,title:string,url:string}|null>}diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjsindex 060b753..53b8d1e 100644--- a/package/ego-browser/src/helpers.test.mjs+++ b/package/ego-browser/src/helpers.test.mjs@@ -89,6 +89,12 @@ test("taskspace helper surface exposes public helpers without claimTaskSpace", (assert.equal(typeof context.newTaskSpace, "function");assert.equal(typeof context.useOrCreateTaskSpace, "function");assert.equal(context.claimTaskSpace, undefined);+ assert.equal(typeof helperExports.openOrReuseTab, "function");+ assert.equal(typeof context.openOrReuseTab, "function");+ assert.equal(typeof helperExports.closeTab, "function");+ assert.equal(typeof context.closeTab, "function");+ assert.equal("newTab" in helperExports, false);+ assert.equal("newTab" in context, false);assert.equal("elementEval" in helperExports, false);assert.equal("elementEval" in context, false);});diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.tsindex 106198c..29ceac2 100644--- a/package/ego-browser/src/helpers.ts+++ b/package/ego-browser/src/helpers.ts@@ -30,8 +30,8 @@ export {listTabs,currentTab,switchTab,- newTab,openOrReuseTab,+ closeTab,gotoAndWait,ensureRealTab,iframeTarget@@ -420,10 +420,11 @@ export async function learnContext(url = undefined) {}export function helperContext(extra: any = {}) {+ const { newTab: _newTab, ...publicNav } = nav;const all = {...pointer,...keyboard,- ...nav,+ ...publicNav,...observe,...waits,...files,diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.mdindex 281e840..3752472 100644--- a/skills/ego-browser/SKILL.md+++ b/skills/ego-browser/SKILL.md@@ -29,7 +29,7 @@ The heredoc body runs in a Node.js process with direct access to all ego-browser## Common helpers- Task spaces: `listTaskSpaces`, `useOrCreateTaskSpace`, `handOffTaskSpace`, `takeOverTaskSpace`, `waitForAgentControl`, `completeTaskSpace`-- Navigation / state: `listTabs`, `openOrReuseTab`, `gotoAndWait`, `currentTab`, `switchTab`, `newTab`, `gotoUrl`, `pageInfo`, `ensureRealTab`+- Navigation / state: `listTabs`, `openOrReuseTab`, `closeTab`, `gotoAndWait`, `currentTab`, `switchTab`, `gotoUrl`, `pageInfo`, `ensureRealTab`- Observation: `snapshotText`, `captureScreenshot`, `drainEvents`- Scroll / mouse: `scrollBy`, `scrollToBottomUntil`, `scroll`, `click`, `doubleClick`, `hover`, `dragMouse`- Keyboard & input: `typeText`, `fillInput`, `pressKey`, `dispatchKey`@@ -41,9 +41,10 @@ The heredoc body runs in a Node.js process with direct access to all ego-browserNotes:- `cliLog(value)` — prints to the terminal; it is the only output mechanism inside a heredoc, and all final results must go through it.-- `pageInfo()` — returns the current tab's `url`, `title`, and other basic metadata; if a native browser dialog is open, returns `{ dialog: ... }`.+- `pageInfo()` — normally returns `{ url, title, w, h, sx, sy, pw, ph }`; if a native browser dialog is open, returns `{ dialog: ... }` instead because page JavaScript is blocked.- If `pageInfo()` returns `{ dialog: ... }`, handle it with `cdp('Page.handleJavaScriptDialog', { accept: true })` or `accept: false` before running page JavaScript.-- `ensureRealTab()` — ensures a real tab exists (a freshly created task space may have none).+- `ensureRealTab()` — switches to an existing non-internal page tab if needed and returns it; returns `null` when none exists. It does not create a tab — use `openOrReuseTab(...)` for that.+- `closeTab(target?)` — closes the given target id / tab object, or the current tab when omitted.- `drainEvents()` — consumes and returns the async event queue produced by the page (navigation events, network events, etc.).- `serverFetch(url, options)` — issues a request from Node and returns the response body.- `browserFetch(url, options)` — issues a request from the current browser page context and returns the response body.@@ -71,7 +72,7 @@ await completeTaskSpace(nameOrId, { keep: true }) // keep the page for the useWhen passing a string that may create a new task space, the string should reflect the task's intent (e.g. `'search github issues'`); don't use literal placeholders.-Keep loose awareness of how many tabs are open — a quick `(await listTabs()).length` is enough; there's no need to spend a dedicated round just to check. When scratch tabs (search-result pages, cross-check pages, and other one-off pages) pile up, close them as you go rather than letting them all accumulate for the end. When finishing with `{ keep: true }` to leave pages for the user, clear out the remaining scratch tabs so only the pages worth showing stay open. Close a single tab with `await cdp('Target.closeTarget', { targetId })` (`targetId` comes from `listTabs()` or an `openOrReuseTab` return value).+Keep loose awareness of how many tabs are open — a quick `(await listTabs()).length` is enough; there's no need to spend a dedicated round just to check. When scratch tabs (search-result pages, cross-check pages, and other one-off pages) pile up, close them as you go rather than letting them all accumulate for the end. When finishing with `{ keep: true }` to leave pages for the user, clear out the remaining scratch tabs so only the pages worth showing stay open. Close a single tab with `await closeTab(targetId)` (`targetId` comes from `listTabs()` or an `openOrReuseTab` return value).### Control handoff@@ -115,11 +116,13 @@ await scrollToBottomUntil(await scroll({ dy: 900 })```-`click`, `doubleClick`, `hover`, and `dragMouse` all accept the same target format. Coordinates are in CSS pixels:+Element-target helpers such as `click`, `doubleClick`, `hover`, `dragMouse`, `fillInput`, `uploadFile`, and `waitForElement` accept the same selector/ref surface: raw CSS, `xpath=...`, `@N` / `ref=N`, and `loc=...` values from `snapshotText()` (`loc=css:...`, `loc=role:...`, `loc=href:...`). `@N` refs are for ego-browser helpers only; they are not valid selectors inside `document.querySelector(...)`.-- `string` — CSS selector or `@ref`; clicks the element's center.+`click`, `doubleClick`, `hover`, and `dragMouse` share these target formats. Coordinates are in CSS pixels:++- `string` — CSS selector, `xpath=...`, `@N` / `ref=N`, or `loc=...`; clicks the element's center.- `[x, y]` or `{x, y}` — viewport coordinates.-- `{selector}` — CSS selector or `@ref`; clicks the element's center.+- `{selector}` — CSS selector, `xpath=...`, `@N` / `ref=N`, or `loc=...`; clicks the element's center.- `{selector, x, y}` — offset from the element's top-left corner by `x`/`y`.- `options.label` (optional) — a 3-6 word action description; triggers a visual highlight animation.@@ -129,7 +132,7 @@ await click('button.primary', { label: 'click submit button' })await click([420, 260])await click({ x: 420, y: 260 })await click({ selector: 'canvas#stage', x: 12, y: 8 })-await hover('@e5', { label: 'hover to reveal menu' })+await hover('@5', { label: 'hover to reveal menu' })await dragMouse([from, to], { label: 'drag card' })```@@ -164,7 +167,8 @@ Start with snapshotText + ref/loc when possible — it preserves semantic struct2. Open or switch pages: prefer `openOrReuseTab(url, { wait: true })`; use `gotoAndWait(url, { timeout, settle })` to navigate within the current tab.3. Observe the page: call `snapshotText()` to get a full-page semantic tree annotated with `[ref=N, loc=..., url=...]`. Refs are auto-registered in refMap, so you can immediately do `click('@N')` / `fillInput('@N', ...)`, or use the `loc=...` value in direct DOM logic.4. Act or extract data: if the logic can be done in the DOM in one shot, wrap it in a browser-side closure and return once.-5. Output the final result: use `cliLog(...)`.+5. After a meaningful click, input, or navigation, observe again with `snapshotText()`, `pageInfo()`, or `captureScreenshot()` before assuming the action succeeded.+6. Output the final result: use `cliLog(...)`.Switch to a different path when it fits better; paths can be combined:- **snapshotText + ref/loc** — default when semantic structure, labels, links, and form controls are clear.