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 CreateSessionRequest = {cua_version?: ('v1' | 'v3' | 'v4' | 'v5') | undefined, model?: ('default' | null) | undefined, screen_width?: number | undefined, screen_height?: number | undefined, max_trajectory_length?: number | undefined, system_prompt?: (string | null) | undefined, instructions?: (string | null) | undefined, tools?: (Array<'click' | 'type_text' | 'key_press' | 'key_combo' | 'scroll' | 'drag' | 'move' | 'wait'> | null) | undefined, action_policy?: ActionPolicy | undefined, metadata?: ({[key: string]: unknown} | null) | undefined, llm?: LlmConfig | undefined}; export type CreateApiV1SessionsArgs = {'Idempotency-Key'?: string | undefined, 'X-LLM-Provider'?: ('anthropic' | 'openai') | undefined, 'X-LLM-Api-Key'?: string | undefined, 'X-LLM-Model'?: string | undefined, body: CreateSessionRequest}; export type CreateApiV1SessionsOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const usageInfo = z.object({input_tokens: z.number().int().optional(), output_tokens: z.number().int().optional(), credits_charged: z.number().int().optional(), cost_cents: z.number().int().optional(), breakdown: z.array(z.object({item: z.enum(["base", "trajectory", "hd_images", "engine", "custom_prompt"]), credits: z.number().int(), count: z.number().int().nullable().optional()})).nullable().optional(), billed: z.boolean().optional(), llm_provider: z.enum(["managed", "anthropic", "openai"]).optional(), llm_model: z.string().nullable().optional(), llm_key_fingerprint: z.string().min(12).max(12).nullable().optional(), llm_key_source: z.enum(["header", "stored"]).nullable().optional(), platform_cost_exempt: z.boolean().optional()}); export const createSessionResponse = z.object({request_id: z.string(), session_id: z.string(), cua_version: z.string(), screen_size: z.string(), created_at: z.string(), expires_at: z.string(), usage: usageInfo}); 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 }; /** * Create a stateful CUA session * * POST /v1/sessions * * Also accepts auth: bearerAuth */ export const createApiV1Sessions = async (args: CreateApiV1SessionsArgs, options?: CreateApiV1SessionsOptions) => { 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/sessions${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(createSessionResponse, await res.json()) };