import {z} from 'zod' export type ElaborateRequestJson = {budget?: (number | null) | undefined, dryRun?: boolean | undefined, entityRef?: (string | null) | undefined, sweep?: boolean | undefined}; export type CreateApiApiV1ContextIdElaborateArgs = {context_id: string, body: ElaborateRequestJson}; export type CreateApiApiV1ContextIdElaborateOptions = {baseUrl: string, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const elaborateProposedRelationJson = z.object({label: z.string(), object: z.string(), subject: z.string()}); export const elaborateOutcomeJson = z.object({dryRun: z.boolean(), entityName: z.string(), entityType: z.string(), proposedRelations: z.array(elaborateProposedRelationJson), relationsEmitted: z.number().int().gte(0), traceId: z.string()}); export const elaborateResponseJson = z.object({outcomes: z.array(elaborateOutcomeJson), relationsEmitted: z.number().int().gte(0)}); 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 11a: elaborate links for a single entity or sweep low-relation entities * * POST /api/v1/{context_id}/elaborate */ export const createApiApiV1ContextIdElaborate = async (args: CreateApiApiV1ContextIdElaborateArgs, options: CreateApiApiV1ContextIdElaborateOptions) => { 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))}/elaborate${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(elaborateResponseJson, await res.json()) };