Skip to content

Open source CapCut alternative.

TypeScript

Add vision inference API

David Le92b23b572358
diff --git a/site/.env.example b/site/.env.example
index e7759845..2023d639 100644
--- a/site/.env.example
+++ b/site/.env.example
@@ -23,3 +23,9 @@ GOOGLE_APPLICATION_CREDENTIALS_JSON='{"type":"service_account",...}'
# audio-output-only model) instead of minting a Vertex token. Production uses the
# keyless Vertex path above.
GEMINI_API_KEY="replace-with-gemini-api-key"
+
+# RunPod-hosted vision worker, served by /api/inference/vision (see
+# vision/README.md). Required for that route; unrelated to the gemini-flash
+# screenshot parser at /api/inference/screenshots/parse.
+RUNPOD_API_KEY="replace-with-runpod-api-key"
+RUNPOD_VISION_ENDPOINT_ID="replace-with-endpoint-id"
diff --git a/site/src/app/api/inference/vision/route.ts b/site/src/app/api/inference/vision/route.ts
new file mode 100644
index 00000000..378a329a
--- /dev/null
+++ b/site/src/app/api/inference/vision/route.ts
@@ -0,0 +1,125 @@
+import { NextResponse } from "next/server";
+
+import {
+ creditUsageHeaders,
+ inferenceUsageRoutes,
+ recordFailedInferenceUsage,
+ recordInferenceUsage,
+ requireInferenceCredits,
+} from "@/lib/credits/inference";
+import { withDonkeyAuth } from "@/lib/donkey-api-auth";
+import { InferenceProviderError } from "@/lib/inference/providers";
+import {
+ checkInMemoryRateLimit,
+ rateLimitResponse,
+} from "@/lib/inference/rate-limit";
+import { readLimitedJsonBody } from "@/lib/inference/request-body";
+import {
+ inferenceErrorCode,
+ inferenceProviderErrorResponse,
+ requireInferenceClientId,
+ validationErrorResponse,
+} from "@/lib/inference/responses";
+import { groundInstruction } from "@/lib/inference/vision/grounding";
+import { parseImage } from "@/lib/inference/vision/parse";
+import {
+ visionRequestSchema,
+ type VisionResponse,
+} from "@/lib/inference/vision/schema";
+
+export const dynamic = "force-dynamic";
+
+const visionMaxBodyBytes = 6_250_000;
+const visionRateLimit = {
+ limit: 4,
+ windowMs: 3_000,
+};
+const inferenceProvider = "omniparser";
+const parseModel = "omniparser-v2";
+
+// B2B vision API: parse a screenshot into UI elements, and optionally ground a
+// natural-language instruction to a click target. Single-shot only.
+export const POST = withDonkeyAuth(async (request) => {
+ const client = requireInferenceClientId(request.donkey.clientId);
+ if (!client.ok) {
+ return client.response;
+ }
+
+ const rateLimit = checkInMemoryRateLimit({
+ key: `${request.donkey.userId}:${client.clientId}`,
+ ...visionRateLimit,
+ });
+ if (!rateLimit.ok) {
+ return rateLimitResponse(rateLimit.retryAfterSeconds);
+ }
+
+ const body = await readLimitedJsonBody(request, visionMaxBodyBytes);
+ if (!body.ok) {
+ return body.response;
+ }
+
+ const parsed = visionRequestSchema.safeParse(body.json);
+ if (!parsed.success) {
+ return validationErrorResponse(parsed.error);
+ }
+ const { image, instruction, model, returnElements, options } = parsed.data;
+ const billedModel = instruction ? model : parseModel;
+
+ const credits = await requireInferenceCredits({
+ model: billedModel,
+ provider: inferenceProvider,
+ route: inferenceUsageRoutes.vision,
+ userId: request.donkey.userId,
+ });
+ if (!credits.ok) {
+ return credits.response;
+ }
+
+ try {
+ const parseResult = await parseImage(image, options);
+
+ const grounding = instruction
+ ? await groundInstruction(parseResult.elements, instruction, model)
+ : null;
+
+ const includeElements = returnElements ?? instruction === undefined;
+ const result: VisionResponse = {
+ image: parseResult.image,
+ ...(includeElements ? { elements: parseResult.elements } : {}),
+ ...(grounding
+ ? { target: grounding.target, alternates: grounding.alternates, model }
+ : {}),
+ };
+
+ const recordedUsage = await recordInferenceUsage({
+ clientId: client.clientId,
+ metadata: { grounded: String(instruction !== undefined) },
+ model: billedModel,
+ provider: inferenceProvider,
+ requestKind: "vision_parse",
+ route: inferenceUsageRoutes.vision,
+ status: "succeeded",
+ userId: request.donkey.userId,
+ });
+
+ return NextResponse.json(result, {
+ headers: creditUsageHeaders(recordedUsage),
+ });
+ } catch (error) {
+ await recordFailedInferenceUsage({
+ clientId: client.clientId,
+ errorCode: inferenceErrorCode(error),
+ metadata: { grounded: String(instruction !== undefined) },
+ model: billedModel,
+ provider: inferenceProvider,
+ requestKind: "vision_parse",
+ route: inferenceUsageRoutes.vision,
+ userId: request.donkey.userId,
+ });
+ if (error instanceof InferenceProviderError) {
+ return inferenceProviderErrorResponse(error);
+ }
+
+ throw error;
+ }
+});
diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.ts
index 2810128a..10795ebd 100644
--- a/site/src/lib/credits/inference.ts
+++ b/site/src/lib/credits/inference.ts
@@ -20,6 +20,7 @@ export const inferenceUsageRoutes = {
chatCompletions: "/api/inference/chat/completions/",
responses: "/api/inference/responses/",
screenshotParse: "/api/inference/screenshots/parse/",
+ vision: "/api/inference/vision/",
} as const;
type CreditsDatabase = PrismaClient | Prisma.TransactionClient;
diff --git a/site/src/lib/inference/screenshot-parsing/gemini-flash.ts b/site/src/lib/inference/screenshot-parsing/gemini-flash.ts
index b2f7c011..bd30ced2 100644
--- a/site/src/lib/inference/screenshot-parsing/gemini-flash.ts
+++ b/site/src/lib/inference/screenshot-parsing/gemini-flash.ts
@@ -14,24 +14,20 @@ import type {
import { ensureConfigured } from "@/lib/inference/http";
import {
isJsonObject,
- toJsonObject,
toJsonValue,
} from "@/lib/inference/json";
import {
InferenceProviderError,
type JsonValue,
} from "@/lib/inference/providers";
+import { normalizedScreenshotResult } from "@/lib/inference/screenshot-parsing/normalize";
import {
geminiScreenshotParseOutputSchema,
geminiScreenshotControlSchema,
type GeminiScreenshotParseOutput,
- type HotLoopRectJSON,
type ScreenshotParseRequest,
} from "@/lib/inference/screenshot-parsing/schema";
-import type {
- ScreenshotParserProvider,
- ScreenshotParserResult,
-} from "@/lib/inference/screenshot-parsing/types";
+import type { ScreenshotParserProvider } from "@/lib/inference/screenshot-parsing/types";
type AdapterEnvironment = Record<string, string | undefined>;
type GeminiClient = Pick<GoogleGenAI, "models">;
@@ -163,81 +159,6 @@ export function screenshotParseModelForRequest(
|| defaultScreenshotParseModel;
}
-export function normalizedScreenshotResult(
- request: ScreenshotParseRequest,
- output: GeminiScreenshotParseOutput,
- metadata: Record<string, string>,
-): ScreenshotParserResult {
- const visibleText = output.visibleText.reduce<Record<string, string>>((result, item, index) => {
- const key = item.id?.trim() || (index === 0 ? "visibleText" : `visibleText.${index + 1}`);
- result[key] = item.text;
- return result;
- }, {});
-
- const controls = output.controls.map((control, index) => {
- const id = control.id?.trim() || `gemini-control-${index + 1}`;
- const controlID = normalizedControlID(control.label, control.kind, id);
- return {
- id,
- label: control.label,
- kind: control.kind,
- frame: rectFromGeminiBox(control.box_2d, request.pixelSize.width, request.pixelSize.height),
- confidence: clamp01(control.confidence),
- metadata: {
- controlID,
- segmentID: id,
- source: "gemini-screenshot-parser",
- boxFormat: "ymin,xmin,ymax,xmax/1000",
- "localUIElement.actionEligibility": "guardedAction",
- directInputActionsAllowed: "true",
- },
- };
- });
-
- const formFields = output.formFields.map((field, index) => {
- const id = field.id?.trim() || `gemini-form-field-${index + 1}`;
- return {
- id,
- label: field.label,
- isRequired: field.isRequired,
- currentValue: field.currentValue ?? null,
- metadata: {
- source: "gemini-screenshot-parser",
- confidence: String(clamp01(field.confidence)),
- },
- };
- });
-
- return {
- visibleText,
- controls,
- formFields,
- confidence: clamp01(output.confidence || controls.map((control) => control.confidence).reduce(
- (max, value) => Math.max(max, value),
- 0,
- )),
- metadata: toJsonObject({
- ...metadata,
- "runtime.backend": "gemini-screenshot-parser",
- "directInputActionsAllowed": "true",
- "screenshotParser.controlCount": String(controls.length),
- "screenshotParser.formFieldCount": String(formFields.length),
- }),
- };
-}
-
-function normalizedControlID(label: string, kind: string, fallbackID: string) {
- const normalized = label
- .trim()
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-+|-+$/g, "");
- if (kind === "searchField") {
- return "search";
- }
- return normalized || fallbackID;
-}
-
function geminiRequestParameters(
request: ScreenshotParseRequest,
model: string,
@@ -562,36 +483,6 @@ function geminiResponseText(response: unknown) {
return directText ?? geminiText(toJsonValue(response));
}
-export function rectFromGeminiBox(
- box: [number, number, number, number],
- imageWidth: number,
- imageHeight: number,
-): HotLoopRectJSON | null {
- const [ymin, xmin, ymax, xmax] = box;
- const x1 = clamp(xmin, 0, 1000) / 1000 * imageWidth;
- const y1 = clamp(ymin, 0, 1000) / 1000 * imageHeight;
- const x2 = clamp(xmax, 0, 1000) / 1000 * imageWidth;
- const y2 = clamp(ymax, 0, 1000) / 1000 * imageHeight;
- const width = Math.max(0, x2 - x1);
- const height = Math.max(0, y2 - y1);
- if (width <= 0 || height <= 0) {
- return null;
- }
-
- return {
- origin: {
- x: x1,
- y: y1,
- space: "window",
- },
- size: {
- width,
- height,
- space: "window",
- },
- };
-}
-
function usageFromGeminiResponse(rawBody: JsonValue): JsonValue | undefined {
if (!isJsonObject(rawBody)) {
return undefined;
@@ -600,13 +491,6 @@ function usageFromGeminiResponse(rawBody: JsonValue): JsonValue | undefined {
return usage === undefined ? undefined : toJsonValue(usage);
}
-function clamp01(value: number) {
- return clamp(value, 0, 1);
-}
-
-function clamp(value: number, lower: number, upper: number) {
- return Math.min(Math.max(value, lower), upper);
-}
const geminiOutputSchema: Schema = {
type: Type.OBJECT,
@@ -663,7 +547,7 @@ const geminiOutputSchema: Schema = {
},
};
-function geminiClientConfig(environment: AdapterEnvironment): {
+export function geminiClientConfig(environment: AdapterEnvironment = process.env): {
configured: boolean;
options: GoogleGenAIOptions;
service: "vertex-ai" | "gemini-api";
diff --git a/site/src/lib/inference/screenshot-parsing/normalize.ts b/site/src/lib/inference/screenshot-parsing/normalize.ts
new file mode 100644
index 00000000..59070da0
--- /dev/null
+++ b/site/src/lib/inference/screenshot-parsing/normalize.ts
@@ -0,0 +1,131 @@
+import { toJsonObject } from "@/lib/inference/json";
+import type {
+ GeminiScreenshotParseOutput,
+ HotLoopRectJSON,
+ ScreenshotParseRequest,
+} from "@/lib/inference/screenshot-parsing/schema";
+import type { ScreenshotParserResult } from "@/lib/inference/screenshot-parsing/types";
+
+// Provider-agnostic normalization shared by the screenshot-parsing providers
+// (gemini-flash, vision). Turns the common parse output — visibleText,
+// controls with box_2d in [ymin, xmin, ymax, xmax]/1000 space, and form fields
+// — into the ScreenshotParserResult contract, stamping each result with its
+// originating `source`.
+export function normalizedScreenshotResult(
+ request: ScreenshotParseRequest,
+ output: GeminiScreenshotParseOutput,
+ metadata: Record<string, string>,
+ source = "gemini-screenshot-parser",
+): ScreenshotParserResult {
+ const visibleText = output.visibleText.reduce<Record<string, string>>((result, item, index) => {
+ const key = item.id?.trim() || (index === 0 ? "visibleText" : `visibleText.${index + 1}`);
+ result[key] = item.text;
+ return result;
+ }, {});
+
+ const usedControlIDs = new Set<string>();
+ const controls = output.controls.map((control) => {
+ // Opaque, unique-per-result control id. searchField keeps the well-known
+ // "search" id that the local-app action plan defaults to.
+ const controlID = control.kind === "searchField"
+ ? "search"
+ : uniqueShortID(usedControlIDs);
+ return {
+ id: controlID,
+ label: control.label,
+ kind: control.kind,
+ frame: rectFromGeminiBox(control.box_2d, request.pixelSize.width, request.pixelSize.height),
+ confidence: clamp01(control.confidence),
+ metadata: {
+ controlID,
+ segmentID: controlID,
+ source,
+ boxFormat: "ymin,xmin,ymax,xmax/1000",
+ "localUIElement.actionEligibility": "guardedAction",
+ directInputActionsAllowed: "true",
+ },
+ };
+ });
+
+ const formFields = output.formFields.map((field, index) => {
+ const id = field.id?.trim() || `form-field-${index + 1}`;
+ return {
+ id,
+ label: field.label,
+ isRequired: field.isRequired,
+ currentValue: field.currentValue ?? null,
+ metadata: {
+ source,
+ confidence: String(clamp01(field.confidence)),
+ },
+ };
+ });
+
+ return {
+ visibleText,
+ controls,
+ formFields,
+ confidence: clamp01(output.confidence || controls.map((control) => control.confidence).reduce(
+ (max, value) => Math.max(max, value),
+ 0,
+ )),
+ metadata: toJsonObject({
+ ...metadata,
+ "runtime.backend": source,
+ "directInputActionsAllowed": "true",
+ "screenshotParser.controlCount": String(controls.length),
+ "screenshotParser.formFieldCount": String(formFields.length),
+ }),
+ };
+}
+
+export function rectFromGeminiBox(
+ box: [number, number, number, number],
+ imageWidth: number,
+ imageHeight: number,
+): HotLoopRectJSON | null {
+ const [ymin, xmin, ymax, xmax] = box;
+ const x1 = clamp(xmin, 0, 1000) / 1000 * imageWidth;
+ const y1 = clamp(ymin, 0, 1000) / 1000 * imageHeight;
+ const x2 = clamp(xmax, 0, 1000) / 1000 * imageWidth;
+ const y2 = clamp(ymax, 0, 1000) / 1000 * imageHeight;
+ const width = Math.max(0, x2 - x1);
+ const height = Math.max(0, y2 - y1);
+ if (width <= 0 || height <= 0) {
+ return null;
+ }
+
+ return {
+ origin: {
+ x: x1,
+ y: y1,
+ space: "window",
+ },
+ size: {
+ width,
+ height,
+ space: "window",
+ },
+ };
+}
+
+function uniqueShortID(used: Set<string>): string {
+ let id = shortID();
+ while (used.has(id)) {
+ id = shortID();
+ }
+ used.add(id);
+ return id;
+}
+
+function shortID(): string {
+ return Math.random().toString(36).slice(2, 8).padEnd(6, "0");
+}
+
+function clamp01(value: number) {
+ return clamp(value, 0, 1);
+}
+
+function clamp(value: number, lower: number, upper: number) {
+ return Math.min(Math.max(value, lower), upper);
+}
diff --git a/site/src/lib/inference/vision/grounding.ts b/site/src/lib/inference/vision/grounding.ts
new file mode 100644
index 00000000..d3a12bfc
--- /dev/null
+++ b/site/src/lib/inference/vision/grounding.ts
@@ -0,0 +1,143 @@
+import { GoogleGenAI, Type } from "@google/genai";
+import { z } from "zod";
+
+import { ensureConfigured } from "@/lib/inference/http";
+import { InferenceProviderError } from "@/lib/inference/providers";
+import { geminiClientConfig } from "@/lib/inference/screenshot-parsing/gemini-flash";
+import type {
+ VisionElement,
+ VisionModel,
+ VisionTarget,
+} from "@/lib/inference/vision/schema";
+
+export type GroundingResult = {
+ target: VisionTarget | null;
+ alternates: VisionTarget[];
+};
+
+const groundingOutputSchema = z.object({
+ elementId: z.string(),
+ confidence: z.number().min(0).max(1).optional().default(0.5),
+ alternates: z.array(z.object({
+ elementId: z.string(),
+ confidence: z.number().min(0).max(1).optional().default(0.5),
+ })).optional().default([]),
+});
+
+const geminiResponseSchema = {
+ type: Type.OBJECT,
+ required: ["elementId", "confidence"],
+ properties: {
+ elementId: {
+ type: Type.STRING,
+ description: "id of the single best-matching element, or empty string if none match.",
+ },
+ confidence: { type: Type.NUMBER },
+ alternates: {
+ type: Type.ARRAY,
+ items: {
+ type: Type.OBJECT,
+ required: ["elementId", "confidence"],
+ properties: {
+ elementId: { type: Type.STRING },
+ confidence: { type: Type.NUMBER },
+ },
+ },
+ },
+ },
+};
+
+// Resolve a natural-language instruction to a click target by letting the model
+// pick from the already-parsed elements (text only — no image). Coordinates
+// always come from the parser, never the model.
+export async function groundInstruction(
+ elements: VisionElement[],
+ instruction: string,
+ model: VisionModel,
+): Promise<GroundingResult> {
+ const config = geminiClientConfig();
+ ensureConfigured(config.configured, "Grounding model credentials are not configured.");
+
+ const byID = new Map(elements.map((element) => [element.id, element]));
+
+ const client = new GoogleGenAI(config.options);
+ let rawResponse: { text?: string };
+ try {
+ rawResponse = await client.models.generateContent({
+ model,
+ contents: groundingPrompt(elements, instruction),
+ config: {
+ responseMimeType: "application/json",
+ responseSchema: geminiResponseSchema,
+ temperature: 0,
+ },
+ });
+ } catch (error) {
+ throw new InferenceProviderError("Grounding request failed.", {
+ statusCode: 502,
+ code: "provider_error",
+ details: { message: error instanceof Error ? error.message : String(error) },
+ });
+ }
+
+ const parsed = groundingOutputSchema.safeParse(safeJsonParse(rawResponse.text));
+ if (!parsed.success) {
+ return { target: null, alternates: [] };
+ }
+
+ const target = targetFor(byID, parsed.data.elementId, parsed.data.confidence);
+ const alternates = parsed.data.alternates
+ .map((alternate) => targetFor(byID, alternate.elementId, alternate.confidence))
+ .filter((value): value is VisionTarget => value !== null);
+
+ return { target, alternates };
+}
+
+function groundingPrompt(elements: VisionElement[], instruction: string): string {
+ const catalog = elements.map((element) => ({
+ id: element.id,
+ label: element.label,
+ kind: element.kind,
+ interactive: element.interactive,
+ }));
+ return [
+ "You select the single UI element that best satisfies a user instruction.",
+ "You are given a JSON list of detected on-screen elements.",
+ "Return the id of the best-matching element, or an empty string if none match.",
+ "Optionally include a few ranked alternates.",
+ "",
+ `Instruction: ${instruction}`,
+ "",
+ `Elements: ${JSON.stringify(catalog)}`,
+ ].join("\n");
+}
+
+function targetFor(
+ byID: Map<string, VisionElement>,
+ elementId: string,
+ confidence: number,
+): VisionTarget | null {
+ const element = byID.get(elementId.trim());
+ if (!element) {
+ return null;
+ }
+ return {
+ elementId: element.id,
+ label: element.label,
+ kind: element.kind,
+ box: element.box,
+ point: element.point,
+ confidence,
+ };
+}
+
+function safeJsonParse(text: string | undefined): unknown {
+ if (!text) {
+ return null;
+ }
+ try {
+ return JSON.parse(text);
+ } catch {
+ return null;
+ }
+}
diff --git a/site/src/lib/inference/vision/parse.ts b/site/src/lib/inference/vision/parse.ts
new file mode 100644
index 00000000..db2f7d01
--- /dev/null
+++ b/site/src/lib/inference/vision/parse.ts
@@ -0,0 +1,167 @@
+import { z } from "zod";
+
+import { InferenceProviderError } from "@/lib/inference/providers";
+import type {
+ VisionElement,
+ VisionParseOptions,
+} from "@/lib/inference/vision/schema";
+
+type FetchImpl = typeof fetch;
+
+// Read RunPod config at module load so a missing var fails the deploy, not the
+// first request.
+const apiKey = requireEnv("RUNPOD_API_KEY");
+const endpointId = requireEnv("RUNPOD_VISION_ENDPOINT_ID");
+
+function requireEnv(name: string): string {
+ const value = process.env[name]?.trim();
+ if (!value) {
+ throw new Error(`${name} must be set to use the vision API.`);
+ }
+ return value;
+}
+
+const defaultBoxThreshold = 0.05;
+const defaultIouThreshold = 0.1;
+const defaultImgsz = 640;
+
+// Raw worker output. bbox is [x1, y1, x2, y2] in ratio space (0-1).
+const workerElementSchema = z.object({
+ type: z.string().optional(),
+ bbox: z.tuple([z.number(), z.number(), z.number(), z.number()]),
+ interactivity: z.boolean().optional(),
+ content: z.string().nullable().optional(),
+});
+
+const workerOutputSchema = z.object({
+ image_size: z.object({ width: z.number().positive(), height: z.number().positive() }),
+ parsed_content_list: z.array(workerElementSchema).default([]),
+});
+
+const runpodResponseSchema = z.object({
+ status: z.string().optional(),
+ error: z.unknown().optional(),
+ output: z.unknown().optional(),
+});
+
+export type VisionParseResult = {
+ image: { width: number; height: number };
+ elements: VisionElement[];
+};
+
+export async function parseImage(
+ imageBase64: string,
+ options: VisionParseOptions = {},
+ fetchImpl: FetchImpl = fetch,
+): Promise<VisionParseResult> {
+ const rawOutput = await callWorker(imageBase64, options, fetchImpl);
+ const parsed = workerOutputSchema.safeParse(rawOutput);
+ if (!parsed.success) {
+ throw new InferenceProviderError("Vision worker output was malformed.", {
+ statusCode: 502,
+ code: "provider_error",
+ });
+ }
+
+ const { width, height } = parsed.data.image_size;
+ const usedIDs = new Set<string>();
+ const elements: VisionElement[] = [];
+
+ for (const element of parsed.data.parsed_content_list) {
+ const [x1, y1, x2, y2] = element.bbox;
+ // Drop degenerate boxes; they carry no usable geometry.
+ if (x2 <= x1 || y2 <= y1) {
+ continue;
+ }
+
+ const boxX = x1 * width;
+ const boxY = y1 * height;
+ const boxW = (x2 - x1) * width;
+ const boxH = (y2 - y1) * height;
+ const content = element.content?.trim() ?? "";
+ const interactive = element.interactivity ?? false;
+
+ elements.push({
+ id: uniqueShortID(usedIDs),
+ label: content || element.type || "element",
+ kind: interactive ? "button" : element.type === "text" ? "text" : "icon",
+ interactive,
+ box: { x: boxX, y: boxY, width: boxW, height: boxH },
+ point: { x: boxX + boxW / 2, y: boxY + boxH / 2 },
+ confidence: 0.5,
+ });
+ }
+
+ return { image: { width, height }, elements };
+}
+
+async function callWorker(
+ imageBase64: string,
+ options: VisionParseOptions,
+ fetchImpl: FetchImpl,
+): Promise<unknown> {
+ let response: Response;
+ try {
+ response = await fetchImpl(`https://api.runpod.ai/v2/${endpointId}/runsync`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ input: {
+ image: imageBase64,
+ box_threshold: options.boxThreshold ?? defaultBoxThreshold,
+ iou_threshold: options.iouThreshold ?? defaultIouThreshold,
+ imgsz: defaultImgsz,
+ },
+ }),
+ });
+ } catch (error) {
+ throw new InferenceProviderError("Vision worker request failed.", {
+ statusCode: 502,
+ code: "provider_request_failed",
+ details: { message: error instanceof Error ? error.message : String(error) },
+ });
+ }
+
+ if (!response.ok) {
+ throw new InferenceProviderError(`Vision worker returned HTTP ${response.status}.`, {
+ statusCode: 502,
+ code: "provider_error",
+ details: { httpStatus: response.status },
+ });
+ }
+
+ const body = runpodResponseSchema.safeParse(await response.json());
+ if (!body.success) {
+ throw new InferenceProviderError("Vision worker response was malformed.", {
+ statusCode: 502,
+ code: "provider_error",
+ });
+ }
+
+ const { status, output, error } = body.data;
+ if (status && status !== "COMPLETED") {
+ throw new InferenceProviderError(`Vision worker job did not complete (status ${status}).`, {
+ statusCode: 502,
+ code: "provider_error",
+ details: typeof error === "string" ? { error } : undefined,
+ });
+ }
+
+ return output;
+}
+
+function uniqueShortID(used: Set<string>): string {
+ let id = shortID();
+ while (used.has(id)) {
+ id = shortID();
+ }
+ used.add(id);
+ return id;
+}
+
+function shortID(): string {
+ return Math.random().toString(36).slice(2, 8).padEnd(6, "0");
+}
diff --git a/site/src/lib/inference/vision/schema.ts b/site/src/lib/inference/vision/schema.ts
new file mode 100644
index 00000000..e63bd8f3
--- /dev/null
+++ b/site/src/lib/inference/vision/schema.ts
@@ -0,0 +1,68 @@
+import { z } from "zod";
+
+// Public B2B vision API contract for POST /api/inference/vision.
+//
+// Two stages: parse a screenshot into UI elements (always), and optionally
+// ground a natural-language instruction ("click the play button") to a click
+// target using an LLM. Coordinates are pixels relative to the uploaded image,
+// origin top-left.
+
+// Allow-list of grounding models. Extend deliberately — each must be wired in
+// vision/grounding.ts.
+export const supportedVisionModels = ["gemini-2.5-flash"] as const;
+export type VisionModel = (typeof supportedVisionModels)[number];
+export const defaultVisionModel: VisionModel = "gemini-2.5-flash";
+
+export const visionParseOptionsSchema = z.object({
+ boxThreshold: z.number().min(0).max(1).optional(),
+ iouThreshold: z.number().min(0).max(1).optional(),
+});
+
+export type VisionParseOptions = z.infer<typeof visionParseOptionsSchema>;
+
+export const visionRequestSchema = z.object({
+ // Base64-encoded screenshot (png/jpeg/webp), no data: prefix.
+ image: z.string().min(1).max(6_000_000),
+ // When present, the LLM grounding stage runs and a target is returned.
+ instruction: z.string().min(1).max(2_000).optional(),
+ // Grounding model; only used when instruction is present.
+ model: z.enum(supportedVisionModels).default(defaultVisionModel),
+ // Whether to include the full parsed element list in the response. Defaults
+ // to true for parse-only requests and false when an instruction is grounded.
+ returnElements: z.boolean().optional(),
+ options: visionParseOptionsSchema.optional().default({}),
+});
+
+export type VisionRequest = z.infer<typeof visionRequestSchema>;
+
+export type VisionPoint = { x: number; y: number };
+export type VisionBox = { x: number; y: number; width: number; height: number };
+
+export type VisionElement = {
+ id: string;
+ label: string;
+ kind: string;
+ interactive: boolean;
+ box: VisionBox;
+ point: VisionPoint;
+ confidence: number;
+};
+
+export type VisionTarget = {
+ elementId: string;
+ label: string;
+ kind: string;
+ box: VisionBox;
+ point: VisionPoint;
+ confidence: number;
+};
+
+export type VisionResponse = {
+ image: { width: number; height: number };
+ // Present unless explicitly suppressed via returnElements: false.
+ elements?: VisionElement[];
+ // Present only when an instruction was grounded.
+ target?: VisionTarget | null;
+ alternates?: VisionTarget[];
+ model?: VisionModel;
+};