Browser Use To Stagehand
BrowserbaseOfficialPublished by Browserbase
- Skill
- Workflow
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured methodology for porting browser-use (Python) agentic scripts to Stagehand v3 (TypeScript) on Browserbase. Rather than a direct transpilation, it emphasizes refactoring opaque agent loops into inspectable, deterministic pipelines. By applying a determinism spectrum, it helps developers replace LLM-heavy agentic steps with specific Stagehand primitives (act, extract, observe) where the page flow is predictable, reserving AI-driven agents only for genuinely open-ended tasks.
What it does
- Analyzes browser-use scripts to extract tasks, browser configurations, and custom actions.
- Maps agentic browser-use steps to Stagehand v3 primitives based on a determinism decision tree.
- Generates runnable TypeScript code using Stagehand v3 and Zod for structured data extraction.
- Provides setup templates for package.json, environment variables, and index.ts.
- Offers a trace-assisted workflow for debugging and migrating flaky or opaque agent scripts.
- Ensures best practices for secret management and browser session handling.
When to use it
- When you need to migrate an existing browser-use Python script to a more stable TypeScript environment.
- When you want to improve the reliability and speed of browser automation by reducing unnecessary LLM calls.
- When you need to move agentic workflows onto the Browserbase platform for better observability.
- When you are refactoring an opaque, flaky agent script into a maintainable, deterministic pipeline.
Advantages
- Increases automation reliability by replacing non-deterministic agent loops with predictable primitives.
- Reduces token costs and latency by using AI only where the page structure is unpredictable.
- Improves maintainability through structured, inspectable TypeScript code.
- Leverages Browserbase platform features for better session management and debugging.
Usage examples
- “Migrate my browser-use script that searches for products on Amazon and extracts prices.”
- The agent will inventory your script, identify the search and extraction steps, and provide a Stagehand v3 script using page.goto for navigation and stagehand.extract for price gathering.
- “I have a flaky browser-use agent that logs into a portal. How do I move it to Stagehand?”
- The agent will guide you through mapping the login flow to a deterministic Stagehand sequence, potentially using Browserbase context to handle authentication reliably.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/browserbase/browser-use-to-stagehand/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip browser-use-to-stagehand.zip -d .agents/skills
Documentation by Browserbase
browser-use → Stagehand on Browserbase (/browser-use-to-stagehand)
Convert a browser-use (Python) script into an idiomatic Stagehand v3 (TypeScript) script on Browserbase, choosing the right level of determinism at each step rather than producing a one-to-one agentic copy.
Core principle: browser-use is agentic-by-default (the LLM decides every action). Stagehand lets you choose how much AI to use. A good migration replaces opaque agent loops with an inspectable, mostly-deterministic pipeline — using AI only where the page is genuinely unpredictable. This is a refactor with judgment, not a transpile.
Source of truth & versions. This skill's durable value is the judgment — the determinism spectrum and the decompose-vs-agent decision — not the API specifics, which drift every release. The code mappings here are a snapshot validated against
@browserbasehq/stagehand3.6.x and browser-use 0.13.x (2026-06). On any conflict, the live docs win — always verify against the installed package and these sources before emitting code:
Stagehand v3: https://docs.stagehand.dev/v3 · installed types:
node_modules/@browserbasehq/stagehandBrowserbase: https://docs.browserbase.com
browser-use: https://docs.browser-use.com
If the installed Stagehand major is not 3, treat this skill as conceptual only and follow the live docs for every signature.
Reference files (read as needed)
references/api-mapping.md— the mechanical browser-use → Stagehand mapping: variant detection, the full feature table, before/after code, Browserbase platform options, and v3 version gotchas. Read this for any non-trivial construct.references/determinism.md— how to chooseagent()vsact/extract/observevs cachedobserve→act. The decision tree. Read this when deciding how to translate anAgent(task=…).references/trace-assisted.md— the optional "run it on Browserbase, read the logs, then rewrite" workflow for opaque/flaky scripts.references/guide.md— the human migration guide: philosophy shift, feature mapping, the determinism spectrum, and a recommended migration path.references/prompt.md— a self-contained, tool-agnostic version of this skill; paste it into any AI assistant along with a browser-use script.EXAMPLES.md— before/after script pairs.
Workflow
1. Get the source
Obtain the browser-use script(s). If the user only described a script, ask for the file(s). Note the target: TypeScript Stagehand on Browserbase unless they say otherwise.
First, gate on scope — is this even migratable? Not every browser-use file is an
Agent(task=…)script. If the source is browser-use running as an MCP server (uvx browser-use --mcp, amcpServersconfig) there is no Stagehand equivalent — flag it as out of scope, don't invent one (see api-mapping §3.7b). If the browser-use call is embedded in a larger app (a class/tool wrapper, web route, queue task), convert only the browser-use surface and preserve the surrounding app glue — see api-mapping §3.8.
2. Detect the browser-use variant
Identify legacy (pre-0.12) vs stable vs Rust beta (only when imports come from browser_use.beta)
— see api-mapping §1. Note: the classic top-level from browser_use import Agent, ChatBrowserUse
surface is alive and well in 0.13.x — ChatBrowserUse alone is not a beta tell; only a
browser_use.beta import is. All variants translate identically, so when unsure, proceed with the
stable mapping. Normalize legacy names before translating. State which variant you found.
3. Inventory the script
Extract a structured inventory before writing any TypeScript:
Task(s) — the
task=string(s); split each into its implied ordered steps.Model — the
Chat*provider + model id.Browser config — local vs
cdp_url/Browserbase; headless; proxies;user_data_dir/storage_state.Structured output — any
output_model_schemaPydantic models.Secrets —
sensitive_data, env-var usage, login flows.Guardrails —
allowed_domains,max_steps.Custom actions —
@tools.action/Controllerfunctions, and whether each is a deterministic side-effect or an agent capability.Setup —
initial_actions, secondary models (page_extraction_llm,planner_llm).
4. Decide the determinism level per step
For each step from the inventory, apply the decision tree in determinism.md:
Navigate to a known URL →
page.goto(url)on the Stagehand page (no AI).On-page action →
act("…"); if it repeats,observe()once then replayact(action)(no LLM call).Reading data →
extract("…", zodSchema).Genuinely open-ended → keep
stagehand.agent().execute(...)(tightened withmaxSteps/systemPrompt).
Default to decomposition when the flow is known; keep agent() only where it isn't. For a
first lift-and-shift, a faithful agent() translation is acceptable — say so and note the
optimization path.
5. Produce the Stagehand v3 rewrite
First, verify the API. Before writing, confirm the exact signatures you're about to use against
the installed package (node_modules/@browserbasehq/stagehand types) or https://docs.stagehand.dev/v3.
The mappings below are a 3.6.x snapshot; if anything differs in the installed version, the installed
version wins. Then emit runnable TypeScript. Always:
import { Stagehand } from "@browserbasehq/stagehand";andimport { z } from "zod";when extracting.Get the page via
const page = stagehand.context.pages()[0];.Call AI methods on the instance:
stagehand.act(...),stagehand.extract(...),stagehand.observe(...)— neverpage.act(...).Set the model as a
"provider/model"string.Default to
env: "BROWSERBASE"; showenv: "LOCAL"as the dev option.Pass secrets via
variablesandprocess.env, never hardcoded.await stagehand.init()at the start,await stagehand.close()in afinally.
Include the project setup so it runs (see the templates below).
6. Write the migration summary
Alongside the code, produce a short summary:
Variant detected and the determinism choices made (which steps became deterministic vs AI vs agent), with the reasoning.
Needs human review — anything that didn't map 1:1: lost
allowed_domainsguardrails, custom-action logic, secondary-model intent, ambiguous task strings.Recommended next step — Browserbase Context for auth reuse, caching for production, or the trace-assisted path if the flow was opaque.
7. Offer the trace-assisted path (only if warranted)
If the source was one large opaque agent(task=…), was flaky, or your rewrite can't be confidently
mapped, offer the trace-assisted workflow (trace-assisted.md): run the original on Browserbase, pull
sessions.logs.list, and rewrite from observed behavior. Don't run anything without the user's go-ahead.
Output templates
package.json
{
"name": "stagehand-migration",
"type": "module",
"scripts": { "start": "tsx index.ts" },
"dependencies": {
"@browserbasehq/stagehand": "^3.0.0",
"dotenv": "^16.0.0",
"zod": "^3.25.0"
},
"devDependencies": { "tsx": "^4.0.0", "typescript": "^5.0.0" }
}Add
"ai": "^5.0.0"(Vercel AI SDK) only if a custom browser-use action maps to an agenttool. Pin v5, not v4 — Stagehand 3.6.x bundlesaiv5 and typesagent({ tools })as the v5ToolSet, where a tool's schema field isinputSchema. The v4tool()helper emitsparametersinstead and will fail to type-check against Stagehand's v5ToolSet. If you can't control the hoistedaiversion, skip thetool()helper and pass a plain object{ description, inputSchema: zodSchema, execute }— it satisfies the v5ToolSetregardless of whichaimajor resolves.
.env
BROWSERBASE_API_KEY=...
BROWSERBASE_PROJECT_ID=...
ANTHROPIC_API_KEY=... # or the provider matching your model stringindex.ts skeleton (decomposed, the preferred shape)
import "dotenv/config";
import { Stagehand } from "@browserbasehq/stagehand";
import { z } from "zod";
async function main() {
const stagehand = new Stagehand({
env: "BROWSERBASE",
model: "anthropic/claude-sonnet-4-6",
});
await stagehand.init();
try {
const page = stagehand.context.pages()[0];
await page.goto("https://example.com"); // deterministic skeleton
await stagehand.act("…"); // AI where the page varies
const data = await stagehand.extract("…", z.object({ /* … */ })); // structured reads
console.log(data);
} finally {
await stagehand.close();
}
}
main().catch((err) => { console.error(err); process.exit(1); });Validation checklist (before declaring done)
[ ] AI methods are on the instance (
stagehand.act/extract/observe), not the page.[ ] Page obtained via
stagehand.context.pages()[0].[ ] Model is a
"provider/model"string; the matching provider key is in.env.[ ]
extractuses a zod schema;zodis in dependencies.[ ] Secrets use
variables+process.env; nothing hardcoded.[ ]
init()/close()present;close()infinally.[ ] Each browser-use step is accounted for, placed deliberately on the determinism spectrum.
[ ] Migration summary lists determinism choices and "needs human review" items.
Common mistakes to avoid
Copying v2 syntax (
page.act(),stagehand.page,modelName/modelClientOptions,enableCaching) from old blog posts. Use v3 — see api-mapping "Version notes".Translating every step into
act()— navigate withpage.gotoand cache repeatable steps viaobserve→act; don't spend an LLM call on every action.Defaulting everything to
agent()— that just reproduces browser-use's non-determinism in a new framework. Decompose where the flow is known.Silently dropping
allowed_domains— Stagehand has no domain firewall; flag it for review.Inventing Browserbase/Stagehand options — if unsure of a field, check https://docs.stagehand.dev/v3 / https://docs.browserbase.com rather than guessing.
Files
- ATTRIBUTION.mdAdded by AutoGineer918 B
- EXAMPLES.md7.1 KiB
- LICENSE.txt1.0 KiB
- SKILL.md11.2 KiB
- references/api-mapping.md24.2 KiB
- references/determinism.md7.8 KiB
- references/guide.md12.1 KiB
- references/prompt.md9.3 KiB
- references/trace-assisted.md5.7 KiB
EXAMPLES.md
Examples: browser-use → Stagehand
Before/after pairs showing the migration patterns. Each "before" is a browser-use (Python) script;
each "after" is its Stagehand v3 (TypeScript) rewrite on Browserbase. Illustrative — validate
against your real site and tighten the act(...) prompts to the actual on-page labels.
See SKILL.md for the workflow, the guide for the philosophy + feature mapping, and references/determinism.md for the decision framework.
Running an "after" example
npm install @browserbasehq/stagehand zod
npm install -D tsx dotenv.env:
BROWSERBASE_API_KEY=...
BROWSERBASE_PROJECT_ID=...
ANTHROPIC_API_KEY=... # or OPENAI_API_KEY, matching the model string in the filenpx tsx example.tsSwap env: "BROWSERBASE" for env: "LOCAL" (with Chrome installed) to run locally during dev.
1. Simple task
A fully-agentic task becomes a deterministic page.goto + one act() — no agent loop.
Before — browser-use
import asyncio
from browser_use import Agent, ChatAnthropic
async def main() -> None:
agent = Agent(
task="Go to Hacker News (news.ycombinator.com) and open the top story",
llm=ChatAnthropic(model="claude-sonnet-4-6"),
)
history = await agent.run(max_steps=20)
print(history.final_result())
if __name__ == "__main__":
asyncio.run(main())After — Stagehand v3
import "dotenv/config";
import { Stagehand } from "@browserbasehq/stagehand";
async function main() {
const stagehand = new Stagehand({
env: "BROWSERBASE", // use "LOCAL" for local dev with a real Chrome
model: "anthropic/claude-sonnet-4-6",
});
await stagehand.init();
try {
const page = stagehand.context.pages()[0];
await page.goto("https://news.ycombinator.com"); // deterministic
await stagehand.act("click the top story's title link"); // AI: markup varies
console.log("Opened:", page.url());
} finally {
await stagehand.close();
}
}
main().catch((err) => {
console.error(err);
process.exit(1);
});2. Structured extraction
A Pydantic output_model_schema becomes a zod extract() — no agent loop, just navigate then read.
Before — browser-use
import asyncio
from pydantic import BaseModel
from browser_use import Agent, ChatOpenAI
class Story(BaseModel):
title: str
points: int
comments: int
class TopStories(BaseModel):
stories: list[Story]
async def main() -> None:
agent = Agent(
task="Go to Hacker News and return the top 5 stories with title, points, and comment count",
llm=ChatOpenAI(model="gpt-5"),
output_model_schema=TopStories,
)
history = await agent.run()
data = history.structured_output # TopStories instance
for story in data.stories:
print(story.title, story.points, story.comments)
if __name__ == "__main__":
asyncio.run(main())After — Stagehand v3
import "dotenv/config";
import { Stagehand } from "@browserbasehq/stagehand";
import { z } from "zod";
async function main() {
const stagehand = new Stagehand({ env: "BROWSERBASE", model: "openai/gpt-5" });
await stagehand.init();
try {
const page = stagehand.context.pages()[0];
await page.goto("https://news.ycombinator.com");
await page.waitForLoadState("domcontentloaded"); // settle before the AI snapshot
const stories = await stagehand.extract(
"extract the top 5 stories with their title, points, and comment count",
z.array(
z.object({
title: z.string(),
points: z.number(),
comments: z.number().describe("number of comments"),
}),
),
);
for (const s of stories) console.log(s.title, s.points, s.comments);
} finally {
await stagehand.close();
}
}
main().catch((err) => {
console.error(err);
process.exit(1);
});3. Login with sensitive data
sensitive_data → variables (secrets never reach the LLM). The known form is driven with
deterministic act() steps. allowed_domains has no direct Stagehand equivalent — replace it with
a page.url() host check. For repeat runs, reuse a Browserbase Context to skip re-login.
Before — browser-use
import asyncio
import os
from browser_use import Agent, Browser, ChatAnthropic
async def main() -> None:
sensitive_data = {
"https://example.com": {
"x_user": os.environ["APP_USER"],
"x_pass": os.environ["APP_PASS"],
}
}
agent = Agent(
task="Log into example.com using username x_user and password x_pass, then open the dashboard",
llm=ChatAnthropic(model="claude-sonnet-4-6"),
sensitive_data=sensitive_data,
use_vision=False, # don't leak secrets via screenshots
browser=Browser(allowed_domains=["https://*.example.com"]),
)
await agent.run()
if __name__ == "__main__":
asyncio.run(main())After — Stagehand v3
import "dotenv/config";
import { Stagehand } from "@browserbasehq/stagehand";
async function main() {
const stagehand = new Stagehand({
env: "BROWSERBASE",
model: "anthropic/claude-sonnet-4-6",
// Reuse auth across runs with a Context:
// browserbaseSessionCreateParams: {
// projectId: process.env.BROWSERBASE_PROJECT_ID!,
// browserSettings: { context: { id: process.env.BB_CONTEXT_ID!, persist: true } },
// },
});
await stagehand.init();
try {
const page = stagehand.context.pages()[0];
await page.goto("https://example.com/login");
await stagehand.act("type %username% into the email field", {
variables: { username: process.env.APP_USER! },
});
await stagehand.act("type %password% into the password field", {
variables: { password: process.env.APP_PASS! },
});
await stagehand.act("click the sign in button");
await page.waitForLoadState("domcontentloaded");
// Best-effort stand-in for allowed_domains=["https://*.example.com"]. browser-use
// enforces the allow-list across the ENTIRE run; a host check only covers the moment
// it runs, so call it after *every* navigation — not just sign-in. For real continuous
// enforcement use Browserbase proxy domain rules (api-mapping §5); this throw is only a
// tripwire and is flagged "needs human review" in the migration summary.
const assertAllowedHost = () => {
const host = new URL(page.url()).hostname;
if (host !== "example.com" && !host.endsWith(".example.com")) {
throw new Error(`navigated off the allow-list: ${page.url()}`);
}
};
assertAllowedHost();
console.log("Logged in:", page.url());
// Second half of the task ("…then open the dashboard") — don't stop at login.
await stagehand.act("open the dashboard");
await page.waitForLoadState("domcontentloaded");
assertAllowedHost(); // re-check: the guardrail must cover this navigation too
console.log("Dashboard:", page.url());
} finally {
await stagehand.close();
}
}
main().catch((err) => {
console.error(err);
process.exit(1);
});Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Needs an MCP server, Needs an API key
The author says: The skill itself uses only Read/Write/Edit/Grep/Bash — no install step. The Stagehand code it generates needs Node 18+, `@browserbasehq/stagehand` (v3) and `zod`, plus `BROWSERBASE_API_KEY` / `BROWSERBASE_PROJECT_ID` and a model-provider key (e.g. `ANTHROPIC_API_KEY`) to run. The optional trace-assisted path uses the Browserbase SDK or the sibling `browser-trace` skill.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Browserbase
- Publisher
- Browserbase (Official)
- Source
- browserbase/skills · skills/browser-use-to-stagehand · commit 6811ca3
- Licence
- MIT License (redistribution allowed)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Browserbase or Browserbase.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download browser-use-to-stagehand.zip