import {z} from 'zod' export type MailboxProvider = 'gmail' | 'microsoft'; export type EmailAddress = {address: string, name?: (string | null) | undefined}; export type WireAttachment = {storage_object_id: string, filename: string, content_type: string, size_bytes: number, disposition?: ('inline' | 'attachment') | undefined, content_id?: (string | null) | undefined}; export type EmailInboundEvent = {organization_id: string, account_id: string, provider: MailboxProvider, provider_thread_id: string, provider_message_id: string, rfc822_message_id: string, in_reply_to?: (string | null) | undefined, references?: Array | undefined, from: EmailAddress, to?: Array | undefined, cc?: Array | undefined, reply_to?: Array | undefined, subject: string, body_text?: (string | null) | undefined, body_html?: (string | null) | undefined, headers?: Array> | undefined, attachments?: Array | undefined, mime_size_bytes?: (number | null) | undefined, raw_storage_object_id?: (string | null) | undefined, received_at: string, received_idempotency_key: string}; export type IngestEmailThreadRequest = {event: EmailInboundEvent}; export type CreateApiV1EmailThreadsThreadIdArgs = {thread_id: string, body: IngestEmailThreadRequest}; export type CreateApiV1EmailThreadsThreadIdOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const ingestEmailThreadResponse = z.object({outcome: z.enum(["reply", "observe", "archive", "drop", "duplicate"]), reason: z.string().nullable().optional(), session_id: z.string().nullable().optional(), user_turn_id: z.string().nullable().optional(), assistant_turn_id: z.string().nullable().optional(), draft_id: z.string().nullable().optional(), auto_dispatched: z.boolean().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 }; /** * Ingest a canonical EmailInboundEvent for the given thread. Bypasses the vendor webhook; used by sandbox / replay / direct integrators. * * POST /v1/email/threads/{thread_id} */ export const createApiV1EmailThreadsThreadId = async (args: CreateApiV1EmailThreadsThreadIdArgs, options: CreateApiV1EmailThreadsThreadIdOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (APIKeyHeader !== undefined) headers.set("x-api-key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/v1/email/threads/${encodeURIComponent(String(args.thread_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(ingestEmailThreadResponse, await res.json()) };