AGENT SKILL

stella-browser

暂无简介

License 许可
MIT
所属仓库
1missthesun/stella
最近更新
2026-11-15
Stars
★ 2
Forks
1

03 SKILL.md 正文

Stella Browser

Use code for production browser automation. Its persistent JavaScript runtime exposes a deeply frozen browser object with top-level await. Bindings and Tab and Locator identities persist across calls, so create handles once and reuse them.

Use var for reusable REPL bindings: let/const names can't be declared again in a later cell. Browser actions are not exposed through Bash; use the frozen browser API only.

Which Browser

Pick the browser at the start of the task:

  • The user's own browser, browser.use("external"), the default while the Stella Browser extension is connected: their real browser (Chrome, Brave, Edge or Arc), signed in exactly as the user is, so their email, GitHub, bank, shopping, social and work tools just work. Your tabs open in the background, in a tab group labeled "Stella". Nothing is copied, so a session never goes stale.
  • Stella's browser, browser.use("in-app"): when the extension isn't connected, or for work that should stay out of the user's browser (throwaway or test sessions, anything that would disturb their tabs or sign them out). It has its own profile and is signed in only where someone signed in inside it (the user in Stella's Browser panel, or a sign-in the user completed in your tab).

Without a browser.use() call, the first browser call picks the user's browser if the extension is connected, else Stella's. await browser.use() (no argument) resolves that default and returns { backend }; read it instead of browser.backend, which only reflects an explicit choice.

await browser.use("external"); // or leave it to the default
var tab = await browser.tabs.new();
await tab.goto("https://github.com/notifications");

browser.use() sets the browser for handles you acquire afterwards. Every Tab and Locator keeps its fixed .backend, so an existing handle keeps routing to the browser that created it. Use both in one task when it helps, for example a throwaway test session in Stella's browser beside the signed-in work in the user's.

Several browsers or profiles

The extension can be connected in several browsers and profiles at once (say Chrome and Brave, or a work and a personal profile). Stella uses the one picked in Settings, otherwise the one the user is in right now (the frontmost browser, its most recently used profile). Once your first external command lands in a browser, your later commands stay there.

await browser.browsers();
// [{ id, label: "Brave · Work (me@corp.com)", browser, profile, email, enabled, inUse, current }]
await browser.use("external", { browser: "Brave" }); // a label, id, browser or profile name from browsers()

current: true marks the browser your commands go to, inUse: true the one Stella would pick by default. Only target a specific one when the task needs that account (for example the work profile); otherwise leave the default. If your browser is closed mid-task, commands fail after a short wait with a message naming it: open a new tab with browser.tabs.new() to continue in another connected browser, or ask the user to reopen it.

Guest rules

In the user's browser you are a guest in their window:

  • Work only in tabs you opened. Never read, use or close their other tabs.
  • Keep to one tab and reuse it. Your tabs close a few minutes after your task ends; tab.leaveForUser() keeps one open for the user.
  • Don't call tab.show() there unless the user asked to see the page: it brings their browser window to the front.

When the extension is not connected, the first command in the user's browser fails with "Extension not connected" and Stella offers the user a card to connect it. If it stays unconnected, continue in Stella's browser. For a step that needs the user's account there, open its sign-in page in a Stella browser tab, show() it, and ask the user to sign in once in Stella's Browser panel; Stella keeps that login. Never ask for or type their password yourself. Continue once they confirm.

If a site in Stella's browser turns out signed out and the task needs the user's account, switch to the user's browser for that site instead of asking them to sign in.

Production Workflow

