Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

124 KB
Raw Blame
// This file is auto-generated by @hey-api/openapi-ts

import * as z from 'zod'

/**
 * ErrorResponse
 *
 * Documented non-2xx body emitted by ``register_external_error_handlers``.
 *
 * ``params`` and ``details`` appear only on the errors that set them. The schema
 * stays open because ``HTTPException.data`` may carry extra keys.
 */
export const zErrorResponse = z.object({
  code: z.string(),
  details: z.record(z.string(), z.unknown()).optional(),
  message: z.string(),
  params: z.string().optional(),
  status: z.int(),
})

/**
 * AgentNotFoundError
 *
 * Agent not found.
 */
export const zAgentNotFoundError = zErrorResponse.and(
  z.object({
    code: z.literal('agent_not_found_error'),
    status: z.literal(404),
  }),
)

/**
 * AgentNameConflictError
 *
 * Agent name already exists.
 */
export const zAgentNameConflictError = zErrorResponse.and(
  z.object({
    code: z.literal('agent_name_conflict_error'),
    status: z.literal(409),
  }),
)

/**
 * AgentApiAccessResponse
 */
export const zAgentApiAccessResponse = z.object({
  access_ready: z.boolean(),
  api_key_count: z.int(),
  api_rph: z.int(),
  api_rpm: z.int(),
  chat_endpoint: z.string(),
  conversations_endpoint: z.string(),
  enabled: z.boolean(),
  files_upload_endpoint: z.string(),
  info_endpoint: z.string(),
  messages_endpoint: z.string(),
  meta_endpoint: z.string(),
  parameters_endpoint: z.string(),
  service_api_base_url: z.string(),
  stop_endpoint: z.string(),
  streaming_only: z.boolean().optional().default(true),
})

/**
 * AgentApiStatusPayload
 */
export const zAgentApiStatusPayload = z.object({
  enable_api: z.boolean(),
})

/**
 * AgentNotPublishedError
 *
 * Publish the Agent before enabling Web App or API access.
 */
export const zAgentNotPublishedError = zErrorResponse.and(
  z.object({
    code: z.literal('agent_not_published'),
    status: z.literal(409),
  }),
)

/**
 * ApiKeyItem
 */
export const zApiKeyItem = z.object({
  created_at: z.int().nullish(),
  dataset_ids: z.array(z.string()).optional().default([]),
  id: z.string(),
  knowledge_space_ids: z.array(z.string()).optional().default([]),
  last_used_at: z.int().nullish(),
  token: z.string(),
  type: z.string(),
})

/**
 * ApiKeyList
 */
export const zApiKeyList = z.object({
  data: z.array(zApiKeyItem),
})

/**
 * MaxKeysExceededError
 *
 * The API key limit has been reached.
 */
export const zMaxKeysExceededError = zErrorResponse.and(
  z.object({
    code: z.literal('max_keys_exceeded'),
    status: z.literal(400),
  }),
)

/**
 * AudioTranscriptResponse
 */
export const zAudioTranscriptResponse = z.object({
  text: z.string(),
})

/**
 * AppUnavailableError
 *
 * App unavailable, please check your app configurations.
 */
export const zAppUnavailableError = zErrorResponse.and(
  z.object({
    code: z.literal('app_unavailable'),
    status: z.literal(400),
  }),
)

/**
 * CompletionRequestError
 *
 * Completion request failed.
 */
export const zCompletionRequestError = zErrorResponse.and(
  z.object({
    code: z.literal('completion_request_error'),
    status: z.literal(400),
  }),
)

/**
 * ModelCurrentlyNotSupportError
 *
 * Dify Hosted OpenAI trial currently not support the GPT-4 model.
 */
export const zModelCurrentlyNotSupportError = zErrorResponse.and(
  z.object({
    code: z.literal('model_currently_not_support'),
    status: z.literal(400),
  }),
)

/**
 * NoAudioUploadedError
 *
 * Please upload your audio.
 */
export const zNoAudioUploadedError = zErrorResponse.and(
  z.object({
    code: z.literal('no_audio_uploaded'),
    status: z.literal(400),
  }),
)

/**
 * ProviderNotInitializeError
 *
 * No valid model provider credentials found. Please go to Settings -> Model Provider to complete your provider credentials.
 */
export const zProviderNotInitializeError = zErrorResponse.and(
  z.object({
    code: z.literal('provider_not_initialize'),
    status: z.literal(400),
  }),
)

/**
 * ProviderNotSupportSpeechToTextError
 *
 * Provider not support speech to text.
 */
export const zProviderNotSupportSpeechToTextError = zErrorResponse.and(
  z.object({
    code: z.literal('provider_not_support_speech_to_text'),
    status: z.literal(400),
  }),
)

/**
 * ProviderQuotaExceededError
 *
 * Your quota for Dify Hosted Model Provider has been exhausted. Please go to Settings -> Model Provider to complete your own provider credentials.
 */
export const zProviderQuotaExceededError = zErrorResponse.and(
  z.object({
    code: z.literal('provider_quota_exceeded'),
    status: z.literal(400),
  }),
)

/**
 * SpeechToTextDisabledError
 *
 * Speech to text is disabled.
 */
export const zSpeechToTextDisabledError = zErrorResponse.and(
  z.object({
    code: z.literal('speech_to_text_disabled'),
    status: z.literal(400),
  }),
)

/**
 * AgentVersionNotFoundError
 *
 * Agent config version not found.
 */
export const zAgentVersionNotFoundError = zErrorResponse.and(
  z.object({
    code: z.literal('agent_version_not_found_error'),
    status: z.literal(404),
  }),
)

/**
 * AudioTooLargeError
 *
 * Audio size exceeded. {message}
 */
export const zAudioTooLargeError = zErrorResponse.and(
  z.object({
    code: z.literal('audio_too_large'),
    status: z.literal(413),
  }),
)

/**
 * UnsupportedAudioTypeError
 *
 * Audio type not allowed.
 */
export const zUnsupportedAudioTypeError = zErrorResponse.and(
  z.object({
    code: z.literal('unsupported_audio_type'),
    status: z.literal(415),
  }),
)

/**
 * SimpleResultResponse
 */
export const zSimpleResultResponse = z.object({
  result: z.string(),
})

/**
 * RateLimitError
 *
 * Rate Limit Error
 */
export const zRateLimitError = zErrorResponse.and(
  z.object({
    code: z.literal('rate_limit_error'),
    status: z.literal(429),
  }),
)

/**
 * AgentSimpleResultResponse
 */
export const zAgentSimpleResultResponse = z.object({
  result: z.string(),
})

/**
 * AgentBuildSandboxNotFoundError
 *
 * The retained Build Sandbox is no longer available.
 */
export const zAgentBuildSandboxNotFoundError = zErrorResponse.and(
  z.object({
    code: z.literal('agent_build_sandbox_not_found'),
    status: z.literal(404),
  }),
)

/**
 * AgentSoulLockedError
 *
 * Agent Soul is locked for this workflow node.
 */
export const zAgentSoulLockedError = zErrorResponse.and(
  z.object({
    code: z.literal('agent_soul_locked_error'),
    status: z.literal(400),
  }),
)

/**
 * AgentBuildDraftApplyResponse
 */
export const zAgentBuildDraftApplyResponse = z.object({
  draft: z.record(z.string(), z.unknown()),
  result: z.string(),
})

/**
 * InvalidComposerConfigError
 *
 * Invalid agent composer config.
 */
export const zInvalidComposerConfigError = zErrorResponse.and(
  z.object({
    code: z.literal('invalid_composer_config_error'),
    status: z.literal(400),
  }),
)

/**
 * PlaintextSecretNotAllowedError
 *
 * Plaintext secret values are not allowed in Agent config.
 */
export const zPlaintextSecretNotAllowedError = zErrorResponse.and(
  z.object({
    code: z.literal('plaintext_secret_not_allowed_error'),
    status: z.literal(400),
  }),
)

/**
 * AgentHomeSnapshotTooLargeError
 *
 * The Agent Home Snapshot exceeds the configured size limit.
 */
export const zAgentHomeSnapshotTooLargeError = zErrorResponse.and(
  z.object({
    code: z.literal('agent_home_snapshot_too_large'),
    status: z.literal(413),
  }),
)

/**
 * AgentHomeSnapshotCreateFailedError
 *
 * Failed to capture the Agent Home Snapshot.
 */
export const zAgentHomeSnapshotCreateFailedError = zErrorResponse.and(
  z.object({
    code: z.literal('agent_home_snapshot_create_failed'),
    status: z.literal(502),
  }),
)

/**
 * AgentBuildDraftCheckoutPayload
 */
export const zAgentBuildDraftCheckoutPayload = z.object({
  force: z.boolean().optional().default(false),
})

/**
 * SuggestedQuestionsResponse
 */
export const zSuggestedQuestionsResponse = z.object({
  data: z.array(z.string()),
})

/**
 * AppSuggestedQuestionsAfterAnswerDisabledError
 *
 * Function Suggested questions after answer disabled.
 */
export const zAppSuggestedQuestionsAfterAnswerDisabledError = zErrorResponse.and(
  z.object({
    code: z.literal('app_suggested_questions_after_answer_disabled'),
    status: z.literal(403),
  }),
)

/**
 * AgentConfigFileUploadPayload
 */
export const zAgentConfigFileUploadPayload = z.object({
  upload_file_id: z.string(),
})

/**
 * AgentConfigFilesUploadPayload
 */
export const zAgentConfigFilesUploadPayload = z.object({
  upload_file_ids: z.array(z.uuid()).min(1),
})

/**
 * AgentConfigDeleteResponse
 */
export const zAgentConfigDeleteResponse = z.object({
  removed_names: z.array(z.string()).optional(),
  result: z.literal('success'),
})

/**
 * AgentConfigDownloadResponse
 */
export const zAgentConfigDownloadResponse = z.object({
  url: z.string(),
})

/**
 * AgentConfigFilePreviewResponse
 */
export const zAgentConfigFilePreviewResponse = z.object({
  binary: z.boolean(),
  name: z.string(),
  size: z.int().nullish(),
  text: z.string().nullish(),
  truncated: z.boolean(),
})

/**
 * AgentConfigSkillFilePreviewResponse
 */
export const zAgentConfigSkillFilePreviewResponse = z.object({
  binary: z.boolean(),
  path: z.string(),
  size: z.int().nullish(),
  text: z.string().nullish(),
  truncated: z.boolean(),
})

/**
 * AgentDebugConversationRefreshResponse
 */
export const zAgentDebugConversationRefreshResponse = z.object({
  debug_conversation_has_messages: z.boolean().optional().default(false),
  debug_conversation_id: z.string(),
  debug_conversation_message_count: z.int().optional().default(0),
})

/**
 * AppMessageFeedbackPayload
 */
export const zAppMessageFeedbackPayload = z.object({
  content: z.string().nullish(),
  message_id: z.string(),
  rating: z.enum(['dislike', 'like']).nullish(),
})

/**
 * MessageFeedbackRatingRequiredError
 *
 * A rating is required when there is no existing feedback to remove.
 */
export const zMessageFeedbackRatingRequiredError = zErrorResponse.and(
  z.object({
    code: z.literal('message_feedback_rating_required'),
    status: z.literal(400),
  }),
)

/**
 * AgentPublishPayload
 */
export const zAgentPublishPayload = z.object({
  version_note: z.string().nullish(),
})

/**
 * AgentModelNotConfiguredError
 *
 * Agent App requires the Agent Soul model to be configured.
 */
export const zAgentModelNotConfiguredError = zErrorResponse.and(
  z.object({
    code: z.literal('agent_model_not_configured'),
    status: z.literal(400),
  }),
)

/**
 * SandboxInfoResponse
 */
export const zSandboxInfoResponse = z.object({
  workspace_cwd: z.string(),
})

/**
 * NoActiveBindingError
 *
 * No active sandbox binding.
 */
export const zNoActiveBindingError = zErrorResponse.and(
  z.object({
    code: z.literal('no_active_binding'),
    status: z.literal(404),
  }),
)

/**
 * AgentBackendUnreachableError
 *
 * Agent backend is unreachable.
 */
export const zAgentBackendUnreachableError = zErrorResponse.and(
  z.object({
    code: z.literal('agent_backend_unreachable'),
    status: z.literal(502),
  }),
)

/**
 * InspectorUnavailableError
 *
 * Sandbox inspector is unavailable.
 */
export const zInspectorUnavailableError = zErrorResponse.and(
  z.object({
    code: z.literal('inspector_unavailable'),
    status: z.literal(503),
  }),
)

/**
 * AgentSandboxDownloadPayload
 */
export const zAgentSandboxDownloadPayload = z.object({
  caller_id: z.string().min(1),
  caller_type: z.enum(['build_draft', 'conversation']),
  path: z.string().min(1),
})

/**
 * SandboxDownloadResponse
 */
export const zSandboxDownloadResponse = z.object({
  url: z.string(),
})

/**
 * BindingFileDownloadUnavailableError
 *
 * Sandbox file download is unavailable.
 */
export const zBindingFileDownloadUnavailableError = zErrorResponse.and(
  z.object({
    code: z.literal('binding_file_download_unavailable'),
    status: z.literal(502),
  }),
)

/**
 * SandboxReadResponse
 */
export const zSandboxReadResponse = z.object({
  binary: z.boolean(),
  path: z.string(),
  size: z.int().nullish(),
  text: z.string().nullish(),
  truncated: z.boolean(),
})

/**
 * TextToSpeechPayload
 */
export const zTextToSpeechPayload = z.object({
  message_id: z.string().nullish(),
  streaming: z.boolean().nullish(),
  text: z.string(),
  voice: z.string().nullish(),
})

/**
 * ProviderNotSupportTextToSpeechError
 *
 * Provider does not support text to speech.
 */
export const zProviderNotSupportTextToSpeechError = zErrorResponse.and(
  z.object({
    code: z.literal('provider_not_support_text_to_speech'),
    status: z.literal(400),
  }),
)

/**
 * AppTraceResponse
 */
export const zAppTraceResponse = z.object({
  capture_agent: z.boolean().optional().default(true),
  capture_content: z.boolean().optional().default(false),
  enabled: z.boolean().optional().default(false),
  tracing_provider: z.string().nullish(),
})

/**
 * AppTracePayload
 */
export const zAppTracePayload = z.object({
  capture_agent: z.boolean().optional().default(true),
  capture_content: z.boolean().optional().default(false),
  enabled: z.boolean(),
  tracing_provider: z.string().nullish(),
})

/**
 * InvalidTracingConfigError
 *
 * The tracing configuration is invalid.
 */
export const zInvalidTracingConfigError = zErrorResponse.and(
  z.object({
    code: z.literal('invalid_tracing_config'),
    status: z.literal(400),
  }),
)

/**
 * TracingProviderUnavailableError
 *
 * The tracing provider is not available in this deployment.
 */
export const zTracingProviderUnavailableError = zErrorResponse.and(
  z.object({
    code: z.literal('tracing_provider_unavailable'),
    status: z.literal(400),
  }),
)

/**
 * UnsupportedTracingProviderError
 *
 * The tracing provider is not supported.
 */
export const zUnsupportedTracingProviderError = zErrorResponse.and(
  z.object({
    code: z.literal('unsupported_tracing_provider'),
    status: z.literal(400),
  }),
)

/**
 * TraceConfigNotFoundError
 *
 * Tracing configuration not found.
 */
export const zTraceConfigNotFoundError = zErrorResponse.and(
  z.object({
    code: z.literal('trace_config_not_found'),
    status: z.literal(404),
  }),
)

/**
 * TracingConfigConflictError
 *
 * Tracing configuration changed. Refresh and try again.
 */
export const zTracingConfigConflictError = zErrorResponse.and(
  z.object({
    code: z.literal('tracing_config_conflict'),
    status: z.literal(409),
  }),
)

/**
 * TracingConfigProcessingFailedError
 *
 * The tracing configuration could not be processed.
 */
export const zTracingConfigProcessingFailedError = zErrorResponse.and(
  z.object({
    code: z.literal('tracing_config_processing_failed'),
    status: z.literal(500),
  }),
)

/**
 * TraceProviderCapabilitiesResponse
 */
export const zTraceProviderCapabilitiesResponse = z.object({
  agent_spans: z.boolean(),
  api_collection_enabled: z.boolean(),
  export_ack: z.literal('accepted'),
  native_cost: z.boolean(),
  native_usage: z.boolean(),
  provider: z.string(),
  session: z.boolean(),
  span_url: z.boolean(),
  trace_url: z.boolean(),
})

/**
 * AppNotFoundError
 *
 * App not found.
 */
export const zAppNotFoundError = zErrorResponse.and(
  z.object({
    code: z.literal('app_not_found'),
    status: z.literal(404),
  }),
)

/**
 * TraceAppConfigResponse
 */
export const zTraceAppConfigResponse = z.object({
  app_id: z.string().nullish(),
  configured_secrets: z.array(z.string()).nullish(),
  created_at: z.string().nullish(),
  error: z.string().nullish(),
  has_not_configured: z.boolean().nullish(),
  id: z.string().nullish(),
  is_active: z.boolean().nullish(),
  result: z.string().nullish(),
  tracing_config: z.record(z.string(), z.string().nullable()).nullish(),
  tracing_provider: z.string().nullish(),
  updated_at: z.string().nullish(),
})

