browser-use-to-stagehand
browserbase/skills
Browserbase上で、ブラウザ操作(Python)用の自動化スクリプトをStagehand v3(TypeScript)に移植し、可能な限り不透明なエージェントループを決定論的なパイプラインに置き換える。
...すべて拡張しますbrowser-use → Browserbase上のStagehand (/browser-use-to-stagehand)
browser-use(Python)スクリプトを、Browserbase上のStagehand v3(TypeScript)の慣用的なスクリプトに変換します。 この際、1対1のエージェンティックなコピーを生成するのではなく、各ステップで適切な決定論のレベルを選択します。
基本原則:browser-useはデフォルトでエージェント型(すべてのアクションをLLMが決定する)です。Stagehand では、AIをどの程度活用するかを選択できます。 優れた移行とは、不透明なエージェントループを、 検証可能で、ほぼ決定論的なパイプラインに置き換えることです。AIは、ページが真に 予測不可能な場合にのみ使用します。これは単なるトランスパイルではなく、判断を伴うリファクタリングです。
真実の源とバージョン。このスキルの永続的な価値は、判断力――決定論の スペクトルや「分解かエージェントか」という決定――にあり、リリースごとに変化するAPIの詳細にはありません。 ここにあるコードのマッピングは、
@browserbasehq/stagehand3.6.x および browser-use 0.13.x (2026-06) に対して検証されたスナップショットです。矛盾がある場合は、ライブドキュメントが優先されます。コードを出力する前に、必ず インストール済みのパッケージと以下のソースに対して検証を行ってください:
- Stagehand v3: https://docs.stagehand.dev/v3 · インストール済みタイプ:
node_modules/@browserbasehq/stagehand- Browserbase: https://docs.browserbase.com
- browser-use: https://docs.browser-use.com
インストールされている Stagehand のメジャーバージョンが 3 でない場合は、このスキルを概念的なものとして扱い、すべてのシグネチャについて ライブドキュメントに従ってください。
参考資料(必要に応じて参照)
references/api-mapping.md— 機械的な browser-use → Stagehand のマッピング:バリアントの検出、完全な機能一覧、変更前後のコード、Browserbase プラットフォームの オプション、および v3 バージョンの注意点。複雑な構文についてはこれを参照してください。references/determinism.md— 選択方法agent()vsact/extract/observevs キャッシュ済みobserve→act。決定木。Agent(task=…)の変換方法を決定する際に これを参照してください。references/trace-assisted.md— 不透明または不安定なスクリプト向けの、オプションの「Browserbaseで実行し、 ログを確認してから書き直す」というワークフロー。references/guide.md— 人間向け移行ガイド:考え方の転換、 機能のマッピング、決定論のスペクトル、および推奨される移行パス。references/prompt.md— このスキルの、 独立したツール非依存版。ブラウザ使用スクリプトと共に、任意のAIアシスタントに貼り付けてください。EXAMPLES.md— スクリプトの「移行前/移行後」のペア。
ワークフロー
1. ソースを入手する
ブラウザ使用スクリプトを入手します。ユーザーがスクリプトについてのみ説明している場合は、ファイルを要求してください。 ターゲットに注意:特に指定がない限り、Browserbase上のTypeScript Stagehandとします。
まず、適用範囲を確認します — そもそも移行可能でしょうか?すべてのブラウザ使用ファイルが
Agent(task=…)スクリプトとは限りません。ソースがMCP サーバーとして実行されているbrowser-use (uvx browser-use --mcp、mcpServersconfig)として動作している場合、Stagehandに相当するものは存在しません。この場合は 対象外としてマークし、無理に作成しないでください(api-mapping §3.7bを参照)。 browser-useの呼び出しが より大規模なアプリ(クラス/ツールラッパー、Webルート、キュータスク)に埋め込まれている場合は、browser-useのインターフェース部分のみを変換し、 周囲のアプリ間の結合部分はそのまま残してください — api-mapping §3.8を参照してください。
2. browser-useのバリエーションを特定する
レガシー(0.12以前)と安定版、およびRustベータ版(インポート元が browser_use.beta)
— api-mapping §1を参照。注:従来のトップレベル from browser_use import Agent, ChatBrowserUse
インターフェースは0.13.xでも健在です — ChatBrowserUse それだけではベータ版であるとは判断できません。
browser_use.beta のみがベータ版であることを示します。すべてのバリエーションは同一に翻訳されるため、不確かな場合は
安定版のマッピングで進めてください。翻訳前にレガシー名を正規化してください。どのバリエーションが見つかったかを明記してください。
3. スクリプトのインベントリ作成
TypeScriptを記述する前に、構造化されたタスク一覧を作成してください:
- タスク —
task=文字列;それぞれを、そこに含まれる順序付きの手順に分割してください。 - モデル —
Chat*プロバイダー + モデル ID。 - ブラウザの設定 — ローカル vs
cdp_url/Browserbase; ヘッドレス; プロキシ;user_data_dir/storage_state. - 構造化出力 — 任意の
output_model_schemaPydanticモデル。 - シークレット —
sensitive_data、環境変数の使用、ログインフロー。 - ガードレール —
allowed_domains,max_steps. - カスタムアクション —
@tools.action/Controller関数、およびそれぞれが決定論的な 副作用であるか、エージェントの機能であるか。 - セットアップ —
initial_actions、二次モデル(page_extraction_llm,planner_llm).
4. 各ステップごとの決定論レベルを決定する
インベントリに記載された各ステップについて、determinism.md の決定木を適用する:
- 既知のURLへ移動 →
page.goto(url)Stagehandページ上で(AIを使用せず)。 - ページ上のアクション →
act("…"); 繰り返す場合は、observe()1回だけ実行し、その後リプレイact(action)(LLM呼び出しなし)。 - データの読み取り →
extract("…", zodSchema). - 真に自由形式 → 維持
stagehand.agent().execute(...)(以下で厳密化:maxSteps/systemPrompt).
フローが判明している場合はデフォルトで分解を行う;そうでない場合のみ維持 agent() 流れが不明な場合のみ適用。
最初のリフト・アンド・シフトにおいては、忠実な agent() 変換であれば許容される — その旨を明記し、
最適化の道筋を記載する。
5. Stagehand v3のリライトを作成する
まず、API を確認します。記述を始める前に、使用しようとしている正確なシグネチャを、
インストール済みのパッケージ(node_modules/@browserbasehq/stagehand types)またはhttps://docs.stagehand.dev/v3に対して、使用する正確なシグネチャを確認すること。
以下のマッピングは3.6.xのスナップショットである。インストール済みのバージョンで差異がある場合は、インストール済みの
バージョンを優先する。その後、実行可能なTypeScriptを生成する。常に:
import { Stagehand } from "@browserbasehq/stagehand";を適用し、import { z } from "zod";を必ず使用してください。- ページを取得するには
const page = stagehand.context.pages()[0];. - インスタンスに対してAIメソッドを呼び出します:
stagehand.act(...),stagehand.extract(...),stagehand.observe(...)— 決してpage.act(...). - モデルを
"provider/model"文字列として設定します。 - デフォルトは
env: "BROWSERBASE"; 開発オプションとしてenv: "LOCAL"をデベロッパーオプションとして表示する。 - シークレットは
variablesおよびprocess.envを使用してシークレットを渡すようにし、決してハードコーディングしないこと。 await stagehand.init()の先頭で、await stagehand.close()でfinally.
プロジェクトが実行されるようセットアップを含めてください(以下のテンプレートを参照)。
6. マイグレーションの概要を作成する
コードとともに、以下の短い要約を作成してください:
- 検出したバリアントと、決定論の選択内容(どのステップが決定論的になったか、AIか、エージェントか)、およびその根拠。
- 人間によるレビューが必要 — 1対1でマッピングされなかったもの:失われた
allowed_domainsガードレール、 カスタムアクションのロジック、セカンダリモデルの意図、曖昧なタスク文字列。 - 推奨される次のステップ — 認証の再利用のためのBrowserbaseコンテキスト、本番環境向けのキャッシュ、または フローが不透明だった場合のトレース支援パス。
7. トレース支援パスを提案する(正当な理由がある場合のみ)
ソースが1つの巨大で不透明な agent(task=…)で不安定な場合、または書き換えを確実に
マッピングできない場合は、トレース支援型ワークフロー(trace-assisted.md)を提案する:Browserbase上でオリジナルを実行し、
sessions.logs.list、観測された挙動に基づいて書き換えます。ユーザーの承認なしに何も実行しないでください。
出力テンプレート
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" }
}
以下の場合にのみ
"ai": "^5.0.0"(Vercel AI SDK)は、カスタムブラウザ使用アクションがエージェントにマッピングされている場合にのみ追加してくださいtoolにマッピングされる場合にのみ追加してください。v4ではなくv5を指定してください — Stagehand 3.6.xにはaiv5をバンドルしており、タイプはagent({ tools })をv5としてToolSetとしてバンドルされており、ツールのスキーマフィールドはinputSchemaです。v4のtool()ヘルパーはparametersを生成し、Stagehandのv5ToolSetに対する型チェックに失敗します。もし 持ち上げられたaiバージョンを制御できない場合は、tool()ヘルパーをスキップし、プレーンなオブジェクトを{ description, inputSchema: zodSchema, execute }を渡してください。これなら、v5のToolSetを満たしますaiメジャーが解決されても、v5の要件を満たします。
.env
BROWSERBASE_API_KEY=...
BROWSERBASE_PROJECT_ID=...
ANTHROPIC_API_KEY=... # or the provider matching your model string
index.ts スケルトン(分解された、推奨される形式)
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); });
検証チェックリスト(完了と宣言する前)
- AI手法はインスタンス(
stagehand.act/extract/observe)にあり、ページ上にはない。 - ページは以下を通じて取得されます
stagehand.context.pages()[0]. - Modelは
"provider/model"文字列です。対応するプロバイダーキーは.env. -
extractはzodスキーマを使用しています;zodは依存関係に含まれています。 - シークレットは
variables+process.envを使用します。ハードコーディングされたものはありません。 -
init()/close()存在します;close()infinally. - 各ブラウザ使用ステップが考慮されており、決定論のスペクトラム上で意図的に位置づけられています。
- 移行の概要には、決定論に関する選択肢と「人的レビューが必要」な項目が記載されています。
避けるべきよくある間違い
- v2の構文(
page.act(),stagehand.page,modelName/modelClientOptions,enableCaching)を古いブログ記事からコピーすること。v3を使用してください — api-mappingの「バージョンノート」を参照してください。 - すべてのステップを
act()に変換すること — ナビゲーションにはpage.gotoを使用してナビゲートし、observe→actを使用して繰り返し可能なステップをキャッシュしてください。すべてのアクションごとにLLM呼び出しを行わないでください。 - すべてを
agent()にデフォルト設定する — それは単に、ブラウザ利用時の非決定性を 新しいフレームワークに再現するだけです。フローが分かっている箇所は分解してください。 allowed_domainsを黙って破棄する — Stagehandにはドメインファイアウォールがないため、レビュー対象としてフラグを立てる。- Browserbase/Stagehandのオプションを独自に考案する — フィールドについて確信が持てない場合は、 推測するのではなく、https://docs.stagehand.dev/v3 / https://docs.browserbase.com を確認してください。
---
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.
すべてのファイル
8件のファイルbrowser-use-to-stagehandをインストール
スキルファイルをダウンロードし、.claude/skills/ ディレクトリに解凍してください。
ZIPをダウンロードリポジトリをクローンし、スキルファイルをプロジェクトにコピーしてください。
git clone https://github.com/browserbase/skills/tree/main/skills/browser-use-to-stagehand # Copy SKILL.md to your .claude/skills/ directory
コピー





家
