import {z} from 'zod' export type ScopeSets = Array>; export type GeoNearJson = {lat: number, lng: number, radiusKm: number}; export type GeoFilterJson = {near?: (GeoNearJson | null) | undefined, within?: (string | null) | undefined}; export type MemoryQueryMode = 'hybrid' | 'vector' | 'bm25' | 'graph'; export type QueryMemoryRequestJson = {asOf?: (string | null) | undefined, atInstant?: (string | null) | undefined, include?: (Array | null) | undefined, includeDuplicates?: (boolean | null) | undefined, k?: number | undefined, labels?: Array | undefined, lens?: ScopeSets | undefined, location?: (GeoFilterJson | null) | undefined, mode?: (MemoryQueryMode | null) | undefined, query: string, scopeView?: (string | null) | undefined, sessionId?: (string | null) | undefined, source?: (string | null) | undefined, validFrom?: (string | null) | undefined, validUntil?: (string | null) | undefined}; export type CreateApiApiV1ContextIdQueryArgs = {context_id: string, body: QueryMemoryRequestJson}; export type CreateApiApiV1ContextIdQueryOptions = {baseUrl: string, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const queryKind = z.enum(["direct_lookup", "hybrid", "full_context"]); export const resourceRef = z.union([z.object({entityType: z.string(), kind: z.literal("entity"), name: z.string()}), z.object({entityType: z.string(), key: z.string(), kind: z.literal("attribute"), name: z.string()}), z.object({kind: z.literal("relation"), label: z.string(), objectName: z.string(), objectType: z.string(), subjectName: z.string(), subjectType: z.string()}), z.object({actorName: z.string(), actorType: z.string(), kind: z.literal("action"), objectName: z.string().nullable().optional(), objectType: z.string().nullable().optional()}), z.object({documentId: z.string(), kind: z.literal("document"), position: z.number().int().nullable().optional()}), z.object({kind: z.literal("session"), position: z.number().int().nullable().optional(), sessionId: z.string(), turnId: z.string().nullable().optional()})]); export const resultKind = z.enum(["attribute", "entity", "action", "chunk", "memory_chunk", "turn", "section"]); export const memoryHitJson = z.object({dateNotes: z.string().nullable().optional(), id: z.string(), occurredAt: z.string().nullable().optional(), resource: resourceRef.nullable().optional(), score: z.number(), source: resultKind, text: z.string()}); export const queryWindowJson = z.object({end: z.string(), phrase: z.string(), precision: z.string(), start: z.string()}); export const tier = z.enum(["direct", "cache", "hybrid", "escalated"]); export const queryTraceJson = z.object({latencyMs: z.number().int().gte(0), resolutionTier: tier, retrievedCount: z.number().int().gte(0), tierReason: z.string(), topScores: z.array(z.number()), traceId: z.string()}); export const queryMemoryResponseJson = z.object({classificationKind: queryKind, contextHits: z.array(memoryHitJson).optional(), hits: z.array(memoryHitJson), queryMs: z.number().int().gte(0), queryWindow: queryWindowJson.nullable().optional(), seedEntities: z.array(z.string()), tier: tier, trace: queryTraceJson}); 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 }; /** * Phase 7 unified query: four-tier router + fused ranker over the substrate * * POST /api/v1/{context_id}/query */ export const createApiApiV1ContextIdQuery = async (args: CreateApiApiV1ContextIdQueryArgs, options: CreateApiApiV1ContextIdQueryOptions) => { const {baseUrl, fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKey !== undefined) headers.set('authorization', `Bearer ${apiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/${encodeURIComponent(String(args.context_id))}/query${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(queryMemoryResponseJson, await res.json()) };