browser-use-to-stagehand
browserbase/skills
Convertir los scripts de automatización del navegador (Python) a Stagehand v3 (TypeScript) en Browserbase, sustituyendo los bucles de agente opacos por flujos determinísticos siempre que sea posible.
...Expandir todobrowser-use → Stagehand en Browserbase (/browser-use-to-stagehand)
Convierte un script de browser-use (Python) en un script idiomático de Stagehand v3 (TypeScript) en Browserbase, eligiendo el nivel adecuado de determinismo en cada paso en lugar de generar una copia agente a agente.
Principio fundamental: «browser-use» es «agente» por defecto (el LLM decide cada acción). Stagehand te permite elegir en qué medida utilizar la IA. Una buena migración sustituye los bucles de agente opacos por un flujo de trabajo inspeccionable y mayoritariamente determinista, utilizando la IA solo cuando la página es realmente impredecible. Se trata de una refactorización con criterio, no de una transpilación.
Fuente de verdad y versiones. El valor duradero de esta habilidad es el criterio —el espectro de determinismo y la decisión entre descomposición y agente— y no los detalles de la API, que cambian con cada lanzamiento. Las correspondencias de código aquí presentadas son una instantánea validada con
@browserbasehq/stagehand3.6.x y browser-use 0.13.x (2026-06). En caso de conflicto, prevalecen los documentos en línea: comprueba siempre con el paquete instalado y estas fuentes antes de generar 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
Si la versión principal de Stagehand instalada no es la 3, considera esta habilidad como meramente conceptual y sigue la documentación en línea para cada firma.
Archivos de referencia (léelos según sea necesario)
references/api-mapping.md— La correspondencia mecánica entre browser-use y Stagehand: detección de variantes, la tabla completa de características, código antes y después, opciones de la plataforma Browserbase y aspectos a tener en cuenta en la versión v3. Léelo para cualquier construcción que no sea trivial.references/determinism.md— Cómo elegiragent()vsact/extract/observevs en cachéobserve→act. El árbol de decisión. Léelo a la hora de decidir cómo traducir unAgent(task=…).references/trace-assisted.md— El flujo de trabajo opcional «ejecútalo en Browserbase, lee los registros y luego reescribe» para scripts opacos o inestables.references/guide.md— La guía de migración para humanos: cambio de filosofía, correspondencia de funciones, el espectro del determinismo y una ruta de migración recomendada.references/prompt.md— una versión autónoma e independiente de herramientas de esta habilidad; pégala en cualquier asistente de IA junto con un script de uso del navegador.EXAMPLES.md— pares de scripts «antes y después».
Flujo de trabajo
1. Obtener la fuente
Consigue el script o scripts de uso del navegador. Si el usuario solo ha descrito un script, pídele los archivos. Ten en cuenta el destino: TypeScript Stagehand en Browserbase, a menos que se indique lo contrario.
En primer lugar, evalúa el alcance: ¿es siquiera migrable? No todos los archivos de uso del navegador son un
Agent(task=…)script. Si el código fuente es «browser-use» ejecutándose como un servidor MCP (uvx browser-use --mcp, unamcpServersconfiguración), no existe un equivalente en Stagehand: márcalo como fuera de alcance, no inventes uno (véase mapeo de API, apartado 3.7b). Si la llamada a «browser-use» está incrustada en una aplicación más amplia (un envoltorio de clase/herramienta, una ruta web, una tarea en cola), convierte solo la superficie de «browser-use» y conserva el código de enlace de la aplicación circundante — véase mapeo de API, apartado 3.8.
2. Detectar la variante de «browser-use»
Identifica la versión heredada (anterior a la 0.12) frente a la estable frente a la beta de Rust (solo cuando las importaciones procedan de browser_use.beta)
— véase «api-mapping», apartado 1. Nota: la superficie clásica de nivel superior from browser_use import Agent, ChatBrowserUse
sigue vigente en la versión 0.13.x — ChatBrowserUse por sí sola no indica que se trate de una beta; solo lo indica una
browser_use.beta import lo es. Todas las variantes se traducen de forma idéntica, así que, en caso de duda, procede con la
asignación estable. Normaliza los nombres heredados antes de traducir. Indica qué variante has encontrado.
3. Haz un inventario del script
Elabora un inventario estructurado antes de escribir ningún código en TypeScript:
- Tarea(s): las
task=cadena(s); divide cada una en los pasos ordenados que implica. - Modelo: el
Chat*proveedor + el ID del modelo. - Configuración del navegador: local frente a
cdp_url/Browserbase; modo sin interfaz gráfica; proxies;user_data_dir/storage_state. - Salida estructurada: cualquier
output_model_schemamodelos Pydantic. - Secretos —
sensitive_data, uso de variables de entorno, flujos de inicio de sesión. - Medidas de seguridad —
allowed_domains,max_steps. - Acciones personalizadas —
@tools.action/Controllerfunciones, y si cada una de ellas es un efecto secundario determinista o una capacidad del agente. - Configuración —
initial_actions, modelos secundarios (page_extraction_llm,planner_llm).
4. Decidir el nivel de determinismo por paso
Para cada paso del inventario, aplica el árbol de decisión de determinism.md:
- Navegar a una URL conocida →
page.goto(url)en la página de Stagehand (sin IA). - Acción en la página →
act("…"); si se repite,observe()una vez y luego volver a reproduciract(action)(sin llamada a LLM). - Lectura de datos →
extract("…", zodSchema). - Verdaderamente abierto → mantener
stagehand.agent().execute(...)(restringido conmaxSteps/systemPrompt).
Por defecto, se recurre a la descomposición cuando se conoce el flujo; mantener agent() solo cuando no lo sea. Para una
primera conversión directa, una agent() es aceptable; indícalo y señala la
ruta de optimización.
5. Realizar la reescritura de Stagehand v3
En primer lugar, verifica la API. Antes de escribir, confirma las firmas exactas que vas a utilizar comparándolas con
el paquete instalado (node_modules/@browserbasehq/stagehand tipos) o https://docs.stagehand.dev/v3.
Las correspondencias que aparecen a continuación corresponden a una instantánea de la versión 3.6.x; si hay alguna diferencia con la versión instalada, prevalecerá la
versión instalada. A continuación, genera código TypeScript ejecutable. Siempre:
import { Stagehand } from "@browserbasehq/stagehand";yimport { z } from "zod";al extraer.- Obtén la página mediante
const page = stagehand.context.pages()[0];. - Llama a los métodos de IA en la instancia:
stagehand.act(...),stagehand.extract(...),stagehand.observe(...)— nuncapage.act(...). - Establecer el modelo como una
"provider/model"cadena. - Por defecto,
env: "BROWSERBASE"; mostrarenv: "LOCAL"como opción de desarrollo. - Pasa los secretos a través de
variablesyprocess.env, nunca codificados de forma fija. await stagehand.init()al principio,await stagehand.close()en unfinally.
Incluye la configuración del proyecto para que se ejecute (consulta las plantillas más abajo).
6. Redacta el resumen de la migración
Junto con el código, elabora un breve resumen:
- Variante detectada y opciones de determinismo elegidas (qué pasos se convirtieron en determinísticos frente a IA frente a agente), con el razonamiento correspondiente.
- Requiere revisión humana: cualquier elemento que no se haya asignado 1:1: pérdida de
allowed_domainsmedidas de seguridad, lógica de acciones personalizadas, intención del modelo secundario, cadenas de tareas ambiguas. - Siguiente paso recomendado: Browserbase Context para la reutilización de la autenticación, almacenamiento en caché para producción o la ruta asistida por trazas si el flujo era opaco.
7. Ofrecer la ruta asistida por traza (solo si está justificado)
Si el código fuente era un único archivo grande y opaco agent(task=…), era inestable o tu reescritura no se puede mapear con seguridad
, ofrece el flujo de trabajo asistido por trazas (trace-assisted.md): ejecuta el original en Browserbase, extrae
sessions.logs.listy reescribe a partir del comportamiento observado. No ejecutes nada sin el visto bueno del usuario.
Plantillas de salida
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" }
}
Añade
"ai": "^5.0.0"(Vercel AI SDK) solo si una acción personalizada de uso del navegador se asigna a un agentetool. Fija la v5, no la v4: Stagehand 3.6.x incluyeaila v5 y lasagent({ tools })como la v5ToolSet, donde el campo «schema» de una herramienta esinputSchema. Eltool()emiteparametersen su lugar y no superará la comprobación de tipos con respecto a la v5 de StagehandToolSet. Si no puedes controlar la versiónai, omite eltool()ayudante y pasa un objeto simple{ description, inputSchema: zodSchema, execute }: cumple con la v5ToolSetindependientemente de cuálaiprincipal se resuelva.
.env
BROWSERBASE_API_KEY=...
BROWSERBASE_PROJECT_ID=...
ANTHROPIC_API_KEY=... # or the provider matching your model string
index.ts Esqueleto (descompuesto, la 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 comprobación de validación (antes de darlo por terminado)
- Los métodos de IA se aplican a la instancia (
stagehand.act/extract/observe), no en la página. - Página obtenida a través de
stagehand.context.pages()[0]. - Modelo es una
"provider/model"cadena de caracteres; la clave del proveedor correspondiente se encuentra en.env. -
extractutiliza un esquema Zod;zodse encuentra en «dependencies». - Los secretos utilizan
variables+process.env; nada está codificado de forma fija. -
init()/close()presentes;close()enfinally. - Se tiene en cuenta cada paso de uso del navegador, situado deliberadamente en el espectro del determinismo.
- El resumen de la migración enumera las opciones de determinismo y los elementos que «requieren revisión humana».
Errores comunes que hay que evitar
- Copiar la sintaxis de la v2 (
page.act(),stagehand.page,modelName/modelClientOptions,enableCaching) de entradas antiguas del blog. Utiliza la v3; consulta las «Notas de versión» de api-mapping. - Traducir cada paso a
act()— navegar conpage.gotoy almacena en caché los pasos repetibles medianteobserve→act; no gastes una llamada al LLM en cada acción. - Establecer todo por defecto en
agent(): eso solo reproduce el carácter no determinista del uso del navegador en un nuevo marco. Descompón el flujo cuando se conozca. - Eliminar en silencio
allowed_domains: Stagehand no tiene un cortafuegos de dominio; márcalo para su revisión. - Inventar opciones de Browserbase/Stagehand: si no estás seguro de un campo, consulta https://docs.stagehand.dev/v3 / https://docs.browserbase.com en lugar de adivinar.
---
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 los archivos
8 archivosInstalar browser-use-to-stagehand
Descarga y descomprime los archivos de habilidades en tu directorio .claude/skills/.
Descargar ZIPClona el repositorio y copia los archivos de la habilidad a tu proyecto.
git clone https://github.com/browserbase/skills/tree/main/skills/browser-use-to-stagehand # Copy SKILL.md to your .claude/skills/ directory
Copiar





Hogar
