import {z} from 'zod' export type CreateApiAppAutomationsInterpretArgs = {body: {intent: string, context?: (Record | null) | undefined}}; export type CreateApiAppAutomationsInterpretOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const appAutomationConfigFieldSchema = z.object({label: z.string(), value: z.string(), filledByAi: z.boolean()}); export const appAutomationSpecSchema = z.object({id: z.string(), intentText: z.string(), title: z.string(), summary: z.string(), signal: z.string(), signalLabel: z.string(), trigger: z.string(), direction: z.enum(["increase", "decrease", "pause", "launch"]), deltaPct: z.number().int(), target: z.string(), scope: z.string(), channels: z.array(z.string()), guardrails: z.string(), requiredConfig: z.array(appAutomationConfigFieldSchema), confidence: z.string()}); export const createApiAppAutomationsInterpretResponse = z.array(appAutomationSpecSchema); 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 }; /** * Interpret a natural-language intent into proposed automations * * POST /app/automations/interpret */ export const createApiAppAutomationsInterpret = async (args: CreateApiAppAutomationsInterpretArgs, options: CreateApiAppAutomationsInterpretOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/app/automations/interpret${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(createApiAppAutomationsInterpretResponse, await res.json()) };