/**
 * TraceConfigPayload
 */
export const zTraceConfigPayload = z.object({
  activate: z.boolean().optional().default(false),
  tracing_config: z.record(z.string(), z.string().nullable()),
  tracing_provider: z.string(),
})

/**
 * TracingConfigVerificationFailedError
 *
 * The tracing configuration could not be verified.
 */
export const zTracingConfigVerificationFailedError = zErrorResponse.and(
  z.object({
    code: z.literal('tracing_config_verification_failed'),
    status: z.literal(400),
  }),
)

/**
 * TraceConfigAlreadyExistsError
 *
 * A tracing configuration already exists for this provider.
 */
export const zTraceConfigAlreadyExistsError = zErrorResponse.and(
  z.object({
    code: z.literal('trace_config_already_exists'),
    status: z.literal(409),
  }),
)

/**
 * TracingNodeNotFoundError
 *
 * The Agent node invocation does not belong to this trace.
 */
export const zTracingNodeNotFoundError = zErrorResponse.and(
  z.object({
    code: z.literal('tracing_node_not_found'),
    status: z.literal(404),
  }),
)

/**
 * TracingSourceNotFoundError
 *
 * The tracing source does not exist in this application.
 */
export const zTracingSourceNotFoundError = zErrorResponse.and(
  z.object({
    code: z.literal('tracing_source_not_found'),
    status: z.literal(404),
  }),
)

/**
 * TraceRunRetryPayload
 */
export const zTraceRunRetryPayload = z.object({
  acknowledge_possible_duplicates: z.boolean().optional().default(false),
})

/**
 * TracingRunNotFoundError
 *
 * No collected trace is available to retry.
 */
export const zTracingRunNotFoundError = zErrorResponse.and(
  z.object({
    code: z.literal('tracing_run_not_found'),
    status: z.literal(404),
  }),
)

/**
 * TracingAlreadyAcceptedError
 *
 * An accepted trace cannot be exported again.
 */
export const zTracingAlreadyAcceptedError = zErrorResponse.and(
  z.object({
    code: z.literal('tracing_already_accepted'),
    status: z.literal(409),
  }),
)

/**
 * TracingDuplicateAcknowledgementRequiredError
 *
 * Acknowledge possible duplicates before retrying an uncertain export.
 */
export const zTracingDuplicateAcknowledgementRequiredError = zErrorResponse.and(
  z.object({
    code: z.literal('tracing_duplicate_acknowledgement_required'),
    status: z.literal(409),
  }),
)

/**
 * TracingRetryNotAllowedError
 *
 * This trace is not in a retryable state.
 */
export const zTracingRetryNotAllowedError = zErrorResponse.and(
  z.object({
    code: z.literal('tracing_retry_not_allowed'),
    status: z.literal(409),
  }),
)

/**
 * AgentConfigSnapshotRestoreResponse
 */
export const zAgentConfigSnapshotRestoreResponse = z.object({
  active_config_snapshot_id: z.string(),
  draft_config_id: z.string().nullish(),
  restored_version_id: z.string().nullish(),
  result: z.literal('success'),
})

/**
 * AgentPublicationCountsResponse
 */
export const zAgentPublicationCountsResponse = z.object({
  drafts: z.int().gte(0),
  published: z.int().gte(0),
})

/**
 * IconType
 */
export const zIconType = z.enum(['emoji', 'image', 'link'])

/**
 * AgentAppCreatePayload
 */
export const zAgentAppCreatePayload = z.object({
  description: z.string().max(400).nullish(),
  icon: z.string().nullish(),
  icon_background: z.string().nullish(),
  icon_type: zIconType.nullish(),
  name: z.string().min(1),
  role: z.string().max(255).nullish(),
})

/**
 * AgentAppUpdatePayload
 */
export const zAgentAppUpdatePayload = z.object({
  description: z.string().max(400).nullish(),
  icon: z.string().nullish(),
  icon_background: z.string().nullish(),
  icon_type: zIconType.nullish(),
  max_active_requests: z.int().nullish(),
  name: z.string().min(1),
  role: z.string().max(255).nullish(),
  use_icon_as_answer_icon: z.boolean().nullish(),
})

/**
 * AgentAppCopyPayload
 */
export const zAgentAppCopyPayload = z.object({
  description: z.string().max(400).nullish(),
  icon: z.string().nullish(),
  icon_background: z.string().nullish(),
  icon_type: zIconType.nullish(),
  name: z.string().nullish(),
  role: z.string().max(255).nullish(),
})

/**
 * WebAppAccessMode
 */
export const zWebAppAccessMode = z.enum(['private', 'private_all', 'public', 'sso_verified'])

/**
 * DeletedTool
 */
export const zDeletedTool = z.object({
  provider_id: z.string(),
  tool_name: z.string(),
  type: z.string(),
})

/**
 * AppMode
 */
export const zAppMode = z.enum([
  'advanced-chat',
  'agent',
  'agent-chat',
  'channel',
  'chat',
  'completion',
  'rag-pipeline',
  'workflow',
])

/**
 * Tag
 */
export const zTag = z.object({
  id: z.string(),
  name: z.string(),
  type: z.string(),
})

/**
 * WorkflowPartial
 */
export const zWorkflowPartial = z.object({
  created_at: z.int().nullish(),
  created_by: z.string().nullish(),
  id: z.string(),
  updated_at: z.int().nullish(),
  updated_by: z.string().nullish(),
})

/**
 * ComposerBindingPayload
 */
export const zComposerBindingPayload = z.object({
  agent_id: z.string().nullish(),
  binding_type: z.enum(['inline_agent', 'roster_agent']),
  current_snapshot_id: z.string().nullish(),
})

/**
 * AgentIconType
 *
 * Supported icon storage formats for Agent roster entries.
 */
export const zAgentIconType = z.enum(['emoji', 'image', 'link'])

/**
 * ComposerSaveStrategy
 */
export const zComposerSaveStrategy = z.enum([
  'node_job_only',
  'save_as_new_agent',
  'save_as_new_version',
  'save_to_current_version',
  'save_to_roster',
])

/**
 * ComposerSoulLockPayload
 */
export const zComposerSoulLockPayload = z.object({
  locked: z.boolean().optional().default(true),
  unlocked_from_version_id: z.string().nullish(),
})

/**
 * ComposerVariant
 */
export const zComposerVariant = z.enum(['agent_app', 'workflow'])

/**
 * AgentConfigSnapshotSummaryResponse
 */
export const zAgentConfigSnapshotSummaryResponse = z.object({
  agent_id: z.string().nullish(),
  created_at: z.int().nullish(),
  created_by: z.string().nullish(),
  display_version: z.int().nullish(),
  id: z.string(),
  snapshot_version: z.int().nullish(),
  summary: z.string().nullish(),
  version: z.int(),
  version_note: z.string().nullish(),
})

/**
 * AgentConfigSnapshotListResponse
 */
export const zAgentConfigSnapshotListResponse = z.object({
  data: z.array(zAgentConfigSnapshotSummaryResponse),
})

/**
 * ComposerCandidateCapabilities
 */
export const zComposerCandidateCapabilities = z.object({
  human_roster_available: z.boolean().optional().default(false),
})

/**
 * ComposerKnowledgePlaceholderResponse
 */
export const zComposerKnowledgePlaceholderResponse = z.object({
  id: z.string(),
  placeholder_name: z.string(),
})

/**
 * ComposerValidationWarningResponse
 */
export const zComposerValidationWarningResponse = z.object({
  code: z.string(),
  id: z.string().nullish(),
  kind: z.string().nullish(),
  message: z.string().nullish(),
  surface: z.string().nullish(),
})

/**
 * AgentComposerValidateResponse
 */
export const zAgentComposerValidateResponse = z.object({
  errors: z.array(z.string()).optional(),
  knowledge_retrieval_placeholder: z.array(zComposerKnowledgePlaceholderResponse).optional(),
  result: z.literal('success'),
  warnings: z.array(zComposerValidationWarningResponse).optional(),
})

/**
 * ComposerValidationFindingsResponse
 */
export const zComposerValidationFindingsResponse = z.object({
  knowledge_retrieval_placeholder: z.array(zComposerKnowledgePlaceholderResponse).optional(),
  warnings: z.array(zComposerValidationWarningResponse).optional(),
})

/**
 * AgentConfigVersionResponse
 */
export const zAgentConfigVersionResponse = z.object({
  id: z.string(),
  kind: z.enum(['build_draft', 'draft', 'snapshot']),
  writable: z.boolean(),
})

/**
 * AgentConfigFileItemResponse
 */
export const zAgentConfigFileItemResponse = z.object({
  file_id: z.string().nullish(),
  hash: z.string().nullish(),
  id: z.string(),
  is_missing: z.boolean().optional().default(false),
  mime_type: z.string().nullish(),
  name: z.string(),
  size: z.int().nullish(),
})

/**
 * AgentConfigFileListResponse
 */
export const zAgentConfigFileListResponse = z.object({
  agent_id: z.string(),
  config_version: zAgentConfigVersionResponse,
  items: z.array(zAgentConfigFileItemResponse).optional(),
})

/**
 * AgentConfigFileUploadResponse
 */
export const zAgentConfigFileUploadResponse = z.object({
  config_version: zAgentConfigVersionResponse,
  file: zAgentConfigFileItemResponse,
})

/**
 * AgentConfigFilesUploadResponse
 */
export const zAgentConfigFilesUploadResponse = z.object({
  config_version: zAgentConfigVersionResponse,
  files: z.array(zAgentConfigFileItemResponse),
})

/**
 * AgentConfigFileItemsResponse
 */
export const zAgentConfigFileItemsResponse = z.object({
  items: z.array(zAgentConfigFileItemResponse).optional(),
})

/**
 * AgentConfigSkillItemResponse
 */
export const zAgentConfigSkillItemResponse = z.object({
  description: z.string().optional().default(''),
  file_id: z.string().nullish(),
  hash: z.string().nullish(),
  id: z.string(),
  is_missing: z.boolean().optional().default(false),
  mime_type: z.string().nullish(),
  name: z.string(),
  size: z.int().nullish(),
})

/**
 * AgentConfigSkillListResponse
 */
export const zAgentConfigSkillListResponse = z.object({
  agent_id: z.string(),
  config_version: zAgentConfigVersionResponse,
  items: z.array(zAgentConfigSkillItemResponse).optional(),
})

/**
 * AgentConfigSkillUploadResponse
 */
export const zAgentConfigSkillUploadResponse = z.object({
  config_version: zAgentConfigVersionResponse,
  skill: zAgentConfigSkillItemResponse,
})

/**
 * AgentConfigSkillItemsResponse
 */
export const zAgentConfigSkillItemsResponse = z.object({
  items: z.array(zAgentConfigSkillItemResponse).optional(),
})

/**
 * AgentConfigManifestResponse
 */
export const zAgentConfigManifestResponse = z.object({
  agent_id: z.string(),
  config_version: zAgentConfigVersionResponse,
  env_keys: z.array(z.string()).optional(),
  files: zAgentConfigFileItemsResponse.optional(),
  note: z.string().optional().default(''),
  skills: zAgentConfigSkillItemsResponse.optional(),
})

/**
 * AgentConfigSkillFileResponse
 */
export const zAgentConfigSkillFileResponse = z.object({
  downloadable: z.boolean(),
  name: z.string(),
  path: z.string(),
  previewable: z.boolean(),
  type: z.enum(['directory', 'file']),
})

/**
 * AgentConfigSkillMarkdownResponse
 */
export const zAgentConfigSkillMarkdownResponse = z.object({
  binary: z.literal(false),
  path: z.literal('SKILL.md'),
  size: z.int().nullish(),
  text: z.string(),
  truncated: z.boolean(),
})

/**
 * AgentConfigSkillInspectResponse
 */
export const zAgentConfigSkillInspectResponse = z.object({
  description: z.string().optional().default(''),
  file_tree: z.array(z.record(z.string(), z.unknown())).nullish(),
  files: z.array(zAgentConfigSkillFileResponse).optional(),
  hash: z.string().nullish(),
  id: z.string(),
  mime_type: z.string().nullish(),
  name: z.string(),
  size: z.int().nullish(),
  skill_md: zAgentConfigSkillMarkdownResponse,
  source: z.literal('config_skill_zip'),
  warnings: z.array(z.string()).optional(),
})

/**
 * AgentFeatureToggleConfig
 */
export const zAgentFeatureToggleConfig = z.object({
  enabled: z.boolean().optional().default(false),
})

/**
 * AgentTextToSpeechFeatureConfig
 */
export const zAgentTextToSpeechFeatureConfig = z.object({
  autoPlay: z.enum(['disabled', 'enabled']).nullish(),
  enabled: z.boolean().optional().default(false),
  language: z.string().nullish(),
  voice: z.string().nullish(),
})

/**
 * AgentLogSourceResponse
 */
export const zAgentLogSourceResponse = z.object({
  app_icon: z.string().nullish(),
  app_icon_background: z.string().nullish(),
  app_icon_type: z.string().nullish(),
  app_id: z.string(),
  app_name: z.string(),
  id: z.string(),
  node_id: z.string().nullish(),
  type: z.enum(['webapp', 'workflow']),
  workflow_id: z.string().nullish(),
  workflow_version: z.string().nullish(),
})

/**
 * AgentLogSourceGroupResponse
 */
export const zAgentLogSourceGroupResponse = z.object({
  label: z.string(),
  sources: z.array(zAgentLogSourceResponse).optional(),
  type: z.enum(['webapp', 'workflow']),
})

/**
 * AgentLogSourceListResponse
 */
export const zAgentLogSourceListResponse = z.object({
  data: z.array(zAgentLogSourceResponse),
  groups: z.array(zAgentLogSourceGroupResponse),
})

/**
 * AgentLogConversationItemResponse
 */
export const zAgentLogConversationItemResponse = z.object({
  conversation_id: z.string(),
  created_at: z.int().nullish(),
  end_user_id: z.string().nullish(),
  id: z.string(),
  message_count: z.int(),
  operation_rate: z.number().nullish(),
  source: zAgentLogSourceResponse.nullish(),
  status: z.enum(['failed', 'paused', 'success']),
  title: z.string().nullish(),
  unread: z.boolean(),
  updated_at: z.int().nullish(),
  user_rate: z.number().nullish(),
})

/**
 * AgentLogListResponse
 */
export const zAgentLogListResponse = z.object({
  data: z.array(zAgentLogConversationItemResponse),
  has_more: z.boolean(),
  limit: z.int(),
  page: z.int(),
  total: z.int(),
})

export const zAnyJsonValue = z.unknown()

/**
 * AgentThought
 */
export const zAgentThought = z.object({
  answer: z.string().nullish(),
  chain_id: z.string().nullish(),
  created_at: z.int().nullish(),
  files: z.array(z.string()),
  id: z.string(),
  message_id: z.string(),
  observation: z.string().nullish(),
  position: z.int(),
  thought: z.string().nullish(),
  tool: z.string().nullish(),
  tool_input: z.string().nullish(),
  tool_labels: zAnyJsonValue,
})

/**
 * MessageFile
 */
export const zMessageFile = z.object({
  belongs_to: z.string().nullish(),
  filename: z.string(),
  id: z.uuid(),
  mime_type: z.string().nullish(),
  size: z.int().nullish(),
  transfer_method: z.string(),
  type: z.string(),
  upload_file_id: z.uuid().nullish(),
  url: z.string().nullish(),
})

/**
 * AgentReferencingWorkflowResponse
 */
export const zAgentReferencingWorkflowResponse = z.object({
  app_icon: z.string().nullish(),
  app_icon_background: z.string().nullish(),
  app_icon_type: z.string().nullish(),
  app_id: z.string(),
  app_mode: z.string(),
  app_name: z.string(),
  app_updated_at: z.int().nullish(),
  node_ids: z.array(z.string()).optional(),
  workflow_id: z.string(),
  workflow_version: z.string(),
})

/**
 * AgentReferencingWorkflowsResponse
 */
export const zAgentReferencingWorkflowsResponse = z.object({
  data: z.array(zAgentReferencingWorkflowResponse).optional(),
})

/**
 * SandboxFileEntryResponse
 */
export const zSandboxFileEntryResponse = z.object({
  mtime: z.int().nullish(),
  name: z.string(),
  size: z.int().nullish(),
  type: z.enum(['dir', 'file', 'other', 'symlink']),
})

/**
 * SandboxListResponse
 */
export const zSandboxListResponse = z.object({
  entries: z.array(zSandboxFileEntryResponse).optional(),
  path: z.string(),
  truncated: z.boolean().optional().default(false),
})

/**
 * AgentStatisticSummaryResponse
 */
export const zAgentStatisticSummaryResponse = z.object({
  average_response_time: z.number(),
  average_session_interactions: z.number(),
  currency: z.string(),
  tokens_per_second: z.number(),
  total_conversations: z.int(),
  total_end_users: z.int(),
  total_messages: z.int(),
  total_price: z.string(),
  total_tokens: z.int(),
  user_satisfaction_rate: z.number(),
})

/**
 * TextToSpeechVoiceResponse
 */
export const zTextToSpeechVoiceResponse = z.object({
  name: z.string(),
  value: z.string(),
})

