import {z} from 'zod' export type SendRecordingUrl = boolean; export type InitiateAICallRequest = {From: string, To: string, AIAssistantId: string, AIAssistantVersion?: string | undefined, AIAssistantDynamicVariables?: {[key: string]: string} | undefined, CallerId?: string | undefined, StatusCallback?: string | undefined, StatusCallbackEvent?: string | undefined, StatusCallbackMethod?: ('GET' | 'POST') | undefined, StatusCallbacks?: Array | undefined, CustomHeaders?: Array<{name: string, value: string}> | undefined, ConversationCallback?: string | undefined, ConversationCallbackMethod?: ('GET' | 'POST') | undefined, ConversationCallbacks?: Array | undefined, MachineDetection?: ('Enable' | 'Disable' | 'DetectMessageEnd') | undefined, DetectionMode?: ('Premium' | 'Regular' | 'PremiumCallScreening') | undefined, AsyncAmd?: boolean | undefined, AsyncAmdStatusCallback?: string | undefined, AsyncAmdStatusCallbackMethod?: ('GET' | 'POST') | undefined, MachineDetectionTimeout?: number | undefined, MachineDetectionPromptEndTimeout?: number | undefined, MachineDetectionSpeechThreshold?: number | undefined, MachineDetectionSpeechEndThreshold?: number | undefined, MachineDetectionSilenceTimeout?: number | undefined, MachineDetectionBeepProfile?: ('both' | 'freq_only') | undefined, MachineDetectionBeepMinFrequency?: number | undefined, MachineDetectionBeepMaxFrequency?: number | undefined, MachineDetectionBeepMinToneDuration?: number | undefined, MachineDetectionBeepSpectralConfirmation?: boolean | undefined, MachineDetectionBeepSpectralWindow?: number | undefined, MachineDetectionBeepSpectralMinPurity?: number | undefined, MachineDetectionBeepSpectralRejectFaxCng?: boolean | undefined, Passports?: string | undefined, TimeLimit?: number | undefined, Timeout?: number | undefined, Record?: boolean | undefined, RecordingChannels?: ('mono' | 'dual') | undefined, RecordingStatusCallback?: string | undefined, RecordingStatusCallbackMethod?: ('GET' | 'POST') | undefined, RecordingStatusCallbackEvent?: string | undefined, RecordingTimeout?: number | undefined, RecordingTrack?: ('inbound' | 'outbound' | 'both') | undefined, Trim?: ('trim-silence' | 'do-not-trim') | undefined, SendRecordingUrl?: SendRecordingUrl | undefined, PreferredCodecs?: string | undefined, SipAuthUsername?: string | undefined, SipAuthPassword?: string | undefined, SipRegion?: ('US' | 'Europe' | 'Canada' | 'Australia' | 'Middle East') | undefined}; export type CreateApiTexmlAiCallsConnectionIdArgs = {connection_id: string, body: InitiateAICallRequest}; export type CreateApiTexmlAiCallsConnectionIdOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const initiateAICallResult = z.object({from: z.string().optional(), to: z.string().optional(), status: z.string().optional(), call_sid: 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 }; /** * Initiate an outbound AI call * * POST /texml/ai_calls/{connection_id} */ export const createApiTexmlAiCallsConnectionId = async (args: CreateApiTexmlAiCallsConnectionIdArgs, options?: CreateApiTexmlAiCallsConnectionIdOptions) => { const {baseUrl = "https://api.telnyx.com/v2", 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(/\/+$/, '')}/texml/ai_calls/${encodeURIComponent(String(args.connection_id))}${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(initiateAICallResult, await res.json()) };