Open source CapCut alternative.
TypeScript
chore(site): delete the desktop agent's leftover inference routes
David Le99718eac5613
diff --git a/apps/Donkey/docs/fast-command-layer-and-gemini-live.md b/apps/Donkey/docs/fast-command-layer-and-gemini-live.mddeleted file mode 100644index 4d60d5cd..00000000--- a/apps/Donkey/docs/fast-command-layer-and-gemini-live.md+++ /dev/null@@ -1,202 +0,0 @@-# Fast Donkey: tool-first Command Layer + always-on Gemini Live--> **Status: implemented end to end.** Command Layer (Phase 1) and the always-on Gemini Live-> session (Phase 2) are built, unit-tested, and wired into the overlay. The backend mints-> short-lived Vertex AI OAuth tokens (`POST /api/inference/live-token/`), the client connects-> directly to the Vertex Live websocket with a Bearer token, text/audio route through the session,-> tool calls execute against the Command Layer, and the mic can stream continuously. Gemini Live is **enabled by default** and takes over once it-> connects; if it can't authenticate it stays disconnected and the existing pipeline runs-> unchanged. The text path is verified end-to-end against real Vertex credentials by-> `GeminiLiveCommandSessionLiveSmokeTests` (mint token → websocket → `setupComplete` → text turn-> → tool call → Command Layer → result). Remaining work is live verification of the optional-> microphone/audio input.--## Context--Donkey is text-first, but slow to *act*. Historically it could only act two ways: generate-AppleScript (a second model round-trip) or fall into a vision loop that screenshots and-re-prompts every turn with a fixed 1.2s sleep (`UserQueryCommandHandler.swift:727`, `:805`).-There was no fast "just do it" substrate — no `open`, no native command.--The goal: **tool-first, screen-last.** Give the model a set of fast, deterministic native tools,-and let an always-on Gemini Live session drive them from text (audio optional), only looking at-the screen when a task genuinely needs visible state.--```-text (always) ─┐-audio (optional) ─┤→ Gemini Live session ──tool call──▶ Command Layer ──result──▶ back to Live-screenshot (only when needed) ─┘ (fast, native, in-process; no screenshot/AX)-```--## Phase 1 — Command Layer--Fast native, in-process tools the model calls directly. Under ~500ms, no screenshot, no AX tree.-A deliberately small set:--| Tool | Implementation |-|---|---|-| `shell_exec` | runs a safe, single-line shell command via `/bin/zsh -c` and returns its output — the primary, general-purpose tool |-| `apps_list` | reuses `MacLocalAppAvailabilityProvider.installedApplications()` (Spotlight-backed, names + bundle ids, includes Apple native apps) + running apps so the model targets exact names instead of guessing; the installed list is paginated (`filter`/`offset`/`limit`, with `hasMore`/`nextOffset` in the result) so the full catalog survives the response cap |-| `app_skill` | looks up the installed operating playbook (skill pack) for a specific app — discovered by the skill's `apps:` frontmatter, never a hardcoded list — and advertises the skill's validated scripts |-| `skill_run` | executes a validated script an installed skill ships (by the `skillID`/`scriptID` that `app_skill` advertised) — the generic native fast path for any skill-covered multi-step workflow a one-liner can't reproduce (e.g. the `music-media` search→play script) |--`shell_exec` is the **primary, general-purpose tool** (the same capability the competitor's-Realtime setup exposes) — listed first and prioritized in the system instruction. It handles most-requests directly: opening/quitting/controlling apps (`open -a Spotify`, `osascript -e '…'`),-changing settings, opening URLs (`open https://…`), and reading system state. Earlier dedicated-tools (`app.open`, `app.quit`, `browser.open_url`, `system.set_volume`) were **removed** as-redundant once `shell_exec` could do them reliably; what remains is generic — `apps_list`-(discovery is awkward via raw shell) and the `app_skill`/`skill_run` pair (skill discovery and-validated-script execution; the earlier hardcoded `music_play` tool became the `music-media`-skill's script, reachable through them). The-model is told to send only safe single-line commands; a backstop guardrail in-`DonkeyCommandBackends` enforces single-line input, a length cap, and a hard ~12s timeout-(SIGTERM→SIGKILL). Unsafe commands are caught by a **command-word** check on each pipeline/segment-leading executable (so bare `rm`, `/bin/rm`, or a denied command inside `$(…)` is caught) plus a-short list of dangerous substrings (`do shell script`, `| sh`, redirects to `/dev`/`/system`/…) —-chosen over the earlier substring denylist, which both missed bare destructive commands and-false-positived on benign redirects.--Tool results are returned to the Live model in full — `status`, `summary`, the execution metadata-(`stdout`, `stderr`, `exitCode`, `reason`), and any clarification `question` — so it can read-output and self-correct, or ask the user when a tool needs input.--**Where it lives / how it's wired.** `DonkeyHarness` only depends on `DonkeyContracts` and can't-import AppKit, so it follows the codebase's existing injected-closure pattern (like-`appleScriptExecutor`):--- `DonkeyHarness/DonkeyCommandLayer.swift` — tool descriptors + the shared `Command` enum- (single source of truth for the command names).-- `DonkeyRuntime/DonkeyCommandBackends.swift` — the native side effects.-- Injected via a new `HarnessBuiltInToolServices.commandExecutor` closure, wired in- `LocalAppUserQueryHarnessServices.builtInSkillBackedServices()`.-- Dispatched from the `default` branch of `BuiltInHarnessToolExecutors.execute` (before- `unknownTool`), and merged into `BuiltInHarnessToolCatalog.descriptors` so the tools surface to- the model automatically (they're `.reversible`/`.guardedInput`, so the planner's tool-name- filter keeps them).--This removes the AppleScript-generation hop and the vision loop for common commands.--## Phase 2 — Always-on Gemini Live session--A single Live session is the command brain. **Text input is always available; audio is an-optional second input** (the existing `MicrophoneWaveformMeter` gained an additive-`onAudioFrames` hook). Tool calls map to the Command Layer; screenshots are sent in-band only-when a task needs visible state.--Files (`DonkeyAI/` unless noted):--- `AIRealtimeSession.swift` — transport-agnostic protocol + event model (parallel to the- request/response `AIHTTPClient`; this one is a persistent socket).-- `GeminiLiveSession.swift` — `URLSessionWebSocketTask` actor: setup advertising the Command- Layer tools, context-window compression, session resumption, and transparent `goAway`/drop- reconnect.-- `GeminiLiveProtocol.swift` — `JSONSerialization`-based message builders + tolerant event parser- for the `BidiGenerateContent` wire format.-- `CommandLayerFunctionDeclarations.swift` — maps `HarnessToolDescriptor` → Gemini function- declarations.-- `GeminiLivePCM.swift` — mono float32 → raw 16kHz PCM16 LE (Live's input format).-- `GeminiLiveConfiguration.swift` — env config (below).-- `Donkey/GeminiLiveVoiceController.swift` — owns the session, runs the tool-call loop against a- Command Layer `HarnessToolRegistry`, and routes anything the model didn't tool-call back to the- normal pipeline via `onComplexRequest`.--### Routing decision — no string matching--Per requirement, the execution path is **always the model's decision**. There is no phrase table-or deterministic prefilter: the Live model chooses a tool call (act now) vs. asking for the screen-(visual task) vs. a plain reply. The speedup comes from the model *preferring* a fast tool, not-from bypassing it.--### Authentication — two paths (`GeminiLiveConnectionFactory`)--`GeminiLiveConnectionFactory.makeProvider` picks the connection path from config:--- **Developer API** (`GEMINI_API_KEY` set): connect directly to- `wss://generativelanguage.googleapis.com/ws/...BidiGenerateContent?key=<KEY>` with the hardcoded- `GeminiLiveConfiguration.defaultModel`. No backend round-trip. **Dev-only** — a client-held key;- not for production. That model is **audio-output only**: the session requests `AUDIO` response- modality (`GeminiLiveConnection.audioOutput`, on by default in code); tool calls and output- transcription still flow, which is all the Command Layer needs.-- **Vertex AI** (no key — production): the backend authenticates with Google Cloud OAuth- (service-account) credentials. `DonkeyBackendInferenceClient.mintLiveConnection()` →- `POST /api/inference/live-token/` (`site/src/app/api/inference/live-token/route.ts` +- `site/src/lib/inference/vertex-live.ts`, `cloud-platform` scope) mints a short-lived access token- and returns the Vertex Live websocket URL (`{location}-aiplatform.googleapis.com`, or- `aiplatform.googleapis.com` for `global`) + fully-qualified model path. The client connects with- `Authorization: Bearer <token>`; the long-lived credential never leaves the backend, and the token- is re-minted on every (re)connect. TEXT response modality.--Both produce a single `GeminiLiveConnection` (url + optional bearer + model + audioOutput).--### Configuration--Everything about the Live session — always-on, mic audio off, audio-output on, model ids, and the-Vertex `global` location — is fixed in code. Only two secrets are read from the environment; both are-optional depending on the auth path.--| Variable | Where | Meaning |-|---|---|---|-| `GEMINI_API_KEY` | client | **Dev-only secret.** When set, route the Live session through the Developer-API key path instead of Vertex. Default/production is keyless Vertex. |-| `GOOGLE_APPLICATION_CREDENTIALS_JSON` | backend | Vertex service-account JSON used to mint tokens. |--### Two models: realtime command vs vision--The realtime Live session (`gemini-live-2.5-flash`) is the **command brain** — fast, tool-calling, screen-last. When a task genuinely needs the screen, the **vision** path uses a stronger turn-based model (`gemini-3.5-flash`) via `GeminiVertexVisionPlanner`: it calls Vertex `generateContent` with the window screenshot and returns the single next click/type/key (coordinates in Gemini's 0–1000 space, mapped to the window). `gemini-3.5-flash` isn't a Live/bidi model, so vision is per-turn `generateContent`, not the socket — slower per turn (~7s) but markedly better grounding than the realtime model. Both run on Vertex with backend-minted tokens.--## How the overlay is wired--`UserQueryOverlayModel` owns a `GeminiLiveVoiceController`, started on init (gated by-`isEnabled`). `submitCommand` routes through the session whenever `liveController.isConnected`:-text goes to `sendText`; the model's tool calls run against the Command Layer and report a short-status back via `onActed`; anything not satisfied by a tool call comes back through-`onComplexRequest` → the full local pipeline (`runLocalCommand`, never re-entering Live). When the-session isn't connected, `submitCommand` runs the local pipeline exactly as before.-`UserQueryOverlayController` streams the mic's `onAudioFrames` into the session via-`streamLiveAudioFrames` (no-op unless audio is enabled and connected); a batch voice transcript is-dropped while audio is streaming to avoid double-handling.--## Continuous audio--Mic-audio streaming is off in code today. When it is on and the session connects, the model fires-`onLiveAudioStreamingChanged(true)`; `UserQueryOverlayController` calls-`MicrophoneWaveformMeter.startContinuousListening()`, which keeps the engine running (and ignores-UI-driven `stop()`s) so audio streams beyond the voice-capture window. Tear down via-`stopContinuousListening()`.--## Configuration recap--Live runs against Vertex AI using backend-minted OAuth tokens (no client-held API key). It is always-on, at the `global` Vertex location, all fixed in code. The backend route needs-`GOOGLE_APPLICATION_CREDENTIALS_JSON`.--## Testing--This environment needs the full Xcode toolchain and a suite filter:--```-DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer swift test --filter GeminiLiveTests-DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer swift test --filter GenericHarnessTests-```--(A no-filter full run hangs on a GUI-dependent suite.) Covered today: Command Layer descriptors-surface + input validation (`GenericHarnessTests`), and Gemini Live config parsing, function-declarations, PCM packing, frame parsing, and the function-name identifier guard (`GeminiLiveTests`).-`GenericHarnessTests` has 8 failures that pre-date this work (confirmed via a clean-tree-`git stash -u` re-run).--For the real round trip, `GeminiLiveCommandSessionLiveSmokeTests` drives the whole text path-against a live backend + Vertex. It is gated behind `DONKEY_LIVE_SMOKE=1` and no-ops otherwise:--```-env DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer \- DONKEY_LIVE_SMOKE=1 DONKEY_WEB_BASE_URL=http://localhost:3000 DONKEY_DEV_AUTH_BYPASS=1 \- swift test --filter GeminiLiveCommandSessionLiveSmokeTests-```--It mints a token, opens the Vertex Live websocket, waits for `setupComplete`, sends a text turn,-and asserts the model's tool call executes against the Command Layer without a harness-side-failure. This is what caught two real bugs the unit tests couldn't: the default model id had to be-a model that exists on Vertex (`gemini-live-2.5-flash`), and tool names must be valid function-call-identifiers — Gemini normalizes dots, so `apps.list`/`music.play` became unreachable and were-renamed to `apps_list`/`music_play`.diff --git a/site/src/app/api/browser/run/route.ts b/site/src/app/api/browser/run/route.tsdeleted file mode 100644index 6ebebf28..00000000--- a/site/src/app/api/browser/run/route.ts+++ /dev/null@@ -1,135 +0,0 @@-import { NextResponse } from "next/server";-import { z } from "zod";--import {- browserUseDefaultMaxCostUsd,- browserUseDefaultModel,- browserUseProvider,- getBrowserUse,-} from "@/lib/browser/client";-import {- creditUsageHeaders,- inferenceUsageRoutes,- recordFailedInferenceUsage,- recordInferenceUsage,- requireInferenceCredits,-} from "@/lib/credits/inference";-import { withDonkeyAuth } from "@/lib/donkey-api-auth";-import {- requireInferenceClientId,- validationErrorResponse,-} from "@/lib/inference/responses";--// 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;-- let session;- try {- session = await getBrowserUse().run(task, {- model: browserUseDefaultModel,- maxCostUsd: browserUseDefaultMaxCostUsd,- timeout: (maxDuration - 20) * 1000,- ...(parsed.data.structuredOutputSchema- ? { outputSchema: parsed.data.structuredOutputSchema }- : {}),- });- } catch (error) {- // The run may have consumed Browser Use steps before throwing (SDK timeout/transport error).- // Record a failed usage event for audit (a failed status is never charged) and return a clean- // error instead of an unhandled 500 that leaves no trace of the run.- await recordFailedInferenceUsage({- userId: request.donkey.userId,- clientId: client.clientId,- conversationId: request.donkey.conversationId,- route: inferenceUsageRoutes.browserRun,- requestKind: "browser_automation",- provider: browserUseProvider,- model: browserUseDefaultModel,- errorCode: "browser_run_failed",- metadata: {- message: error instanceof Error ? error.message : "Unknown error",- },- });- return NextResponse.json(- {- error: "browser_run_failed",- message: "The browser automation run did not complete.",- },- { status: 502 },- );- }-- 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,- conversationId: request.donkey.conversationId,- 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 text = typeof output === "string" ? output : null;- let structured: string | null = null;- if (output !== null && typeof output === "object") {- try {- structured = JSON.stringify(output);- } catch {- // Unserializable output (e.g. a BigInt or circular reference) must not throw here — credits- // were already charged above, so drop the structured payload rather than 500 after billing.- structured = 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/app/api/inference/chat/completions/route.ts b/site/src/app/api/inference/chat/completions/route.tsdeleted file mode 100644index a757729d..00000000--- a/site/src/app/api/inference/chat/completions/route.ts+++ /dev/null@@ -1,207 +0,0 @@-import { NextResponse } from "next/server";--import {- creditErrorResponse,- creditUsageHeaders,- inferenceUsageRoutes,- recordFailedInferenceUsage,- recordInferenceUsage,- requireInferenceCredits,-} from "@/lib/credits/inference";-import { createProviderRegistry } from "@/lib/inference/router";-import { resolveInferenceBlobs } from "@/lib/inference/blobs";-import { toJsonValue } from "@/lib/inference/json";-import {- inferenceErrorCode,- inferenceProviderErrorResponse,- requireInferenceClientId,- validationErrorResponse,-} from "@/lib/inference/responses";-import { chatCompletionRequestSchema } from "@/lib/inference/schemas";-import {- shouldBypassDonkeyInferenceCredits,- withDonkeyAuth,-} from "@/lib/donkey-api-auth";-import { InferenceProviderError } from "@/lib/inference/providers";--export const POST = withDonkeyAuth(async (request) => {- const client = requireInferenceClientId(request.donkey.clientId);- if (!client.ok) {- return client.response;- }-- const parsed = chatCompletionRequestSchema.safeParse(await request.json());- if (!parsed.success) {- return validationErrorResponse(parsed.error);- }-- if (- parsed.data.stream &&- parsed.data.modalities?.some((modality) => modality !== "text")- ) {- return NextResponse.json(- {- error: "Unsupported stream",- message: "Streaming is supported for text completions only.",- },- { status: 400 },- );- }-- const requestedModel =- parsed.data.model?.trim() || parsed.data.models?.[0]?.trim() || "unknown";- const bypassCredits = shouldBypassDonkeyInferenceCredits(request.donkey);- if (!bypassCredits) {- const credits = await requireInferenceCredits({- model: requestedModel,- route: inferenceUsageRoutes.chatCompletions,- userId: request.donkey.userId,- });- if (!credits.ok) {- return credits.response;- }- }-- let failedUsageProvider = "default";-- try {- // Attached pictures and sound ride storage, not the request body — they- // become inline message parts here, on the server-to-server leg.- const data = {- ...parsed.data,- messages: (await resolveInferenceBlobs(- toJsonValue(parsed.data.messages),- request.donkey.userId,- )) as typeof parsed.data.messages,- };- const registry = createProviderRegistry();- const provider = registry.textProvider(data.stream);- failedUsageProvider = provider.id;-- if (data.stream) {- const result = await provider.streamCompletion?.(data);- if (!result) {- if (!bypassCredits) {- await recordFailedInferenceUsage({- clientId: client.clientId,- conversationId: request.donkey.conversationId,- errorCode: "streaming_unavailable",- model: requestedModel,- provider: failedUsageProvider,- requestKind: "chat_completions",- route: inferenceUsageRoutes.chatCompletions,- userId: request.donkey.userId,- });- }-- return NextResponse.json(- {- error: "Streaming unavailable",- },- { status: 503 },- );- }-- let streamUsageHeaders: Record<string, string> = {};- if (bypassCredits) {- streamUsageHeaders["X-Donkey-Dev-Auth-Bypass"] = "true";- } else {- const recordedUsage = await recordInferenceUsage({- clientId: client.clientId,- conversationId: request.donkey.conversationId,- model: result.model,- provider: result.provider,- requestKind: "chat_completions",- route: inferenceUsageRoutes.chatCompletions,- status: "succeeded",- userId: request.donkey.userId,- });- streamUsageHeaders = creditUsageHeaders(recordedUsage);- }-- return new Response(result.response.body, {- status: result.response.status,- headers: {- "Content-Type":- result.response.headers.get("content-type") ?? "text/event-stream",- "Cache-Control": "no-cache",- Connection: "keep-alive",- "X-Donkey-Inference-Provider": result.provider,- "X-Donkey-Inference-Model": result.model,- ...streamUsageHeaders,- },- });- }-- const result = await provider.completeText?.(data);- if (!result) {- if (!bypassCredits) {- await recordFailedInferenceUsage({- clientId: client.clientId,- conversationId: request.donkey.conversationId,- errorCode: "completion_unavailable",- model: requestedModel,- provider: failedUsageProvider,- requestKind: "chat_completions",- route: inferenceUsageRoutes.chatCompletions,- userId: request.donkey.userId,- });- }-- return NextResponse.json(- {- error: "Completion unavailable",- },- { status: 503 },- );- }-- let usageHeaders: Record<string, string> = {};- if (bypassCredits) {- usageHeaders["X-Donkey-Dev-Auth-Bypass"] = "true";- } else {- const recordedUsage = await recordInferenceUsage({- clientId: client.clientId,- conversationId: request.donkey.conversationId,- model: result.model,- provider: result.provider,- requestKind: "chat_completions",- route: inferenceUsageRoutes.chatCompletions,- status: "succeeded",- usage: result.usage,- userId: request.donkey.userId,- });- usageHeaders = creditUsageHeaders(recordedUsage);- }-- return NextResponse.json(result.body, {- headers: {- "X-Donkey-Inference-Provider": result.provider,- "X-Donkey-Inference-Model": result.model,- ...usageHeaders,- },- });- } catch (error) {- if (!bypassCredits) {- await recordFailedInferenceUsage({- clientId: client.clientId,- conversationId: request.donkey.conversationId,- errorCode: inferenceErrorCode(error),- model: requestedModel,- provider: failedUsageProvider,- requestKind: "chat_completions",- route: inferenceUsageRoutes.chatCompletions,- userId: request.donkey.userId,- });- }- const creditResponse = creditErrorResponse(error);- if (creditResponse) {- return creditResponse;- }- if (error instanceof InferenceProviderError) {- return inferenceProviderErrorResponse(error);- }-- throw error;- }-});diff --git a/site/src/app/api/inference/live-token/route.ts b/site/src/app/api/inference/live-token/route.tsdeleted file mode 100644index 045ccaad..00000000--- a/site/src/app/api/inference/live-token/route.ts+++ /dev/null@@ -1,20 +0,0 @@-import { NextResponse } from "next/server";--import { withDonkeyAuth } from "@/lib/donkey-api-auth";-import { requireInferenceClientId } from "@/lib/inference/responses";-import { mintVertexLiveConnection } from "@/lib/inference/vertex-live";--// Mints a short-lived Vertex AI access token so a Donkey client can open a-// Gemini Live websocket directly. The long-lived service-account credential-// stays on the backend. Errors propagate raw.-export const POST = withDonkeyAuth(async (request) => {- const client = requireInferenceClientId(request.donkey.clientId);- if (!client.ok) {- return client.response;- }-- const connection = await mintVertexLiveConnection();- return NextResponse.json(connection, {- headers: { "Cache-Control": "no-store" },- });-});diff --git a/site/src/app/api/web/fetch/route.ts b/site/src/app/api/web/fetch/route.tsdeleted file mode 100644index f8bb36b4..00000000--- a/site/src/app/api/web/fetch/route.ts+++ /dev/null@@ -1,39 +0,0 @@-import { NextResponse } from "next/server";-import { z } from "zod";--import { withDonkeyAuth } from "@/lib/donkey-api-auth";-import {- requireInferenceClientId,- validationErrorResponse,-} from "@/lib/inference/responses";-import { fetchWebContent } from "@/lib/inference/web-fetch";--const webFetchRequestSchema = z.object({- url: z.string().trim().url().max(2000),-});--// Web page reader for the Mac app's web.fetch tool. Fetches the page server-side (SSRF-guarded to-// public http(s)) and returns just the main content as clean markdown — nav, ads, and boilerplate-// removed — so the model gets the article instead of raw HTML. Provider-neutral: a URL in, a title-// plus markdown out.-export const POST = withDonkeyAuth(async (request) => {- const client = requireInferenceClientId(request.donkey.clientId);- if (!client.ok) {- return client.response;- }-- const parsed = webFetchRequestSchema.safeParse(await request.json());- if (!parsed.success) {- return validationErrorResponse(parsed.error);- }-- const result = await fetchWebContent(parsed.data.url);- if (!result) {- return NextResponse.json(- { title: "", markdown: "" },- { headers: { "Cache-Control": "no-store" } },- );- }-- return NextResponse.json(result, { headers: { "Cache-Control": "no-store" } });-});diff --git a/site/src/app/api/web/search/route.ts b/site/src/app/api/web/search/route.tsdeleted file mode 100644index 13961956..00000000--- a/site/src/app/api/web/search/route.ts+++ /dev/null@@ -1,35 +0,0 @@-import { NextResponse } from "next/server";-import { z } from "zod";--import { withDonkeyAuth } from "@/lib/donkey-api-auth";-import {- requireInferenceClientId,- validationErrorResponse,-} from "@/lib/inference/responses";-import { searchWeb } from "@/lib/inference/web-search";--const webSearchRequestSchema = z.object({- query: z.string().trim().min(1).max(500),-});--// Web search for the Mac app's web.search tool. Runs Gemini's Google Search grounding on Vertex with-// the backend's service-account credential, so no key reaches the app. Provider-neutral in/out: a-// query in, a grounded summary plus ranked source pages out.-export const POST = withDonkeyAuth(async (request) => {- const client = requireInferenceClientId(request.donkey.clientId);- if (!client.ok) {- return client.response;- }-- const parsed = webSearchRequestSchema.safeParse(await request.json());- if (!parsed.success) {- return validationErrorResponse(parsed.error);- }-- const result = await searchWeb(parsed.data.query);- if (!result) {- return NextResponse.json({ summary: "", sources: [] }, { headers: { "Cache-Control": "no-store" } });- }-- return NextResponse.json(result, { headers: { "Cache-Control": "no-store" } });-});diff --git a/site/src/lib/browser/client.ts b/site/src/lib/browser/client.tsdeleted file mode 100644index 5a2127fb..00000000--- a/site/src/lib/browser/client.ts+++ /dev/null@@ -1,19 +0,0 @@-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;diff --git a/site/src/lib/browser/models.ts b/site/src/lib/browser/models.tsdeleted file mode 100644index 966dbf94..00000000--- a/site/src/lib/browser/models.ts+++ /dev/null@@ -1,11 +0,0 @@-// 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.tsdeleted file mode 100644index 53b3fea2..00000000--- a/site/src/lib/browser/pricing.ts+++ /dev/null@@ -1,9 +0,0 @@-// 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 001e34d0..e4425096 100644--- a/site/src/lib/credits/inference.ts+++ b/site/src/lib/credits/inference.ts@@ -21,8 +21,6 @@ export const creditGrantUnit = "credit";export const inferenceUsageRoutes = {assets: "/api/inference/assets/",assetsRefresh: "/api/inference/assets/refresh/",- browserRun: "/api/browser/run/",- chatCompletions: "/api/inference/chat/completions/",responses: "/api/inference/responses/",} as const;diff --git a/site/src/lib/credits/provider-pricing.ts b/site/src/lib/credits/provider-pricing.tsindex faa4cb28..5f96b719 100644--- a/site/src/lib/credits/provider-pricing.ts+++ b/site/src/lib/credits/provider-pricing.ts@@ -16,7 +16,6 @@ import {type GeminiOmniModel,type GeminiTtsModel,} from "@/lib/inference/gemini-models";-import { browserUsePerStepUsd } from "@/lib/browser/pricing";import { falMatteModels, type FalMatteModel } from "@/lib/inference/matte-models";export type ProviderCreditPricing = {@@ -71,23 +70,10 @@ export function providerCreditPricing(if (normalizedProvider === "fal") {return falMatteCreditPricing(normalizedModel);}- if (normalizedProvider === "browser-use") {- return browserUseCreditPricing();- }return undefined;}-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) {diff --git a/site/src/lib/inference/vertex-live.ts b/site/src/lib/inference/vertex-live.tsdeleted file mode 100644index 9186f273..00000000--- a/site/src/lib/inference/vertex-live.ts+++ /dev/null@@ -1,116 +0,0 @@-import { JWT } from "google-auth-library";--import { InferenceProviderError } from "@/lib/inference/providers";--const vertexAIScope = "https://www.googleapis.com/auth/cloud-platform";-const defaultVertexLocation = "global";-// The backend owns the Live model id (the client never selects it).-// `gemini-live-2.5-flash` is the model that resolves on Vertex AI in the `global`-// location and accepts the BidiGenerateContent setup (verified end-to-end via-// GeminiLiveCommandSessionLiveSmokeTests).-const defaultLiveModel = "gemini-live-2.5-flash";--type AdapterEnvironment = Record<string, string | undefined>;--/**- * Connection details a Donkey client needs to open a Gemini Live (Vertex AI)- * websocket directly: a short-lived OAuth access token plus the endpoint and- * fully-qualified model path. The long-lived service-account credential never- * leaves the backend.- */-export type VertexLiveConnection = {- token: string;- expiresAt: string | null;- websocketUrl: string;- model: string;- project: string;- location: string;-};--export function vertexLiveConfigured(- environment: AdapterEnvironment = process.env,-): boolean {- return Boolean(environment.GOOGLE_APPLICATION_CREDENTIALS_JSON?.trim());-}--/** Mint a short-lived Vertex AI access token + Live connection details. */-export async function mintVertexLiveConnection(- environment: AdapterEnvironment = process.env,-): Promise<VertexLiveConnection> {- const raw = environment.GOOGLE_APPLICATION_CREDENTIALS_JSON?.trim();- if (!raw) {- throw new InferenceProviderError(- "Vertex AI service account credentials are not configured.",- { statusCode: 503, code: "vertex_live_not_configured" },- );- }-- let parsed: unknown;- try {- parsed = JSON.parse(raw);- } catch {- throw new InferenceProviderError("Google service account JSON is invalid.", {- statusCode: 500,- code: "invalid_google_service_account_json",- });- }-- const credentials = parsed as {- client_email?: string;- private_key?: string;- private_key_id?: string;- project_id?: string;- };- const clientEmail = credentials.client_email?.trim();- const privateKey = credentials.private_key;- const project = credentials.project_id?.trim();- if (!clientEmail || !privateKey || !project) {- throw new InferenceProviderError(- "Google service account JSON must include client_email, private_key, and project_id.",- { statusCode: 500, code: "invalid_google_service_account_json" },- );- }-- const jwt = new JWT({- email: clientEmail,- key: privateKey,- keyId: credentials.private_key_id,- scopes: [vertexAIScope],- });-- let token: string | null | undefined;- try {- ({ token } = await jwt.getAccessToken());- } catch (error) {- throw new InferenceProviderError("Failed to mint a Vertex AI access token.", {- statusCode: 502,- code: "vertex_live_token_failed",- details: { message: error instanceof Error ? error.message : String(error) },- });- }- if (!token) {- throw new InferenceProviderError("Failed to mint a Vertex AI access token.", {- statusCode: 502,- code: "vertex_live_token_failed",- });- }-- const location = defaultVertexLocation;- const model = defaultLiveModel;- const host =- location === "global"- ? "aiplatform.googleapis.com"- : `${location}-aiplatform.googleapis.com`;- const websocketUrl =- `wss://${host}/ws/google.cloud.aiplatform.v1beta1.LlmBidiService/BidiGenerateContent`;- const expiry = jwt.credentials.expiry_date;-- return {- token,- expiresAt: typeof expiry === "number" ? new Date(expiry).toISOString() : null,- websocketUrl,- model: `projects/${project}/locations/${location}/publishers/google/models/${model}`,- project,- location,- };-}diff --git a/site/src/lib/inference/web-fetch.ts b/site/src/lib/inference/web-fetch.tsdeleted file mode 100644index 7fdd3784..00000000--- a/site/src/lib/inference/web-fetch.ts+++ /dev/null@@ -1,119 +0,0 @@-import { Defuddle } from "defuddle/node";-import { parseHTML } from "linkedom";--export type WebFetchResult = {- title: string;- /** The page's main content as clean markdown (nav/ads/boilerplate removed). */- markdown: string;- author?: string;- published?: string;- wordCount?: number;-};--const FETCH_TIMEOUT_MS = 20_000;-const MAX_BYTES = 5_000_000;--/**- * Read a web page and return just its main content as clean markdown. Uses Defuddle (a modern- * Readability successor built for markdown) over a linkedom DOM to strip nav, sidebars, ads, and- * boilerplate, so the model gets the article — headings, links, lists intact — instead of raw HTML- * or a flattened tag-strip. Runs on the backend so credentials/IP stay server-side; SSRF-guarded to- * public http(s) only.- */-export async function fetchWebContent(rawUrl: string): Promise<WebFetchResult | null> {- const url = safePublicURL(rawUrl);- if (!url) {- return null;- }-- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);- let html: string;- try {- const response = await fetch(url, {- signal: controller.signal,- redirect: "follow",- headers: {- "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Donkey/1.0",- Accept: "text/html,application/xhtml+xml",- },- });- if (!response.ok) {- return null;- }- const contentType = response.headers.get("content-type") ?? "";- if (contentType && !/html|xml|text/i.test(contentType)) {- return null;- }- html = await readBounded(response);- } catch {- return null;- } finally {- clearTimeout(timeout);- }-- try {- const { document } = parseHTML(html);- const result = await Defuddle(document, url, { markdown: true });- const markdown = (result.content ?? "").trim();- if (!markdown) {- return null;- }- return {- title: (result.title ?? "").trim(),- markdown,- author: result.author?.trim() || undefined,- published: result.published?.trim() || undefined,- wordCount: typeof result.wordCount === "number" ? result.wordCount : undefined,- };- } catch {- return null;- }-}--/** Only public http(s) URLs — reject other schemes and obvious internal/loopback/metadata hosts. */-function safePublicURL(rawUrl: string): string | null {- let parsed: URL;- try {- parsed = new URL(rawUrl);- } catch {- return null;- }- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {- return null;- }- const host = parsed.hostname.toLowerCase();- const blocked =- host === "localhost" ||- host === "0.0.0.0" ||- host === "169.254.169.254" || // cloud metadata- host.endsWith(".localhost") ||- host.endsWith(".internal") ||- /^127\./.test(host) ||- /^10\./.test(host) ||- /^192\.168\./.test(host) ||- /^172\.(1[6-9]|2\d|3[01])\./.test(host);- return blocked ? null : parsed.toString();-}--/** Read the response body but stop at MAX_BYTES so a huge page can't blow up memory. */-async function readBounded(response: Response): Promise<string> {- const reader = response.body?.getReader();- if (!reader) {- return await response.text();- }- const decoder = new TextDecoder();- let total = 0;- let out = "";- for (;;) {- const { done, value } = await reader.read();- if (done) break;- total += value.byteLength;- out += decoder.decode(value, { stream: true });- if (total > MAX_BYTES) {- await reader.cancel();- break;- }- }- return out;-}diff --git a/site/src/lib/inference/web-search.ts b/site/src/lib/inference/web-search.tsdeleted file mode 100644index 1f946224..00000000--- a/site/src/lib/inference/web-search.ts+++ /dev/null@@ -1,74 +0,0 @@-import { GoogleGenAI } from "@google/genai";--import { geminiClientConfig } from "@/lib/inference/adapters/gemini-client";-import { geminiModelRoles } from "@/lib/inference/gemini-models";--export type WebSearchSource = {- title: string;- url: string;-};--export type WebSearchResult = {- /** A short grounded answer to the query (from the model). */- summary: string;- /** The web sources the answer is grounded in. */- sources: WebSearchSource[];-};--/**- * Web search via Gemini's built-in Google Search grounding on Vertex AI. This uses the backend's- * service-account credential (the same one behind live-token) — no API key and no separate- * Programmable Search Engine. The model searches the web for the query and returns a- * grounded summary plus the source pages it used, which the caller turns into ranked results.- */-export async function searchWeb(query: string): Promise<WebSearchResult | null> {- const config = geminiClientConfig(process.env);- if (!config.configured) {- return null;- }- const client = new GoogleGenAI(config.options);-- const response = await client.models.generateContent({- model: geminiModelRoles.chat,- contents: [- {- role: "user",- parts: [- {- text:- `Search the web for: ${query}\n` +- "Answer in one or two sentences from current results. The caller will read the source " +- "pages itself, so keep it short.",- },- ],- },- ],- config: {- tools: [{ googleSearch: {} }],- temperature: 0,- // Cap synthesis: we mainly want the grounded sources, not a long essay. Less generation = less- // latency on the grounded call (the Google search itself is the unavoidable part).- maxOutputTokens: 400,- thinkingConfig: { thinkingBudget: 0 },- },- });-- const candidate = response.candidates?.[0];- const summary = (response.text ?? "").trim();- const chunks = candidate?.groundingMetadata?.groundingChunks ?? [];- const sources: WebSearchSource[] = [];- const seen = new Set<string>();- for (const chunk of chunks) {- const web = chunk.web;- if (!web?.uri || seen.has(web.uri)) {- continue;- }- seen.add(web.uri);- sources.push({ title: web.title ?? web.uri, url: web.uri });- }-- if (!summary && sources.length === 0) {- return null;- }- return { summary, sources };-}