import {z} from 'zod' export type CoordinateBounds = {min_x?: number | undefined, min_y?: number | undefined, max_x: number, max_y: number}; export type ActionPolicy = {allowed_actions?: (Array | null) | undefined, blocked_actions?: Array | undefined, blocked_keys?: Array | undefined, block_window_close?: boolean | undefined, max_actions?: (number | null) | undefined, coordinate_bounds?: (CoordinateBounds | null) | undefined}; export type LlmConfig = {provider?: ('managed' | 'anthropic' | 'openai') | undefined, model?: (string | null) | undefined, grounding_model?: (string | null) | undefined, compaction_model?: (string | null) | undefined, code_agent_model?: (string | null) | undefined}; export type RunRequest = {machine_id: string, task: string, cua_version?: ('v1' | 'v3' | 'v4' | 'v5') | undefined, instructions?: (string | null) | undefined, system_prompt?: (string | null) | undefined, model?: (string | null) | undefined, max_steps?: number | undefined, action_policy?: ActionPolicy | undefined, deadline_seconds?: (number | null) | undefined, on_awaiting_human?: ('pause' | 'fail' | 'cancel') | undefined, awaiting_human_timeout_seconds?: (number | null) | undefined, webhook_url?: (string | null) | undefined, metadata?: ({[key: string]: unknown} | null) | undefined, llm?: LlmConfig | undefined}; export type CreateApiV1RunsArgs = {'Idempotency-Key'?: string | undefined, 'X-LLM-Provider'?: ('anthropic' | 'openai') | undefined, 'X-LLM-Api-Key'?: string | undefined, 'X-LLM-Model'?: string | undefined, body: RunRequest}; export type CreateApiV1RunsOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const runLlmInfo = z.object({provider: z.enum(["anthropic", "openai"]), model: z.string().min(1).max(256), key_fingerprint: z.string().min(12).max(12), key_source: z.enum(["header", "stored"]), key_scrubbed: z.boolean()}); export const runResponse = z.object({id: z.string(), object: z.literal("agent.run"), status: z.enum(["queued", "running", "awaiting_human", "succeeded", "failed", "cancelled", "timed_out"]), machine_id: z.string().nullable().optional(), machine: z.object({mode: z.literal("automatic").optional(), status: z.enum(["provisioning", "starting", "reconciling", "ready", "terminated", "cleanup_failed"]).optional(), id: z.string().nullable().optional(), cleanup: z.literal("always").optional(), cleanup_status: z.enum(["pending", "terminating", "retrying", "terminated"]).optional(), error: z.record(z.string(), z.unknown()).optional()}).nullable().optional(), task: z.string().optional(), cua_version: z.string().optional(), instructions: z.string().nullable().optional(), max_steps: z.number().int().optional(), deadline_seconds: z.number().int().optional(), awaiting_human_timeout_seconds: z.number().int().optional(), on_awaiting_human: z.string().optional(), steps_completed: z.number().int().optional(), credits_charged: z.number().int().optional(), cost_cents: z.number().int().optional(), result: z.record(z.string(), z.unknown()).nullable().optional(), error: z.record(z.string(), z.unknown()).nullable().optional(), awaiting_human_reason: z.string().nullable().optional(), metadata: z.record(z.string(), z.unknown()).nullable().optional(), llm: runLlmInfo.nullable().optional(), webhook_url: z.string().nullable().optional(), webhook_secret: z.string().nullable().optional(), created_at: z.string().nullable().optional(), started_at: z.string().nullable().optional(), awaiting_human_since: z.string().nullable().optional(), finished_at: z.string().nullable().optional(), request_id: z.string().nullable().optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Start an autonomous run * * POST /v1/runs * * Also accepts auth: bearerAuth */ export const createApiV1Runs = async (args: CreateApiV1RunsArgs, options?: CreateApiV1RunsOptions) => { const {baseUrl = "https://coasty.ai", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (args['X-LLM-Provider'] != null) headers.set("X-LLM-Provider", String(args['X-LLM-Provider'])) if (args['X-LLM-Api-Key'] != null) headers.set("X-LLM-Api-Key", String(args['X-LLM-Api-Key'])) if (args['X-LLM-Model'] != null) headers.set("X-LLM-Model", String(args['X-LLM-Model'])) if (apiKey !== undefined) headers.set("X-API-Key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/runs${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(runResponse, await res.json()) };