import {z} from 'zod' export type MonitorMessageRole = 'system' | 'user' | 'assistant' | 'tool' | 'developer'; export type JSONPrimitive = string | number | number | boolean | null; export type JSONValueInput = JSONPrimitive | Array | {[key: string]: JSONValueInput}; export type MonitorMessageContentPart = {type: string, text?: (string | null) | undefined, source?: ({[key: string]: JSONValueInput} | null) | undefined, input?: ({[key: string]: JSONValueInput} | null) | undefined, name?: (string | null) | undefined, id?: (string | null) | undefined} | {[key: string]: unknown}; export type Function = {arguments: string, name: string} | {[key: string]: unknown}; export type ChatCompletionMessageFunctionToolCall = {id: string, function: Function, type: 'function'} | {[key: string]: unknown}; export type MonitorTool = {[key: string]: JSONValueInput}; export type PIIScannerConfig = {pii_types?: Array | undefined}; export type SystemPromptScannerConfig = {system_prompt?: string | undefined}; export type CreateMonitorRequest = {text?: (string | null) | undefined, messages?: (Array<{role: MonitorMessageRole, content?: (string | Array | null) | undefined, tool_calls?: (Array | null) | undefined, tool_call_id?: (string | null) | undefined, name?: (string | null) | undefined, type?: string | undefined} | {type: string, role?: ('system' | 'user' | 'assistant' | 'tool' | 'developer') | undefined} | {[key: string]: unknown}> | null) | undefined, tools?: (Array | null) | undefined, metadata?: ({[key: string]: JSONValueInput} | null) | undefined, categories?: ({[key: string]: string} | Array | Array<{[key: string]: string}> | null) | undefined, rules?: ({[key: string]: string} | Array | Array<{[key: string]: string}> | null) | undefined, reasoning_mode?: ('off' | 'thinking' | 'hybrid' | null) | undefined, policy_id?: (string | null) | undefined, policy_ids?: (Array | null) | undefined, policy_version_id?: (string | null) | undefined, policy_snapshot_id?: (string | null) | undefined, scanner_configs?: (Array<{[key: string]: PIIScannerConfig | SystemPromptScannerConfig | {[key: string]: unknown}}> | null) | undefined, litellm_metadata?: ({[key: string]: JSONValueInput} | null) | undefined}; export type CreateApiCygnalMonitorArgs = {body: CreateMonitorRequest}; export type CreateApiCygnalMonitorOptions = {baseUrl?: string | undefined, GraySwanBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const ruleDescription = z.object({rule: z.number().int().optional(), name: z.string().optional(), description: z.string().optional()}).and(z.record(z.string(), z.unknown())); export const ignoredInput = z.object({type: z.enum(["media", "transcript"]), reason: z.enum(["text_moderation_only", "unsupported_transcript_shape"]), description: z.string()}).and(z.record(z.string(), z.unknown())); export const appliedPolicy = z.object({id: z.string(), name: z.string(), version_id: z.string().optional()}).and(z.record(z.string(), z.unknown())); export const monitoringResponse = z.object({violation: z.number().optional(), observe_violation: z.number().nullable().optional(), violated_rules: z.array(z.number().int()).optional(), violated_rule_descriptions: z.array(ruleDescription).optional(), ignored_inputs: z.array(ignoredInput).optional(), ipi: z.boolean().optional(), mutation: z.boolean().optional(), scanner_output: z.record(z.string(), z.unknown()).nullable().optional(), reasoning: z.string().nullable().optional(), input_tokens: z.number().int().nullable().optional(), output_tokens: z.number().int().nullable().optional(), activity_id: z.string().nullable().optional(), block_message: z.string().nullable().optional(), applied_policies: z.array(appliedPolicy).nullable().optional(), error: z.boolean().optional(), error_message: z.string().nullable().optional(), judgment_deferred: z.boolean().optional()}).and(z.record(z.string(), z.unknown())); 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 }; /** * Cygnal Monitor * * POST /cygnal/monitor * * Also accepts auth: x-grayswan-api-key, grayswan-api-key, x-gs-api-key, gs-api-key, gs_api_key */ export const createApiCygnalMonitor = async (args: CreateApiCygnalMonitorArgs, options?: CreateApiCygnalMonitorOptions) => { const {baseUrl = "https://api.grayswan.ai", fetch: fetchFn = fetch, GraySwanBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (GraySwanBearer !== undefined) headers.set('authorization', `Bearer ${GraySwanBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/cygnal/monitor${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(monitoringResponse, await res.json()) };