import {z} from 'zod' export type CacheControl = {type?: 'ephemeral' | undefined, ttl?: string | undefined}; export type OpenAIResponsesRequest = {model: string, input: string | Array<{id?: string | undefined, type?: ('message' | 'file_search_call' | 'computer_call' | 'computer_call_output' | 'web_search_call' | 'web_fetch_call' | 'function_call' | 'function_call_output' | 'code_interpreter_call' | 'local_shell_call' | 'local_shell_call_output' | 'mcp_call' | 'custom_tool_call' | 'custom_tool_call_output' | 'image_generation_call' | 'mcp_list_tools' | 'mcp_approval_request' | 'mcp_approval_responses' | 'reasoning' | 'item_reference' | 'refusal') | undefined, status?: ('in_progress' | 'completed' | 'incomplete' | 'interpreting' | 'failed') | undefined, role?: ('assistant' | 'user' | 'system' | 'developer') | undefined, content?: (string | Array<{type: 'input_text' | 'input_image' | 'input_file' | 'input_audio' | 'output_text' | 'refusal' | 'reasoning_text', file_id?: string | undefined, text?: string | undefined, signature?: string | undefined, image_url?: string | undefined, detail?: string | undefined, file_data?: string | undefined, file_url?: string | undefined, filename?: string | undefined, file_type?: string | undefined, input_audio?: ({format: 'mp3' | 'wav', data: string}) | undefined, annotations?: (Array<{type?: ('file_citation' | 'url_citation' | 'container_file_citation' | 'file_path') | undefined, index?: number | undefined, file_id?: string | undefined, text?: string | undefined, start_index?: number | undefined, end_index?: number | undefined, filename?: string | undefined, title?: string | undefined, url?: string | undefined, container_id?: string | undefined}>) | undefined, logprobs?: (Array<{bytes?: Array | undefined, logprob?: number | undefined, token?: string | undefined, top_logprobs?: (Array<{bytes?: Array | undefined, logprob?: number | undefined, token?: string | undefined}>) | undefined}>) | undefined, refusal?: string | undefined, cache_control?: CacheControl | undefined}>) | undefined, call_id?: string | undefined, name?: string | undefined, arguments?: string | undefined, output?: (string | Array<{type: 'input_text' | 'input_image' | 'input_file' | 'input_audio' | 'output_text' | 'refusal' | 'reasoning_text', file_id?: string | undefined, text?: string | undefined, signature?: string | undefined, image_url?: string | undefined, detail?: string | undefined, file_data?: string | undefined, file_url?: string | undefined, filename?: string | undefined, file_type?: string | undefined, input_audio?: ({format: 'mp3' | 'wav', data: string}) | undefined, annotations?: (Array<{type?: ('file_citation' | 'url_citation' | 'container_file_citation' | 'file_path') | undefined, index?: number | undefined, file_id?: string | undefined, text?: string | undefined, start_index?: number | undefined, end_index?: number | undefined, filename?: string | undefined, title?: string | undefined, url?: string | undefined, container_id?: string | undefined}>) | undefined, logprobs?: (Array<{bytes?: Array | undefined, logprob?: number | undefined, token?: string | undefined, top_logprobs?: (Array<{bytes?: Array | undefined, logprob?: number | undefined, token?: string | undefined}>) | undefined}>) | undefined, refusal?: string | undefined, cache_control?: CacheControl | undefined}> | {type?: 'computer_screenshot' | undefined, file_id?: string | undefined, image_url?: string | undefined}) | undefined, action?: Record | undefined, error?: string | undefined, queries?: Array | undefined, results?: Array> | undefined, summary?: Array<{type: 'summary_text', text: string}> | undefined, encrypted_content?: string | undefined}>, stream?: boolean | undefined, instructions?: string | undefined, max_output_tokens?: number | undefined, metadata?: {[key: string]: unknown} | undefined, parallel_tool_calls?: boolean | undefined, previous_response_id?: string | undefined, reasoning?: ({effort?: ('none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh') | undefined, generate_summary?: ('auto' | 'concise' | 'detailed') | undefined, summary?: ('auto' | 'concise' | 'detailed') | undefined, max_tokens?: number | undefined}) | undefined, store?: boolean | undefined, temperature?: number | undefined, text?: ({format?: ({type?: ('text' | 'json_object' | 'json_schema') | undefined, json_schema?: ({name?: string | undefined, schema?: Record | undefined, strict?: boolean | undefined}) | undefined}) | undefined}) | undefined, tool_choice?: ('none' | 'auto' | 'required' | {type: 'none' | 'auto' | 'any' | 'required' | 'function' | 'allowed_tools' | 'file_search' | 'web_search_preview' | 'computer_use_preview' | 'code_interpreter' | 'image_generation' | 'mcp' | 'custom', mode?: string | undefined, name?: string | undefined, server_label?: string | undefined, tools?: (Array<{type: 'function' | 'mcp' | 'image_generation', name?: string | undefined, server_label?: string | undefined}>) | undefined}) | undefined, tools?: (Array<{type: 'function' | 'file_search' | 'computer_use_preview' | 'web_search' | 'web_fetch' | 'mcp' | 'code_interpreter' | 'image_generation' | 'local_shell' | 'custom' | 'web_search_preview' | 'memory' | 'tool_search', name?: string | undefined, description?: string | undefined, cache_control?: CacheControl | undefined, parameters?: ({type?: string | undefined, description?: string | undefined, required?: Array | undefined, properties?: {[key: string]: unknown} | undefined, enum?: Array | undefined, additionalProperties?: boolean | undefined}) | undefined, strict?: boolean | undefined, vector_store_ids?: Array | undefined, filters?: Record | undefined, max_num_results?: number | undefined, ranking_options?: Record | undefined, display_height?: number | undefined, display_width?: number | undefined, environment?: string | undefined, enable_zoom?: boolean | undefined, search_context_size?: string | undefined, user_location?: Record | undefined, server_label?: string | undefined, server_url?: string | undefined, allowed_tools?: Record | undefined, authorization?: string | undefined, connector_id?: string | undefined, headers?: {[key: string]: string} | undefined, require_approval?: Record | undefined, server_description?: string | undefined, container?: Record | undefined, background?: string | undefined, input_fidelity?: string | undefined, input_image_mask?: Record | undefined, moderation?: string | undefined, output_compression?: number | undefined, output_format?: string | undefined, partial_images?: number | undefined, quality?: string | undefined, size?: string | undefined, format?: Record | undefined}>) | undefined, top_p?: number | undefined, truncation?: ('auto' | 'disabled') | undefined, user?: string | undefined, fallbacks?: Array | undefined}; export type CreateApiCursorV1ChatCompletionsArgs = {body: OpenAIResponsesRequest}; export type CreateApiCursorV1ChatCompletionsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const cacheControl = z.object({type: z.literal("ephemeral").optional(), ttl: z.string().optional()}); export const chatMessage = z.object({role: z.enum(["assistant", "user", "system", "tool", "developer"]), name: z.string().optional(), content: z.union([z.string(), z.array(z.object({type: z.enum(["text", "image_url", "input_audio", "file", "refusal"]), text: z.string().optional(), refusal: z.string().optional(), image_url: z.object({url: z.string(), detail: z.enum(["low", "high", "auto"]).optional()}).optional(), input_audio: z.object({data: z.string(), format: z.string().optional()}).optional(), file: z.object({file_data: z.string().optional(), file_id: z.string().optional(), filename: z.string().optional(), file_type: z.string().optional()}).optional(), cache_control: cacheControl.optional()}))]).optional(), tool_call_id: z.string().optional(), refusal: z.string().optional(), audio: z.object({id: z.string().optional(), data: z.string().optional(), expires_at: z.number().int().optional(), transcript: z.string().optional()}).optional(), reasoning: z.string().optional(), reasoning_details: z.array(z.object({id: z.string().optional(), index: z.number().int().optional(), type: z.enum(["reasoning.summary", "reasoning.encrypted", "reasoning.text"]).optional(), summary: z.string().optional(), text: z.string().optional(), signature: z.string().optional(), data: z.string().optional()})).optional(), annotations: z.array(z.object({type: z.string().optional(), url_citation: z.object({start_index: z.number().int().optional(), end_index: z.number().int().optional(), title: z.string().optional(), url: z.string().optional(), sources: z.object({}).optional(), type: z.string().optional()}).optional()})).optional(), tool_calls: z.array(z.object({index: z.number().int().optional(), type: z.string().optional(), id: z.string().optional(), function: z.object({name: z.string().optional(), arguments: z.string().optional()})})).optional()}); export const chatPromptTokensDetails = z.object({text_tokens: z.number().int().optional(), audio_tokens: z.number().int().optional(), image_tokens: z.number().int().optional(), cached_read_tokens: z.number().int().optional(), cached_write_tokens: z.number().int().optional()}); export const chatCompletionTokensDetails = z.object({text_tokens: z.number().int().optional(), accepted_prediction_tokens: z.number().int().optional(), audio_tokens: z.number().int().optional(), citation_tokens: z.number().int().optional(), num_search_queries: z.number().int().optional(), reasoning_tokens: z.number().int().optional(), image_tokens: z.number().int().optional(), rejected_prediction_tokens: z.number().int().optional()}); export const bifrostCost = z.object({input_tokens_cost: z.number().optional(), output_tokens_cost: z.number().optional(), reasoning_tokens_cost: z.number().optional(), citation_tokens_cost: z.number().optional(), search_queries_cost: z.number().optional(), request_cost: z.number().optional(), total_cost: z.number().optional()}); export const bifrostLLMUsage = z.object({prompt_tokens: z.number().int().optional(), prompt_tokens_details: chatPromptTokensDetails.optional(), completion_tokens: z.number().int().optional(), completion_tokens_details: chatCompletionTokensDetails.optional(), total_tokens: z.number().int().optional(), cost: bifrostCost.optional()}); export const modelProvider = z.enum(["openai", "azure", "anthropic", "bedrock", "cohere", "vertex", "vllm", "mistral", "ollama", "groq", "sgl", "parasail", "perplexity", "replicate", "cerebras", "deepseek", "gemini", "openrouter", "elevenlabs", "huggingface", "nebius", "xai", "runway", "fireworks"]); export const bifrostCacheDebug = z.object({cache_hit: z.boolean().optional(), cache_id: z.string().optional(), hit_type: z.string().optional(), requested_provider: z.string().optional(), requested_model: z.string().optional(), provider_used: z.string().optional(), model_used: z.string().optional(), input_tokens: z.number().int().optional(), threshold: z.number().optional(), similarity: z.number().optional()}); export const bifrostResponseExtraFields = z.object({request_type: z.string().optional(), provider: modelProvider.optional(), model_requested: z.string().optional(), model_deployment: z.string().optional(), latency: z.number().int().optional(), chunk_index: z.number().int().optional(), raw_request: z.object({}).optional(), raw_response: z.object({}).optional(), cache_debug: bifrostCacheDebug.optional()}); export const perplexitySearchResult = z.object({title: z.string().optional(), url: z.string().optional(), date: z.string().optional(), last_updated: z.string().optional(), snippet: z.string().optional(), source: z.string().optional()}); export const perplexityVideoResult = z.object({url: z.string().optional(), thumbnail_url: z.string().optional(), thumbnail_width: z.number().int().optional(), thumbnail_height: z.number().int().optional(), duration: z.number().optional()}); export const chatCompletionResponse = z.object({id: z.string().optional(), choices: z.array(z.object({index: z.number().int().optional(), finish_reason: z.string().optional(), log_probs: z.object({content: z.array(z.object({bytes: z.array(z.number().int()).optional(), logprob: z.number().optional(), token: z.string().optional(), top_logprobs: z.array(z.object({bytes: z.array(z.number().int()).optional(), logprob: z.number().optional(), token: z.string().optional()})).optional()})).optional(), refusal: z.array(z.object({bytes: z.array(z.number().int()).optional(), logprob: z.number().optional(), token: z.string().optional()})).optional(), text_offset: z.array(z.number().int()).optional(), token_logprobs: z.array(z.number()).optional(), tokens: z.array(z.string()).optional(), top_logprobs: z.array(z.record(z.string(), z.number())).optional()}).optional(), text: z.string().optional(), message: chatMessage.optional(), delta: z.object({role: z.string().optional(), content: z.string().optional(), refusal: z.string().optional(), audio: z.object({id: z.string().optional(), data: z.string().optional(), expires_at: z.number().int().optional(), transcript: z.string().optional()}).optional(), reasoning: z.string().optional(), reasoning_details: z.array(z.object({id: z.string().optional(), index: z.number().int().optional(), type: z.enum(["reasoning.summary", "reasoning.encrypted", "reasoning.text"]).optional(), summary: z.string().optional(), text: z.string().optional(), signature: z.string().optional(), data: z.string().optional()})).optional(), tool_calls: z.array(z.object({index: z.number().int().optional(), type: z.string().optional(), id: z.string().optional(), function: z.object({name: z.string().optional(), arguments: z.string().optional()})})).optional()}).optional()})).optional(), created: z.number().int().optional(), model: z.string().optional(), object: z.string().optional(), service_tier: z.string().optional(), system_fingerprint: z.string().optional(), usage: bifrostLLMUsage.optional(), extra_fields: bifrostResponseExtraFields.optional(), search_results: z.array(perplexitySearchResult).optional(), videos: z.array(perplexityVideoResult).optional(), citations: z.array(z.string()).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 }; /** * Cursor hybrid chat completions * * POST /cursor/v1/chat/completions * * Also accepts auth: BasicAuth, VirtualKeyAuth, ApiKeyAuth */ export const createApiCursorV1ChatCompletions = async (args: CreateApiCursorV1ChatCompletionsArgs, options?: CreateApiCursorV1ChatCompletionsOptions) => { const {baseUrl = "http://localhost:8080", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/cursor/v1/chat/completions${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(chatCompletionResponse, await res.json()) };