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.

revert(skill): keep site learnings and their v1 helpers

Zhuowei Wange5b613d8f978
diff --git a/.github/dev-skills/ego-lite-simplify/SKILL.md b/.github/dev-skills/ego-lite-simplify/SKILL.md
index fe363cb..e8a482c 100644
--- a/.github/dev-skills/ego-lite-simplify/SKILL.md
+++ b/.github/dev-skills/ego-lite-simplify/SKILL.md
@@ -39,7 +39,7 @@ Use `rg` first. Search exact symbols, method forms, event names, configuration k
Classify evidence as:
-- **Production:** `package/ego-browser/src`, runtime scripts, build and loader paths.
+- **Production:** `package/ego-browser/src`, runtime scripts, build and loader paths, and shipped site learnings.
- **Contract:** public JSDoc consumed by `help()`, `package/ego-browser/skill-body/SKILL.md`, architecture documents, and native binding behavior.
- **Non-production:** tests, fixtures, snapshots, comments, and historical or draft documents.
- **Ambiguous:** examples and development scripts; inspect how they are invoked before deciding.
@@ -68,6 +68,6 @@ Follow spec-driven TDD when changing code:
4. Keep comments in English and explain only non-obvious constraints.
5. Prefer deleting a state or transition over adding another abstraction around it.
-Run the narrowest relevant checks first. From `package/ego-browser/`, use `npm test` for runtime changes, `npm run e2e` for real task-space/browser behavior, and `npm --prefix ../../plugins/ego test` for Skill or plugin changes. Finish with `git diff --check` and report any verification that could not run.
+Run the narrowest relevant checks first. From `package/ego-browser/`, use `npm test` for runtime changes, `npm run e2e` for real task-space/browser behavior, and `npm run validate:site-skills` for learning changes. Finish with `git diff --check` and report any verification that could not run.
Never edit generated build output as the source of a simplification. Never remove a defensive path until its trust or lifecycle boundary is understood.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2ba37b8..2bc4386 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -38,6 +38,7 @@ jobs:
- name: Test agent plugin
working-directory: plugins/ego
run: npm test
+ - run: npm run validate:site-skills
- name: Archive release payload
if: env.SHOULD_RELEASE == 'true'
run: tar -czf dist/ego-browser-release-payload.tar.gz -C dist/out .
diff --git a/AGENTS.md b/AGENTS.md
index f9106ef..d743c78 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,7 +2,7 @@
## Project Overview
-`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), and exposes a compact snapshot/ref workflow.
+`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.
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. The Skill has two layers: `skills/ego-browser/` is a thin entry Skill that tells agents to run `ego-browser skill`, and `package/ego-browser/skill-body/SKILL.md` is the versioned usage guide that command prints (`ego-browser nodejs <<'EOF' ... EOF`). The repo CLI built here takes the heredoc directly on stdin with no subcommand.
@@ -20,7 +20,8 @@ This repo contains the open-source harness and the agent skill package — **not
- `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/page-ref-registry.ts` + `src/page-ledger.ts`: v2 Page refs (`@21`, not `@e21`) are SDK-assigned ids bound to one frame/document/backend node. Their mappings and invalidation persist across rounds; partial snapshots merge by node identity and full snapshots replace the active set. Missing refs require a fresh snapshot. `src/ref-map.ts` + `src/ref-state.ts` retain the v1 native-ref refresh behavior.
- `src/driver/` — `nav` (tabs, navigation), `pointer` (click/scroll/drag), `keyboard`, `observe` (snapshot/screenshot), `waits`, `files` (upload), `element-ops` (objectId handles), `load`.
-- `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 guide dir bundled next to the build output) used for `agent_helpers.js` and `.env`.
+- `src/learning/` — discovery, validation, and execution of site skills from `skill-body/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 guide dir bundled next to the build output, then the package's `skill-body`).
- `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(...)`.
@@ -38,11 +39,12 @@ Task spaces are isolated browsing contexts with an ownership model (`agent` / `u
## Key Directories
-- `package/ego-browser/src/` — runtime, helpers, resolver, drivers.
+- `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`, renders `skill-body/SKILL.md` → `dist/out/ego-browser/SKILL.md` with version and end markers, copies the entry Skill → `dist/out/agent-skills/ego-browser`) and the real-browser E2E runner.
+- `package/ego-browser/scripts/` — `build.mjs` (esbuild per-file → `dist/src`, rollup bundle → `dist/out/index.js`, renders `skill-body/SKILL.md` → `dist/out/ego-browser/SKILL.md` with version and end markers and copies `skill-body/learnings` next to it, copies the entry Skill → `dist/out/agent-skills/ego-browser`), `validate-site-skills.ts`, and the real-browser E2E runner.
- `package/ego-browser/skill-body/SKILL.md` — canonical agent-facing usage guide, printed by `ego-browser skill`.
- `skills/ego-browser/` — thin entry Skill published to skill markets and plugins: `SKILL.md`, `references/install.md`, `references/clearing-state.md`, `scripts/install.sh`. See `docs/ego-browser-skill-command.md` for the browser-side contract.
+- `package/ego-browser/skill-body/learnings/` — reusable per-site experience packs (`manifest.json` + `notes/` + `tools/` + `browser-tools/`).
## Development Commands
@@ -51,12 +53,13 @@ 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` — 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
- ESM only (`"type": "module"`); Node 22+.
-- Public helpers are camelCase, verb-first for async actions (`ensureSession`, `taskSpace`).
+- Public helpers are camelCase, verb-first for async actions (`ensureSession`, `runSiteTool`).
- V2 `TaskSpace` and `Page` time parameters are milliseconds. The v1
compatibility helpers keep their original units.
- Helpers are injected into the script scope, not imported by agent scripts.
@@ -65,6 +68,7 @@ Run from `package/ego-browser/`:
- 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.
## Testing & QA
@@ -72,7 +76,7 @@ Run from `package/ego-browser/`:
- 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` and `src/page-model.test.mjs`).
-- Cover session handling, locator resolution, and helper behavior when changing runtime code.
+- Cover session handling, locator resolution, helper behavior, and site-skill validation when changing runtime code; run `npm run validate:site-skills` for learning changes.
- `npm run e2e` is the self-contained real-browser gate. It builds the current
checkout, passes the resulting absolute bundle through `--sdk-path`, starts a
local fixture server, uses a unique temporary task space, and cleans it up.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index bcd5580..4ac3af6 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -35,15 +35,15 @@ Local dependency installation also installs the Git hooks configured in
| Output | Purpose |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `dist/out/index.js` | The single-file ESM SDK loaded by the ego lite CLI or embedded host. Use this file for browser debugging and distribution. |
-| `dist/out/ego-browser/` | The matching usage guide `SKILL.md`, printed by `ego-browser skill`. |
+| `dist/out/ego-browser/` | The matching usage guide `SKILL.md`, printed by `ego-browser skill`, and the site `learnings/`. |
| `dist/out/agent-skills/` | The entry Skill the browser installs into `~/.agents/skills/ego-browser`. |
| `dist/src/` | Compiled runtime modules used by the repository's unit tests. |
-| `dist/scripts/` | Compiled TypeScript maintenance scripts. |
+| `dist/scripts/` | Compiled TypeScript maintenance scripts, including the site-learning validator. |
The release payload is the contents of `dist/out/`: `index.js`, the adjacent
-`ego-browser/` guide, and `agent-skills/`. Keep them together when copying a
-standalone payload so `ego-browser skill` prints the guide that matches the SDK.
-See [the `ego-browser skill` contract](docs/ego-browser-skill-command.md). `dist/src/index.js` is not the
+`ego-browser/` guide and learnings, and `agent-skills/`. Keep them together when
+copying a standalone payload so `ego-browser skill` prints the guide that matches
+the SDK. See [the `ego-browser skill` contract](docs/ego-browser-skill-command.md). `dist/src/index.js` is not the
single-file release entry point.
Edit source files under `src/`, `scripts/`, `skill-body/`, or `skills/ego-browser/`, then rebuild.
@@ -144,6 +144,7 @@ For additional CLI setup and troubleshooting, see
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `npm test` | Builds the SDK, checks any local Skill translation, typechecks, then runs `src/**/*.test.mjs` with Node's test runner. |
| `npm run style:check` | Checks formatting of runtime source, build scripts, and package documentation. |
+| `npm run validate:site-skills` | Builds and validates the site-learning packs. Run this when changing their manifests, tools, notes, or validation code. |
| `npm run e2e` | Builds the current checkout and runs the complete real-browser suite with its SDK. |
Tests live next to the runtime source and use `node:assert/strict`, injected
@@ -169,7 +170,7 @@ ego lite CLI explicitly.
| `package/ego-browser/src/element-resolver.ts`, `page-ref-registry.ts`, `page-ledger.ts` | Element resolution and durable Page/ref identity. |
| `package/ego-browser/src/driver/` | Browser action, input, observation, and wait implementations. |
| `package/ego-browser/scripts/real-browser-e2e/` | Real-browser fixtures and regression cases. |
-| `package/ego-browser/skill-body/SKILL.md` | The canonical usage guide printed by `ego-browser skill`. |
+| `package/ego-browser/skill-body/` | The canonical usage guide printed by `ego-browser skill`, and site learnings. |
| `skills/ego-browser/` | The thin entry Skill, installation guide, and installation script. |
Keep changes focused and match the surrounding style. Runtime code uses ESM,
@@ -179,6 +180,10 @@ honestly as transient or permanent because retry behavior depends on them.
When changing a public API, update its schema, implementation, regression tests,
and the usage guide together.
+Keep reusable site behavior in `package/ego-browser/skill-body/learnings/<site>/`. Start from
+an existing pack, declare its tools in `manifest.json`, and use stable URLs and
+selectors. Do not put credentials or one-off task history in learning packs.
+
## Submit a pull request
Start from the latest branch you intend to target. Current v2 work targets
@@ -200,7 +205,7 @@ check is inapplicable, exclude only `branch-up-to-date` with
[CI](.github/workflows/ci.yml) runs on pull requests, pushes to `dev` and `main`,
and version tags. It installs dependencies, checks formatting and dependency
-vulnerabilities, and runs `npm test`. The real-browser
+vulnerabilities, runs `npm test`, and validates site learnings. The real-browser
E2E suite is a local gate and is not run by this GitHub-hosted workflow.
The current release behavior is:
diff --git a/docs/ego-browser-skill-command.md b/docs/ego-browser-skill-command.md
index 059049f..8a7828a 100644
--- a/docs/ego-browser-skill-command.md
+++ b/docs/ego-browser-skill-command.md
@@ -22,7 +22,8 @@ must implement. Everything else lives in this repository.
dist/out/
├── index.js SDK bundle
├── ego-browser/
-│ └── SKILL.md usage guide printed by `ego-browser skill`
+│ ├── SKILL.md usage guide printed by `ego-browser skill`
+│ └── learnings/ site learnings the SDK reads at runtime
└── agent-skills/
└── ego-browser/ entry Skill to install into ~/.agents/skills/ego-browser
├── SKILL.md
@@ -32,8 +33,8 @@ dist/out/
└── assets/
```
-Ship `dist/out/` as one unit inside the app, keeping `ego-browser/SKILL.md`
-next to `index.js`.
+Ship `dist/out/` as one unit inside the app, keeping `ego-browser/` next to
+`index.js`.
## 1. Add the `ego-browser skill` subcommand
diff --git a/lefthook.yml b/lefthook.yml
index cde2e1c..cf6d225 100644
--- a/lefthook.yml
+++ b/lefthook.yml
@@ -23,7 +23,7 @@ pre-commit:
exit 1
style-check:
run: |
- files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '^(package/ego-browser|plugins)/.*\.(ts|mjs|js|json|md)$' || true)
+ files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '^(package/ego-browser|plugins)/.*\.(ts|mjs|js|json|md)$' | grep -v '^package/ego-browser/skill-body/learnings/' || true)
[ -z "$files" ] && exit 0
package/ego-browser/node_modules/.bin/prettier --check $files
vulnerability-audit:
@@ -34,6 +34,10 @@ pre-commit:
run: |
git diff --cached --name-only --diff-filter=ACMR | grep -Eq '^(package/ego-browser/|skills/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/(src/learning/|scripts/validate-site-skills\.ts|skill-body/learnings/)' || exit 0
+ cd package/ego-browser && npm run validate:site-skills
plugin-tests:
run: |
git diff --cached --name-only --diff-filter=ACMR | grep -Eq '^(plugins/|skills/ego-browser/|package/ego-browser/skill-body/|\.agents/plugins/|\.claude-plugin/)' || exit 0
diff --git a/package/ego-browser/README.md b/package/ego-browser/README.md
index 00bc95a..25143a5 100644
--- a/package/ego-browser/README.md
+++ b/package/ego-browser/README.md
@@ -37,7 +37,25 @@ Use `-h` or `--help` to print the local CLI usage.
## Skill workspace
-The usage guide lives in `skill-body/SKILL.md`. The build renders it to `dist/out/ego-browser/SKILL.md` next to the bundle, where `ego-browser skill` prints it. The runtime loads optional `agent_helpers.js` and `.env` from that directory; override it with `EGO_BROWSER_AGENT_WORKSPACE`.
+The usage guide and site learnings live in `skill-body/`. The build renders the guide to `dist/out/ego-browser/SKILL.md`, where `ego-browser skill` prints it, and copies `learnings/` next to it. By default the runtime loads agent helpers and site learnings from that directory:
+
+```text
+dist/out/ego-browser
+```
+
+Override with `EGO_BROWSER_AGENT_WORKSPACE`:
+
+```bash
+EGO_BROWSER_AGENT_WORKSPACE=/path/to/skill ego-browser nodejs <<'EOF'
+cliLog(await siteSkills())
+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
+```
## Source layout
@@ -59,6 +77,7 @@ src/
files.ts uploadFile
http.ts serverFetch, browserFetch
cdp-eval.ts cdp() and js() raw eval
+ learning/ site-learnings discovery and manifest validation
scripts/
build.mjs esbuild bundling
```
@@ -94,6 +113,7 @@ existing scripts.
default `help()`, and the usage guide must remain aligned.
- Embedded hosts should await the exported `disposeEgoSdk()` hook before
discarding a Node context; see `../../docs/native-sdk-lifecycle-requirement.md`.
+- Site-specific reusable experience belongs under `skill-body/learnings/`, not in the runtime source.
## License
diff --git a/package/ego-browser/package.json b/package/ego-browser/package.json
index faee3eb..c42db71 100644
--- a/package/ego-browser/package.json
+++ b/package/ego-browser/package.json
@@ -14,7 +14,8 @@
"prepare": "if [ \"$CI\" = \"true\" ]; then exit 0; fi; cd ../.. && lefthook install",
"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:skill-translation && npm run typecheck && node --test \"src/**/*.test.mjs\""
+ "test": "npm run build && npm run check:skill-translation && npm run typecheck && node --test \"src/**/*.test.mjs\"",
+ "validate:site-skills": "npm run build && EGO_BROWSER_AGENT_WORKSPACE=skill-body node dist/scripts/validate-site-skills.js"
},
"engines": {
"node": ">=22"
diff --git a/package/ego-browser/scripts/build.mjs b/package/ego-browser/scripts/build.mjs
index 90a2e78..8e1f367 100644
--- a/package/ego-browser/scripts/build.mjs
+++ b/package/ego-browser/scripts/build.mjs
@@ -23,8 +23,10 @@ const distDir = join(root, "dist");
const outDir = join(distDir, "out");
const bundledCliDir = outDir;
const bundledCli = join(bundledCliDir, "index.js");
-// The usage guide printed by `ego-browser skill`, versioned with this SDK.
+// The usage guide printed by `ego-browser skill` and the site learnings the
+// runtime reads next to the bundle, both versioned with this SDK.
const guideSource = join(root, "skill-body", "SKILL.md");
+const learningsSource = join(root, "skill-body", "learnings");
const bundledGuideDir = join(outDir, "ego-browser");
// The thin entry Skill the browser installs into ~/.agents/skills/ego-browser.
const entrySkillSourceDir = join(repoRoot, "skills", "ego-browser");
@@ -98,6 +100,9 @@ try {
join(bundledGuideDir, "SKILL.md"),
renderGuide(await readFile(guideSource, "utf8")),
);
+ await cp(learningsSource, join(bundledGuideDir, "learnings"), {
+ recursive: true,
+ });
for (const entry of entrySkillEntries) {
await cp(
join(entrySkillSourceDir, entry),
diff --git a/package/ego-browser/scripts/validate-site-skills.ts b/package/ego-browser/scripts/validate-site-skills.ts
new file mode 100644
index 0000000..c5d41a1
--- /dev/null
+++ b/package/ego-browser/scripts/validate-site-skills.ts
@@ -0,0 +1,34 @@
+#!/usr/bin/env node
+import { pathToFileURL } from "node:url";
+import { resolve } from "node:path";
+
+import { siteSkillsRoot, validateSiteSkills } from "../src/learning/index.js";
+
+export { validateSiteSkills };
+
+export async function main(argv = process.argv.slice(2)) {
+ const rootArg = argv[0] || siteSkillsRoot();
+ const root = resolve(rootArg);
+ const canonicalRoot = resolve(siteSkillsRoot());
+ if (root !== canonicalRoot) {
+ console.warn(
+ `warning: validating ${root} which differs from siteSkillsRoot() ${canonicalRoot}`,
+ );
+ }
+ const errors = await validateSiteSkills(root);
+ if (errors.length > 0) {
+ for (const error of errors) {
+ console.error(error);
+ }
+ return 1;
+ }
+ console.log(`site skills ok: ${root}`);
+ return 0;
+}
+
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
+ process.exitCode = await main();
+}
diff --git a/package/ego-browser/skill-body/learnings/github/browser-tools/repo-stats.js b/package/ego-browser/skill-body/learnings/github/browser-tools/repo-stats.js
new file mode 100644
index 0000000..291946e
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/github/browser-tools/repo-stats.js
@@ -0,0 +1,10 @@
+async function(args) {
+ const stats = {
+ stars: document.querySelector('a[href*="stargazers"]')?.innerText?.replace(/\s/g, '') || '',
+ forks: document.querySelector('a[href*="forks"]')?.innerText?.replace(/\s/g, '') || '',
+ language: document.querySelector('[itemprop="programmingLanguage"]')?.innerText?.trim() || '',
+ name: document.querySelector('[data-target="repo-banner.repoName"]')?.innerText?.trim() || '',
+ description: document.querySelector('[data-testid="about-section-notice-p"]')?.nextElementSibling?.innerText?.trim() || '',
+ };
+ return stats;
+}
diff --git a/package/ego-browser/skill-body/learnings/github/manifest.json b/package/ego-browser/skill-body/learnings/github/manifest.json
new file mode 100644
index 0000000..49ef262
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/github/manifest.json
@@ -0,0 +1,61 @@
+{
+ "id": "github",
+ "name": "GitHub",
+ "domains": ["github.com", "*.github.com"],
+ "notes": ["notes/overview.md"],
+ "nodeTools": {
+ "search_repos": {
+ "description": "Search GitHub repositories and extract results.",
+ "path": "tools/search-repos.js",
+ "callable": "searchRepos",
+ "args": {
+ "query": {
+ "type": "string",
+ "required": true,
+ "description": "Search query for repos."
+ },
+ "maxResults": {
+ "type": "integer",
+ "required": false,
+ "description": "Maximum number of repos to extract."
+ }
+ },
+ "returns": {
+ "type": "array",
+ "description": "Array of {name, owner, stars, description} objects."
+ }
+ },
+ "get_open_issues": {
+ "description": "Extract open issues from a repository.",
+ "path": "tools/open-issues.js",
+ "callable": "getOpenIssues",
+ "args": {
+ "owner": {
+ "type": "string",
+ "required": true,
+ "description": "Repository owner (username or org)."
+ },
+ "repo": {
+ "type": "string",
+ "required": true,
+ "description": "Repository name."
+ }
+ },
+ "returns": {
+ "type": "array",
+ "description": "Array of {title, number, state} objects."
+ }
+ }
+ },
+ "browserTools": {
+ "get_repo_stats": {
+ "description": "Extract stars, forks, and language from a GitHub repo page.",
+ "path": "browser-tools/repo-stats.js",
+ "args": {},
+ "returns": {
+ "type": "object",
+ "description": "Object with stars, forks, language."
+ }
+ }
+ }
+}
diff --git a/package/ego-browser/skill-body/learnings/github/notes/overview.md b/package/ego-browser/skill-body/learnings/github/notes/overview.md
new file mode 100644
index 0000000..0a15362
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/github/notes/overview.md
@@ -0,0 +1,21 @@
+# GitHub Overview
+
+## Page structure
+- Navigation: Header with logo, search, notifications
+- Repository page: `[data-view-component]` wraps the repo body
+- File tree: `#repo-files-toc` or `Box-row`
+- Issues: `[data-test-id="issue-list-item"]` for issue rows
+
+## Navigation patterns
+- Repo URL: `https://github.com/{owner}/{repo}`
+- Search URL: `https://github.com/search?q={query}&type=repositories`
+- Issues URL: `https://github.com/{owner}/{repo}/issues`
+- PR URL: `https://github.com/{owner}/{repo}/pulls`
+
+## Common selectors
+- Repo name: `[data-target="repo-banner.repoName"]`
+- Stars button: `a.Link--muted[data-hydro-click*="stargazers"]`
+- Forks button: `a.Link--muted[data-hydro-click*="forks"]`
+- Language: `[itemprop="programmingLanguage"]`
+- Description: About section content
+- Search input: `input[data-testid="search-input"]` or `input.repository-search-bar-input`
diff --git a/package/ego-browser/skill-body/learnings/github/tools/open-issues.js b/package/ego-browser/skill-body/learnings/github/tools/open-issues.js
new file mode 100644
index 0000000..ccc8b6d
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/github/tools/open-issues.js
@@ -0,0 +1,24 @@
+const OWNER_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/;
+const REPO_RE = /^[A-Za-z0-9._-]+$/;
+
+export async function getOpenIssues(ctx, args = {}) {
+ const owner = args.owner || "";
+ const repo = args.repo || "";
+ if (!OWNER_RE.test(owner) || !REPO_RE.test(repo)) {
+ throw new Error("valid GitHub owner and repo are required");
+ }
+
+ await ctx.openOrReuseTab(`https://github.com/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues`, { wait: true });
+ await ctx.waitForLoad();
+
+ const issues = await ctx.js(String.raw`(() => {
+ const rows = [...document.querySelectorAll('[data-test-id="issue-list-item"]')]
+ return rows.map(el => {
+ const title = el.querySelector('a[aria-label*="issue"]')?.innerText?.trim() || el.querySelector('h2 a')?.innerText?.trim() || ''
+ const number = el.querySelector('[itemprop="discussionUrl"]')?.innerText?.trim() || ''
+ return { title, number }
+ }).filter(i => i.title)
+ })()`);
+
+ return issues;
+}
diff --git a/package/ego-browser/skill-body/learnings/github/tools/search-repos.js b/package/ego-browser/skill-body/learnings/github/tools/search-repos.js
new file mode 100644
index 0000000..636b0a9
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/github/tools/search-repos.js
@@ -0,0 +1,30 @@
+function boundedInteger(value, fallback, max) {
+ const number = value === undefined ? fallback : Number(value);
+ if (!Number.isFinite(number)) return fallback;
+ return Math.max(1, Math.min(max, Math.trunc(number)));
+}
+
+export async function searchRepos(ctx, args = {}) {
+ const query = args.query || "";
+ const maxResults = boundedInteger(args.maxResults, 25, 100);
+ if (!query) throw new Error("search query is required");
+
+ await ctx.openOrReuseTab(`https://github.com/search?q=${encodeURIComponent(query)}&type=repositories&s=stars&o=desc`, {
+ wait: true,
+ });
+ await ctx.waitForLoad();
+
+ const repos = await ctx.js(String.raw`(() => {
+ const repos = [...document.querySelectorAll('[data-hydro-click*="repo"]')]
+ return repos.slice(0, ${maxResults}).map(el => {
+ const name = el.querySelector('h2 a')?.innerText?.trim() || ''
+ const link = el.querySelector('h2 a')?.getAttribute('href') || ''
+ const parts = link.split('/')
+ const owner = parts[1] || ''
+ const stars = el.querySelector('a[href*="stargazers"]')?.innerText?.replace(/\s/g, '') || ''
+ return { name: parts[2] || name, owner, stars, link }
+ }).filter(r => r.name)
+ })()`);
+
+ return repos;
+}
diff --git a/package/ego-browser/skill-body/learnings/google/browser-tools/autocomplete.js b/package/ego-browser/skill-body/learnings/google/browser-tools/autocomplete.js
new file mode 100644
index 0000000..bb27936
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/google/browser-tools/autocomplete.js
@@ -0,0 +1,11 @@
+async function(args) {
+ const suggestionEls = document.querySelectorAll('span.gsqphr');
+ if (suggestionEls.length) {
+ return [...suggestionEls].map(el => el.innerText?.trim() || '').filter(Boolean);
+ }
+ const lis = document.querySelectorAll('.ssb-a');
+ if (lis.length) {
+ return [...lis].map(li => li.innerText?.trim() || '').filter(Boolean);
+ }
+ return [];
+}
diff --git a/package/ego-browser/skill-body/learnings/google/manifest.json b/package/ego-browser/skill-body/learnings/google/manifest.json
new file mode 100644
index 0000000..2382bae
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/google/manifest.json
@@ -0,0 +1,40 @@
+{
+ "id": "google",
+ "name": "Google Search",
+ "domains": ["google.com", "*.google.com", "www.google.com"],
+ "notes": ["notes/overview.md"],
+ "nodeTools": {
+ "search_and_extract": {
+ "description": "Perform a Google search and extract top organic results.",
+ "path": "tools/search-extract.js",
+ "callable": "searchAndExtract",
+ "args": {
+ "query": {
+ "type": "string",
+ "required": true,
+ "description": "Search query string."
+ },
+ "maxResults": {
+ "type": "integer",
+ "required": false,
+ "description": "Maximum number of results to extract."
+ }
+ },
+ "returns": {
+ "type": "array",
+ "description": "Array of {title, url, snippet} objects."
+ }
+ }
+ },
+ "browserTools": {
+ "get_autocomplete_suggestions": {
+ "description": "Get autocomplete suggestions for the current search query.",
+ "path": "browser-tools/autocomplete.js",
+ "args": {},
+ "returns": {
+ "type": "array",
+ "description": "Array of suggestion strings."
+ }
+ }
+ }
+}
diff --git a/package/ego-browser/skill-body/learnings/google/notes/overview.md b/package/ego-browser/skill-body/learnings/google/notes/overview.md
new file mode 100644
index 0000000..3344644
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/google/notes/overview.md
@@ -0,0 +1,20 @@
+# Google Search Overview
+
+## Page structure
+- Search input: `textarea[name="q"]` or `input[name="q"]`
+- Results container: `div#search`
+- Individual result items: `div.g`
+- Result title: `h3` inside `div.g`
+- Result link: `a[href]` inside `div.g a`
+- Result snippet: text content below the title
+
+## Navigation
+- Use `openOrReuseTab` with `https://www.google.com/search?q=...`
+- Results load immediately, no infinite scroll on first page
+- Pagination links at bottom: `a[href*="/search?q="]`
+
+## Common selectors
+- Query box: `textarea[name="q"]`
+- Search button: `input[type="submit"]`
+- Auto-complete dropdown: `div[role="listbox"]`
+- Auto-complete items: `.ssb-a`
diff --git a/package/ego-browser/skill-body/learnings/google/tools/search-extract.js b/package/ego-browser/skill-body/learnings/google/tools/search-extract.js
new file mode 100644
index 0000000..7f042bb
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/google/tools/search-extract.js
@@ -0,0 +1,25 @@
+function boundedInteger(value, fallback, max) {
+ const number = value === undefined ? fallback : Number(value);
+ if (!Number.isFinite(number)) return fallback;
+ return Math.max(1, Math.min(max, Math.trunc(number)));
+}
+
+export async function searchAndExtract(ctx, args = {}) {
+ const query = args.query || "";
+ const maxResults = boundedInteger(args.maxResults, 10, 100);
+ if (!query) throw new Error("search query is required");
+
+ await ctx.openOrReuseTab(`https://www.google.com/search?q=${encodeURIComponent(query)}`, { wait: true });
+ await ctx.waitForLoad();
+
+ const results = await ctx.js(String.raw`(() => {
+ const items = [...document.querySelectorAll('div.g')]
+ return items.slice(0, ${maxResults}).map(el => ({
+ title: el.querySelector('h3')?.innerText?.trim() || '',
+ url: el.querySelector('a')?.getAttribute('href') || '',
+ snippet: el.querySelector('[data-sncf]')?.innerText?.trim() || el.querySelector('span')?.innerText?.trim() || '',
+ })).filter(r => r.title)
+ })()`);
+
+ return results;
+}
diff --git a/package/ego-browser/skill-body/learnings/x-com/browser-tools/extract-post.js b/package/ego-browser/skill-body/learnings/x-com/browser-tools/extract-post.js
new file mode 100644
index 0000000..7d2e0b1
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/x-com/browser-tools/extract-post.js
@@ -0,0 +1,9 @@
+async function(args) {
+ const el = document.querySelector('[data-testid="tweet"]:focus') || document.querySelector('[data-testid="tweet"]');
+ if (!el) return { error: 'no active tweet found' };
+ return {
+ text: el.querySelector('[data-testid="tweetText"]')?.innerText?.trim() || '',
+ author: el.querySelector('[data-testid="User-Name"] span')?.innerText?.trim() || '',
+ timestamp: el.querySelector('time')?.getAttribute('datetime') || '',
+ };
+}
diff --git a/package/ego-browser/skill-body/learnings/x-com/manifest.json b/package/ego-browser/skill-body/learnings/x-com/manifest.json
new file mode 100644
index 0000000..b39561c
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/x-com/manifest.json
@@ -0,0 +1,51 @@
+{
+ "id": "x-com",
+ "name": "X (Twitter)",
+ "domains": ["x.com", "*.x.com", "twitter.com", "*.twitter.com"],
+ "notes": ["notes/overview.md", "notes/timeline.md"],
+ "nodeTools": {
+ "get_timeline_posts": {
+ "description": "Extract posts from the current X timeline using the anti-click-wrap pattern.",
+ "path": "tools/timeline.js",
+ "callable": "getTimelinePosts",
+ "args": {
+ "maxPosts": {
+ "type": "integer",
+ "required": false,
+ "description": "Maximum number of posts to extract."
+ }
+ },
+ "returns": {
+ "type": "array",
+ "description": "Array of post objects with text, author, and timestamp."
+ }
+ },
+ "search_users": {
+ "description": "Search for users on X.",
+ "path": "tools/search-users.js",
+ "callable": "searchUsers",
+ "args": {
+ "query": {
+ "type": "string",
+ "required": true,
+ "description": "Search query string."
+ }
+ },
+ "returns": {
+ "type": "array",
+ "description": "Array of user info objects."
+ }
+ }
+ },
+ "browserTools": {
+ "post_from_active_element": {
+ "description": "Extract tweet data from the currently focused element in the timeline.",
+ "path": "browser-tools/extract-post.js",
+ "args": {},
+ "returns": {
+ "type": "object",
+ "description": "Tweet text, author, timestamp."
+ }
+ }
+ }
+}
diff --git a/package/ego-browser/skill-body/learnings/x-com/notes/overview.md b/package/ego-browser/skill-body/learnings/x-com/notes/overview.md
new file mode 100644
index 0000000..f7548bd
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/x-com/notes/overview.md
@@ -0,0 +1,18 @@
+# X (Twitter) Overview
+
+## Page structure
+- Main navigation: Left sidebar `[data-testid="AppTabBar"]`
+- Timeline content: `[data-testid="primaryColumn"]`
+- Tweet items: `[data-testid="tweet"]` — each contains text, author, timestamp
+- Compose box: `[data-testid="twaCreateTweetText"]`
+
+## Anti-click-wrap
+- Tweet text is inside `[data-testid="tweetText"]`, click target is `[data-testid="tweet"]`
+- Actions (reply/retweet/like) are inside `div[role="group"]` at the bottom of each tweet card
+
+## Common selectors
+- Tweet text: `[data-testid="tweetText"]`
+- Author name: `[data-testid="User-Name"] span`
+- Timestamp: `time` element with `datetime` attribute
+- Search input: `[data-testid="SearchBox_Search_Input"]`
+- Compose textarea: `[data-testid="twaCreateTweetTextarea"]`
diff --git a/package/ego-browser/skill-body/learnings/x-com/notes/timeline.md b/package/ego-browser/skill-body/learnings/x-com/notes/timeline.md
new file mode 100644
index 0000000..e3c8e25
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/x-com/notes/timeline.md
@@ -0,0 +1,16 @@
+# X Timeline Navigation
+
+## Scrolling timeline
+- Timeline is inside `[data-testid="primaryColumn"]`
+- Posts load lazily as you scroll — use `scrollToBottomUntil` to load more
+- Virtual list: DOM only renders visible articles + buffer
+
+## Extracting posts
+- Query `[data-testid="tweet"]` for post elements
+- Each post has `[data-testid="tweetText"]` for content
+- Author info at `[data-testid="User-Name"]`
+- Always extract in one pass via browser-side closure
+
+## Pinned post
+- Pinned post is the first `[data-testid="tweet"]` in timeline
+- To filter pinned post, skip the first element only when at top of timeline
diff --git a/package/ego-browser/skill-body/learnings/x-com/tools/search-users.js b/package/ego-browser/skill-body/learnings/x-com/tools/search-users.js
new file mode 100644
index 0000000..a7af3c7
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/x-com/tools/search-users.js
@@ -0,0 +1,18 @@
+export async function searchUsers(ctx, args = {}) {
+ const query = args.query || "";
+ if (!query) throw new Error("search query is required");
+
+ await ctx.openOrReuseTab(`https://x.com/search?f=user&q=${encodeURIComponent(query)}`, { wait: true });
+ await ctx.waitForLoad();
+
+ const users = await ctx.js(String.raw`(() => {
+ const results = [...document.querySelectorAll('[data-testid="cellInnerDiv"]')]
+ return results.map(el => ({
+ name: el.querySelector('[data-testid="User-Name"] span')?.innerText?.trim() || '',
+ handle: el.querySelector('[data-testid="User-Name"] a')?.innerText?.trim() || '',
+ followers: el.querySelector('[data-testid="Follow"]')?.previousElementSibling?.innerText?.trim() || '',
+ })).filter(u => u.name || u.handle)
+ })()`);
+
+ return users;
+}
diff --git a/package/ego-browser/skill-body/learnings/x-com/tools/timeline.js b/package/ego-browser/skill-body/learnings/x-com/tools/timeline.js
new file mode 100644
index 0000000..4ab6557
--- /dev/null
+++ b/package/ego-browser/skill-body/learnings/x-com/tools/timeline.js
@@ -0,0 +1,21 @@
+function boundedInteger(value, fallback, max) {
+ const number = value === undefined ? fallback : Number(value);
+ if (!Number.isFinite(number)) return fallback;
+ return Math.max(1, Math.min(max, Math.trunc(number)));
+}
+
+export async function getTimelinePosts(ctx, args = {}) {
+ const maxPosts = boundedInteger(args.maxPosts, 50, 100);
+
+ const posts = await ctx.js(String.raw`(() => {
+ const articles = [...document.querySelectorAll('[data-testid="tweet"]')]
+ return articles.slice(0, ${maxPosts}).map(el => ({
+ text: el.querySelector('[data-testid="tweetText"]')?.innerText?.trim() || '',
+ author: el.querySelector('[data-testid="User-Name"]')?.querySelector('span')?.innerText?.trim() || '',
+ handle: el.querySelector('[data-testid="User-Name"]')?.querySelector('a')?.getAttribute('href') || '',
+ timestamp: el.querySelector('time')?.getAttribute('datetime') || '',
+ }))
+ })()`);
+
+ return posts;
+}
diff --git a/package/ego-browser/src/env.ts b/package/ego-browser/src/env.ts
index 911d5a3..44bf52e 100644
--- a/package/ego-browser/src/env.ts
+++ b/package/ego-browser/src/env.ts
@@ -16,7 +16,7 @@ export function agentWorkspace() {
return bundledSkill;
}
- return resolve(REPO_ROOT, "..", "..", "skills", "ego-browser");
+ return resolve(REPO_ROOT, "..", "skill-body");
}
function resolvePath(path) {
diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.ts
index 762e84b..401ee5d 100644
--- a/package/ego-browser/src/helpers.ts
+++ b/package/ego-browser/src/helpers.ts
@@ -21,6 +21,13 @@ import {
initializeTaskSpaceHandle,
rollbackCreatedTaskSpace,
} from "./page-model.js";
+import {
+ loadBrowserToolSource,
+ loadLearnedContext,
+ runNodeSiteTool,
+ siteSkillsForUrl as siteSkillsForUrlCore,
+ wrapBrowserTool,
+} from "./learning/index.js";
export { NAME } from "./state.js";
export { cdp, js } from "./cdp-eval.js";
@@ -605,6 +612,62 @@ function findMatchingTaskSpace(spaces, nameOrId) {
return undefined;
}
+export async function siteSkillsForUrl(url) {
+ return siteSkillsForUrlCore(url, {
+ agentWorkspace: state.agentWorkspace(),
+ });
+}
+
+/**
+ * Return site skills matching a URL, or the current page URL when omitted.
+ * @param {string} [url] URL to inspect for site skills.
+ * @returns {Promise<Array<object|string>>}
+ */
+export async function siteSkills(url = undefined) {
+ const targetUrl = url ?? (await nav.pageInfo()).url ?? "";
+ return siteSkillsForUrl(targetUrl);
+}
+
+/**
+ * Run a learned Node site tool with the helper context.
+ * @param {string} siteId Site identifier.
+ * @param {string} toolName Tool name within the site.
+ * @param {object} [args] Tool arguments.
+ * @returns {Promise<any>} Tool result.
+ */
+export async function runSiteTool(siteId, toolName, args: any = {}) {
+ return runNodeSiteTool(siteId, toolName, args, helperContext(), {
+ agentWorkspace: state.agentWorkspace(),
+ });
+}
+
+/**
+ * Run a learned browser-side site tool in the current page.
+ * @param {string} siteId Site identifier.
+ * @param {string} toolName Tool name within the site.
+ * @param {object} [args] Tool arguments.
+ * @returns {Promise<any>} Browser tool result.
+ */
+export async function runSiteBrowserTool(siteId, toolName, args: any = {}) {
+ const source = await loadBrowserToolSource(siteId, toolName, {
+ agentWorkspace: state.agentWorkspace(),
+ });
+ return js(wrapBrowserTool(source, args));
+}
+
+/**
+ * Load learned context for the current page or a given URL.
+ * Returns accumulated site knowledge: notes content, available tools, usage examples.
+ * @param {string} [url] URL to inspect. Defaults to current page.
+ * @returns {Promise<object>} Learned context with knowledge and tool signatures.
+ */
+export async function learnContext(url = undefined) {
+ const targetUrl = url ?? (await nav.pageInfo()).url ?? "";
+ return loadLearnedContext(targetUrl, {
+ agentWorkspace: state.agentWorkspace(),
+ });
+}
+
export function helperContext(extra: any = {}) {
const { newTab: _newTab, ...publicNav } = nav;
const all = {
@@ -618,6 +681,11 @@ export function helperContext(extra: any = {}) {
js,
serverFetch,
browserFetch,
+ siteSkills,
+ siteSkillsForUrl,
+ runSiteTool,
+ runSiteBrowserTool,
+ learnContext,
profiles,
listTaskSpaces,
switchTaskSpace,
diff --git a/package/ego-browser/src/learning/check-domain-learning.ts b/package/ego-browser/src/learning/check-domain-learning.ts
new file mode 100644
index 0000000..a8df146
--- /dev/null
+++ b/package/ego-browser/src/learning/check-domain-learning.ts
@@ -0,0 +1,226 @@
+import { readdir, readFile, stat } from "node:fs/promises";
+import { join } from "node:path";
+
+import { agentWorkspace } from "../env.js";
+
+export interface ToolArgSchema {
+ type: string;
+ required: boolean;
+ description: string;
+}
+
+export interface ToolSchema {
+ description: string;
+ path: string;
+ args: Record<string, ToolArgSchema>;
+ returns: { type: string; description: string };
+}
+
+export interface NodeToolSchema extends ToolSchema {
+ callable: string;
+}
+
+export interface LearningManifest {
+ id: string;
+ name: string;
+ domains: string[];
+ notes: string[];
+ nodeTools?: Record<string, NodeToolSchema>;
+ browserTools?: Record<string, ToolSchema>;
+}
+
+export interface LearningEntry {
+ id: string;
+ name: string;
+ path: string;
+ domains: string[];
+ notes: string[];
+ nodeTools: Record<string, NodeToolSchema>;
+ browserTools: Record<string, ToolSchema>;
+}
+
+export interface LearnedContext {
+ exists: boolean;
+ siteId: string | null;
+ siteName: string | null;
+ domain: string;
+ knowledge: LearnedKnowledgeNote[];
+ tools: LearnedToolSignature[];
+}
+
+export interface LearnedKnowledgeNote {
+ siteId: string;
+ fileName: string;
+ content: string;
+}
+
+export interface LearnedToolSignature {
+ siteId: string;
+ toolName: string;
+ toolType: "node" | "browser";
+ description: string;
+ args: Record<string, ToolArgSchema>;
+ example: string;
+}
+
+export function learningsRoot(workspace = agentWorkspace()) {
+ return join(workspace, "learnings");
+}
+
+export const siteSkillsRoot = learningsRoot;
+
+export async function checkDomainLearningExists(
+ urlOrDomain: string,
+ options: { root?: string; agentWorkspace?: string } = {},
+) {
+ const hostname = urlHostname(urlOrDomain);
+ const root =
+ options.root || learningsRoot(options.agentWorkspace || agentWorkspace());
+ const matches = hostname ? await siteSkillsForUrl(hostname, { root }) : [];
+ return {
+ exists: matches.length > 0,
+ hostname,
+ root,
+ matches,
+ };
+}
+
+export async function checkLearningExists(
+ siteId: string,
+ options: { root?: string; agentWorkspace?: string } = {},
+) {
+ const root =
+ options.root || learningsRoot(options.agentWorkspace || agentWorkspace());
+ const siteDir = join(root, siteId);
+ const manifestPath = join(siteDir, "manifest.json");
+ const exists = await pathExists(manifestPath);
+ return {
+ exists,
+ root,
+ siteDir,
+ manifestPath,
+ };
+}
+
+export async function siteSkillsForUrl(url, options: any = {}) {
+ const hostname = urlHostname(url);
+ if (!hostname) {
+ return [];
+ }
+ const root =
+ options.root || learningsRoot(options.agentWorkspace || agentWorkspace());
+ const matches = [];
+ for (const siteDir of await iterLearningDirs(root)) {
+ let manifest;
+ try {
+ manifest = await loadLearningManifest(siteDir);
+ } catch {
+ continue;
+ }
+ const domains = Array.isArray(manifest.domains) ? manifest.domains : [];
+ if (
+ domains.some(
+ (domain) =>
+ typeof domain === "string" && domainMatches(hostname, domain),
+ )
+ ) {
+ matches.push(learningEntry(siteDir, manifest));
+ }
+ }
+ return matches;
+}
+
+export async function iterLearningDirs(root: string) {
+ let entries;
+ try {
+ entries = await readdir(root, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ return entries
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith("_"))
+ .map((entry) => join(root, entry.name))
+ .sort();
+}
+
+export async function loadLearningManifest(
+ siteDir: string,
+): Promise<LearningManifest> {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(await readFile(join(siteDir, "manifest.json"), "utf8"));
+ } catch (error) {
+ throw new Error(
+ `site skill ${JSON.stringify(siteDir)} has invalid or missing manifest.json: ${error.message}`,
+ );
+ }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ throw new Error(
+ `site skill ${JSON.stringify(siteDir)} manifest must be an object`,
+ );
+ }
+ return parsed as LearningManifest;
+}
+
+export function learningEntry(
+ siteDir: string,
+ manifest: LearningManifest,
+): LearningEntry {
+ const notes = Array.isArray(manifest.notes) ? manifest.notes : [];
+ return {
+ id: manifest.id || siteDir.split(/[\\/]/).at(-1),
+ name: manifest.name || manifest.id || siteDir.split(/[\\/]/).at(-1),
+ path: siteDir,
+ domains: Array.isArray(manifest.domains) ? [...manifest.domains] : [],
+ notes: notes.map((note) => join(siteDir, note)),
+ nodeTools: toolSchemasNode(manifest),
+ browserTools: toolSchemasBrowser(manifest),
+ };
+}
+
+export async function pathExists(path: string) {
+ try {
+ await stat(path);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function urlHostname(url) {
+ try {
+ const parsed = String(url).includes("://")
+ ? new URL(String(url))
+ : new URL(`https://${url}`);
+ return (parsed.hostname || "").toLowerCase().replace(/\.$/, "");
+ } catch {
+ return "";
+ }
+}
+
+function domainMatches(hostname, pattern) {
+ const normalized = String(pattern || "")
+ .toLowerCase()
+ .replace(/\.$/, "");
+ if (normalized.startsWith("*.")) {
+ const suffix = normalized.slice(2);
+ return hostname.endsWith(`.${suffix}`);
+ }
+ return hostname === normalized;
+}
+
+function toolSchemasNode(
+ manifest: LearningManifest,
+): Record<string, NodeToolSchema> {
+ const value = manifest.nodeTools;
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
+ return { ...value };
+}
+
+function toolSchemasBrowser(
+ manifest: LearningManifest,
+): Record<string, ToolSchema> {
+ const value = manifest.browserTools;
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
+ return { ...value };
+}
diff --git a/package/ego-browser/src/learning/index.ts b/package/ego-browser/src/learning/index.ts
new file mode 100644
index 0000000..86784e4
--- /dev/null
+++ b/package/ego-browser/src/learning/index.ts
@@ -0,0 +1,228 @@
+import { pathToFileURL } from "node:url";
+import { readFile } from "node:fs/promises";
+import { isAbsolute, relative, resolve } from "node:path";
+
+import {
+ iterLearningDirs,
+ learningEntry,
+ loadLearningManifest,
+ siteSkillsForUrl,
+ siteSkillsRoot,
+ urlHostname,
+ LearningManifest,
+ LearnedContext,
+ LearnedKnowledgeNote,
+ LearnedToolSignature,
+ NodeToolSchema,
+ ToolSchema,
+} from "./check-domain-learning.js";
+
+export {
+ checkDomainLearningExists,
+ checkLearningExists,
+ iterLearningDirs,
+ learningsRoot,
+ pathExists,
+ siteSkillsForUrl,
+ siteSkillsRoot,
+} from "./check-domain-learning.js";
+export {
+ validateLearning,
+ validateLearnings,
+ validateSiteSkills,
+} from "./validate-learning-format.js";
+
+/**
+ * Load learned context for a given URL.
+ * Returns site knowledge (notes content, available tools, selector hints).
+ */
+export async function loadLearnedContext(
+ url: string,
+ options: any = {},
+): Promise<LearnedContext> {
+ const matches = await siteSkillsForUrl(url, options);
+ if (matches.length === 0) {
+ return {
+ exists: false,
+ siteId: null,
+ siteName: null,
+ domain: urlHostname(url),
+ knowledge: [],
+ tools: [],
+ };
+ }
+
+ const toolSignatures: LearnedToolSignature[] = [];
+ const knowledgeNotes: LearnedKnowledgeNote[] = [];
+
+ for (const entry of matches) {
+ const siteId = entry.id;
+
+ for (const notePath of entry.notes) {
+ if (!isLearningNotePath(entry.path, notePath)) {
+ continue;
+ }
+ let content: string;
+ try {
+ content = await readFile(notePath, "utf8");
+ } catch {
+ continue;
+ }
+ const fileName = notePath.split(/[\\/]/).pop() || "";
+ knowledgeNotes.push({ siteId, fileName, content });
+ }
+
+ // Build tool signatures with usage examples
+ const nodeTools: Record<string, NodeToolSchema> = entry.nodeTools || {};
+ for (const [toolName, schema] of Object.entries(nodeTools)) {
+ toolSignatures.push({
+ siteId,
+ toolName,
+ toolType: "node",
+ description: schema.description || "",
+ args: schema.args || {},
+ example: `await runSiteTool("${siteId}", "${toolName}", { ... })`,
+ });
+ }
+
+ const browserTools: Record<string, ToolSchema> = entry.browserTools || {};
+ for (const [toolName, schema] of Object.entries(browserTools)) {
+ toolSignatures.push({
+ siteId,
+ toolName,
+ toolType: "browser",
+ description: schema.description || "",
+ args: schema.args || {},
+ example: `await runSiteBrowserTool("${siteId}", "${toolName}", { ... })`,
+ });
+ }
+ }
+
+ return {
+ exists: true,
+ siteId: matches[0].id,
+ siteName: matches[0].name,
+ domain: urlHostname(url),
+ knowledge: knowledgeNotes,
+ tools: toolSignatures,
+ };
+}
+
+function isLearningNotePath(siteDir: string, notePath: string) {
+ const relativePath = relative(resolve(siteDir), resolve(notePath));
+ const parts = relativePath.split(/[\\/]/);
+ return (
+ parts.length === 2 &&
+ parts[0] === "notes" &&
+ parts[1].endsWith(".md") &&
+ parts.every((part) => part && part !== "." && part !== "..")
+ );
+}
+
+export async function findSiteSkill(
+ siteId: string,
+ options: any = {},
+): Promise<{ siteDir: string; manifest: LearningManifest }> {
+ const root = options.root || siteSkillsRoot(options.agentWorkspace);
+ for (const siteDir of await iterLearningDirs(root)) {
+ const manifest = await loadLearningManifest(siteDir);
+ if (manifest.id === siteId) {
+ return { siteDir, manifest };
+ }
+ }
+ throw siteSkillNotFoundError(siteId, root);
+}
+
+export async function runNodeSiteTool(
+ siteId,
+ toolName,
+ args: any = {},
+ ctx,
+ options: any = {},
+) {
+ const { siteDir, manifest } = await findSiteSkill(siteId, options);
+ const schema = toolSchemas(manifest, "nodeTools")[toolName];
+ if (!schema || typeof schema !== "object") {
+ throw new Error(
+ `Node tool ${JSON.stringify(toolName)} is not declared by site skill ${JSON.stringify(siteId)}`,
+ );
+ }
+ const toolPath = relativeSitePath(siteDir, schema.path, "Node tool");
+ const module = await import(
+ `${pathToFileURL(toolPath).href}?t=${Date.now()}`
+ );
+ const callableName = schema.callable;
+ if (typeof callableName !== "string" || !callableName.trim()) {
+ throw new Error(
+ `Node tool ${JSON.stringify(toolName)} must declare a callable`,
+ );
+ }
+ const tool = module[callableName];
+ if (typeof tool !== "function") {
+ throw new Error(
+ `site skill ${JSON.stringify(siteId)} is missing Node callable ${JSON.stringify(callableName)}`,
+ );
+ }
+ return tool(ctx, args || {});
+}
+
+export async function loadBrowserToolSource(
+ siteId,
+ toolName,
+ options: any = {},
+) {
+ const { siteDir, manifest } = await findSiteSkill(siteId, options);
+ const schema = toolSchemas(manifest, "browserTools")[toolName];
+ if (!schema || typeof schema !== "object") {
+ throw new Error(
+ `browser tool ${JSON.stringify(toolName)} is not declared by site skill ${JSON.stringify(siteId)}`,
+ );
+ }
+ const toolPath = relativeSitePath(siteDir, schema.path, "browser tool");
+ return readFile(toolPath, "utf8");
+}
+
+export function wrapBrowserTool(source, args: any = {}) {
+ return `(async () => { const __egoBrowserTool = ${source}; return await __egoBrowserTool(${JSON.stringify(args || {})}); })()`;
+}
+
+export { learningEntry };
+
+function siteSkillNotFoundError(siteId, searchedRoot) {
+ const workspace = process.env.EGO_BROWSER_AGENT_WORKSPACE || "unset";
+ const lines = [
+ `site skill not found: ${JSON.stringify(siteId)}`,
+ ` searched: ${searchedRoot}`,
+ ` EGO_BROWSER_AGENT_WORKSPACE: ${workspace}`,
+ ` hint: ensure your write path begins with the searched root above`,
+ ];
+ return new Error(lines.join("\n"));
+}
+
+function toolSchemas(manifest, key) {
+ const value = manifest[key] || {};
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? { ...value }
+ : {};
+}
+
+function relativeSitePath(siteDir, manifestPath, label) {
+ if (typeof manifestPath !== "string" || !manifestPath.trim()) {
+ throw new Error(`${label} path must be a non-empty relative path`);
+ }
+ if (
+ manifestPath.includes("\\") ||
+ isAbsolute(manifestPath) ||
+ manifestPath.split("/").includes("..")
+ ) {
+ throw new Error(
+ `${label} path must be relative to the site skill directory`,
+ );
+ }
+ const resolved = resolve(siteDir, manifestPath);
+ const siteRoot = resolve(siteDir);
+ if (resolved !== siteRoot && !resolved.startsWith(`${siteRoot}/`)) {
+ throw new Error(`${label} path must stay inside the site skill directory`);
+ }
+ return resolved;
+}
diff --git a/package/ego-browser/src/learning/validate-learning-format.ts b/package/ego-browser/src/learning/validate-learning-format.ts
new file mode 100644
index 0000000..f895eb5
--- /dev/null
+++ b/package/ego-browser/src/learning/validate-learning-format.ts
@@ -0,0 +1,374 @@
+import { pathToFileURL } from "node:url";
+import { readFile } from "node:fs/promises";
+import { isAbsolute, join } from "node:path";
+
+import {
+ iterLearningDirs,
+ learningsRoot,
+ pathExists,
+} from "./check-domain-learning.js";
+
+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) {
+ const errors: string[] = [];
+ const siteId = siteDir.split(/[\\/]/).at(-1);
+ const manifestPath = join(siteDir, "manifest.json");
+ let manifest;
+ try {
+ manifest = JSON.parse(await readFile(manifestPath, "utf8"));
+ } catch (error) {
+ return [`${siteId}: invalid or missing manifest.json: ${error.message}`];
+ }
+ if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) {
+ return [`${siteId}: manifest.json must contain a JSON object`];
+ }
+
+ if (manifest.id !== siteId) {
+ errors.push(`${siteId}: manifest id must match directory name`);
+ }
+ if (typeof manifest.name !== "string" || !manifest.name.trim()) {
+ errors.push(`${siteId}: name must be a non-empty string`);
+ }
+
+ const domains = asStringList(manifest, "domains", errors, siteId);
+ if (domains.length === 0) {
+ errors.push(`${siteId}: domains must not be empty`);
+ }
+ for (const domain of domains) {
+ if (!isValidDomain(domain)) {
+ errors.push(`${siteId}: invalid domain ${JSON.stringify(domain)}`);
+ }
+ }
+
+ for (const note of asStringList(manifest, "notes", errors, siteId)) {
+ if (!isNotePath(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,
+ );
+ }
+
+ 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)}`,
+ );
+ continue;
+ }
+ 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)}`,
+ );
+ }
+ } catch (error) {
+ errors.push(
+ `${siteId}: cannot import Node tool ${JSON.stringify(schema.path)}: ${error.message}`,
+ );
+ }
+ }
+
+ 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)
+ ) {
+ 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,
+ );
+ }
+
+ return errors;
+}
+
+export async function validateLearnings(root = learningsRoot()) {
+ const errors: string[] = [];
+ for (const siteDir of await iterLearningDirs(root)) {
+ errors.push(...(await validateLearning(siteDir)));
+ }
+ return errors;
+}
+
+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())
+ ) {
+ 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> {
+ const value = manifest[key] || {};
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ errors.push(`${siteId}: ${key} must be an object keyed by tool name`);
+ return {};
+ }
+ for (const [toolName, schema] of Object.entries(value)) {
+ validateToolSchema(siteId, key, toolName, schema, errors);
+ }
+ return value;
+}
+
+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)}`,
+ );
+ return;
+ }
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
+ errors.push(`${prefix}: schema must be an object`);
+ return;
+ }
+ if (typeof schema.description !== "string" || !schema.description.trim()) {
+ errors.push(`${prefix}: description must be a non-empty string`);
+ }
+ if (key === "nodeTools") {
+ if (!isNodeToolPath(schema.path)) {
+ errors.push(`${prefix}: path must be a relative tools/*.js path`);
+ }
+ if (typeof schema.callable !== "string" || !schema.callable.trim()) {
+ errors.push(`${prefix}: callable must be a non-empty string`);
+ }
+ } else if (!isBrowserToolPath(schema.path)) {
+ errors.push(`${prefix}: path must be a relative browser-tools/*.js path`);
+ }
+
+ 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)}`,
+ );
+ continue;
+ }
+ validateValueSchema(
+ `${prefix}.args.${argName}`,
+ argSchema,
+ errors,
+ true,
+ "arg",
+ );
+ }
+ }
+ 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",
+ );
+ }
+}
+
+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)}`,
+ );
+ }
+ if (requireRequired && typeof schema.required !== "boolean") {
+ errors.push(`${prefix}: required must be a boolean`);
+ }
+ if (typeof schema.description !== "string" || !schema.description.trim()) {
+ errors.push(`${prefix}: description must be a non-empty string`);
+ }
+}
+
+function isValidDomain(pattern) {
+ if (typeof pattern !== "string" || !pattern) {
+ return false;
+ }
+ 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 true;
+}
+
+function isSafeToolName(name) {
+ 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)
+ ) {
+ return false;
+ }
+ return path.split("/").every((part) => part && part !== "." && part !== "..");
+}
+
+function isNotePath(path) {
+ const parts = isSafeRelativePath(path) ? path.split("/") : [];
+ return parts.length === 2 && parts[0] === "notes" && parts[1].endsWith(".md");
+}
+
+function isNodeToolPath(path) {
+ const parts = isSafeRelativePath(path) ? path.split("/") : [];
+ return parts.length === 2 && parts[0] === "tools" && parts[1].endsWith(".js");
+}
+
+function isBrowserToolPath(path) {
+ const parts = isSafeRelativePath(path) ? path.split("/") : [];
+ 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)))) {
+ errors.push(message);
+ }
+}
+
+async function rejectTemporaryRefs(
+ siteDir: string,
+ relativePath: string,
+ prefix: string,
+ errors: string[],
+) {
+ let text;
+ try {
+ text = await readFile(join(siteDir, relativePath), "utf8");
+ } catch {
+ return;
+ }
+ if (TEMP_REF_RE.test(text)) {
+ errors.push(
+ `${prefix}: contains temporary snapshot ref; use stable locators instead`,
+ );
+ }
+}
diff --git a/package/ego-browser/src/skill-package.test.mjs b/package/ego-browser/src/skill-package.test.mjs
index 00e233c..2ea33da 100644
--- a/package/ego-browser/src/skill-package.test.mjs
+++ b/package/ego-browser/src/skill-package.test.mjs
@@ -16,7 +16,10 @@ test("the bundled usage guide is the source guide between version and end marker
const version = /^version: "([^"]+)"$/m.exec(source)[1];
const lines = bundled.trimEnd().split("\n");
- assert.deepEqual(await readdir(join(outDir, "ego-browser")), ["SKILL.md"]);
+ assert.deepEqual((await readdir(join(outDir, "ego-browser"))).sort(), [
+ "SKILL.md",
+ "learnings",
+ ]);
assert.equal(
lines[0],
`[ego-browser:skill] ego-browser usage guide v${version}`,