/**
 * TextToSpeechVoiceListResponse
 *
 * Available voices
 */
export const zTextToSpeechVoiceListResponse = z.array(zTextToSpeechVoiceResponse)

/**
 * TraceProviderSupportResponse
 *
 * Adapter support declarations, not successful-delivery or platform-verification results.
 */
export const zTraceProviderSupportResponse = z.object({
  agent_spans: z.boolean(),
  export_ack: z.literal('accepted'),
  native_cost: z.boolean(),
  native_usage: z.boolean(),
  provider: z.string(),
  session: z.boolean(),
  span_url: z.boolean(),
  trace_url: z.boolean(),
})

export const zTraceSourceKind = z.enum(['message', 'node', 'workflow'])

/**
 * TraceRunStatusResponse
 */
export const zTraceRunStatusResponse = z.object({
  accepted_at: z.iso.datetime().nullish(),
  attempts: z.int().nullish(),
  capabilities: zTraceProviderSupportResponse.nullish(),
  capture_agent: z.boolean().nullish(),
  capture_content: z.boolean().nullish(),
  config_revision: z.string().nullish(),
  error_code: z.string().nullish(),
  project_url: z.string().nullish(),
  provider: z.string().nullish(),
  queryable: z.boolean().nullish(),
  source_id: z.string(),
  source_kind: zTraceSourceKind,
  span_count: z.int().nullish(),
  span_url: z.string().nullish(),
  status: z.enum([
    'accepted',
    'collecting',
    'exporting',
    'failed',
    'not_collected',
    'ready',
    'retrying',
    'uncertain',
  ]),
  trace_id: z.string().nullish(),
  trace_url: z.string().nullish(),
})

/**
 * AgentAppPublishedReferenceResponse
 */
export const zAgentAppPublishedReferenceResponse = z.object({
  app_icon: z.string().nullish(),
  app_icon_background: z.string().nullish(),
  app_icon_type: z.string().nullish(),
  app_id: z.string(),
  app_name: z.string(),
})

/**
 * AppAnnotationReplyDisabledResponse
 */
export const zAppAnnotationReplyDisabledResponse = z.object({
  enabled: z.literal(false),
})

/**
 * AppEnabledConfigResponse
 */
export const zAppEnabledConfigResponse = z.object({
  enabled: z.boolean(),
})

/**
 * PromptType
 *
 * Prompt configuration type
 */
export const zPromptType = z.enum(['advanced', 'simple'])

/**
 * AppTextToSpeechResponse
 */
export const zAppTextToSpeechResponse = z.object({
  autoPlay: z.enum(['disabled', 'enabled']).optional(),
  enabled: z.boolean(),
  language: z.string().optional(),
  voice: z.string().optional(),
})

/**
 * CustomizeTokenStrategy
 *
 * Site token customization strategy
 */
export const zCustomizeTokenStrategy = z.enum(['allow', 'must', 'not_allow', 'uuid'])

/**
 * AppDetailSiteResponse
 */
export const zAppDetailSiteResponse = z.object({
  access_token: z.string().nullable(),
  app_base_url: z.string(),
  chat_color_theme: z.string().nullable(),
  chat_color_theme_inverted: z.boolean(),
  code: z.string().nullable(),
  copyright: z.string().nullable(),
  created_at: z.int(),
  created_by: z.string().nullable(),
  custom_disclaimer: z.string(),
  customize_domain: z.string().nullable(),
  customize_token_strategy: zCustomizeTokenStrategy,
  default_language: z.string(),
  description: z.string().nullable(),
  icon: z.string().nullable(),
  icon_background: z.string().nullable(),
  icon_type: zIconType.nullable(),
  icon_url: z.string().nullable(),
  input_placeholder: z.string().nullable(),
  privacy_policy: z.string().nullable(),
  prompt_public: z.boolean(),
  show_workflow_steps: z.boolean(),
  title: z.string(),
  updated_at: z.int(),
  updated_by: z.string().nullable(),
  use_icon_as_answer_icon: z.boolean(),
})

/**
 * AgentKind
 *
 * Agent implementation family.
 *
 * This leaves room for future non-Dify agent implementations while keeping
 * the current roster/workflow APIs scoped to Dify Agent.
 */
export const zAgentKind = z.enum(['dify_agent'])

/**
 * AgentPublishedReferenceResponse
 */
export const zAgentPublishedReferenceResponse = z.object({
  app_icon: z.string().nullish(),
  app_icon_background: z.string().nullish(),
  app_icon_type: z.string().nullish(),
  app_id: z.string(),
  app_mode: z.string(),
  app_name: z.string(),
  app_updated_at: z.int().nullish(),
  node_ids: z.array(z.string()).optional(),
  workflow_id: z.string(),
  workflow_version: z.string(),
})

/**
 * AgentScope
 *
 * Visibility and lifecycle scope of an Agent record.
 */
export const zAgentScope = z.enum(['roster', 'workflow_only'])

/**
 * AgentSource
 *
 * Origin that created or imported the Agent.
 */
export const zAgentSource = z.enum(['agent_app', 'imported', 'roster', 'system', 'workflow'])

/**
 * AgentStatus
 *
 * Soft lifecycle state for Agent records.
 */
export const zAgentStatus = z.enum(['active', 'archived'])

/**
 * AgentInviteOptionResponse
 */
export const zAgentInviteOptionResponse = z.object({
  active_config_is_published: z.boolean().optional().default(false),
  active_config_snapshot: zAgentConfigSnapshotSummaryResponse.nullish(),
  active_config_snapshot_id: z.string().nullish(),
  agent_kind: zAgentKind,
  app_id: z.string().nullish(),
  archived_at: z.int().nullish(),
  archived_by: z.string().nullish(),
  backing_app_id: z.string().nullish(),
  created_at: z.int().nullish(),
  created_by: z.string().nullish(),
  description: z.string(),
  existing_node_ids: z.array(z.string()).optional(),
  hidden_app_backed: z.boolean().optional().default(false),
  icon: z.string().nullish(),
  icon_background: z.string().nullish(),
  icon_type: zAgentIconType.nullish(),
  id: z.string(),
  in_current_workflow_count: z.int().optional().default(0),
  is_in_current_workflow: z.boolean().optional().default(false),
  name: z.string(),
  published_node_reference_count: z.int().optional().default(0),
  published_reference_count: z.int().optional().default(0),
  published_references: z.array(zAgentPublishedReferenceResponse).optional(),
  reference_count: z.int().nullish(),
  role: z.string().optional().default(''),
  scope: zAgentScope,
  source: zAgentSource,
  status: zAgentStatus,
  updated_at: z.int().nullish(),
  updated_by: z.string().nullish(),
  workflow_id: z.string().nullish(),
  workflow_node_id: z.string().nullish(),
})

/**
 * AgentInviteOptionsResponse
 */
export const zAgentInviteOptionsResponse = z.object({
  data: z.array(zAgentInviteOptionResponse),
  has_more: z.boolean(),
  limit: z.int(),
  page: z.int(),
  total: z.int(),
})

/**
 * AgentComposerAgentResponse
 */
export const zAgentComposerAgentResponse = z.object({
  active_config_snapshot_id: z.string().nullish(),
  app_id: z.string().nullish(),
  backing_app_id: z.string().nullish(),
  description: z.string(),
  hidden_app_backed: z.boolean().optional().default(false),
  icon: z.string().nullish(),
  icon_background: z.string().nullish(),
  icon_type: z.string().nullish(),
  id: z.string(),
  name: z.string(),
  role: z.string().nullish(),
  scope: zAgentScope,
  source: zAgentSource.nullish(),
  status: zAgentStatus,
})

/**
 * AppVariableConfig
 */
export const zAppVariableConfig = z.object({
  default: z.unknown().optional(),
  name: z.string().min(1).max(255),
  required: z.boolean().optional().default(false),
  type: z.string().min(1).max(64),
})

/**
 * AgentConfigFileRefConfig
 *
 * Stable Agent Soul reference to one config file payload.
 */
export const zAgentConfigFileRefConfig = z.object({
  file_id: z.string().max(255).optional().default(''),
  file_kind: z.enum(['tool_file', 'upload_file']),
  hash: z.string().nullish(),
  is_missing: z.boolean().optional().default(false),
  mime_type: z.string().nullish(),
  name: z.string().min(1).max(255),
  size: z.int().nullish(),
})

/**
 * AgentConfigSkillRefConfig
 *
 * Stable Agent Soul reference to one normalized skill archive.
 */
export const zAgentConfigSkillRefConfig = z.object({
  description: z.string().optional().default(''),
  file_id: z.string().max(255).optional().default(''),
  file_kind: z.literal('tool_file').optional().default('tool_file'),
  hash: z.string().nullish(),
  is_missing: z.boolean().optional().default(false),
  mime_type: z.string().nullish().default('application/zip'),
  name: z.string().min(1).max(255),
  size: z.int().nullish(),
})

/**
 * AgentSoulPromptConfig
 */
export const zAgentSoulPromptConfig = z.object({
  system_prompt: z.string().optional().default(''),
})

/**
 * AgentConfigDraftType
 *
 * Editable Agent Soul draft workspace type.
 */
export const zAgentConfigDraftType = z.enum(['debug_build', 'draft'])

/**
 * AgentConfigDraftSummaryResponse
 */
export const zAgentConfigDraftSummaryResponse = z.object({
  account_id: z.string().nullish(),
  agent_id: z.string(),
  base_snapshot_id: z.string().nullish(),
  created_at: z.int().nullish(),
  created_by: z.string().nullish(),
  draft_type: zAgentConfigDraftType,
  id: z.string(),
  updated_at: z.int().nullish(),
  updated_by: z.string().nullish(),
})

/**
 * AgentPublishResponse
 */
export const zAgentPublishResponse = z.object({
  active_config_snapshot: zAgentConfigSnapshotSummaryResponse.nullish(),
  active_config_snapshot_id: z.string(),
  draft: zAgentConfigDraftSummaryResponse.nullish(),
  publication_kind: z.enum(['first', 'update']),
  result: z.string(),
})

/**
 * AgentHumanContactConfig
 */
export const zAgentHumanContactConfig = z.object({
  channel: z.string().max(64).nullish(),
  contact_id: z.string().max(255).nullish(),
  contact_method: z.string().max(64).nullish(),
  email: z.string().max(255).nullish(),
  human_id: z.string().max(255).nullish(),
  id: z.string().max(255).nullish(),
  method: z.string().max(64).nullish(),
  name: z.string().max(255).nullish(),
  tenant_id: z.string().max(255).nullish(),
})

/**
 * WorkflowNodeJobMode
 */
export const zWorkflowNodeJobMode = z.enum(['let_agent_figure_it_out', 'tell_agent_what_to_do'])

/**
 * WorkflowPreviousNodeOutputRef
 */
export const zWorkflowPreviousNodeOutputRef = z.object({
  key: z.string().max(255).nullish(),
  name: z.string().max(255).nullish(),
  node_id: z.string().max(255).nullish(),
  output: z.string().max(255).nullish(),
  selector: z.array(z.union([z.string(), z.int(), z.number(), z.boolean(), z.null()])).nullish(),
  value_selector: z
    .array(z.union([z.string(), z.int(), z.number(), z.boolean(), z.null()]))
    .nullish(),
  variable: z.string().max(255).nullish(),
  variable_selector: z
    .array(z.union([z.string(), z.int(), z.number(), z.boolean(), z.null()]))
    .nullish(),
})

/**
 * DeclaredOutputType
 */
export const zDeclaredOutputType = z.enum([
  'array',
  'boolean',
  'file',
  'number',
  'object',
  'string',
])

/**
 * AgentComposerNodeJobCandidatesResponse
 */
export const zAgentComposerNodeJobCandidatesResponse = z.object({
  declare_output_types: z.array(zDeclaredOutputType).optional(),
  human_contacts: z.array(zAgentHumanContactConfig).optional(),
  previous_node_outputs: z.array(zWorkflowPreviousNodeOutputRef).optional(),
})

/**
 * AgentComposerDifyToolCandidateResponse
 */
export const zAgentComposerDifyToolCandidateResponse = z.object({
  description: z.string().nullish(),
  granularity: z.string().nullish(),
  id: z.string().nullish(),
  name: z.string().nullish(),
  plugin_id: z.string().nullish(),
  provider: z.string().nullish(),
  provider_id: z.string().nullish(),
  tools_count: z.int().nullish(),
})

/**
 * AgentSuggestedQuestionsAfterAnswerModelConfig
 *
 * Legacy Chat App model config used only for follow-up question generation.
 */
export const zAgentSuggestedQuestionsAfterAnswerModelConfig = z.object({
  completion_params: z.record(z.string(), z.unknown()).nullish(),
  mode: z.string().max(64).nullish(),
  name: z.string().min(1).max(255),
  provider: z.string().min(1).max(255),
})

/**
 * AgentSuggestedQuestionsAfterAnswerFeatureConfig
 */
export const zAgentSuggestedQuestionsAfterAnswerFeatureConfig = z.object({
  enabled: z.boolean().optional().default(false),
  model: zAgentSuggestedQuestionsAfterAnswerModelConfig.nullish(),
  prompt: z.string().nullish(),
})

/**
 * AgentLogFeedbackResponse
 */
export const zAgentLogFeedbackResponse = z.object({
  content: z.string().nullish(),
  from_source: z.enum(['admin', 'user']),
  rating: z.enum(['dislike', 'like']),
})

/**
 * AgentLogMessageItemResponse
 */
export const zAgentLogMessageItemResponse = z.object({
  answer: z.string(),
  answer_tokens: z.int(),
  conversation_id: z.string(),
  created_at: z.int().nullish(),
  currency: z.string(),
  error: z.string().nullish(),
  feedback_enabled: z.boolean().optional().default(false),
  feedbacks: z.array(zAgentLogFeedbackResponse).optional(),
  from_account_id: z.string().nullish(),
  from_end_user_id: z.string().nullish(),
  id: z.string(),
  latency: z.number(),
  message_id: z.string(),
  message_tokens: z.int(),
  query: z.string(),
  status: z.string(),
  total_price: z.string(),
  total_tokens: z.int(),
  updated_at: z.int().nullish(),
})

/**
 * AgentLogMessageListResponse
 */
export const zAgentLogMessageListResponse = z.object({
  data: z.array(zAgentLogMessageItemResponse),
  has_more: z.boolean(),
  limit: z.int(),
  page: z.int(),
  total: z.int(),
})

/**
 * SimpleAccount
 */
export const zSimpleAccount = z.object({
  email: z.string(),
  id: z.string(),
  name: z.string(),
})

/**
 * ConversationAnnotation
 */
export const zConversationAnnotation = z.object({
  account: zSimpleAccount.nullish(),
  content: z.string(),
  created_at: z.int().nullish(),
  id: z.string(),
  question: z.string().nullish(),
})

/**
 * ConversationAnnotationHitHistory
 */
export const zConversationAnnotationHitHistory = z.object({
  annotation_create_account: zSimpleAccount.nullish(),
  annotation_id: z.string(),
  created_at: z.int().nullish(),
})

/**
 * Feedback
 */
export const zFeedback = z.object({
  content: z.string().nullish(),
  from_account: zSimpleAccount.nullish(),
  from_end_user_id: z.string().nullish(),
  from_source: z.string(),
  rating: z.string(),
})

/**
 * ExecutionContentType
 */
export const zExecutionContentType = z.enum(['human_input'])

/**
 * KnowledgeFsCitation
 *
 * Immutable evidence identity; no signed URLs, tokens or storage keys.
 */
export const zKnowledgeFsCitation = z.object({
  artifact_hash: z.string().min(1).max(255),
  control_space_id: z.string().length(36),
  document_asset_id: z.string().min(1).max(512),
  document_title: z.string().max(2000).nullish(),
  document_version: z.int().gte(1).nullish(),
  end_offset: z.int().gte(0).nullish(),
  id: z.string().regex(/^kfs_[a-f0-9]{32}$/),
  node_id: z.string().min(1).max(512),
  page_number: z.int().gte(0).nullish(),
  parse_artifact_id: z.string().max(512).nullish(),
  section_path: z.array(z.string()).max(64).optional(),
  space_name: z.string().min(1).max(120),
  start_offset: z.int().gte(0).nullish(),
})

/**
 * RetrievalSourceMetadata
 */
export const zRetrievalSourceMetadata = z.object({
  content: z.string().nullish(),
  data_source_type: z.string().nullish(),
  dataset_id: z.string().nullish(),
  dataset_name: z.string().nullish(),
  doc_metadata: z.record(z.string(), z.unknown()).nullish(),
  document_asset_id: z.string().nullish(),
  document_id: z.string().nullish(),
  document_name: z.string().nullish(),
  document_revision: z.int().nullish(),
  document_version: z.int().nullish(),
  files: z.array(z.record(z.string(), z.unknown())).nullish(),
  hit_count: z.int().nullish(),
  index_node_hash: z.string().nullish(),
  knowledge_fs_citation: zKnowledgeFsCitation.nullish(),
  page: z.int().nullish(),
  position: z.int().nullish(),
  retriever_from: z.string().nullish(),
  score: z.number().nullish(),
  segment_id: z.string().nullish(),
  segment_position: z.int().nullish(),
  summary: z.string().nullish(),
  title: z.string().nullish(),
  word_count: z.int().nullish(),
})

