import {z} from 'zod' export type ResponseInputMessage = {type: 'message', role: 'user' | 'assistant', content: string}; export type AgentSessionId = string; export type LibraryId = string; export type AssetId = string; export type Scope = {library_ids: Array, asset_ids: Array}; export type WorkflowReference = {id: string, version: string}; export type StructuredTextFormat = {type: 'json_schema', name: string, schema: {[key: string]: unknown}}; export type ExecutionPolicy = 'local_only' | 'prefer_local' | 'cloud_allowed' | 'cloud_required'; export type CreateResponseRequest = {input: Array, agent_session_id?: (AgentSessionId | null) | undefined, scope: Scope, instructions?: (string | null) | undefined, workflow?: (WorkflowReference | null) | undefined, text?: ({format?: StructuredTextFormat | undefined}) | undefined, execution_policy: ExecutionPolicy, stream: boolean, include?: (Array<'tool_events' | 'citations'>) | undefined}; export type CreateApiV1ResponsesArgs = {'Idempotency-Key': string, 'Last-Event-ID'?: string | undefined, body: CreateResponseRequest}; export type CreateApiV1ResponsesOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const requestId = z.string(); export const runtimeLocation = z.enum(["local", "cloud"]); export const execution = z.object({location: runtimeLocation, capability_id: z.string().nullable().optional(), capability_version: z.string().nullable().optional()}); export const usage = z.object({billable: z.boolean(), quantity: z.number().gte(0), unit: z.string(), credits: z.number().gte(0).optional()}); export const responseId = z.string(); export const agentSessionId = z.string(); export const responseOutputItem = z.object({type: z.enum(["message", "tool_summary"]), content: z.string()}); export const evidenceId = z.string(); export const assetId = z.string(); export const evidenceLocator = z.object({type: z.enum(["local", "cloud"]), url: z.string()}); export const evidence = z.object({id: evidenceId, asset_id: assetId, kind: z.enum(["transcript", "frame", "video_clip", "segment"]), start_seconds: z.number().gte(0), end_seconds: z.number().gte(0), quote: z.string(), locators: z.array(evidenceLocator)}); export const artifactId = z.string(); export const jobId = z.string(); export const artifact = z.object({id: artifactId, kind: z.enum(["clip_gallery", "comparison", "timeline", "highlight_reel", "storyboard", "dataset_manifest", "review_queue"]), schema_version: z.string(), job_id: jobId.nullable().optional(), response_id: responseId.nullable().optional(), evidence_ids: z.array(evidenceId), payload: z.record(z.string(), z.unknown()), created_at: z.string()}); export const response = z.object({response_id: responseId, agent_session_id: agentSessionId, status: z.enum(["in_progress", "completed", "failed", "canceled"]), output: z.array(responseOutputItem), citations: z.array(evidence), artifacts: z.array(artifact)}); export const responseEnvelope = z.object({request_id: requestId, execution: execution, usage: usage, warnings: z.array(z.string()), data: response}); 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 }; /** * Create a constrained Agent response * * POST /v1/responses * * Also accepts auth: apiKeyAuth */ export const createApiV1Responses = async (args: CreateApiV1ResponsesArgs, options?: CreateApiV1ResponsesOptions) => { const {baseUrl = "https://api.cerul.ai", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (args['Last-Event-ID'] != null) headers.set("Last-Event-ID", String(args['Last-Event-ID'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/responses${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(responseEnvelope, await res.json()) };