import {z} from 'zod' export type ChatMessage = {role: string, content: string, timestamp?: (string | null) | undefined, metadata?: Record | undefined}; export type Scope = {org_id: string, user_id?: (string | null) | undefined, session_id?: (string | null) | undefined}; export type EpisodeMetadata = {agent_name?: (string | null) | undefined, episode_type?: (string | null) | undefined, topics?: Array | undefined, custom?: Record | undefined}; export type EpisodeOptions = {extract_preferences?: boolean | undefined, temporal_tracking?: boolean | undefined, auto_create_schema?: boolean | undefined, generate_embeddings?: boolean | undefined}; export type EpisodeIngestRequest = {episode_id?: (string | null) | undefined, messages: Array, scope: string | Scope, session_id?: (string | null) | undefined, metadata?: (EpisodeMetadata | null) | undefined, options?: (EpisodeOptions | null) | undefined, timezone?: (string | null) | undefined}; export type CreateApiIngestionEpisodeArgs = {body: EpisodeIngestRequest}; export type CreateApiIngestionEpisodeOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const turnTime = z.object({turn_index: z.number().int(), original: z.unknown(), timestamp: z.string(), timestamp_ms: z.number().int(), source: z.enum(["explicit", "relative", "arrival"]), uncertain: z.boolean()}); export const usage = z.object({tokens_in: z.number().int().optional(), tokens_out: z.number().int().optional()}); export const episodeIngestResponse = z.object({job_id: z.string(), episode_id: z.string(), status: z.string(), preferences_detected: z.number().int().nullable().optional(), estimated_time: z.number().int().nullable().optional(), message: z.string().nullable().optional(), turn_ids: z.array(z.string()).optional(), active_fragment_ids: z.array(z.string()).optional(), turn_times: z.array(turnTime).optional(), not_stored_forgotten: z.array(z.string()).optional(), usage: usage.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 }; /** * Ingest Episode * * POST /ingestion/episode */ export const createApiIngestionEpisode = async (args: CreateApiIngestionEpisodeArgs, options: CreateApiIngestionEpisodeOptions) => { const {baseUrl, fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/ingestion/episode${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(episodeIngestResponse, await res.json()) };