/**
 * AgentAverageResponseTimeStatisticResponse
 */
export const zAgentAverageResponseTimeStatisticResponse = z.object({
  date: z.string(),
  latency: z.number(),
})

/**
 * AgentAverageSessionInteractionStatisticResponse
 */
export const zAgentAverageSessionInteractionStatisticResponse = z.object({
  date: z.string(),
  interactions: z.number(),
})

/**
 * AgentDailyConversationStatisticResponse
 */
export const zAgentDailyConversationStatisticResponse = z.object({
  conversation_count: z.int(),
  date: z.string(),
})

/**
 * AgentDailyEndUserStatisticResponse
 */
export const zAgentDailyEndUserStatisticResponse = z.object({
  date: z.string(),
  terminal_count: z.int(),
})

/**
 * AgentDailyMessageStatisticResponse
 */
export const zAgentDailyMessageStatisticResponse = z.object({
  date: z.string(),
  message_count: z.int(),
})

/**
 * AgentTokenUsageStatisticResponse
 */
export const zAgentTokenUsageStatisticResponse = z.object({
  currency: z.string(),
  date: z.string(),
  token_count: z.int(),
  total_price: z.string(),
})

/**
 * AgentTokensPerSecondStatisticResponse
 */
export const zAgentTokensPerSecondStatisticResponse = z.object({
  date: z.string(),
  tps: z.number(),
})

/**
 * AgentUserSatisfactionRateStatisticResponse
 */
export const zAgentUserSatisfactionRateStatisticResponse = z.object({
  date: z.string(),
  rate: z.number(),
})

/**
 * AgentStatisticChartsResponse
 */
export const zAgentStatisticChartsResponse = z.object({
  average_response_time: z.array(zAgentAverageResponseTimeStatisticResponse).optional(),
  average_session_interactions: z
    .array(zAgentAverageSessionInteractionStatisticResponse)
    .optional(),
  daily_conversations: z.array(zAgentDailyConversationStatisticResponse).optional(),
  daily_end_users: z.array(zAgentDailyEndUserStatisticResponse).optional(),
  daily_messages: z.array(zAgentDailyMessageStatisticResponse).optional(),
  token_usage: z.array(zAgentTokenUsageStatisticResponse).optional(),
  tokens_per_second: z.array(zAgentTokensPerSecondStatisticResponse).optional(),
  user_satisfaction_rate: z.array(zAgentUserSatisfactionRateStatisticResponse).optional(),
})

/**
 * AgentStatisticSummaryEnvelopeResponse
 */
export const zAgentStatisticSummaryEnvelopeResponse = z.object({
  charts: zAgentStatisticChartsResponse,
  source: z.string(),
  summary: zAgentStatisticSummaryResponse,
})

/**
 * AgentConfigRevisionOperation
 *
 * Audit operation recorded for Agent Soul version/revision changes.
 */
export const zAgentConfigRevisionOperation = z.enum([
  'create_version',
  'import_package',
  'publish_draft',
  'restore_version',
  'save_current_version',
  'save_new_agent',
  'save_new_version',
  'save_to_roster',
])

/**
 * AgentConfigRevisionResponse
 */
export const zAgentConfigRevisionResponse = z.object({
  created_at: z.int().nullish(),
  created_by: z.string().nullish(),
  current_snapshot_id: z.string(),
  id: z.string(),
  operation: zAgentConfigRevisionOperation,
  previous_snapshot_id: z.string().nullish(),
  revision: z.int(),
  summary: z.string().nullish(),
  version_note: z.string().nullish(),
})

/**
 * AppAgentPromptResponse
 */
export const zAppAgentPromptResponse = z.object({
  first_prompt: z.string().optional(),
  next_iteration: z.string().optional(),
})

/**
 * PlanningStrategy
 */
export const zPlanningStrategy = z.enum(['function_call', 'react', 'react_router', 'router'])

/**
 * AppEmbeddingModelResponse
 */
export const zAppEmbeddingModelResponse = z.object({
  embedding_model_name: z.string(),
  embedding_provider_name: z.string(),
})

/**
 * AppAnnotationReplyEnabledResponse
 */
export const zAppAnnotationReplyEnabledResponse = z.object({
  embedding_model: zAppEmbeddingModelResponse,
  enabled: z.literal(true),
  id: z.string(),
  score_threshold: z.number(),
})

/**
 * AppChatPromptMessageResponse
 */
export const zAppChatPromptMessageResponse = z.object({
  role: z.string(),
  text: z.string(),
})

/**
 * AppChatPromptConfigResponse
 */
export const zAppChatPromptConfigResponse = z.object({
  prompt: z.array(zAppChatPromptMessageResponse).optional(),
})

/**
 * AppConversationHistoriesRoleResponse
 */
export const zAppConversationHistoriesRoleResponse = z.object({
  assistant_prefix: z.string(),
  user_prefix: z.string(),
})

/**
 * AppCompletionPromptTextResponse
 */
export const zAppCompletionPromptTextResponse = z.object({
  text: z.string(),
})

/**
 * AppCompletionPromptConfigResponse
 */
export const zAppCompletionPromptConfigResponse = z.object({
  conversation_histories_role: zAppConversationHistoriesRoleResponse.optional(),
  prompt: zAppCompletionPromptTextResponse.optional(),
})

/**
 * RerankMode
 */
export const zRerankMode = z.enum(['reranking_model', 'weighted_score'])

/**
 * AppRerankingModelResponse
 */
export const zAppRerankingModelResponse = z.object({
  reranking_model_name: z.string().optional(),
  reranking_provider_name: z.string().optional(),
})

export const zJsonValue = z.unknown()

/**
 * AppEnabledExternalDataToolResponse
 */
export const zAppEnabledExternalDataToolResponse = z.object({
  config: z.record(z.string(), zJsonValue),
  enabled: z.literal(true),
  icon: z.string().optional(),
  icon_background: z.string().optional(),
  label: z.string().optional(),
  type: z.string(),
  variable: z.string(),
})

/**
 * AppDisabledExternalDataToolResponse
 */
export const zAppDisabledExternalDataToolResponse = z.object({
  config: z.record(z.string(), zJsonValue).optional(),
  enabled: z.literal(false),
  icon: z.string().optional(),
  icon_background: z.string().optional(),
  label: z.string().optional(),
  type: z.string().optional(),
  variable: z.string().optional(),
})

/**
 * AppSensitiveWordAvoidanceResponse
 */
export const zAppSensitiveWordAvoidanceResponse = z.object({
  config: z.record(z.string(), zJsonValue).optional(),
  configs: z.array(zJsonValue).optional(),
  enabled: z.boolean(),
  type: z.string().optional(),
})

/**
 * HumanInputFormSubmissionData
 */
export const zHumanInputFormSubmissionData = z.object({
  action_id: z.string(),
  action_text: z.string(),
  node_id: z.string(),
  node_title: z.string(),
  rendered_content: z.string(),
  submitted_data: z.record(z.string(), zJsonValue).nullish(),
})

/**
 * AppLegacyGoogleSearchToolResponse
 */
export const zAppLegacyGoogleSearchToolResponse = z.object({
  google_search: z.record(z.string(), zJsonValue),
})

/**
 * AppLegacyWebReaderToolResponse
 */
export const zAppLegacyWebReaderToolResponse = z.object({
  web_reader: z.record(z.string(), zJsonValue),
})

/**
 * AppLegacyWikipediaToolResponse
 */
export const zAppLegacyWikipediaToolResponse = z.object({
  wikipedia: z.record(z.string(), zJsonValue),
})

/**
 * AppLegacyCurrentDatetimeToolResponse
 */
export const zAppLegacyCurrentDatetimeToolResponse = z.object({
  current_datetime: z.record(z.string(), zJsonValue),
})

/**
 * FileType
 */
export const zFileType = z.enum(['audio', 'custom', 'document', 'image', 'video'])

/**
 * FileTransferMethod
 */
export const zFileTransferMethod = z.enum([
  'datasource_file',
  'local_file',
  'remote_url',
  'tool_file',
])

/**
 * AppImageUploadResponse
 */
export const zAppImageUploadResponse = z.object({
  detail: z.enum(['high', 'low']).nullish(),
  enabled: z.boolean().optional(),
  number_limits: z.int().optional(),
  transfer_methods: z.array(zFileTransferMethod).optional(),
})

/**
 * AppFileUploadResponse
 */
export const zAppFileUploadResponse = z.object({
  allowed_file_extensions: z.array(z.string()).optional(),
  allowed_file_types: z.array(zFileType).optional(),
  allowed_file_upload_methods: z.array(zFileTransferMethod).optional(),
  enabled: z.boolean().optional(),
  image: zAppImageUploadResponse.optional(),
  number_limits: z.int().optional(),
})

/**
 * LLMMode
 *
 * Enum class for large language model mode.
 */
export const zLlmMode = z.enum(['chat', 'completion'])

/**
 * AppModelSelectionResponse
 */
export const zAppModelSelectionResponse = z.object({
  completion_params: z.record(z.string(), zJsonValue).optional(),
  mode: z.union([zLlmMode, z.literal('')]).optional(),
  name: z.string().optional(),
  provider: z.string().optional(),
})

/**
 * ModelConfigPartial
 */
export const zModelConfigPartial = z.object({
  created_at: z.int().nullish(),
  created_by: z.string().nullish(),
  model: zAppModelSelectionResponse.nullish(),
  pre_prompt: z.string().nullish(),
  updated_at: z.int().nullish(),
  updated_by: z.string().nullish(),
})

/**
 * AgentAppPartial
 */
export const zAgentAppPartial = z.object({
  access_mode: zWebAppAccessMode.nullish(),
  active_config_is_published: z.boolean().optional().default(false),
  app_id: z.string().nullish(),
  author_name: z.string().nullish(),
  backing_app_id: z.string().nullish(),
  bound_agent_id: z.string().nullish(),
  create_user_name: z.string().nullish(),
  created_at: z.int().nullish(),
  created_by: z.string().nullish(),
  debug_conversation_id: z.string().nullish(),
  description: z.string().nullish(),
  has_draft_trigger: z.boolean().nullish(),
  hidden_app_backed: z.boolean().optional().default(false),
  icon: z.string().nullish(),
  icon_background: z.string().nullish(),
  icon_type: zIconType.nullish(),
  icon_url: z.string().nullable(),
  id: z.string(),
  is_starred: z.boolean().optional().default(false),
  maintainer: z.string().nullish(),
  max_active_requests: z.int().nullish(),
  mode: zAppMode,
  model_config: zModelConfigPartial.nullish(),
  name: z.string(),
  permission_keys: z.array(z.string()),
  published_reference_count: z.int().optional().default(0),
  published_references: z.array(zAgentAppPublishedReferenceResponse).optional(),
  reference_count: z.int().nullish(),
  role: z.string().nullish(),
  tags: z.array(zTag).optional(),
  updated_at: z.int().nullish(),
  updated_by: z.string().nullish(),
  use_icon_as_answer_icon: z.boolean().nullish(),
  workflow: zWorkflowPartial.nullish(),
})

/**
 * AgentAppPagination
 */
export const zAgentAppPagination = z.object({
  data: z.array(zAgentAppPartial),
  has_more: z.boolean(),
  limit: z.int(),
  page: z.int(),
  publication_counts: zAgentPublicationCountsResponse,
  total: z.int(),
})

/**
 * AppSuggestedQuestionsAfterAnswerResponse
 */
export const zAppSuggestedQuestionsAfterAnswerResponse = z.object({
  enabled: z.boolean(),
  model: zAppModelSelectionResponse.optional(),
  prompt: z.string().optional(),
})

/**
 * AppUserInputFormConfigResponse
 */
export const zAppUserInputFormConfigResponse = z.object({
  allowed_file_extensions: z.array(z.string()).optional(),
  allowed_file_types: z.array(zFileType).optional(),
  allowed_file_upload_methods: z.array(zFileTransferMethod).optional(),
  config: z.record(z.string(), zJsonValue).optional(),
  default: zJsonValue.optional(),
  description: z.string().optional(),
  enabled: z.boolean().optional(),
  hide: z.boolean().optional(),
  icon: z.string().nullish(),
  icon_background: z.string().nullish(),
  json_schema: z.union([z.string(), z.record(z.string(), zJsonValue)]).nullish(),
  label: z.string(),
  max_length: z.int().nullish(),
  options: z.array(z.string()).optional(),
  required: z.boolean().optional(),
  type: z.string().optional(),
  variable: z.string(),
})

/**
 * AppTextInputFormResponse
 */
export const zAppTextInputFormResponse = z.object({
  'text-input': zAppUserInputFormConfigResponse,
})

/**
 * AppSelectFormResponse
 */
export const zAppSelectFormResponse = z.object({
  select: zAppUserInputFormConfigResponse,
})

/**
 * AppParagraphFormResponse
 */
export const zAppParagraphFormResponse = z.object({
  paragraph: zAppUserInputFormConfigResponse,
})

/**
 * AppNumberFormResponse
 */
export const zAppNumberFormResponse = z.object({
  number: zAppUserInputFormConfigResponse,
})

/**
 * AppCheckboxFormResponse
 */
export const zAppCheckboxFormResponse = z.object({
  checkbox: zAppUserInputFormConfigResponse,
})

/**
 * AppFileFormResponse
 */
export const zAppFileFormResponse = z.object({
  file: zAppUserInputFormConfigResponse,
})

/**
 * AppFileListFormResponse
 */
export const zAppFileListFormResponse = z.object({
  'file-list': zAppUserInputFormConfigResponse,
})

/**
 * AppExternalDataToolFormResponse
 */
export const zAppExternalDataToolFormResponse = z.object({
  external_data_tool: zAppUserInputFormConfigResponse,
})

/**
 * AppJsonObjectFormResponse
 */
export const zAppJsonObjectFormResponse = z.object({
  json_object: zAppUserInputFormConfigResponse,
})

/**
 * AgentEnvVariableConfig
 */
export const zAgentEnvVariableConfig = z.object({
  default: z
    .union([
      z.string(),
      z.int(),
      z.number(),
      z.boolean(),
      z.array(z.string()),
      z.array(z.int()),
      z.array(z.number()),
      z.array(z.boolean()),
    ])
    .nullish(),
  env_name: z.string().max(255).nullish(),
  key: z.string().max(255).nullish(),
  name: z.string().max(255).nullish(),
  required: z.boolean().optional().default(false),
  type: z.string().max(64).nullish(),
  value: z
    .union([
      z.string(),
      z.int(),
      z.number(),
      z.boolean(),
      z.array(z.string()),
      z.array(z.int()),
      z.array(z.number()),
      z.array(z.boolean()),
    ])
    .nullish(),
  variable: z.string().max(255).nullish(),
})

/**
 * AgentHumanToolConfig
 */
export const zAgentHumanToolConfig = z.object({
  description: z.string().nullish(),
  enabled: z.boolean().optional().default(true),
  name: z.string().max(255).nullish(),
})

/**
 * AgentSoulHumanConfig
 */
export const zAgentSoulHumanConfig = z.object({
  contacts: z.array(zAgentHumanContactConfig).optional(),
  tools: z.array(zAgentHumanToolConfig).optional(),
})

/**
 * AgentKnowledgeSpaceConfig
 *
 * One read-only Agent Knowledge Base binding, addressed by stable ID or CLI alias.
 *
 * The control-space ID is Dify-owned, never the execution-plane space ID.
 * ``is_missing`` preserves unresolved DSL references for editing; it never
 * authorizes execution. Names/descriptions are author guidance, not authority.
 */
export const zAgentKnowledgeSpaceConfig = z.object({
  control_space_id: z.string().length(36),
  description: z.string().max(2000).nullish(),
  id: z.string().min(1).max(255),
  is_missing: z.boolean().optional().default(false),
  name: z.string().min(1).max(120),
})

/**
 * AgentMemoryArtifactConfig
 */
export const zAgentMemoryArtifactConfig = z.object({
  id: z.string().max(255).nullish(),
  name: z.string().max(255).nullish(),
  type: z.string().max(64).nullish(),
  url: z.string().nullish(),
})

/**
 * AgentSoulMemoryConfig
 */
export const zAgentSoulMemoryConfig = z.object({
  artifacts: z.array(zAgentMemoryArtifactConfig).optional(),
  budget: z.string().nullish(),
  scope: z.string().nullish(),
})

/**
 * AgentSoulModelCredentialRef
 *
 * Reference to model credentials resolved only at runtime.
 */
export const zAgentSoulModelCredentialRef = z.object({
  id: z.string().max(255).nullish(),
  provider: z.string().max(255).nullish(),
  type: z.string().min(1).max(64),
})

/**
 * AgentSandboxProviderConfig
 */
export const zAgentSandboxProviderConfig = z.object({
  cpu: z.int().gte(1).nullish(),
  env: z.array(zAgentEnvVariableConfig).optional(),
  image: z.string().nullish(),
  working_dir: z.string().nullish(),
})

/**
 * AgentSoulSandboxConfig
 */
export const zAgentSoulSandboxConfig = z.object({
  config: zAgentSandboxProviderConfig.optional(),
  provider: z.string().nullish(),
})

