browser-use-to-stagehand
browserbase/skills
Converter scripts de automação de navegador (Python) para o Stagehand v3 (TypeScript) no Browserbase, substituindo loops de agente opacos por pipelines determinísticos sempre que possível.
...Expandir tudobrowser-use → Stagehand no Browserbase (/browser-use-to-stagehand)
Converta um script do browser-use (Python) em um script idiomático do Stagehand v3 (TypeScript) no Browserbase, escolhendo o nível certo de determinismo em cada etapa, em vez de produzir uma cópia agente a agente.
Princípio fundamental: o browser-use é baseado em agentes por padrão (o LLM decide todas as ações). O Stagehand permite que você escolha o nível de IA a ser utilizado. Uma boa migração substitui loops de agente opacos por um fluxo inspecionável e predominantemente determinístico — utilizando IA apenas onde a página é genuinamente imprevisível. Trata-se de uma refatoração com discernimento, não de uma transpilagem.
Fonte de verdade e versões. O valor duradouro dessa habilidade está no discernimento — o espectro de determinismo e a decisão entre decomposição e agente — e não nos detalhes da API, que mudam a cada lançamento. Os mapeamentos de código aqui apresentados são um instantâneo validado contra o
@browserbasehq/stagehand3.6.x e o browser-use 0.13.x (2026-06). Em caso de conflito, a documentação atualizada prevalece — sempre verifique em relação ao pacote instalado e a estas fontes antes de gerar código:
- Stagehand v3: https://docs.stagehand.dev/v3 · tipos instalados:
node_modules/@browserbasehq/stagehand- Browserbase: https://docs.browserbase.com
- browser-use: https://docs.browser-use.com
Se a versão principal do Stagehand instalado não for 3, considere esta habilidade apenas conceitual e siga a documentação online para cada assinatura.
Arquivos de referência (leia conforme necessário)
references/api-mapping.md— o mapeamento mecânico do browser-use → Stagehand : detecção de variantes, a tabela completa de recursos, código antes/depois, opções da plataforma Browserbase e armadilhas da versão v3. Leia isso para qualquer construção não trivial.references/determinism.md— como escolheragent()vsact/extract/observevs em cacheobserve→act. A árvore de decisão. Leia isso ao decidir como traduzir umAgent(task=…).references/trace-assisted.md— o fluxo de trabalho opcional “execute no Browserbase, leia os logs e, em seguida, reescreva” para scripts opacos/instáveis.references/guide.md— o guia de migração para humanos: mudança de filosofia, mapeamento de recursos, o espectro do determinismo e um caminho de migração recomendado.references/prompt.md— uma versão autônoma e independente de ferramentas dessa habilidade; cole-a em qualquer assistente de IA junto com um script de uso do navegador.EXAMPLES.md— pares de scripts “antes” e “depois”.
Fluxo de trabalho
1. Obtenha a fonte
Obtenha o(s) script(s) de uso do navegador. Se o usuário tiver descrito apenas um script, peça o(s) arquivo(s). Anote o destino: TypeScript Stagehand no Browserbase, a menos que seja indicado o contrário.
Primeiro, avalie o escopo — isso é mesmo migrável? Nem todo arquivo de uso do navegador é um
Agent(task=…)script. Se a fonte for o browser-use rodando como um servidor MCP (uvx browser-use --mcp, umamcpServersconfig), não há equivalente no Stagehand — marque-o como fora do escopo, não invente um (consulte mapeamento de API §3.7b). Se a chamada do `browser-use` estiver incorporada em um aplicativo maior (um wrapper de classe/ferramenta, rota web, tarefa em fila), converta apenas a superfície do `browser-use` e preserve a integração com o aplicativo ao redor — consulte o mapeamento de API §3.8.
2. Detecte a variante do uso do navegador
Identifique a versão legada (pré-0.12) versus a estável versus a beta do Rust (somente quando as importações vierem de browser_use.beta)
— consulte api-mapping §1. Observação: a superfície clássica de nível superior from browser_use import Agent, ChatBrowserUse
continua ativa e funcionando na versão 0.13.x — ChatBrowserUse por si só não é um indicador de versão beta; apenas uma
browser_use.beta import é. Todas as variantes são traduzidas de forma idêntica; portanto, em caso de dúvida, proceda com o
mapeamento estável. Normalize os nomes legados antes de traduzir. Indique qual variante você encontrou.
3. Faça um inventário do script
Extraia um inventário estruturado antes de escrever qualquer TypeScript:
- Tarefa(s) — as
task=string(s); divida cada uma em suas etapas ordenadas implícitas. - Modelo — o
Chat*provedor + ID do modelo. - Configuração do navegador — local vs
cdp_url/Browserbase; modo headless; proxies;user_data_dir/storage_state. - Saída estruturada — quaisquer
output_model_schemamodelos Pydantic. - Segredos —
sensitive_data, uso de variáveis de ambiente, fluxos de login. - Medidas de segurança —
allowed_domains,max_steps. - Ações personalizadas —
@tools.action/Controllerfunções e se cada uma delas é um efeito colateral determinístico ou uma capacidade do agente. - Configuração —
initial_actions, modelos secundários (page_extraction_llm,planner_llm).
4. Decida o nível de determinismo por etapa
Para cada etapa do inventário, aplique a árvore de decisão em determinism.md:
- Navegar para uma URL conhecida →
page.goto(url)na página Stagehand (sem IA). - Ação na página →
act("…"); se se repetir,observe()uma vez, repitaact(action)(sem chamada de LLM). - Leitura de dados →
extract("…", zodSchema). - Genuinamente aberto → manter
stagehand.agent().execute(...)(aprimorado commaxSteps/systemPrompt).
Padrão para decomposição quando o fluxo é conhecido; manter agent() apenas quando não for. Para um
primeiro “lift-and-shift”, uma agent() tradução é aceitável — indique isso e anote o
caminho de otimização.
5. Produza a reescrita do Stagehand v3
Primeiro, verifique a API. Antes de escrever, confirme as assinaturas exatas que você está prestes a usar em relação ao
pacote instalado (node_modules/@browserbasehq/stagehand tipos) ou https://docs.stagehand.dev/v3.
Os mapeamentos abaixo são um instantâneo da versão 3.6.x; se houver alguma diferença na versão instalada, a versão instalada
prevalece. Em seguida, gere um código TypeScript executável. Sempre:
import { Stagehand } from "@browserbasehq/stagehand";eimport { z } from "zod";ao extrair.- Obtenha a página por meio de
const page = stagehand.context.pages()[0];. - Chame métodos de IA na instância:
stagehand.act(...),stagehand.extract(...),stagehand.observe(...)— nuncapage.act(...). - Defina o modelo como uma
"provider/model"string. - O padrão é
env: "BROWSERBASE"; exibirenv: "LOCAL"como opção de desenvolvimento. - Passe segredos via
variableseprocess.env, nunca codificados diretamente. await stagehand.init()no início,await stagehand.close()em umfinally.
Inclua a configuração do projeto para que ele seja executado (veja os modelos abaixo).
6. Escreva o resumo da migração
Juntamente com o código, elabore um breve resumo:
- Variante detectada e as escolhas de determinismo feitas (quais etapas se tornaram determinísticas vs. IA vs. agente), com o raciocínio.
- Requer revisão humana — qualquer coisa que não tenha sido mapeada 1:1: perda de
allowed_domainsbarreiras de segurança, lógica de ação personalizada, intenção do modelo secundário, sequências de tarefas ambíguas. - Próximo passo recomendado — Browserbase Context para reutilização de autenticação, armazenamento em cache para produção ou o caminho assistido por rastreamento, caso o fluxo tenha sido opaco.
7. Ofereça o caminho assistido por rastreamento (somente se justificado)
Se a fonte for um único código grande e opaco agent(task=…), instável ou se sua reescrita não puder ser mapeada com confiança
, ofereça o fluxo de trabalho assistido por rastreamento (trace-assisted.md): execute o original no Browserbase, extraia
sessions.logs.liste reescreva com base no comportamento observado. Não execute nada sem a autorização do usuário.
Modelos de saída
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" }
}
Adicione
"ai": "^5.0.0"(Vercel AI SDK) somente se uma ação personalizada de uso do navegador corresponder a um agentetool. Fixe a v5, não a v4 — o Stagehand 3.6.x incluiaia v5 e classificaagent({ tools })como a v5ToolSet, em que o campo de esquema de uma ferramenta éinputSchema. Otool()emiteparametersem vez disso e falhará na verificação de tipos em relação ao v5 do StagehandToolSet. Se você não puder controlar a versãoai, ignore otool()auxiliar e passe um objeto simples{ description, inputSchema: zodSchema, execute }— ele atende à v5ToolSet, independentemente de qualaiprincipal for resolvido.
.env
BROWSERBASE_API_KEY=...
BROWSERBASE_PROJECT_ID=...
ANTHROPIC_API_KEY=... # or the provider matching your model string
index.ts Esqueleto (decomposto, a forma preferida)
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); });
Lista de verificação de validação (antes de declarar concluído)
- Os métodos de IA estão na instância (
stagehand.act/extract/observe), e não na página. - Página obtida por meio de
stagehand.context.pages()[0]. - Modelo é uma
"provider/model"string; a chave do provedor correspondente está em.env. -
extractusa um esquema Zod;zodestá nas dependências. - Os segredos utilizam
variables+process.env; nada codificado estaticamente. -
init()/close()presente;close()emfinally. - Cada etapa de uso do navegador é considerada, posicionada deliberadamente no espectro do determinismo.
- O resumo da migração lista as opções de determinismo e os itens que “precisam de revisão humana”.
Erros comuns a evitar
- Copiar a sintaxe da v2 (
page.act(),stagehand.page,modelName/modelClientOptions,enableCaching) de posts antigos do blog. Use a v3 — consulte as “Notas de versão” do mapeamento de API. - Traduzir cada etapa para “
act()” — navegue compage.gotoe armazene em cache as etapas repetíveis por meio deobserve→act; não gaste uma chamada ao LLM em cada ação. - Definir tudo como padrão em
agent()— isso apenas reproduz o não determinismo do uso do navegador em uma nova estrutura. Decomponha onde o fluxo for conhecido. - Descartar silenciosamente o `
allowed_domains` — o Stagehand não possui firewall de domínio; sinalize para revisão. - Inventar opções do Browserbase/Stagehand — se não tiver certeza sobre um campo, verifique https://docs.stagehand.dev/v3 / https://docs.browserbase.com em vez de adivinhar.
---
name: browser-use-to-stagehand
description: Convert browser-use (Python) browser-automation scripts to Stagehand v3 (TypeScript) on Browserbase, replacing opaque agent loops with deterministic pipelines where possible.
license: MIT
---
# 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/stagehand` 3.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/stagehand`
> - Browserbase: <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`](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`](references/determinism.md) — how to choose `agent()` vs
`act`/`extract`/`observe` vs cached `observe`→`act`. The decision tree. **Read this when deciding
how to translate an `Agent(task=…)`.**
- [`references/trace-assisted.md`](references/trace-assisted.md) — the optional "run it on
Browserbase, read the logs, then rewrite" workflow for opaque/flaky scripts.
- [`references/guide.md`](references/guide.md) — the human migration guide: philosophy shift,
feature mapping, the determinism spectrum, and a recommended migration path.
- [`references/prompt.md`](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`](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`, a `mcpServers` config) 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_schema` Pydantic models.
- **Secrets** — `sensitive_data`, env-var usage, login flows.
- **Guardrails** — `allowed_domains`, `max_steps`.
- **Custom actions** — `@tools.action` / `Controller` functions, 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 replay `act(action)` (no LLM call).
- Reading data → `extract("…", zodSchema)`.
- Genuinely open-ended → keep `stagehand.agent().execute(...)` (tightened with `maxSteps`/`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";` and `import { 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(...)` — **never** `page.act(...)`.
- Set the model as a `"provider/model"` string.
- Default to `env: "BROWSERBASE"`; show `env: "LOCAL"` as the dev option.
- Pass secrets via `variables` and `process.env`, never hardcoded.
- `await stagehand.init()` at the start, `await stagehand.close()` in a `finally`.
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_domains` guardrails,
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`**
```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 agent
> `tool`. **Pin v5, not v4** — Stagehand 3.6.x bundles `ai` v5 and types `agent({ tools })` as the v5
> `ToolSet`, where a tool's schema field is **`inputSchema`**. The v4 `tool()` helper emits
> `parameters` instead and will **fail to type-check** against Stagehand's v5 `ToolSet`. If you can't
> control the hoisted `ai` version, skip the `tool()` helper and pass a plain object
> `{ description, inputSchema: zodSchema, execute }` — it satisfies the v5 `ToolSet` regardless of which
> `ai` major resolves.
**`.env`**
```bash
BROWSERBASE_API_KEY=...
BROWSERBASE_PROJECT_ID=...
ANTHROPIC_API_KEY=... # or the provider matching your model string
```
**`index.ts` skeleton** (decomposed, the preferred shape)
```typescript
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`.
- [ ] `extract` uses a zod schema; `zod` is in dependencies.
- [ ] Secrets use `variables` + `process.env`; nothing hardcoded.
- [ ] `init()` / `close()` present; `close()` in `finally`.
- [ ] 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 with `page.goto` and cache repeatable steps via `observe`→`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.
Todos os arquivos
8 arquivosInstalar browser-use-to-stagehand
Baixe e descompacte os arquivos de habilidades no diretório .claude/skills/.
Baixar ZIPClone o repositório e copie os arquivos da habilidade para o seu projeto.
git clone https://github.com/browserbase/skills/tree/main/skills/browser-use-to-stagehand # Copy SKILL.md to your .claude/skills/ directory
Copiar





Lar
