import {z} from 'zod' export type Scope = {org_id: string, user_id?: (string | null) | undefined, session_id?: (string | null) | undefined}; export type IngestTurn = {text: string, role: 'user' | 'assistant', timestamp: string, observations?: Array | undefined}; export type IngestMemoryOptions = {write_active?: boolean | undefined, write_passive?: boolean | undefined, ingest_mode?: ('sequential' | 'batched' | null) | undefined}; export type IngestMemoryRequest = {timezone?: (string | null) | undefined, scope: string | Scope, session_id?: (string | null) | undefined, agent_id?: (string | null) | undefined, turns: Array, supersedes?: (Array | null) | undefined, options?: (IngestMemoryOptions | null) | undefined, inactivity_timeout_seconds?: (number | null) | undefined, metadata?: (Record | null) | undefined}; export type CreateApiIngestionMemoryArgs = {body: IngestMemoryRequest}; export type CreateApiIngestionMemoryOptions = {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 ingestMemoryResponse = z.object({turn_times: z.array(turnTime).optional(), job_id: z.string(), active_fragment_ids: z.array(z.string()).optional(), turn_ids: z.array(z.string()).optional(), not_stored_forgotten: z.array(z.string()).optional(), superseded: z.array(z.string()).optional(), supersede_errors: z.array(z.string()).optional(), passive_job_id: z.string().nullable().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 }; /** * Unified dual-write ingest (active memory + HelixDB) * * POST /ingestion/memory */ export const createApiIngestionMemory = async (args: CreateApiIngestionMemoryArgs, options: CreateApiIngestionMemoryOptions) => { 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/memory${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(ingestMemoryResponse, await res.json()) };