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.

docs: rewrite AGENTS.md to match the actual architecture

Aute6a45df9593d0
diff --git a/AGENTS.md b/AGENTS.md
index d773bae..3b30bf1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,148 +1,60 @@
# Repository Guidelines
## Project Overview
-`ego-browser` is a Node.js CDP browser-automation CLI for AI agents. It drives a real Chrome session through `ego` helpers, exposes a compact snapshot/ref workflow, and layers reusable site-specific knowledge on top of the browser runtime.
+`ego-browser` is a Node.js CDP browser-automation harness for AI agents. It drives the ego lite browser through `globalThis.ego` bindings (provided by the closed-source ego lite app), exposes a compact snapshot/ref workflow, and layers reusable site-specific knowledge ("learnings") on top of the browser runtime.
-## Architecture & Data Flow
-- `package/ego-browser/bin/ego-browser.js` is the entrypoint.
- - Direct CLI execution calls `runMain()`.
- - Importing the package installs the SDK onto `globalThis`.
-- `package/ego-browser/src/run.js` reads JavaScript from stdin and executes it inside an async function with helper APIs injected as parameters.
-- `package/ego-browser/src/helpers.js` composes the user-facing helper surface: navigation, observation, waits, pointer/keyboard/file helpers, `js()`, `cdp()`, and site-skill execution helpers.
-- `package/ego-browser/src/browser-runtime.js` owns CDP transport, session attachment/caching, event buffering, and session invalidation.
-- `package/ego-browser/src/element-resolver.js` resolves refs, locators, CSS/XPath, and AX-based targets.
-- `package/ego-browser/src/site-skills.js` discovers and loads site skills from `skills/ego-browser/learnings/`.
-- Shared mutable runtime state lives in `package/ego-browser/src/state.js`.
+This repo contains the open-source harness and the agent skill package — **not** the browser itself. The ego lite app bundles its own `ego-browser` binary that embeds this runtime; `skills/ego-browser/SKILL.md` documents that binary's usage (`ego-browser nodejs <<'EOF' ... EOF`). The repo CLI built here takes the heredoc directly on stdin with no subcommand.
-Data flow is generally:
-`stdin JS` → `runMain()` → injected helpers → browser runtime/CDP → snapshot or DOM/AX resolution → optional site skills/tools.
+## Architecture & Data Flow
+- `package/ego-browser/src/index.ts` is the entrypoint with two startup paths:
+ - Executed directly as a CLI → `runMain()` (reads JavaScript from stdin, executes it).
+ - Imported as a module (how the app embeds it) → `installEgoSdk(globalThis)`.
+- Both paths expose the same helper surface, built by `helperContext()` in `src/helpers.ts` — the single source of truth for what agents can call (including `help()` and `agent_helpers.js` extensions).
+- `src/run.ts` executes stdin JavaScript inside an async function with the helpers injected as parameters.
+- `src/browser-runtime.ts` owns CDP transport over `ego.sendCDPMessage`, session attach/caching (2s TTL, auto re-attach on session loss), the buffered event queue (10k cap), and JS dialog tracking.
+- `src/cdp-eval.ts` provides `cdp()` and `js()` (string-expression evaluation; top-level `return` is auto-wrapped in an IIFE).
+- `src/element-resolver.ts` resolves all target forms — `@N` refs, `loc=css:` / `loc=role:` / `loc=href:` locators, `xpath=`, raw CSS — and classifies failures as `transient` (retryable) or `permanent`.
+- `src/ref-map.ts` + `src/ref-state.ts`: refs are numeric `backendNodeId`s (`@21`, not `@e21`). The map is rebuilt on every snapshot; using a ref while the map is empty triggers an automatic re-snapshot, which is what makes refs work across heredoc rounds.
+- `src/driver/` — `nav` (tabs, navigation), `pointer` (click/scroll/drag), `keyboard`, `observe` (snapshot/screenshot), `waits`, `files` (upload), `element-ops` (objectId handles), `load`.
+- `src/learning/` — discovery, validation, and execution of site skills from `skills/ego-browser/learnings/<site>/manifest.json` (`runSiteTool`, `runSiteBrowserTool`, `learnContext`).
+- `src/state.ts` is the shared mutable runtime state singleton; `src/env.ts` resolves the agent workspace (`EGO_BROWSER_AGENT_WORKSPACE`, falling back to the skill dir bundled next to the build output, then the repo's `skills/ego-browser`).
+- `src/help-runtime.ts` parses the built bundle's JSDoc with acorn at runtime to power `help()` — JSDoc on exported helpers is therefore user-facing documentation.
+
+Data flow: `stdin JS` → `runMain()` → `helperContext()` helpers → browser runtime/CDP → snapshot or DOM/AX resolution → optional site tools → `cliLog(...)`.
+
+## Task Spaces
+Task spaces are isolated browsing contexts with an ownership model (`agent` / `user`):
+- `useOrCreateTaskSpace(nameOrId)` reuses an agent-owned space, claims a user-owned one, or creates a new one. Ids are numeric; prefer `task.id` over names across rounds.
+- `switchTaskSpace` requires agent ownership; `newTaskSpace` creates; `completeTaskSpace(nameOrId, { keep })` finishes (`keep` is mandatory).
+- Control handoff: `handOffTaskSpace` / `takeOverTaskSpace` / `waitForAgentControl`.
## Key Directories
-- `package/ego-browser/src/` — runtime, helpers, resolver, and site-skill loading.
-- `package/ego-browser/bin/` — CLI entrypoint.
-- `package/ego-browser/test/` — Node test suite for runtime, helpers, navigation, state, and site skills.
-- `package/ego-browser/scripts/` — validation scripts for learned site skills.
-- `skills/ego-browser/` — agent skill package, docs, references, and learned site skills.
-- `skills/ego-browser/learnings/` — reusable per-site experience packs.
-- `skills/ego-browser/references/` — maintenance guidance for learned skills.
+- `package/ego-browser/src/` — runtime, helpers, resolver, drivers, learning subsystem.
+- `package/ego-browser/src/**/*.test.mjs` — tests are colocated with the code (there is no separate `test/` directory).
+- `package/ego-browser/scripts/` — `build.mjs` (esbuild per-file → `dist/src`, rollup bundle → `dist/out/index.js`, copies `skills/ego-browser` → `dist/out/ego-browser`), `validate-site-skills.ts`, `run-e2e.sh`.
+- `skills/ego-browser/` — agent skill package: `SKILL.md` (canonical agent-facing usage guide), `references/install.md`, `scripts/install.sh`.
+- `skills/ego-browser/learnings/` — reusable per-site experience packs (`manifest.json` + `notes/` + `tools/` + `browser-tools/`).
## Development Commands
Run from `package/ego-browser/`:
-- `npm test` — run the Node test suite (`node --test`).
-- `npm run validate:learnings` — validate learned site skills.
-- `npm run validate:site-skills` — same validator entrypoint.
-- `node bin/ego-browser.js <<'JS' ... JS` — run the CLI from this checkout.
-- `npm link` — make the CLI available on PATH locally.
+- `npm test` — build, typecheck, then `node --test` over `src/**/*.test.mjs`.
+- `npm run e2e` — task-space e2e suite (`src/taskspace-e2e.test.mjs`).
+- `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).
## Code Conventions & Common Patterns
-- ESM only: `"type": "module"`.
-- Node 22+ is required by `package/ego-browser/package.json`.
-- Public helpers are camelCase only; avoid snake_case aliases.
-- Async helpers use verb-first names such as `runMain`, `ensureSession`, `siteSkillsForUrl`, and `runSiteTool`.
-- The code prefers a small shared state singleton over threading connection state through many call sites.
-- Helpers are designed to be injected into the script scope, not imported manually by agent scripts.
-- Snapshot refs like `@e1` are short-lived; re-snapshot after navigation or DOM changes and prefer stable `loc=...` values for reuse.
+- ESM only (`"type": "module"`); Node 22+.
+- Public helpers are camelCase, verb-first for async actions (`ensureSession`, `runSiteTool`).
+- Time parameters are in seconds unless the name ends in `Ms`.
+- Helpers are injected into the script scope, not imported by agent scripts.
+- New public helpers go through `helperContext()` in `src/helpers.ts` and need JSDoc (it feeds `help()`); keep `SKILL.md` in sync.
+- Snapshot refs (`@N`) are short-lived; re-snapshot after navigation or DOM changes and prefer stable `loc=...` values for reuse.
+- Element-resolution failures should use `ElementResolutionError` with an honest `transient`/`permanent` kind — wait loops rely on it.
+- The code prefers the small shared state singleton (`src/state.ts`) over threading connection state through call sites.
- Site skills must stay site-shaped and verifiable: stable URLs, durable selectors, no pixel coordinates, no secrets.
-## Important Files
-- `package/ego-browser/bin/ego-browser.js` — CLI/SDK bootstrap.
-- `package/ego-browser/src/run.js` — stdin executor.
-- `package/ego-browser/src/browser-runtime.js` — CDP transport and session handling.
-- `package/ego-browser/src/helpers.js` — helper composition.
-- `package/ego-browser/src/site-skills.js` — site-skill discovery and execution.
-- `package/ego-browser/scripts/validate-site-skills.js` — skill manifest validator.
-- `skills/ego-browser/SKILL.md` — canonical agent-facing usage guide.
-- `skills/ego-browser/scripts/check-domain-learned.js` — checks whether a domain is already covered by a learning.
-- `skills/ego-browser/learnings/_template/TEMPLATE.md` — starting point for new learnings.
-
-## Runtime/Tooling Preferences
-- Use Node.js 22 or newer.
-- Package manager is npm.
-- The runnable CLI lives in `package/ego-browser`; the skill package under `skills/ego-browser` is documentation and reusable learning assets, not the executable CLI.
-- By default the CLI loads agent workspace content from `../../skills/ego-browser`; override with `EGO_BROWSER_AGENT_WORKSPACE`.
-- Learned site skills are always active and are read on each helper call.
-
## Testing & QA
-- Test framework: Node’s built-in test runner via `node --test`.
-- Assertions use `node:assert/strict`.
-- Tests are behavior-focused and rely on temporary workspaces plus injected overrides.
-- Validate changes that affect learned skills with `npm run validate:site-skills`.
-- Prefer covering session handling, locator resolution, helper behavior, and site-skill validation when changing runtime code.
-
-## The Solution
-
-Four principles in one file that directly address these issues:
-
-| Principle | Addresses |
-|-----------|-----------|
-| **Think Before Coding** | Wrong assumptions, hidden confusion, missing tradeoffs |
-| **Simplicity First** | Overcomplication, bloated abstractions |
-| **Surgical Changes** | Orthogonal edits, touching code you shouldn't |
-| **Goal-Driven Execution** | Leverage through tests-first, verifiable success criteria |
-
-## The Four Principles in Detail
-
-### 1. Think Before Coding
-
-**Don't assume. Don't hide confusion. Surface tradeoffs.**
-
-LLMs often pick an interpretation silently and run with it. This principle forces explicit reasoning:
-
-- **State assumptions explicitly** — If uncertain, ask rather than guess
-- **Present multiple interpretations** — Don't pick silently when ambiguity exists
-- **Push back when warranted** — If a simpler approach exists, say so
-- **Stop when confused** — Name what's unclear and ask for clarification
-
-### 2. Simplicity First
-
-**Minimum code that solves the problem. Nothing speculative.**
-
-Combat the tendency toward overengineering:
-
-- No features beyond what was asked
-- No abstractions for single-use code
-- No "flexibility" or "configurability" that wasn't requested
-- No error handling for impossible scenarios
-- If 200 lines could be 50, rewrite it
-
-**The test:** Would a senior engineer say this is overcomplicated? If yes, simplify.
-
-### 3. Surgical Changes
-
-**Touch only what you must. Clean up only your own mess.**
-
-When editing existing code:
-
-- Don't "improve" adjacent code, comments, or formatting
-- Don't refactor things that aren't broken
-- Match existing style, even if you'd do it differently
-- If you notice unrelated dead code, mention it — don't delete it
-
-When your changes create orphans:
-
-- Remove imports/variables/functions that YOUR changes made unused
-- Don't remove pre-existing dead code unless asked
-
-**The test:** Every changed line should trace directly to the user's request.
-
-### 4. Goal-Driven Execution
-
-**Define success criteria. Loop until verified.**
-
-Transform imperative tasks into verifiable goals:
-
-| Instead of... | Transform to... |
-|--------------|-----------------|
-| "Add validation" | "Write tests for invalid inputs, then make them pass" |
-| "Fix the bug" | "Write a test that reproduces it, then make it pass" |
-| "Refactor X" | "Ensure tests pass before and after" |
-
-For multi-step tasks, state a brief plan:
-
-```
-1. [Step] → verify: [check]
-2. [Step] → verify: [check]
-3. [Step] → verify: [check]
-```
-
-Strong success criteria let the LLM loop independently. Weak criteria ("make it work") require constant clarification.
+- Framework: Node's built-in runner (`node --test`), assertions via `node:assert/strict`.
+- Tests run against the build output (`dist/src/...`) — `npm test` builds first.
+- Behavior-focused tests inject overrides (`__testing.setOverrides`) or a `FakeEgo` double (see `src/helpers.test.mjs`, `src/taskspace-e2e.test.mjs`).
+- Cover session handling, locator resolution, helper behavior, and site-skill validation when changing runtime code; run `npm run validate:site-skills` for learning changes.