/**
 * DeclaredArrayItem
 *
 * Per-item shape for an ``array``-typed declared output.
 *
 * The PRD output configuration section limits arrays to one level; nested arrays
 * are rejected so the runtime type checker and JSON Schema stay easy to reason
 * about. Stage 4 §4.2.
 */
export const zDeclaredArrayItem = z.object({
  children: z
    .array(
      z.object({
        array_item: z
          .object({
            children: z.array(z.record(z.string(), z.unknown())).optional(),
            description: z.string().nullish(),
            type: z.enum(['array', 'boolean', 'file', 'number', 'object', 'string']).optional(),
          })
          .nullish(),
        children: z.array(z.record(z.string(), z.unknown())).optional(),
        description: z.string().nullish(),
        file: z.record(z.string(), z.unknown()).nullish(),
        name: z.string(),
        required: z.boolean().optional(),
        type: z.enum(['array', 'boolean', 'file', 'number', 'object', 'string']),
      }),
    )
    .optional(),
  description: z.string().nullish(),
  type: zDeclaredOutputType,
})

/**
 * DeclaredOutputFileConfig
 *
 * File-type output metadata. Both lists empty means "any file accepted".
 */
export const zDeclaredOutputFileConfig = z.object({
  extensions: z.array(z.string()).optional(),
  mime_types: z.array(z.string()).optional(),
})

/**
 * AgentFileRefConfig
 */
export const zAgentFileRefConfig = z.object({
  file_id: z.string().max(255).nullish(),
  id: z.string().max(255).nullish(),
  name: z.string().max(255).nullish(),
  reference: z.string().max(255).nullish(),
  remote_url: z.string().nullish(),
  tenant_id: z.string().max(255).nullish(),
  transfer_method: z.string().max(64).nullish(),
  type: z.string().max(64).nullish(),
  upload_file_id: z.string().max(255).nullish(),
  url: z.string().nullish(),
})

/**
 * WorkflowNodeJobMetadata
 */
export const zWorkflowNodeJobMetadata = z.object({
  agent_soul: z.record(z.string(), z.unknown()).nullish(),
  file_refs: z.array(zAgentFileRefConfig).nullish(),
})

/**
 * WorkflowOutputRoute
 *
 * Stable workflow exit identity and its model-visible selection condition.
 */
export const zWorkflowOutputRoute = z.object({
  id: z.string().min(1),
  label: z.string().nullish(),
  name: z.string().optional().default(''),
})

/**
 * WorkflowOutputRoutes
 *
 * Enabled routes require at least two exits; drafts may omit conditions.
 */
export const zWorkflowOutputRoutes = z.object({
  enabled: z.boolean().optional().default(false),
  routes: z.array(zWorkflowOutputRoute).optional(),
})

/**
 * AgentCliToolAuthorizationStatus
 *
 * Authorization state for Agent-scoped CLI tools.
 *
 * Missing status keeps backward compatibility with draft rows and CLI tools that
 * do not need pre-authorization. Explicit denied-like states are blocked by the
 * composer/publish validators and skipped by runtime request builders.
 */
export const zAgentCliToolAuthorizationStatus = z.enum([
  'allowed',
  'authorized',
  'denied',
  'forbidden',
  'not_required',
  'pending',
  'pre_authorized',
  'unauthorized',
])

/**
 * AgentPermissionConfig
 */
export const zAgentPermissionConfig = z.object({
  allowed: z.boolean().nullish(),
  state: z.string().max(64).nullish(),
  status: z.string().max(64).nullish(),
})

/**
 * AgentSecretRefConfig
 */
export const zAgentSecretRefConfig = z.object({
  credential_id: z.string().max(255).nullish(),
  env_name: z.string().max(255).nullish(),
  id: z.string().max(255).nullish(),
  key: z.string().max(255).nullish(),
  name: z.string().max(255).nullish(),
  permission: zAgentPermissionConfig.nullish(),
  permission_status: z.string().max(64).nullish(),
  provider: z.string().max(255).nullish(),
  provider_credential_id: z.string().max(255).nullish(),
  ref: z.string().max(255).nullish(),
  type: z.string().max(64).nullish(),
  value: z.string().nullish(),
  variable: z.string().max(255).nullish(),
})

/**
 * AgentSoulEnvConfig
 */
export const zAgentSoulEnvConfig = z.object({
  secret_refs: z.array(zAgentSecretRefConfig).optional(),
  variables: z.array(zAgentEnvVariableConfig).optional(),
})

/**
 * AgentCliToolEnvConfig
 */
export const zAgentCliToolEnvConfig = z.object({
  secret_refs: z.array(zAgentSecretRefConfig).optional(),
  variables: z.array(zAgentEnvVariableConfig).optional(),
})

/**
 * AgentCliToolRiskLevel
 *
 * Risk marker for CLI tool bootstrap commands.
 */
export const zAgentCliToolRiskLevel = z.enum(['dangerous', 'safe', 'unknown'])

/**
 * AgentCliToolConfig
 */
export const zAgentCliToolConfig = z.object({
  approved: z.boolean().optional().default(false),
  authorization_status: zAgentCliToolAuthorizationStatus.nullish(),
  command: z.string().nullish(),
  dangerous: z.boolean().optional().default(false),
  dangerous_accepted: z.boolean().optional().default(false),
  dangerous_acknowledged: z.boolean().optional().default(false),
  dangerous_command: z.boolean().optional().default(false),
  description: z.string().nullish(),
  enabled: z.boolean().optional().default(true),
  env: zAgentCliToolEnvConfig.optional(),
  id: z.string().max(255).nullish(),
  inferred_from: z.string().max(255).nullish(),
  install: z.string().nullish(),
  install_command: z.string().nullish(),
  install_commands: z.array(z.string()).optional(),
  invoke_metadata: z.record(z.string(), z.unknown()).optional(),
  label: z.string().max(255).nullish(),
  name: z.string().max(255).nullish(),
  permission: zAgentPermissionConfig.nullish(),
  pre_authorized: z.boolean().nullish(),
  requires_confirmation: z.boolean().optional().default(false),
  risk_accepted: z.boolean().optional().default(false),
  risk_level: zAgentCliToolRiskLevel.nullish(),
  setup_command: z.string().nullish(),
  tool_name: z.string().max(255).nullish(),
})

/**
 * AgentComposerKnowledgeDatasetCandidateResponse
 */
export const zAgentComposerKnowledgeDatasetCandidateResponse = z.object({
  description: z.string().nullish(),
  id: z.string().max(255).nullish(),
  missing: z.boolean().optional().default(false),
  name: z.string().max(255).nullish(),
})

/**
 * AgentComposerKnowledgeSetCandidateResponse
 */
export const zAgentComposerKnowledgeSetCandidateResponse = z.object({
  control_space_id: z.string().nullish(),
  datasets: z.array(zAgentComposerKnowledgeDatasetCandidateResponse).optional(),
  description: z.string().nullish(),
  id: z.string(),
  missing: z.boolean().optional().default(false),
  missing_dataset_ids: z.array(z.string()).optional(),
  name: z.string(),
})

/**
 * AgentComposerSoulCandidatesResponse
 */
export const zAgentComposerSoulCandidatesResponse = z.object({
  cli_tools: z.array(zAgentCliToolConfig).optional(),
  dify_tools: z.array(zAgentComposerDifyToolCandidateResponse).optional(),
  human_contacts: z.array(zAgentHumanContactConfig).optional(),
  knowledge_sets: z.array(zAgentComposerKnowledgeSetCandidateResponse).optional(),
})

/**
 * AgentComposerCandidatesResponse
 */
export const zAgentComposerCandidatesResponse = z.object({
  allowed_node_job_candidates: zAgentComposerNodeJobCandidatesResponse.optional(),
  allowed_soul_candidates: zAgentComposerSoulCandidatesResponse.optional(),
  capabilities: zComposerCandidateCapabilities.optional(),
  truncated: z.boolean().optional().default(false),
  variant: zComposerVariant,
})

/**
 * AgentModerationIOConfig
 */
export const zAgentModerationIoConfig = z.object({
  enabled: z.boolean().optional().default(false),
  preset_response: z.string().nullish(),
})

/**
 * AgentModerationProviderConfig
 */
export const zAgentModerationProviderConfig = z.object({
  api_based_extension_id: z.string().nullish(),
  inputs_config: zAgentModerationIoConfig.nullish(),
  keywords: z.string().nullish(),
  outputs_config: zAgentModerationIoConfig.nullish(),
})

/**
 * AgentSensitiveWordAvoidanceFeatureConfig
 */
export const zAgentSensitiveWordAvoidanceFeatureConfig = z.object({
  config: zAgentModerationProviderConfig.nullish(),
  enabled: z.boolean().optional().default(false),
  type: z.string().nullish(),
})

/**
 * AgentAppFeaturesPayload
 *
 * Presentation features configurable on an Agent App.
 *
 * All fields are optional; an omitted field is reset to its disabled/empty
 * default (the config form sends the full desired feature state on save).
 */
export const zAgentAppFeaturesPayload = z.object({
  opening_statement: z.string().nullish(),
  retriever_resource: zAgentFeatureToggleConfig.nullish(),
  sensitive_word_avoidance: zAgentSensitiveWordAvoidanceFeatureConfig.nullish(),
  speech_to_text: zAgentFeatureToggleConfig.nullish(),
  suggested_questions: z.array(z.string()).nullish(),
  suggested_questions_after_answer: zAgentSuggestedQuestionsAfterAnswerFeatureConfig.nullish(),
  text_to_speech: zAgentTextToSpeechFeatureConfig.nullish(),
})

/**
 * ToolProviderType
 *
 * Enum class for tool provider
 */
export const zToolProviderType = z.enum([
  'api',
  'app',
  'builtin',
  'dataset-retrieval',
  'mcp',
  'plugin',
  'workflow',
])

/**
 * AppProviderAgentToolResponse
 */
export const zAppProviderAgentToolResponse = z.object({
  credential_id: z.string().nullish(),
  enabled: z.boolean().optional(),
  isDeleted: z.boolean().optional(),
  notAuthor: z.boolean().optional(),
  plugin_unique_identifier: z.string().nullish(),
  provider_id: z.string(),
  provider_name: z.string().optional(),
  provider_type: zToolProviderType,
  tool_label: z.string().optional(),
  tool_name: z.string(),
  tool_parameters: z.record(z.string(), zJsonValue),
})

/**
 * AppDatasetReferenceResponse
 */
export const zAppDatasetReferenceResponse = z.object({
  enabled: z.boolean().optional(),
  id: z.string().optional(),
})

/**
 * AppLegacyDatasetToolResponse
 */
export const zAppLegacyDatasetToolResponse = z.object({
  dataset: zAppDatasetReferenceResponse,
})

/**
 * AppLegacySensitiveWordToolResponse
 */
export const zAppLegacySensitiveWordToolResponse = z.object({
  canned_response: z.string(),
  enabled: z.boolean(),
  words: z.array(z.string()),
})

/**
 * AppLegacySensitiveWordToolResponseItem
 */
export const zAppLegacySensitiveWordToolResponseItem = z.object({
  'sensitive-word-avoidance': zAppLegacySensitiveWordToolResponse,
})

/**
 * AppAgentModeResponse
 */
export const zAppAgentModeResponse = z.object({
  enabled: z.boolean(),
  max_iteration: z.int().optional(),
  prompt: z.union([zAppAgentPromptResponse, z.string()]).nullish(),
  strategy: z.union([zPlanningStrategy, z.enum(['cot', 'function-calling'])]).nullish(),
  tools: z
    .array(
      z.union([
        zAppProviderAgentToolResponse,
        zAppLegacyDatasetToolResponse,
        zAppLegacyGoogleSearchToolResponse,
        zAppLegacyWebReaderToolResponse,
        zAppLegacyWikipediaToolResponse,
        zAppLegacyCurrentDatetimeToolResponse,
        zAppLegacySensitiveWordToolResponseItem,
      ]),
    )
    .optional(),
})

/**
 * AppDatasetItemResponse
 */
export const zAppDatasetItemResponse = z.object({
  dataset: zAppDatasetReferenceResponse,
})

/**
 * AppDatasetListResponse
 */
export const zAppDatasetListResponse = z.object({
  datasets: z.array(zAppDatasetItemResponse),
  strategy: z.string().optional(),
})

/**
 * AppMetadataConditionResponse
 */
export const zAppMetadataConditionResponse = z.object({
  comparison_operator: z.enum([
    '<',
    '=',
    '>',
    'after',
    'before',
    'contains',
    'empty',
    'end with',
    'in',
    'is',
    'is not',
    'not contains',
    'not empty',
    'not in',
    'start with',
    '≠',
    '≤',
    '≥',
  ]),
  id: z.string().optional(),
  metadata_id: z.string().optional(),
  name: z.string(),
  value: z.union([z.string(), z.array(z.string()), z.int(), z.number()]).nullish(),
})

/**
 * AppMetadataFilteringConditionsResponse
 */
export const zAppMetadataFilteringConditionsResponse = z.object({
  conditions: z.array(zAppMetadataConditionResponse).nullish(),
  logical_operator: z.enum(['and', 'or']).nullish(),
})

/**
 * AppKeywordSettingResponse
 */
export const zAppKeywordSettingResponse = z.object({
  keyword_weight: z.number(),
})

/**
 * AppVectorSettingResponse
 */
export const zAppVectorSettingResponse = z.object({
  embedding_model_name: z.string(),
  embedding_provider_name: z.string(),
  vector_weight: z.number(),
})

/**
 * AppWeightsResponse
 */
export const zAppWeightsResponse = z.object({
  keyword_setting: zAppKeywordSettingResponse,
  vector_setting: zAppVectorSettingResponse,
  weight_type: z.enum(['customized', 'keyword_first', 'semantic_first']).optional(),
})

/**
 * AppDatasetConfigsResponse
 */
export const zAppDatasetConfigsResponse = z.object({
  datasets: zAppDatasetListResponse.optional(),
  metadata_filtering_conditions: zAppMetadataFilteringConditionsResponse.nullish(),
  metadata_filtering_mode: z.enum(['automatic', 'disabled', 'manual']).optional(),
  metadata_model_config: zAppModelSelectionResponse.nullish(),
  reranking_enable: z.boolean().optional(),
  reranking_enabled: z.boolean().optional(),
  reranking_mode: zRerankMode.optional(),
  reranking_model: zAppRerankingModelResponse.nullish(),
  retrieval_model: z.enum(['multiple', 'single']),
  score_threshold: z.number().nullish(),
  score_threshold_enabled: z.boolean().optional(),
  top_k: z.int().optional(),
  weights: zAppWeightsResponse.nullish(),
})

/**
 * AppModelConfigResponse
 */
export const zAppModelConfigResponse = z.object({
  agent_mode: zAppAgentModeResponse,
  annotation_reply: z.union([
    zAppAnnotationReplyEnabledResponse,
    zAppAnnotationReplyDisabledResponse,
  ]),
  chat_prompt_config: zAppChatPromptConfigResponse,
  completion_prompt_config: zAppCompletionPromptConfigResponse,
  created_at: z.int(),
  created_by: z.string().nullable(),
  dataset_configs: zAppDatasetConfigsResponse,
  dataset_query_variable: z.string().nullable(),
  external_data_tools: z.array(
    z.union([zAppEnabledExternalDataToolResponse, zAppDisabledExternalDataToolResponse]),
  ),
  file_upload: zAppFileUploadResponse,
  model: zAppModelSelectionResponse,
  more_like_this: zAppEnabledConfigResponse,
  opening_statement: z.string().nullable(),
  pre_prompt: z.string().nullable(),
  prompt_type: zPromptType,
  retriever_resource: zAppEnabledConfigResponse,
  sensitive_word_avoidance: zAppSensitiveWordAvoidanceResponse,
  speech_to_text: zAppEnabledConfigResponse,
  suggested_questions: z.array(z.string()),
  suggested_questions_after_answer: zAppSuggestedQuestionsAfterAnswerResponse,
  text_to_speech: zAppTextToSpeechResponse,
  updated_at: z.int(),
  updated_by: z.string().nullable(),
  user_input_form: z.array(
    z.union([
      zAppTextInputFormResponse,
      zAppSelectFormResponse,
      zAppParagraphFormResponse,
      zAppNumberFormResponse,
      zAppCheckboxFormResponse,
      zAppFileFormResponse,
      zAppFileListFormResponse,
      zAppExternalDataToolFormResponse,
      zAppJsonObjectFormResponse,
    ]),
  ),
})

/**
 * AgentAppDetailWithSite
 */