Acquire one task-owned tab, navigate that handle, keep its page and locator handles, and batch deterministic dependent actions in one cell. Reuse that one tab with tab.goto() for every navigation in the task — never open a new tab per page, and close() any extra tab as soon as it has served its purpose (stray tabs accumulate in the user's browser, especially in external mode):

var tab = await browser.tabs.new();
await tab.goto("https://example.com/sign-in");
var page = tab.playwright;
var email = page.getByLabel("Email", { exact: true });
var password = page.getByLabel("Password", { exact: true });
var submit = page.getByRole("button", { name: "Sign in", exact: true });

await email.fill("user@example.com");
await password.fill("correct-horse-battery-staple");
await submit.click();
await page.waitForURL("**/dashboard");
({ url: await tab.url(), title: await tab.title() });

goto(), click() and Enter presses already wait for the page to settle (loaded and quiet, up to 3 s). Never add fixed sleeps (setTimeout, waitForTimeout); if what you need is still loading, wait for it: await locator.waitFor().

Do not spend one code call per action. Keep sequential awaits together when no intermediate result changes the plan. Split at a real decision point, return the cheapest useful value, then continue with the same handles in the next cell:

var search = page.getByPlaceholder("Search");
var rows = page.locator("[data-testid='result-row']");
await search.fill("quarterly report");
await search.press("Enter");
await rows.first().waitFor({ state: "visible" });
await rows.count();

After deciding which result to use, reuse tab, page, and rows:

var chosenRow = rows.nth(0);
await chosenRow.click();
await page.waitForURL("**/reports/**");
await tab.title();

Locators resolve against current page state when called; do not replace a locator merely because the DOM changed. Rebuild it only when the selector or intended element changes.

Selectors (semantic and CSS) search the top document plus same-origin iframes and open shadow roots. Snapshots also expose cross-origin frame content through frame-qualified refs (see Observe Cheaply below); to act inside a cross-origin frame, use a ref from the latest observation rather than guessing a top-document selector or matching a same-named control elsewhere.

Keyboard

There is no page.keyboard. Page-level keys go through the tab handle:

  • tab.press(key) sends a key to whatever holds focus: "Enter", "Escape", "Tab", combos like "Control+a" or "Meta+Shift+P".
  • tab.keyboard.type(text) inserts raw text at the current focus without per-character key events (works for emoji/CJK, and for canvas-style editors after clicking into them).
  • locator.press(key) focuses its element first, then presses.
await tab.playwright.getByRole("textbox", { name: "Document content" }).click();
await tab.keyboard.type("Hello world");
await tab.press("Control+a");

Observe Cheaply

Use the least expensive observation that answers the question:

  • Page identity: await tab.url() or await tab.title().
  • Element existence or state: count(), isVisible(), isEnabled(), or isChecked().
  • Focused values: innerText(), textContent(), inputValue(), or getAttribute().
  • Unknown structure at a branch or recovery point: tab.axSnapshot() (incremental; see below). It is not available in cloud browser sessions; there, and whenever the full DOM snapshot format is wanted, use tab.snapshot() or page.domSnapshot().
  • Visual appearance, coordinates, or rendering: tab.screenshot(). The image is attached to the tool result automatically; the JavaScript return value is only a compact { attached, path, format, mimeType } receipt. Do not pass that receipt to codeRuntime.emitImage().

Screenshot files stay on disk after the code call returns, so later Bash, Read or drive_upload calls can use the returned path. By default they go to ~/.stella/media/screenshots/<agent or conversation>/ and are deleted after 7 days (or sooner, oldest first, once that folder passes 1 GB). To keep one or put it somewhere specific, pass path: await tab.screenshot({ path: "~/.stella/outputs/report/home.png" }) writes there (a relative path is relative to your working directory, ~ is your home, .png/.jpg picks the format) and that file is never cleaned up.

Do not take a snapshot after every action. Snapshot only when page structure is needed to choose the next step. Use a screenshot only when pixels matter.

Semantic snapshots are bounded to 200 emitted entries and 20,000 characters. When a page exceeds that budget, metadata reports truncation and unavailable frames; narrow with selector, interactive, compact, or maxDepth instead of requesting repeated full-page snapshots. Selector-scoped captures omit descendant frames.

Frame-qualified refs are bound to the document they were observed in: a cross-origin ref rejects a detached node or a replaced document instead of falling back to a same-named control, and pointer geometry through a transformed or CSS-zoomed iframe is rejected when it cannot be mapped safely. If a snapshot fails closed because an operator-configured domain filter (STELLA_BROWSER_ALLOWED_DOMAINS) applies to the external browser, use the in-app browser instead; never disable the filter.

Incremental AX observations

tab.axSnapshot() reads the browser accessibility tree, including accessible child frames. Its default mode: "auto" returns one of:

  • { kind: "full", snapshotId, snapshot, reason } on first use, a document/options change, when a diff would be larger than the full tree, or when the bounded diff computation would exceed its budget.
  • { kind: "diff", snapshotId, baseSnapshotId, diff } with unified line-diff hunks relative to the indicated previous observation. Deleted lines are prefixed -, added lines +, and nearby unchanged lines with a space. Refs on deleted lines are no longer evidence for an action.
  • { kind: "unchanged", snapshotId } when the bounded tree has not changed. This does not mean the page has finished loading or that pixels are unchanged.

The baseline is private to this persistent runtime, backend, tab generation and snapshot options. Document replacement and reload reset identity even when the URL is unchanged. Same-document history changes can appear as ordinary diffs. A failed capture clears the baseline. Only the observed bounded tree is compared; omitted content is not claimed unchanged.

var observation = await tab.axSnapshot();
// Select a ref from the returned full tree or its subsequent changes.
await tab.playwright.locator("@e123").click(); // replace with an observed ref
await tab.axSnapshot();

Use await tab.axSnapshot({ mode: "full" }) after context compaction, output pruning, or whenever the referenced baseline is no longer in context. mode: "diff" requests differences even if larger; a missing or incompatible baseline or exhausted computation budget still returns full output. AX options are mode, interactive, compact, maxDepth, and selector. Keep using the same options to retain the baseline. The DOM snapshot APIs remain full-output and do not share the AX baseline.

Dialogs and Unresponsive Tabs

Page dialogs never block you:

  • alert() is dismissed, confirm() answers Cancel and prompt() returns null. Actions that may trigger one (click, press, check, selectOption, …) return { dialogs: [{ type, message, answer }] } when one fired, so read it to learn what the page said.
  • To accept a confirm (for example "Delete this item?"), override it before the click: await page.evaluate(() => { window.confirm = () => true; }).
  • "Leave site?" (beforeunload) prompts are accepted automatically when you navigate, go back or close your tab.

If a tab stops answering (a command times out with a message saying the page may be blocked), don't retry the same command on it. await tab.goto(url) usually recovers it; if not, await tab.close() and continue in await browser.tabs.new(). After a timeout on a mutating action, check the page state before repeating it.

Downloads and File Pickers

In Stella's browser nothing opens a native dialog. A download saves straight to ~/.stella/media/downloads/<agent or conversation>/; wrap the action that starts it to get the file:

var file = await tab.waitForDownload(async () => await page.getByRole("button", { name: "Export MP4" }).click());
file.path; // absolute path of the saved file, e.g. for Bash, Read or drive_upload

waitForDownload() resolves once a download started after the action finishes (default timeout 60 s, { timeoutMs } up to 600 s) and throws if it was cancelled. await browser.downloads() lists this session's recent downloads, newest first. Clicking a file input opens no picker: use locator.setInputFiles([absolutePath]). window.print() does nothing; take tab.screenshot({ fullPage: true }) instead. In the user's own browser, downloads go to their browser's Downloads folder as usual.

Synchronize on Browser State

Wait for the state caused by the action:

await submit.click();
await page.waitForURL("**/complete", { timeout: 30000 });

var confirmation = page.getByText("Saved", { exact: true });
await confirmation.waitFor({ state: "visible", timeout: 30000 });

Locator.waitFor() supports attached, detached, visible, and hidden. Prefer it, waitForURL(), or expectNewTab() over fixed delays. Although page.waitForTimeout(ms) exists, do not use it for routine synchronization or insert sleeps between deterministic actions.

New Tabs

Wrap the action that opens a tab with expectNewTab(). Calling it after the click misses the before-state used to identify the new owned tab.

var openReport = page.getByRole("link", { name: "Open report", exact: true });
var reportTab = await tab.expectNewTab(async () => await openReport.click(), {
  timeoutMs: 10000,
});
var reportPage = reportTab.playwright;
await reportPage.getByRole("heading", { name: "Report" }).waitFor();

expectNewTab() succeeds only when exactly one newly adopted owned tab appears. Its default timeout is 10 seconds and its maximum is 60 seconds. The same method is available as page.expectNewTab().

Showing a Tab to the User

Your tabs appear in the user's Browser panel, but the panel never switches to them on its own: opening a tab or navigating does not take the user away from what they are viewing. When the user wants to see the page (they asked you to open something for them, to show them something, or to take over a sign-in), bring the tab forward yourself:

await tab.goto("https://example.com");
await tab.show();

Call show() once the page is worth looking at, not on every step, and not for tabs you only use for research or background work. On a tab in the user's own browser, show() activates the tab and brings their browser window to the front, so call it there only when they asked to see it.

Finalize Owned Tabs

Your tabs belong to your task. A few minutes after it ends (finished, stopped or failed), its tabs close, except tabs left for the user and tabs the user has looked at or taken over, which are released to them and stay open.

Whenever your report points the user at a tab ("it's open in your browser", a page to review, a form to finish, a sign-in to complete), leave it for them before you report:

await tab.leaveForUser();

Stella never closes that tab. You can keep using it until you finish; when your other tabs close, it moves out of the Stella group instead and is the user's from then on. As a safety net, a tab whose address or title your final report mentions is kept the same way, but don't rely on that. markHandoff() and markDeliverable() do the same as leaveForUser().

browser.tabs.finalize() remains the explicit authoritative cleanup operation. List only tabs intentionally retained; unlisted task-owned tabs are closed even if previously marked.

await browser.tabs.finalize([
  { tab, status: "handoff" },
  { tab: reportTab, status: "deliverable" },
]);

Entries may be a Tab, tab ID, or { tab, status }/{ tabId, status }. Status must be "handoff" or "deliverable"; a bare tab defaults to "deliverable". Use await browser.tabs.finalize([]) when no task-owned tab should remain.

When you are resumed after your tabs closed, they come back by URL at your first browser command, in the same order with the same tab selected. Only their pages reload: scroll position, form input and other in-page state are gone, and handles you kept from before point at closed tabs. Get fresh ones with browser.tabs.list() or browser.tabs.selected(), then check the page before continuing.

Frozen Browser API

The public object graph is frozen. Do not mutate it or attach properties. This installed skill is the runtime reference. For lightweight discovery, inspect browser.capabilities, Object.keys(browser), Object.keys(tab), or Object.keys(locator); there is no runtime documentation command.

Browser and Tabs

Object Supported API
browser capabilities, use(backend?, { browser? }), browsers(), downloads(), chain(steps, options), tabs
browser.tabs list(), new(url?), selected(), get(id), finalize(entries?)

For a new task, call tabs.new() once and then navigate that handle with tab.goto(url). If navigation fails, reuse the same handle or inspect tabs.list(); do not loop on tabs.new() because a delayed response can otherwise create a pileup of blank tabs. Use tabs.selected() only when the user's currently selected owned tab is the target, and tabs.list() when tab choice is itself a decision.

browser.chain() is a low-level JSON action batch, limited to 100 steps. Prefer normal method calls with multiple awaits in one REPL cell because they preserve typed handles and are easier to branch and debug. Chains reject unknown actions, options, arbitrary values, and nested chains. Supported chain options are timeout (milliseconds, at most 240000), delay, waitForSelector, waitTimeout, abortOnError, returnSnapshot, and returnScreenshot; do not add delay or automatic snapshots without a concrete need.

Tab

API Notes
id Positive numeric owned-tab ID.
playwright Frozen page facade, cached for this tab.
goto(url, { waitUntil?, timeout? }) Navigate the tab.
back({ timeout? }), forward({ timeout? }), reload({ timeout? }) History navigation.
close() Close this tab.
leaveForUser(), markHandoff(), markDeliverable() Keep open for the user; never closed.
show() Bring this tab forward for the user.
url(), title() Async methods, not strings: (await tab.url()).includes(…).
snapshot(options?) Structural observation.
axSnapshot({ mode?, interactive?, compact?, maxDepth?, selector? }) AX tree, incremental; not in cloud sessions.
screenshot(options?) Pixel observation.
press(key) Page-level key press to current focus.
keyboard.type(text), keyboard.press(key) Raw text insertion / key press.
scroll(options?) Scroll page or element.
expectNewTab(action, { timeoutMs? }) Capture exactly one new owned tab.
waitForDownload(action, { timeoutMs? }) The file a download saved (Stella's browser).

Snapshot options are interactive, cursor, maxDepth (or depth), compact, and selector. Screenshot options are fullPage, selector, format ("png" or "jpeg"), quality (0-100), annotate, and path (where to save the file). Scroll options are pixel deltas x/y (negative scrolls up/left) or selector + direction + amount; prefer locator.scrollIntoViewIfNeeded() before acting on an element.

Page Facade

tab.playwright supports only this Playwright-like subset:

domSnapshot(options?)
evaluate(pageFunction, arg?)
locator(css)
getByRole(role, { name?, exact? })
getByText(text, { exact? })
getByLabel(text, { exact? })
getByPlaceholder(text, { exact? })
getByTestId(testId, { exact? })
waitForURL(url, { timeout? })
waitForTimeout(ms)
expectNewTab(action, { timeoutMs? })

This is not the full Playwright API. Locator values and URL patterns are strings; regular expressions are rejected. evaluate() accepts a function or source string. Pass external data through its JSON-serializable argument because page functions do not retain REPL closures.

Locator

Locators support:

locator(css)
filter({ hasText?, hasNotText?, has?, hasNot? })
nth(index), first(), last(), count()
click(), dblclick(), fill(value), type(text), press(key)
hover(), focus(), check(), uncheck(), setChecked(boolean)
selectOption(valueOrValues), setInputFiles(absolutePaths)
scrollIntoViewIfNeeded()
innerText(), textContent(), inputValue(), getAttribute(name)
isVisible(), isEnabled(), isChecked(), boundingBox()
evaluate(pageFunction, arg?), waitFor(options?), allTextContents()

setInputFiles requires absolute file paths and targets <input type=file>.

locator() chaining is supported only from an unfiltered CSS locator. filter({ has, hasNot }) requires same-tab CSS locators. nth() is zero-based. Semantic locators use the frozen API's small role mapping and string matching; they do not provide every Playwright accessibility behavior.

Timeouts are non-negative milliseconds and are capped at 120 seconds unless a smaller expectNewTab() limit applies. Locator actions retry transient not-found/not-actionable state for one shared three-second deadline, then add a bounded five-match diagnostic; unknown-outcome transport failures are never replayed. A low-level browser.chain() has its own overall timeout option capped at 240 seconds. Unknown option keys fail fast. A timeout error states whether its deadline was the caller's override or the runtime default and whether the request had already been dispatched; if dispatch occurred, treat the remote outcome as unknown and inspect state before retrying a mutating action.

Transport Failures

"Extension not connected" is not a transport failure; see Which Browser above. Do not fall back to shell commands or to driving a Chrome/Brave window yourself when the frozen browser API reports a bridge or transport failure. Report the exact error and park the browser-dependent step; continue only work that does not require browser access. Do not promise automatic backend recovery, retries, or stale-tab cleanup; none is part of the frozen worker API contract.

04 同仓库更多 Skills