Skip to content

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.

refactor(ego-browser): tighten runtime diagnostics

Auteda0e162b1399
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8b97aaa..4fa8c7e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -23,6 +23,8 @@ jobs:
cache: npm
cache-dependency-path: package/ego-browser/package-lock.json
- run: npm ci
+ - run: npm run style:check
+ - run: npm audit --registry=https://registry.npmjs.org --audit-level=moderate
- run: npm test
- run: npm run validate:site-skills
diff --git a/.github/workflows/quality-gates.yml b/.github/workflows/quality-gates.yml
deleted file mode 100644
index 629efe6..0000000
--- a/.github/workflows/quality-gates.yml
+++ /dev/null
@@ -1,75 +0,0 @@
-name: Quality Gates
-
-on:
- pull_request:
- paths:
- - ".github/workflows/quality-gates.yml"
- - "lefthook.yml"
- - "package/ego-browser/**"
- - "skills/ego-browser/learnings/**"
- push:
- branches:
- - dev
- - main
- paths:
- - ".github/workflows/quality-gates.yml"
- - "lefthook.yml"
- - "package/ego-browser/**"
- - "skills/ego-browser/learnings/**"
-
-jobs:
- quality-gates:
- runs-on: ubuntu-latest
- defaults:
- run:
- shell: bash
-
- steps:
- - name: Check out repository
- uses: actions/checkout@v4
- with:
- fetch-depth: 0
-
- - name: Set up Node.js
- uses: actions/setup-node@v4
- with:
- node-version: 22
- cache: npm
- cache-dependency-path: package/ego-browser/package-lock.json
-
- - name: Install dependencies
- working-directory: package/ego-browser
- run: npm ci
-
- - name: Check changed file style
- run: |
- if [ "${{ github.event_name }}" = "pull_request" ]; then
- base="${{ github.event.pull_request.base.sha }}"
- else
- base="${{ github.event.before }}"
- fi
-
- if [ -z "$base" ] || [[ "$base" =~ ^0+$ ]]; then
- base="$(git rev-list --max-parents=0 HEAD)"
- fi
-
- files="$(git diff --name-only --diff-filter=ACMR "$base" HEAD | grep -E '^package/ego-browser/.*\.(ts|mjs|js|json|md)$' || true)"
- [ -z "$files" ] && exit 0
- package/ego-browser/node_modules/.bin/prettier --check $files
-
- - name: Analyze vulnerabilities
- working-directory: package/ego-browser
- run: npm audit --registry=https://registry.npmjs.org --audit-level=moderate
-
- - name: Check code
- working-directory: package/ego-browser
- run: npm run typecheck
-
- - name: Run smoke tests
- working-directory: package/ego-browser
- run: npm test
-
- - name: Validate site skills
- working-directory: package/ego-browser
- run: npm run validate:site-skills
-
diff --git a/AGENTS.md b/AGENTS.md
index 8cf8804..1ea16c1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -52,8 +52,8 @@ Run from `package/ego-browser/`:
- `npm test` — build, typecheck, then `node --test` over `src/**/*.test.mjs`.
- `npm run e2e` — self-contained real-browser E2E suite using the current
checkout through `--sdk-path`.
-- `npm run validate:site-skills` (alias `validate:learnings`) — validate learned site skills.
-- `node dist/out/index.js <<'JS' ... JS` — run the built CLI from this checkout (requires an `ego` runtime for real browser work; `--doctor`, `--reload`, `-h` also supported).
+- `npm run validate:site-skills` — validate learned site skills.
+- `node dist/out/index.js <<'JS' ... JS` — run the built CLI from this checkout (requires an `ego` runtime for real browser work; `-h` is also supported).
## Code Conventions & Common Patterns
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index bc4590d..1761e4a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -111,7 +111,7 @@ npm run typecheck
npm test
# 5. Validate site learnings
-npm run validate:site-skills # alias: validate:learnings
+npm run validate:site-skills
```
**Calling the CLI directly** (for local debugging):
@@ -122,12 +122,7 @@ console.log(await help())
JS
```
-**CLI debug flags** (see `src/run.ts`):
-
-- `--help` / `-h`: print usage
-- `--doctor`: check browser and connection state
-- `--reload`: force-rebuild the CDP connection on next call
-- `--debug-clicks`: equivalent to `EGO_BROWSER_DEBUG_CLICKS=1`
+Use `--help` or `-h` to print the local CLI usage.
**Key environment variables**:
@@ -135,7 +130,6 @@ JS
| ----------------------------- | -------------------------------------------------------------------------------- |
| `EGO_BROWSER_AGENT_WORKSPACE` | Override skill workspace root (defaults to `skills/ego-browser` inside the repo) |
| `EGO_BROWSER_NAME` | Browser instance name (default `default`) |
-| `EGO_BROWSER_DEBUG_CLICKS` | Enable click debug logging |
---
@@ -236,7 +230,7 @@ learnings/<site>/
cd package/ego-browser
npm run validate:site-skills
```
-5. Add at least one behavior test in the `test/site-skills.test.js` style.
+5. Add a colocated behavior test under `package/ego-browser/src/`.
**Hard constraints for learning packs**:
@@ -249,8 +243,7 @@ learnings/<site>/
## 8. Testing & Quality
- Test framework: `node --test` with `node:assert/strict`
-- Tests are colocated in `package/ego-browser/src/**/*.test.mjs`, with a small
- set of package tests in `package/ego-browser/test/*.test.js`.
+- Tests are colocated in `package/ego-browser/src/**/*.test.mjs`.
- Unit tests use temporary workspaces, overrides, or a fake Ego binding.
- `npm run e2e` is the self-contained real-browser suite. It builds the current
checkout, launches it through `--sdk-path`, uses a unique temporary space,
diff --git a/docs/native-bindings-api.md b/docs/native-bindings-api.md
index df6ea61..2e00e70 100644
--- a/docs/native-bindings-api.md
+++ b/docs/native-bindings-api.md
@@ -148,9 +148,10 @@ Returns the selected `id` synchronously.
Throws `TypeError` when `id` is missing, not a number, or extra arguments are
provided. The thrown error has `error_code: 'EGO_INVALID_ARGUMENT'`.
-Use `ego.createTaskSpace(name)` to create a new agent-owned task space. Use
-`ego.claimTaskSpace(id, name?)` to take ownership of an existing user-owned space
-before selecting it.
+Use `ego.createTaskSpace(name)` to create a new agent-owned task space. Regular
+Spaces created by the user are returned by `ego.listTaskSpaces()` with
+`ownership: 'user'`. Pass their numeric `id` to
+`ego.claimTaskSpace(id, name?)` before selecting them.
## Profiles
@@ -385,7 +386,9 @@ contains a stable code such as `EGO_SNAPSHOT_FAILED`,
### `await ego.listTaskSpaces()`
-Lists known task spaces.
+Lists Agent task spaces and regular user-created Spaces that are available to
+the native task-space bridge. Listing is read-only: it does not select or claim
+a Space.
```js
const spaces = await ego.listTaskSpaces();
@@ -401,6 +404,16 @@ Returns:
```js
{
taskSpaces: [
+ {
+ taskId: 'research',
+ id: 3,
+ name: 'research',
+ createdBy: 'user',
+ ownership: 'user',
+ profileId: 'Default',
+ profileName: 'Work',
+ recentTabTitles: ['Project notes', 'Reference'],
+ },
{
taskId: 'checkout-flow',
id: 7,
@@ -413,6 +426,12 @@ Returns:
}
```
+`id` is the locator for `ego.claimTaskSpace()` and other task-space APIs.
+`name` and `taskId` are display values and may be duplicated. A regular Space
+created in the Ego Lite UI has `createdBy: 'user'` and `ownership: 'user'`.
+`recentTabTitles` may help the caller identify the intended Space without
+claiming it.
+
Throws `TypeError` when any argument is passed.
The thrown error has `error_code: 'EGO_INVALID_ARGUMENT'`.
@@ -480,8 +499,9 @@ object:
### `await ego.claimTaskSpace(id, name?)`
-Claims an existing space by numeric id and turns it into an agent-owned task
-space. Pass `name` to rename the space while claiming it.
+Claims a Space returned by `ego.listTaskSpaces()` and turns it into an
+agent-owned task space. This includes regular Spaces created by the user. Pass
+`name` to rename the Space while claiming it.
```js
const spaces = await ego.listTaskSpaces();
@@ -507,6 +527,10 @@ Returns:
}
```
+Claiming a regular user Space keeps its browser profile, tabs, active tab, and
+numeric `id`; it does not create a replacement Space. The caller must have the
+user's approval before taking ownership.
+
Throws `TypeError` when `id` is missing or not a number, when `name` is present
but not a string, or when extra arguments are provided. The thrown error has
`error_code: 'EGO_INVALID_ARGUMENT'`.
@@ -545,7 +569,8 @@ Throws `TypeError` when any argument is passed. The thrown error has
### `await ego.completeTaskSpace()`
Completes the current task space by removing agent task state while leaving the
-space open as a normal space.
+Space open for the user. It remains discoverable through
+`ego.listTaskSpaces()` under the same numeric `id` with user ownership.
```js
await ego.completeTaskSpace();
diff --git a/lefthook.yml b/lefthook.yml
index 2048f69..8cd4909 100644
--- a/lefthook.yml
+++ b/lefthook.yml
@@ -30,17 +30,13 @@ pre-commit:
run: |
git diff --cached --name-only --diff-filter=ACMR | grep -q '^package/ego-browser/' || exit 0
cd package/ego-browser && npm audit --registry=https://registry.npmjs.org --audit-level=moderate
- code-check:
- run: |
- git diff --cached --name-only --diff-filter=ACMR | grep -q '^package/ego-browser/' || exit 0
- cd package/ego-browser && npm run typecheck
smoke-test:
run: |
git diff --cached --name-only --diff-filter=ACMR | grep -q '^package/ego-browser/' || exit 0
cd package/ego-browser && npm test
site-skill-validation:
run: |
- git diff --cached --name-only --diff-filter=ACMR | grep -Eq '^(package/ego-browser/|skills/ego-browser/learnings/)' || exit 0
+ git diff --cached --name-only --diff-filter=ACMR | grep -Eq '^(package/ego-browser/(src/learning/|scripts/validate-site-skills\.ts)|skills/ego-browser/learnings/)' || exit 0
cd package/ego-browser && npm run validate:site-skills
e2e-test:
run: |
diff --git a/package/ego-browser/README.md b/package/ego-browser/README.md
index db6b17f..bbaf39c 100644
--- a/package/ego-browser/README.md
+++ b/package/ego-browser/README.md
@@ -32,7 +32,7 @@ console.log(await help())
JS
```
-Flags: `-h | --help`, `--doctor`, `--reload`, `--debug-clicks`.
+Use `-h` or `--help` to print the local CLI usage.
## Skill workspace
@@ -53,7 +53,7 @@ EOF
Site learnings under `agentWorkspace()/learnings/<site>/` are always active and read on every helper call. Validate them with:
```bash
-npm run validate:site-skills # alias: validate:learnings
+npm run validate:site-skills
```
## Source layout
diff --git a/package/ego-browser/package.json b/package/ego-browser/package.json
index f359a34..e9af00d 100644
--- a/package/ego-browser/package.json
+++ b/package/ego-browser/package.json
@@ -14,10 +14,9 @@
"check:skill-translation": "node scripts/check-skill-translation.mjs",
"e2e": "node scripts/run-real-browser-e2e.mjs",
"prepare": "if [ \"$CI\" = \"true\" ]; then exit 0; fi; cd ../.. && lefthook install",
- "style:check": "prettier --check",
+ "style:check": "prettier --check \"src/**/*.{ts,mjs,js}\" \"scripts/**/*.{ts,mjs,js}\" package.json README.md",
"typecheck": "tsc --noEmit",
- "test": "npm run build && npm run check:api-docs && npm run check:skill-translation && npm run typecheck && node --test \"src/**/*.test.mjs\" \"test/*.test.js\"",
- "validate:learnings": "npm run build && EGO_BROWSER_AGENT_WORKSPACE=../../skills/ego-browser node dist/scripts/validate-site-skills.js",
+ "test": "npm run build && npm run check:api-docs && npm run check:skill-translation && npm run typecheck && node --test \"src/**/*.test.mjs\"",
"validate:site-skills": "npm run build && EGO_BROWSER_AGENT_WORKSPACE=../../skills/ego-browser node dist/scripts/validate-site-skills.js"
},
"engines": {
diff --git a/package/ego-browser/scripts/validate-site-skills.ts b/package/ego-browser/scripts/validate-site-skills.ts
index 91bccc7..c5d41a1 100644
--- a/package/ego-browser/scripts/validate-site-skills.ts
+++ b/package/ego-browser/scripts/validate-site-skills.ts
@@ -11,7 +11,9 @@ export async function main(argv = process.argv.slice(2)) {
const root = resolve(rootArg);
const canonicalRoot = resolve(siteSkillsRoot());
if (root !== canonicalRoot) {
- console.warn(`warning: validating ${root} which differs from siteSkillsRoot() ${canonicalRoot}`);
+ console.warn(
+ `warning: validating ${root} which differs from siteSkillsRoot() ${canonicalRoot}`,
+ );
}
const errors = await validateSiteSkills(root);
if (errors.length > 0) {
@@ -24,6 +26,9 @@ export async function main(argv = process.argv.slice(2)) {
return 0;
}
-if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
process.exitCode = await main();
}
diff --git a/package/ego-browser/src/cdp-eval.ts b/package/ego-browser/src/cdp-eval.ts
index 6c57508..c543a6f 100644
--- a/package/ego-browser/src/cdp-eval.ts
+++ b/package/ego-browser/src/cdp-eval.ts
@@ -1,8 +1,6 @@
import { browserCdp } from "./browser-runtime.js";
import { state } from "./state.js";
-class TimeoutError extends Error {}
-
let hasWarnedAboutFunctionJs = false;
/**
@@ -84,10 +82,7 @@ async function runtimeEvaluate(
);
return runtimeValue(response, expression);
} catch (error) {
- if (
- error instanceof TimeoutError ||
- /timed out/i.test(error?.message || "")
- ) {
+ if (/timed out/i.test(error?.message || "")) {
throw new Error(
`Runtime.evaluate timed out; expression: ${jsSnippet(expression)}`,
);
diff --git a/package/ego-browser/src/driver/element-ops.ts b/package/ego-browser/src/driver/element-ops.ts
index 082f62e..b2f168f 100644
--- a/package/ego-browser/src/driver/element-ops.ts
+++ b/package/ego-browser/src/driver/element-ops.ts
@@ -12,7 +12,12 @@ import { resolveElementObjectId } from "../element-resolver.js";
*/
export async function resolveHandle(selectorOrRef) {
await ensureRefMapForRef(selectorOrRef);
- return resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);
+ return resolveElementObjectId(
+ { sendRaw: cdp },
+ undefined,
+ browserRefMap,
+ selectorOrRef,
+ );
}
/**
@@ -55,15 +60,23 @@ export async function withHandle(selectorOrRef, fn) {
* @param {Array<unknown>} [args=[]] Arguments passed by value.
* @returns {Promise<{result: any, objectId: string, sessionId?: string}>}
*/
-export async function resolveAndCall(selectorOrRef, functionDeclaration, args = []) {
+export 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);
+ 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/element-resolver.test.mjs b/package/ego-browser/src/element-resolver.test.mjs
index 7b9aa22..dd48728 100644
--- a/package/ego-browser/src/element-resolver.test.mjs
+++ b/package/ego-browser/src/element-resolver.test.mjs
@@ -187,8 +187,22 @@ test("quoted text locators use exact case-sensitive matching", async () => {
});
test("ambiguous text locators fail permanently instead of choosing one match", async () => {
- const cdp = new FakeCDP(async (method) => {
+ const cdp = new FakeCDP(async (method, params) => {
if (method === "Runtime.evaluate") {
+ if (params.expression.includes("__egoDescribeMatches")) {
+ return {
+ result: {
+ value: {
+ visible: 2,
+ hidden: 0,
+ candidates: [
+ { tag: "button", name: "Save draft", visible: true },
+ { tag: "button", name: "Save changes", visible: true },
+ ],
+ },
+ },
+ };
+ }
return {
result: {
value: { error: "Locator text=Save matched 2 elements" },
@@ -204,6 +218,9 @@ test("ambiguous text locators fail permanently instead of choosing one match", a
assert.ok(error instanceof ElementResolutionError);
assert.equal(error.kind, "permanent");
assert.match(error.message, /matched 2 elements/);
+ assert.match(error.message, /2 visible, 0 hidden/);
+ assert.match(error.message, /button "Save draft"/);
+ assert.match(error.message, /current snapshot ref|more specific/i);
return true;
},
);
@@ -212,6 +229,38 @@ test("ambiguous text locators fail permanently instead of choosing one match", a
test("ambiguous raw CSS selectors fail instead of choosing the first match", async () => {
const cdp = new FakeCDP(async (method, params) => {
if (method === "Runtime.evaluate") {
+ if (params.expression.includes("__egoDescribeMatches")) {
+ return {
+ result: {
+ value: {
+ visible: 2,
+ hidden: 1,
+ candidates: [
+ {
+ tag: "button",
+ role: "button",
+ name: "Create",
+ visible: true,
+ disabled: false,
+ },
+ {
+ tag: "button",
+ role: "button",
+ name: "Create menu",
+ visible: true,
+ disabled: false,
+ },
+ {
+ tag: "button",
+ name: "Create",
+ visible: false,
+ disabled: true,
+ },
+ ],
+ },
+ },
+ };
+ }
assert.match(params.expression, /querySelectorAll/);
return { result: { value: 3 } };
}
@@ -232,6 +281,10 @@ test("ambiguous raw CSS selectors fail instead of choosing the first match", asy
assert.ok(error instanceof ElementResolutionError);
assert.equal(error.kind, "permanent");
assert.match(error.message, /Selector button\.save matched 3 elements/);
+ assert.match(error.message, /2 visible, 1 hidden/);
+ assert.match(error.message, /button role=button "Create" \(visible\)/);
+ assert.match(error.message, /button "Create" \(hidden, disabled\)/);
+ assert.match(error.message, /current snapshot ref|more specific/i);
return true;
},
);
diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.ts
index e67b6e3..1951921 100644
--- a/package/ego-browser/src/element-resolver.ts
+++ b/package/ego-browser/src/element-resolver.ts
@@ -248,7 +248,9 @@ async function resolveRawSelectorObjectId(cdp, sessions, selector) {
async function findUniqueRawSelectorSession(cdp, sessions, selector) {
const mainCount = await rawSelectorCount(cdp, sessions[0], selector);
- if (mainCount > 1) throw rawSelectorCountError(selector.raw, mainCount);
+ if (mainCount > 1) {
+ throw await rawSelectorCountError(cdp, [sessions[0]], selector, mainCount);
+ }
if (mainCount === 1) return { sessionId: sessions[0] };
const matches = [];
@@ -270,7 +272,14 @@ async function findUniqueRawSelectorSession(cdp, sessions, selector) {
"transient",
);
}
- if (count > 1) throw rawSelectorCountError(selector.raw, count);
+ if (count > 1) {
+ throw await rawSelectorCountError(
+ cdp,
+ matches.map((match) => match.sessionId),
+ selector,
+ count,
+ );
+ }
return matches[0];
}
@@ -291,10 +300,14 @@ async function rawSelectorCount(cdp, sessionId, selector) {
return Number(result.result?.value || 0);
}
-function rawSelectorCountError(raw, count) {
- return new ElementResolutionError(
- `Selector ${raw} matched ${count} elements`,
- "permanent",
+async function rawSelectorCountError(cdp, sessions, selector, count) {
+ return ambiguityError(
+ `Selector ${selector.raw} matched ${count} elements`,
+ await collectMatchDiagnostics(
+ cdp,
+ sessions,
+ buildRawSelectorElementsJs(selector),
+ ),
);
}
@@ -384,7 +397,16 @@ async function resolveLocatorCenter(cdp, sessionId, locator, iframeSessions) {
}
const value = result.result?.value;
if (value?.error) {
- throw new ElementResolutionError(value.error, matchCountKind(value.error));
+ const kind = matchCountKind(value.error);
+ if (kind === "permanent") {
+ throw await locatorCountError(
+ cdp,
+ [match.sessionId],
+ locator,
+ matchCount(value.error),
+ );
+ }
+ throw new ElementResolutionError(value.error, kind);
}
if (typeof value?.x !== "number" || typeof value?.y !== "number") {
throw new ElementResolutionError(
@@ -454,10 +476,7 @@ async function findUniqueLocatorSession(cdp, sessions, locator) {
let count = 0;
const mainCount = await locatorCount(cdp, sessions[0], locator);
if (mainCount > 1) {
- throw new ElementResolutionError(
- `Locator ${locator.raw} matched ${mainCount} elements`,
- "permanent",
- );
+ throw await locatorCountError(cdp, [sessions[0]], locator, mainCount);
}
if (mainCount === 1) return { count: 1, sessionId: sessions[0] };
@@ -475,9 +494,11 @@ async function findUniqueLocatorSession(cdp, sessions, locator) {
);
}
if (count > 1) {
- throw new ElementResolutionError(
- `Locator ${locator.raw} matched ${count} elements`,
- "permanent",
+ throw await locatorCountError(
+ cdp,
+ matches.map((match) => match.sessionId),
+ locator,
+ count,
);
}
return matches[0];
@@ -524,10 +545,7 @@ async function findUniqueRoleMatch(cdp, contexts, role, name, raw) {
);
}
if (matches.length > 1) {
- throw new ElementResolutionError(
- `Locator ${raw} matched ${matches.length} elements`,
- "permanent",
- );
+ throw ambiguityError(`Locator ${raw} matched ${matches.length} elements`);
}
return matches[0];
}
@@ -552,6 +570,96 @@ async function locatorCount(cdp, sessionId, locator) {
return Number(result.result?.value || 0);
}
+async function locatorCountError(cdp, sessions, locator, count) {
+ if (locator.kind === "role") {
+ return ambiguityError(`Locator ${locator.raw} matched ${count} elements`);
+ }
+ return ambiguityError(
+ `Locator ${locator.raw} matched ${count} elements`,
+ await collectMatchDiagnostics(
+ cdp,
+ sessions,
+ buildLocatorElementsJs(locator),
+ ),
+ );
+}
+
+function matchCount(message) {
+ const match = /matched (\d+)/.exec(message);
+ return match ? Number(match[1]) : 0;
+}
+
+async function collectMatchDiagnostics(cdp, sessions, elementsExpression) {
+ const combined: {
+ visible: number;
+ hidden: number;
+ candidates: Array<{
+ tag?: string;
+ role?: string;
+ name?: string;
+ visible?: boolean;
+ disabled?: boolean;
+ }>;
+ } = { visible: 0, hidden: 0, candidates: [] };
+ try {
+ for (const sessionId of sessions) {
+ const result = await send(
+ cdp,
+ "Runtime.evaluate",
+ {
+ expression: buildMatchDiagnosticsJs(elementsExpression),
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ sessionId,
+ );
+ const value = result.result?.value;
+ if (
+ typeof value?.visible !== "number" ||
+ typeof value?.hidden !== "number" ||
+ !Array.isArray(value?.candidates)
+ ) {
+ continue;
+ }
+ combined.visible += value.visible;
+ combined.hidden += value.hidden;
+ combined.candidates.push(
+ ...value.candidates.slice(0, 3 - combined.candidates.length),
+ );
+ }
+ return combined.visible + combined.hidden > 0 ? combined : undefined;
+ } catch {
+ // Diagnostics must never replace the original strict-selector failure.
+ return undefined;
+ }
+}
+
+function ambiguityError(message, diagnostics = undefined) {
+ const visibility = diagnostics
+ ? ` (${diagnostics.visible} visible, ${diagnostics.hidden} hidden)`
+ : "";
+ const candidates = diagnostics?.candidates?.length
+ ? ` Candidates: ${diagnostics.candidates
+ .map(
+ (candidate, index) => `${index + 1}. ${formatCandidate(candidate)}`,
+ )
+ .join("; ")}.`
+ : "";
+ return new ElementResolutionError(
+ `${message}${visibility}.${candidates} Use a current snapshot ref or a more specific role, text, or CSS selector.`,
+ "permanent",
+ );
+}
+
+function formatCandidate(candidate) {
+ const tag = candidate?.tag || "element";
+ const role = candidate?.role ? ` role=${candidate.role}` : "";
+ const name = candidate?.name ? ` ${JSON.stringify(candidate.name)}` : "";
+ const states = [candidate?.visible === false ? "hidden" : "visible"];
+ if (candidate?.disabled) states.push("disabled");
+ return `${tag}${role}${name} (${states.join(", ")})`;
+}
+
async function findBackendNodeIdByRoleName(
cdp,
sessionId,
@@ -675,6 +783,16 @@ function buildRawSelectorCountJs(selector) {
return buildCssCountJs(selector.selector);
}
+function buildRawSelectorElementsJs(selector) {
+ if (selector.kind === "xpath") {
+ return `(() => {
+ const result = document.evaluate(${JSON.stringify(selector.selector)}, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
+ return Array.from({ length: result.snapshotLength }, (_, index) => result.snapshotItem(index));
+ })()`;
+ }
+ return buildCssQueryAllJs(selector.selector);
+}
+
function buildLocatorFindJs(locator) {
if (locator.kind === "css") {
return buildCssFindJs(locator.selector);
@@ -695,6 +813,63 @@ function buildLocatorCountJs(locator) {
return `(() => ${hrefElementsJs(locator.href)}.length)()`;
}
+function buildLocatorElementsJs(locator) {
+ if (locator.kind === "css") {
+ return buildCssQueryAllJs(locator.selector);
+ }
+ if (locator.kind === "text") {
+ return textElementsJs(locator);
+ }
+ return hrefElementsJs(locator.href);
+}
+
+function buildMatchDiagnosticsJs(elementsExpression) {
+ return `(() => {
+ const __egoDescribeMatches = (values) => {
+ const elements = Array.from(values || []).filter(Boolean);
+ const normalize = (value) =>
+ String(value ?? "").replace(/\\s+/g, " ").trim();
+ const visible = (element) => {
+ const style = getComputedStyle(element);
+ const rect = element.getBoundingClientRect();
+ return !element.closest("[hidden], [inert]") &&
+ style.display !== "none" &&
+ style.visibility !== "hidden" &&
+ style.opacity !== "0" &&
+ rect.width > 0 && rect.height > 0;
+ };
+ const candidates = elements.slice(0, 3).map((element) => {
+ const isVisible = visible(element);
+ const name = normalize(
+ element.getAttribute?.("aria-label") ||
+ element.getAttribute?.("alt") ||
+ element.getAttribute?.("title") ||
+ element.value ||
+ element.innerText ||
+ element.textContent
+ ).slice(0, 80);
+ return {
+ tag: String(element.tagName || "element").toLowerCase(),
+ role: element.getAttribute?.("role") || undefined,
+ name: name || undefined,
+ visible: isVisible,
+ disabled: Boolean(
+ element.disabled ||
+ element.getAttribute?.("aria-disabled") === "true"
+ )
+ };
+ });
+ const visibleCount = elements.filter(visible).length;
+ return {
+ visible: visibleCount,
+ hidden: elements.length - visibleCount,
+ candidates
+ };
+ };
+ return __egoDescribeMatches(${elementsExpression});
+ })()`;
+}
+
function buildLocatorCenterJs(locator) {
return `(() => {
const count = ${buildLocatorCountJs(locator)};
diff --git a/package/ego-browser/src/env.ts b/package/ego-browser/src/env.ts
index 3954413..911d5a3 100644
--- a/package/ego-browser/src/env.ts
+++ b/package/ego-browser/src/env.ts
@@ -1,9 +1,10 @@
-import { existsSync, readFileSync } from "node:fs";
+import { existsSync } from "node:fs";
import { dirname, resolve } from "node:path";
+import { loadEnvFile as loadNodeEnvFile } from "node:process";
import { fileURLToPath } from "node:url";
-export const SRC_DIR = dirname(fileURLToPath(import.meta.url));
-export const REPO_ROOT = resolve(SRC_DIR, "..");
+const SRC_DIR = dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = resolve(SRC_DIR, "..");
export function agentWorkspace() {
if (process.env.EGO_BROWSER_AGENT_WORKSPACE) {
@@ -18,29 +19,21 @@ export function agentWorkspace() {
return resolve(REPO_ROOT, "..", "..", "skills", "ego-browser");
}
-export function resolvePath(path) {
+function resolvePath(path) {
if (path.startsWith("~")) {
- return resolve(process.env.HOME || process.env.USERPROFILE || ".", path.slice(1));
+ return resolve(
+ process.env.HOME || process.env.USERPROFILE || ".",
+ path.slice(1),
+ );
}
return resolve(path);
}
-export function loadEnvFile(path) {
+function loadEnvFile(path) {
if (!existsSync(path)) {
return;
}
- for (const rawLine of readFileSync(path, "utf8").split(/\r?\n/)) {
- const line = rawLine.trim();
- if (!line || line.startsWith("#") || !line.includes("=")) {
- continue;
- }
- const index = line.indexOf("=");
- const key = line.slice(0, index).trim();
- const value = line.slice(index + 1).trim().replace(/^['"]|['"]$/g, "");
- if (key && process.env[key] === undefined) {
- process.env[key] = value;
- }
- }
+ loadNodeEnvFile(path);
}
export function loadEnv() {
diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjs
index 35efdf9..698d698 100644
--- a/package/ego-browser/src/helpers.test.mjs
+++ b/package/ego-browser/src/helpers.test.mjs
@@ -64,6 +64,29 @@ test("listTaskSpaces normalizes the current taskSpaces binding shape", async ()
);
});
+test("listTaskSpaces preserves claimable user-created space metadata", async () => {
+ const userSpace = {
+ taskId: "research",
+ id: 3,
+ name: "research",
+ createdBy: "user",
+ ownership: "user",
+ profileId: "Default",
+ profileName: "Work",
+ recentTabTitles: ["Project notes", "Reference"],
+ };
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ return { taskSpaces: [userSpace] };
+ },
+ },
+ async () => {
+ assert.deepEqual(await listTaskSpaces(), [userSpace]);
+ },
+ );
+});
+
test("listTaskSpaces rejects legacy taskIds results", async () => {
await withEgo(
{
diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.ts
index b9330e7..1ad14c8 100644
--- a/package/ego-browser/src/helpers.ts
+++ b/package/ego-browser/src/helpers.ts
@@ -76,8 +76,9 @@ export { uploadFile } from "./driver/files.js";
export { browserFetch, serverFetch } from "./http.js";
/**
- * List all task spaces.
- * @returns {Promise<Array<{taskId:string,id:number,name:string,createdBy?:string,ownership?:string,recentTabTitles?:string[]}>>}
+ * List Agent-owned and user-owned spaces exposed by Ego Lite.
+ * Use the numeric id as the stable locator; display names may be duplicated.
+ * @returns {Promise<Array<{taskId:string,id:number,name:string,createdBy?:string,ownership?:string,profileId?:string,profileName?:string,recentTabTitles?:string[]}>>}
*/
export async function listTaskSpaces() {
const ego = globalThis.ego;
diff --git a/package/ego-browser/src/http.ts b/package/ego-browser/src/http.ts
index 4179384..59e7be6 100644
--- a/package/ego-browser/src/http.ts
+++ b/package/ego-browser/src/http.ts
@@ -11,10 +11,12 @@ export async function serverFetch(url, options: any = {}) {
const response = await fetch(url, {
...fetchOptions,
headers: { "User-Agent": "Mozilla/5.0", ...headers },
- signal: AbortSignal.timeout(timeout * 1000)
+ signal: AbortSignal.timeout(timeout * 1000),
});
if (!response.ok) {
- throw new Error(`${fetchOptions.method || "GET"} ${url} failed: HTTP ${response.status}`);
+ throw new Error(
+ `${fetchOptions.method || "GET"} ${url} failed: HTTP ${response.status}`,
+ );
}
return response.text();
}
diff --git a/package/ego-browser/src/index.ts b/package/ego-browser/src/index.ts
index c93bd98..3804c9c 100644
--- a/package/ego-browser/src/index.ts
+++ b/package/ego-browser/src/index.ts
@@ -60,10 +60,9 @@ export function installEgoSdk(
if (target === globalThis) installPageContextGuard(target);
const context = options.context || helpers.helperContext();
const readySignal = Promise.resolve(options.ready);
- let readyError = null;
- readySignal.catch((error) => {
- readyError = error;
- });
+ // The host may reject readiness before a helper is called. Mark the promise
+ // as observed while preserving the same rejection for every helper await.
+ void readySignal.catch(() => {});
const installed: Record<string, HelperFunction> = {};
for (const [name, value] of Object.entries(context)) {
if (typeof value !== "function") {
@@ -73,9 +72,6 @@ export function installEgoSdk(
? value
: async (...args: unknown[]) => {
await readySignal;
- if (readyError) {
- throw readyError;
- }
return value(...args);
};
Object.defineProperty(target, name, {
diff --git a/package/ego-browser/src/learning/validate-learning-format.ts b/package/ego-browser/src/learning/validate-learning-format.ts
index c603e56..f895eb5 100644
--- a/package/ego-browser/src/learning/validate-learning-format.ts
+++ b/package/ego-browser/src/learning/validate-learning-format.ts
@@ -5,10 +5,17 @@ import { isAbsolute, join } from "node:path";
import {
iterLearningDirs,
learningsRoot,
- pathExists
+ pathExists,
} from "./check-domain-learning.js";
-const TOOL_VALUE_TYPES = new Set(["string", "number", "integer", "boolean", "array", "object"]);
+const TOOL_VALUE_TYPES = new Set([
+ "string",
+ "number",
+ "integer",
+ "boolean",
+ "array",
+ "object",
+]);
const TEMP_REF_RE = /(?:@\d+\b|\bref=\d+\b)/;
export async function validateLearning(siteDir: string) {
@@ -44,41 +51,93 @@ export async function validateLearning(siteDir: string) {
for (const note of asStringList(manifest, "notes", errors, siteId)) {
if (!isNotePath(note)) {
- errors.push(`${siteId}: notes must point to notes/*.md: ${JSON.stringify(note)}`);
+ errors.push(
+ `${siteId}: notes must point to notes/*.md: ${JSON.stringify(note)}`,
+ );
continue;
}
- await requireFile(siteDir, note, `${siteId}: missing note ${JSON.stringify(note)}`, errors);
- await rejectTemporaryRefs(siteDir, note, `${siteId}: note ${JSON.stringify(note)}`, errors);
+ await requireFile(
+ siteDir,
+ note,
+ `${siteId}: missing note ${JSON.stringify(note)}`,
+ errors,
+ );
+ await rejectTemporaryRefs(
+ siteDir,
+ note,
+ `${siteId}: note ${JSON.stringify(note)}`,
+ errors,
+ );
}
- const nodeTools: Record<string, any> = validateToolMap(manifest, "nodeTools", errors, siteId);
+ const nodeTools: Record<string, any> = validateToolMap(
+ manifest,
+ "nodeTools",
+ errors,
+ siteId,
+ );
for (const [toolName, schema] of Object.entries(nodeTools)) {
if (!schema || typeof schema !== "object" || !isNodeToolPath(schema.path)) {
continue;
}
const toolPath = join(siteDir, schema.path);
- if (!await pathExists(toolPath)) {
- errors.push(`${siteId}: missing Node tool file ${JSON.stringify(schema.path)} for tool ${JSON.stringify(toolName)}`);
+ if (!(await pathExists(toolPath))) {
+ errors.push(
+ `${siteId}: missing Node tool file ${JSON.stringify(schema.path)} for tool ${JSON.stringify(toolName)}`,
+ );
continue;
}
- await rejectTemporaryRefs(siteDir, schema.path, `${siteId}: Node tool ${JSON.stringify(toolName)}`, errors);
+ await rejectTemporaryRefs(
+ siteDir,
+ schema.path,
+ `${siteId}: Node tool ${JSON.stringify(toolName)}`,
+ errors,
+ );
try {
- const module = await import(`${pathToFileURL(toolPath).href}?validate=${Date.now()}`);
- if (typeof schema.callable === "string" && typeof module[schema.callable] !== "function") {
- errors.push(`${siteId}: missing Node callable ${JSON.stringify(schema.callable)} for tool ${JSON.stringify(toolName)}`);
+ const module = await import(
+ `${pathToFileURL(toolPath).href}?validate=${Date.now()}`
+ );
+ if (
+ typeof schema.callable === "string" &&
+ typeof module[schema.callable] !== "function"
+ ) {
+ errors.push(
+ `${siteId}: missing Node callable ${JSON.stringify(schema.callable)} for tool ${JSON.stringify(toolName)}`,
+ );
}
} catch (error) {
- errors.push(`${siteId}: cannot import Node tool ${JSON.stringify(schema.path)}: ${error.message}`);
+ errors.push(
+ `${siteId}: cannot import Node tool ${JSON.stringify(schema.path)}: ${error.message}`,
+ );
}
}
- const browserTools: Record<string, any> = validateToolMap(manifest, "browserTools", errors, siteId);
+ const browserTools: Record<string, any> = validateToolMap(
+ manifest,
+ "browserTools",
+ errors,
+ siteId,
+ );
for (const [toolName, schema] of Object.entries(browserTools)) {
- if (!schema || typeof schema !== "object" || !isBrowserToolPath(schema.path)) {
+ if (
+ !schema ||
+ typeof schema !== "object" ||
+ !isBrowserToolPath(schema.path)
+ ) {
continue;
}
- await requireFile(siteDir, schema.path, `${siteId}: missing browser tool file ${JSON.stringify(schema.path)} for tool ${JSON.stringify(toolName)}`, errors);
- await rejectTemporaryRefs(siteDir, schema.path, `${siteId}: browser tool ${JSON.stringify(toolName)}`, errors);
+ await requireFile(
+ siteDir,
+ schema.path,
+ `${siteId}: missing browser tool file ${JSON.stringify(schema.path)} for tool ${JSON.stringify(toolName)}`,
+ errors,
+ );
+ await rejectTemporaryRefs(
+ siteDir,
+ schema.path,
+ `${siteId}: browser tool ${JSON.stringify(toolName)}`,
+ errors,
+ );
}
return errors;
@@ -87,7 +146,7 @@ export async function validateLearning(siteDir: string) {
export async function validateLearnings(root = learningsRoot()) {
const errors: string[] = [];
for (const siteDir of await iterLearningDirs(root)) {
- errors.push(...await validateLearning(siteDir));
+ errors.push(...(await validateLearning(siteDir)));
}
return errors;
}
@@ -96,14 +155,22 @@ export const validateSiteSkills = validateLearnings;
function asStringList(manifest, key, errors: string[], siteId: string) {
const value = manifest[key] || [];
- if (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item.trim())) {
+ if (
+ !Array.isArray(value) ||
+ !value.every((item) => typeof item === "string" && item.trim())
+ ) {
errors.push(`${siteId}: ${key} must be a list of non-empty strings`);
return [];
}
return value;
}
-function validateToolMap(manifest, key, errors: string[], siteId: string): Record<string, any> {
+function validateToolMap(
+ manifest,
+ key,
+ errors: string[],
+ siteId: string,
+): Record<string, any> {
const value = manifest[key] || {};
if (!value || typeof value !== "object" || Array.isArray(value)) {
errors.push(`${siteId}: ${key} must be an object keyed by tool name`);
@@ -115,10 +182,18 @@ function validateToolMap(manifest, key, errors: string[], siteId: string): Recor
return value;
}
-function validateToolSchema(siteId: string, key: string, toolName: string, schema, errors: string[]) {
+function validateToolSchema(
+ siteId: string,
+ key: string,
+ toolName: string,
+ schema,
+ errors: string[],
+) {
const prefix = `${siteId}: ${key}.${toolName}`;
if (!isSafeToolName(toolName)) {
- errors.push(`${siteId}: ${key} contains invalid tool name ${JSON.stringify(toolName)}`);
+ errors.push(
+ `${siteId}: ${key} contains invalid tool name ${JSON.stringify(toolName)}`,
+ );
return;
}
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
@@ -139,31 +214,61 @@ function validateToolSchema(siteId: string, key: string, toolName: string, schem
errors.push(`${prefix}: path must be a relative browser-tools/*.js path`);
}
- if (!schema.args || typeof schema.args !== "object" || Array.isArray(schema.args)) {
+ if (
+ !schema.args ||
+ typeof schema.args !== "object" ||
+ Array.isArray(schema.args)
+ ) {
errors.push(`${prefix}: args must be an object`);
} else {
for (const [argName, argSchema] of Object.entries(schema.args)) {
if (typeof argName !== "string" || !argName.trim()) {
- errors.push(`${prefix}: args contains invalid argument name ${JSON.stringify(argName)}`);
+ errors.push(
+ `${prefix}: args contains invalid argument name ${JSON.stringify(argName)}`,
+ );
continue;
}
- validateValueSchema(`${prefix}.args.${argName}`, argSchema, errors, true, "arg");
+ validateValueSchema(
+ `${prefix}.args.${argName}`,
+ argSchema,
+ errors,
+ true,
+ "arg",
+ );
}
}
- if (!schema.returns || typeof schema.returns !== "object" || Array.isArray(schema.returns)) {
+ if (
+ !schema.returns ||
+ typeof schema.returns !== "object" ||
+ Array.isArray(schema.returns)
+ ) {
errors.push(`${prefix}: returns must be an object`);
} else {
- validateValueSchema(`${prefix}.returns`, schema.returns, errors, false, "return");
+ validateValueSchema(
+ `${prefix}.returns`,
+ schema.returns,
+ errors,
+ false,
+ "return",
+ );
}
}
-function validateValueSchema(prefix: string, schema, errors: string[], requireRequired: boolean, typeLabel: string) {
+function validateValueSchema(
+ prefix: string,
+ schema,
+ errors: string[],
+ requireRequired: boolean,
+ typeLabel: string,
+) {
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
errors.push(`${prefix}: schema must be an object`);
return;
}
if (!TOOL_VALUE_TYPES.has(schema.type)) {
- errors.push(`${prefix}: invalid ${typeLabel} type ${JSON.stringify(schema.type)}`);
+ errors.push(
+ `${prefix}: invalid ${typeLabel} type ${JSON.stringify(schema.type)}`,
+ );
}
if (requireRequired && typeof schema.required !== "boolean") {
errors.push(`${prefix}: required must be a boolean`);
@@ -177,27 +282,43 @@ function isValidDomain(pattern) {
if (typeof pattern !== "string" || !pattern) {
return false;
}
- if (pattern.includes("://") || pattern.includes("/") || pattern.startsWith(".") || pattern.endsWith(".")) {
+ if (
+ pattern.includes("://") ||
+ pattern.includes("/") ||
+ pattern.startsWith(".") ||
+ pattern.endsWith(".")
+ ) {
return false;
}
if (pattern.includes("*")) {
- return pattern.startsWith("*.") && pattern.indexOf("*") === pattern.lastIndexOf("*") && pattern.length > 2;
+ return (
+ pattern.startsWith("*.") &&
+ pattern.indexOf("*") === pattern.lastIndexOf("*") &&
+ pattern.length > 2
+ );
}
return true;
}
function isSafeToolName(name) {
- return typeof name === "string"
- && Boolean(name)
- && !name.includes("/")
- && !name.includes("\\")
- && name !== "."
- && name !== ".."
- && !name.includes("..");
+ return (
+ typeof name === "string" &&
+ Boolean(name) &&
+ !name.includes("/") &&
+ !name.includes("\\") &&
+ name !== "." &&
+ name !== ".." &&
+ !name.includes("..")
+ );
}
function isSafeRelativePath(path) {
- if (typeof path !== "string" || !path || path.includes("\\") || isAbsolute(path)) {
+ if (
+ typeof path !== "string" ||
+ !path ||
+ path.includes("\\") ||
+ isAbsolute(path)
+ ) {
return false;
}
return path.split("/").every((part) => part && part !== "." && part !== "..");
@@ -215,16 +336,30 @@ function isNodeToolPath(path) {
function isBrowserToolPath(path) {
const parts = isSafeRelativePath(path) ? path.split("/") : [];
- return parts.length === 2 && parts[0] === "browser-tools" && parts[1].endsWith(".js");
+ return (
+ parts.length === 2 &&
+ parts[0] === "browser-tools" &&
+ parts[1].endsWith(".js")
+ );
}
-async function requireFile(siteDir: string, relativePath: string, message: string, errors: string[]) {
- if (!await pathExists(join(siteDir, relativePath))) {
+async function requireFile(
+ siteDir: string,
+ relativePath: string,
+ message: string,
+ errors: string[],
+) {
+ if (!(await pathExists(join(siteDir, relativePath)))) {
errors.push(message);
}
}
-async function rejectTemporaryRefs(siteDir: string, relativePath: string, prefix: string, errors: string[]) {
+async function rejectTemporaryRefs(
+ siteDir: string,
+ relativePath: string,
+ prefix: string,
+ errors: string[],
+) {
let text;
try {
text = await readFile(join(siteDir, relativePath), "utf8");
@@ -232,6 +367,8 @@ async function rejectTemporaryRefs(siteDir: string, relativePath: string, prefix
return;
}
if (TEMP_REF_RE.test(text)) {
- errors.push(`${prefix}: contains temporary snapshot ref; use stable locators instead`);
+ errors.push(
+ `${prefix}: contains temporary snapshot ref; use stable locators instead`,
+ );
}
}
diff --git a/package/ego-browser/src/page-ref-registry.test.mjs b/package/ego-browser/src/page-ref-registry.test.mjs
index 4b3cf72..3097cd0 100644
--- a/package/ego-browser/src/page-ref-registry.test.mjs
+++ b/package/ego-browser/src/page-ref-registry.test.mjs
@@ -19,7 +19,6 @@ test("Page refs preserve native frame provenance and an explicit ref id", () =>
role: "button",
name: "Run iframe action",
nth: undefined,
- selector: undefined,
frameId: "frame-target",
});
assert.equal(
diff --git a/package/ego-browser/src/public-api-schema.test.mjs b/package/ego-browser/src/public-api-schema.test.mjs
index 23bc473..e3979be 100644
--- a/package/ego-browser/src/public-api-schema.test.mjs
+++ b/package/ego-browser/src/public-api-schema.test.mjs
@@ -11,6 +11,7 @@ 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",
+ "listTaskSpaces",
"taskSpace",
"claimTaskSpace",
"takeOverTaskSpace",
@@ -80,6 +81,7 @@ 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 listTaskSpaces\(\)`/);
assert.match(markdown, /`await taskSpace\(nameOrId, \{ profileId\? \}\)`/);
assert.match(
markdown,
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index 5f33ba5..a56f8d8 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -56,6 +56,12 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
signature: "await profiles()",
summary: "List browser profiles available for new task spaces.",
},
+ {
+ name: "listTaskSpaces",
+ signature: "await listTaskSpaces()",
+ summary:
+ "List Agent-owned and user-owned spaces available to reuse or claim.",
+ },
{
name: "taskSpace",
signature: "await taskSpace(nameOrId, { profileId? })",
diff --git a/package/ego-browser/src/ref-map.ts b/package/ego-browser/src/ref-map.ts
index c5e17ab..0453bc0 100644
--- a/package/ego-browser/src/ref-map.ts
+++ b/package/ego-browser/src/ref-map.ts
@@ -22,7 +22,6 @@ export class RefMap {
role,
name,
nth,
- selector: undefined,
frameId,
});
}
@@ -31,10 +30,6 @@ export class RefMap {
return this.map.get(refId);
}
- remove(refId) {
- this.map.delete(refId);
- }
-
clear() {
this.map.clear();
}
diff --git a/package/ego-browser/src/run-output-sink.test.mjs b/package/ego-browser/src/run-output-sink.test.mjs
index 4d5d204..ea240bc 100644
--- a/package/ego-browser/src/run-output-sink.test.mjs
+++ b/package/ego-browser/src/run-output-sink.test.mjs
@@ -69,7 +69,6 @@ async function runScript(code, ego) {
stdinText: code,
stdout,
stderr,
- services: { printUpdateBanner() {} },
});
} catch (err) {
error = err;
@@ -275,6 +274,37 @@ test("a top-level document ReferenceError explains the Page execution boundary",
assert.match(result.error.message, /page\.evaluate\(\)/i);
});
+test("a syntax error points to the invalid user-script line", async () => {
+ const result = await runScript(`
+const task = await taskSpace(556);
+const rows = (await task.pages()).map(page => ({ title: await page.title() }));
+console.log(rows);
+`);
+
+ assert.ok(result.error, "expected runMain to reject");
+ assert.match(result.error.message, /syntax error at line 3, column \d+/i);
+ assert.match(result.error.message, /3 \| const rows =/);
+ assert.match(result.error.message, /\^/);
+ assert.doesNotMatch(result.error.message, /node:internal\/vm/);
+});
+
+test("the direct CLI rejects removed placeholder commands", async () => {
+ for (const command of ["--doctor", "--reload", "--debug-clicks"]) {
+ const stdout = captureStream();
+ const stderr = captureStream();
+ const exitCode = await runMain({
+ argv: [command],
+ stdinText: "",
+ stdout,
+ stderr,
+ });
+
+ assert.equal(exitCode, 2, command);
+ assert.equal(stdout.text(), "", command);
+ assert.match(stderr.text(), /^Usage:/, command);
+ }
+});
+
test("the direct CLI prints an ordinary uncaught error once", () => {
const entry = new URL("../dist/out/index.js", import.meta.url);
const result = spawnSync(process.execPath, [entry.pathname], {
diff --git a/package/ego-browser/src/run.ts b/package/ego-browser/src/run.ts
index 122b3fe..9de843e 100644
--- a/package/ego-browser/src/run.ts
+++ b/package/ego-browser/src/run.ts
@@ -3,6 +3,7 @@ import {
stdout as processStdout,
stderr as processStderr,
} from "node:process";
+import { parse } from "acorn";
import { formatCliLogValue } from "./format.js";
import * as helpers from "./helpers.js";
@@ -25,20 +26,12 @@ type ReadableLike = {
on(event: "error", listener: (error: Error) => void): unknown;
};
-type RunServices = {
- resetConnection(): Promise<void>;
- printUpdateBanner(stream: WritableLike): void;
- runDoctor(stream: WritableLike): Promise<number>;
-};
-
export type RunMainOptions = {
argv?: string[];
stdout?: WritableLike;
stderr?: WritableLike;
stdin?: ReadableLike;
stdinText?: string;
- env?: Record<string, string | undefined>;
- services?: Partial<RunServices>;
};
export const HELP = `ego-browser
@@ -47,20 +40,19 @@ Read the ego-browser skill for the default workflow and examples.
Typical usage:
ego-browser <<'JS'
- await waitForLoad()
- cliLog(await pageInfo())
+ const task = await taskSpace('demo')
+ const page = await task.openPage('https://example.com', { as: 'p1' })
+ console.log(await page.snapshot())
JS
Helpers are pre-imported and the browser connection is prepared automatically.
-
-Commands:
- ego-browser --doctor inspect browser and connection state
- ego-browser --reload reset the browser connection on next call
`;
export const USAGE = `Usage:
ego-browser <<'JS'
- cliLog(await pageInfo())
+ const task = await taskSpace('demo')
+ const page = await task.openPage('https://example.com', { as: 'p1' })
+ console.log(await page.snapshot())
JS
`;
@@ -68,30 +60,11 @@ export async function runMain(options: RunMainOptions = {}) {
const argv = options.argv || process.argv.slice(2);
const stdout = options.stdout || processStdout;
const stderr = options.stderr || processStderr;
- const env = options.env || process.env;
- const services = {
- resetConnection: async () => {},
- printUpdateBanner: () => {},
- runDoctor: async () => 0,
- ...options.services,
- };
if (argv[0] === "-h" || argv[0] === "--help") {
write(stdout, HELP);
return 0;
}
- if (argv[0] === "--doctor") {
- return services.runDoctor(stdout);
- }
- if (argv[0] === "--reload") {
- await services.resetConnection();
- write(stdout, "browser connection reset on next call\n");
- return 0;
- }
- if (argv[0] === "--debug-clicks") {
- env.EGO_BROWSER_DEBUG_CLICKS = "1";
- argv.shift();
- }
if (argv.length > 0) {
write(stderr, USAGE);
return 2;
@@ -106,7 +79,6 @@ export async function runMain(options: RunMainOptions = {}) {
return 2;
}
- services.printUpdateBanner(stderr);
await execute(code, stdout);
return 0;
}
@@ -122,7 +94,13 @@ async function execute(code: string, stdout: WritableLike) {
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
const names = Object.keys(context);
const values = Object.values(context);
- const fn = new AsyncFunction(...names, `"use strict";\n${code}`);
+ let fn: (...args: unknown[]) => Promise<unknown>;
+ try {
+ fn = new AsyncFunction(...names, `"use strict";\n${code}`);
+ } catch (error) {
+ flushSink(stdout, true);
+ throw userScriptSyntaxError(code, error);
+ }
try {
await fn(...values);
} catch (error) {
@@ -134,6 +112,38 @@ async function execute(code: string, stdout: WritableLike) {
flushSink(stdout, false);
}
+function userScriptSyntaxError(code: string, original: unknown): SyntaxError {
+ const originalMessage =
+ original instanceof Error ? original.message : String(original);
+ try {
+ // V8 omits source locations for Function-constructor syntax errors. Acorn
+ // only runs after compilation fails and recovers the location in the
+ // user's script; wrapping preserves top-level await support.
+ parse(`async function __egoBrowserUserScript__() {\n${code}\n}`, {
+ ecmaVersion: "latest",
+ sourceType: "script",
+ });
+ } catch (parseError) {
+ const location = (parseError as { loc?: { line: number; column: number } })
+ .loc;
+ if (location && location.line >= 2) {
+ const userLineNumber = location.line - 1;
+ const sourceLine = code.split(/\r?\n/)[userLineNumber - 1] ?? "";
+ const columnNumber = location.column + 1;
+ const error = new SyntaxError(
+ `Browser script syntax error at line ${userLineNumber}, column ${columnNumber}: ${originalMessage}\n` +
+ `${userLineNumber} | ${sourceLine}\n` +
+ `${" ".repeat(String(userLineNumber).length + 3 + location.column)}^`,
+ );
+ (error as SyntaxError & { cause?: unknown }).cause = original;
+ return error;
+ }
+ }
+ return original instanceof SyntaxError
+ ? original
+ : new SyntaxError(originalMessage);
+}
+
export async function executionContext() {
const agentHelpers = await helpers.loadAgentHelpers();
// Single source of truth for the agent-facing surface: the same helperContext()
diff --git a/package/ego-browser/src/taskspace-e2e.test.mjs b/package/ego-browser/src/taskspace-e2e.test.mjs
index 29b3628..bee6a1d 100644
--- a/package/ego-browser/src/taskspace-e2e.test.mjs
+++ b/package/ego-browser/src/taskspace-e2e.test.mjs
@@ -94,7 +94,6 @@ async function runTaskspaceScript(ego, code) {
stdinText: code,
stdout,
stderr,
- services: { printUpdateBanner() {} },
});
return { exitCode, stdout: stdout.text(), stderr: stderr.text() };
} finally {
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index 29b96eb..40af8dc 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -111,7 +111,6 @@ 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");
```
Element actions accept:
@@ -130,14 +129,11 @@ When a selector identifies a wrapper, `focus()` and `press()` may use its
interactive ancestor or unique editable descendant; `fill()` and
`setInputFiles()` only continue to a unique compatible control.
-Snapshot node names are accessibility roles. Use a current ref for an immediate
-action and a generated locator for reuse. When a useful node has no ref,
-construct a selector from its role, text, or surrounding context. CSS searches
-nested open shadow roots; role locators also search frames when the top-level
-document has no match.
-
-Refs belong to one Page and one observed state. Take a fresh snapshot whenever
-the page may have changed and before using a ref in a later round.
+Snapshot node names are accessibility roles. Use a ref now or `loc=...` to find
+the element again. After the page changes, take a new snapshot. When a useful
+node has no ref, construct a selector from its role, text, or surrounding
+context. CSS searches nested open shadow roots; role locators also search
+frames when the top-level document has no match.
### Visual pages: screenshot, mouse, and keyboard
@@ -266,10 +262,14 @@ const userPage = task.userPage();
Adopt `userPage` if it is unmanaged. Use `waitForControl()` only when the current
script must wait in place. Claim a user-owned or inactive space only when the
-user explicitly asks:
+user explicitly asks. Find its numeric id first; names may be duplicated:
```js
+const spaces = await listTaskSpaces();
+console.log(spaces.filter((space) => space.ownership === "user"));
+
const task = await claimTaskSpace(7);
+const userPage = task.userPage();
```
After verifying the result, call `task.close()` by default. Use `task.finish()`
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index 8b4e5c2..4928fe9 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -11,6 +11,7 @@ For an explicit popup wait, arm it before the action: `const popupPromise = page
| API | Options | Purpose |
| ------------------------------------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `await profiles()` | — | List browser profiles available for new task spaces. |
+| `await listTaskSpaces()` | — | List Agent-owned and user-owned spaces available to reuse or claim. |
| `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. |