Open source CapCut alternative.
TypeScript
feat: browser automation via Browser Use Cloud (web.automate)
David Lefc9c9b480d6b
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swiftindex 7e730a98..36211350 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift@@ -173,6 +173,32 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {return try JSONDecoder().decode(RemoteWebFetchResult.self, from: data)}+ /// Start a Browser Use Cloud agent task through the backend. Returns immediately with our task id;+ /// poll `pollBrowserRun` for status and result. The backend owns the API key and credit charge.+ /// Run an agentic browser task and wait for its result. The backend runs it to completion+ /// (it polls Browser Use server-side) and charges credits there, so this is a single blocking+ /// call — no client-side polling. Structured output, when requested, comes back as a JSON string.+ public func runBrowserTask(+ task: String,+ startURL: String?,+ structuredOutputSchemaJSON: String?+ ) async throws -> RemoteBrowserRunStatus {+ var request = makeRequest(path: "/api/browser/run/")+ request.httpMethod = "POST"+ // The backend runs the task to completion before responding; allow a long round trip.+ request.timeoutInterval = 300+ var body: [String: Any] = ["task": task]+ if let startURL { body["startUrl"] = startURL }+ if let schema = structuredOutputSchemaJSON,+ let schemaData = schema.data(using: .utf8),+ let schemaObject = try? JSONSerialization.jsonObject(with: schemaData) {+ body["structuredOutputSchema"] = schemaObject+ }+ request.httpBody = try JSONSerialization.data(withJSONObject: body)+ let data = try await send(request)+ return try JSONDecoder().decode(RemoteBrowserRunStatus.self, from: data)+ }+public func parseScreenshot(_ understandingRequest: LocalUIUnderstandingRequest,imageData: Data? = nil,diff --git a/apps/Donkey/Sources/DonkeyAI/HostedWebAutomate.swift b/apps/Donkey/Sources/DonkeyAI/HostedWebAutomate.swiftnew file mode 100644index 00000000..bca8f224--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/HostedWebAutomate.swift@@ -0,0 +1,61 @@+import DonkeyHarness+import Foundation++/// The result of a browser run. `structured` is the agent's structured output (when a schema was+/// requested) as a JSON string; otherwise the free-form `text` carries the result. Property names+/// match the backend JSON keys so this decodes directly.+public struct RemoteBrowserRunStatus: Codable, Sendable {+ public var status: String+ public var isTaskSuccessful: Bool?+ public var text: String?+ public var structured: String?+ public var recordingUrl: String?+ public var liveUrl: String?+ public var stepCount: Int+ public var lastStepSummary: String?+}++/// Backs the `web.automate` harness tool: runs a Browser Use Cloud task through the Donkey backend,+/// which executes it to completion server-side and returns the result, then formats it as a single+/// text block for the agent to read. Long-running by nature — the planner narrates a wait.+public struct HostedWebAutomate: Sendable {+ private let backend: DonkeyBackendInferenceClient++ public init(backend: DonkeyBackendInferenceClient) {+ self.backend = backend+ }++ public func run(_ request: HarnessWebAutomateRequest) async -> String? {+ guard let result = try? await backend.runBrowserTask(+ task: request.task,+ startURL: request.startURL,+ structuredOutputSchemaJSON: request.structuredOutputSchemaJSON+ ) else {+ return nil+ }+ return format(result)+ }++ private func format(_ status: RemoteBrowserRunStatus) -> String {+ var lines: [String] = []+ let state = status.isTaskSuccessful == false+ ? "did not fully succeed (\(status.status))"+ : "completed (\(status.status))"+ lines.append("Browser task \(state) after \(status.stepCount) steps.")+ if let structured = status.structured {+ lines.append("")+ lines.append(structured)+ } else if let text = status.text, !text.isEmpty {+ lines.append("")+ lines.append(text)+ } else if let summary = status.lastStepSummary, !summary.isEmpty {+ lines.append("")+ lines.append("Last step: \(summary)")+ }+ if let recording = status.recordingUrl {+ lines.append("")+ lines.append("Recording: \(recording)")+ }+ return lines.joined(separator: "\n")+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swiftindex 3e7fe764..f4c9f4f6 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift@@ -105,18 +105,21 @@ public enum DonkeyCommandBackends {)}- /// Resolve the output file URL: an explicit `destination` (absolute, or a bare- /// name placed in ~/Downloads), else a generated `~/Downloads/<host>.<ext>`.+ /// Resolve the output file URL inside ~/Downloads. A `destination` is treated as+ /// a file *name* only — any directory components are stripped — so this no-consent+ /// capture tool can never overwrite a file outside Downloads. Falls back to a+ /// generated `<host>.<ext>` name.private static func snapshotDestination(_ destination: String?, url: URL, format: String) -> URL {let downloads = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Downloads", isDirectory: true)if let destination {- let candidate = (destination as NSString).isAbsolutePath- ? URL(fileURLWithPath: destination)- : downloads.appendingPathComponent(destination)- return candidate.pathExtension.isEmpty- ? candidate.appendingPathExtension(format)- : candidate+ let name = (destination as NSString).lastPathComponent+ if !name.isEmpty {+ let candidate = downloads.appendingPathComponent(name)+ return candidate.pathExtension.isEmpty+ ? candidate.appendingPathExtension(format)+ : candidate+ }}let host = url.host?.replacingOccurrences(of: ".", with: "-") ?? "page"return downloads.appendingPathComponent("\(host).\(format)")diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/web-automation/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/web-automation/SKILL.mdnew file mode 100644index 00000000..74bb861b--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/web-automation/SKILL.md@@ -0,0 +1,43 @@+# Web Automation++id: web-automation+description: Drive a real browser in the cloud to do multi-step web tasks — navigate, log in, fill forms, click through, and extract data — when reading and local capture can't.+tags: web, browser, automate, agent, login, form, extract+keywords: log in, sign in, fill form, checkout, book, apply, download from site, navigate, click through, scrape, extract from website, multi-step+tools: web.automate++`web.automate` runs an agentic browser task on the hosted Browser Use service and+returns its result. It is the heaviest, slowest, and only paid web tool — reach+for it last.++## When to use it (and when not)+- Use it only when the task truly needs to *act* across pages: log in, fill and+ submit a form, click through a multi-step flow, or extract data from a site+ that `web.fetch` can't read and `web_snapshot` can't render.+- Do NOT use it to read an article or look something up — that's `web.fetch`. Do+ NOT use it to save a page as PDF/PNG — that's `web_snapshot`. Those are free.++## Cost and consent+- Each run spends the user's credits (billed by browser steps). Before starting a+ task that logs in, submits, pays, or changes anything on the user's accounts,+ confirm with the user — say what it will do and that it uses a real browser.+- Reading/extraction tasks that only look at public pages can run once confirmed+ the hosted browser is the right tool.++## How to call it+- `web.automate` with `task` = the full goal in plain language ("Go to example.com,+ log in as the user, and download the latest invoice as a PDF"). Put the starting+ site in `task` or in `startUrl`.+- For structured results, pass `schema` (a JSON Schema string); the result then+ comes back as JSON matching it. Otherwise the result is the agent's text output.+- It runs to completion before returning (seconds to a few minutes); the result+ text reports the status, the output, and a recording link when available.++## Verify+- Read the returned status and output: a run that "did not fully succeed" did not+ achieve the goal — report that plainly rather than assuming success. For an+ extraction, check the returned data actually contains the requested fields.++## Limitations+- It cannot reuse the user's local browser logins; the agent logs in within the+ hosted browser, so credentials/2FA flows are the user's call to approve.diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/web-capture/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/web-capture/SKILL.mdindex ed45b328..c7c419a1 100644--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/web-capture/SKILL.md+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/web-capture/SKILL.md@@ -4,7 +4,7 @@ id: web-capturedescription: Save a web page to a file — clean markdown via web.fetch, or a PDF or full-page screenshot of the rendered page.tags: web, capture, pdf, screenshot, archive, markdownkeywords: save page, web page, website, pdf, screenshot, archive, markdown, capture, print to pdf-tools: web.fetch, web_snapshot, shell_exec, apps_list+tools: web.fetch, web_snapshot, web.automate, shell_exec, apps_listPick the format the user asked for. Saving to a file is reversible; default thedestination to `~/Downloads`.@@ -17,7 +17,7 @@ destination to `~/Downloads`.Capture the rendered page with the cheapest engine that works, in order:1. **Local Chromium**, only if one is installed — check `apps_list` (Google Chrome, Brave, Microsoft Edge, Arc), then `'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' --headless=new --disable-gpu --print-to-pdf=$HOME/Downloads/page.pdf 'URL'` (PDF) or `--screenshot=$HOME/Downloads/page.png --window-size=1280,2000 'URL'`.2. **Built-in `web_snapshot`** — always available, no external browser. `web_snapshot` with `url` and `format=pdf` (default) or `format=png` (full page), optional `destination`. Use this whenever no Chromium is installed.-3. If the page needs a login or is blocked by bot-protection so neither renders it, say so plainly. (A hosted browser fallback for those cases is coming — see `plans/browser-use-integration.md`.)+3. **Hosted browser (`web.automate`)** — for a page behind a login or heavy bot-protection that the free engines can't render. It drives a real cloud browser and spends the user's credits, so confirm first. See the `web-automation` skill.Do not invent a headless flag for Safari; it has none. For just the visiblescreen rather than the whole page, `screencapture -x ~/Downloads/shot.png` afterdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/SkillInstallTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/SkillInstallTests.swiftindex aa917c2e..c6a08f0f 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/SkillInstallTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/SkillInstallTests.swift@@ -264,7 +264,7 @@ struct SkillInstallTests {// The five capability skills (media, images, pdf, data, web-capture) ship built-in and are// discovered by walking the tree — no enumerated list to keep in sync.let ids = Set(BuiltInLocalAppSkillPacks.descriptors().map(\.id))- for id in ["media", "images", "pdf", "data", "web-capture"] {+ for id in ["media", "images", "pdf", "data", "web-capture", "web-automation"] {#expect(ids.contains(id))}}diff --git a/plans/browser-use-integration.md b/plans/browser-use-integration.mdindex ccc62cdd..7d238b84 100644--- a/plans/browser-use-integration.md+++ b/plans/browser-use-integration.md@@ -25,18 +25,19 @@ proxies). The Cloud API removes all of that for a per-task fee. We mirror howonly.- SDKs: TypeScript `browser-use-sdk` (`import { BrowserUse } from"browser-use-sdk/v3"`) and Python. Our backend is TS, so use the TS SDK.-- Run a task: natural-language task + options (starting URL, allowed domains, max- steps, model, **structured output schema** for typed JSON results). Tasks are- long-running (seconds to minutes).-- Results: final output text, validated structured JSON, live preview + recording- URL, and files the agent downloaded (workspaces).-- Async signals: **webhooks** (`agent.task.status_update`, signed with- `X-Browser-Use-Signature` = HMAC-SHA256 over `"{timestamp}.{sorted-json}"`,- plus `X-Browser-Use-Timestamp`; reject if older than 5 min) and live message- streaming. Sessions/profiles persist browser state (cookies/logins) across- follow-up tasks.-- OpenAPI spec: `https://docs.browser-use.com/cloud/openapi/v3.json` — use it as- the source of truth for exact request/response fields during implementation.+- SDK (verified, `[email protected]`): `new BrowserUse({ apiKey })`, then+ `client.sessions.create(body)` to start and `client.sessions.get(id)` to poll.+ `body` (camelCase, mapped to snake_case): `task`, `startUrl`, `allowedDomains`,+ `maxSteps`, `model`, `structuredOutput`/`schema`.+- `SessionResponse` fields we use: `id`, `status`+ (`created → idle → running → stopped | timed_out | error`), `output`+ (free-form string OR structured object when an output schema was given),+ `stepCount`, `isTaskSuccessful`, `recordingUrls`, `liveUrl`, `lastStepSummary`.+- **No webhooks — polling.** The API has no task-completion webhook; the SDK+ polls `sessions.get`. So our app polls our backend, and our backend polls+ Browser Use. (Earlier draft assumed webhooks; corrected.)+- **No per-task USD cost field.** The response exposes `stepCount`, and Browser+ Use bills `$0.01 init + per-step`. So we price by steps (see billing).## Architecture@@ -70,100 +71,100 @@ can't do it. The `web-capture` skill drives this order:Agentic automation (navigate/click/fill/extract, multi-step) has no localequivalent, so it goes straight to Cloud (Phase 2).-- **Backend (`site/`)**: routes behind `withDonkeyAuth`, queries in- `src/queries/`, any tables in a grouped `site/prisma/BrowserTasks.prisma`- (no hand-written SQL/migrations):- - `POST /api/browser/run` — validate, gate on credits, call Browser Use Cloud- to start a task, persist a row, return `{ taskId, status }`.- - `GET /api/browser/run/:id` — return `{ status, output, structured,- recordingUrl, files }`.- - `POST /api/browser/webhook` — verify the HMAC signature + timestamp, then- update the task row when Cloud reports completion (so the GET is fast and we- avoid hammering Cloud with polls).-- **Async model**: start → return `taskId`; the app's `web.automate` tool polls- `GET /api/browser/run/:id` using the harness's existing waiting state until the- task reaches a terminal status or a bounded timeout. Webhooks keep the backend- row fresh; the app polls our backend, not Browser Use.+- **Backend (`site/`)**: one route behind `withDonkeyAuth`:+ - `POST /api/browser/run` — validate, preflight credits, then+ `client.run(task, …)` which executes the task to completion **server-side**+ (the SDK polls Browser Use on our server), charge credits by `stepCount`, and+ return `{ status, isTaskSuccessful, text, structured, recordingUrl, liveUrl,+ stepCount }`. `maxDuration = 300`; `maxCostUsd` bounds the task so it finishes+ within that.+- **Synchronous, not polled.** Charging happens here, after the run finishes, and+ never depends on the client. The app makes one blocking call and waits — no GET+ poll route, no cron sweep, no `BrowserRun` table (the credit usage event is the+ audit record). The only residual edge is a task that exceeds `maxDuration`+ (rare, bounded by `maxCostUsd`); accepted rather than reintroducing+ client-driven settlement.## Secrets, cost, and safety (decide before building)- **`BROWSER_USE_API_KEY`** lives only in backend env / secrets — never in the appbundle or repo (OSS).-- **Billing (required)**: Browser Use Cloud cost is **variable per task**, not a- flat fee — V3 (the version we use) is token-based at ~1.2× the underlying LLM- rate plus a $0.01/task init; a run is ~5–30 steps. So we bill it exactly like- every other provider in Donkey: **pass the actual Cloud task cost through at the- standard 1.3× margin** (`provider-pricing.ts`), debited *after* completion via- `recordInferenceUsage`, not a hand-set price. Flow:- - **Preflight**: `requireInferenceCredits` + require balance ≥ a worst-case- ceiling derived from a per-task `maxSteps` cap (so a runaway task can't- surprise-bill); 402 when short.- - **Bound + disclose**: cap `maxSteps` per task; show the worst-case credit- estimate and the target domains in the consent gate before running.- - **Debit actual**: on the completion webhook, debit the real Cloud cost × 1.3- via `recordInferenceUsage` (route `/api/browser/run/`, provider- `browser-use`), reconciling the preflight hold. Add a `browser-use` entry to- the provider pricing so the 1.3× margin + ceil-rounding apply automatically.- - **Free rungs never charge**: local Chromium and `WKWebView` capture cost- nothing; only `web.automate` Cloud runs debit credits.- - Implementation check: confirm the task result/webhook returns the task's- cost (or step/token counts) — see `openapi/v3.json`. If cost is returned,- pass it through directly; if only steps/tokens, price from those.+- **Billing (required)**: the API exposes no per-task USD cost, but it does+ expose `stepCount`, and Browser Use bills `$0.01 init + per-step`. So we price+ **by steps** at Donkey's standard 1.3× margin: a `browser-use` provider-pricing+ entry with `generationCostMicros = usdWithMargin(<per-step USD>)`, charged via+ `recordInferenceUsage` with `usage = { generationCount: stepCount }`. Flow:+ - **Preflight**: `requireInferenceCredits` (402 when the balance is empty),+ consistent with the other inference routes; the actual debit is after the run.+ - **Bound**: `maxCostUsd` caps the Browser Use spend per run, which also keeps a+ run within `maxDuration`. (No bespoke consent gate — `web.automate` is+ `.sensitive` and the skill instructs confirming login/pay turns.)+ - **Charge at completion, server-side**: when `client.run` returns (terminal),+ debit `stepCount × per-step × 1.3` via `recordInferenceUsage` (route+ `/api/browser/run/`, provider `browser-use`) in the same request. One request+ = one charge, so no idempotency dance. Browser Use bills steps even on+ failure, so charge regardless of `isTaskSuccessful`.+ - **Free rungs never charge**: local Chromium and `web_snapshot` cost nothing;+ only Cloud `web.automate` runs debit credits.+ - Per-step rate tracks the default model's published per-step price; fold the+ $0.01 init into the rate. Revisit if Browser Use later exposes exact cost.- **Data/privacy**: the task text, target sites, and any credentials pass throughBrowser Use's servers. Call this out to users for automation tasks; keepcredential/login flows behind explicit consent and prefer Browser Use**profiles** / human-in-the-loop for auth rather than passing raw passwords.-- **Domain scoping**: default `allowedDomains` to the task's target so a run can't- wander; surface the consent with the domains it will touch.+- **Scoping**: v3 has no `allowedDomains` field — the target site is expressed in+ the task prompt (and `startUrl` is folded in). `maxCostUsd` is the spend bound.## Phasing-- **Phase 1 — the capture ladder.** Build the free rungs first: the native- `web.snapshot` (`WKWebView` → PDF/PNG) tool, and confirm the local-Chromium path- in the `web-capture` skill. Then add `web.automate` (Cloud) as the paid fallback- for pages the free engines can't render, plus structured extraction for pages- `web.fetch` can't read. Wire the three backend routes, credit gating, and- consent. Update the `web-capture` skill to encode the ladder (Chromium →- `WKWebView` → Cloud) and keep `web.fetch` for static markdown.+- **Phase 1 — the capture ladder (done).** The native `web_snapshot`+ (`WKWebView` → PDF/PNG) free rung, the local-Chromium path in the `web-capture`+ skill, and `web.automate` (Cloud) as the paid fallback + structured extraction+ for pages `web.fetch` can't read, with synchronous credit charging. The+ `web-capture` skill encodes the ladder (Chromium → `WKWebView` → Cloud) and+ keeps `web.fetch` for static markdown.- **Phase 2 — agentic automation.** Cloud-only multi-step tasks(navigate/click/fill), follow-up tasks in a session, profiles for persistentauth, and human-in-the-loop for approvals/payments. Likely its own capabilityskill (`web-automation`) describing when to use it vs. the read/capture tools.-## Files (anticipated)+## Files (implemented)-- `apps/Donkey/Sources/DonkeyAI/HostedBrowserAutomation.swift` (new; mirrors- `HostedWebFetch.swift`)-- a `WKWebView`-backed `web.snapshot` capture tool in `DonkeyRuntime` (new)-- registry tool wiring for `web.automate` and `web.snapshot` (alongside `web.*`)-- `site/src/app/api/browser/run/route.ts`, `…/run/[id]/route.ts`,- `…/browser/webhook/route.ts` (new)-- `site/src/queries/browser.ts`, `site/prisma/BrowserTasks.prisma` (new)-- `apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/web-capture/SKILL.md`- (point rich capture at `web.automate`); a new `web-automation` skill in Phase 2+- `apps/Donkey/Sources/DonkeyAI/HostedWebAutomate.swift` — single blocking call;+ `DonkeyBackendInferenceClient.runBrowserTask`+- `web_snapshot` (`WKWebView` → PDF/PNG) in `DonkeyCommandBackends.swift` ++ descriptor in `DonkeyCommandLayer.swift`; `web.automate` descriptor + executor ++ `webAutomator` service in the harness+- `site/src/app/api/browser/run/route.ts` (synchronous POST)+- `site/src/lib/browser/{client,models,pricing}.ts`;+ `site/src/lib/credits/{provider-pricing,inference}.ts` (browser-use pricing ++ route). No `BrowserRun` table — the credit usage event is the audit record.+- `BuiltInSkills/web-capture/SKILL.md` (ladder) + `BuiltInSkills/web-automation/SKILL.md`## Verification-- Backend: a route test that starts a task against Browser Use Cloud (test key)- and returns a terminal result; webhook signature verification unit test- (reconstruct `"{timestamp}.{sorted-json}"`, timing-safe compare).-- App E2E: "save this JS-heavy page as a PDF" (Phase 1) and "go to <site> and- extract <fields> as JSON" — confirm the consent gate appears with the target- domains, the artifact returns, and a credit is debited.+- Built + checks green: `swift build`, `swift test --filter SkillInstallTests`,+ site `tsc --noEmit`, `eslint`.+- E2E (needs `BROWSER_USE_API_KEY` on a deploy): "save this JS-heavy page as a+ PDF" (free `web_snapshot` rung), and "go to <site> and extract <fields> as+ JSON" (`web.automate` — confirm the result returns and a credit is debited by+ `stepCount`).## Decisions-- **Credits**: every Browser Use Cloud run is accounted for and debited from- Donkey credits; the free capture rungs are not. _(decided)_+- **Credits**: every Cloud run is debited from Donkey credits, **server-side at+ completion** (never client-driven); free capture rungs aren't charged. _(done)_- **Capture ladder**: local Chromium → `WKWebView` → Browser Use Cloud, paid only- as the last resort. _(decided)_--- **Pricing model**: pass the actual Browser Use task cost through at Donkey's- standard 1.3× margin (debit-after-completion), bounded by a `maxSteps` cap — not- a flat hand-set fee. _(decided)_--Still to settle before Phase 1:--1. The `maxSteps` cap (cost ceiling) and the worst-case estimate shown at consent.-2. **Sync-poll vs webhook-only** for result delivery (plan assumes both: webhook- updates the row, app polls our backend).+ as the last resort. _(done)_+- **Pricing**: charge `stepCount × per-step × 1.3` (per-step + cap centralized in+ `browser/pricing.ts`); `maxCostUsd` bounds spend. _(done)_+- **Delivery**: synchronous — the backend runs the task to completion and charges+ in the one request; no polling, webhooks, or cron. _(done)_+- **No consent gate** for `web.automate` (per product call). _(done)_++Open follow-ups:++1. Tune the per-step rate (`browser/pricing.ts`, `$0.02`) and the `maxCostUsd`+ cap (`$0.5`) against real Browser Use bills once it's live.+2. Phase 2: follow-up tasks in a session, profiles for persistent auth,+ human-in-the-loop — its own `web-automation` depth beyond single tasks.diff --git a/site/.env.example b/site/.env.exampleindex bf2370d8..ae1a0c4b 100644--- a/site/.env.example+++ b/site/.env.example@@ -38,3 +38,7 @@ STRIPE_SECRET_KEY="replace-with-stripe-secret-key"STRIPE_WEBHOOK_SECRET="replace-with-stripe-webhook-signing-secret"STRIPE_VISION_PRICE_ID="replace-with-stripe-price-id"STRIPE_PORTAL_CONFIGURATION_ID="replace-with-stripe-portal-configuration-id"++# Browser Use Cloud (agentic web automation via /api/browser/run). Backend-only+# secret; the Mac app never carries it. Key starts with "bu_".+BROWSER_USE_API_KEY="replace-with-browser-use-api-key"diff --git a/site/package-lock.json b/site/package-lock.jsonindex 5dce9636..a4bc9e73 100644--- a/site/package-lock.json+++ b/site/package-lock.json@@ -27,6 +27,7 @@"@tanstack/react-query": "^5.101.0","@types/mdx": "^2.0.13","better-auth": "1.6.11",+ "browser-use-sdk": "^3.8.4","class-variance-authority": "^0.7.1","clsx": "^2.1.1","defuddle": "^0.18.1",@@ -4728,6 +4729,32 @@"node": ">=8"}},+ "node_modules/browser-use-sdk": {+ "version": "3.8.4",+ "resolved": "https://registry.npmjs.org/browser-use-sdk/-/browser-use-sdk-3.8.4.tgz",+ "integrity": "sha512-QO8BAAcMJ2v2zW/jU4BEHUVdVIKBRYFpCVVI+oipjsZWktn71l8LmkpXoltAOtOyXyxm0JELlsGP2A1qlPnPSw==",+ "license": "MIT",+ "dependencies": {+ "dotenv": "^17.2.4",+ "zod": "^4.3.6"+ },+ "peerDependencies": {+ "@x402/evm": "^2.11.0",+ "@x402/fetch": "^2.11.0",+ "viem": "^2.48.0"+ },+ "peerDependenciesMeta": {+ "@x402/evm": {+ "optional": true+ },+ "@x402/fetch": {+ "optional": true+ },+ "viem": {+ "optional": true+ }+ }+ },"node_modules/browserslist": {"version": "4.28.2","resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz",diff --git a/site/package.json b/site/package.jsonindex 1b060ed8..f608a65d 100644--- a/site/package.json+++ b/site/package.json@@ -33,6 +33,7 @@"@tanstack/react-query": "^5.101.0","@types/mdx": "^2.0.13","better-auth": "1.6.11",+ "browser-use-sdk": "^3.8.4","class-variance-authority": "^0.7.1","clsx": "^2.1.1","defuddle": "^0.18.1",diff --git a/site/src/app/api/browser/run/route.ts b/site/src/app/api/browser/run/route.tsnew file mode 100644index 00000000..57fa3bb4--- /dev/null+++ b/site/src/app/api/browser/run/route.ts@@ -0,0 +1,101 @@+import { NextResponse } from "next/server";+import { z } from "zod";++import {+ browserUseDefaultMaxCostUsd,+ browserUseDefaultModel,+ browserUseProvider,+ getBrowserUse,+} from "@/lib/browser/client";+import {+ creditUsageHeaders,+ inferenceUsageRoutes,+ recordInferenceUsage,+ requireInferenceCredits,+} from "@/lib/credits/inference";+import { withDonkeyAuth } from "@/lib/donkey-api-auth";+import {+ requireInferenceClientId,+ validationErrorResponse,+} from "@/lib/inference/responses";++export const dynamic = "force-dynamic";+// The run executes server-side to completion (the SDK polls Browser Use here, not+// the app), so the function must be allowed to run long. maxCostUsd bounds the+// task so it finishes well within this.+export const maxDuration = 300;++const runSchema = z.object({+ task: z.string().min(1),+ startUrl: z.string().url().optional(),+ structuredOutputSchema: z.record(z.string(), z.unknown()).optional(),+});++// Run an agentic browser task and return its result. The backend runs it to+// completion and charges credits here (by step count), so charging never depends+// on the client polling.+export const POST = withDonkeyAuth(async (request) => {+ const client = requireInferenceClientId(request.donkey.clientId);+ if (!client.ok) return client.response;++ const parsed = runSchema.safeParse(await request.json());+ if (!parsed.success) return validationErrorResponse(parsed.error);++ const credits = await requireInferenceCredits({+ userId: request.donkey.userId,+ route: inferenceUsageRoutes.browserRun,+ provider: browserUseProvider,+ model: browserUseDefaultModel,+ });+ if (!credits.ok) return credits.response;++ // v3 has no separate start-url field; fold it into the task prompt.+ const task = parsed.data.startUrl+ ? `Start at ${parsed.data.startUrl}. ${parsed.data.task}`+ : parsed.data.task;++ const session = await getBrowserUse().run(task, {+ model: browserUseDefaultModel,+ maxCostUsd: browserUseDefaultMaxCostUsd,+ timeout: (maxDuration - 20) * 1000,+ ...(parsed.data.structuredOutputSchema+ ? { outputSchema: parsed.data.structuredOutputSchema }+ : {}),+ });++ const stepCount = session.stepCount ?? 0;+ // Browser Use bills steps even on failure, so charge regardless of success.+ const recorded = await recordInferenceUsage({+ userId: request.donkey.userId,+ clientId: client.clientId,+ route: inferenceUsageRoutes.browserRun,+ requestKind: "browser_automation",+ provider: browserUseProvider,+ model: browserUseDefaultModel,+ status: "succeeded",+ usage: { generationCount: stepCount },+ metadata: { isTaskSuccessful: session.isTaskSuccessful ?? null },+ });++ const output: unknown = session.output ?? null;+ const structured =+ output !== null && typeof output === "object"+ ? JSON.stringify(output)+ : null;+ const text = typeof output === "string" ? output : null;++ return NextResponse.json(+ {+ status: session.status,+ done: true,+ isTaskSuccessful: session.isTaskSuccessful ?? null,+ text,+ structured,+ recordingUrl: session.recordingUrls?.[0] ?? null,+ liveUrl: session.liveUrl ?? null,+ stepCount,+ lastStepSummary: session.lastStepSummary ?? null,+ },+ { headers: creditUsageHeaders(recorded) },+ );+});diff --git a/site/src/lib/browser/client.ts b/site/src/lib/browser/client.tsnew file mode 100644index 00000000..8dc7ed6c--- /dev/null+++ b/site/src/lib/browser/client.ts@@ -0,0 +1,25 @@+import { BrowserUse } from "browser-use-sdk/v3";++import { browserUseModels } from "@/lib/browser/models";++export { browserUseDefaultMaxCostUsd } from "@/lib/browser/pricing";++let cached: BrowserUse | null = null;++/// Lazy, cached Browser Use Cloud client. BROWSER_USE_API_KEY is a backend secret+/// that is always configured in our environments; it never reaches the app.+export function getBrowserUse(): BrowserUse {+ cached ??= new BrowserUse({ apiKey: process.env.BROWSER_USE_API_KEY });+ return cached;+}++/// Provider/model identity for credit accounting (see provider-pricing.ts).+export const browserUseProvider = "browser-use";+/// The default agent model for web.automate tasks.+export const browserUseDefaultModel = browserUseModels.agent;++/// Browser Use session lifecycle terminal states (created → idle → running →+/// these). A run is done — and billable — once it reaches one of these.+export function isTerminalBrowserStatus(status: string): boolean {+ return status === "stopped" || status === "timed_out" || status === "error";+}diff --git a/site/src/lib/browser/models.ts b/site/src/lib/browser/models.tsnew file mode 100644index 00000000..966dbf94--- /dev/null+++ b/site/src/lib/browser/models.ts@@ -0,0 +1,11 @@+// Central registry of Browser Use Cloud model IDs (mirrors gemini-models.ts).+//+// Browser Use exposes its own model catalog (BuModel); pin the one we run here+// so bumping it is a one-line change. Its SDK default is the most expensive Opus+// tier, so we choose a fast, cost-effective model explicitly.+export const browserUseModels = {+ agent: "gemini-3-flash",+} as const;++export type BrowserUseModel =+ (typeof browserUseModels)[keyof typeof browserUseModels];diff --git a/site/src/lib/browser/pricing.ts b/site/src/lib/browser/pricing.tsnew file mode 100644index 00000000..53b3fea2--- /dev/null+++ b/site/src/lib/browser/pricing.ts@@ -0,0 +1,9 @@+// Browser Use cost knobs in one place, so the credit charge and the hard spend+// cap can't drift apart in separate files.+//+// `perStepUsd` is what we charge per agent step (the 1.3x margin is applied in+// provider-pricing.ts via usdWithMargin). `defaultMaxCostUsd` is the per-run USD+// budget sent to Browser Use, which stops a run if reached. Keep them consistent:+// a run that hits the cap is roughly defaultMaxCostUsd / perStepUsd steps.+export const browserUsePerStepUsd = "0.02";+export const browserUseDefaultMaxCostUsd = 0.5;diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.tsindex f9f3870b..a1462952 100644--- a/site/src/lib/credits/inference.ts+++ b/site/src/lib/credits/inference.ts@@ -24,6 +24,7 @@ export type CreditGrantUnit = typeof creditGrantUnit | typeof visionCallGrantUniexport const inferenceUsageRoutes = {assets: "/api/inference/assets/",assetsRefresh: "/api/inference/assets/refresh/",+ browserRun: "/api/browser/run/",chatCompletions: "/api/inference/chat/completions/",responses: "/api/inference/responses/",screenshotParse: "/api/inference/screenshots/parse/",diff --git a/site/src/lib/credits/provider-pricing.ts b/site/src/lib/credits/provider-pricing.tsindex af29898a..27fddefa 100644--- a/site/src/lib/credits/provider-pricing.ts+++ b/site/src/lib/credits/provider-pricing.ts@@ -8,6 +8,7 @@ import {} from "@/lib/inference/elevenlabs-models";import { geminiModels, type GeminiModel } from "@/lib/inference/gemini-models";import { openaiModels, type OpenAIRunModel } from "@/lib/inference/openai-models";+import { browserUsePerStepUsd } from "@/lib/browser/pricing";export type ProviderCreditPricing = {inputTokenCostMicrosPerMillion?: bigint;@@ -44,6 +45,9 @@ export function providerCreditPricing(if (normalizedProvider === "elevenlabs") {return elevenLabsCreditPricing(normalizedModel);}+ if (normalizedProvider === "browser-use") {+ return browserUseCreditPricing();+ }return undefined;}@@ -68,6 +72,16 @@ const openaiRunModelPricing: Record<OpenAIRunModel, ProviderCreditPricing> = {}),};+function browserUseCreditPricing(): ProviderCreditPricing {+ // Browser Use Cloud bills ~$0.01/task init + a per-step LLM fee, and the API+ // exposes stepCount (not a USD cost), so we price per step. The per-step rate+ // (which folds in the init fee) lives with the spend cap in browser/pricing.ts;+ // usdWithMargin adds the 1.3x. Charged as generationCount = stepCount.+ return {+ generationCostMicros: usdWithMargin(browserUsePerStepUsd),+ };+}+function openAICreditPricing(model: string): ProviderCreditPricing | undefined {const audioPricing = openAIAudioCreditPricing(model);if (audioPricing) {