import {z} from 'zod' export type TextContentPart = {type: 'text', text: string}; export type FileInputMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'application/pdf' | 'text/plain'; export type Base64FileSource = {type: 'base64', filename: string, media_type: FileInputMimeType, data: string}; export type FileIdSource = {type: 'file_id', file_id: string}; export type FileContentPart = {type: 'file', source: Base64FileSource | FileIdSource}; export type UserMessageInputItem = {type: 'user_message', content: Array}; export type ClientToolResultItem = {type: 'client_tool_result', tool_call_id: string, result: string, is_error: boolean, error_type?: ('user_rejected' | 'external_server' | 'external_client' | 'customer_auth' | 'client_timeout' | 'unknown' | null) | undefined}; export type ContextualUpdatePlacement = 'in_place' | 'end'; export type ContextualUpdateInputItem = {type: 'contextual_update', text: string, context_id: string, placement?: ContextualUpdatePlacement | undefined}; export type SendConversationMessageRequest = {input: Array, background?: boolean | undefined}; export type CreateApiV1ConvaiConversationsConversationIdMessagesArgs = {conversation_id: string, 'xi-api-key'?: (string | null) | undefined, body: SendConversationMessageRequest}; export type CreateApiV1ConvaiConversationsConversationIdMessagesOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const agentOutputStatus = z.enum(["in_progress", "completed", "requires_action", "failed", "timed_out"]); export const textOutputItem = z.object({type: z.literal("text").optional(), role: z.literal("agent"), id: z.string().nullable().optional(), text: z.string(), created_at_unix_ms: z.number().int().nullable().optional()}); export const agentOutputError = z.object({type: z.string(), code: z.string(), message: z.string()}); export const clientToolCallRequiredAction = z.object({type: z.literal("client_tool_call").optional(), tool_call_id: z.string(), tool_name: z.string(), parameters: z.record(z.string(), z.unknown())}); export const conversationTurn = z.object({turn_id: z.string(), status: agentOutputStatus, output: z.array(textOutputItem).optional(), error: agentOutputError.nullable().optional(), required_actions: z.array(clientToolCallRequiredAction).optional(), stream_cursor: 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 }; /** * Send Conversation Message * * POST /v1/convai/conversations/{conversation_id}/messages */ export const createApiV1ConvaiConversationsConversationIdMessages = async (args: CreateApiV1ConvaiConversationsConversationIdMessagesArgs, options: CreateApiV1ConvaiConversationsConversationIdMessagesOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['xi-api-key'] != null) headers.set("xi-api-key", String(args['xi-api-key'])) const url = `${baseUrl.replace(/\/+$/, '')}/v1/convai/conversations/${encodeURIComponent(String(args.conversation_id))}/messages${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(conversationTurn, await res.json()) };