import {z} from 'zod' export type ScopeSets = Array>; export type ChatRequestJson = {bypassCache?: boolean | undefined, labels?: Array | undefined, message: string, model?: (string | null) | undefined, scopes?: ScopeSets | undefined, sessionId?: (string | null) | undefined, stream?: boolean | undefined, suppressMarkers?: boolean | undefined}; export type CreateApiApiV1ContextIdChatArgs = {context_id: string, body: ChatRequestJson}; export type CreateApiApiV1ContextIdChatOptions = {baseUrl: string, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const citationJson = z.object({documentTitle: z.string().nullable().optional(), id: z.string(), kind: z.string(), marker: z.string(), occurredAt: z.string().nullable().optional(), positionPercent: z.number().int().gte(0).nullable().optional(), role: z.string().nullable().optional(), score: z.number(), snippet: z.string()}); export const memoryCategory = z.enum(["identity", "knowledge", "context"]); export const actionSummaryJson = z.object({actor: z.string(), memoryCategory: memoryCategory, object: z.string().nullable().optional(), occurredAt: z.string().nullable().optional(), summary: z.string(), verb: z.string()}); export const attributeSummaryJson = z.object({entityId: z.string(), id: z.string(), key: z.string(), memoryCategory: memoryCategory, value: z.string()}); export const correctionSummaryJson = z.object({entityId: z.string(), key: z.string(), newValue: z.string(), oldValue: z.string()}); export const entitySummaryJson = z.object({entityType: z.string(), id: z.string(), isNew: z.boolean(), memoryCategory: memoryCategory, name: z.string()}); export const instructionSummaryJson = z.object({description: z.string(), id: z.string(), label: z.string()}); export const relationSummaryJson = z.object({label: z.string(), memoryCategory: memoryCategory, object: z.string(), subject: z.string()}); export const uncertaintySummaryJson = z.object({about: z.string(), reason: z.string()}); export const extractionResultJson = z.object({actions: z.array(actionSummaryJson), attributes: z.array(attributeSummaryJson), corrections: z.array(correctionSummaryJson), entities: z.array(entitySummaryJson), instructions: z.array(instructionSummaryJson), relations: z.array(relationSummaryJson), turnId: z.string(), uncertainties: z.array(uncertaintySummaryJson)}); export const chatResponseJson = z.object({citations: z.array(citationJson), memoryUpdates: extractionResultJson, reply: z.string(), sessionId: z.string(), traceId: z.string()}); 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.5 — Spectron-as-agent chat endpoint. Resolves the session, retrieves context via the unified /query router, and calls the configured LLM provider; then, only after a successful synthesis (or a tier-2 cache hit), stores the user message and the assistant response via /facts and emits a response_trace. A failed synthesis writes no turn, fact, or response_trace (a retrieval_trace recording the query may still be written). Set `stream=true` for SSE. * * POST /api/v1/{context_id}/chat */ export const createApiApiV1ContextIdChat = async (args: CreateApiApiV1ContextIdChatArgs, options: CreateApiApiV1ContextIdChatOptions) => { 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))}/chat${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(chatResponseJson, await res.json()) };