import {z} from 'zod' export type SystemContextVariableSpec = {name: string, type: 'string' | 'int' | 'float' | 'bool' | 'enum', enum_values?: (Array | null) | undefined, description?: (string | null) | undefined}; export type LegacySystemContextVariableSpec = {name: string, type: 'string' | 'int' | 'float' | 'bool' | 'enum', enum_values?: (Array | null) | undefined, description?: (string | null) | undefined, source?: ('system' | null) | undefined, reask_cap: unknown}; export type ModelConfig = {temperature?: (number | null) | undefined, max_tokens?: (number | null) | undefined, top_p?: (number | null) | undefined, stop_sequences?: (Array | null) | undefined, reasoning_effort?: ('none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | null) | undefined, request_timeout_ms?: (number | null) | undefined, thinking_budget?: (number | null) | undefined}; export type ModelChainEntry = {model: string, config?: ModelConfig | undefined}; export type CurrentTimeSettings = {enabled?: (boolean | null) | undefined, timezone?: (string | null) | undefined}; export type InputArgType = 'default' | 'pinned'; export type InputArgConfig = {value: unknown, type?: InputArgType | undefined}; export type ToolRef = {kind: 'api' | 'integration' | 'util' | 'kb', id?: (string | null) | undefined, slug?: (string | null) | undefined, output_bindings?: ({[key: string]: string} | null) | undefined, input_defaults?: ({[key: string]: InputArgConfig} | null) | undefined}; export type KnowledgeBaseRef = {id: string, description?: (string | null) | undefined, clearance_level?: (number | null) | undefined}; export type AssistantCreateComposite = {name: string, description?: (string | null) | undefined, persona?: (string | null) | undefined, system_prompt?: (string | null) | undefined, system_context_variables?: (Array | null) | undefined, context_variables?: (Array | null) | undefined, variable_defaults?: ({[key: string]: unknown} | null) | undefined, channel_specific_config?: ({[key: string]: unknown} | null) | undefined, router_config_id?: (string | null) | undefined, model_settings?: (ModelChainEntry | null) | undefined, current_time?: (CurrentTimeSettings | null) | undefined, analyzer_model_settings?: (ModelChainEntry | null) | undefined, memory_enabled?: boolean | undefined, router_model_settings?: ({[key: string]: unknown} | null) | undefined, metadata?: ({[key: string]: unknown} | null) | undefined, kb_clearance_level?: (number | null) | undefined, kb_audience_tags?: (Array | null) | undefined, knowledge_gap_analysis_enabled?: boolean | undefined, tool_refs?: (Array | null) | undefined, knowledge_base_refs?: (Array | null) | undefined, instructions?: string | undefined, workflow_description?: (string | null) | undefined}; export type CreateApiV1AssistantsArgs = {body: AssistantCreateComposite}; export type CreateApiV1AssistantsOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const contextVarSpec = z.object({name: z.string(), type: z.enum(["string", "int", "float", "bool", "enum"]), source: z.enum(["system", "derived"]).optional(), enum_values: z.array(z.string()).nullable().optional(), reask_cap: z.number().int().nullable().optional(), description: z.string().nullable().optional()}); export const firstSpeakingConfig = z.object({first_speaker: z.enum(["agent", "user"]).optional(), mode: z.enum(["static", "dynamic"]).optional(), text: z.string().max(1000).nullable().optional(), instructions: z.string().max(2000).nullable().optional(), interruptible: z.boolean().optional(), ai_disclosure_text: z.string().max(500).nullable().optional()}); export const warmTransferChannelConfig = z.object({briefing_template: z.string().max(4000).nullable().optional()}); export const channelConfig = z.object({prompt: z.string().nullable().optional(), first_speaking_config: firstSpeakingConfig.nullable().optional(), warm_transfer: warmTransferChannelConfig.nullable().optional()}); export const modelConfig = z.object({temperature: z.number().gte(0).lte(2).nullable().optional(), max_tokens: z.number().int().gte(1).nullable().optional(), top_p: z.number().gte(0).lte(1).nullable().optional(), stop_sequences: z.array(z.string()).nullable().optional(), reasoning_effort: z.enum(["none", "minimal", "low", "medium", "high", "xhigh", "max"]).nullable().optional(), request_timeout_ms: z.number().int().gte(1000).lte(20000).nullable().optional(), thinking_budget: z.number().int().gte(1).nullable().optional()}); export const modelChainEntry = z.object({model: z.string(), config: modelConfig.optional()}); export const currentTimeSettings = z.object({enabled: z.boolean().nullable().optional(), timezone: z.string().nullable().optional()}); export const systemContextVariableSpec = z.object({name: z.string(), type: z.enum(["string", "int", "float", "bool", "enum"]), enum_values: z.array(z.string()).nullable().optional(), description: z.string().nullable().optional()}); export const agentRevisionResponse = z.object({id: z.string(), agent_id: z.string(), name: z.string(), description: z.string().nullable().optional(), persona: z.string().nullable().optional(), system_prompt: z.string().nullable().optional(), context_variables: z.array(contextVarSpec).nullable().optional(), variable_defaults: z.record(z.string(), z.unknown()).nullable().optional(), tool_refs: z.array(z.record(z.string(), z.unknown())).nullable().optional(), knowledge_base_refs: z.array(z.record(z.string(), z.unknown())).nullable().optional(), platform_tools: z.record(z.string(), z.unknown()).optional(), policies_enabled: z.boolean().optional(), policy_refs: z.array(z.record(z.string(), z.unknown())).nullable().optional(), channel_specific_config: z.record(z.string(), channelConfig).nullable().optional(), router_config_id: z.string().nullable().optional(), model_settings: modelChainEntry.nullable().optional(), analyzer_model_settings: modelChainEntry.nullable().optional(), workflow_enabled: z.boolean().optional(), memory_enabled: z.boolean().optional(), current_time: currentTimeSettings.nullable().optional(), kb_clearance_level: z.number().int().nullable().optional(), kb_audience_tags: z.array(z.string()).optional(), continue_after_flow: z.boolean().nullable().optional(), voice_call_settings: z.record(z.string(), z.unknown()).nullable().optional(), created_by: z.string().nullable().optional(), created_at: z.string(), updated_at: z.string(), published_at: z.string().nullable().optional(), system_context_variables: z.array(systemContextVariableSpec).nullable()}); export const releaseGateMode = z.enum(["off", "advisory"]); export const agentResponse = z.object({id: z.string(), organization_id: z.string(), name: z.string(), description: z.string().nullable().optional(), active_revision_id: z.string().nullable().optional(), active_revision: agentRevisionResponse.nullable().optional(), metadata: z.record(z.string(), z.unknown()).optional(), platform_tools: z.record(z.string(), z.unknown()).optional(), knowledge_gap_analysis_enabled: z.boolean().optional(), release_suite_id: z.string().nullable().optional(), release_gate_mode: releaseGateMode.optional(), release_gate_max_failures: z.number().int().optional(), max_active_calls: z.number().int().nullable().optional(), created_at: z.string(), updated_at: z.string()}); export const inputArgType = z.enum(["default", "pinned"]); export const inputArgConfig = z.object({value: z.unknown(), type: inputArgType.optional()}); export const toolType = z.enum(["api_call", "call_transfer"]); export const headerConfig = z.object({key: z.string(), value: z.string(), secure: z.boolean().optional()}); export const queryParamConfig = z.object({key: z.string(), value: z.string(), secure: z.boolean().optional()}); export const variableDefinition = z.object({name: z.string(), type: z.enum(["str", "int", "float", "bool"]).optional(), description: z.string().nullable().optional(), required: z.boolean().optional()}); export const retryConfig = z.object({max_retries: z.number().int().gte(0).lte(5).optional(), base_delay_seconds: z.number().gte(0.1).lte(30).optional(), max_delay_seconds: z.number().gte(1).lte(120).optional(), jitter: z.boolean().optional()}); export const aPICallConfiguration = z.object({url: z.string(), method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).optional(), headers: z.array(headerConfig).optional(), query_params: z.array(queryParamConfig).optional(), body: z.record(z.string(), z.unknown()).optional(), timeout: z.number().int().gte(1).lte(300).optional(), variables: z.array(variableDefinition).optional(), retry: retryConfig.nullable().optional()}); export const destinationSourceConfig = z.object({type: z.literal("api_tool").optional(), tool_id: z.string(), input_mapping: z.record(z.string(), z.union([z.string(), z.number().int(), z.number(), z.boolean()]).nullable()).optional(), response_path: z.string()}); export const transferTargetView = z.object({destination: z.string().nullable().optional(), destination_source: destinationSourceConfig.nullable().optional(), mode: z.enum(["cold", "warm"]).optional()}); export const responseFieldMapping = z.object({path: z.string(), alias: z.string().nullable().optional()}); export const responseFieldSelector = z.object({field_mappings: z.array(responseFieldMapping).optional()}); export const toolCompatibilityFindingResponse = z.object({severity: z.enum(["blocking", "advisory"]), assistant_id: z.string(), assistant_revision_id: z.string(), revision_state: z.enum(["active", "candidate", "historical"]), finding_type: z.string(), field_path: z.string(), detail: z.string(), configuration_scope: z.enum(["assistant_tool_default", "agent_node_tool", "action_step_tool"]), workflow_id: z.string().nullable().optional(), workflow_revision_id: z.string().nullable().optional(), component_node_id: z.string().nullable().optional(), graph_node_id: z.string().nullable().optional(), graph_node_name: z.string().nullable().optional(), step_id: z.string().nullable().optional(), tool_ref_index: z.number().int().nullable().optional()}); export const toolCompatibilityReportResponse = z.object({tool_id: z.string(), old_revision_id: z.string().nullable(), new_revision_id: z.string(), findings: z.array(toolCompatibilityFindingResponse).optional(), has_blocking: z.boolean(), active_blocking_count: z.number().int(), active_blocking_finding_count: z.number().int(), active_finding_count: z.number().int(), affected_assistant_count: z.number().int()}); export const toolRevisionResponse = z.object({id: z.string(), tool_id: z.string(), name: z.string(), description: z.string().nullable(), configuration: aPICallConfiguration.nullable().optional(), transfer_target: transferTargetView.nullable().optional(), response_schema: responseFieldSelector.nullable().optional(), status: z.string(), has_secrets: z.boolean().optional(), input_defaults: z.record(z.string(), inputArgConfig).nullable().optional(), compatibility: toolCompatibilityReportResponse.nullable().optional(), created_by: z.string().nullable(), created_at: z.string(), updated_at: z.string(), default_count: z.number().int(), pinned_count: z.number().int(), stale_input_fields: z.array(z.string()), merged_input_preview: z.record(z.string(), z.unknown())}); export const toolResponse = z.object({id: z.string(), organization_id: z.string(), name: z.string(), description: z.string().nullable(), tool_type: toolType, active_revision_id: z.string().nullable(), active_revision: toolRevisionResponse.nullable().optional(), metadata: z.record(z.string(), z.unknown()).optional(), created_at: z.string(), updated_at: z.string()}); export const workflowToolResponse = z.object({tool: toolResponse}); export const workflowRevisionResponse = z.object({id: z.string(), workflow_id: z.string(), name: z.string(), description: z.string().nullable().optional(), instructions: z.string(), compiled_graph: z.record(z.string(), z.unknown()).nullable().optional(), executable_graph: z.record(z.string(), z.unknown()).nullable().optional(), quality_report: z.record(z.string(), z.unknown()).nullable().optional(), compilation_errors: z.array(z.string()).nullable().optional(), compilation_strategy: z.string(), compilation_status: z.string(), compilation_task_id: z.string().nullable().optional(), compilation_input_hash: z.string().nullable().optional(), trigger_type: z.string(), trigger_config: z.record(z.string(), z.unknown()), router_config_id: z.string().nullable().optional(), analyzer_model_settings: modelChainEntry.nullable().optional(), router_model_settings: modelChainEntry.nullable().optional(), policy_ids: z.array(z.unknown()).optional(), tool_input_defaults: z.record(z.string(), z.record(z.string(), inputArgConfig)).nullable().optional(), tools: z.array(workflowToolResponse).optional(), knowledge_base_ids: z.array(z.string()).optional(), created_by: z.string().nullable().optional(), created_at: z.string(), updated_at: z.string(), graph_version: z.number().int().optional(), warnings: z.array(z.string()).optional()}); export const workflowResponse = z.object({id: z.string(), organization_id: z.string(), name: z.string(), description: z.string().nullable().optional(), kind: z.string().optional(), active_revision_id: z.string().nullable().optional(), active_revision: workflowRevisionResponse.nullable().optional(), metadata: z.record(z.string(), z.unknown()).optional(), created_at: z.string(), updated_at: z.string()}); export const assistantCompositeResponse = z.object({agent: agentResponse, agent_revision: agentRevisionResponse, workflow: workflowResponse, workflow_revision_id: 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 }; /** * Create an assistant (agent + workflow) as one unit * * POST /v1/assistants */ export const createApiV1Assistants = async (args: CreateApiV1AssistantsArgs, options: CreateApiV1AssistantsOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (APIKeyHeader !== undefined) headers.set("x-api-key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/v1/assistants${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(assistantCompositeResponse, await res.json()) };