export const zAgentAppDetailWithSite = z.object({
  access_mode: zWebAppAccessMode.nullable(),
  access_ready: z.boolean().optional().default(false),
  api_base_url: z.string(),
  app_id: z.string().nullish(),
  backing_app_id: z.string().nullish(),
  bound_agent_id: z.string().nullish(),
  created_at: z.int(),
  created_by: z.string().nullable(),
  debug_conversation_has_messages: z.boolean().optional().default(false),
  debug_conversation_id: z.string().nullish(),
  debug_conversation_message_count: z.int().optional().default(0),
  deleted_tools: z.array(zDeletedTool),
  description: z.string(),
  enable_api: z.boolean(),
  enable_site: z.boolean(),
  hidden_app_backed: z.boolean().optional().default(false),
  icon: z.string().nullable(),
  icon_background: z.string().nullable(),
  icon_type: zIconType.nullable(),
  icon_url: z.string().nullable(),
  id: z.string(),
  maintainer: z.string().nullable(),
  max_active_requests: z.int().nullable(),
  mode: zAppMode,
  model_config: zAppModelConfigResponse.nullable(),
  name: z.string(),
  permission_keys: z.array(z.string()),
  role: z.string().nullish(),
  site: zAppDetailSiteResponse.nullable(),
  tags: z.array(zTag),
  tracing: z.string().nullable(),
  updated_at: z.int(),
  updated_by: z.string().nullable(),
  use_icon_as_answer_icon: z.boolean(),
  workflow: zWorkflowPartial.nullable(),
})

/**
 * AgentFileUploadImageFeatureConfig
 */
export const zAgentFileUploadImageFeatureConfig = z.object({
  enabled: z.boolean().optional().default(true),
})

/**
 * AgentFileUploadFeatureConfig
 */
export const zAgentFileUploadFeatureConfig = z.object({
  allowed_file_extensions: z.array(z.string()).optional(),
  allowed_file_types: z.array(zFileType).optional(),
  allowed_file_upload_methods: z.array(zFileTransferMethod).optional(),
  enabled: z.boolean().optional().default(true),
  image: zAgentFileUploadImageFeatureConfig.optional(),
  number_limits: z.int().optional().default(3),
})

/**
 * AgentSoulAppFeaturesConfig
 */
export const zAgentSoulAppFeaturesConfig = z.object({
  file_upload: zAgentFileUploadFeatureConfig.optional(),
  opening_statement: z.string().nullish(),
  retriever_resource: zAgentFeatureToggleConfig.nullish(),
  sensitive_word_avoidance: zAgentSensitiveWordAvoidanceFeatureConfig.nullish(),
  show_thoughts: zAgentFeatureToggleConfig.nullish(),
  speech_to_text: zAgentFeatureToggleConfig.nullish(),
  suggested_questions: z.array(z.string()).nullish(),
  suggested_questions_after_answer: zAgentSuggestedQuestionsAfterAnswerFeatureConfig.nullish(),
  text_to_speech: zAgentTextToSpeechFeatureConfig.nullish(),
})

/**
 * AgentKnowledgeDatasetConfig
 */
export const zAgentKnowledgeDatasetConfig = z.object({
  description: z.string().nullish(),
  id: z.string().max(255).nullish(),
  name: z.string().max(255).nullish(),
})

/**
 * AgentModelResponseFormatConfig
 */
export const zAgentModelResponseFormatConfig = z.object({
  type: z.string().max(64).nullish(),
})

/**
 * AgentSoulModelSettings
 *
 * Model parameters for the Agent Soul model.
 *
 * Model plugins can declare arbitrary parameters via ``parameter_rules``
 * (e.g. Qwen/Tongyi's ``enable_thinking``) beyond the common OpenAI-style
 * fields typed below, so extra keys must round-trip through persistence
 * rather than being dropped.
 */
export const zAgentSoulModelSettings = z.object({
  frequency_penalty: z.number().nullish(),
  max_tokens: z.int().nullish(),
  presence_penalty: z.number().nullish(),
  response_format: z.union([z.string(), zAgentModelResponseFormatConfig]).nullish(),
  stop: z.array(z.string()).nullish(),
  temperature: z.number().nullish(),
  top_p: z.number().nullish(),
})

/**
 * AgentSoulModelConfig
 *
 * Stable model selection for Agent runtime without storing secret values.
 */
export const zAgentSoulModelConfig = z.object({
  credential_ref: zAgentSoulModelCredentialRef.nullish(),
  model: z.string().min(1).max(255),
  model_provider: z.string().min(1).max(255),
  model_settings: zAgentSoulModelSettings.optional(),
  plugin_id: z.string().min(1).max(255),
})

/**
 * DeclaredOutputCheckConfig
 *
 * File-output content check via a model-based comparison against a benchmark file.
 *
 * Per the PRD output configuration section, output checks are **file-only** and optional. Stage 4 §4.3.
 */
export const zDeclaredOutputCheckConfig = z.object({
  benchmark_file_ref: zAgentFileRefConfig.nullish(),
  enabled: z.boolean().optional().default(false),
  model_ref: zAgentSoulModelConfig.nullish(),
  prompt: z.string().nullish(),
})

/**
 * AgentSoulDifyToolCredentialRef
 *
 * Reference to a stored Dify Plugin Tool credential.
 *
 * Secret values are resolved only at runtime. The legacy ``credential_id``
 * field is accepted by :class:`AgentSoulDifyToolConfig` and normalized here so
 * old Agent tool payloads can be read while new payloads stay explicit.
 */
export const zAgentSoulDifyToolCredentialRef = z.object({
  id: z.string().max(255).nullish(),
  provider: z.string().max(255).nullish(),
  type: z.enum(['provider', 'tool']).optional().default('tool'),
})

/**
 * AgentSoulDifyToolConfig
 *
 * One Dify tool configured on Agent Soul.
 *
 * The API backend prepares this persisted product shape into
 * either ``DifyPluginToolConfig`` or ``DifyCoreToolConfig`` before sending a
 * run request to Agent backend. ``plugin`` providers keep the direct
 * ``dify.plugin.tools`` transport; ``builtin`` / ``api`` / ``workflow`` /
 * ``mcp`` providers are prepared for ``dify.core.tools``. ``provider_id``
 * keeps compatibility with existing Agent tool config payloads; new callers
 * should send ``plugin_id`` + ``provider`` when available.
 */
export const zAgentSoulDifyToolConfig = z.object({
  credential_ref: zAgentSoulDifyToolCredentialRef.nullish(),
  credential_type: z.enum(['api-key', 'oauth2', 'unauthorized']).optional().default('api-key'),
  description: z.string().nullish(),
  enabled: z.boolean().optional().default(true),
  name: z.string().max(255).nullish(),
  plugin_id: z.string().max(255).nullish(),
  provider: z.string().max(255).nullish(),
  provider_id: z.string().max(255).nullish(),
  provider_type: zToolProviderType,
  runtime_parameters: z
    .record(
      z.string(),
      z
        .union([
          z.string(),
          z.int(),
          z.number(),
          z.boolean(),
          z.array(z.string()),
          z.array(z.int()),
          z.array(z.number()),
          z.array(z.boolean()),
        ])
        .nullable(),
    )
    .optional(),
  tool_name: z.string().min(1).max(255).nullish(),
})

/**
 * AgentSoulToolsConfig
 */
export const zAgentSoulToolsConfig = z.object({
  cli_tools: z.array(zAgentCliToolConfig).optional(),
  dify_tools: z.array(zAgentSoulDifyToolConfig).optional(),
})

/**
 * OutputErrorStrategy
 *
 * Per-output failure handling strategy.
 *
 * Mirrors ``graphon.ErrorStrategy`` but scoped to a single declared output of
 * a Workflow Agent Node. The runtime applies the strategy after type check or
 * output check fails and any configured retry attempts have been exhausted.
 */
export const zOutputErrorStrategy = z.enum(['default_value', 'fail_branch', 'stop'])

/**
 * DeclaredOutputRetryConfig
 *
 * Per-output retry configuration that mirrors ``graphon.RetryConfig`` shape.
 */
export const zDeclaredOutputRetryConfig = z.object({
  enabled: z.boolean().optional().default(false),
  max_retries: z.int().gte(0).lte(10).optional().default(0),
  retry_interval_ms: z.int().gte(0).lte(60000).optional().default(0),
})

/**
 * DeclaredOutputFailureStrategy
 *
 * Per-output failure handling.
 *
 * A single strategy applies to both ``type_check`` and ``output_check`` failures
 * (PRD does not distinguish them at the UX level). Stage 4 §4.4.
 */
export const zDeclaredOutputFailureStrategy = z.object({
  default_value: z.unknown().optional(),
  on_failure: zOutputErrorStrategy.optional().default('stop'),
  retry: zDeclaredOutputRetryConfig.optional(),
})

/**
 * DeclaredOutputConfig
 *
 * One declared output of a Workflow Agent Node.
 *
 * Stage 4 normalizes the shape: ``check`` is singular (was ``checks: list`` in
 * stage 3), and ``failure_strategy`` defaults to a populated value so runtime
 * code can call ``output.failure_strategy.on_failure`` without None-guards.
 */
export const zDeclaredOutputConfig = z.object({
  array_item: zDeclaredArrayItem.nullish(),
  check: zDeclaredOutputCheckConfig.nullish(),
  children: z
    .array(
      z.object({
        array_item: z
          .object({
            children: z.array(z.record(z.string(), z.unknown())).optional(),
            description: z.string().nullish(),
            type: z.enum(['array', 'boolean', 'file', 'number', 'object', 'string']).optional(),
          })
          .nullish(),
        children: z.array(z.record(z.string(), z.unknown())).optional(),
        description: z.string().nullish(),
        file: z.record(z.string(), z.unknown()).nullish(),
        name: z.string(),
        required: z.boolean().optional(),
        type: z.enum(['array', 'boolean', 'file', 'number', 'object', 'string']),
      }),
    )
    .optional(),
  description: z.string().nullish(),
  failure_strategy: zDeclaredOutputFailureStrategy.optional(),
  file: zDeclaredOutputFileConfig.nullish(),
  id: z.string().nullish(),
  name: z.string().min(1).max(255),
  required: z.boolean().optional().default(true),
  type: zDeclaredOutputType,
})

/**
 * WorkflowNodeJobConfig
 */
export const zWorkflowNodeJobConfig = z.object({
  declared_outputs: z.array(zDeclaredOutputConfig).optional(),
  human_contacts: z.array(zAgentHumanContactConfig).optional(),
  metadata: zWorkflowNodeJobMetadata.optional(),
  mode: zWorkflowNodeJobMode.optional().default('tell_agent_what_to_do'),
  output_routes: zWorkflowOutputRoutes.optional(),
  previous_node_output_refs: z.array(zWorkflowPreviousNodeOutputRef).optional(),
  schema_version: z.int().optional().default(1),
  workflow_prompt: z.string().optional().default(''),
})

/**
 * ButtonStyle
 *
 * Button styles for user actions.
 */
export const zButtonStyle = z.enum(['accent', 'default', 'ghost', 'primary'])

/**
 * UserActionConfig
 *
 * User action configuration.
 */
export const zUserActionConfig = z.object({
  button_style: zButtonStyle.optional().default('default'),
  id: z
    .string()
    .max(20)
    .regex(/^[A-Za-z_][A-Za-z0-9_]*$/),
  title: z.string().max(100),
})

/**
 * FileInputConfig
 */
export const zFileInputConfig = z.object({
  allowed_file_extensions: z.array(z.string()).optional(),
  allowed_file_types: z.array(zFileType).optional(),
  allowed_file_upload_methods: z.array(zFileTransferMethod).optional(),
  output_variable_name: z.string(),
  type: z.literal('file').optional().default('file'),
})

/**
 * FileListInputConfig
 */
export const zFileListInputConfig = z.object({
  allowed_file_extensions: z.array(z.string()).optional(),
  allowed_file_types: z.array(zFileType).optional(),
  allowed_file_upload_methods: z.array(zFileTransferMethod).optional(),
  number_limits: z.int().gte(0).optional().default(0),
  output_variable_name: z.string(),
  type: z.literal('file-list').optional().default('file-list'),
})

/**
 * AgentKnowledgeModelConfig
 */
export const zAgentKnowledgeModelConfig = z.object({
  completion_params: z.record(z.string(), z.unknown()).optional(),
  mode: z.string().min(1).max(64),
  name: z.string().min(1).max(255),
  provider: z.string().min(1).max(255),
})

/**
 * AgentKnowledgeQueryMode
 */
export const zAgentKnowledgeQueryMode = z.enum(['generated_query', 'user_query'])

/**
 * AgentKnowledgeQueryConfig
 *
 * Per-set query policy for Agent v2 knowledge retrieval.
 *
 * Agent v2 stores knowledge as explicit ``knowledge.sets`` rather than the
 * legacy flat ``datasets`` / ``query_mode`` / ``query_config`` shape. Each
 * set owns its own query policy. Mode-dependent completeness, such as
 * requiring ``value`` for ``user_query``, is enforced by composer publish
 * validation so draft saves can persist partially configured knowledge sets.
 */
export const zAgentKnowledgeQueryConfig = z.object({
  mode: zAgentKnowledgeQueryMode,
  value: z.string().nullish(),
})

/**
 * AgentKnowledgeRerankingModelConfig
 */
export const zAgentKnowledgeRerankingModelConfig = z.object({
  model: z.string().min(1).max(255),
  provider: z.string().min(1).max(255),
})

/**
 * AgentKnowledgeWeightedScoreConfig
 */
export const zAgentKnowledgeWeightedScoreConfig = z.object({
  keyword_setting: z.record(z.string(), z.unknown()).nullish(),
  vector_setting: z.record(z.string(), z.unknown()).nullish(),
  weight_type: z.string().max(64).nullish(),
})

/**
 * AgentKnowledgeRetrievalConfig
 *
 * Per-set retrieval policy for Agent v2 knowledge retrieval.
 *
 * Retrieval settings now live on each knowledge set instead of one shared
 * flat config. Mode-dependent completeness, such as requiring ``top_k`` for
 * ``multiple`` or a model for ``single``, is enforced by composer publish
 * validation so draft saves can persist partially configured knowledge sets.
 */
export const zAgentKnowledgeRetrievalConfig = z.object({
  mode: z.enum(['multiple', 'single']),
  model: zAgentKnowledgeModelConfig.nullish(),
  reranking_enable: z.boolean().optional().default(true),
  reranking_mode: z.string().optional().default('reranking_model'),
  reranking_model: zAgentKnowledgeRerankingModelConfig.nullish(),
  score_threshold: z.number().gte(0).lte(1).nullish(),
  top_k: z.int().gte(1).nullish(),
  weights: zAgentKnowledgeWeightedScoreConfig.nullish(),
})

/**
 * AgentKnowledgeMetadataCondition
 *
 * One manual metadata filter clause.
 *
 * ``id`` and ``metadata_id`` are UI-only bookkeeping the composer sends on
 * every save (a stable row key and a reference to the selected metadata
 * field). They are persisted here for round-tripping the composer's draft
 * state but are stripped before building the Agent runtime request, whose
 * DTO only accepts ``name``/``comparison_operator``/``value``.
 */
export const zAgentKnowledgeMetadataCondition = z.object({
  comparison_operator: z.enum([
    '<',
    '=',
    '>',
    'after',
    'before',
    'contains',
    'empty',
    'end with',
    'in',
    'is',
    'is not',
    'not contains',
    'not empty',
    'not in',
    'start with',
    '≠',
    '≤',
    '≥',
  ]),
  id: z.string().nullish(),
  metadata_id: z.string().nullish(),
  name: z.string().min(1).max(255),
  value: z.union([z.string(), z.array(z.string()), z.number()]).nullish(),
})

/**
 * AgentKnowledgeMetadataConditions
 */
export const zAgentKnowledgeMetadataConditions = z.object({
  conditions: z.array(zAgentKnowledgeMetadataCondition).optional(),
  logical_operator: z.enum(['and', 'or']).optional().default('and'),
})

/**
 * AgentKnowledgeMetadataFilteringConfig
 *
 * Per-set metadata filtering policy.
 *
 * The Python attribute uses ``metadata_model_config`` for clarity because the
 * model belongs to metadata filtering specifically, while the external API and
 * generated schema keep the historical ``model_config`` field name via alias.
 * Mode-dependent completeness is enforced by composer publish validation so
 * draft saves can persist partially configured metadata filters.
 */
export const zAgentKnowledgeMetadataFilteringConfig = z.object({
  conditions: zAgentKnowledgeMetadataConditions.nullish(),
  mode: z.enum(['automatic', 'disabled', 'manual']).optional().default('disabled'),
  model_config: zAgentKnowledgeModelConfig.nullish(),
})

/**
 * AgentKnowledgeSetConfig
 *
 * One explicit knowledge set in Agent v2.
 *
 * ``knowledge.sets`` replaces the old flat knowledge config. Each set owns
 * its datasets plus query, retrieval, and metadata policies. An individual
 * set must contain at least one dataset id even though the overall knowledge
 * section may be empty, which is how callers express "no knowledge layer".
 */
export const zAgentKnowledgeSetConfig = z.object({
  datasets: z.array(zAgentKnowledgeDatasetConfig),
  description: z.string().nullish(),
  id: z.string().min(1).max(255),
  metadata_filtering: zAgentKnowledgeMetadataFilteringConfig.optional(),
  name: z.string().min(1).max(255),
  query: zAgentKnowledgeQueryConfig,
  retrieval: zAgentKnowledgeRetrievalConfig,
})

/**
 * AgentSoulKnowledgeConfig
 *
 * Agent Knowledge Base and Classic Knowledge Base bindings for an Agent.
 *
 * ``spaces`` use the KnowledgeFS layer and ``sets`` use the Classic Knowledge
 * Base layer. Both may be configured together; empty knowledge adds no runtime
 * capability.
 */
