citrolabs/ego-lite / package/ego-browser/skill-body
skill-body
Verifiedego-browser
Call help() or help("page.click") to print signatures and uncommon options
of APIs named below; it prints by itself, so do not wrap it in console.log.
For installation or connection problems, read references/install.md in the
ego-browser Skill directory and follow its link for your operating system.
Run browser scripts
Pass the script to ego-browser nodejs.
Heredoc exists only in Bash/Zsh, so the form depends on your shell.
Bash, Zsh, Git Bash
ego-browser nodejs <<'EOF'
const task = await taskSpace("inspect example page");
const page = task.page("p1");
await page.goto("https://example.com");
console.log({ taskSpaceId: task.spaceId, page: page.label });
console.log(await page.snapshot());
EOF
When a sandbox blocks heredoc input, use ego-browser nodejs -e '<code>'
instead. Use single quotes around the code and double quotes for JavaScript
strings; single quotes within the code require shell quoting.
PowerShell
PowerShell has no heredoc, and Windows PowerShell 5.1 strips double quotes from
native-program arguments, which splits the script. Never pass a multi-line or
double-quoted script to -e. Write a UTF-8 .mjs file and evaluate this
one-line entry point:
ego-browser nodejs -e "await import('file:///C:/Users/<name>/ego/task.mjs')"
The module gets the same helpers and console as an inline script, so put the
whole task in the file. Use forward slashes in the URL, and keep non-ASCII text
such as Chinese in the file, never in -e.
Do not pipe the file with Get-Content: 5.1 corrupts non-ASCII text and
truncates strings. PowerShell has no < redirection either.
cmd
cmd has no heredoc but supports input redirection:
ego-browser nodejs < C:\Users\<name>\ego\task.mjs
Later rounds with a script file
Each run is a new process, so write a new, complete file per round
(round-01.mjs, round-02.mjs, ...); editing the previous one replays old
steps. Keep one goal's files in a new directory named for the goal and time,
such as C:/Users/<name>/ego/laptop-prices-20260922-1405/, and only run files
written in this conversation. Create files with your file tool: PowerShell
Set-Content, Out-File, and > write ANSI or UTF-16 on 5.1.
When the script fails to parse
SyntaxError: await is only valid in async functions and the top level bodies of modules almost always means the shell damaged the script; top-level await is
supported. Do not wrap the code in an async IIFE, open a new task space, or
resend the command. Switch to the .mjs file form.
The script always runs in Node.js, not in the web Page. Browser helpers and
Node.js APIs belong in the script; Page globals such as window, document,
location, and DOM APIs do not. Put browser-side JavaScript inside
page.evaluate(). Do not import Playwright or launch another browser.
The Node.js runtime uses ESM. When a script needs local files, load built-ins
with dynamic imports such as await import("node:fs/promises"). The script
does not run in your shell's working directory, so use absolute paths for every
file it reads or writes. It also does not inherit your shell's environment
variables: process.env will not contain values you set before running
ego-browser, so write every input directly into the script.
Ego-browser exposes a small custom API. It is not Playwright, even where names
and options look similar. Use only the TaskSpace, Page, FileChooser, mouse, and
keyboard APIs listed in this Skill. Do not infer methods such as locator(),
getByRole(), context(), expect(), or route(). When the listed API does
not cover an operation, use page.evaluate() or page.cdp() instead of
guessing another method.
Only these pointer actions accept an optional label option: click(),
dblclick(), hover(), dragAndDrop(), mouse.click(), mouse.move(), and
mouse.wheel(). Pass a concise 3-6 word description to keep the action text
next to the visible agent cursor in sync with the action. Other methods, such
as fill(), press(), focus(), selectOption(), waitForSelector(),
keyboard.*(), mouse.down(), and mouse.up(), reject a label option.
The label in selectOption(selector, { label }) is different: it selects the
option whose visible text matches.
When the user explicitly asks for ego-browser, start with a real browser command and diagnose the CLI or installation only if it fails.
Spaces, rounds, and pages
- One user goal keeps one TaskSpace across your replies while that space exists. Use multiple spaces only when the user explicitly requests them.
- Start and end each reply's browser work as described in "Starting and ending a reply" below. Task space names are unique; prefer the numeric id once you have it.
- Never use a new TaskSpace to recover from a stuck, blocked, timed-out, or unexpected Page. Recover within the existing space; if it cannot continue, stop and ask the user.
- Every invocation starts a new Node.js process. Task spaces, tabs, and Page labels persist; JavaScript variables do not.
- A new task space starts with Page
p1; navigate it instead of opening another Page. - Reuse a Page with
goto()instead of opening a new Page for every URL. - All time values are milliseconds.
Do not inspect or select profiles unless the user explicitly requests a
particular Ego Lite profile. A profileId applies only when creating a space;
use help("profiles") for the exact workflow.
Supported TaskSpace API:
- State:
spaceId,name,ownership,page(label),userPage() - Pages:
await task.pages(),await task.tabs(),newPage(),adopt(page, { as? }),release(label) - Control:
waitForControl(options),handOff(),finish({ keep }) - Advanced:
cdp(method, params, options)
Pages receive permanent labels such as p1, p2, and p3. Prefer these labels
to custom { as } values. Reuse or close Pages as the task proceeds; the runtime
reports the configured Page budget when it is reached.
task.page(label) only refers to a Page that already exists; it never creates
one, and its handle is always truthy, so task.page("p2") || await task.newPage()
and if (!page) do not detect a missing label. Use labels printed by earlier
output or by await task.pages(). When multiple Pages must stay open, call
await task.newPage() for another blank Page and navigate it with goto().
await task.pages() returns managed Pages. await task.tabs() returns every tab in the
space as { label?, page, targetId, title, url, active, openedBy }. A tab
without a label is unmanaged; adopt it before operating:
const active = (await task.tabs()).find((item) => item.active);
if (active && !active.label) {
const page = await task.adopt(active.page);
console.log({ page: page.label, url: await page.url() });
}
release(label) returns an unknown-origin Page to the user without closing its
tab. Close Agent-created Pages with page.close(). Treat openedBy: "unknown"
as user-owned when deciding whether a Page may be closed.
Page operations
Page API:
- State and observation:
label,spaceId,openedBy,targetId,url(),title(),info(),snapshot(),screenshot() - Navigation and waits:
goto(),reload(),waitForURL(),waitForEvent(),waitForSelector(),waitForLoadState(),waitForFunction(),waitForTimeout() - Elements:
click(),dblclick(),hover(),dragAndDrop(),fill(),selectOption(),focus(),press(),setInputFiles(),waitForFileChooser(),close() - Dialogs:
acceptDialog(promptText?),dismissDialog() - Pointer:
mouse.click(),move(),down(),up(),wheel() - Keyboard:
keyboard.down(),up(),press(),type(),insertText(),paste() - Page code and protocols:
evaluate(fnOrString, argument),fetch(url, options),cdp(method, params, options),events()
page.evaluate() callbacks run only inside the Page; they cannot read variables
or Node.js modules from the surrounding script. Define browser-side helpers
inside the callback or pass one JSON-serializable value as its second argument.
goto() and reload() stop a navigation that has not committed by their
timeout, so the Page stays usable on its previous document; retry with a longer
timeout. Any other call on a Page whose navigation is pending (after a link
click, for example) waits one bounded period, then fails with
EGO_PAGE_UNRESPONSIVE and stops that navigation; the error says which
document the Page shows now and how to load the pending one. evaluate()
reports the same outcome as EGO_PAGE_EVALUATION_TIMED_OUT with stopped
set.
Work efficiently:
- Each time you observe, collect only the cheapest page state sufficient to choose the next action. Use a snapshot for semantic or locator ground truth and a screenshot for visual confirmation; do not request both by default.
- If an action does not produce the expected result, inspect the current page before deciding whether to retry. Do not blindly repeat it or immediately fall back to coordinates or raw CDP.
- Once the page clearly shows the requested result, stop; do not confirm the same result through multiple surfaces.
Semantic pages: snapshot and selectors
Prefer snapshots and semantic selectors for ordinary DOM pages. Use screenshots and coordinates only when useful DOM semantics are unavailable.
Before choosing an unfamiliar target, take a snapshot. When the current state is sufficient to plan several actions on the same Page, complete them in one script invocation, then observe the result once. Observe between actions only when an intermediate result changes what should happen next. Keep the action sequence, the wait for its final expected state, and the next snapshot in the same script invocation. Print the snapshot last so the next round can act on it directly. The final snapshot is the next round's starting view of the changed page; without it, that round usually has to spend a separate browser call observing before it can choose the next target, which wastes compute.
Wait for the expected result: use waitForURL() for navigation,
waitForSelector() for element state, or waitForFunction() for application
state. Avoid fixed delays when an observable condition exists. Actions stop
waiting for a missing target once the page is idle, so waitForSelector()
first when an element is expected later. A snapshot captures the current
moment; it does not wait for the page to become stable.
page.snapshot() captures the current viewport. For content outside it, use
page.snapshot({ scope: "full_page" }). When the document scrolls past the
viewport, the snapshot ends with a [more content below the viewport: ...]
line: nodes are omitted, not absent. If the expected result may land below
the fold, scroll or use full_page before concluding it did not appear.
The default viewport snapshot includes visible iframe content returned by the
browser. To focus on a frame's subtree, reuse the ref printed on its iframe
line:
console.log(await page.snapshot({ scope: "subtree", root: "@12" }));
Use the refs returned by the subtree for actions inside the iframe. A subtree snapshot does not scope later locator actions; they still prefer actionable matches in the top document before searching frames.
waitForLoadState() defaults to load. waitForFunction() takes Playwright's
args (undefined before options if no arg) but returns true, not the
predicate's value:
await page.waitForFunction(() => window.ready, undefined, { timeout: 5000 });
// Next round: act using the previous output, verify, then prepare the next round.
const page = task.page("p1");
await page.fill("@21", "user@example.com");
await page.click("loc=role:button[name='Sign in']");
await page.waitForSelector("loc=css:#account-home", { state: "visible" });
console.log(await page.snapshot());
Element actions accept:
- snapshot refs such as
@21orref=21 text=...for page contentloc=css:,loc=role:, andloc=href:locatorsxpath=...- raw CSS selectors
Selector actions require exactly one match. Unquoted text normalizes whitespace,
ignores case, and matches a substring; quoted text such as
text="Save changes" is exact and case-sensitive.
A small Playwright-compatible selector subset is also accepted: css=...,
terminal :has-text("...") and :text-is("..."), >> nth=N after a CSS,
text, or href selector (N is -1 or non-negative), plus
loc=role:...[name*="..."] for accessible-name substrings. Other Playwright
selector syntax is not supported.
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.
click(), fill(), hover(), and dragAndDrop() automatically bring their
target into view with browser wheel input, falling back to a programmatic
scroll when the wheel does not move the target. Do not pre-scroll solely to
make a DOM target actionable.
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. Actions use an actionable match
in the top document first, then search frames when the top document has none.
Multiple actionable matches in the selected document or frame are ambiguous.
Select options by value, visible label, or zero-based index. A string matches either value or label; pass an array for a multiple select:
await page.selectOption("select[name=month]", { label: "October" });
Pass null or [] to clear the current selection.
Visual pages: screenshot, mouse, and keyboard
Use a screenshot with mouse and keyboard operations for canvas, rich-text, spreadsheets, maps, and other interfaces that lack useful DOM semantics:
const path = await page.screenshot({ path: "/absolute/path/before.png" });
await page.mouse.click(420, 260, { label: "open spreadsheet cell" });
await page.mouse.wheel(0, 600, { label: "scroll project board" });
await page.keyboard.paste("hello\tworld");
console.log({ screenshot: path });
path must be absolute; relative paths are rejected. Omit path to write
into the system temporary directory and use the returned file path.
Use forward slashes in Windows paths, such as
C:/Users/<name>/ego-shots/before.png: backslashes are JavaScript string
escapes.
Inspect the screenshot with an image-viewing tool. Coordinates use CSS pixels;
keyboard names and +-separated chords follow Playwright syntax. Use
ControlOrMeta for portable shortcuts and verify the resulting page state.
mouse.wheel() performs a short wheel-input motion at the current mouse
position and resolves when that motion completes. In each script invocation, move or
click over the intended scrollable area before using it.
On macOS and Windows, keyboard.paste() sends the native paste shortcut and
then restores the user's clipboard. Pass { text, html } when a rich editor
needs structured clipboard content; text is the plain-text fallback. On other
platforms, use keyboard.insertText() for plain text.
For rich-text editors and editable grids, validate a small edit before repeating it at scale. Canvas-backed editors may not expose visible content through DOM text or selectors; verify those results with a screenshot or an application-specific visible state.
page.screenshot() can sometimes fail after about 15s with
EGO_PAGE_UNRESPONSIVE on Page.captureScreenshot, even if page.evaluate()
still works. Retry at most once. For a canvas, read its pixels through
page.evaluate() with canvas.toDataURL("image/png") (tainted canvases throw;
WebGL may read blank).
Page JavaScript and CDP
Use page.evaluate() for bulk extraction or complex in-page work. It returns a
JSON-serializable value:
const rows = await page.evaluate(
({ selector, limit }) =>
[...document.querySelectorAll(selector)].slice(0, limit).map((node) => ({
text: node.textContent?.trim(),
href: node.querySelector("a")?.href,
})),
{ selector: "article", limit: 20 },
);
page.evaluate() has no timeout option. Keep long work in bounded calls; on a
safety timeout, use executionStopped and mayHaveLateEffects to decide
whether an unsafe follow-up requires reloading or closing the Page first.
Use documented Page methods first. If a wrapper is missing or does not work
reliably on the current page, use page.cdp() as a lower-level path for
diagnosis or control. It accepts Page, Runtime, DOM, Network, Input, and similar
commands; use task.cdp() for Target and Browser commands. Both reject a misplaced
sessionId in params. Raw CDP invalidates refs. Do not persist page.targetId
across rounds.
Action receipts, popups, and dialogs
When an action is expected to open a new Page, start the wait before the action:
const popupPromise = page.waitForEvent("popup");
await page.click('a[target="_blank"]');
const popupPage = await popupPromise;
await popupPage.waitForLoadState();
High-level actions also report immediately observed popups in receipt.popups
as { label, targetId }. Resolve the Page with
task.page(receipt.popups[0].label) and continue there; wait for its URL when
the destination matters.
Page sessions hide page console messages from CDP so sites cannot detect the
automation. To read Runtime.consoleAPICalled while debugging, first call
await page.cdp("egoAutomated.disable"), then page.cdp("Runtime.enable").
Sites can detect CDP again while it is off.
A synchronous JavaScript dialog may appear as receipt.dialog or in
page.info(). Handle it before continuing:
await page.acceptDialog("prompt response");
// Or: await page.dismissDialog();
A receipt describes only the dispatched action and immediate popup or dialog observations; it does not verify the resulting application state.
Files and requests
Set an existing file input with absolute paths:
await page.setInputFiles("input[type=file]", ["/absolute/path/report.pdf"]);
If a click creates the file input, start waiting before the click:
const chooserPromise = page.waitForFileChooser({ timeout: 10_000 });
await page.click("button.upload");
const chooser = await chooserPromise;
const result = await chooser.setFiles("/absolute/path/report.pdf");
An upload-triggered JavaScript dialog may be returned as result.dialog; when
present, handle it with the dialog methods above.
For a browser download, arm the event before the triggering action and save the returned artifact to an absolute path in the same script:
const downloadPromise = page.waitForEvent("download", { timeout: 30_000 });
await page.click("button.download");
const download = await downloadPromise;
console.log({
url: download.url(),
suggestedFilename: download.suggestedFilename(),
});
await download.saveAs("/absolute/path/report.pdf");
download.saveAs() waits for completion and creates missing parent
directories. download.path() returns the round-local temporary file;
failure(), cancel(), and delete() manage its lifecycle. Temporary download
files are removed when the SDK round is disposed, so call saveAs() before the
script ends. Do not set a download directory with raw CDP; the download wait
manages the browser's single shared download setting.
page.fetch() runs window.fetch() in the Page: relative URLs, cookies, and
service workers use that Page, and browser CORS still applies. It returns
{ ok, status, statusText, url, headers, body }:
const response = await page.fetch("/api/items", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ limit: 20 }),
timeout: 10_000,
});
Save binary responses without converting them to text:
await page.fetch("/image.png", { saveAs: "/absolute/path/image.png" });
Use standard Node.js fetch() for background requests that do not need Page
browser semantics.
Starting and ending a reply
Begin the first script of each reply by choosing the space. A new goal gets a new space. A user message that continues an earlier goal, such as a further question, a correction, or a request to continue, continues in that goal's space if it still exists, whatever state your last reply left it in:
const SPACE_ID = 7; // printed by your last reply about this goal; null for a new goal
const entry =
SPACE_ID === null
? undefined
: (await listTaskSpaces()).find((s) => s.id === SPACE_ID);
const task = !entry
? await taskSpace("descriptive goal name") // new goal, or the earlier space was closed
: entry.ownership === "user"
? await claimTaskSpace(SPACE_ID) // you finished it with kept Pages
: entry.ownership === "agentDelegatedToUser"
? await takeOverTaskSpace(SPACE_ID) // control is with the user
: await taskSpace(SPACE_ID); // still in your control
// After a claim, no tab has a label yet: adopt the tab you kept.
const page =
(await task.pages())[0] ?? (await task.adopt((await task.tabs())[0].page));
console.log({
taskSpaceId: task.spaceId,
page: page.label,
tabs: await task.tabs(),
});
finish() ends all Page labels, kept Pages included. Until you claim a space
you finished with kept Pages, neither taskSpace() nor takeOverTaskSpace()
can resume it. After the claim, adopt each tab you kept and use the label
adopt() returns.
End each reply's browser work with one finish() in a separate last script,
run after earlier output has shown that the request is done, and wait for it
before you report. A space finished too early must not take more work in this
reply:
const task = await taskSpace(7); // the taskSpaceId printed earlier in this reply
// Default: close the space, including tabs you kept in an earlier reply.
await task.finish({ keep: [] });
// Exception, instead of the default: keep only the result Page for the user.
await task.finish({ keep: ["p2"] });
Keeping Pages is a rare exception: retain only necessary Pages when the user explicitly asks, or when the result must remain in the browser for the user to view or continue working with. Pages merely visited, search results, and intermediate steps do not need to remain open.
After finish(), do not operate any Page in the same script.
User control
Stop when the user takes control or the space is inactive or unassigned. Do not retry or route around the stop. Permission prompts, device choosers, and other browser-owned prompts require the user to handle them.
When the user must act in the browser (login without credentials the user gave,
CAPTCHA or human verification, 2FA, or other manual step), call
await task.handOff(), end the round, and explain what they should do. Do not
guess credentials or work around it silently.
After the user confirms, resume the same space:
const task = await takeOverTaskSpace(7);
const userPage = task.userPage();
Adopt userPage if it is unmanaged. Use waitForControl() only when the current
script must wait in place.
Claim any other user-owned or inactive space only when the user explicitly asks; the space you finished for the current goal is claimed as in "Starting and ending a reply".
User-created and unknown-origin tabs are protected; if any remain, keep: []
does not close the whole space, and the script output says so. Tabs you kept in
an earlier reply stay yours after a claim and do not block closing. The blank
tab that page.close() leaves when it closes the last Page is SDK-owned and
never blocks closing. Do not close unwanted Pages one by one at completion; list
the Pages to keep instead. Do not call finish() when the task stops for user
control or an error.
If the final output contains [ego-browser:notice], finish the current browser
task, tell the user an Ego Lite update is available, and run
ego-browser upgrade only with their approval. Run ego-browser skill again
after the upgrade.
Clearing cookies, cache, and storage
Before clearing any cookie, cache, or storage, read
references/clearing-state.md in the ego-browser Skill directory. Some clears
reach the whole browser profile.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |