From dae7e0881a0258dca5379fd4776cfacc4bb5ba88 Mon Sep 17 00:00:00 2001 From: junhsss Date: Sat, 7 Nov 2026 19:24:45 +0900 Subject: [PATCH] chore: bump cookbook version --- content/docs/cookbook/agentkit.mdx | 10 +- content/docs/cookbook/agno.mdx | 8 +- content/docs/cookbook/auth-context.mdx | 22 ++-- content/docs/cookbook/authors/nibzard.mdx | 3 +- .../cookbook/browser-use-captcha-auto.mdx | 10 +- .../cookbook/browser-use-captcha-manual.mdx | 10 +- content/docs/cookbook/browser-use.mdx | 10 +- content/docs/cookbook/chromedp.mdx | 12 +-- content/docs/cookbook/chromiumoxide.mdx | 9 +- content/docs/cookbook/claude-agent-sdk.mdx | 12 +-- .../cookbook/claude-computer-use-mobile.mdx | 8 +- content/docs/cookbook/claude-computer-use.mdx | 43 ++++---- .../docs/cookbook/convex-chat-with-page.mdx | 10 +- content/docs/cookbook/convex-price-watch.mdx | 6 +- content/docs/cookbook/credentials.mdx | 34 +++--- content/docs/cookbook/crewai.mdx | 8 +- content/docs/cookbook/deep-research.mdx | 12 +-- content/docs/cookbook/eino.mdx | 16 +-- content/docs/cookbook/extensions.mdx | 20 ++-- content/docs/cookbook/files.mdx | 39 +++---- content/docs/cookbook/gemini-computer-use.mdx | 18 ++-- content/docs/cookbook/genkit.mdx | 10 +- content/docs/cookbook/google-adk.mdx | 10 +- content/docs/cookbook/headless-chrome.mdx | 8 +- content/docs/cookbook/index.mdx | 13 +++ content/docs/cookbook/langchaingo.mdx | 16 +-- content/docs/cookbook/langgraph.mdx | 8 +- content/docs/cookbook/magnitude.mdx | 8 +- content/docs/cookbook/mastra.mdx | 8 +- content/docs/cookbook/mcp.mdx | 28 +++-- content/docs/cookbook/meta.json | 7 -- .../cookbook/microsoft-agent-framework.mdx | 8 +- content/docs/cookbook/notte.mdx | 10 +- content/docs/cookbook/openai-agents.mdx | 8 +- content/docs/cookbook/openai-computer-use.mdx | 32 +++--- content/docs/cookbook/playwright.mdx | 20 ++-- content/docs/cookbook/profiles.mdx | 18 ++-- content/docs/cookbook/puppeteer.mdx | 6 +- content/docs/cookbook/pydantic-ai.mdx | 8 +- content/docs/cookbook/restate-agent.mdx | 14 +-- content/docs/cookbook/rig.mdx | 10 +- content/docs/cookbook/rod.mdx | 29 ++--- content/docs/cookbook/scrape.mdx | 53 ++++----- content/docs/cookbook/selenium.mdx | 6 +- content/docs/cookbook/stagehand.mdx | 8 +- .../cookbook/stripe-projects-web-agent.mdx | 102 ++++++++++++++++++ content/docs/cookbook/swiftide.mdx | 25 +++-- .../cookbook/temporal-browser-workflow.mdx | 12 +-- content/docs/cookbook/topics/agents.mdx | 1 + .../cookbook/topics/browser-automation.mdx | 6 -- content/docs/cookbook/topics/browser-use.mdx | 4 - content/docs/cookbook/topics/captchas.mdx | 7 +- content/docs/cookbook/topics/computer-use.mdx | 6 -- content/docs/cookbook/topics/mobile.mdx | 4 - content/docs/cookbook/topics/nextjs.mdx | 1 + content/docs/cookbook/topics/playwright.mdx | 4 - content/docs/cookbook/topics/subagents.mdx | 4 - content/docs/cookbook/topics/typed-output.mdx | 6 -- .../docs/cookbook/trigger-dev-browser-job.mdx | 8 +- .../docs/cookbook/vercel-ai-sdk-nextjs.mdx | 8 +- content/docs/cookbook/vercel-ai-sdk.mdx | 6 +- content/docs/cookbook/you-com-search.mdx | 14 +-- cookbook.lock.json | 2 +- 63 files changed, 482 insertions(+), 404 deletions(-) create mode 100644 content/docs/cookbook/stripe-projects-web-agent.mdx diff --git a/content/docs/cookbook/agentkit.mdx b/content/docs/cookbook/agentkit.mdx index 9cae0b2c..1ef23f58 100644 --- a/content/docs/cookbook/agentkit.mdx +++ b/content/docs/cookbook/agentkit.mdx @@ -3,15 +3,15 @@ title: Build a browser agent with Inngest AgentKit description: "Integrate Steel with Inngest's AgentKit framework." --- - + - + -Agent Kit is Inngest's framework for [multi-agent systems](/cookbook/topics/agents): a **tool** is a typed function the model can call, an **agent** bundles a system prompt with a tool set, and a **network** groups agents so they can collaborate on a task. Agent Kit handles the routing between them and wraps each call in Inngest's `step.run` checkpoint, so a network that crashes mid-flight resumes from the last finished step. +Agent Kit is Inngest's framework for multi-agent systems: a **tool** is a typed function the model can call, an **agent** bundles a system prompt with a tool set, and a **network** groups agents so they can collaborate on a task. Agent Kit handles the routing between them and wraps each call in Inngest's `step.run` checkpoint, so a network that crashes mid-flight resumes from the last finished step. -This starter wires Agent Kit to Steel through a single tool, `browse_hacker_news`, that opens a Steel session, drives it with Playwright over CDP, and returns structured rows. The [Inngest AgentKit integration](/integrations/agentkit) covers install and configuration. +This starter wires Agent Kit to Steel through a single tool, `browse_hacker_news`, that opens a Steel session, drives it with Playwright over CDP, and returns structured rows. ```typescript const browseHackerNews = createTool({ @@ -116,7 +116,7 @@ A run lands in the ~20-40 second range. ## Related recipes + - diff --git a/content/docs/cookbook/agno.mdx b/content/docs/cookbook/agno.mdx index 7545aaac..212b0d5d 100644 --- a/content/docs/cookbook/agno.mdx +++ b/content/docs/cookbook/agno.mdx @@ -3,15 +3,15 @@ title: Build a browser agent with Agno description: Integrate Steel with the Agno agent framework. --- - + - + Agno's primitive is `Agent(model=..., tools=[...])`. Tools are typed Python methods grouped into a `Toolkit` subclass; docstrings and type hints become the JSON schema the model sees. -This recipe wraps a Steel browser in a `SteelTools` toolkit, hands it to an Agent, and lets the model drive the session by picking which method to call and filling in arguments on its own. The [Agno integration](/integrations/agno) covers install and configuration. +This recipe wraps a Steel browser in a `SteelTools` toolkit, hands it to an Agent, and lets the model drive the session by picking which method to call and filling in arguments on its own. ```python tools = SteelTools(api_key=STEEL_API_KEY) @@ -77,7 +77,7 @@ The `finally` block in `main()` calls `tools.close_session()`, which releases th ## Related recipes + - diff --git a/content/docs/cookbook/auth-context.mdx b/content/docs/cookbook/auth-context.mdx index d3ab0a6b..c9dd890b 100644 --- a/content/docs/cookbook/auth-context.mdx +++ b/content/docs/cookbook/auth-context.mdx @@ -3,13 +3,13 @@ title: Reuse authenticated sessions across browsers description: Maintain authenticated sessions across Steel browser instances by capturing and reusing cookies and local storage. --- - + - + @@ -79,7 +79,7 @@ Auth context fits one-shot flows where you already have a way to log in and just - Run an agent that signs in, snapshot at the end, hand the snapshot to the next agent in the pipeline. - Keep a single "warm" context in memory and spawn short-lived workers from it. -If you want Steel to store credentials and handle the login itself, see [credentials](/cookbook/credentials). If you need a long-lived named identity that accumulates state across runs (history, extensions, preferences), that's a different primitive. The [authentication topic](/cookbook/topics/authentication) collects the related recipes. +If you want Steel to store credentials and handle the login itself, see [credentials](/cookbook/credentials). If you need a long-lived named identity that accumulates state across runs (history, extensions, preferences), that's a different primitive. ## Make it yours @@ -95,7 +95,7 @@ If you want Steel to store credentials and handle the login itself, see [credent - + @@ -165,7 +165,7 @@ A run takes about 20 seconds and costs a few cents of session time. Both session - + @@ -181,7 +181,7 @@ One detail matters in Rust that the dynamic SDKs hide: the snapshot you read bac 2. Read the snapshot with `client.sessions().context(&session.id)`, then release session #1. 3. Map the read snapshot into a `SessionCreateParamsSessionContext`, create session #2 with `session_context` set, connect, and call `verify_auth` again without logging in. -Each chromiumoxide connection spawns a handler task (`tokio::spawn`) to pump CDP events and `handle.abort()`s it before the session is released. The cookie map copies `name` and `value` (the required fields) plus the optional `domain`, `path`, `expires`, `http_only`, `secure`, `same_site`, `priority`, `source_scheme`, `url`, and `session` directly, since those types are shared between the read and write cookie structs; only `partition_key` is dropped. The `local_storage` and `session_storage` maps move across unchanged. +Each chromiumoxide connection spawns a handler task (`tokio::spawn`) to pump CDP events and `handle.abort()`s it before the session is released. The cookie map copies `name` and `value` (the required fields) plus the optional `domain`, `path`, `expires`, `http_only`, `secure`, `url`, and `session` directly. `same_site`, `priority`, and `source_scheme` are separate enums on each side, so `to_write_same_site`, `to_write_priority`, and `to_write_source_scheme` map them variant by variant; only `partition_key` is dropped. The `local_storage` and `session_storage` maps move across unchanged. ## Run it @@ -223,7 +223,7 @@ A run takes ~20 seconds. Both sessions go through `client.sessions().release(... - + @@ -234,8 +234,8 @@ A Steel session can hand you a snapshot of its browser state: cookies, localStor captured, _ := client.Sessions.Context(ctx, first.ID) // Restore them into a brand new session #2 -second, _ := client.Sessions.Create(ctx, steel.SessionCreateParams{ - SessionContext: restoreContext(captured), +second, _ := client.Sessions.New(ctx, steel.SessionNewParams{ + SessionContext: steel.F(restoreContext(captured)), }) ``` @@ -243,9 +243,9 @@ second, _ := client.Sessions.Create(ctx, steel.SessionCreateParams{ ## The read type is not the write type -This is the one sharp edge in the Go SDK. `Sessions.Context` returns a `*steel.SessionContext` with plain Go values: `Cookies []steel.SessionContextCookie`, `LocalStorage map[string]map[string]string`, and so on. The create side wants a `steel.SessionCreateParamsSessionContext`, where every field is wrapped in `param.Field[...]` and built with `steel.F(...)`. So you cannot pass the captured value straight back in: you read concrete values and you write wrapped ones. +This is the one sharp edge in the Go SDK. `Sessions.Context` returns a `*steel.SessionContext` with plain Go values: `Cookies []steel.SessionContextCookie`, `LocalStorage map[string]map[string]string`, and so on. The create side wants a `steel.SessionNewParamsSessionContext`, where every field is wrapped in `param.Field[...]` and built with `steel.F(...)`. So you cannot pass the captured value straight back in: you read concrete values and you write wrapped ones. -`restoreContext` does that bridge. It rebuilds each cookie into a `steel.SessionCreateParamsSessionContextCookie`, wrapping `Name`, `Value`, `Domain`, `Path`, `Expires`, `HTTPOnly`, and `Secure` with `steel.F`. The `SameSite` enum is the same named type on both sides (`CreateSessionRequestSessionContextCookiesItemSameSite`), so it just gets wrapped, not converted. `LocalStorage` and `SessionStorage` are the same map type on each side and pass through `steel.F` unchanged. If you only need cookies for your target site, you can skip storage entirely. +`restoreContext` does that bridge. It rebuilds each cookie into a `steel.SessionNewParamsSessionContextCookie`, wrapping `Name`, `Value`, `Domain`, `Path`, `Expires`, `HTTPOnly`, and `Secure` with `steel.F`. The `SameSite` enum is a different named type on each side (`SessionContextCookieSameSite` on the read, `SessionNewParamsSessionContextCookieSameSite` on the write), so it gets a type conversion before `steel.F` wraps it. `LocalStorage` and `SessionStorage` are the same map type on each side and pass through `steel.F` unchanged. If you only need cookies for your target site, you can skip storage entirely. ## Run it diff --git a/content/docs/cookbook/authors/nibzard.mdx b/content/docs/cookbook/authors/nibzard.mdx index 64690e0c..48be13a6 100644 --- a/content/docs/cookbook/authors/nibzard.mdx +++ b/content/docs/cookbook/authors/nibzard.mdx @@ -1,12 +1,13 @@ --- title: Nikola Balic -description: 3 recipes contributed to the Steel Cookbook by Nikola Balic. +description: 4 recipes contributed to the Steel Cookbook by Nikola Balic. llm: false --- + diff --git a/content/docs/cookbook/browser-use-captcha-auto.mdx b/content/docs/cookbook/browser-use-captcha-auto.mdx index f39e845c..7e326cdc 100644 --- a/content/docs/cookbook/browser-use-captcha-auto.mdx +++ b/content/docs/cookbook/browser-use-captcha-auto.mdx @@ -3,13 +3,13 @@ title: Solve CAPTCHAs automatically in a Browser Use agent description: Build an AI agent with browser-use and Steel that solves CAPTCHAs automatically. --- - + - + -Steel can solve [CAPTCHAs](/cookbook/topics/captchas) inside a session without the agent lifting a finger. This recipe wires that into Browser Use: one flag at session creation, one custom tool the agent calls to block until the solver reports done. Everything else is the same perception-plan-act loop as the base [Browser Use](/cookbook/browser-use) recipe. +Steel can solve CAPTCHAs inside a session without the agent lifting a finger. This recipe wires that into Browser Use: one flag at session creation, one custom tool the agent calls to block until the solver reports done. Everything else is the same perception-plan-act loop as the base [Browser Use](/cookbook/browser-use) recipe. ```python session = client.sessions.create(solve_captcha=True) @@ -85,7 +85,7 @@ A run usually finishes in under a minute: a few cents of Steel session time plus ## Make it yours -- **Point at a real target.** Replace the `TASK` string with the actual flow: "sign up at example.com with these details." Keep the instruction to call `wait_for_captcha_solution` when a CAPTCHA appears; everything else, the agent figures out. +- **Point at a real target.** Replace the `TASK` string with the actual flow: "sign up at example.com with these details". Keep the instruction to call `wait_for_captcha_solution` when a CAPTCHA appears; everything else, the agent figures out. - **Tune the poll loop.** `wait_for_captcha_solution` uses `timeout_ms=60000` and `poll_interval_ms=1000`. Image grids and audio fallbacks sometimes need 90-120 seconds. A 2-3 second poll cuts API calls without noticeable delay. - **Fail loud on solver failure.** The current summary counts `failed` tasks but the tool does not short-circuit on them. Check `summary["failed_tasks"] > 0` inside the loop and return an error string so the agent can retry or abort. - **Combine with stealth.** `sessions.create()` accepts `use_proxy=True` and `session_timeout=1800000` alongside `solve_captcha=True`. Sites that CAPTCHA you aggressively usually want all three. @@ -101,5 +101,5 @@ A run usually finishes in under a minute: a few cents of Steel session time plus - + diff --git a/content/docs/cookbook/browser-use-captcha-manual.mdx b/content/docs/cookbook/browser-use-captcha-manual.mdx index a71d5d22..6dc5ebad 100644 --- a/content/docs/cookbook/browser-use-captcha-manual.mdx +++ b/content/docs/cookbook/browser-use-captcha-manual.mdx @@ -3,17 +3,17 @@ title: Solve reCAPTCHA v2 manually with Browser Use description: "Manually solve reCAPTCHA v2 using Steel's CAPTCHA API with the browser-use framework." --- - + - + -Steel can solve [CAPTCHAs](/cookbook/topics/captchas) for you in the background, or it can hand you the status API and let you drive. This recipe picks the second path. The session is created with auto-solving explicitly off, a custom Browser Use tool polls `client.sessions.captchas.status()`, and it calls `client.sessions.captchas.solve()` only for the CAPTCHA type you care about. Every state transition (detected, solving, validating, solved) is yours to read and react to. +Steel can solve CAPTCHAs for you in the background, or it can hand you the status API and let you drive. This recipe picks the second path. The session is created with auto-solving explicitly off, a custom Browser Use tool polls `client.sessions.captchas.status()`, and it calls `client.sessions.captchas.solve()` only for the CAPTCHA type you care about. Every state transition (detected, solving, validating, solved) is yours to read and react to. ```python session = client.sessions.create( - timeout=300000, + api_timeout=300000, solve_captcha=True, stealth_config={"auto_captcha_solving": False}, ) @@ -139,5 +139,5 @@ A run takes ~60 seconds and costs Steel session time plus OpenAI tokens for each - + diff --git a/content/docs/cookbook/browser-use.mdx b/content/docs/cookbook/browser-use.mdx index d58dbdd8..d5d9f928 100644 --- a/content/docs/cookbook/browser-use.mdx +++ b/content/docs/cookbook/browser-use.mdx @@ -3,13 +3,13 @@ title: Build a browser agent with Browser Use description: Integrate Steel with the browser-use framework for AI-driven web automation. --- - + - + -[Browser Use](/cookbook/topics/browser-use) is an agent framework: you give it an LLM, a browser, and a natural-language `task`, and it runs a perception-plan-act loop until the task is done. It doesn't need selectors or scripted steps. The model reads the page, decides the next action, and executes it against the browser you give it. The browser in this recipe is a Steel session, so the agent runs on managed cloud Chrome with stealth, proxies, and a live viewer instead of local Chromium. The [Browser Use integration](/integrations/browser-use) covers install and setup. +Browser Use is an agent framework: you give it an LLM, a browser, and a natural-language `task`, and it runs a perception-plan-act loop until the task is done. It doesn't need selectors or scripted steps. The model reads the page, decides the next action, and executes it against the browser you give it. The browser in this recipe is a Steel session, so the agent runs on managed cloud Chrome with stealth, proxies, and a live viewer instead of local Chromium. ```python session = client.sessions.create() @@ -62,7 +62,7 @@ A run costs a few cents of Steel session time plus OpenAI tokens for each step t ## Make it yours -- **Change the task.** Set `TASK` in `.env` or edit the default in `main.py`. Any sentence works: "log in to example.com and download the latest invoice PDF," "compare prices for the top 3 vacuum cleaners on Amazon," "fill out the contact form at acme.com with these fields." Long tasks are fine; the agent breaks them into steps on its own. +- **Change the task.** Set `TASK` in `.env` or edit the default in `main.py`. Any sentence works: "log in to example.com and download the latest invoice PDF", "compare prices for the top 3 vacuum cleaners on Amazon", "fill out the contact form at acme.com with these fields". Long tasks are fine; the agent breaks them into steps on its own. - **Turn on stealth.** Add `use_proxy=True`, `solve_captcha=True`, or `session_timeout=1800000` to the `sessions.create()` call for sites with anti-bot. Tasks that navigate logged-in areas usually need longer timeouts than the 5-minute default. - **Swap the model.** `ChatOpenAI(model="gpt-5", ...)` is the default; Browser Use also ships `ChatAnthropic`, `ChatGoogle`, and others. Change the import and the `model` arg passed to `Agent`. - **Persist login.** Reuse cookies and local storage across runs via [credentials](/cookbook/credentials) so the agent doesn't have to sign in every time. @@ -76,5 +76,5 @@ A run costs a few cents of Steel session time plus OpenAI tokens for each step t - + diff --git a/content/docs/cookbook/chromedp.mdx b/content/docs/cookbook/chromedp.mdx index 069b58f9..573591ba 100644 --- a/content/docs/cookbook/chromedp.mdx +++ b/content/docs/cookbook/chromedp.mdx @@ -3,13 +3,13 @@ title: Automate a cloud browser with chromedp description: Use Steel with chromedp to connect over CDP, navigate to Hacker News, extract the top stories, and capture a screenshot. --- - + - + -chromedp speaks the Chrome DevTools Protocol over a WebSocket and never shells out to a local Chrome. A Steel session exposes exactly that WebSocket, so `chromedp.NewRemoteAllocator` points at the remote browser and every `chromedp.Run` step executes in the cloud, behind Steel's stealth, proxies, and live viewer. No browser on your machine, just the same [browser automation](/cookbook/topics/browser-automation) over CDP the other driver recipes use. +chromedp speaks the Chrome DevTools Protocol over a websocket and never shells out to a local Chrome. A Steel session exposes exactly that websocket, so `chromedp.NewRemoteAllocator` points at the remote browser and every `chromedp.Run` step executes in the cloud, behind Steel's stealth, proxies, and live viewer. No browser on your machine. ```go cdpURL := fmt.Sprintf("%s&apiKey=%s", sess.WebsocketURL, apiKey) @@ -21,7 +21,7 @@ browserCtx, cancelBrowser := chromedp.NewContext(allocCtx) defer cancelBrowser() ``` -`NoModifyURL` is the one detail that matters here. By default chromedp probes `/json/version` and rewrites the WebSocket it gets back. Steel already hands you the exact browser endpoint with its auth query string attached, so rewriting it breaks the connection. The flag tells chromedp to dial the URL verbatim. +`NoModifyURL` is the one detail that matters here. By default chromedp probes `/json/version` and rewrites the websocket it gets back. Steel already hands you the exact browser endpoint with its auth query string attached, so rewriting it breaks the connection. The flag tells chromedp to dial the URL verbatim. After that it is plain chromedp. `run` builds one task list and ships it in a single `chromedp.Run`: navigate, wait for the story rows, pull data out, screenshot. @@ -74,12 +74,12 @@ A run costs a few cents of browser time. Steel bills per session-minute, so the - **Swap the target.** Change the `chromedp.Navigate` URL, the `WaitVisible` selector, and the `extractTopStories` script. Session setup and cleanup stay identical. The JSON-string bridge works for any shape: define a matching Go struct and unmarshal. - **Add steps.** chromedp tasks compose, so append `chromedp.Click`, `chromedp.SendKeys`, or `chromedp.SetValue` to the `Run` list to fill forms or paginate before you extract. -- **Turn on stealth.** `SessionCreateParams` takes pointers like `BlockAds`, `SolveCaptcha`, and `UseProxy` for sites with anti-bot, plus `Timeout` to extend the session past five minutes. Set the field to the address of a value (`v := true; params.BlockAds = &v`) since they are all optional. +- **Turn on stealth.** `SessionNewParams` takes fields like `BlockAds`, `SolveCaptcha`, and `UseProxy` for sites with anti-bot, plus `Timeout` to extend the session past five minutes. They are all optional, so wrap each value with `steel.F` (`BlockAds: steel.F(true)`). `UseProxy` is typed `any`, so it takes `steel.F[any](true)`. - **Tune the screenshot.** `FullScreenshot` captures the whole scroll height at the given JPEG quality (0 to 100). Swap it for `chromedp.CaptureScreenshot` to grab only the viewport. ## Related -[Playwright version](/cookbook/playwright) and [Python Playwright](/cookbook/playwright) connect over CDP the same way with a different driver. [Rod](/cookbook/rod) is the other Go option, with a fluent page API instead of a task list. chromedp's own [examples](https://github.com/chromedp/chromedp/tree/master/examples) cover clicks, downloads, and network interception. +[Playwright version](/cookbook/playwright) and [Python Playwright](/cookbook/playwright) connect over CDP the same way with a different driver. [Rod](/cookbook/rod) is the other Go option, with a fluent page API instead of a task list. chromedp's own [examples](https://github.com/chromedp/examples) cover clicks, downloads, and network interception. ## Related recipes diff --git a/content/docs/cookbook/chromiumoxide.mdx b/content/docs/cookbook/chromiumoxide.mdx index 65eb0b28..786a99c9 100644 --- a/content/docs/cookbook/chromiumoxide.mdx +++ b/content/docs/cookbook/chromiumoxide.mdx @@ -3,20 +3,20 @@ title: Automate a cloud browser with chromiumoxide description: Use Steel with chromiumoxide to connect over CDP, drive the handler task, extract page content, and capture a screenshot. --- - + - + -chromiumoxide speaks the Chrome DevTools Protocol over a WebSocket, which is exactly what a Steel session exposes. `Browser::connect` takes the session's WebSocket URL and hands back a connected browser plus a `Handler`. From there you get plain async chromiumoxide: `new_page`, `content`, `get_title`, `find_elements`, `evaluate`, `screenshot`. No local Chrome, no `chromedriver`, no display, just [browser automation](/cookbook/topics/browser-automation) over CDP against a cloud browser. +chromiumoxide speaks the Chrome DevTools Protocol over a websocket, which is exactly what a Steel session exposes. `Browser::connect` takes the session's websocket URL and hands back a connected browser plus a `Handler`. From there you get plain async chromiumoxide: `new_page`, `content`, `get_title`, `find_elements`, `evaluate`, `screenshot`. No local Chrome, no `chromedriver`, no display. The connection is one line, but it returns a tuple, and the second half is the part that trips everyone up: ```rust let (browser, mut handler) = Browser::connect(cdp_url).await?; -let handle = tokio::spawn(async move { while let Some(_) = handler.next().await {} }); +let handle = tokio::spawn(async move { while handler.next().await.is_some() {} }); ``` chromiumoxide splits the API surface (`browser`, `page`) from the connection's event loop (`handler`). The `browser` handle only queues CDP commands. Nothing is sent, and no response ever comes back, until something polls `handler` to completion. If you skip the spawn, `browser.new_page(...)` does not error: it hangs forever, because the future that would resolve it is never driven. This is the single most common chromiumoxide mistake. Spawn the drain loop right after `connect`, keep the `JoinHandle`, and abort it on the way out. `run` does exactly that. @@ -85,7 +85,6 @@ A run costs a few cents of browser time. Steel bills per session-minute, so the ## Related - [scrape-rs](/cookbook/scrape) reaches the same page without a browser library, through Steel's `scrape` and `screenshot` endpoints. Start there if you only need content or an image and never touch the DOM. -- [Selenium](/cookbook/selenium) drives Steel over WebDriver instead of CDP. - [playwright-py](/cookbook/playwright) is the same connect-over-CDP shape in Python, useful for comparing the handler model against Playwright's. - [chromiumoxide docs](https://docs.rs/chromiumoxide) cover the `Page`, `Element`, and `ScreenshotParams` APIs in full. diff --git a/content/docs/cookbook/claude-agent-sdk.mdx b/content/docs/cookbook/claude-agent-sdk.mdx index 81581290..0b2eb689 100644 --- a/content/docs/cookbook/claude-agent-sdk.mdx +++ b/content/docs/cookbook/claude-agent-sdk.mdx @@ -3,19 +3,19 @@ title: Build a browser agent with the Claude Agent SDK description: "Use Steel with the Claude Agent SDK (TypeScript) to build a tool-using browser agent on Anthropic's first-party agent loop." --- - + - + -`@anthropic-ai/claude-agent-sdk` is the engine behind the Claude Code CLI, exposed as a Node library. You get the CLI's [agent loop](/cookbook/topics/agents), hooks, subagents, MCP support, and built-in tool catalog (`Read`, `Edit`, `Bash`, `Grep`, ...) without spawning the CLI yourself. +`@anthropic-ai/claude-agent-sdk` is the engine behind the Claude Code CLI, exposed as a Node library. You get the CLI's agent loop, hooks, subagents, MCP support, and built-in tool catalog (`Read`, `Edit`, `Bash`, `Grep`, ...) without spawning the CLI yourself. -This recipe disables those built-ins and attaches a Steel cloud browser instead; the [Claude Agent SDK integration](/integrations/claude-agent-sdk) covers install and setup. Four MCP tools (`openSession`, `navigate`, `snapshot`, `extract`) sit in front of Playwright; the agent calls them by name and streams back typed messages. +This recipe disables those built-ins and attaches a Steel cloud browser instead. Four MCP tools (`openSession`, `navigate`, `snapshot`, `extract`) sit in front of Playwright; the agent calls them by name and streams back typed messages. ```typescript const navigate = tool( @@ -120,7 +120,7 @@ A run takes ~25 to 45 seconds and 3 to 6 turns. Cost is Steel session-minutes pl - + @@ -232,7 +232,7 @@ A run takes ~30 to 50 seconds and 3 to 6 turns. Cost is Steel session-minutes pl ## Related recipes + - diff --git a/content/docs/cookbook/claude-computer-use-mobile.mdx b/content/docs/cookbook/claude-computer-use-mobile.mdx index 5ddd6243..62732464 100644 --- a/content/docs/cookbook/claude-computer-use-mobile.mdx +++ b/content/docs/cookbook/claude-computer-use-mobile.mdx @@ -3,13 +3,13 @@ title: Drive a mobile browser with Claude Computer Use description: Claude Computer Use with Steel for autonomous task execution in mobile browser environments. --- - + - + -Mobile-emulated Chrome, driven by Claude's computer-use tool. The agent loop is the same as the [Desktop TS](/cookbook/claude-computer-use) recipe (screenshot in, coordinate out, next screenshot back), but three things change when the surface is a [phone](/cookbook/topics/mobile): Steel allocates the viewport instead of you, Playwright drives the page over CDP instead of Steel's Input API, and every coordinate is clamped before it touches the browser. The [Claude Computer Use integration](/integrations/claude-computer-use) covers the base setup. +Mobile-emulated Chrome, driven by Claude's computer-use tool. The agent loop is the same as the [Desktop TS](/cookbook/claude-computer-use) recipe (screenshot in, coordinate out, next screenshot back), but three things change when the surface is a phone: Steel allocates the viewport instead of you, Playwright drives the page over CDP instead of Steel's Input API, and every coordinate is clamped before it touches the browser. ## Mobile session, Playwright driver @@ -17,7 +17,7 @@ Mobile-emulated Chrome, driven by Claude's computer-use tool. The agent loop is ```typescript this.session = await this.client.sessions.create({ - apiTimeout: 900000, + timeout: 900000, solveCaptcha: false, deviceConfig: { device: "mobile" }, }); diff --git a/content/docs/cookbook/claude-computer-use.mdx b/content/docs/cookbook/claude-computer-use.mdx index 0a492ac0..5fca0fd6 100644 --- a/content/docs/cookbook/claude-computer-use.mdx +++ b/content/docs/cookbook/claude-computer-use.mdx @@ -3,17 +3,17 @@ title: Drive a browser with Claude Computer Use description: Connect Claude to a Steel browser session for autonomous web interactions. --- - + - + -Claude sees the screen as an image and returns concrete actions at pixel coordinates: `left_click [640, 412]`, `type "claude 4.7 opus"`, `scroll down 3`. Something has to execute those actions against a real browser and send the next screenshot back. That "something" is the agent loop in `index.ts`, and the browser is a Steel session. The [Claude Computer Use integration](/integrations/claude-computer-use) covers install and setup. +Claude sees the screen as an image and returns concrete actions at pixel coordinates: `left_click [640, 412]`, `type "claude 4.7 opus"`, `scroll down 3`. Something has to execute those actions against a real browser and send the next screenshot back. That "something" is the agent loop in `index.ts`, and the browser is a Steel session. ## The loop @@ -31,7 +31,7 @@ const response = await this.client.beta.messages.create({ The tool definition declares `computer_20251124` with the viewport's `display_width_px` and `display_height_px`. Keep it consistent with the Steel session's `dimensions` (1280x768 here) or clicks land in the wrong place. -`executeComputerAction` is the translation layer. Claude emits [computer-use actions](/cookbook/topics/computer-use) (`left_click`, `type`, `key`, `scroll`, `screenshot`, ...); Steel's Input API speaks a parallel vocabulary (`click_mouse`, `type_text`, `press_key`, `scroll`, `take_screenshot`): +`executeComputerAction` is the translation layer. Claude emits computer-use actions (`left_click`, `type`, `key`, `scroll`, `screenshot`, ...); Steel's Input API speaks a parallel vocabulary (`click_mouse`, `type_text`, `press_key`, `scroll`, `take_screenshot`): ```typescript case "left_click": @@ -118,7 +118,7 @@ Expect ~60-120 seconds and 15-40 iterations for a simple browsing task. - + @@ -236,13 +236,13 @@ A run typically takes 60-180 seconds and 10-30 loop iterations. - + There is no first-party Anthropic SDK for Rust, so the Messages API here is exactly what it is on the wire: one `POST https://api.anthropic.com/v1/messages` with `reqwest`, three headers, and a JSON body you assemble yourself. That turns out to be an advantage for computer use. The request body is dynamic (a growing transcript of text, `tool_use`, and screenshot `tool_result` blocks), so you build it with `serde_json::json!`; the response shape is fixed, so you decode it into a typed `enum`. The half that benefits from types gets them, the half that does not stays loose. -The other half of the loop is the browser. A Steel session is a headful Chromium in a VM, and `client.sessions().computer(&id, action)` runs one mouse or keyboard action server-side and returns a base64 PNG in the same call. The `steel` crate models the action set as a `SessionComputerParams` enum, so the actions you send Steel are fully typed even though the actions you receive from Claude arrive as untyped JSON. +The other half of the loop is the browser. A Steel session is a headful Chromium in a VM, and `client.sessions().computer(&id, action)` runs one mouse or keyboard action server-side and returns a base64 PNG in the same call. The `steel-rs` crate models the action set as a `SessionComputerParams` enum, so the actions you send Steel are fully typed even though the actions you receive from Claude arrive as untyped JSON. ## Two type boundaries @@ -267,7 +267,7 @@ Going the other direction, `execute_computer_action` reads that loose `input` an ```rust "left_click" | "right_click" | "middle_click" | "double_click" | "triple_click" => { - SessionComputerParams::ClickMouse(ComputerActionRequestClickMouse { + SessionComputerParams::ClickMouse(SessionComputerParamsClickMouse { button: Some(button), coordinates: Some(vec![coords.0, coords.1]), num_clicks, @@ -355,33 +355,32 @@ Expect 60 to 180 seconds and 10 to 30 iterations for a simple browse, plus Anthr - + -Two typed unions meet in this recipe. Claude's Beta Messages API returns a `computer` tool call (`left_click` at `[640, 412]`, `type "claude opus"`, `scroll down 3`); Steel's Sessions Computer endpoint accepts a discriminated union of actions (`click_mouse`, `type_text`, `scroll`) and returns a screenshot. `main.go` is the agent loop that translates one into the other and feeds the screenshot back, using the official `anthropic-sdk-go` and `steel-go` SDKs end to end with no hand-rolled HTTP. +Two typed unions meet in this recipe. Claude's Beta Messages API returns a `computer` tool call (`left_click` at `[640, 412]`, `type "claude opus"`, `scroll down 3`); Steel's Sessions Computer endpoint accepts a discriminated union of actions (`click_mouse`, `type_text`, `scroll`) and returns a screenshot. `main.go` is the agent loop that translates one into the other and feeds the screenshot back, using the official `anthropic-sdk-go` and `github.com/steel-dev/sdk/go` SDKs end to end with no hand-rolled HTTP. A Steel session is a headful Chromium in a VM. The Computer endpoint (`client.Sessions.Computer`) runs a mouse or keyboard action server-side and, when you pass `Screenshot: true`, returns a base64 PNG in the same call. So one round-trip both acts and observes. ## Constructing a Steel action -Steel models its action request as a tagged union. In Go that is `SessionComputerParams`: a discriminator `Action` plus one pointer field per variant, all marshaled by the SDK based on the tag. You set the string and the matching struct, and leave the rest nil: +Steel models its action request as a tagged union. In Go that is `SessionComputerParams`, whose `Body` field takes exactly one of the `SessionComputerParamsBody*` variant structs. Each variant carries its own `Action` constant, which the SDK sends as the tag, so you build the struct and hand it over: ```go -req := &steel.ComputerActionRequestClickMouse{ - Action: "click_mouse", - Button: &button, - Coordinates: &coords, - Screenshot: ptr(true), +req := steel.SessionComputerParamsBodyClickMouse{ + Action: steel.F(steel.SessionComputerParamsBodyClickMouseActionClickMouse), + Button: steel.F(button), + Coordinates: steel.F(coords), + Screenshot: steel.F(true), } -resp, err := a.steelClient.Sessions.Computer(ctx, a.session.ID, - steel.SessionComputerParams{Action: "click_mouse", ComputerActionRequestClickMouse: req}) -img := resp.Base64Image // *string, base64 PNG +resp, err := a.steelClient.Sessions.Computer(ctx, a.session.ID, steel.SessionComputerParams{Body: req}) +img := resp.Base64Image // string, base64 PNG ``` -`executeComputerAction` is one big `switch` over Claude's action names that builds the right variant for each: `left_click` and friends become a `ComputerActionRequestClickMouse` (with `NumClicks` 2 or 3 for double and triple), `type` becomes `ComputerActionRequestTypeText`, `scroll` becomes a `ComputerActionRequestScroll` with pixel deltas. Two translation details carry over from the Python and TypeScript versions: `scroll_amount` is multiplied by 100 pixels per step, and key names like `CTRL+A` run through `normalizeKey` (`CTRL` to `Control`, `ESC` to `Escape`, `UP` to `ArrowUp`) before they reach `press_key`. +`executeComputerAction` is one big `switch` over Claude's action names that builds the right variant for each: `left_click` and friends become a `SessionComputerParamsBodyClickMouse` (with `NumClicks` 2 or 3 for double and triple), `type` becomes `SessionComputerParamsBodyTypeText`, `scroll` becomes a `SessionComputerParamsBodyScroll` with pixel deltas. Two translation details carry over from the Python and TypeScript versions: `scroll_amount` is multiplied by 100 pixels per step, and key names like `CTRL+A` run through `normalizeKey` (`CTRL` to `Control`, `ESC` to `Escape`, `UP` to `ArrowUp`) before they reach `press_key`. -Most coordinate and key fields on these structs are pointers (`*[]float64`, `*bool`), so the `ptr` generic helper near the top of the file keeps the construction readable. +Every field on these structs is a `param.Field`, so each value goes in through `steel.F`, and a field you never set, such as `HoldKeys` when Claude sends no modifier, stays out of the request. ## Reading Claude's turn @@ -464,7 +463,7 @@ Expect roughly 60 to 180 seconds and 10 to 40 loop iterations for a simple brows - **Tune the viewport.** `viewportWidth` and `viewportHeight` set both the Steel `Dimensions` and the tool's `display_*_px`. Keep them equal. - **Rework the system prompt.** `browserSystemPrompt` is where the browsing conventions live: date injection, the screenshot-after-submit rule, black-screen recovery. - **Raise the ceiling.** `maxIterations` is the safety net for long tasks. -- **Hand off auth.** Pass `SessionContext` to `Sessions.Create` to start authenticated. See [credentials](/cookbook/credentials) and [auth-context](/cookbook/auth-context). +- **Hand off auth.** Pass `SessionContext` to `Sessions.New` to start authenticated. See [credentials](/cookbook/credentials) and [auth-context](/cookbook/auth-context). ## Related diff --git a/content/docs/cookbook/convex-chat-with-page.mdx b/content/docs/cookbook/convex-chat-with-page.mdx index 8e7df7fc..02713dfb 100644 --- a/content/docs/cookbook/convex-chat-with-page.mdx +++ b/content/docs/cookbook/convex-chat-with-page.mdx @@ -3,13 +3,13 @@ title: Chat with any webpage on Convex description: "Convex app that streams an AI agent's answer about any URL. The agent runs server-side with one Steel-backed scrape tool and pages through long articles via a chunked cache." --- - + - + -A [Convex](/cookbook/topics/convex) app where the user pastes a URL, asks a question, and an [AI agent](/cookbook/topics/agents) answers from the live page. The agent runs server-side as a `pageAgent` defined in `convex/agent.ts`, with a single tool, `scrapePage`, that fetches the URL through the `@steel-dev/convex` component and serves the markdown back in chunks. Tokens stream into the UI over WebSockets via `@convex-dev/agent`'s delta sync. +A Convex app where the user pastes a URL, asks a question, and an AI agent answers from the live page. The agent runs server-side as a `pageAgent` defined in `convex/agent.ts`, with a single tool, `scrapePage`, that fetches the URL through the `@steel-dev/convex` component and serves the markdown back in chunks. Tokens stream into the UI over websockets via `@convex-dev/agent`'s delta sync. ``` convex/ @@ -98,7 +98,7 @@ The result is then chunked at paragraph boundaries into ~25k-character pieces (` - **Plug in real auth.** `ownerId` is a single string. Replace the hardcoded `alice` / `bob` toggle in `App.tsx` with the user id from Clerk, WorkOS, or your auth provider, and the app becomes multi-tenant against real users. - **Add login walls.** Compose with the [`credentials`](/cookbook/credentials) recipe to log in to a real account before scraping, and the [`profiles`](/cookbook/profiles) recipe to keep cookies across sessions. -- **Solve CAPTCHAs in-session.** Steel's `solveCaptcha` flag handles the common challenges. Pass it through `commandArgs` on `steel.steel.scrape`. +- **Solve captchas in-session.** Steel's `solveCaptcha` flag handles the common challenges. Pass it through `commandArgs` on `steel.steel.scrape`. - **Swap models.** `openai.chat("gpt-5.4-mini")` is one line in `convex/agent.ts`. Any `@ai-sdk/openai` model that supports tool calls works. - **Adjust the cache TTL.** `CACHE_TTL_MS` is 10 minutes in `scrape.ts`. Lower for fast-moving content, raise for static articles. @@ -111,7 +111,7 @@ The result is then chunked at paragraph boundaries into ~25k-character pieces (` ## Related recipes + - diff --git a/content/docs/cookbook/convex-price-watch.mdx b/content/docs/cookbook/convex-price-watch.mdx index c4badbac..a237ae1c 100644 --- a/content/docs/cookbook/convex-price-watch.mdx +++ b/content/docs/cookbook/convex-price-watch.mdx @@ -3,13 +3,13 @@ title: Watch Claude pricing for divergent A/B variants description: Convex cron plus two parallel Steel proxy probes against claude.com/pricing. Stores per-tier per-region snapshots and surfaces tiers where the probes disagree. --- - + - + -A scheduled monitor: scrape `https://claude.com/pricing` every 10 minutes from two parallel proxy probes, store one row per (region, tier, capturedAt) in [Convex](/cookbook/topics/convex), and surface tiers where the probes disagree. No LLM, no streaming. Just `@steel-dev/convex`, a cron, and a reactive dashboard. +A scheduled monitor: scrape `https://claude.com/pricing` every 10 minutes from two parallel proxy probes, store one row per (region, tier, capturedAt) in Convex, and surface tiers where the probes disagree. No LLM, no streaming. Just `@steel-dev/convex`, a cron, and a reactive dashboard. ``` convex/ diff --git a/content/docs/cookbook/credentials.mdx b/content/docs/cookbook/credentials.mdx index 35efe02f..b6fd45d3 100644 --- a/content/docs/cookbook/credentials.mdx +++ b/content/docs/cookbook/credentials.mdx @@ -3,17 +3,17 @@ title: Automate logins with the Credentials API description: Use the Steel Credentials API with Playwright to automate flows with stored credentials. --- - + - + -Steel's credentials vault stores usernames and passwords against an origin. When a session opts in, Steel watches for login forms on that origin and fills them for you. No login code in your automation, no plaintext passwords in env vars, no custom storage for cookies. It's one of Steel's [authentication](/cookbook/topics/authentication) primitives. +Steel's credentials vault stores usernames and passwords against an origin. When a session opts in, Steel watches for login forms on that origin and fills them for you. No login code in your automation, no plaintext passwords in env vars, no custom storage for cookies. Two API calls wire it up. First, save the credential once: @@ -102,7 +102,7 @@ Reach for credentials when you want a stable, long-lived setup tied to an accoun - + @@ -180,7 +180,7 @@ Both persist a login across runs, by different means. Credentials stores a usern - + @@ -190,7 +190,7 @@ This recipe wires it up with two SDK calls, then connects [chromiumoxide](https: ## How it fits together -`main` stores the credential once with `client.credentials().create(...)`. Credentials are per-origin, so a re-run hits "Credential already exists"; the recipe matches that text on the returned `steel::Error` and continues, which keeps the script idempotent: +`main` stores the credential once with `client.credentials().create(...)`. Credentials are per-origin, so a re-run hits "Credential already exists"; the recipe matches that text on the returned `steel_rs::Error` and continues, which keeps the script idempotent: ```rust match create { @@ -206,12 +206,12 @@ The opt-in is a default `SessionCreateParamsCredentials` on session create. Pres ```rust client.sessions().create(SessionCreateParams { - credentials: Some(Box::new(SessionCreateParamsCredentials::default())), + credentials: Some(SessionCreateParamsCredentials::default()), ..Default::default() }).await? ``` -From there it is ordinary chromiumoxide: open the Altoro Mutual login page and poll the username field (`#uid`) until Steel injects the vaulted value, which is the proof the fill landed. With the default `auto_submit` Steel also submits the form, so the filled field is only briefly visible — polling catches it as soon as it appears. The test site currently serves an expired certificate, so the page first sends `SetIgnoreCertificateErrorsParams`; drop that for a site with a valid certificate. +From there it is ordinary chromiumoxide: open the Altoro Mutual login page and poll the username field (`#uid`) until Steel injects the vaulted value, which is the proof the fill landed. With the default `auto_submit` Steel also submits the form, so the filled field is only briefly visible. Polling catches it as soon as it appears. The test site currently serves an expired certificate, so the page first sends `SetIgnoreCertificateErrorsParams`; drop that for a site with a valid certificate. ## Run it @@ -254,7 +254,7 @@ On a second run the first lines read `Credential already exists, moving on`; the - + @@ -263,7 +263,7 @@ The automation in `main.go` never types a username or a password. It opens the s Wiring it up is two API calls. Store the credential against an origin: ```go -client.Credentials.Create(ctx, steel.CredentialCreateParams{ +client.Credentials.New(ctx, steel.CredentialNewParams{ Origin: steel.F("https://demo.testfire.net"), Value: steel.F(map[string]string{"username": "admin", "password": "admin"}), }) @@ -272,18 +272,18 @@ client.Credentials.Create(ctx, steel.CredentialCreateParams{ Then opt the session into the vault with an empty config struct: ```go -client.Sessions.Create(ctx, steel.SessionCreateParams{ - Credentials: steel.F(steel.SessionCreateParamsCredentials{}), +client.Sessions.New(ctx, steel.SessionNewParams{ + Credentials: steel.F(steel.SessionNewParamsCredentials{}), }) ``` -`SessionCreateParamsCredentials{}` is the opt-in. Leave it off and the vault is ignored for that session. The zero value uses the defaults; its fields (`AutoSubmit`, `BlurFields`, `ExactOrigin`) tune whether Steel presses submit for you, masks the typed values, and matches the origin exactly. +`SessionNewParamsCredentials{}` is the opt-in. Leave it off and the vault is ignored for that session. The zero value uses the defaults; its fields (`AutoSubmit`, `BlurFields`, `ExactOrigin`) tune whether Steel presses submit for you, masks the typed values, and matches the origin exactly. ## Confirming the fill -After navigating to `/login.jsp`, the script polls the username field (`#uid`) until Steel injects the vaulted value, then reports success. With the default `AutoSubmit`, Steel also presses submit, so the filled field is only briefly visible — polling catches it as soon as it lands. The demo site currently serves an expired certificate, so the run first sends `Security.setIgnoreCertificateErrors`; drop that for a site with a valid certificate. +After navigating to `/login.jsp`, the script polls the username field (`#uid`) until Steel injects the vaulted value, then reports success. With the default `AutoSubmit`, Steel also presses submit, so the filled field is only briefly visible, and polling catches it as soon as it lands. The demo site currently serves an expired certificate, so the run first sends `Security.setIgnoreCertificateErrors`; drop that for a site with a valid certificate. -Re-running `Credentials.Create` for an origin that already has a stored credential returns an error whose message contains `already exists`. The script checks for that string and continues, so repeat runs are idempotent. +Before storing, the script calls `Credentials.List` filtered by the same `Origin` and skips `Credentials.New` when the vault already holds a credential for it. Repeat runs are idempotent, and they do not depend on the error the API returns for a duplicate. ## Run it @@ -313,8 +313,8 @@ On a second run the credential is already in the vault, so the first lines read ## Make it yours - **Target another site.** Change `origin` and the `Value` map, then point the navigation and the polled field selector at the new login form. Steel handles detection for any standard username/password form. -- **Tune the fill.** Set `AutoSubmit`, `BlurFields`, or `ExactOrigin` on `SessionCreateParamsCredentials` to control submit behavior, value masking, and origin matching. -- **Manage creds out of band.** `Credentials.List`, `Credentials.Update`, and `Credentials.Delete` let a setup script rotate or audit stored values while `main.go` stays focused on the workflow. +- **Tune the fill.** Set `AutoSubmit`, `BlurFields`, or `ExactOrigin` on `SessionNewParamsCredentials` to control submit behavior, value masking, and origin matching. +- **Manage creds out of band.** `Credentials.List`, `Credentials.Update`, and `Credentials.Delete` let a setup script audit, rotate, or remove stored values while `main.go` stays focused on the workflow. Rotation has to happen there: `main.go` only stores a credential when its origin has none, so editing the `Value` map alone does not change what the vault holds. ## Related diff --git a/content/docs/cookbook/crewai.mdx b/content/docs/cookbook/crewai.mdx index f3fe1f5d..ff85982d 100644 --- a/content/docs/cookbook/crewai.mdx +++ b/content/docs/cookbook/crewai.mdx @@ -3,13 +3,13 @@ title: Build a multi-agent browser workflow with CrewAI description: Integrate Steel with the CrewAI multi-agent framework. --- - + - + -CrewAI composes LLM work out of three primitives: an `Agent` (role, goal, tools), a `Task` (description + expected output), and a `Crew` that runs them in order. This recipe wires two [agents](/cookbook/topics/agents), a `researcher` and a `reporting_analyst`, to a single custom tool that calls Steel's scrape API. The researcher gathers sources; the analyst turns them into `report.md`. The [CrewAI integration](/integrations/crewai) covers install and setup. +CrewAI composes LLM work out of three primitives: an `Agent` (role, goal, tools), a `Task` (description + expected output), and a `Crew` that runs them in order. This recipe wires two agents, a `researcher` and a `reporting_analyst`, to a single custom tool that calls Steel's scrape API. The researcher gathers sources; the analyst turns them into `report.md`. ```python @agent @@ -89,7 +89,7 @@ A run takes ~60-90 seconds. `report.md` is overwritten each run. ## Related recipes + - diff --git a/content/docs/cookbook/deep-research.mdx b/content/docs/cookbook/deep-research.mdx index 3b6ab7a6..309dd1b6 100644 --- a/content/docs/cookbook/deep-research.mdx +++ b/content/docs/cookbook/deep-research.mdx @@ -3,19 +3,19 @@ title: Deep research with Claude Agent SDK subagents description: Lead orchestrator dispatches parallel researcher subagents, each driving its own Steel browser, and synthesizes findings into a cited Markdown report. --- - + - + -`@anthropic-ai/claude-agent-sdk` exposes typed `AgentDefinition` values that you pass through the `agents` field on `query()`. The lead agent invokes them through the built-in `Agent` tool. Multiple `Agent` calls fired in a single assistant turn run in parallel, and each [subagent](/cookbook/topics/subagents) starts in fresh context. +`@anthropic-ai/claude-agent-sdk` exposes typed `AgentDefinition` values that you pass through the `agents` field on `query()`. The lead agent invokes them through the built-in `Agent` tool. Multiple `Agent` calls fired in a single assistant turn run in parallel, and each subagent starts in fresh context. -This recipe wires that pattern to Steel, built on the [Claude Agent SDK integration](/integrations/claude-agent-sdk). The lead "orchestrator" never opens a browser. It splits a research question into focused sub-questions, hands one to each `researcher` subagent, and synthesizes their cited findings into a Markdown report. Every researcher gets its own Steel session, so three browsers run side by side without stomping on each other's address bar. +This recipe wires that pattern to Steel. The lead "orchestrator" never opens a browser. It splits a research question into focused sub-questions, hands one to each `researcher` subagent, and synthesizes their cited findings into a Markdown report. Every researcher gets its own Steel session, so three browsers run side by side without stomping on each other's address bar. ```ts const researcher: AgentDefinition = { @@ -177,7 +177,7 @@ A run takes ~4 to 6 minutes wall-clock with 3 Steel sessions in parallel. Cost i - + @@ -350,7 +350,7 @@ A run takes ~4 to 6 minutes wall-clock with 3 Steel sessions running in parallel ## Related recipes + - diff --git a/content/docs/cookbook/eino.mdx b/content/docs/cookbook/eino.mdx index b8e51501..5bcd4ef1 100644 --- a/content/docs/cookbook/eino.mdx +++ b/content/docs/cookbook/eino.mdx @@ -3,13 +3,13 @@ title: Build a browser agent with Eino description: "Use Steel with the ByteDance Eino framework to build a ReAct agent that calls Steel's scrape API as a tool to research and answer a web question." --- - + - + -[Eino](https://www.cloudwego.io/docs/eino/) is ByteDance's LLM application framework for Go. Its `flow/agent/react` package ships a prebuilt [ReAct agent](/cookbook/topics/agents): give it a tool-calling model and a set of tools, and it runs the reason-act loop for you. This recipe gives that agent two tools backed by Steel's Scrape API and points it at a news front page to write a short research briefing. +[Eino](https://www.cloudwego.io/docs/eino/) is ByteDance's LLM application framework for Go. Its `flow/agent/react` package ships a prebuilt ReAct agent: give it a tool-calling model and a set of tools, and it runs the reason-act loop for you. This recipe gives that agent two tools backed by Steel's Scrape API and points it at a news front page to write a short research briefing. Unlike a CDP-driven recipe, there is no browser session to open or release here. `client.Scrape` runs a browser on Steel's side, fetches the page, and returns clean Markdown plus the page's links. The agent reads pages the way an LLM wants to read them (as text, not pixels), so the tools are plain HTTP calls and the whole program is stateless between turns. @@ -46,8 +46,10 @@ scrapeTool, _ := utils.InferTool( "scrape_page", "Fetch a web page through Steel and return it as clean Markdown plus title and description.", func(ctx context.Context, args scrapePageArgs) (string, error) { - format := []steel.ScrapeRequestFormatItem{steel.ScrapeRequestFormatItemMarkdown} - res, err := client.Scrape(ctx, steel.ClientScrapeParams{URL: args.URL, Format: &format}) + res, err := client.Scrape(ctx, steel.ScrapeParams{ + URL: steel.F(args.URL), + Format: steel.F([]steel.ScrapeParamsFormat{steel.ScrapeParamsFormatMarkdown}), + }) // ... marshal title + markdown to a JSON string for the model }, ) @@ -93,7 +95,7 @@ A run is typically 5 to 9 agent turns and ~15 to 35 seconds against Hacker News. - **Swap the task.** Change the `task` constant. The tools stay the same; the agent re-plans against the new instructions. Try a comparison ("read these two pricing pages and tabulate the differences") or a single-page extraction. - **Swap the model.** Eino's model components are interchangeable. Replace the `claude` import and `claude.NewChatModel` with `github.com/cloudwego/eino-ext/components/model/openai` and `openai.NewChatModel(ctx, &openai.ChatModelConfig{...})`; the tools and agent wiring do not change because tool schemas are provider-agnostic. -- **Return richer Markdown.** Add `steel.ScrapeRequestFormatItemReadability` or `steel.ScrapeRequestFormatItemCleanedHTML` to the `Format` slice and surface those fields if you want the article body without site chrome. +- **Return richer Markdown.** Add `steel.ScrapeParamsFormatReadability` or `steel.ScrapeParamsFormatCleanedHTML` to the `Format` slice and surface those fields if you want the article body without site chrome. - **Add a tool.** Write another typed function and pass it through `utils.InferTool`, then add it to the `Tools` slice. A useful third tool is a `screenshot` call backed by `client.Screenshot` when the agent needs to confirm a page rendered. - **Cap the loop differently.** `MaxStep` bounds how many model-plus-tool rounds run before the agent returns whatever it has. Lower it to fail fast on hard tasks, raise it for multi-page research. @@ -104,7 +106,7 @@ A run is typically 5 to 9 agent turns and ~15 to 35 seconds against Hacker News. ## Related recipes + - diff --git a/content/docs/cookbook/extensions.mdx b/content/docs/cookbook/extensions.mdx index ae4c2b25..58fb7a6e 100644 --- a/content/docs/cookbook/extensions.mdx +++ b/content/docs/cookbook/extensions.mdx @@ -3,17 +3,17 @@ title: Upload and run browser extensions description: Use the Steel Extensions API with Playwright to upload and run browser extensions. --- - + - + -Steel sessions launch a clean Chrome with nothing installed. The [Extensions API](/cookbook/topics/steel-apis) lets you upload a Chrome extension once, get back an ID, and attach it to any future session via `extensionIds` on `sessions.create()`. Content scripts and background workers load before your first `page.goto`, so the extension has already rewritten the DOM by the time Playwright observes it. +Steel sessions launch a clean Chrome with nothing installed. The Extensions API lets you upload a Chrome extension once, get back an ID, and attach it to any future session via `extensionIds` on `sessions.create()`. Content scripts and background workers load before your first `page.goto`, so the extension has already rewritten the DOM by the time Playwright observes it. ```typescript const extensionExists = (await client.extensions.list()).extensions.find( @@ -99,7 +99,7 @@ A run takes ~20 seconds and costs a few cents of session time. First run uploads - + @@ -174,7 +174,7 @@ A run takes ~20 seconds and costs a few cents of session time. The first run upl - + @@ -245,11 +245,11 @@ The first run uploads the extension; later runs print `Reusing uploaded extensio - + -A fresh Steel session boots a stock Chrome with no extensions. The Extensions API lets you upload a Chrome extension once, keep the returned ID on your account, and attach it to any session through `ExtensionIDs` on `Sessions.Create`. Content scripts run before chromedp ever issues a `Navigate`, so by the time the page renders the extension has already rewritten the DOM. +A fresh Steel session boots a stock Chrome with no extensions. The Extensions API lets you upload a Chrome extension once, keep the returned ID on your account, and attach it to any session through `ExtensionIDs` on `Sessions.New`. Content scripts run before chromedp ever issues a `Navigate`, so by the time the page renders the extension has already rewritten the DOM. This recipe proves that attachment happened by waiting on a selector the extension creates, nothing more. It does not scrape or pretty-print the numbers the extension renders. @@ -263,12 +263,12 @@ for _, ext := range list.Extensions { if extID == "" { uploaded, _ := client.Extensions.Upload(ctx, steel.ExtensionUploadParams{ - URL: steel.Ptr("https://chromewebstore.google.com/detail/github-isometric-contribu/mjoedlfflcchnleknnceiplgaeoegien"), + URL: steel.F("https://chromewebstore.google.com/detail/github-isometric-contribu/mjoedlfflcchnleknnceiplgaeoegien"), }) extID = uploaded.ID } -sess, _ := client.Sessions.Create(ctx, steel.SessionCreateParams{ +sess, _ := client.Sessions.New(ctx, steel.SessionNewParams{ ExtensionIDs: steel.F([]string{extID}), }) ``` @@ -306,7 +306,7 @@ Releasing session... - **Upload your own extension.** `Extensions.Upload` takes any Chrome Web Store listing URL. Swap `storeURL` and update the `extensionName` that `Extensions.List` matches on, remembering the truncated, underscored form. - **Target a different profile.** Change `profileURL` to any public GitHub user. -- **Stack extensions.** `ExtensionIDs` is a slice. Upload several and attach them together in one `Sessions.Create`. +- **Stack extensions.** `ExtensionIDs` is a slice. Upload several and attach them together in one `Sessions.New`. - **Assert on real content.** Once the wrapper is visible, add `chromedp.Text` or `chromedp.Evaluate` steps to pull values the extension injected. ## Related diff --git a/content/docs/cookbook/files.mdx b/content/docs/cookbook/files.mdx index 87b51482..336929cc 100644 --- a/content/docs/cookbook/files.mdx +++ b/content/docs/cookbook/files.mdx @@ -3,17 +3,17 @@ title: Move files between your machine and a cloud browser description: Use the Steel Files API with Playwright to automate file uploads and downloads in the cloud. --- - + - + -Every Steel session ships with a scoped filesystem inside the session VM. `client.sessions.files` exposes methods to move bytes across the boundary between your machine and that sandbox. This recipe uses `upload` to push a local CSV into the session, hands the resulting path to a remote `` over CDP, and lets the browser render a chart against it. It's one of Steel's [session APIs](/cookbook/topics/steel-apis). +Every Steel session ships with a scoped filesystem inside the session VM. `client.sessions.files` exposes methods to move bytes across the boundary between your machine and that sandbox. This recipe uses `upload` to push a local CSV into the session, hands the resulting path to a remote `` over CDP, and lets the browser render a chart against it. ```typescript const uploadedFile = await client.sessions.files.upload(session.id, { @@ -105,7 +105,7 @@ There's also `client.files` (without `.sessions`), an organization-scoped store - + @@ -189,7 +189,7 @@ Done! - + @@ -201,15 +201,14 @@ let uploaded = client .files() .upload( session_id, - SessionFileUploadParams { - file: FileUpload::new("stock.csv", bytes).with_content_type("text/csv"), - path: None, - }, + SessionFileUploadParams::new( + Upload::from_bytes("stock.csv", bytes).with_content_type("text/csv"), + ), ) .await?; ``` -`FileUpload::new` takes a filename and the raw bytes; `with_content_type` is the builder step for the MIME type. What comes back is a `File` whose `path` is a handle inside the session VM (for this asset, `stock.csv` at the sandbox root). That path is meaningful to the browser running on Steel, not to your laptop, and keeping those two namespaces straight is the whole point of the recipe. +`Upload::from_bytes` takes a filename and the raw bytes; `with_content_type` is the builder step for the MIME type. What comes back is a `File` whose `path` is a handle inside the session VM (for this asset, `stock.csv` at the sandbox root). That path is meaningful to the browser running on Steel, not to your laptop, and keeping those two namespaces straight is the whole point of the recipe. ## Driving a file input over raw CDP @@ -260,7 +259,7 @@ Session released ## Make it yours -- **Upload from a URL.** `FileUpload` carries the bytes here, but the underlying endpoint also accepts a URL it fetches server-side, so you can skip reading the file locally for large fixtures. +- **Upload from a URL.** `Upload` carries the bytes here, but the underlying endpoint also accepts a URL it fetches server-side, so you can skip reading the file locally for large fixtures. - **Harvest generated files.** Swap the csvplot flow for a site that exports. After the download fires, call `files().list(session_id)` to discover the new path, then `files().download(session_id, &path)` to pull the bytes back. - **Target a nested path.** Set `path: Some("inputs/stock.csv".into())` on `SessionFileUploadParams` to control where the file lands inside the sandbox instead of the default filename at root. @@ -272,25 +271,21 @@ Session released - + A Steel session carries its own filesystem inside the session VM. `client.Sessions.Files` moves bytes across the boundary between your machine and that sandbox. This recipe reads a local CSV, uploads it with `Upload`, then hands the returned server-side path to a remote `` so csvplot.com can render a chart against bytes that never lived on the browser host's local disk. -The upload is a plain Go value, not an `io.Reader` or a multipart form you assemble yourself: +The upload takes an `io.Reader`, and the SDK assembles the multipart form for you. `steel.FileParam` attaches the filename and content type that the form part carries: ```go uploaded, err := client.Sessions.Files.Upload(ctx, sess.ID, steel.SessionFileUploadParams{ - File: steel.FileUpload{ - Name: "stock.csv", - Content: csvBytes, - ContentType: "text/csv", - }, + File: steel.FileParam(bytes.NewReader(csvBytes), "stock.csv", "text/csv"), }) ``` -`Content` is the raw `[]byte` you got from `os.ReadFile`. What comes back is a `*steel.File` whose `Path` is a handle inside the session VM (typically `stock.csv` at the sandbox root). That path is meaningless on your laptop, and your laptop's paths are meaningless inside the session. Keeping that distinction straight is the whole point. +`bytes.NewReader` wraps the raw `[]byte` you got from `os.ReadFile`. What comes back is a `*steel.File` whose `Path` is a handle inside the session VM (typically `stock.csv` at the sandbox root). That path is meaningless on your laptop, and your laptop's paths are meaningless inside the session. Keeping that distinction straight is the whole point. ## Wiring a remote file into a DOM input @@ -341,9 +336,9 @@ Releasing session... ## Make it yours -- **Upload from a URL.** `steel.FileUpload` carries bytes, but the underlying API also accepts a URL string for the file field. Fetch a report server-side and skip your machine entirely. -- **Harvest generated files.** Swap the csvplot.com flow for a site that exports. After the download fires, call `client.Sessions.Files.List(ctx, sess.ID)` to discover the new path, then `client.Sessions.Files.Download(ctx, sess.ID, path)` to pull it back as an `io.ReadCloser`. -- **Target a nested path.** `SessionFileUploadParams` has an optional `Path` field. The default is the filename at the sandbox root; set `Path` to a pointer to nest the upload, for example under `inputs/`. +- **Upload from a URL.** `steel.FileParam` wraps bytes, but the underlying API also accepts a URL string for the file field. Pass `File: steel.Raw[io.Reader](url)` to fetch a report server-side and skip your machine entirely. +- **Harvest generated files.** Swap the csvplot.com flow for a site that exports. After the download fires, call `client.Sessions.Files.List(ctx, sess.ID)` to discover the new path, then `client.Sessions.Files.Download(ctx, sess.ID, path)` to pull it back as an `*http.Response` whose `Body` streams the file. +- **Target a nested path.** `SessionFileUploadParams` has an optional `Path` field. The default is the filename at the sandbox root; set `Path` with `steel.F` to nest the upload, for example under `inputs/`. ## Related diff --git a/content/docs/cookbook/gemini-computer-use.mdx b/content/docs/cookbook/gemini-computer-use.mdx index 43007a04..79c0da33 100644 --- a/content/docs/cookbook/gemini-computer-use.mdx +++ b/content/docs/cookbook/gemini-computer-use.mdx @@ -3,19 +3,19 @@ title: Drive a browser with Gemini Computer Use description: "Connect Google's Gemini Computer Use to a Steel browser session for autonomous web interactions." --- - + - + -Gemini exposes [computer use](/cookbook/topics/computer-use) as a built-in tool type, not a hand-written schema. You set `config.tools = [{ computerUse: { environment: Environment.ENVIRONMENT_BROWSER } }]` on a `generateContent` call and the model plans against a fixed action vocabulary (`click_at`, `type_text_at`, `navigate`, `scroll_document`, `search`, `drag_and_drop`, `key_combination`, ...) with coordinates in a normalized 0-1000 grid. +Gemini exposes computer use as a built-in tool type, not a hand-written schema. You set `config.tools = [{ computerUse: { environment: Environment.ENVIRONMENT_BROWSER } }]` on a `generateContent` call and the model plans against a fixed action vocabulary (`click_at`, `type_text_at`, `navigate`, `scroll_document`, `search`, `drag_and_drop`, `key_combination`, ...) with coordinates in a normalized 0-1000 grid. -The model defaults to `gemini-3-flash-preview`. Conversation state lives entirely on your side, appended to `this.contents` turn by turn. The [Gemini Computer Use integration](/integrations/gemini-computer-use) covers install and setup. +The model defaults to `gemini-3-flash-preview`. Conversation state lives entirely on your side, appended to `this.contents` turn by turn. ## Coordinates and action mapping @@ -114,7 +114,7 @@ Expect roughly 60-120 seconds and 15-40 turns for a simple browsing task. - + @@ -237,7 +237,7 @@ A run typically takes 60-180 seconds and 10-30 iterations. Because `generate_con - + @@ -320,7 +320,7 @@ Expect roughly 60 to 120 seconds and 15 to 40 turns for a simple browsing task. - + @@ -330,7 +330,7 @@ Steel runs the screen. A session is a headful Chromium in a VM, and `client.Sess ## Two typed surfaces, one bytes gotcha -The Steel computer endpoint accepts the action as an `any` body, so each action is a distinct struct: `steel.ClickMouse`, `steel.MoveMouse`, `steel.PressKey`, `steel.TypeText`, `steel.Scroll`, `steel.DragMouse`, `steel.Wait`, `steel.TakeScreenshot`. The agent's `switch fc.Name` builds the right one per Gemini call, and `run` reads `*resp.Base64Image` back out (pointer fields, nil-checked). +The Steel computer endpoint takes the action as the `Body` of `SessionComputerParams`, a union interface, so each action is a distinct struct: `steel.SessionComputerParamsBodyClickMouse`, `...MoveMouse`, `...PressKey`, `...TypeText`, `...Scroll`, `...DragMouse`, `...Wait`, `...TakeScreenshot`. The agent's `switch fc.Name` builds the right one per Gemini call, and `run` reads `resp.Base64Image` back out (a plain string, empty when the action captured no screenshot). Gemini's args land in a `map[string]any` with JSON types: numbers are `float64`, so `argInt` casts before `denormalizeX` / `denormalizeY` scale 0-1000 onto the 1440x900 viewport. The one trap worth naming: `genai.Blob.Data` is `[]byte`, not a base64 string. Steel hands back base64 text, so every screenshot is run through `base64.StdEncoding.DecodeString` before it becomes an `InlineData` part. @@ -407,7 +407,7 @@ A run usually takes 60-180 seconds across 10-30 iterations. - Swap the model. The `model` constant is the only version string. - Resize the viewport. `viewportWidth` / `viewportHeight` feed both the Steel `Dimensions` and the denormalize math. - Gate safety decisions. Replace the auto-acknowledge branch in `executeTask` with a human approval before the action fires. -- Hand off auth. Pass `SessionContext` to `Sessions.Create` to resume with cookies and local storage. See [credentials](/cookbook/credentials). +- Hand off auth. Pass `SessionContext` to `Sessions.New` to resume with cookies and local storage. See [credentials](/cookbook/credentials). ## Related diff --git a/content/docs/cookbook/genkit.mdx b/content/docs/cookbook/genkit.mdx index 82f52c5b..33a9a652 100644 --- a/content/docs/cookbook/genkit.mdx +++ b/content/docs/cookbook/genkit.mdx @@ -3,9 +3,9 @@ title: Build a browser agent with Genkit description: Use Steel with Genkit Go to build a tool-calling agent that navigates and extracts from a chromedp-backed browser and completes a web task. --- - + - + @@ -44,7 +44,7 @@ type extractInput struct { ## Two ways to read a page -The tools cover the two access patterns a [browsing agent](/cookbook/topics/agents) needs: +The tools cover the two access patterns a browsing agent needs: - `navigate` + `extract` drive one live chromedp tab attached to the Steel session over CDP. `extract` takes a row selector plus a field-per-column list and runs the whole pull inside a single `chromedp.Evaluate`. Serial CDP round-trips to a cloud browser run about 200 to 300 ms each, so collapsing N rows by M fields into one evaluate keeps a page read under a second instead of stacking dozens of trips. - `scrape` calls `client.Scrape` and returns clean Markdown for a URL without touching the tab. It is the reliable path when the agent just needs an article's text, and it sidesteps selector guesswork entirely. @@ -95,7 +95,7 @@ A run takes about 20 to 40 seconds and 4 to 8 model turns. Cost is a few cents o ## Notes - **Go version.** Genkit Go 1.0 requires Go 1.25, so `go.mod` declares `go 1.25.0`. chromedp is pinned to `v0.13.6`, the last release that still builds on Go 1.23, to keep the rest of the tree from pulling the toolchain higher than Genkit needs. -- **Session reuse.** One Steel session and one chromedp tab live in the `browser` struct shared by every tool, so `navigate` and `extract` act on the same page. `chromedp.NoModifyURL` stops chromedp rewriting Steel's WebSocket URL, which would drop the `apiKey` query parameter. +- **Session reuse.** One Steel session and one chromedp tab live in the `browser` struct shared by every tool, so `navigate` and `extract` act on the same page. `chromedp.NoModifyURL` stops chromedp rewriting Steel's websocket URL, which would drop the `apiKey` query parameter. ## Make it yours @@ -111,7 +111,7 @@ A run takes about 20 to 40 seconds and 4 to 8 model turns. Cost is a few cents o ## Related recipes + - diff --git a/content/docs/cookbook/google-adk.mdx b/content/docs/cookbook/google-adk.mdx index eeb1d6b3..35d87c13 100644 --- a/content/docs/cookbook/google-adk.mdx +++ b/content/docs/cookbook/google-adk.mdx @@ -3,17 +3,17 @@ title: Build a browser agent with Google ADK description: "Use Steel with Google's Agent Development Kit (ADK) for Go to build a tool-using browser agent that drives a chromedp session over CDP and reads Hacker News." --- - + - + -[Google ADK](https://adk.dev/) (`@google/adk`) is Google's Agent Development Kit. You build an `LlmAgent` with a Gemini model, `instruction`, and a list of `FunctionTool`s, then hand it to a `Runner`. The runner owns the loop: it appends your message to a session, calls the model, dispatches tool calls, feeds results back, and yields an async stream of `Event`s until the [agent](/cookbook/topics/agents) produces its final answer. +[Google ADK](https://adk.dev/) (`@google/adk`) is Google's Agent Development Kit. You build an `LlmAgent` with a Gemini model, `instruction`, and a list of `FunctionTool`s, then hand it to a `Runner`. The runner owns the loop: it appends your message to a session, calls the model, dispatches tool calls, feeds results back, and yields an async stream of `Event`s until the agent produces its final answer. This recipe wires that tool layer to a Steel cloud browser. Three `FunctionTool`s in `index.ts` (`navigate`, `snapshot`, `extract`) drive a single Playwright page over CDP. The Steel session opens once in `main()` before the runner starts, so the tools close over a live `page` rather than spinning up a browser per call. Demo task: read the front page of Hacker News and return the top 5 stories as JSON. @@ -114,7 +114,7 @@ This agent has no `outputSchema`. ADK disables tool calls when an output schema - + @@ -250,7 +250,7 @@ A run takes ~20 to 40 seconds and a handful of agent turns on Hacker News. Cost - + diff --git a/content/docs/cookbook/headless-chrome.mdx b/content/docs/cookbook/headless-chrome.mdx index 9c301ea0..c40c2d6c 100644 --- a/content/docs/cookbook/headless-chrome.mdx +++ b/content/docs/cookbook/headless-chrome.mdx @@ -3,13 +3,13 @@ title: Automate a cloud browser with headless_chrome description: Use Steel with headless_chrome, the synchronous Rust equivalent of Puppeteer, to connect over CDP and scrape quotes with element handles. --- - + - + -headless_chrome is the Rust equivalent of Puppeteer: a high-level, synchronous wrapper over the Chrome DevTools Protocol. `Browser::connect` takes a WebSocket URL and returns a connected browser, which is all a Steel session is. There is no event loop to drive and no async runtime in the browser code itself: `new_tab`, `navigate_to`, `find_elements`, and `capture_screenshot` block until they return, the way the Node original does. It is the same cloud [browser automation](/cookbook/topics/browser-automation) as the other CDP recipes, in synchronous Rust. +headless_chrome is the Rust equivalent of Puppeteer: a high-level, synchronous wrapper over the Chrome DevTools Protocol. `Browser::connect` takes a websocket URL and returns a connected browser, which is all a Steel session is. There is no event loop to drive and no async runtime in the browser code itself: `new_tab`, `navigate_to`, `find_elements`, and `capture_screenshot` block until they return, the way the Node original does. ```rust let browser = Browser::connect(cdp_url)?; @@ -34,7 +34,7 @@ let result = tokio::task::spawn_blocking(move || scrape(&websocket_url, &key)).a That is also why `scrape` returns `Box` rather than the bare `Box` you would reach for first: `spawn_blocking` moves the closure to another thread, so its return type has to be `Send`. The session is created before the blocking call and released after it, so the browser work sits between two `await` points and the async SDK never blocks. -One detail in `scrape` is shared with the [chromiumoxide](/cookbook/chromiumoxide) recipe: the connect URL is normalized to carry a path. Steel's WebSocket URL is `wss://host?token`, and the WebSocket layer underneath headless_chrome expects `wss://host/?token`, so the `match` on `://` and `?` inserts the slash before `Browser::connect` dials it. +One detail in `scrape` is shared with the [chromiumoxide](/cookbook/chromiumoxide) recipe: the connect URL is normalized to carry a path. Steel's websocket URL is `wss://host?token`, and the websocket layer underneath headless_chrome expects `wss://host/?token`, so the `match` on `://` and `?` inserts the slash before `Browser::connect` dials it. ## Run it diff --git a/content/docs/cookbook/index.mdx b/content/docs/cookbook/index.mdx index a882f281..a544eacf 100644 --- a/content/docs/cookbook/index.mdx +++ b/content/docs/cookbook/index.mdx @@ -5,6 +5,19 @@ description: Runnable recipes for using Steel with your favorite libraries and f --- + - + -[LangChainGo](https://github.com/tmc/langchaingo) is the Go port of LangChain: LLM wrappers, chains, and agents that loop over tools until they reach an answer. This recipe gives a LangChainGo [browser agent](/cookbook/topics/agents) one tool backed by Steel's `scrape` endpoint, so the model reads pages as clean Markdown and never touches a browser library or CDP. The agent runs on Anthropic (`claude-sonnet-4-6`) through a zero-shot ReAct (MRKL) executor. +[LangChainGo](https://github.com/tmc/langchaingo) is the Go port of LangChain: LLM wrappers, chains, and agents that loop over tools until they reach an answer. This recipe gives a LangChainGo agent one tool backed by Steel's `scrape` endpoint, so the model reads pages as clean Markdown and never touches a browser library or CDP. The agent runs on Anthropic (`claude-sonnet-4-6`) through a zero-shot ReAct (MRKL) executor. LangChainGo's `tools.Tool` interface is deliberately small. A tool is a name, a description, and a `Call` that takes a string and returns a string: @@ -21,9 +21,9 @@ func (t scrapeTool) Description() string { return "Fetch a web page as clean Mar func (t scrapeTool) Call(ctx context.Context, input string) (string, error) { url := strings.Trim(strings.TrimSpace(input), "\"'") - resp, err := t.client.Scrape(ctx, steel.ClientScrapeParams{ - URL: url, - Format: &[]steel.ScrapeRequestFormatItem{steel.ScrapeRequestFormatItemMarkdown}, + resp, err := t.client.Scrape(ctx, steel.ScrapeParams{ + URL: steel.F(url), + Format: steel.F([]steel.ScrapeParamsFormat{steel.ScrapeParamsFormatMarkdown}), }) // ... return the capped resp.Content.Markdown } @@ -75,12 +75,12 @@ Each scrape call spins up a short-lived Steel browser server-side, so a run cost ## Related -[eino](/cookbook/eino) is the closest sibling: another Go ReAct agent on Steel's scrape API, but with typed tool arguments instead of LangChainGo's string interface. [genkit](/cookbook/genkit) drives a chromedp browser instead of the scrape endpoint. The [LangChainGo docs](https://pkg.go.dev/github.com/tmc/langchaingo) cover chains, memory, and the agent types. +[eino](/cookbook/eino) is the closest sibling: another Go ReAct agent on Steel's scrape API, but with typed tool arguments instead of LangChainGo's string interface. [genkit](/cookbook/genkit) drives a chromedp browser instead of the scrape endpoint. The [LangChainGo docs](https://tmc.github.io/langchaingo/docs/) cover chains, memory, and the agent types. ## Related recipes + - diff --git a/content/docs/cookbook/langgraph.mdx b/content/docs/cookbook/langgraph.mdx index d8019f3a..ca896ba1 100644 --- a/content/docs/cookbook/langgraph.mdx +++ b/content/docs/cookbook/langgraph.mdx @@ -3,15 +3,15 @@ title: Build a typed browser agent with LangGraph description: Use Steel with LangGraph to build a typed browser agent with an explicit state-machine loop and a structured-output formatter node. --- - + - + -[LangGraph](https://langchain-ai.github.io/langgraph/) builds agents as state machines: nodes do work, edges route control, and the agent loop is something you compose explicitly. LangChain ships the model wrapper (`ChatAnthropic`) and the `@tool` decorator; LangGraph ships the graph runtime, plus prebuilt `ToolNode` and `tools_condition` helpers. Steel's [LangGraph integration](/integrations/langgraph) covers the same setup on its own. +[LangGraph](https://langchain-ai.github.io/langgraph/) builds agents as state machines: nodes do work, edges route control, and the agent loop is something you compose explicitly. LangChain ships the model wrapper (`ChatAnthropic`) and the `@tool` decorator; LangGraph ships the graph runtime, plus prebuilt `ToolNode` and `tools_condition` helpers. -This recipe is a four-tool [browser agent](/cookbook/topics/agents): `open_session`, `navigate`, `snapshot`, `extract`. Each tool drives a Steel cloud session over Playwright. The graph has three nodes (`agent`, `tools`, `format`) and runs against `github.com/trending/python`, returning a Pydantic-validated `FinalReport`. +This recipe is a four-tool browser agent: `open_session`, `navigate`, `snapshot`, `extract`. Each tool drives a Steel cloud session over Playwright. The graph has three nodes (`agent`, `tools`, `format`) and runs against `github.com/trending/python`, returning a Pydantic-validated `FinalReport`. ```python graph = StateGraph(State) diff --git a/content/docs/cookbook/magnitude.mdx b/content/docs/cookbook/magnitude.mdx index 6925c575..70c8ba15 100644 --- a/content/docs/cookbook/magnitude.mdx +++ b/content/docs/cookbook/magnitude.mdx @@ -3,13 +3,13 @@ title: Build an AI browser agent with Magnitude description: Use Steel with Magnitude for AI-powered browser automation. --- - + - + -Magnitude grew out of end-to-end testing and kept the bias: an [agent loop](/cookbook/topics/agents) that narrates each turn, a CDP-level browser hookup, and LLM-backed primitives designed to intermix navigation, action, and typed readback. Steel's [Magnitude integration](/integrations/magnitude) covers the same setup on its own. `startBrowserAgent()` hands you a `BrowserAgent` with a small surface this recipe exercises: +Magnitude grew out of end-to-end testing and kept the bias: an agent loop that narrates each turn, a CDP-level browser hookup, and LLM-backed primitives designed to intermix navigation, action, and typed readback. `startBrowserAgent()` hands you a `BrowserAgent` with a small surface this recipe exercises: - `agent.extract(instruction, schema)`: describe what to pull off the page, pass a Zod schema, get a typed result. - `agent.act(instruction)`: describe an interaction in natural language. The agent plans, clicks, types, retries. @@ -120,7 +120,7 @@ A full run takes ~45 seconds. The `finally` block stops the agent first, then re ## Related recipes + - diff --git a/content/docs/cookbook/mastra.mdx b/content/docs/cookbook/mastra.mdx index 0f1a2580..be45e001 100644 --- a/content/docs/cookbook/mastra.mdx +++ b/content/docs/cookbook/mastra.mdx @@ -3,15 +3,15 @@ title: Build a typed browser agent with Mastra description: Use Steel with Mastra to build a typed browser agent with the Mastra Model Router and Studio playground. --- - + - + -[Mastra](https://mastra.ai/) is a TypeScript framework that wraps the Vercel AI SDK with typed tools, a model router, and a built-in Studio playground for chatting with your agents and inspecting traces. Steel's [Mastra integration](/integrations/mastra) covers the same setup on its own. +[Mastra](https://mastra.ai/) is a TypeScript framework that wraps the Vercel AI SDK with typed tools, a model router, and a built-in Studio playground for chatting with your agents and inspecting traces. -This recipe is a four-tool [browser agent](/cookbook/topics/agents): `open-session`, `navigate`, `snapshot`, `extract`. Each tool drives a Steel cloud session over Playwright. The agent runs against `github.com/trending/python` and returns a Zod-validated `FinalReport`. +This recipe is a four-tool browser agent: `open-session`, `navigate`, `snapshot`, `extract`. Each tool drives a Steel cloud session over Playwright. The agent runs against `github.com/trending/python` and returns a Zod-validated `FinalReport`. ```typescript const researchAgent = new Agent({ diff --git a/content/docs/cookbook/mcp.mdx b/content/docs/cookbook/mcp.mdx index e31d5121..f23dda72 100644 --- a/content/docs/cookbook/mcp.mdx +++ b/content/docs/cookbook/mcp.mdx @@ -3,20 +3,22 @@ title: Expose a Steel browser to any MCP client description: Build a Model Context Protocol server in Go with the official SDK and chromedp that hands any MCP client a Steel cloud browser through explicit session-handle tools. --- - + - + -This is a [Model Context Protocol](https://modelcontextprotocol.io) server that hands any [MCP client](/cookbook/topics/mcp) a Steel cloud browser to drive. It uses the official [TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) and drives the browser with Playwright over CDP through `connectOverCDP`, so there is no local Chrome to launch. The server carries no model key of its own: the client supplies the model, this process owns the cloud session. +This is a [Model Context Protocol](https://modelcontextprotocol.io) server that hands any MCP client a Steel cloud browser to drive. It uses the official [TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) and drives the browser with Playwright over CDP through `connectOverCDP`, so there is no local Chrome to launch. The server carries no model key of its own: the client supplies the model, this process owns the cloud session. Five tools make up the surface. `create_session` opens a Steel session and returns its id; `navigate`, `extract`, and `screenshot` take that id and act on the browser; `release_session` closes it. +Don't need your own tools? Steel also hosts an MCP server at `https://mcp.steel.dev/mcp` that any client can connect to directly. See the [Steel MCP server docs](https://docs.steel.dev/overview/mcp). + ## Each tool declares its shape, the id ties them together Every tool is a `server.registerTool` call: a name, a description, an `inputSchema` written as a Zod shape, and the handler. The shape is the contract the client sees and the type of the handler's argument in one place: @@ -79,7 +81,7 @@ Restart the client and ask it to open a page and read it back. It calls `create_ - + @@ -87,6 +89,8 @@ This is a [Model Context Protocol](https://modelcontextprotocol.io) server that Five tools make up the surface. `create_session` opens a Steel session and returns its id; `navigate`, `extract`, and `screenshot` act on a session by id; `release_session` closes it. +Don't need your own tools? Steel also hosts an MCP server at `https://mcp.steel.dev/mcp` that any client can connect to directly. See the [Steel MCP server docs](https://docs.steel.dev/overview/mcp). + ## The decorator is the schema, the id is the handle Each tool is a plain async function under `@mcp.tool()`. FastMCP reads the type hints and the docstring to build the JSON Schema the client sees, so the signature is the whole contract: @@ -145,7 +149,7 @@ Restart the client and ask it to open a page and read it back. It calls `create_ - + @@ -153,6 +157,8 @@ This is a [Model Context Protocol](https://modelcontextprotocol.io) server that Five tools make up the surface. `create_session` opens a Steel session and returns its id; `navigate`, `extract`, and `screenshot` take that id and act on the browser; `release_session` closes it. Each tool is one `#[tool]`-annotated method on `SteelMcp`, and `#[tool_router]` plus `#[tool_handler]` turn those methods into the served schema. +Don't need your own tools? Steel also hosts an MCP server at `https://mcp.steel.dev/mcp` that any client can connect to directly. See the [Steel MCP server docs](https://docs.steel.dev/overview/mcp). + ## Holding the browser open between calls The hard part of a browser MCP server is not any single tool, it is keeping one browser alive and reachable across separate calls. `create_session` does three things that have to outlive the call that made them: @@ -194,7 +200,7 @@ Restart the client and ask it to open a page and read it back. It calls `create_ - **Add a tool.** Write one more `async fn` with a `#[tool]` attribute and a `Parameters` argument carrying `session_id`. A `click` tool is `entry.page.find_element(sel).await?.click().await?`. - **Start authenticated.** Pass a populated `SessionCreateParams` to `sessions().create` to attach a [profile](/cookbook/profiles) or [credentials](/cookbook/credentials) so the session opens already logged in. -- **Return richer output.** Tools here return `Content::text` and `Content::image`. Swap in structured JSON content when a client wants typed fields instead of a string. +- **Return richer output.** Tools here return `ContentBlock::text` and `ContentBlock::image`. Swap in structured JSON content when a client wants typed fields instead of a string. ## Related @@ -204,7 +210,7 @@ Restart the client and ask it to open a page and read it back. It calls `create_ - + @@ -212,13 +218,15 @@ This is a [Model Context Protocol](https://modelcontextprotocol.io) server that The server exposes five tools. `create_session` starts a Steel session and returns its id; `navigate`, `extract`, and `screenshot` act on a session; `release_session` tears it down. The id Steel returns is the only thing tying the calls together. +Don't need your own tools? Steel also hosts an MCP server at `https://mcp.steel.dev/mcp` that any client can connect to directly. See the [Steel MCP server docs](https://docs.steel.dev/overview/mcp). + ## The session id is the handle A browser MCP server has to answer one question: when two tools run against "the browser," which browser do they mean? Hiding a single session in a global is the trap the [MCP spec calls out](https://blog.modelcontextprotocol.io/posts/2026-07-28-release-candidate/), because a second client on the same process would inherit the first one's cookies and page. The 2026 spec removed the transport-level session and says state should ride on an explicit handle "a `browser_id` minted from a tool and passed back as an ordinary argument." That is exactly what `create_session` does: ```go func (s *server) createSession(ctx context.Context, _ *mcp.CallToolRequest, _ createInput) (*mcp.CallToolResult, createOutput, error) { - steelSession, err := s.steel.Sessions.Create(ctx, steel.SessionCreateParams{ ... }) + steelSession, err := s.steel.Sessions.New(ctx, steel.SessionNewParams{ ... }) // ... connect chromedp to steelSession.WebsocketURL ... s.sessions[steelSession.ID] = sess return nil, createOutput{SessionID: steelSession.ID, LiveViewURL: sess.viewerURL}, nil @@ -257,7 +265,7 @@ One stdio rule: the JSON-RPC stream owns stdout, so the server logs only to stde ## Make it yours - **Add a tool.** A `click` tool is a few `chromedp.Click` lines and one more `mcp.AddTool` call. Take a `session_id`, look it up with `s.get`, act on the tab. -- **Start authenticated.** Swap the `SessionCreateParams` in `createSession` to attach a [profile](/cookbook/profiles) or [credentials](/cookbook/credentials) so a session opens already logged in. +- **Start authenticated.** Swap the `SessionNewParams` in `createSession` to attach a [profile](/cookbook/profiles) or [credentials](/cookbook/credentials) so a session opens already logged in. - **Go remote.** Replace `mcp.StdioTransport` with the SDK's streamable-HTTP handler to serve many clients from one process. The handle pattern already carries the state, so nothing else changes. ## Related @@ -271,7 +279,7 @@ One stdio rule: the JSON-RPC stream owns stdout, so the server logs only to stde ## Related recipes + - diff --git a/content/docs/cookbook/meta.json b/content/docs/cookbook/meta.json index 87d6626d..5126ce62 100644 --- a/content/docs/cookbook/meta.json +++ b/content/docs/cookbook/meta.json @@ -5,15 +5,8 @@ "index", "---Topics---", "topics/browser-automation", - "topics/playwright", - "topics/browser-use", "topics/agents", "topics/computer-use", - "topics/subagents", - "topics/authentication", - "topics/captchas", - "topics/search", - "topics/mcp", "topics/steel-apis", "---Contribute---", "[Cookbook on GitHub](https://github.com/steel-dev/steel-cookbook)" diff --git a/content/docs/cookbook/microsoft-agent-framework.mdx b/content/docs/cookbook/microsoft-agent-framework.mdx index 7ad7f4be..dc2f104f 100644 --- a/content/docs/cookbook/microsoft-agent-framework.mdx +++ b/content/docs/cookbook/microsoft-agent-framework.mdx @@ -3,15 +3,15 @@ title: Build a browser agent with Microsoft Agent Framework description: Use Steel with Microsoft Agent Framework 1.0 (the successor to AutoGen and Semantic Kernel) to build a tool-using browser agent. --- - + - + [Microsoft Agent Framework](https://learn.microsoft.com/en-us/agent-framework/overview/) is Microsoft's 1.0 agent runtime (Python + .NET), the successor to AutoGen and Semantic Kernel. Provider-agnostic chat clients, function tools as plain Python callables, and built-in MCP / A2A interop. -This starter wires a Steel browser into the framework's `@tool` decorator pattern and points the [agent](/cookbook/topics/agents) at GitHub Trending. +This starter wires a Steel browser into the framework's `@tool` decorator pattern and points the agent at GitHub Trending. ```python from agent_framework import Agent, tool @@ -98,7 +98,7 @@ A run takes ~20 to 40 seconds and 5 to 10 agent turns on GitHub Trending. Cost i ## Related recipes + - diff --git a/content/docs/cookbook/notte.mdx b/content/docs/cookbook/notte.mdx index 19a3eba5..581deac6 100644 --- a/content/docs/cookbook/notte.mdx +++ b/content/docs/cookbook/notte.mdx @@ -3,15 +3,15 @@ title: "Control a browser with Notte's reasoning engine" description: "Control browsers with AI using Steel's infrastructure and Notte's reasoning engine." --- - + - + -Notte builds its [agent](/cookbook/topics/agents) on top of a perception layer. Each step, `notte.Session` flattens the live DOM into a compact action space (labeled interactive elements, form fields, section headings) and hands that structured view to the reasoning model. The model picks an action by id, Notte translates it back into a browser command. Steel's [Notte integration](/integrations/notte) covers the same setup on its own. +Notte builds its agent on top of a perception layer. Each step, `notte.Session` flattens the live DOM into a compact action space (labeled interactive elements, form fields, section headings) and hands that structured view to the reasoning model. The model picks an action by id, Notte translates it back into a browser command. -This recipe points that loop at a Steel session instead of a locally launched browser. +This recipe points that loop at a Steel session instead of a locally-launched browser. ```python with notte.Session(cdp_url=cdp_url) as notte_session: @@ -81,7 +81,7 @@ A default run takes ~25 seconds. The `finally` block calls `client.sessions.rele ## Related recipes + - diff --git a/content/docs/cookbook/openai-agents.mdx b/content/docs/cookbook/openai-agents.mdx index 93ccf633..699bc39a 100644 --- a/content/docs/cookbook/openai-agents.mdx +++ b/content/docs/cookbook/openai-agents.mdx @@ -3,17 +3,17 @@ title: Build a typed browser agent with the OpenAI Agents SDK description: Use Steel with the OpenAI Agents SDK for TypeScript to build typed, tool-using browser agents. --- - + - + -The [OpenAI Agents SDK](https://openai.github.io/openai-agents-js/) (`@openai/agents`) is a small runtime for [agentic loops](/cookbook/topics/agents). You define an `Agent` with `instructions`, a `model`, `tools`, and an `outputType`. You call `run(agent, prompt)`. The SDK handles "pick a tool, call it, feed the result back, repeat" and validates the final message against your schema. Steel's [OpenAI Agents SDK integration](/integrations/openai-agents-sdk) covers the same pairing on its own. +The [OpenAI Agents SDK](https://openai.github.io/openai-agents-js/) (`@openai/agents`) is a small runtime for agentic loops. You define an `Agent` with `instructions`, a `model`, `tools`, and an `outputType`. You call `run(agent, prompt)`. The SDK handles "pick a tool, call it, feed the result back, repeat" and validates the final message against your schema. This recipe turns the tool layer into a Steel cloud browser. Four `tool()` wrappers in `index.ts` (`openSession`, `navigate`, `snapshot`, `extract`) shuttle CDP calls between the agent and Playwright. Demo task: scan `github.com/trending/python` and return the top 3 AI/ML repos as a validated `FinalReport`. @@ -96,7 +96,7 @@ A full run is ~20-40 seconds. Cost is a few cents of Steel session time plus Ope - + diff --git a/content/docs/cookbook/openai-computer-use.mdx b/content/docs/cookbook/openai-computer-use.mdx index 321a7799..692a6fd1 100644 --- a/content/docs/cookbook/openai-computer-use.mdx +++ b/content/docs/cookbook/openai-computer-use.mdx @@ -3,17 +3,17 @@ title: Drive a browser with OpenAI Computer Use description: "Connect OpenAI's Computer Use Assistant to a Steel browser session for autonomous web interactions." --- - + - + -OpenAI's [computer-use](/cookbook/topics/computer-use) model ships as a single tool declaration: `{ type: "computer" }`. You hand it to the Responses API, send a screenshot, and the model returns `computer_call` items with actions like `click`, `type`, `keypress`, `scroll`. Your job is to execute them against a real browser, capture the next screenshot, and feed it back. Steel's [OpenAI Computer Use integration](/integrations/openai-computer-use) covers the same loop as a guide. +OpenAI's computer-use model ships as a single tool declaration: `{ type: "computer" }`. You hand it to the Responses API, send a screenshot, and the model returns `computer_call` items with actions like `click`, `type`, `keypress`, `scroll`. Your job is to execute them against a real browser, capture the next screenshot, and feed it back. ## The loop @@ -139,7 +139,7 @@ Expect roughly 60-120 seconds and 15-40 turns for a simple browsing task. - + @@ -265,7 +265,7 @@ A run typically takes 60-180 seconds and 10-30 iterations. Screenshots are cache - + @@ -300,7 +300,7 @@ Contrast [claude-computer-use-rs](/cookbook/claude-computer-use), where the Anth A `computer_call` carries one `action` such as `{ "type": "click", "button": "left", "x": 412, "y": 280 }`. `execute_action` matches on `type` and builds the matching Steel `SessionComputerParams`: ```rust -"click" => SessionComputerParams::ClickMouse(ComputerActionRequestClickMouse { +"click" => SessionComputerParams::ClickMouse(SessionComputerParamsClickMouse { button: Some(map_button(/* left | right | middle | back | forward */)), coordinates: Some(vec![x, y]), screenshot: Some(true), @@ -360,26 +360,26 @@ A run drives a real session and a vision model across many turns, so it costs a - + This recipe wires two typed Go SDKs together so OpenAI's `computer-use-preview` model can drive a Steel cloud browser. The model emits a computer action through the official `github.com/openai/openai-go/v3` Responses API. You execute that action against a Steel session with `client.Sessions.Computer`, then hand the resulting screenshot back so the next turn sees what changed. That single exchange, repeated, is the whole agent. -The interesting part in Go is the seam between the two SDKs, because each models the action vocabulary differently. openai-go gives you a *flattened* union: `ResponseComputerToolCallActionUnion` carries every possible field (`X`, `Y`, `Button`, `Keys`, `ScrollX`, `Text`, `Path`) on one struct, and you read whichever ones the `Type` discriminator says are live. Steel's Go SDK takes the opposite shape: `SessionComputerParams` is a *constructed* discriminated union where you set an `Action` string and attach the one matching `ComputerActionRequest*` pointer. `executeAction` is the translation layer between the two. +The interesting part in Go is the seam between the two SDKs, because each models the action vocabulary differently. openai-go gives you a *flattened* union: `ResponseComputerToolCallActionUnion` carries every possible field (`X`, `Y`, `Button`, `Keys`, `ScrollX`, `Text`, `Path`) on one struct, and you read whichever ones the `Type` discriminator says are live. Steel's Go SDK takes the opposite shape: `SessionComputerParams` is a *constructed* discriminated union where `Body` holds exactly one `SessionComputerParamsBody*` struct, and that struct's type decides the action. `executeAction` is the translation layer between the two. ```go case "click": - body := &steel.ComputerActionRequestClickMouse{ - Action: steel.ComputerActionRequestClickMouseActionClickMouse, - Button: ptr(mapButton(act.Button)), - Coordinates: coords(), - Screenshot: ptr(true), + body := steel.SessionComputerParamsBodyClickMouse{ + Action: steel.F(steel.SessionComputerParamsBodyClickMouseActionClickMouse), + Button: steel.F(mapButton(act.Button)), + Coordinates: steel.F(coords()), + Screenshot: steel.F(true), } - return a.run(ctx, steel.SessionComputerParams{Action: "click_mouse", ComputerActionRequestClickMouse: body}) + return a.run(ctx, steel.SessionComputerParams{Body: body}) ``` -Every branch sets `Screenshot: ptr(true)`, so the Steel call that performs the action also returns the screenshot in the same round trip. `run` reads `resp.Base64Image` and falls back to an explicit `take_screenshot` if a particular action did not capture one. +Every branch sets `Screenshot: steel.F(true)`, so the Steel call that performs the action also returns the screenshot in the same round trip. `run` reads `resp.Base64Image` and falls back to an explicit `take_screenshot` if a particular action did not capture one. ## Responses keeps the conversation, you keep the loop @@ -467,7 +467,7 @@ A run typically takes 60-180 seconds across 10-30 model turns. Each turn is one - **Adjust the viewport.** `viewportWidth` and `viewportHeight` feed both the Steel session `Dimensions` and the `computer_use_preview` tool's display size. Keep the two in sync so the model's coordinates match the real screen. - **Raise or lower the ceiling.** `maxIterations` bounds the loop at 50 turns. Lower it to cap spend on a flaky task. - **Gate safety checks.** Replace the auto-acknowledge block with a prompt or an allowlist before appending to `acks`. -- **Persist a login.** Pass `SessionContext` to `Sessions.Create` to reuse cookies across runs. See [credentials](/cookbook/credentials). +- **Persist a login.** Pass `SessionContext` to `Sessions.New` to reuse cookies across runs. See [credentials](/cookbook/credentials). ## Notes diff --git a/content/docs/cookbook/playwright.mdx b/content/docs/cookbook/playwright.mdx index 5fc55e48..17c873d7 100644 --- a/content/docs/cookbook/playwright.mdx +++ b/content/docs/cookbook/playwright.mdx @@ -3,17 +3,17 @@ title: Automate a cloud browser with Playwright description: Use Steel with Playwright in TypeScript for cloud browser automation. --- - + - + -Playwright exposes `chromium.connectOverCDP()`, which attaches to any Chrome speaking the Chrome DevTools Protocol. Steel sessions expose one over a websocket. Connect them and your local code [drives a remote browser](/cookbook/topics/browser-automation) with stealth, proxies, and a live viewer. No Chrome on your machine required. Steel's [Playwright integration](/integrations/playwright) covers the same connection as a guide. +Playwright exposes `chromium.connectOverCDP()`, which attaches to any Chrome speaking the Chrome DevTools Protocol. Steel sessions expose one over a websocket. Connect them and your local code drives a remote browser with stealth, proxies, and a live viewer. No Chrome on your machine required. ```typescript session = await client.sessions.create(); @@ -81,7 +81,7 @@ A run costs a few cents of browser time. Steel bills per session-minute, so the - + @@ -156,7 +156,7 @@ One run costs a few cents of session time. Steel bills per session-minute, which - + @@ -173,7 +173,7 @@ Steel returns a context with a page already open, so there is no `NewContext` / ## The driver, not the browser -playwright-go is not a pure-Go CDP client the way [chromedp](/cookbook/chromedp) and [Rod](/cookbook/rod) are. It drives the same Node-based Playwright driver the other language bindings use, so that driver has to exist on disk before `playwright.Run()` will start. The program installs it on the first line of `run`: +playwright-go is not a pure-Go CDP client the way [chromedp](/cookbook/chromedp) and [Rod](/cookbook/rod) are. It drives the same Node-based Playwright driver the other language bindings use, so that driver has to exist on disk before `playwright.Run()` will start. The program installs it in `run`, right after the Steel session is created: ```go if err := playwright.Install(&playwright.RunOptions{SkipInstallBrowsers: true}); err != nil { @@ -182,7 +182,7 @@ if err := playwright.Install(&playwright.RunOptions{SkipInstallBrowsers: true}); pw, err := playwright.Run() ``` -`SkipInstallBrowsers: true` is the part that matters for Steel. A normal Playwright install also downloads Chromium, Firefox, and WebKit, hundreds of megabytes you never run, because the browser lives in Steel's cloud, not on your machine. The flag fetches the driver alone. Drop it and the first run still works, but it pulls three browser engines you will never launch. Calling `Install` in code is convenient for a one-file example; in a larger project you would run `go run github.com/playwright-community/playwright-go/cmd/playwright install` once at build time instead and let `Run` assume the driver is present. +`SkipInstallBrowsers: true` is the part that matters for Steel. A normal Playwright install also downloads Chromium, Firefox, and WebKit, hundreds of megabytes you never run, because the browser lives in Steel's cloud, not on your machine. The flag fetches the driver alone. Drop it and the first run still works, but it pulls three browser engines you will never launch. Calling `Install` in code is convenient for a one-file example; in a larger project you would run `go run github.com/mxschmitt/playwright-go/cmd/playwright install` once at build time instead and let `Run` assume the driver is present. The extraction reads the way it does in [chromedp](/cookbook/chromedp) for the same reason. `page.Evaluate` returns an `interface{}`, and a slice of structs does not cross that boundary cleanly, so the page-side script `JSON.stringify`s its result and the Go side `json.Unmarshal`s the string into a typed `[]story`. The `extractTopStories` constant holds that script: it pulls title, link, and points from the top five `tr.athing` rows. @@ -195,7 +195,7 @@ go mod tidy go run . ``` -Get a key at [app.steel.dev/settings/api-keys](https://app.steel.dev/settings/api-keys). The first `go run` downloads the Playwright driver, which takes a moment; later runs reuse it. The program prints a session viewer URL as it starts. Open it in another tab to watch the page load live, and it writes `hackernews.png` to the working directory on the way out. +Get a key at [app.steel.dev/settings/api-keys](https://app.steel.dev/settings/api-keys). The first `go run` downloads the Playwright driver (about 140 MB: the `playwright-core` npm package and a Node.js binary), which takes a moment; later runs reuse it. The program prints a session viewer URL as it starts. Open it in another tab to watch the page load live, and it writes `hackernews.png` to the working directory on the way out. Your output varies with the site. Structure looks like this: @@ -225,12 +225,12 @@ A run costs a few cents of browser time. Steel bills per session-minute, so the - **Swap the target.** Change the `page.Goto` URL and the `extractTopStories` script. The JSON-string bridge works for any shape: define a matching Go struct and unmarshal. Session setup and cleanup stay identical. - **Skip the JS.** `page.QuerySelectorAll("tr.athing")` returns `ElementHandle` values with `TextContent` and `GetAttribute`, if you would rather query node by node than evaluate a script. It is more round-trips and easier to debug one selector at a time. -- **Turn on stealth.** `SessionCreateParams` carries `UseProxy`, `SolveCaptcha`, and `Timeout` for sites with anti-bot defenses. Set them on the struct you pass to `Sessions.Create`. +- **Turn on stealth.** `SessionNewParams` carries `UseProxy`, `SolveCaptcha`, and `Timeout` for sites with anti-bot defenses. Set them on the struct you pass to `Sessions.New`. - **Add steps.** Playwright auto-waits on actionability, so `page.Click`, `page.Fill`, and `page.WaitForSelector` are reliable without manual sleeps when you fill forms or paginate before extracting. ## Related -[chromedp](/cookbook/chromedp) and [Rod](/cookbook/rod) are the pure-Go options: both speak CDP directly with no Node driver to install, so compare their `main.go` against this one to decide whether the Playwright API is worth the extra dependency. The [TypeScript](/cookbook/playwright) and [Python](/cookbook/playwright) starters connect to Steel the same way through the official Playwright bindings. See the [playwright-go docs](https://pkg.go.dev/github.com/playwright-community/playwright-go) for the full page, locator, and screenshot API. +[chromedp](/cookbook/chromedp) and [Rod](/cookbook/rod) are the pure-Go options: both speak CDP directly with no Node driver to install, so compare their `main.go` against this one to decide whether the Playwright API is worth the extra dependency. The [TypeScript](/cookbook/playwright) and [Python](/cookbook/playwright) starters connect to Steel the same way through the official Playwright bindings. See the [playwright-go docs](https://pkg.go.dev/github.com/mxschmitt/playwright-go) for the full page, locator, and screenshot API. diff --git a/content/docs/cookbook/profiles.mdx b/content/docs/cookbook/profiles.mdx index 8b2b284c..889c498b 100644 --- a/content/docs/cookbook/profiles.mdx +++ b/content/docs/cookbook/profiles.mdx @@ -3,17 +3,17 @@ title: Persist authenticated sessions with Profiles description: Maintain authenticated sessions across Steel browser instances using profiles. --- - + - + -A Steel profile is a named, long-lived browser identity. It holds everything a real Chrome user profile accumulates over time: cookies, localStorage, IndexedDB, history, installed extensions, autofill, site permissions. Every session you attach to the profile starts where the last one left off, and writes the user data directory back on release. Profiles are one of Steel's [authentication](/cookbook/topics/authentication) options for starting a browser already signed in. +A Steel profile is a named, long-lived browser identity. It holds everything a real Chrome user profile accumulates over time: cookies, localStorage, IndexedDB, history, installed extensions, autofill, site permissions. Every session you attach to the profile starts where the last one left off, and writes the user data directory back on release. Two options on `sessions.create` wire it up. On the first run, mint a fresh profile: @@ -125,7 +125,7 @@ Three recipes handle "start the browser already signed in." Pick by lifetime: - + @@ -217,7 +217,7 @@ Other ports of this recipe: [profiles-ts](/cookbook/profiles) (interactive picke - + @@ -291,17 +291,17 @@ A full round trip takes ~30 seconds. Both sessions go through `client.sessions() - + A Steel profile is a named, long-lived browser identity. It carries everything a real Chrome user profile accumulates: cookies, localStorage, IndexedDB, history, installed extensions, autofill, site permissions. Attach a session to a profile and the browser opens where the last one left off; on release, Steel writes the user data directory back to the profile. -Two fields on `Sessions.Create` wire it up, both through the `steel.F(...)` field wrapper. To mint a fresh profile, pass `PersistProfile: steel.F(true)` and leave `ProfileID` unset. The created `*steel.Session` exposes `.ProfileID`. Store it. Every later run passes it back as `ProfileID: steel.F(profileID)` alongside `PersistProfile`, and the browser opens as that identity. +Two fields on `Sessions.New` wire it up, both through the `steel.F(...)` field wrapper. To mint a fresh profile, pass `PersistProfile: steel.F(true)` and leave `ProfileID` unset. The created `*steel.Session` exposes `.ProfileID`. Store it. Every later run passes it back as `ProfileID: steel.F(profileID)` alongside `PersistProfile`, and the browser opens as that identity. ## Non-interactive by design -The TypeScript sibling opens an `inquirer` menu so you can pick an existing profile or create a new one. This Go port drops the picker and runs the full round-trip end to end in one invocation: `seedCart` mints a profile and adds an item, the program sleeps about three seconds so the snapshot settles, then `verifyCart` opens a second session from the same `ProfileID` and counts the cart rows. Nothing to click. To reuse a profile from a previous run, read the printed `Profile ID` and feed it into `Sessions.Create` yourself. +The TypeScript sibling opens an `inquirer` menu so you can pick an existing profile or create a new one. This Go port drops the picker and runs the full round-trip end to end in one invocation: `seedCart` mints a profile and adds an item, the program sleeps about three seconds so the snapshot settles, then `verifyCart` opens a second session from the same `ProfileID` and counts the cart rows. Nothing to click. To reuse a profile from a previous run, read the printed `Profile ID` and feed it into `Sessions.New` yourself. chromedp talks CDP directly: `chromedp.Evaluate` runs the cart logic in the page (`document.querySelector(".product-box-add-to-cart-button")` with an `input[value='Add to cart']` fallback, then `.cart-qty` for the header count and `.cart tbody tr` for the row count). `chromedp.NewRemoteAllocator` with `chromedp.NoModifyURL` attaches to the Steel browser over the websocket URL, the same idiom as the [chromedp](/cookbook/chromedp) recipe. @@ -341,7 +341,7 @@ Session #2 viewer: https://app.steel.dev/sessions/ef56gh78... Found 1 item(s) in the cart. Profile persistence works. ``` -Both sessions release through the `release` helper deferred right after each `Sessions.Create`. Skipping release keeps browsers running until the default timeout and delays the profile snapshot. +Both sessions release through the `release` helper deferred right after each `Sessions.New`. Skipping release keeps browsers running until the default timeout and delays the profile snapshot. ## Make it yours diff --git a/content/docs/cookbook/puppeteer.mdx b/content/docs/cookbook/puppeteer.mdx index 384981db..9b1286fb 100644 --- a/content/docs/cookbook/puppeteer.mdx +++ b/content/docs/cookbook/puppeteer.mdx @@ -3,13 +3,13 @@ title: Automate a cloud browser with Puppeteer description: Use Steel with Puppeteer in TypeScript for cloud browser automation. --- - + - + -Puppeteer ships a `connect()` call that attaches to any Chrome exposing a DevTools WebSocket. Steel sessions expose one. Point Puppeteer at it and the rest of the script is plain Puppeteer: `page.goto`, `page.evaluate`, `page.waitForSelector`, the whole surface area. Stealth, proxies, and the live session viewer come from Steel without extra wiring. +Puppeteer ships a `connect()` call that attaches to any Chrome exposing a DevTools websocket. Steel sessions expose one. Point Puppeteer at it and the rest of the script is plain Puppeteer: `page.goto`, `page.evaluate`, `page.waitForSelector`, the whole surface area. Stealth, proxies, and the live session viewer come from Steel without extra wiring. ```typescript session = await client.sessions.create(); diff --git a/content/docs/cookbook/pydantic-ai.mdx b/content/docs/cookbook/pydantic-ai.mdx index 415efabf..89680a57 100644 --- a/content/docs/cookbook/pydantic-ai.mdx +++ b/content/docs/cookbook/pydantic-ai.mdx @@ -3,15 +3,15 @@ title: Build a typed browser agent with Pydantic AI description: Use Steel with Pydantic AI to build typed, provider-agnostic browser agents with dependency injection. --- - + - + -[Pydantic AI](https://ai.pydantic.dev/) is the Pydantic team's agent framework. It's provider-agnostic and reuses Pydantic models for tool arguments and final outputs. Steel's [Pydantic AI integration](/integrations/pydantic-ai) covers the same setup on its own. +[Pydantic AI](https://ai.pydantic.dev/) is the Pydantic team's agent framework. It's provider-agnostic and reuses Pydantic models for tool arguments and final outputs. -This starter wires a Steel browser into Pydantic AI's dependency-injection pattern and points the [agent](/cookbook/topics/agents) at GitHub Trending. +This starter wires a Steel browser into Pydantic AI's dependency-injection pattern and points the agent at GitHub Trending. ```python from pydantic_ai import Agent, RunContext diff --git a/content/docs/cookbook/restate-agent.mdx b/content/docs/cookbook/restate-agent.mdx index a6a599e2..b6e833e6 100644 --- a/content/docs/cookbook/restate-agent.mdx +++ b/content/docs/cookbook/restate-agent.mdx @@ -3,17 +3,17 @@ title: Run a durable browser agent with Restate description: Build a Restate Virtual Object in TypeScript that uses durable OpenAI planning steps and Steel scraping to answer browser research questions. --- - + - + -This recipe runs a [Restate](/cookbook/topics/restate) Virtual Object named `ResearchSession`. Its `answer` handler keeps scraped observations in object state, wraps OpenAI planning calls in durable `ctx.run` steps, and calls Steel's `scrape` API as the browser tool. If the service process crashes after Steel has fetched a page, Restate replays the journal entry instead of scraping the same page again. +This recipe runs a Restate Virtual Object named `ResearchSession`. Its `answer` handler keeps scraped observations in object state, wraps OpenAI planning calls in durable `ctx.run` steps, and calls Steel's `scrape` API as the browser tool. If the service process crashes after Steel has fetched a page, Restate replays the journal entry instead of scraping the same page again. The agent loop is deliberately small: @@ -84,7 +84,7 @@ Open the Restate UI at `http://localhost:9070` and inspect the invocation journa - + @@ -157,7 +157,7 @@ curl localhost:8080/restate/call/ResearchSession/demo/history --json '{}' - + @@ -218,7 +218,7 @@ The first build pulls `restate-sdk`, `steel-rs`, `reqwest`, and their transitive - + @@ -283,7 +283,7 @@ Use the Restate UI at `http://localhost:9070` to inspect the journal. The handle ## Related recipes + - diff --git a/content/docs/cookbook/rig.mdx b/content/docs/cookbook/rig.mdx index 43be2e98..02706ca5 100644 --- a/content/docs/cookbook/rig.mdx +++ b/content/docs/cookbook/rig.mdx @@ -3,13 +3,13 @@ title: Build a browser agent with rig description: Use Steel with rig to build an agent that drives a cloud browser over CDP with chromiumoxide through navigate and extract tools, then answers a multi-step web task. --- - + - + -[rig](https://docs.rs/rig-core) is a Rust framework for LLM applications: you define tools as trait impls, hand them to an `Agent`, and call `prompt`, which loops the model over those tools until it produces an answer. This recipe gives the [agent](/cookbook/topics/agents) two tools backed by a real Chrome running in the cloud through Steel, driven over CDP with [chromiumoxide](https://docs.rs/chromiumoxide). The model navigates and reads the live DOM itself instead of receiving pre-scraped text, so it can follow links and work on pages that only exist after JavaScript runs. +[rig](https://docs.rs/rig-core) is a Rust framework for LLM applications: you define tools as trait impls, hand them to an `Agent`, and call `prompt`, which loops the model over those tools until it produces an answer. This recipe gives the agent two tools backed by a real Chrome running in the cloud through Steel, driven over CDP with [chromiumoxide](https://docs.rs/chromiumoxide). The model navigates and reads the live DOM itself instead of receiving pre-scraped text, so it can follow links and work on pages that only exist after JavaScript runs. Each tool is a struct that owns a `chromiumoxide::Page` and implements rig's `Tool` trait: @@ -69,7 +69,7 @@ cp .env.example .env # set STEEL_API_KEY and ANTHROPIC_API_KEY cargo run ``` -Get a Steel key at [app.steel.dev/settings/api-keys](https://app.steel.dev/settings/api-keys) and an Anthropic key at [console.anthropic.com](https://console.anthropic.com/settings/keys). Both keys are read from the environment; the Steel key is also passed to `Steel::new` explicitly so the same value signs the CDP WebSocket URL. +Get a Steel key at [app.steel.dev/settings/api-keys](https://app.steel.dev/settings/api-keys) and an Anthropic key at [console.anthropic.com](https://console.anthropic.com/settings/keys). Both keys are read from the environment; the Steel key is also passed to `Client::builder().api_key(...)` explicitly so the same value signs the CDP WebSocket URL. The run is quiet until the answer lands, since the agent loops without streaming its intermediate turns. Your output varies. Structure looks like this: @@ -100,7 +100,7 @@ A run costs a few cents of browser time plus the Anthropic tokens for up to eigh ## Related recipes + - diff --git a/content/docs/cookbook/rod.mdx b/content/docs/cookbook/rod.mdx index d97e9c0f..f9b09fbd 100644 --- a/content/docs/cookbook/rod.mdx +++ b/content/docs/cookbook/rod.mdx @@ -3,37 +3,40 @@ title: Automate a cloud browser with Rod description: "Use Steel with Rod's fluent, chainable API to connect over CDP and scrape quotes.toscrape.com from a cloud browser." --- - + - + -Rod talks the Chrome DevTools Protocol directly and exposes it through a chainable, panic-on-error API. A Steel session is a Chrome instance reachable over a WebSocket, so `ControlURL` is the only seam you need: hand Rod the session's WebSocket URL with your key appended, and the rest of your code is ordinary Rod against a browser that runs in Steel's cloud with stealth, proxies, and a live viewer. Nothing about the queries below knows or cares that the browser is remote. It is the same connect-over-CDP [browser automation](/cookbook/topics/browser-automation) the rest of the cookbook uses. +Rod talks the Chrome DevTools Protocol directly and exposes it through a chainable, panic-on-error API. A Steel session is a Chrome instance reachable over a websocket, so the CDP connection is the only seam you need: hand Rod a client dialed to the session's websocket URL with your key appended, and the rest of your code is ordinary Rod against a browser that runs in Steel's cloud with stealth, proxies, and a live viewer. Nothing about the queries below knows or cares that the browser is remote. ```go cdpURL := fmt.Sprintf("%s&apiKey=%s", session.WebsocketURL, apiKey) -browser := rod.New().ControlURL(cdpURL).MustConnect() +cdpClient, err := connectCDP(ctx, cdpURL) +browser := rod.New().Client(cdpClient).MustConnect() defer browser.MustClose() page := browser.MustPage("https://quotes.toscrape.com").MustWaitStable() ``` -`rod.New()` returns a `*Browser` you keep configuring by chaining. `ControlURL` points it at the remote Chrome instead of launching a local one, and `MustConnect` attaches over CDP. There is no `NewContext` or `NewPage` ceremony: `MustPage` opens a tab and returns a `*Page` you query straight away. +`rod.New()` returns a `*Browser` you keep configuring by chaining. `Client` hands it a CDP client already dialed to the remote Chrome, so Rod never launches a local one, and `MustConnect` attaches over CDP. There is no `NewContext` or `NewPage` ceremony: `MustPage` opens a tab and returns a `*Page` you query straight away. ## The connect URL -`session.WebsocketURL` already carries Steel's session identifier. The one thing you add is your API key as a query parameter, which is why the code formats `%s&apiKey=%s` rather than passing the URL through untouched. Rod connects to exactly the URL you give it and does not rewrite the address, so the key has to be in the string before `ControlURL` sees it. If you forget it, the WebSocket handshake is rejected and `MustConnect` panics before the first page loads. +`session.WebsocketURL` already carries Steel's session identifier. The one thing you add is your API key as a query parameter, which is why the code formats `%s&apiKey=%s` rather than passing the URL through untouched. `connectCDP` dials exactly the URL you give it and does not rewrite the address, so the key has to be in the string before the dial. If you forget it, the websocket handshake is rejected and `connectCDP` returns an error before the first page loads. -The session itself comes from the Steel SDK. `client.Sessions.Create` returns a `*Session` whose `WebsocketURL`, `SessionViewerURL`, and `ID` fields drive the rest of the program: the WebSocket URL to connect, the viewer URL to print, and the ID to release at the end. +`connectCDP` exists because Rod's built-in websocket client is too minimal for Steel. Its handshake, the one `ControlURL` uses, sends the literal header `Sec-WebSocket-Key: nil`, which Steel answers with `400 Bad request`. Its reader also ignores frame types, so the close frame Steel sends when the browser or session ends lands in Rod's JSON decoder and crashes the process from a background goroutine, before the deferred `Release` can run. `connectCDP` dials with `github.com/gorilla/websocket` instead and wraps the connection in `cdpSocket`, a small adapter for Rod's two-method `cdp.WebSocketable` interface. A close frame then comes back from `Read` as an ordinary error (`websocket: close 1000 (normal)`), Rod returns it to any CDP call still waiting, and a normal shutdown exits cleanly. + +The session itself comes from the Steel SDK. `client.Sessions.New` returns a `*Session` whose `WebsocketURL`, `SessionViewerURL`, and `ID` fields drive the rest of the program: the websocket URL to connect, the viewer URL to print, and the ID to release at the end. ```go -session, err := client.Sessions.Create(ctx, steel.SessionCreateParams{ - Dimensions: &steel.SessionCreateParamsDimensions{Width: 1280, Height: 800}, +session, err := client.Sessions.New(ctx, steel.SessionNewParams{ + Dimensions: steel.F(steel.SessionNewParamsDimensions{Width: steel.F(int64(1280)), Height: steel.F(int64(800))}), }) ``` -Every field on `SessionCreateParams` is a pointer, so an omitted field is a real "unset" rather than a zero value the API has to guess about. The `ptr` helper at the top of `main.go` is a one-line generic that wraps a literal in a pointer, which is what lets you write `Dimensions` inline and, later, flags like `SolveCaptcha: ptr(true)`. +Every field on `SessionNewParams` is a `param.Field`, so an omitted field is a real "unset" rather than a zero value the API has to guess about. `steel.F` wraps a value to mark it as set, which is what lets you write `Dimensions` inline and, later, flags like `SolveCaptcha: steel.F(true)`. The one field worth setting deliberately on a longer job is `Timeout`. It is the hard cap on session lifetime in milliseconds and defaults to 300000, five minutes. A scrape that needs longer has to raise it at creation time, because there is no way to extend a session once it is live: when the timeout elapses, Steel releases the browser out from under you and the next Rod call fails. For the quick scrape here the default is plenty, and the deferred `Release` ends the session in well under a second anyway. @@ -59,7 +62,7 @@ The screenshot is captured on the remote browser and streamed back as bytes, so ## Watch it run -The program prints `session.SessionViewerURL` right after `Create`. Opening that link shows the live browser: the page navigating, the DOM settling, and the screenshot firing, all in real time. It is the fastest way to debug a selector that is not matching, because you can see the actual rendered page rather than guessing from a panic message. The viewer also keeps showing the last frame after the session ends, so a run that failed mid-scrape still leaves you something to inspect. +The program prints `session.SessionViewerURL` right after `Sessions.New`. Opening that link shows the live browser: the page navigating, the DOM settling, and the screenshot firing, all in real time. It is the fastest way to debug a selector that is not matching, because you can see the actual rendered page rather than guessing from a panic message. The viewer also keeps showing the last frame after the session ends, so a run that failed mid-scrape still leaves you something to inspect. ## Run it @@ -94,10 +97,10 @@ Found 10 quotes on the page: ... Saved screenshot to quotes.png +Done! Releasing session... Session released -Done! ``` A run takes a few seconds and costs a few cents of browser time. Steel bills per session-minute, so the `defer client.Sessions.Release(...)` call is not optional: skip it and the browser stays live until the default five-minute timeout, billing the whole time. `browser.MustClose()` closes the CDP connection; `Release` ends the Steel session. You want both, and you want them deferred so a panic from a `Must` call still triggers them on the way out. @@ -106,7 +109,7 @@ A run takes a few seconds and costs a few cents of browser time. Steel bills per - **Swap the target.** Change the `MustPage` URL and the selectors in the loop. The `quotes.toscrape.com` site paginates with a `.next > a` link, so you can follow it in a loop and scrape every page instead of one. Session setup and cleanup stay the same. - **Wait on real readiness.** `MustWaitStable` blocks until the DOM stops changing, which suits server-rendered pages. For a site that loads content with JavaScript after first paint, wait on the element you actually need with `page.MustElement(sel)`, which polls until it appears instead of guessing at a fixed delay. -- **Turn on stealth.** `SessionCreateParams` accepts `SolveCaptcha`, `UseProxy`, and `Timeout` for sites with anti-bot defenses. Each is a pointer, so set them through the `ptr` helper: `SolveCaptcha: ptr(true)`. +- **Turn on stealth.** `SessionNewParams` accepts `SolveCaptcha`, `UseProxy`, and `Timeout` for sites with anti-bot defenses. Wrap each value with `steel.F`: `SolveCaptcha: steel.F(true)`. `UseProxy` is typed `any`, so it takes `steel.F[any](true)`. - **Survive missing elements.** The `Must` methods are convenient for a script. For a long-running job, use the non-`Must` variants (`page.Element` returns `(*rod.Element, error)`) or wrap the risky section in `rod.Try`, which converts a panic into an error you can inspect and recover from rather than crashing the process. ## Related diff --git a/content/docs/cookbook/scrape.mdx b/content/docs/cookbook/scrape.mdx index 8a072aa5..1159cbae 100644 --- a/content/docs/cookbook/scrape.mdx +++ b/content/docs/cookbook/scrape.mdx @@ -1,16 +1,15 @@ --- -title: Scrape JavaScript-Rendered Pages to Markdown -sidebarTitle: Scrape to Markdown -description: "Scrape JavaScript-rendered pages to clean Markdown for LLM context with the Steel API, plus screenshots and PDFs. No browser library required." +title: Scrape a page to Markdown, screenshot, and PDF +description: "Use the Steel TypeScript SDK's direct API to scrape a page to clean Markdown for LLM context, plus screenshot and PDF, with no browser library." --- - + - + @@ -25,7 +24,7 @@ const scraped = await client.scrape({ const markdown = scraped.content.markdown ?? ""; ``` -`scrape()` runs the fetch and the cleanup on Steel's side, so there is no session to create, connect to, or release. One HTTP call in, structured content out. `scrape` is one of the direct [Steel API](/cookbook/topics/steel-apis) endpoints, with no browser session to manage. The same `client.screenshot()` and `client.pdf()` calls render the same page two other ways. +`scrape()` runs the fetch and the cleanup on Steel's side, so there is no session to create, connect to, or release. One HTTP call in, structured content out. The same `client.screenshot()` and `client.pdf()` calls render the same page two other ways. ## Markdown for model context @@ -117,7 +116,7 @@ Each of the three calls is one billed request against Steel, so a full run costs - + @@ -186,7 +185,7 @@ The other recipes in the cookbook connect a browser library (Playwright, Seleniu - + @@ -196,10 +195,9 @@ That makes this the shortest path into Steel from Rust, and it leans on the SDK' ```rust let scraped = client - .scrape(ClientScrapeParams { - url: TARGET_URL.to_string(), - format: Some(vec![ScrapeRequestFormatItem::Markdown]), - // remaining options set to None; see main.rs + .scrape(ScrapeParams { + format: Some(vec![ScrapeParamsFormat::Markdown]), + ..ScrapeParams::new(TARGET_URL.to_string()) }) .await?; @@ -211,7 +209,7 @@ scraped.links.len(); // Vec scraped.content.markdown; // Option ``` -`metadata` carries about twenty parsed fields (Open Graph tags, canonical URL, author, published time, the HTTP status code), so you get the document's shape without writing a single selector. `content` holds whichever formats you asked for in `format`: `Markdown`, `HTML`, `CleanedHTML`, or `Readability`. Request only what you need; markdown alone keeps the payload small for LLM context. +`metadata` carries about twenty parsed fields (Open Graph tags, canonical URL, author, published time, the HTTP status code), so you get the document's shape without writing a single selector. `content` holds whichever formats you asked for in `format`: `Markdown`, `Html`, `CleanedHtml`, or `Readability`. Request only what you need; markdown alone keeps the payload small for LLM context. `main` runs all three calls against Hacker News, prints the typed metadata, and writes `page.md`, `screenshot.png`, and `page.pdf` to the working directory. Screenshot and PDF responses are a hosted URL, not bytes, so the `download` helper fetches each URL with `reqwest` and writes the file. The artifacts live on Steel for a while after the call, which is handy if you would rather hand the URL to another service than store the bytes yourself. @@ -247,9 +245,9 @@ Three calls cost a few cents of browser time total. Steel bills per session-minu ## Make it yours - **Change the target.** Edit the `TARGET_URL` constant. Every call reads from it. -- **Pick formats.** Pass more variants in `format`, for example `vec![ScrapeRequestFormatItem::Markdown, ScrapeRequestFormatItem::HTML]`, then read `scraped.content.html`. Each requested format comes back as its own `Option` field on `content`. +- **Pick formats.** Pass more variants in `format`, for example `vec![ScrapeParamsFormat::Markdown, ScrapeParamsFormat::Html]`, then read `scraped.content.html`. Each requested format comes back as its own `Option` field on `content`. - **Get the screenshot and PDF in one call.** `scrape()` takes `pdf: Some(true)` and `screenshot: Some(true)`; the URLs come back on `scraped.pdf` and `scraped.screenshot` instead of making three round trips. -- **Handle anti-bot pages.** Set `use_proxy: Some(true)` on any of the params to route through a Steel residential proxy. Add `delay: Some(2000)` to wait for late-loading content before capture. +- **Handle anti-bot pages.** Set `use_proxy: Some(true)` on any of the params to route through a Steel residential proxy. Add `delay: Some(2000.0)` to wait for late-loading content before capture. - **Match on the status.** `meta.status_code` is an `i64`, so branch on it before trusting the content (a soft 404 still returns markdown). ## Related @@ -260,7 +258,7 @@ Three calls cost a few cents of browser time total. Steel bills per session-minu - + @@ -269,23 +267,26 @@ Steel's direct API turns a URL into clean content with no browser library and no The scrape call leads: ```go -scraped, err := client.Scrape(ctx, steel.ClientScrapeParams{ - URL: targetURL, - Format: &[]steel.ScrapeRequestFormatItem{steel.ScrapeRequestFormatItemMarkdown}, +scraped, err := client.Scrape(ctx, steel.ScrapeParams{ + URL: steel.F(targetURL), + Format: steel.F([]steel.ScrapeParamsFormat{steel.ScrapeParamsFormatMarkdown}), }) -markdown := deref(scraped.Content.Markdown, "") -title := deref(scraped.Metadata.Title, "(no title)") +markdown := scraped.Content.Markdown +title := scraped.Metadata.Title +if title == "" { + title = "(no title)" +} ``` -Two Go specifics show up here. Optional request fields are pointers (`Format` is a `*[]ScrapeRequestFormatItem`, `FullPage` is a `*bool`), and steel-go ships no pointer constructors, so the recipe defines a one-line `ptr[T]` generic. Response fields like `Content.Markdown` and `Metadata.Title` are `*string`, so a small `deref` helper supplies a fallback. The format is a typed constant (`steel.ScrapeRequestFormatItemMarkdown`), not a bare string. +Two Go specifics show up here. Every request field is a `param.Field` (`Format` is a `param.Field[[]ScrapeParamsFormat]`, `FullPage` is a `param.Field[bool]`), and `steel.F` wraps a value to mark it as set, so a field you leave out is never sent. Response fields are plain values: `Content.Markdown` and `Metadata.Title` are `string`, and a field the API leaves out comes back empty, so the fallback is an ordinary `title == ""` check. The format is a typed constant (`steel.ScrapeParamsFormatMarkdown`), not a bare string. Screenshot and PDF come back as hosted URLs, not bytes: ```go -shot, _ := client.Screenshot(ctx, steel.ClientScreenshotParams{URL: targetURL, FullPage: ptr(true)}) +shot, _ := client.Screenshot(ctx, steel.ScreenshotParams{URL: steel.F(targetURL), FullPage: steel.F(true)}) fmt.Println(shot.URL) // https://... -pdf, _ := client.Pdf(ctx, steel.ClientPdfParams{URL: targetURL}) +pdf, _ := client.Pdf(ctx, steel.PdfParams{URL: steel.F(targetURL)}) fmt.Println(pdf.URL) ``` @@ -327,9 +328,9 @@ A scrape call costs a few cents of browser time. Steel starts and tears down the ## Make it yours - **Change the page.** Set `TARGET_URL` in `.env`, or pass a different URL to `client.Scrape`. -- **Ask for several formats.** `Format` takes a slice, so request more than one at once (`ScrapeRequestFormatItemMarkdown`, `...HTML`, `...Readability`, `...CleanedHTML`). Each lands under its own field on `Content`. +- **Ask for several formats.** `Format` takes a slice, so request more than one at once (`ScrapeParamsFormatMarkdown`, `...HTML`, `...Readability`, `...CleanedHTML`). Each lands under its own field on `Content`. - **Save the artifacts.** Fetch `shot.URL` and `pdf.URL` with `net/http` and `os.WriteFile` to write `screenshot.png` and `page.pdf`, the way the Python recipe does. -- **Scrape behind a proxy.** Set `UseProxy: ptr(true)` to route through a Steel residential proxy for geofenced or bot-sensitive pages. +- **Scrape behind a proxy.** Set `UseProxy: steel.F(true)` to route through a Steel residential proxy for geofenced or bot-sensitive pages. ## Related diff --git a/content/docs/cookbook/selenium.mdx b/content/docs/cookbook/selenium.mdx index 7aa9d6c1..f009838b 100644 --- a/content/docs/cookbook/selenium.mdx +++ b/content/docs/cookbook/selenium.mdx @@ -3,9 +3,9 @@ title: Automate a cloud browser with Selenium description: Use Steel with Selenium in Python for cloud browser automation. --- - + - + @@ -30,7 +30,7 @@ class CustomRemoteConnection(RemoteConnection): `get_remote_connection_headers` runs on every outbound request. Selenium has no persistent connection to keep alive; the two headers ride along with each command. That's the integration. After the driver is wired, the rest is vanilla Selenium 4. -One requirement: create the session with `is_selenium=True`. Steel provisions a WebDriver-compatible node for those sessions; without the flag you get a CDP browser that Selenium cannot drive. Steel's [Selenium integration](/integrations/selenium) covers the same setup on its own. +One requirement: create the session with `is_selenium=True`. Steel provisions a WebDriver-compatible node for those sessions; without the flag you get a CDP browser that Selenium cannot drive. ```python session = client.sessions.create(is_selenium=True) diff --git a/content/docs/cookbook/stagehand.mdx b/content/docs/cookbook/stagehand.mdx index 31ca6e7f..2d15e003 100644 --- a/content/docs/cookbook/stagehand.mdx +++ b/content/docs/cookbook/stagehand.mdx @@ -3,13 +3,13 @@ title: Automate browsing with natural-language instructions using Stagehand description: Use Steel with Stagehand for natural-language-driven AI browser automation. --- - + - + @@ -18,7 +18,7 @@ Stagehand replaces brittle selectors with two LLM-backed primitives: - `stagehand.extract(instruction, schema)`: describe what you want, pass a Zod schema, get typed data back. - `stagehand.act(instruction)`: describe an action in natural language, Stagehand figures out the click / type / scroll. -Both run against a Steel session over CDP, so Stagehand handles the reasoning and Steel handles the browser (stealth, proxies, live viewer). Steel's [Stagehand integration](/integrations/stagehand) covers the same wiring on its own. +Both run against a Steel session over CDP, so Stagehand handles the reasoning and Steel handles the browser (stealth, proxies, live viewer). ```typescript stagehand = new Stagehand({ @@ -105,7 +105,7 @@ A full run takes ~30 seconds and costs a few cents of Steel session time plus Op - + diff --git a/content/docs/cookbook/stripe-projects-web-agent.mdx b/content/docs/cookbook/stripe-projects-web-agent.mdx new file mode 100644 index 00000000..565f612d --- /dev/null +++ b/content/docs/cookbook/stripe-projects-web-agent.mdx @@ -0,0 +1,102 @@ +--- +title: Build a live browser agent with Stripe Projects +description: Stripe Projects provisions Steel, OpenRouter, and Vercel for a Next.js browser agent with embedded Steel Live View and a bounded tool loop. +--- + + + + + + + +Stripe Projects provisions this Next.js application with Steel browser infrastructure, an OpenRouter model, and a Vercel project. The agent opens managed browser sessions, navigates public webpages, inspects page content, and returns a structured report with source links. The interface streams its tool activity and embeds each active session in Steel Live View. + +Each run is bounded to 12 agent steps and four concurrent browser sessions. The Stop control cancels the active stream, and the request lifecycle releases its Steel sessions when work finishes or stops. + +## Build and run + +Create the application through Stripe Projects: + +```bash +stripe plugin install projects +stripe projects build my-agent --template steel/web-agent-studio +cd my-agent +npm run dev +``` + +Open [http://localhost:3000](http://localhost:3000), choose a sample task or write your own, and start the run. The browser panel appears when the agent opens its first Steel session. + +The build command materializes the pinned template, installs its dependencies, provisions all three services, and writes their configuration into the project. This example has no manual provider-key setup path. + +## Provisioned stack + +| Service | Role in the application | +| --- | --- | +| Steel | Creates managed browser sessions and provides embedded Live View URLs | +| OpenRouter | Runs the model behind the server-side agent loop | +| Vercel | Provides the project targeted by the deployment script | + +The agent runtime reads two generated variables: + +```text +STEEL_API_KEY +OPENROUTER_API_API_KEY +``` + +The repeated `API` in `OPENROUTER_API_API_KEY` is intentional. It matches the environment contract generated by Stripe Projects. The API route validates both variables before starting a run. + +## Agent flow + +The browser client posts a task to `/api/chat`. The route streams model output and tool results back to the page while keeping browser state on the server. + +The model can call four tools: + +- `openSession` creates a Steel session and returns the Live View metadata used by the UI. +- `navigate` loads a public HTTP or HTTPS URL in a selected session. +- `inspectPage` returns the current page title, URL, text, and links for model context. +- `deliverReport` returns typed findings and source links for the final report card. + +`openSession` can create up to four sessions in one run, which lets the agent compare sources without an unbounded browser fan-out. The server forces the first browser step, keeps the loop on tool calls, and forces `deliverReport` on the final allowed step. The run ends no later than step 12. + +The UI renders each tool transition in the activity timeline. Active sessions appear as Live View tabs, and the completed response appears as a structured report instead of an unformatted chat message. + +## Deploy the provisioned project + +The template includes a deployment helper for the Vercel project created by Stripe Projects: + +```bash +npm run deploy +``` + +The helper loads the Stripe-generated local environment, syncs only `STEEL_API_KEY` and `OPENROUTER_API_API_KEY` to Vercel production, uploads the application, and starts a production deployment. It excludes `.env` files, the local `.projects` workspace, and Vercel control credentials from the upload. + +If the Vercel credentials are missing or stale, refresh the project environment and retry: + +```bash +stripe projects env --pull +npm run deploy +``` + +The deployed route uses your provisioned Steel and OpenRouter resources. Add authentication and per-user rate limits before sharing it as a public application. + +The route rejects literal local and private destinations and screens DNS before browser requests. That resolution runs in the application while the Steel browser connects from its own network, so treat the guard as defense in depth rather than a private-network egress boundary. Enforce private-network restrictions at the browser or proxy layer before accepting untrusted destinations in a public deployment. + +Run `npm test` after changing the URL guard. Its focused suite covers successful cache reuse, expiry, concurrent resolution, failure retries, and the stale-lookup race. + +## Make it yours + +- Change the seeded tasks in the page component to match the workflows you want to demonstrate. +- Adjust the system prompt and step limit in the chat route for a narrower agent policy. +- Extend `inspectPage` with application-specific extraction fields. +- Add tools for screenshots, downloads, or authenticated workflows while preserving session cleanup. +- Extend the report schema when the application needs richer findings than a title, summary, and source list. + +Keep provider credentials on the server. Client components should consume streamed tool results and Live View metadata, never the generated API keys. + +## Related recipes + + + + + + diff --git a/content/docs/cookbook/swiftide.mdx b/content/docs/cookbook/swiftide.mdx index d2684b11..94bdd664 100644 --- a/content/docs/cookbook/swiftide.mdx +++ b/content/docs/cookbook/swiftide.mdx @@ -3,13 +3,13 @@ title: Build a research agent with Swiftide description: "Use Steel with Swiftide to build an agent whose tool reads the web through Steel's scrape endpoint, so the model works from clean Markdown with no browser library." --- - + - + -[Swiftide](https://swiftide.rs) is a Rust framework for LLM applications: indexing pipelines, query pipelines, and agents that loop over tool calls until they reach an answer. This recipe builds an [agent](/cookbook/topics/agents) whose only tool reads the web through Steel's `scrape` endpoint, so the model works from clean Markdown instead of raw HTML and never touches a browser library or CDP. +[Swiftide](https://swiftide.rs) is a Rust framework for LLM applications: indexing pipelines, query pipelines, and agents that loop over tool calls until they reach an answer. This recipe builds an agent whose only tool reads the web through Steel's `scrape` endpoint, so the model works from clean Markdown instead of raw HTML and never touches a browser library or CDP. The agent runs on Anthropic (`claude-sonnet-4-6`) and the tool is a `#[derive(Tool)]` struct that owns the Steel client: @@ -21,22 +21,21 @@ The agent runs on Anthropic (`claude-sonnet-4-6`) and the tool is a `#[derive(To param(name = "url", description = "Absolute URL of the page to read, including https://") )] struct ReadPage { - client: Arc, + client: Arc, } impl ReadPage { async fn read_page(&self, _ctx: &dyn AgentContext, url: &str) -> Result { - let response = self.client.scrape(ClientScrapeParams { - url: url.to_string(), - format: Some(vec![ScrapeRequestFormatItem::Markdown]), - .. + let response = self.client.scrape(ScrapeParams { + format: Some(vec![ScrapeParamsFormat::Markdown]), + ..ScrapeParams::new(url.to_string()) }).await?; // ... return response.content.markdown plus response.links } } ``` -The derive macro reads the struct's snake-case name (`ReadPage` -> `read_page`), finds the method with that name, and turns each `#[tool(param(...))]` into a JSON Schema field via `schemars`. Anything that implements `Tool` slots into `Agent::builder().tools(...)`, so a stateful struct and a `#[swiftide::tool]` free function are interchangeable at the call site. The struct form is what lets the tool hold `Arc`; a free function has nowhere to put it. +The derive macro reads the struct's snake-case name (`ReadPage` -> `read_page`), finds the method with that name, and turns each `#[tool(param(...))]` into a JSON Schema field via `schemars`. Anything that implements `Tool` slots into `Agent::builder().tools(...)`, so a stateful struct and a `#[swiftide::tool]` free function are interchangeable at the call site. The struct form is what lets the tool hold `Arc`; a free function has nowhere to put it. Wiring the agent is four builder calls: @@ -63,7 +62,7 @@ cp .env.example .env # set STEEL_API_KEY and ANTHROPIC_API_KEY cargo run ``` -Get a Steel key at [app.steel.dev/settings/api-keys](https://app.steel.dev/settings/api-keys) and an Anthropic key at [console.anthropic.com](https://console.anthropic.com/settings/keys). The Anthropic client reads `ANTHROPIC_API_KEY` from the environment on its own; the Steel key is passed to `Steel::new` explicitly. +Get a Steel key at [app.steel.dev/settings/api-keys](https://app.steel.dev/settings/api-keys) and an Anthropic key at [console.anthropic.com](https://console.anthropic.com/settings/keys). The Anthropic client reads `ANTHROPIC_API_KEY` from the environment on its own; the Steel key is passed to `Client::builder().api_key(...)` explicitly. Your output varies. Structure looks like this: @@ -86,13 +85,13 @@ Each `scrape` call spins up a short-lived Steel browser server-side, so a run co **The `#[derive(Tool)]` macro needs `serde` and `async-trait` as direct dependencies.** The expansion emits a bare `#[async_trait::async_trait]` and a `serde`-derived args struct without a `#[serde(crate = ...)]` override, so both crates have to resolve at the crate root even though you never name them. They are in `Cargo.toml` for that reason alone. The `#[swiftide::tool]` attribute macro on a free function fully qualifies its paths and does not need them, so that is the lighter option when your tool is stateless. -Steel's request builders implement `IntoFuture` with a `Send` future, so `client.scrape(...).await` works directly inside a Swiftide tool even though tools run on a multi-threaded Tokio runtime. +Steel's client methods are plain `async fn`s with `Send` futures, so `client.scrape(...).await` works directly inside a Swiftide tool even though tools run on a multi-threaded Tokio runtime. ## Make it yours - **Swap the task.** Change `TASK` and `SYSTEM_PROMPT` in `main.rs`. The tool stays the same; the agent re-plans against the new goal. - **Give it more reach.** The tool already returns up to 40 of the page's links, which is what lets the model follow a story into its comments. Raise `.limit(8)` if you want it to crawl deeper, and widen or drop the link cap. -- **Add a second tool.** A `screenshot` tool backed by `client.screenshot(...)` (returns a base64 PNG) or a `pdf` tool backed by `client.pdf(...)` drops in as another `#[derive(Tool)]` struct in the `tools(vec![...])` list. The agent picks per turn. +- **Add a second tool.** A `screenshot` tool backed by `client.screenshot(...)` (returns a hosted image URL) or a `pdf` tool backed by `client.pdf(...)` drops in as another `#[derive(Tool)]` struct in the `tools(vec![...])` list. The agent picks per turn. - **Change the model.** Any Anthropic chat model works in `default_prompt_model`. Swiftide also ships OpenAI, Gemini, Groq, and Ollama integrations behind feature flags; swap the `Anthropic` builder for one of those and the tools are unaffected. ## Related @@ -102,7 +101,7 @@ Steel's request builders implement `IntoFuture` with a `Send` future, so `client ## Related recipes + - diff --git a/content/docs/cookbook/temporal-browser-workflow.mdx b/content/docs/cookbook/temporal-browser-workflow.mdx index d457cad6..3da4b603 100644 --- a/content/docs/cookbook/temporal-browser-workflow.mdx +++ b/content/docs/cookbook/temporal-browser-workflow.mdx @@ -3,17 +3,17 @@ title: Run a durable browser workflow with Temporal description: Build a Temporal TypeScript Workflow that schedules retryable Steel browser Activities to capture page summaries, screenshots, and Markdown artifacts. --- - + - + -This recipe runs a [Temporal](/cookbook/topics/temporal) Workflow named `browserWorkflow`. The Workflow stays deterministic: it clamps small inputs, loops over URLs, and delegates each Steel scrape plus screenshot to the `capturePage` Activity. The Activity writes Markdown and PNG artifacts locally, then returns the compact page summary recorded in workflow history. +This recipe runs a Temporal Workflow named `browserWorkflow`. The Workflow stays deterministic: it clamps small inputs, loops over URLs, and delegates each Steel scrape plus screenshot to the `capturePage` Activity. The Activity writes Markdown and PNG artifacts locally, then returns the compact page summary recorded in workflow history. The retry boundary lives on the Activity proxy in `workflows.ts`: @@ -100,7 +100,7 @@ This keeps browser cost tied to Activity attempts. A failed Activity can retry. - + @@ -170,7 +170,7 @@ artifacts/ - + @@ -247,7 +247,7 @@ Your output varies. Structure looks like this: - + diff --git a/content/docs/cookbook/topics/agents.mdx b/content/docs/cookbook/topics/agents.mdx index 596e0cc6..446a42fc 100644 --- a/content/docs/cookbook/topics/agents.mdx +++ b/content/docs/cookbook/topics/agents.mdx @@ -4,6 +4,7 @@ description: Agent frameworks that run a perception-plan-act loop against a Stee --- + diff --git a/content/docs/cookbook/topics/browser-automation.mdx b/content/docs/cookbook/topics/browser-automation.mdx index 4a9f9936..4ba0f7de 100644 --- a/content/docs/cookbook/topics/browser-automation.mdx +++ b/content/docs/cookbook/topics/browser-automation.mdx @@ -15,9 +15,3 @@ description: "Drive a cloud browser with familiar automation libraries: Playwrig - -## Related integrations - -- [Steel + Playwright](/integrations/playwright): Drive a Steel browser with Playwright over CDP. -- [Steel + Puppeteer](/integrations/puppeteer): Drive a Steel browser with Puppeteer over CDP. -- [Steel + Selenium](/integrations/selenium): Drive a Steel browser with Selenium. diff --git a/content/docs/cookbook/topics/browser-use.mdx b/content/docs/cookbook/topics/browser-use.mdx index f18bf95d..e45ad6d6 100644 --- a/content/docs/cookbook/topics/browser-use.mdx +++ b/content/docs/cookbook/topics/browser-use.mdx @@ -8,7 +8,3 @@ description: Agent recipes built on the browser-use framework. - -## Related integrations - -- [Steel + Browser Use](/integrations/browser-use): Set up Steel with the browser-use framework. diff --git a/content/docs/cookbook/topics/captchas.mdx b/content/docs/cookbook/topics/captchas.mdx index ea285a3a..3b9300ba 100644 --- a/content/docs/cookbook/topics/captchas.mdx +++ b/content/docs/cookbook/topics/captchas.mdx @@ -1,5 +1,5 @@ --- -title: CAPTCHAs +title: Captchas description: "Recipes that handle CAPTCHA challenges using Steel's CAPTCHA API." --- @@ -7,8 +7,3 @@ description: "Recipes that handle CAPTCHA challenges using Steel's CAPTCHA API." - -## Related guides - -- [Solving CAPTCHAs](/overview/stealth/captcha-solving): How Steel detects and solves CAPTCHA challenges. -- [Proxies](/overview/stealth/proxies): Route traffic through proxies to reduce CAPTCHA challenges. diff --git a/content/docs/cookbook/topics/computer-use.mdx b/content/docs/cookbook/topics/computer-use.mdx index 460ed6a6..b5fdefac 100644 --- a/content/docs/cookbook/topics/computer-use.mdx +++ b/content/docs/cookbook/topics/computer-use.mdx @@ -9,9 +9,3 @@ description: Model-native browser control where the LLM sees the screen and emit - -## Related integrations - -- [Steel + Claude Computer Use](/integrations/claude-computer-use): Point Claude's computer-use loop at a Steel session. -- [Steel + OpenAI Computer Use](/integrations/openai-computer-use): Point OpenAI's Computer Use Assistant at a Steel session. -- [Steel + Gemini Computer Use](/integrations/gemini-computer-use): Point Gemini Computer Use at a Steel session. diff --git a/content/docs/cookbook/topics/mobile.mdx b/content/docs/cookbook/topics/mobile.mdx index b25ca497..2927fe64 100644 --- a/content/docs/cookbook/topics/mobile.mdx +++ b/content/docs/cookbook/topics/mobile.mdx @@ -6,7 +6,3 @@ description: "Recipes targeting Steel's mobile browser environment." - -## Related integrations - -- [Steel + Claude Computer Use](/integrations/claude-computer-use): Drive Steel's mobile browser with Claude's computer-use model. diff --git a/content/docs/cookbook/topics/nextjs.mdx b/content/docs/cookbook/topics/nextjs.mdx index 1bce8ae0..39d8a017 100644 --- a/content/docs/cookbook/topics/nextjs.mdx +++ b/content/docs/cookbook/topics/nextjs.mdx @@ -4,5 +4,6 @@ description: Recipes that integrate Steel into a Next.js application. --- + diff --git a/content/docs/cookbook/topics/playwright.mdx b/content/docs/cookbook/topics/playwright.mdx index f26a3519..fa22b7b8 100644 --- a/content/docs/cookbook/topics/playwright.mdx +++ b/content/docs/cookbook/topics/playwright.mdx @@ -8,7 +8,3 @@ description: Recipes that use Playwright to drive a Steel session, either as the - -## Related integrations - -- [Steel + Playwright](/integrations/playwright): Set up Steel with Playwright and connect over CDP. diff --git a/content/docs/cookbook/topics/subagents.mdx b/content/docs/cookbook/topics/subagents.mdx index 9803708b..7b73ffd2 100644 --- a/content/docs/cookbook/topics/subagents.mdx +++ b/content/docs/cookbook/topics/subagents.mdx @@ -6,7 +6,3 @@ description: Multi-agent recipes where a lead orchestrator dispatches parallel s - -## Related integrations - -- [Steel + Claude Agent SDK](/integrations/claude-agent-sdk): Build the orchestrator and subagents on Anthropic's agent loop. diff --git a/content/docs/cookbook/topics/typed-output.mdx b/content/docs/cookbook/topics/typed-output.mdx index c55df93c..822e5777 100644 --- a/content/docs/cookbook/topics/typed-output.mdx +++ b/content/docs/cookbook/topics/typed-output.mdx @@ -12,9 +12,3 @@ description: Agents that return structured, schema-validated results instead of - -## Related integrations - -- [Steel + Pydantic AI](/integrations/pydantic-ai): Return typed, schema-validated agent results with Pydantic AI. -- [Steel + LangGraph](/integrations/langgraph): Return typed agent results with an explicit LangGraph state machine. -- [Steel + Mastra](/integrations/mastra): Return typed agent results with Mastra. diff --git a/content/docs/cookbook/trigger-dev-browser-job.mdx b/content/docs/cookbook/trigger-dev-browser-job.mdx index d1d77133..acd83641 100644 --- a/content/docs/cookbook/trigger-dev-browser-job.mdx +++ b/content/docs/cookbook/trigger-dev-browser-job.mdx @@ -3,13 +3,13 @@ title: Run a Steel browser job with Trigger.dev description: Queue a Trigger.dev task that creates a Steel session, drives Playwright over CDP, saves artifacts, and releases the browser in cleanup. --- - + - + -This recipe runs browser automation as a [queued background job](/cookbook/topics/triggerdev). The request +This recipe runs browser automation as a queued background job. The request path only enqueues `steel-browser-job`; the task creates a Steel session, connects Playwright over CDP, extracts a page summary, saves artifacts, and releases the session in `finally`. @@ -23,7 +23,7 @@ export const browserJob = task({ retry: { maxAttempts: 3 }, queue: { concurrencyLimit: 2 }, run: async (payload) => { - session = await steel.sessions.create({ sessionTimeout: 600000 }); + session = await steel.sessions.create({ timeout: 600000 }); browser = await chromium.connectOverCDP( `${session.websocketUrl}&apiKey=${steelApiKey}` ); diff --git a/content/docs/cookbook/vercel-ai-sdk-nextjs.mdx b/content/docs/cookbook/vercel-ai-sdk-nextjs.mdx index 63b392cd..54cfa58e 100644 --- a/content/docs/cookbook/vercel-ai-sdk-nextjs.mdx +++ b/content/docs/cookbook/vercel-ai-sdk-nextjs.mdx @@ -3,13 +3,13 @@ title: Stream a browser agent into a Next.js chat app description: A Next.js App Router chat app where a Vercel AI SDK agent drives a Steel cloud browser with embedded Live View. --- - + - + -A [Next.js](/cookbook/topics/nextjs) chat app where an [AI SDK v6](/integrations/ai-sdk) agent drives a Steel cloud browser server-side and streams every tool call back into the UI. `useChat` on the client posts to `/api/chat`; that route calls `streamText` with four Steel-backed tools (`openSession`, `navigate`, `snapshot`, `extract`). Each tool call surfaces as a typed `tool-*` part on the message stream, and a Live View iframe on the right lights up the moment the agent opens a session. +A Next.js chat app where an AI SDK v6 agent drives a Steel cloud browser server-side and streams every tool call back into the UI. `useChat` on the client posts to `/api/chat`; that route calls `streamText` with four Steel-backed tools (`openSession`, `navigate`, `snapshot`, `extract`). Each tool call surfaces as a typed `tool-*` part on the message stream, and a Live View iframe on the right lights up the moment the agent opens a session. ``` app/ @@ -90,7 +90,7 @@ The `/api/chat` route already declares `maxDuration = 120` and `runtime = "nodej ## Related recipes + - diff --git a/content/docs/cookbook/vercel-ai-sdk.mdx b/content/docs/cookbook/vercel-ai-sdk.mdx index d3d1aebb..3af491ab 100644 --- a/content/docs/cookbook/vercel-ai-sdk.mdx +++ b/content/docs/cookbook/vercel-ai-sdk.mdx @@ -3,13 +3,13 @@ title: Build a typed browser agent with the Vercel AI SDK description: Use Steel with the Vercel AI SDK v6 ToolLoopAgent for typed, tool-using browser agents. --- - + - + -The [Vercel AI SDK v6](https://ai-sdk.dev/docs/agents/overview) ships `ToolLoopAgent`, a [typed agent](/cookbook/topics/typed-output) that picks a tool, calls it, observes the result, and decides the next step. Give it tools that drive a Playwright page connected to a Steel session and you get a terminal browser agent with no UI scaffolding in the way. Steel's [AI SDK integration](/integrations/ai-sdk) covers the same pairing on its own. +The [Vercel AI SDK v6](https://ai-sdk.dev/docs/agents/overview) ships `ToolLoopAgent`, a typed agent that picks a tool, calls it, observes the result, and decides the next step. Give it tools that drive a Playwright page connected to a Steel session and you get a terminal browser agent with no UI scaffolding in the way. ```typescript const researchAgent = new ToolLoopAgent({ diff --git a/content/docs/cookbook/you-com-search.mdx b/content/docs/cookbook/you-com-search.mdx index 80874135..3082ed68 100644 --- a/content/docs/cookbook/you-com-search.mdx +++ b/content/docs/cookbook/you-com-search.mdx @@ -3,13 +3,13 @@ title: Combine You.com search with Steel browser actions description: Pair the You.com Search and Contents APIs with a Steel cloud browser in a search-then-act LangChain agent that prefers the cheap path and only opens a session when interaction is required. --- - + - + -A [search-then-act agent](/cookbook/topics/search): [You.com](https://you.com/) handles discovery and static extraction, Steel handles real browser actions. The agent gets five tools across two cost tiers and is told to prefer the cheap tier. The Steel session is opened lazily on the first `navigate` call, so a question that resolves on search alone never spins up a browser. +A search-then-act agent: [You.com](https://you.com/) handles discovery and static extraction, Steel handles real browser actions. The agent gets five tools across two cost tiers and is told to prefer the cheap tier. The Steel session is opened lazily on the first `navigate` call, so a question that resolves on search alone never spins up a browser. ```python tools = [youcom_search, youcom_contents, navigate, snapshot, click_text] @@ -42,7 +42,7 @@ async def youcom_contents(urls: list[str]) -> dict: r = await client.post( f"{YOU_BASE}/contents", json={"urls": urls, "formats": ["markdown"]}, - headers={"X-API-Key": YOUCOM_API_KEY, ...}, + headers={"X-API-Key": YDC_API_KEY, ...}, ) ... ``` @@ -88,7 +88,7 @@ result = await executor.ainvoke({"input": question}) ```bash cd examples/you-com-search -cp .env.example .env # set STEEL_API_KEY, ANTHROPIC_API_KEY, YOUCOM_API_KEY +cp .env.example .env # set STEEL_API_KEY, ANTHROPIC_API_KEY, YDC_API_KEY uv sync uv run playwright install chromium uv run main.py @@ -121,7 +121,7 @@ If the agent answers from search and contents alone, the `open_session`, `naviga - **Swap the cheap tool.** Replace `youcom_search` with the Research API (`https://api.you.com/v1/research`) when you want a multi-step reasoned answer instead of raw results. The agent gets fewer URLs but better-synthesized inputs. - **Add more browser actions.** `click_text` is the minimum interactive primitive. Add `fill(selector, text)`, `press(key)`, `wait_for_selector`, or `scroll` when the agent needs to operate forms or trigger lazy-loaded content. -- **Tighten the routing.** The `verbose=False` agent re-derives the routing each turn. For repeatable production flows, replace the agent with an explicit two-step pipeline: always run `youcom_search`, always run `youcom_contents` on the top hit, only call browser tools if a heuristic flag (response too short, contains "Please enable JavaScript," etc.) trips. +- **Tighten the routing.** The `verbose=False` agent re-derives the routing each turn. For repeatable production flows, replace the agent with an explicit two-step pipeline: always run `youcom_search`, always run `youcom_contents` on the top hit, only call browser tools if a heuristic flag (response too short, contains "Please enable JavaScript", etc.) trips. - **Trace with LangSmith.** Set `LANGSMITH_API_KEY` and `LANGSMITH_TRACING=true` in `.env`. No code changes; every tool call shows up at [smith.langchain.com](https://smith.langchain.com). - **Swap the model.** `ChatOpenAI(model="gpt-5-mini")` works without touching the tools. The system prompt is generic. - **Self-host.** Both Steel (open-source browser infra) and the cookbook are deployable; the You.com APIs are remote. For a fully self-hostable variant, replace `youcom_contents` with a local extractor (Trafilatura, Readability) and a search frontend like SearXNG, and keep Steel for the browser tier. @@ -133,7 +133,7 @@ If the agent answers from search and contents alone, the `open_session`, `naviga ## Related recipes + - diff --git a/cookbook.lock.json b/cookbook.lock.json index 3fa8efbe..c2afcc09 100644 --- a/cookbook.lock.json +++ b/cookbook.lock.json @@ -1,5 +1,5 @@ { "repo": "steel-dev/steel-cookbook", "ref": "main", - "sha": "e86cfbf8ba715cdbbc49fc2ef13e9fd7798695dc" + "sha": "e8ae071b522623f10950c1881389423082b6a0ae" }