export const zAgentSoulKnowledgeConfig = z.object({
  sets: z.array(zAgentKnowledgeSetConfig).optional(),
  spaces: z.array(zAgentKnowledgeSpaceConfig).max(10).optional(),
})

/**
 * AgentSoulConfig
 */
export const zAgentSoulConfig = z.object({
  app_features: zAgentSoulAppFeaturesConfig.optional(),
  app_variables: z.array(zAppVariableConfig).optional(),
  config_files: z.array(zAgentConfigFileRefConfig).optional(),
  config_note: z.string().optional().default(''),
  config_skills: z.array(zAgentConfigSkillRefConfig).optional(),
  env: zAgentSoulEnvConfig.optional(),
  human: zAgentSoulHumanConfig.optional(),
  knowledge: zAgentSoulKnowledgeConfig.optional(),
  memory: zAgentSoulMemoryConfig.optional(),
  misc_legacy: zAgentSoulAppFeaturesConfig.optional(),
  model: zAgentSoulModelConfig.nullish(),
  prompt: zAgentSoulPromptConfig.optional(),
  sandbox: zAgentSoulSandboxConfig.optional(),
  schema_version: z.int().optional().default(1),
  tools: zAgentSoulToolsConfig.optional(),
})

/**
 * AgentBuildDraftResponse
 */
export const zAgentBuildDraftResponse = z.object({
  agent_soul: zAgentSoulConfig,
  draft: zAgentConfigDraftSummaryResponse,
  variant: z.string(),
})

/**
 * ComposerSavePayload
 */
export const zComposerSavePayload = z.object({
  agent_soul: zAgentSoulConfig.nullish(),
  binding: zComposerBindingPayload.nullish(),
  client_revision_id: z.string().nullish(),
  description: z.string().nullish(),
  icon: z.string().max(255).nullish(),
  icon_background: z.string().max(255).nullish(),
  icon_type: zAgentIconType.nullish(),
  idempotency_key: z.string().nullish(),
  new_agent_name: z.string().min(1).max(255).nullish(),
  node_job: zWorkflowNodeJobConfig.nullish(),
  role: z.string().max(255).nullish(),
  save_strategy: zComposerSaveStrategy,
  soul_lock: zComposerSoulLockPayload.optional(),
  variant: zComposerVariant,
  version_note: z.string().nullish(),
})

/**
 * AgentAppComposerResponse
 */
export const zAgentAppComposerResponse = z.object({
  active_config_is_published: z.boolean(),
  active_config_snapshot: zAgentConfigSnapshotSummaryResponse.nullish(),
  agent: zAgentComposerAgentResponse,
  agent_soul: zAgentSoulConfig,
  app_id: z.string().nullish(),
  backing_app_id: z.string().nullish(),
  chat_endpoint: z.string().nullish(),
  draft: zAgentConfigDraftSummaryResponse.nullish(),
  hidden_app_backed: z.boolean().optional().default(false),
  save_options: z.array(zComposerSaveStrategy),
  validation: zComposerValidationFindingsResponse.nullish(),
  variant: z.literal('agent_app'),
})

/**
 * AgentConfigSnapshotDetailResponse
 */
export const zAgentConfigSnapshotDetailResponse = z.object({
  agent_id: z.string().nullish(),
  config_snapshot: zAgentSoulConfig,
  created_at: z.int().nullish(),
  created_by: z.string().nullish(),
  display_version: z.int().nullish(),
  id: z.string(),
  revisions: z.array(zAgentConfigRevisionResponse).optional(),
  snapshot_version: z.int().nullish(),
  summary: z.string().nullish(),
  version: z.int(),
  version_note: z.string().nullish(),
})

/**
 * ValueSourceType
 *
 * ValueSourceType records whether the value comes from a static setting
 * in form definition, or a variable while the workflow is running.
 */
export const zValueSourceType = z.enum(['constant', 'variable'])

/**
 * StringSource
 *
 * Default configuration for form inputs.
 */
export const zStringSource = z.object({
  selector: z.array(z.string()).optional(),
  type: zValueSourceType,
  value: z.string().optional().default(''),
})

/**
 * ParagraphInputConfig
 *
 * Form input definition.
 */
export const zParagraphInputConfig = z.object({
  default: zStringSource.nullish(),
  output_variable_name: z.string(),
  type: z.literal('paragraph').optional().default('paragraph'),
})

/**
 * StringListSource
 */
export const zStringListSource = z.object({
  selector: z.array(z.string()).optional(),
  type: zValueSourceType,
  value: z.array(z.string()).optional(),
})

/**
 * SelectInputConfig
 */
export const zSelectInputConfig = z.object({
  option_source: zStringListSource,
  output_variable_name: z.string(),
  type: z.literal('select').optional().default('select'),
})

export const zFormInputConfig = z.discriminatedUnion('type', [
  zParagraphInputConfig,
  zSelectInputConfig,
  zFileInputConfig,
  zFileListInputConfig,
])

/**
 * HumanInputFormDefinition
 */
export const zHumanInputFormDefinition = z.object({
  actions: z.array(zUserActionConfig).optional(),
  display_in_ui: z.boolean().optional().default(false),
  expiration_time: z.int(),
  form_content: z.string(),
  form_id: z.string(),
  form_token: z.string().nullish(),
  form_version: z.enum(['1', '2']).optional().default('1'),
  inputs: z.array(zFormInputConfig).optional(),
  node_id: z.string(),
  node_title: z.string(),
  resolved_default_values: z.record(z.string(), z.unknown()).optional(),
})

/**
 * HumanInputContent
 */
export const zHumanInputContent = z.object({
  form_definition: zHumanInputFormDefinition.nullish(),
  form_submission_data: zHumanInputFormSubmissionData.nullish(),
  submitted: z.boolean(),
  type: zExecutionContentType.optional().default('human_input'),
  workflow_run_id: z.string(),
})

/**
 * MessageDetailResponse
 */
export const zMessageDetailResponse = z.object({
  agent_thoughts: z.array(zAgentThought),
  annotation: zConversationAnnotation.nullish(),
  annotation_hit_history: zConversationAnnotationHitHistory.nullish(),
  answer: z.string(),
  answer_tokens: z.int(),
  conversation_id: z.string(),
  created_at: z.int().nullish(),
  error: z.string().nullish(),
  extra_contents: z.array(zHumanInputContent).optional(),
  feedbacks: z.array(zFeedback),
  from_account_id: z.string().nullish(),
  from_end_user_id: z.string().nullish(),
  from_source: z.string(),
  id: z.string(),
  inputs: z.record(z.string(), zAnyJsonValue),
  message: zAnyJsonValue,
  message_files: z.array(zMessageFile),
  message_tokens: z.int(),
  metadata: zAnyJsonValue,
  parent_message_id: z.string().nullish(),
  provider_response_latency: z.number(),
  query: z.string(),
  retriever_resources: z.array(zRetrievalSourceMetadata).optional(),
  status: z.string(),
  workflow_run_id: z.string().nullish(),
})

/**
 * MessageInfiniteScrollPaginationResponse
 */
export const zMessageInfiniteScrollPaginationResponse = z.object({
  data: z.array(zMessageDetailResponse),
  has_more: z.boolean(),
  limit: z.int(),
})

/**
 * AgentAppPartial
 */
export const zAgentAppPartialWritable = z.object({
  access_mode: zWebAppAccessMode.nullish(),
  active_config_is_published: z.boolean().optional().default(false),
  app_id: z.string().nullish(),
  author_name: z.string().nullish(),
  backing_app_id: z.string().nullish(),
  bound_agent_id: z.string().nullish(),
  create_user_name: z.string().nullish(),
  created_at: z.int().nullish(),
  created_by: z.string().nullish(),
  debug_conversation_id: z.string().nullish(),
  description: z.string().nullish(),
  has_draft_trigger: z.boolean().nullish(),
  hidden_app_backed: z.boolean().optional().default(false),
  icon: z.string().nullish(),
  icon_background: z.string().nullish(),
  icon_type: zIconType.nullish(),
  id: z.string(),
  is_starred: z.boolean().optional().default(false),
  maintainer: z.string().nullish(),
  max_active_requests: z.int().nullish(),
  mode: zAppMode,
  model_config: zModelConfigPartial.nullish(),
  name: z.string(),
  permission_keys: z.array(z.string()),
  published_reference_count: z.int().optional().default(0),
  published_references: z.array(zAgentAppPublishedReferenceResponse).optional(),
  reference_count: z.int().nullish(),
  role: z.string().nullish(),
  tags: z.array(zTag).optional(),
  updated_at: z.int().nullish(),
  updated_by: z.string().nullish(),
  use_icon_as_answer_icon: z.boolean().nullish(),
  workflow: zWorkflowPartial.nullish(),
})

/**
 * AgentAppPagination
 */
export const zAgentAppPaginationWritable = z.object({
  data: z.array(zAgentAppPartialWritable),
  has_more: z.boolean(),
  limit: z.int(),
  page: z.int(),
  publication_counts: zAgentPublicationCountsResponse,
  total: z.int(),
})

/**
 * AppDetailSiteResponse
 */
export const zAppDetailSiteResponseWritable = z.object({
  access_token: z.string().nullable(),
  app_base_url: z.string(),
  chat_color_theme: z.string().nullable(),
  chat_color_theme_inverted: z.boolean(),
  code: z.string().nullable(),
  copyright: z.string().nullable(),
  created_at: z.int(),
  created_by: z.string().nullable(),
  custom_disclaimer: z.string(),
  customize_domain: z.string().nullable(),
  customize_token_strategy: zCustomizeTokenStrategy,
  default_language: z.string(),
  description: z.string().nullable(),
  icon: z.string().nullable(),
  icon_background: z.string().nullable(),
  icon_type: zIconType.nullable(),
  input_placeholder: z.string().nullable(),
  privacy_policy: z.string().nullable(),
  prompt_public: z.boolean(),
  show_workflow_steps: z.boolean(),
  title: z.string(),
  updated_at: z.int(),
  updated_by: z.string().nullable(),
  use_icon_as_answer_icon: z.boolean(),
})

/**
 * AgentAppDetailWithSite
 */
export const zAgentAppDetailWithSiteWritable = z.object({
  access_mode: zWebAppAccessMode.nullable(),
  access_ready: z.boolean().optional().default(false),
  api_base_url: z.string(),
  app_id: z.string().nullish(),
  backing_app_id: z.string().nullish(),
  bound_agent_id: z.string().nullish(),
  created_at: z.int(),
  created_by: z.string().nullable(),
  debug_conversation_has_messages: z.boolean().optional().default(false),
  debug_conversation_id: z.string().nullish(),
  debug_conversation_message_count: z.int().optional().default(0),
  deleted_tools: z.array(zDeletedTool),
  description: z.string(),
  enable_api: z.boolean(),
  enable_site: z.boolean(),
  hidden_app_backed: z.boolean().optional().default(false),
  icon: z.string().nullable(),
  icon_background: z.string().nullable(),
  icon_type: zIconType.nullable(),
  id: z.string(),
  maintainer: z.string().nullable(),
  max_active_requests: z.int().nullable(),
  mode: zAppMode,
  model_config: zAppModelConfigResponse.nullable(),
  name: z.string(),
  permission_keys: z.array(z.string()),
  role: z.string().nullish(),
  site: zAppDetailSiteResponseWritable.nullable(),
  tags: z.array(zTag),
  tracing: z.string().nullable(),
  updated_at: z.int(),
  updated_by: z.string().nullable(),
  use_icon_as_answer_icon: z.boolean(),
  workflow: zWorkflowPartial.nullable(),
})

export const zGetAgentQuery = z.object({
  creator_ids: z.array(z.string()).optional(),
  is_created_by_me: z.boolean().optional(),
  limit: z.int().gte(1).lte(100).optional().default(20),
  mode: z
    .enum([
      'advanced-chat',
      'agent',
      'agent-chat',
      'all',
      'channel',
      'chat',
      'completion',
      'workflow',
    ])
    .optional()
    .default('all'),
  name: z.string().optional(),
  openapi_visible: z.boolean().optional().default(false),
  page: z.int().gte(1).lte(99999).optional().default(1),
  publication_status: z.enum(['drafts', 'published']).optional(),
  sort_by: z
    .enum(['earliest_created', 'last_modified', 'recently_created'])
    .optional()
    .default('last_modified'),
  tag_ids: z.array(z.string()).optional(),
})

/**
 * Agent app list
 */
export const zGetAgentResponse = zAgentAppPagination

export const zPostAgentBody = zAgentAppCreatePayload

/**
 * Agent app created successfully
 */
export const zPostAgentResponse = zAgentAppDetailWithSite

export const zGetAgentInviteOptionsQuery = z.object({
  app_id: z.string().optional(),
  keyword: z.string().optional(),
  limit: z.int().gte(1).lte(100).optional().default(20),
  page: z.int().gte(1).optional().default(1),
})

/**
 * Agent invite options
 */
export const zGetAgentInviteOptionsResponse = zAgentInviteOptionsResponse

export const zDeleteAgentByAgentIdPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent app deleted successfully
 */
export const zDeleteAgentByAgentIdResponse = z.void()

export const zGetAgentByAgentIdPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent app detail
 */
export const zGetAgentByAgentIdResponse = zAgentAppDetailWithSite

export const zPutAgentByAgentIdBody = zAgentAppUpdatePayload

export const zPutAgentByAgentIdPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent app updated successfully
 */
export const zPutAgentByAgentIdResponse = zAgentAppDetailWithSite

export const zGetAgentByAgentIdApiAccessPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent service API access
 */
export const zGetAgentByAgentIdApiAccessResponse = zAgentApiAccessResponse

export const zPostAgentByAgentIdApiEnableBody = zAgentApiStatusPayload

export const zPostAgentByAgentIdApiEnablePath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent service API status updated
 */
export const zPostAgentByAgentIdApiEnableResponse = zAgentApiAccessResponse

export const zGetAgentByAgentIdApiKeysPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent service API keys
 */
export const zGetAgentByAgentIdApiKeysResponse = zApiKeyList

export const zPostAgentByAgentIdApiKeysPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent service API key created
 */
export const zPostAgentByAgentIdApiKeysResponse = zApiKeyItem

export const zDeleteAgentByAgentIdApiKeysByApiKeyIdPath = z.object({
  agent_id: z.uuid(),
  api_key_id: z.uuid(),
})

/**
 * Agent service API key deleted
 */
export const zDeleteAgentByAgentIdApiKeysByApiKeyIdResponse = z.void()

export const zPostAgentByAgentIdAudioToTextBody = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional().default('draft'),
  file: z.custom<Blob | File>((value) => value instanceof Blob || value instanceof File),
})

export const zPostAgentByAgentIdAudioToTextPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Audio transcription successful
 */
export const zPostAgentByAgentIdAudioToTextResponse = zAudioTranscriptResponse

export const zPostAgentByAgentIdBuildChatFinalizePath = z.object({
  agent_id: z.uuid(),
})

/**
 * Success
 */
export const zPostAgentByAgentIdBuildChatFinalizeResponse = zSimpleResultResponse

export const zDeleteAgentByAgentIdBuildDraftPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent build draft discarded
 */
export const zDeleteAgentByAgentIdBuildDraftResponse = zAgentSimpleResultResponse

export const zGetAgentByAgentIdBuildDraftPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent build draft
 */
export const zGetAgentByAgentIdBuildDraftResponse = zAgentBuildDraftResponse

export const zPutAgentByAgentIdBuildDraftBody = zComposerSavePayload

export const zPutAgentByAgentIdBuildDraftPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent build draft saved
 */
export const zPutAgentByAgentIdBuildDraftResponse = zAgentBuildDraftResponse

export const zPostAgentByAgentIdBuildDraftApplyPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent build draft applied
 */
export const zPostAgentByAgentIdBuildDraftApplyResponse = zAgentBuildDraftApplyResponse

export const zPostAgentByAgentIdBuildDraftCheckoutBody = zAgentBuildDraftCheckoutPayload

export const zPostAgentByAgentIdBuildDraftCheckoutPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent build draft checked out
 */
export const zPostAgentByAgentIdBuildDraftCheckoutResponse = zAgentBuildDraftResponse

export const zGetAgentByAgentIdChatMessagesPath = z.object({
  agent_id: z.uuid(),
})

export const zGetAgentByAgentIdChatMessagesQuery = z.object({
  conversation_id: z.string(),
  first_id: z.string().optional(),
  limit: z.int().gte(1).lte(100).optional().default(20),
})

/**
 * Success
 */
export const zGetAgentByAgentIdChatMessagesResponse = zMessageInfiniteScrollPaginationResponse

export const zGetAgentByAgentIdChatMessagesByMessageIdSuggestedQuestionsPath = z.object({
  agent_id: z.uuid(),
  message_id: z.uuid(),
})

/**
 * Suggested questions retrieved successfully
 */
export const zGetAgentByAgentIdChatMessagesByMessageIdSuggestedQuestionsResponse =
  zSuggestedQuestionsResponse

export const zPostAgentByAgentIdChatMessagesByTaskIdStopPath = z.object({
  agent_id: z.uuid(),
  task_id: z.string(),
})

/**
 * Task stopped successfully
 */
export const zPostAgentByAgentIdChatMessagesByTaskIdStopResponse = zSimpleResultResponse

export const zGetAgentByAgentIdComposerPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent app composer state
 */
export const zGetAgentByAgentIdComposerResponse = zAgentAppComposerResponse

export const zPutAgentByAgentIdComposerBody = zComposerSavePayload

export const zPutAgentByAgentIdComposerPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent app composer saved
 */
export const zPutAgentByAgentIdComposerResponse = zAgentAppComposerResponse

export const zGetAgentByAgentIdComposerCandidatesPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent app composer candidates
 */
export const zGetAgentByAgentIdComposerCandidatesResponse = zAgentComposerCandidatesResponse

export const zPostAgentByAgentIdComposerValidateBody = zComposerSavePayload

export const zPostAgentByAgentIdComposerValidatePath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent app composer validation result
 */
export const zPostAgentByAgentIdComposerValidateResponse = zAgentComposerValidateResponse

export const zGetAgentByAgentIdConfigFilesPath = z.object({
  agent_id: z.uuid(),
})

export const zGetAgentByAgentIdConfigFilesQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  version_id: z.string().optional(),
})

/**
 * Config files
 */
export const zGetAgentByAgentIdConfigFilesResponse = zAgentConfigFileListResponse

export const zPostAgentByAgentIdConfigFilesBody = zAgentConfigFileUploadPayload

export const zPostAgentByAgentIdConfigFilesPath = z.object({
  agent_id: z.uuid(),
})

export const zPostAgentByAgentIdConfigFilesQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  version_id: z.string().optional(),
})

/**
 * Uploaded config file
 */
export const zPostAgentByAgentIdConfigFilesResponse = zAgentConfigFileUploadResponse

export const zPostAgentByAgentIdConfigFilesBatchBody = zAgentConfigFilesUploadPayload

export const zPostAgentByAgentIdConfigFilesBatchPath = z.object({
  agent_id: z.uuid(),
})

export const zPostAgentByAgentIdConfigFilesBatchQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  version_id: z.string().optional(),
})

/**
 * Bound config files
 */
export const zPostAgentByAgentIdConfigFilesBatchResponse = zAgentConfigFilesUploadResponse

export const zDeleteAgentByAgentIdConfigFilesByNamePath = z.object({
  agent_id: z.uuid(),
  name: z.string(),
})

export const zDeleteAgentByAgentIdConfigFilesByNameQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  version_id: z.string().optional(),
})

/**
 * Config file deleted
 */
export const zDeleteAgentByAgentIdConfigFilesByNameResponse = zAgentConfigDeleteResponse

export const zGetAgentByAgentIdConfigFilesByNameDownloadPath = z.object({
  agent_id: z.uuid(),
  name: z.string(),
})

export const zGetAgentByAgentIdConfigFilesByNameDownloadQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  version_id: z.string().optional(),
})

/**
 * Config file download URL
 */
export const zGetAgentByAgentIdConfigFilesByNameDownloadResponse = zAgentConfigDownloadResponse

export const zGetAgentByAgentIdConfigFilesByNamePreviewPath = z.object({
  agent_id: z.uuid(),
  name: z.string(),
})

export const zGetAgentByAgentIdConfigFilesByNamePreviewQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  version_id: z.string().optional(),
})

/**
 * Preview
 */
export const zGetAgentByAgentIdConfigFilesByNamePreviewResponse = zAgentConfigFilePreviewResponse

export const zGetAgentByAgentIdConfigManifestPath = z.object({
  agent_id: z.uuid(),
})

export const zGetAgentByAgentIdConfigManifestQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  version_id: z.string().optional(),
})

/**
 * Agent config manifest
 */
export const zGetAgentByAgentIdConfigManifestResponse = zAgentConfigManifestResponse

export const zGetAgentByAgentIdConfigSkillsPath = z.object({
  agent_id: z.uuid(),
})

export const zGetAgentByAgentIdConfigSkillsQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  version_id: z.string().optional(),
})

/**
 * Config skills
 */
export const zGetAgentByAgentIdConfigSkillsResponse = zAgentConfigSkillListResponse

export const zPostAgentByAgentIdConfigSkillsUploadBody = z.object({
  file: z.custom<Blob | File>((value) => value instanceof Blob || value instanceof File),
})

export const zPostAgentByAgentIdConfigSkillsUploadPath = z.object({
  agent_id: z.uuid(),
})

export const zPostAgentByAgentIdConfigSkillsUploadQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  version_id: z.string().optional(),
})

/**
 * Uploaded config skill
 */
export const zPostAgentByAgentIdConfigSkillsUploadResponse = zAgentConfigSkillUploadResponse

export const zDeleteAgentByAgentIdConfigSkillsByNamePath = z.object({
  agent_id: z.uuid(),
  name: z.string(),
})

export const zDeleteAgentByAgentIdConfigSkillsByNameQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  version_id: z.string().optional(),
})

/**
 * Config skill deleted
 */
export const zDeleteAgentByAgentIdConfigSkillsByNameResponse = zAgentConfigDeleteResponse

export const zGetAgentByAgentIdConfigSkillsByNameDownloadPath = z.object({
  agent_id: z.uuid(),
  name: z.string(),
})

export const zGetAgentByAgentIdConfigSkillsByNameDownloadQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  version_id: z.string().optional(),
})

/**
 * Config skill download URL
 */
export const zGetAgentByAgentIdConfigSkillsByNameDownloadResponse = zAgentConfigDownloadResponse

export const zGetAgentByAgentIdConfigSkillsByNameFilesContentPath = z.object({
  agent_id: z.uuid(),
  name: z.string(),
})

/**
 * Success
 */
export const zGetAgentByAgentIdConfigSkillsByNameFilesContentResponse = z.record(
  z.string(),
  z.unknown(),
)

export const zGetAgentByAgentIdConfigSkillsByNameFilesDownloadPath = z.object({
  agent_id: z.uuid(),
  name: z.string(),
})

export const zGetAgentByAgentIdConfigSkillsByNameFilesDownloadQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  path: z.string(),
  version_id: z.string().optional(),
})

/**
 * Config skill file download URL
 */
export const zGetAgentByAgentIdConfigSkillsByNameFilesDownloadResponse =
  zAgentConfigDownloadResponse

export const zGetAgentByAgentIdConfigSkillsByNameFilesPreviewPath = z.object({
  agent_id: z.uuid(),
  name: z.string(),
})

export const zGetAgentByAgentIdConfigSkillsByNameFilesPreviewQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  path: z.string(),
  version_id: z.string().optional(),
})

/**
 * Config skill file preview
 */
export const zGetAgentByAgentIdConfigSkillsByNameFilesPreviewResponse =
  zAgentConfigSkillFilePreviewResponse

export const zGetAgentByAgentIdConfigSkillsByNameInspectPath = z.object({
  agent_id: z.uuid(),
  name: z.string(),
})

export const zGetAgentByAgentIdConfigSkillsByNameInspectQuery = z.object({
  draft_type: z.enum(['debug_build', 'draft']).optional(),
  version_id: z.string().optional(),
})

/**
 * Config skill inspect view
 */
export const zGetAgentByAgentIdConfigSkillsByNameInspectResponse = zAgentConfigSkillInspectResponse

export const zPostAgentByAgentIdCopyBody = zAgentAppCopyPayload

export const zPostAgentByAgentIdCopyPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent app copied successfully
 */
export const zPostAgentByAgentIdCopyResponse = zAgentAppDetailWithSite

export const zPostAgentByAgentIdDebugConversationRefreshPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent debug conversation refreshed
 */
export const zPostAgentByAgentIdDebugConversationRefreshResponse =
  zAgentDebugConversationRefreshResponse

export const zPostAgentByAgentIdFeaturesBody = zAgentAppFeaturesPayload

export const zPostAgentByAgentIdFeaturesPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Features updated successfully
 */
export const zPostAgentByAgentIdFeaturesResponse = zSimpleResultResponse

export const zPostAgentByAgentIdFeedbacksBody = zAppMessageFeedbackPayload

export const zPostAgentByAgentIdFeedbacksPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Feedback updated successfully
 */
export const zPostAgentByAgentIdFeedbacksResponse = zSimpleResultResponse

export const zGetAgentByAgentIdLogSourcesPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent log sources
 */
export const zGetAgentByAgentIdLogSourcesResponse = zAgentLogSourceListResponse

export const zGetAgentByAgentIdLogsPath = z.object({
  agent_id: z.uuid(),
})

export const zGetAgentByAgentIdLogsQuery = z.object({
  end: z.string().optional(),
  keyword: z.string().optional(),
  limit: z.int().gte(1).lte(100).optional().default(20),
  page: z.int().gte(1).optional().default(1),
  sort_by: z.string().optional().default('updated_at'),
  sort_order: z.string().optional().default('desc'),
  source: z.string().optional(),
  sources: z.array(z.string()).optional(),
  start: z.string().optional(),
  status: z.string().optional(),
  statuses: z.array(z.string()).optional(),
})

/**
 * Agent logs
 */
export const zGetAgentByAgentIdLogsResponse = zAgentLogListResponse

export const zGetAgentByAgentIdLogsByConversationIdMessagesPath = z.object({
  agent_id: z.uuid(),
  conversation_id: z.uuid(),
})

export const zGetAgentByAgentIdLogsByConversationIdMessagesQuery = z.object({
  end: z.string().optional(),
  keyword: z.string().optional(),
  limit: z.int().gte(1).lte(100).optional().default(20),
  page: z.int().gte(1).optional().default(1),
  sort_by: z.string().optional().default('updated_at'),
  sort_order: z.string().optional().default('desc'),
  source: z.string().optional(),
  sources: z.array(z.string()).optional(),
  start: z.string().optional(),
  status: z.string().optional(),
  statuses: z.array(z.string()).optional(),
})

/**
 * Agent log messages
 */
export const zGetAgentByAgentIdLogsByConversationIdMessagesResponse = zAgentLogMessageListResponse

export const zGetAgentByAgentIdMessagesByMessageIdPath = z.object({
  agent_id: z.uuid(),
  message_id: z.uuid(),
})

/**
 * Message retrieved successfully
 */
export const zGetAgentByAgentIdMessagesByMessageIdResponse = zMessageDetailResponse

export const zPostAgentByAgentIdPublishBody = zAgentPublishPayload

export const zPostAgentByAgentIdPublishPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent draft published
 */
export const zPostAgentByAgentIdPublishResponse = zAgentPublishResponse

export const zGetAgentByAgentIdReferencingWorkflowsPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Referencing workflows listed successfully
 */
export const zGetAgentByAgentIdReferencingWorkflowsResponse = zAgentReferencingWorkflowsResponse

export const zGetAgentByAgentIdSandboxPath = z.object({
  agent_id: z.uuid(),
})

export const zGetAgentByAgentIdSandboxQuery = z.object({
  caller_id: z.string().min(1),
  caller_type: z.enum(['build_draft', 'conversation']),
})

/**
 * Sandbox information returned
 */
export const zGetAgentByAgentIdSandboxResponse = zSandboxInfoResponse

export const zGetAgentByAgentIdSandboxFilesPath = z.object({
  agent_id: z.uuid(),
})

export const zGetAgentByAgentIdSandboxFilesQuery = z.object({
  caller_id: z.string().min(1),
  caller_type: z.enum(['build_draft', 'conversation']),
  path: z.string().optional().default('.'),
})

/**
 * Listing returned
 */
export const zGetAgentByAgentIdSandboxFilesResponse = zSandboxListResponse

export const zPostAgentByAgentIdSandboxFilesDownloadBody = zAgentSandboxDownloadPayload

export const zPostAgentByAgentIdSandboxFilesDownloadPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Download URL returned
 */
export const zPostAgentByAgentIdSandboxFilesDownloadResponse = zSandboxDownloadResponse

export const zGetAgentByAgentIdSandboxFilesReadPath = z.object({
  agent_id: z.uuid(),
})

export const zGetAgentByAgentIdSandboxFilesReadQuery = z.object({
  caller_id: z.string().min(1),
  caller_type: z.enum(['build_draft', 'conversation']),
  path: z.string().min(1),
})

/**
 * Preview returned
 */
export const zGetAgentByAgentIdSandboxFilesReadResponse = zSandboxReadResponse

export const zGetAgentByAgentIdStatisticsSummaryPath = z.object({
  agent_id: z.uuid(),
})

export const zGetAgentByAgentIdStatisticsSummaryQuery = z.object({
  end: z.string().optional(),
  source: z.string().optional(),
  start: z.string().optional(),
})

/**
 * Agent monitoring summary and chart data
 */
export const zGetAgentByAgentIdStatisticsSummaryResponse = zAgentStatisticSummaryEnvelopeResponse

export const zPostAgentByAgentIdTextToAudioBody = zTextToSpeechPayload

export const zPostAgentByAgentIdTextToAudioPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Generated audio bytes in the provider audio format
 */
export const zPostAgentByAgentIdTextToAudioResponse = z.custom<Blob | File>(
  (value) => value instanceof Blob || value instanceof File,
)

export const zGetAgentByAgentIdTextToAudioVoicesPath = z.object({
  agent_id: z.uuid(),
})

export const zGetAgentByAgentIdTextToAudioVoicesQuery = z.object({
  language: z.string(),
})

/**
 * TTS voices retrieved successfully
 */
export const zGetAgentByAgentIdTextToAudioVoicesResponse = zTextToSpeechVoiceListResponse

export const zGetAgentByAgentIdTracePath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent tracing settings
 */
export const zGetAgentByAgentIdTraceResponse = zAppTraceResponse

export const zPostAgentByAgentIdTraceBody = zAppTracePayload

export const zPostAgentByAgentIdTracePath = z.object({
  agent_id: z.uuid(),
})

/**
 * Updated Agent tracing settings
 */
export const zPostAgentByAgentIdTraceResponse = zAppTraceResponse

export const zGetAgentByAgentIdTraceCapabilitiesPath = z.object({
  agent_id: z.uuid(),
})

export const zGetAgentByAgentIdTraceCapabilitiesQuery = z.object({
  tracing_provider: z.string(),
})

/**
 * Provider support declarations
 */
export const zGetAgentByAgentIdTraceCapabilitiesResponse = zTraceProviderCapabilitiesResponse

export const zDeleteAgentByAgentIdTraceConfigPath = z.object({
  agent_id: z.uuid(),
})

export const zDeleteAgentByAgentIdTraceConfigQuery = z.object({
  tracing_provider: z.string(),
})

/**
 * Agent provider configuration deleted
 */
export const zDeleteAgentByAgentIdTraceConfigResponse = z.void()

export const zGetAgentByAgentIdTraceConfigPath = z.object({
  agent_id: z.uuid(),
})

export const zGetAgentByAgentIdTraceConfigQuery = z.object({
  tracing_provider: z.string(),
})

/**
 * Masked Agent provider configuration
 */
export const zGetAgentByAgentIdTraceConfigResponse = zTraceAppConfigResponse

export const zPatchAgentByAgentIdTraceConfigBody = zTraceConfigPayload

export const zPatchAgentByAgentIdTraceConfigPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent provider updated
 */
export const zPatchAgentByAgentIdTraceConfigResponse = zTraceAppConfigResponse

export const zPostAgentByAgentIdTraceConfigBody = zTraceConfigPayload

export const zPostAgentByAgentIdTraceConfigPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent provider configured
 */
export const zPostAgentByAgentIdTraceConfigResponse = zTraceAppConfigResponse

export const zGetAgentByAgentIdTraceRunsByMessageIdPath = z.object({
  agent_id: z.uuid(),
  message_id: z.uuid(),
})

export const zGetAgentByAgentIdTraceRunsByMessageIdQuery = z.object({
  node_execution_id: z.uuid().optional(),
})

/**
 * Frozen trace destination and export state
 */
export const zGetAgentByAgentIdTraceRunsByMessageIdResponse = zTraceRunStatusResponse

export const zPostAgentByAgentIdTraceRunsByMessageIdRetryBody = zTraceRunRetryPayload

export const zPostAgentByAgentIdTraceRunsByMessageIdRetryPath = z.object({
  agent_id: z.uuid(),
  message_id: z.uuid(),
})

export const zPostAgentByAgentIdTraceRunsByMessageIdRetryQuery = z.object({
  node_execution_id: z.uuid().optional(),
})

/**
 * Retry state for the same frozen destination
 */
export const zPostAgentByAgentIdTraceRunsByMessageIdRetryResponse = zTraceRunStatusResponse

export const zGetAgentByAgentIdVersionsPath = z.object({
  agent_id: z.uuid(),
})

/**
 * Agent versions
 */
export const zGetAgentByAgentIdVersionsResponse = zAgentConfigSnapshotListResponse

export const zGetAgentByAgentIdVersionsByVersionIdPath = z.object({
  agent_id: z.uuid(),
  version_id: z.uuid(),
})

/**
 * Agent version detail
 */
export const zGetAgentByAgentIdVersionsByVersionIdResponse = zAgentConfigSnapshotDetailResponse

export const zPostAgentByAgentIdVersionsByVersionIdRestorePath = z.object({
  agent_id: z.uuid(),
  version_id: z.uuid(),
})

/**
 * Agent version restored
 */
export const zPostAgentByAgentIdVersionsByVersionIdRestoreResponse =
  zAgentConfigSnapshotRestoreResponse