import {z} from 'zod' export type ConversationID = string; export type MemoryRetrievalRequest = {conversationId?: ConversationID | undefined, query?: string | undefined, beginDate?: string | undefined, endDate?: string | undefined, communicationsLimit?: number | undefined, observationsLimit?: number | undefined, summariesLimit?: number | undefined, relevanceThreshold?: number | undefined}; export type CreateApiV1StoresStoreIdProfilesProfileIdRecallArgs = {'Accept-Encoding'?: string | undefined, 'Content-Encoding'?: ('gzip' | 'deflate' | 'br' | 'compress') | undefined, body: MemoryRetrievalRequest}; export type CreateApiV1StoresStoreIdProfilesProfileIdRecallOptions = {baseUrl?: string | undefined, accountSidAuthToken?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const conversationID = z.string(); export const observationID = z.string(); export const recallObservationInfo = z.object({content: z.string().min(1).max(4096), occurredAt: z.string(), source: z.string().min(1).max(100), conversationIds: z.array(conversationID).optional(), id: observationID, createdAt: z.string(), updatedAt: z.string(), score: z.number().gte(0).lte(1).optional()}); export const summaryID = z.string(); export const recallSummaryInfo = z.object({source: z.string().max(100).optional(), content: z.string().min(1).max(4096), occurredAt: z.string(), conversationId: conversationID, id: summaryID, createdAt: z.string(), updatedAt: z.string(), score: z.number().gte(0).lte(1).optional()}); export const communicationContent = z.object({text: z.string().max(8388608).optional()}); export const participantType = z.enum(["HUMAN_AGENT", "CUSTOMER", "AI_AGENT", "AGENT", "UNKNOWN"]); export const participant = z.object({id: z.string(), name: z.string().max(256), type: participantType.optional(), profileId: z.string().optional(), address: z.string().max(254), channel: z.enum(["VOICE", "SMS", "RCS", "EMAIL", "WHATSAPP", "CHAT", "API", "SYSTEM"])}); export const communication = z.object({id: z.string(), channelId: z.string().max(256).optional(), content: communicationContent, createdAt: z.string().optional(), updatedAt: z.string().optional(), author: participant, recipients: z.array(z.object({id: z.string(), name: z.string().max(256), type: participantType.optional(), profileId: z.string().optional(), address: z.string().max(254), channel: z.enum(["VOICE", "SMS", "RCS", "EMAIL", "WHATSAPP", "CHAT", "API", "SYSTEM"]), deliveryStatus: z.enum(["INITIATED", "IN_PROGRESS", "DELIVERED", "COMPLETED", "FAILED"]).optional()}))}); export const memoryRetrievalResponse = z.object({observations: z.array(recallObservationInfo), summaries: z.array(recallSummaryInfo), communications: z.array(communication), meta: z.object({queryTime: z.number().int().gte(0).lte(600000)})}); 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 }; /** * Retrieve Memories * * POST /v1/Stores/{storeId}/Profiles/{profileId}/Recall */ export const createApiV1StoresStoreIdProfilesProfileIdRecall = async (args: CreateApiV1StoresStoreIdProfilesProfileIdRecallArgs, options?: CreateApiV1StoresStoreIdProfilesProfileIdRecallOptions) => { const {baseUrl = "https://memory.twilio.com", fetch: fetchFn = fetch, accountSidAuthToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Accept-Encoding'] != null) headers.set("Accept-Encoding", String(args['Accept-Encoding'])) if (args['Content-Encoding'] != null) headers.set("Content-Encoding", String(args['Content-Encoding'])) if (accountSidAuthToken !== undefined) headers.set('authorization', `Basic ${btoa(`${accountSidAuthToken.username}:${accountSidAuthToken.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/Stores/${encodeURIComponent(String(args.storeId))}/Profiles/${encodeURIComponent(String(args.profileId))}/Recall${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(memoryRetrievalResponse, await res.json()) };