{"version":3,"file":"data-service-Bx6IFaSa.mjs","names":["openAI","google","deleteUser","getSharedLink","createSharedLink","updateSharedLink","userKeyQuery","revokeUserKey","revokeAllUserKeys","genTitle","updateConversation","archiveConversation","archiveAllConversations","pinConversation","deleteConversation","forkConversation","duplicateConversation","deletePreset","login","logout","register","refreshToken","requestPasswordReset","resetPassword","verifyEmail","resendVerificationEmail","cancelMCPOAuth","addPromptToGroup","revertAgentVersion","speechToText","textToSpeech","getCustomConfigSpeech","getPromptGroup","getPrompt","getRandomPrompts","updatePromptGroup","recordPromptGroupUsage","updatePromptLabels","deletePromptGroup","deletePrompt","getCategories","getAllPromptGroups","importSkill","getSkill","getRole","updatePromptPermissions","updateMemoryPermissions","updateAgentPermissions","updatePeoplePickerPermissions","updateMCPServersPermissions","updateRemoteAgentsPermissions","updateMarketplacePermissions","updateSkillPermissions","addTagToConversation","enableTwoFactor","verifyTwoFactor","confirmTwoFactor","disableTwoFactor","regenerateBackupCodes","verifyTwoFactorTemp","searchPrincipals","getAccessRoles","getResourcePermissions","updateResourcePermissions","getEffectivePermissions","getAllEffectivePermissions","endpoints.refreshToken","endpoints.apiBaseUrl","endpoints.buildLoginRedirectUrl","request","request","endpoints.insights","endpoints.insightsAccess","endpoints.conversationTraceAvailability","endpoints.conversationTraceRecords","endpoints.conversationTraceRecord","endpoints.adminLangfuseConnection","endpoints.adminLangfuseConnectionTest","endpoints.adminLangfuseSessionLink","endpoints.revokeUserKey","endpoints.revokeAllUserKeys","endpoints.deleteUser","endpoints.codeEnvironments","endpoints.codeEnvironmentStatus","endpoints.codeEnvironmentPairings","endpoints.codeEnvironmentById","endpoints.codeEnvironmentSettings","endpoints.apiBaseUrl","endpoints.pinnedOrder","endpoints.toolFavorites","endpoints.toolFavorite","endpoints.skillStates","endpoints.shareMessages","endpoints.sharedStartupConfig","endpoints.getSharedLinks","endpoints.getSharedLink","endpoints.createSharedLink","endpoints.updateSharedLink","endpoints.keys","endpoints.apiKeys","endpoints.apiKeyById","endpoints.presets","endpoints.deletePreset","endpoints.searchEnabled","endpoints.user","endpoints.userPreferences","endpoints.balance","endpoints.tokenizer","endpoints.login","endpoints.logout","endpoints.register","endpoints.userKeyQuery","endpoints.loginGoogle","endpoints.requestPasswordReset","endpoints.resetPassword","endpoints.verifyEmail","endpoints.resendVerificationEmail","endpoints.plugins","endpoints.userPlugins","endpoints.mcpReinitialize","endpoints.mcpOAuthBind","endpoints.actionOAuthBind","endpoints.mcpConnectionStatus","endpoints.mcpServerConnectionStatus","endpoints.mcpAuthValues","endpoints.cancelMCPOAuth","endpoints.mcpOAuthStatus","endpoints.config","endpoints.aiEndpoints","endpoints.tokenConfig","endpoints.models","endpoints.assistants","s.isAssistantsEndpoint","config.defaultAssistantsVersion","endpoints.agents","endpoints.files","endpoints.filePreview","endpoints.sharedFilePreview","endpoints.agentFiles","endpoints.images","endpoints.fileUsage","endpoints.revertAgentVersion","endpoints.mcpServer","endpoints.importConversation","endpoints.avatar","endpoints.sharedFileDownload","endpoints.speechToText","endpoints.textToSpeechManual","endpoints.textToSpeechVoices","endpoints.getCustomConfigSpeech","endpoints.duplicateConversation","endpoints.forkConversation","endpoints.forkSharedMessages","endpoints.deleteConversation","endpoints.deleteAllConversation","endpoints.conversations","endpoints.conversationById","endpoints.updateConversation","endpoints.archiveConversation","endpoints.archiveAllConversations","endpoints.projects","endpoints.projectById","endpoints.projectConversation","endpoints.pinConversation","endpoints.genTitle","endpoints.messages","endpoints.messagesArtifacts","endpoints.messagesBranch","endpoints.parentSubagents","endpoints.subagentThread","endpoints.subagentControl","endpoints.getPrompt","endpoints.getPromptsWithFilters","endpoints.getAllPromptGroups","endpoints.getPromptGroupsWithFilters","endpoints.getPromptGroup","endpoints.postPrompt","endpoints.addPromptToGroup","endpoints.updatePromptGroup","endpoints.recordPromptGroupUsage","endpoints.deletePrompt","endpoints.updatePromptTag","endpoints.updatePromptLabels","endpoints.deletePromptGroup","endpoints.getCategories","endpoints.getRandomPrompts","endpoints.listSkillsWithFilters","endpoints.schedules","endpoints.agentQueuedTurns","endpoints.agentQueuedTurnsByConversation","endpoints.agentQueuedTurn","endpoints.schedule","endpoints.runSchedule","endpoints.getSkill","endpoints.skills","endpoints.skillFiles","endpoints.importSkill","endpoints.skillFile","endpoints.adminSkillsSyncStatus","endpoints.adminSkillsSyncRun","endpoints.adminSkillsSyncCredential","endpoints.adminRoles","endpoints.getRole","endpoints.updatePromptPermissions","endpoints.updateAgentPermissions","endpoints.updateMemoryPermissions","endpoints.updatePeoplePickerPermissions","endpoints.updateMCPServersPermissions","endpoints.updateRemoteAgentsPermissions","endpoints.updateMarketplacePermissions","endpoints.updateSkillPermissions","endpoints.conversationTags","endpoints.addTagToConversation","endpoints.health","endpoints.userTerms","endpoints.acceptUserTerms","endpoints.banner","endpoints.feedback","endpoints.enableTwoFactor","endpoints.verifyTwoFactor","endpoints.confirmTwoFactor","endpoints.disableTwoFactor","endpoints.regenerateBackupCodes","endpoints.verifyTwoFactorTemp","endpoints.memories","endpoints.memory","endpoints.memoryById","endpoints.memoryPreferences","endpoints.searchPrincipals","endpoints.getAccessRoles","endpoints.getResourcePermissions","endpoints.updateResourcePermissions","endpoints.getEffectivePermissions","endpoints.getAllEffectivePermissions","endpoints.graphToken","endpoints.activeJobs"],"sources":["../src/utils.ts","../src/filters.ts","../src/code/workspace.ts","../src/feedback.ts","../src/code/approval.ts","../src/stateful-code.ts","../src/types/assistants.ts","../src/schemas.ts","../src/generate.ts","../src/limits.ts","../src/models.ts","../src/balance.ts","../src/file-config.ts","../src/api-endpoints.ts","../src/types/files.ts","../src/types/agents.ts","../src/mcp.ts","../src/config.ts","../src/accessPermissions.ts","../src/keys.ts","../src/headers-helpers.ts","../src/request.ts","../src/upload.ts","../src/data-service.ts"],"sourcesContent":["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 { RE2JS } from 're2js';\n\nexport const FILTER_PII_STARTER_PATTERNS = [\n  'sk_prefix',\n  'bearer_header',\n  'api_key_header',\n] as const;\n\nexport const MAX_PII_PATTERNS_PER_SOURCE = 256;\nexport const MAX_PII_PATTERN_LENGTH = 512;\nexport const MAX_PII_PATTERN_ID_LENGTH = 256;\nexport const MAX_PII_PATTERN_LABEL_LENGTH = 512;\nexport const MAX_PII_CUSTOM_REGEX_CHARACTERS = 8_192;\nexport const MAX_PII_CUSTOM_REGEX_INSTRUCTIONS = 8_192;\nexport const MAX_PII_CUSTOM_PATTERNS_TOTAL = 256;\n\nconst MAX_PII_REGEX_SIZE_CACHE_ENTRIES = 512;\nconst PII_REGEX_PROGRAM_SIZE_CACHE = new Map<string, number | null>();\n\nexport function getPiiRegexProgramSize(pattern: string): number | null {\n  if (PII_REGEX_PROGRAM_SIZE_CACHE.has(pattern)) {\n    return PII_REGEX_PROGRAM_SIZE_CACHE.get(pattern) ?? null;\n  }\n  let programSize: number | null = null;\n  let compiled: RE2JS | undefined;\n  try {\n    compiled = RE2JS.compile(pattern);\n    const candidate = compiled.programSize();\n    if (Number.isSafeInteger(candidate) && candidate > 0) {\n      programSize = candidate;\n    }\n  } catch {\n    programSize = null;\n  } finally {\n    compiled?.reset();\n  }\n  if (PII_REGEX_PROGRAM_SIZE_CACHE.size >= MAX_PII_REGEX_SIZE_CACHE_ENTRIES) {\n    PII_REGEX_PROGRAM_SIZE_CACHE.clear();\n  }\n  PII_REGEX_PROGRAM_SIZE_CACHE.set(pattern, programSize);\n  return programSize;\n}\n\nexport const MESSAGE_FILTER_FIELDS = [\n  'name',\n  'text',\n  'summary',\n  'quote',\n  'answer',\n  'decision_response',\n  'decision_reason',\n  'content_part',\n  'attachment_reference',\n  'assembled_context',\n] as const;\n\nexport const HITL_MESSAGE_FILTER_FIELDS = [\n  'answer',\n  'decision_response',\n  'decision_reason',\n] as const;\n\nconst REQUEST_ONLY_MESSAGE_FILTER_FIELDS = new Set<string>(HITL_MESSAGE_FILTER_FIELDS);\n\n/** Message fields structurally recoverable without exact semantic provenance. */\nexport const STORED_MESSAGE_FILTER_FIELDS = MESSAGE_FILTER_FIELDS.filter(\n  (field) => !REQUEST_ONLY_MESSAGE_FILTER_FIELDS.has(field),\n);\n\nexport const PROMPT_FILTER_FIELDS = [\n  'name',\n  'description',\n  'oneliner',\n  'category',\n  'command',\n  'text',\n  'preset_text',\n  'system',\n  'context',\n  'instructions',\n  'additional_instructions',\n  'greeting',\n  'example_input',\n  'example_output',\n] as const;\n\nexport const AGENT_INSTRUCTION_FILTER_FIELDS = [\n  'name',\n  'category',\n  'description',\n  'instructions',\n  'additional_instructions',\n  'edge_description',\n  'edge_prompt',\n  'edge_prompt_key',\n  'artifacts',\n  'support_contact_name',\n  'support_contact_email',\n] as const;\n\nexport const CONVERSATION_STARTER_FILTER_FIELDS = ['text'] as const;\nexport const CONVERSATION_TITLE_FILTER_FIELDS = ['title'] as const;\nexport const FEEDBACK_FILTER_FIELDS = ['text'] as const;\n\nexport const SKILL_FILTER_FIELDS = [\n  'name',\n  'display_title',\n  'description',\n  'category',\n  'frontmatter',\n  'instructions',\n  'imported_text',\n  'file_name',\n  'file_text',\n] as const;\n\nexport const MEMORY_FILTER_FIELDS = ['key', 'value', 'summary'] as const;\n\nexport const FILE_FILTER_FIELDS = [\n  'name',\n  'content',\n  'extracted_text',\n  'transcript',\n  'uri',\n] as const;\n\nexport const TOOL_ARGUMENT_FILTER_FIELDS = ['name', 'arguments', 'output'] as const;\n\nexport const MODEL_PARAMETER_FILTER_FIELDS = [\n  'stop',\n  'request_fields',\n  'response_format',\n  'metadata',\n] as const;\n\nexport const ACTION_METADATA_FILTER_FIELDS = [\n  'raw_spec',\n  'domain',\n  'privacy_policy_url',\n  'authorization_type',\n  'custom_auth_header',\n  'authorization_content_type',\n  'authorization_url',\n  'client_url',\n  'scope',\n  'token_exchange_method',\n  'api_key',\n  'oauth_client_id',\n  'oauth_client_secret',\n] as const;\n\nexport const messageFilterFieldSchema = z.enum(MESSAGE_FILTER_FIELDS);\nexport const promptFilterFieldSchema = z.enum(PROMPT_FILTER_FIELDS);\nexport const agentInstructionFilterFieldSchema = z.enum(AGENT_INSTRUCTION_FILTER_FIELDS);\nexport const conversationStarterFilterFieldSchema = z.enum(CONVERSATION_STARTER_FILTER_FIELDS);\nexport const conversationTitleFilterFieldSchema = z.enum(CONVERSATION_TITLE_FILTER_FIELDS);\nexport const feedbackFilterFieldSchema = z.enum(FEEDBACK_FILTER_FIELDS);\nexport const skillFilterFieldSchema = z.enum(SKILL_FILTER_FIELDS);\nexport const memoryFilterFieldSchema = z.enum(MEMORY_FILTER_FIELDS);\nexport const fileFilterFieldSchema = z.enum(FILE_FILTER_FIELDS);\nexport const toolArgumentFilterFieldSchema = z.enum(TOOL_ARGUMENT_FILTER_FIELDS);\nexport const modelParameterFilterFieldSchema = z.enum(MODEL_PARAMETER_FILTER_FIELDS);\nexport const filterPiiStarterPatternSchema = z.enum(FILTER_PII_STARTER_PATTERNS);\nexport const filterPiiActionSchema = z.enum(['block', 'audit']);\nexport const actionMetadataFilterFieldSchema = z.enum(ACTION_METADATA_FILTER_FIELDS);\nexport const unattributedAssistantContentSchema = z.enum(['model_output', 'inspect']);\nexport type UnattributedAssistantContent = z.infer<typeof unattributedAssistantContentSchema>;\n\nexport type MessageFilterField = z.infer<typeof messageFilterFieldSchema>;\nexport type PromptFilterField = z.infer<typeof promptFilterFieldSchema>;\nexport type AgentInstructionFilterField = z.infer<typeof agentInstructionFilterFieldSchema>;\nexport type ConversationStarterFilterField = z.infer<typeof conversationStarterFilterFieldSchema>;\nexport type ConversationTitleFilterField = z.infer<typeof conversationTitleFilterFieldSchema>;\nexport type FeedbackFilterField = z.infer<typeof feedbackFilterFieldSchema>;\nexport type SkillFilterField = z.infer<typeof skillFilterFieldSchema>;\nexport type MemoryFilterField = z.infer<typeof memoryFilterFieldSchema>;\nexport type FileFilterField = z.infer<typeof fileFilterFieldSchema>;\nexport type ToolArgumentFilterField = z.infer<typeof toolArgumentFilterFieldSchema>;\nexport type ModelParameterFilterField = z.infer<typeof modelParameterFilterFieldSchema>;\nexport type ActionMetadataFilterField = z.infer<typeof actionMetadataFilterFieldSchema>;\nexport type FilterPiiAction = z.infer<typeof filterPiiActionSchema>;\n\nexport const userSubmittedMessageFieldPathSchema = z\n  .object({\n    path: z.string().startsWith('/').max(2048),\n    field: z.enum(HITL_MESSAGE_FILTER_FIELDS),\n  })\n  .strict();\n\nexport type UserSubmittedMessageFieldPath = z.infer<typeof userSubmittedMessageFieldPathSchema>;\n\ntype PiiPatternSelection = {\n  readonly starterPatterns?: readonly unknown[];\n  readonly customPatterns?: readonly unknown[];\n};\n\ntype PiiFieldSelection = PiiPatternSelection & {\n  readonly fields?: readonly string[];\n};\n\nconst UNINSPECTABLE_FILE_FIELDS = new Set<FileFilterField>([\n  'content',\n  'extracted_text',\n  'transcript',\n]);\n\n/**\n * An omitted starter selection enables the built-in catalog. An explicit\n * empty selection disables it, so a source is active only when custom rules\n * remain. This mirrors the documented filter semantics without compiling\n * regular expressions.\n */\nexport function hasActivePiiPatterns(config: PiiPatternSelection | null | undefined): boolean {\n  return (\n    config != null &&\n    (config.starterPatterns == null ||\n      config.starterPatterns.length > 0 ||\n      (config.customPatterns?.length ?? 0) > 0)\n  );\n}\n\n/** Returns whether an active PII rule can inspect at least one candidate field. */\nexport function hasActivePiiFields(\n  config: PiiFieldSelection | null | undefined,\n  candidates: readonly string[],\n): boolean {\n  return (\n    hasActivePiiPatterns(config) &&\n    (config?.fields == null || candidates.some((field) => config.fields?.includes(field)))\n  );\n}\n\n/**\n * Returns whether a parsed source-aware config can enforce any rule. An\n * explicit fail-close file policy remains active even without text patterns.\n */\nexport function hasActiveFiltersConfig(filters: FiltersConfig | null | undefined): boolean {\n  if (filters == null) {\n    return false;\n  }\n  if (filters.messages?.unattributedAssistantContent === 'inspect') {\n    return true;\n  }\n  const sourcePatterns = [\n    filters.messages?.pii,\n    filters.prompts?.pii,\n    filters.agentInstructions?.pii,\n    filters.conversationStarters?.pii,\n    filters.conversationTitles?.pii,\n    filters.feedback?.pii,\n    filters.skills?.pii,\n    filters.memories?.pii,\n    filters.files?.pii,\n    filters.toolArguments?.pii,\n    filters.modelParameters?.pii,\n    filters.actionMetadata?.pii,\n  ];\n  if (sourcePatterns.some(hasActivePiiPatterns)) {\n    return true;\n  }\n  const filePii = filters.files?.pii;\n  return (\n    filePii?.uninspectable === 'block' &&\n    (filePii.fields == null || filePii.fields.some((field) => UNINSPECTABLE_FILE_FIELDS.has(field)))\n  );\n}\n\nexport const filterPiiRegexSchema = z\n  .string()\n  .min(1)\n  .max(MAX_PII_PATTERN_LENGTH)\n  .refine((value) => getPiiRegexProgramSize(value) != null, {\n    message: 'Regex must use supported linear-time syntax',\n  });\n\nexport const filterPiiCustomPatternSchema = z\n  .object({\n    id: z.string().min(1).max(MAX_PII_PATTERN_ID_LENGTH),\n    label: z.string().min(1).max(MAX_PII_PATTERN_LABEL_LENGTH),\n    regex: filterPiiRegexSchema,\n  })\n  .strict();\n\nexport type FilterPiiCustomPatternConfig = z.infer<typeof filterPiiCustomPatternSchema>;\n\nfunction createPiiFilterSchema<Field extends z.ZodTypeAny>(fieldSchema: Field) {\n  return z\n    .object({\n      action: filterPiiActionSchema.optional(),\n      fields: z.array(fieldSchema).min(1).max(MAX_PII_PATTERNS_PER_SOURCE).optional(),\n      starterPatterns: z\n        .array(filterPiiStarterPatternSchema)\n        .max(MAX_PII_PATTERNS_PER_SOURCE)\n        .optional(),\n      customPatterns: z\n        .array(filterPiiCustomPatternSchema)\n        .max(MAX_PII_PATTERNS_PER_SOURCE)\n        .optional(),\n    })\n    .strict();\n}\n\nfunction createSourceFilterSchema<Field extends z.ZodTypeAny>(fieldSchema: Field) {\n  return z\n    .object({\n      pii: createPiiFilterSchema(fieldSchema).optional(),\n    })\n    .strict();\n}\n\nconst messageSourceFilterSchema = z\n  .object({\n    pii: createPiiFilterSchema(messageFilterFieldSchema).optional(),\n    unattributedAssistantContent: unattributedAssistantContentSchema.optional(),\n  })\n  .strict();\n\nconst fileSourceFilterSchema = z\n  .object({\n    pii: createPiiFilterSchema(fileFilterFieldSchema)\n      .extend({\n        uninspectable: z.enum(['allow', 'block']).optional(),\n      })\n      .optional(),\n  })\n  .strict();\n\nexport const filtersConfigSchema = z\n  .object({\n    messages: messageSourceFilterSchema.optional(),\n    prompts: createSourceFilterSchema(promptFilterFieldSchema).optional(),\n    agentInstructions: createSourceFilterSchema(agentInstructionFilterFieldSchema).optional(),\n    conversationStarters: createSourceFilterSchema(conversationStarterFilterFieldSchema).optional(),\n    conversationTitles: createSourceFilterSchema(conversationTitleFilterFieldSchema).optional(),\n    feedback: createSourceFilterSchema(feedbackFilterFieldSchema).optional(),\n    skills: createSourceFilterSchema(skillFilterFieldSchema).optional(),\n    memories: createSourceFilterSchema(memoryFilterFieldSchema).optional(),\n    files: fileSourceFilterSchema.optional(),\n    toolArguments: createSourceFilterSchema(toolArgumentFilterFieldSchema).optional(),\n    modelParameters: createSourceFilterSchema(modelParameterFilterFieldSchema).optional(),\n    actionMetadata: createSourceFilterSchema(actionMetadataFilterFieldSchema).optional(),\n  })\n  .strict()\n  .superRefine((filters, context) => {\n    let customPatterns = 0;\n    let regexCharacters = 0;\n    let regexInstructions = 0;\n    for (const source of Object.values(filters)) {\n      for (const pattern of source?.pii?.customPatterns ?? []) {\n        customPatterns++;\n        regexCharacters += pattern.regex.length;\n        regexInstructions += getPiiRegexProgramSize(pattern.regex) ?? 0;\n      }\n    }\n    if (customPatterns > MAX_PII_CUSTOM_PATTERNS_TOTAL) {\n      context.addIssue({\n        code: z.ZodIssueCode.custom,\n        message: `At most ${MAX_PII_CUSTOM_PATTERNS_TOTAL} custom PII patterns may be configured in total`,\n      });\n    }\n    if (regexCharacters > MAX_PII_CUSTOM_REGEX_CHARACTERS) {\n      context.addIssue({\n        code: z.ZodIssueCode.custom,\n        message: `Custom PII regexes may contain at most ${MAX_PII_CUSTOM_REGEX_CHARACTERS} characters in total`,\n      });\n    }\n    if (regexInstructions > MAX_PII_CUSTOM_REGEX_INSTRUCTIONS) {\n      context.addIssue({\n        code: z.ZodIssueCode.custom,\n        message: `Custom PII regexes may compile to at most ${MAX_PII_CUSTOM_REGEX_INSTRUCTIONS} instructions in total`,\n      });\n    }\n  });\n\nexport type FiltersConfig = z.infer<typeof filtersConfigSchema>;\n","export const CODE_WORKSPACE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;\n/** Protocol-v1 ceiling enforced by the worker and Code API. */\nexport const CODE_WORKSPACE_MAX_COUNT = 32;\n/** API/client protocol for immutable conversation-owned environment decisions. */\nexport const CODE_ENVIRONMENT_DECISION_VERSION = 1 as const;\nexport const CODE_WORKSPACE_OPERATIONS = [\n  'read_file',\n  'search_text',\n  'list_files',\n  'write_file',\n  'preview_edit',\n  'edit_file',\n  'execute_command',\n] as const;\nexport const CODE_WORKSPACE_SELECTION_ERROR_REASONS = [\n  'required',\n  'invalid',\n  'worker_unavailable',\n  'unsupported',\n  'missing',\n  'locked',\n] as const;\nexport const CODE_ENVIRONMENT_MODES = ['attached', 'without_attached'] as const;\n\nexport type CodeWorkspaceOperation = (typeof CODE_WORKSPACE_OPERATIONS)[number];\nexport type CodeWorkspaceSelectionErrorReason =\n  (typeof CODE_WORKSPACE_SELECTION_ERROR_REASONS)[number];\nexport type CodeEnvironmentMode = (typeof CODE_ENVIRONMENT_MODES)[number];\n\n/** Public, path-free description of one root registered by an attached worker. */\nexport interface CodeWorkspaceDescriptor {\n  id: string;\n  name?: string;\n  /** Omitted when every worker-level operation applies to this workspace. */\n  operations?: CodeWorkspaceOperation[];\n}\n\n/** Conversation-owned selection, bound to the environment that advertised it. */\nexport interface CodeWorkspaceSelection {\n  environmentId: string;\n  workspaceId: string;\n}\n\nexport function isCodeEnvironmentMode(value: unknown): value is CodeEnvironmentMode {\n  return CODE_ENVIRONMENT_MODES.some((mode) => mode === value);\n}\n\nexport function isCodeWorkspaceSelectionErrorReason(\n  value: unknown,\n): value is CodeWorkspaceSelectionErrorReason {\n  return CODE_WORKSPACE_SELECTION_ERROR_REASONS.some((reason) => reason === value);\n}\n\nexport function isCodeWorkspaceSelection(value: unknown): value is CodeWorkspaceSelection {\n  if (value == null || typeof value !== 'object' || Array.isArray(value)) {\n    return false;\n  }\n  const selection = value as Record<string, unknown>;\n  return (\n    Object.keys(selection).every((key) => key === 'environmentId' || key === 'workspaceId') &&\n    typeof selection.environmentId === 'string' &&\n    CODE_WORKSPACE_ID_PATTERN.test(selection.environmentId) &&\n    typeof selection.workspaceId === 'string' &&\n    CODE_WORKSPACE_ID_PATTERN.test(selection.workspaceId)\n  );\n}\n\n/** One exact workspace per attached environment used by a conversation. */\nexport function isCodeWorkspaceSelections(value: unknown): value is CodeWorkspaceSelection[] {\n  if (!Array.isArray(value)) return false;\n  const environmentIds = new Set<string>();\n  return value.every((selection) => {\n    if (!isCodeWorkspaceSelection(selection) || environmentIds.has(selection.environmentId)) {\n      return false;\n    }\n    environmentIds.add(selection.environmentId);\n    return true;\n  });\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\n  .object({\n    rating: feedbackRatingSchema,\n    tag: feedbackTagKeySchema,\n    text: z.string().max(1024).optional(),\n  })\n  .refine(\n    ({ rating, tag }) =>\n      FEEDBACK_TAGS.some(\n        (feedbackTag) => feedbackTag.key === tag && feedbackTag.direction === rating,\n      ),\n    {\n      message: 'Feedback tag does not match rating',\n      path: ['tag'],\n    },\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 type {\n  CodeEnvironmentPermissionDecision,\n  CodeEnvironmentUserConfigSchema,\n  CodeEnvironmentUserSettings,\n} from '../config';\n\nexport const CODE_APPROVAL_MODES = ['ask', 'acceptEdits', 'fullAccess'] as const;\nexport type CodeApprovalMode = (typeof CODE_APPROVAL_MODES)[number];\n\ntype CodePermissions = Required<NonNullable<CodeEnvironmentUserSettings['permissions']>>;\n\nconst MODE_PERMISSIONS: Record<CodeApprovalMode, CodePermissions> = {\n  ask: { fileWrite: 'ask', commandExecution: 'ask' },\n  acceptEdits: { fileWrite: 'allow', commandExecution: 'ask' },\n  fullAccess: { fileWrite: 'allow', commandExecution: 'allow' },\n};\n\nexport type CodeApprovalConstraints = {\n  environment: 'attached' | 'managed';\n  enabled?: boolean;\n  allowedModes?: readonly CodeApprovalMode[];\n  configSchema?: CodeEnvironmentUserConfigSchema;\n  settings?: CodeEnvironmentUserSettings;\n};\n\n/** Omitted deployment configuration never grants unattended execution. */\nexport function getAllowedCodeApprovalModes({\n  enabled,\n  allowedModes,\n  configSchema,\n  settings,\n  environment,\n}: CodeApprovalConstraints): CodeApprovalMode[] {\n  if (enabled === false) return [];\n  const permitted = new Set(allowedModes ?? ['ask']);\n  return CODE_APPROVAL_MODES.filter((mode) => {\n    if (!permitted.has(mode)) return false;\n    if (environment === 'managed') return true;\n    for (const category of ['fileWrite', 'commandExecution'] as const) {\n      if (MODE_PERMISSIONS[mode][category] !== 'allow') continue;\n      const field = configSchema?.permissions?.[category];\n      const configured = settings?.permissions?.[category];\n      const effective =\n        configured != null && field?.allowed.includes(configured) === true\n          ? configured\n          : (field?.default ?? 'ask');\n      if (effective === 'deny' || field?.allowed.includes('allow') !== true) return false;\n    }\n    return true;\n  });\n}\n\nexport class CodeApprovalModeError extends Error {\n  readonly code = 'CODE_APPROVAL_MODE_NOT_ALLOWED';\n\n  constructor() {\n    super('The selected code approval mode is not permitted by the current policy.');\n    this.name = 'CodeApprovalModeError';\n  }\n}\n\n/** Validate untrusted request state again at admission, including after policy changes. */\nexport function resolveCodeApprovalMode(\n  requested: unknown,\n  constraints: CodeApprovalConstraints,\n): CodeApprovalMode | undefined {\n  if (requested == null) return undefined;\n  const allowed = getAllowedCodeApprovalModes(constraints);\n  const selected = allowed.find((mode) => mode === requested);\n  if (selected == null) throw new CodeApprovalModeError();\n  return selected;\n}\n\n/** Apply a turn preference without modifying machine settings or overriding an existing deny. */\nexport function resolveCodePermissionDecision({\n  mode,\n  category,\n  decision,\n}: {\n  mode?: CodeApprovalMode;\n  category: keyof CodePermissions;\n  decision: CodeEnvironmentPermissionDecision;\n}): CodeEnvironmentPermissionDecision {\n  if (mode == null || decision === 'deny') return decision;\n  if (MODE_PERMISSIONS[mode] == null) throw new CodeApprovalModeError();\n  return MODE_PERMISSIONS[mode][category];\n}\n","export const STATEFUL_CODE_ENVIRONMENTS = ['user', 'agent-user', 'conversation'] as const;\nexport type StatefulCodeEnvironment = (typeof STATEFUL_CODE_ENVIRONMENTS)[number];\n\n/** Resolve a deployment allowlist in stable UI order. An omitted value preserves\n * the backward-compatible behavior where every environment is available. */\nexport function resolveAllowedStatefulCodeEnvironments(\n  configured?: readonly StatefulCodeEnvironment[] | null,\n): StatefulCodeEnvironment[] {\n  if (configured == null) {\n    return [...STATEFUL_CODE_ENVIRONMENTS];\n  }\n\n  const configuredSet = new Set(configured);\n  return STATEFUL_CODE_ENVIRONMENTS.filter((environment) => configuredSet.has(environment));\n}\n\n/** Keep an allowed preference, otherwise select the first deployment-allowed scope. */\nexport function resolveStatefulCodeEnvironment(\n  preferred: StatefulCodeEnvironment | null | undefined,\n  configured?: readonly StatefulCodeEnvironment[] | null,\n): StatefulCodeEnvironment | undefined {\n  const allowed = resolveAllowedStatefulCodeEnvironments(configured);\n  return preferred != null && allowed.includes(preferred) ? preferred : allowed[0];\n}\n","import { z } from 'zod';\nimport type { OpenAPIV3 } from 'openapi-types';\nimport type { AssistantsEndpoint, AgentProvider, MemoryScope, SkillsScope } from 'src/schemas';\nimport type { StatefulCodeEnvironment } from '../stateful-code';\nimport type { ContentTypes, SubagentIdentity } from './runs';\nimport type { Agents, GraphEdge } from './agents';\nimport type { TFile } from './files';\nimport { ArtifactModes } from 'src/artifacts';\nexport {\n  STATEFUL_CODE_ENVIRONMENTS,\n  resolveStatefulCodeEnvironment,\n  resolveAllowedStatefulCodeEnvironments,\n} from '../stateful-code';\nexport type { StatefulCodeEnvironment } from '../stateful-code';\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  skill = 'skill',\n  read_file = 'read_file',\n  bash_tool = 'bash_tool',\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\nexport type AgentOwnerContact = {\n  name?: 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   * If true (and the `run_in_background` capability is enabled), the tool's\n   * schema gains a `run_in_background` boolean so the model can dispatch the\n   * call detached and poll its result via `check_background_task`.\n   * @default false\n   */\n  run_in_background?: boolean;\n  /**\n   * If true (and the `tool_intents` capability is enabled), the tool's schema\n   * gains an `intent` string as its FIRST property — one model-authored\n   * sentence per call, rendered as the call's live status label. Native host\n   * tools default on while the capability is enabled; `false` opts one out.\n   * @default false\n   */\n  describe_intent?: boolean;\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\n/**\n * Configuration for spawning subagents (isolated-context child agents) from an agent.\n * When `enabled` is true, the agent gets a subagent-spawn tool that can delegate work\n * to itself, listed single-agent targets, and/or explicit saved-agent teams.\n */\nexport type AgentSubagentGraphEdge = Omit<\n  GraphEdge,\n  'edgeType' | 'condition' | 'prompt' | 'promptKey'\n> & {\n  edgeType: 'direct';\n  condition?: never;\n  prompt?: string;\n  promptKey?: never;\n};\n\n/** A bounded saved-agent team that can be spawned as one isolated child graph. */\nexport type AgentSubagentGraph = {\n  /** Stable spawn-tool enum value for the team. */\n  type: string;\n  name: string;\n  description: string;\n  /** Member IDs. In create/update payloads, an empty ID refers to the current agent. */\n  agent_ids: string[];\n  edges: AgentSubagentGraphEdge[];\n  /** Entry member ID. In create/update payloads, an empty ID refers to the current agent. */\n  entry_agent_id: string;\n  /** Result member ID. In create/update payloads, an empty ID refers to the current agent. */\n  result_agent_id: string;\n};\n\nexport type AgentSubagentsConfig = {\n  enabled?: boolean;\n  /** When true (default), the agent may spawn itself in an isolated context. */\n  allowSelf?: boolean;\n  /** Share current-turn files with authorized descendants. Off unless explicitly enabled. */\n  shareFiles?: boolean;\n  /** Specific agents that may be spawned as subagents. */\n  agent_ids?: string[];\n  /** Explicit saved-agent teams that may be spawned as bounded child graphs. */\n  graphs?: AgentSubagentGraph[];\n};\n\nexport type AgentGitIdentity = {\n  /** Commit author and committer display name. */\n  name: string;\n  /** Commit author and committer email address. */\n  email: string;\n};\n\nexport const agentGitIdentitySchema: z.ZodType<AgentGitIdentity | undefined> = z\n  .object({\n    name: z\n      .string()\n      .trim()\n      .min(1)\n      .max(128)\n      .refine((value) => !/[\\0\\r\\n]/.test(value)),\n    email: z\n      .string()\n      .trim()\n      .email()\n      .max(254)\n      .refine((value) => !/[\\0\\r\\n]/.test(value)),\n  })\n  .optional();\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  /** Per-agent opt-in for stateful code sessions (requires the app-level capability). */\n  stateful_code_sessions?: boolean;\n  /** Stateful workspace sharing scope. Defaults to one workspace per user. */\n  stateful_code_environment?: StatefulCodeEnvironment;\n  /** Operator-configured managed or attached stateful execution environment. */\n  code_environment_id?: string | null;\n  /** Default attached workspace for new chats; empty means no agent default. */\n  code_workspace_id?: string;\n  /** Non-secret Git authorship injected into this agent's sandboxed commands. */\n  git_identity?: AgentGitIdentity | null;\n  artifacts?: ArtifactModes;\n  recursion_limit?: number;\n  isPublic?: boolean;\n  /**\n   * Whether the requesting user holds EDIT on this agent, so a single VIEW-scoped fetch can\n   * serve consumers that only need the editable subset instead of issuing a second full\n   * paginated walk under an EDIT-scoped cache key.\n   *\n   * Set by the list endpoint only; single-agent responses omit it. Treat absence as unknown\n   * and fail open (`isEditable !== false`), never as `false`, since a client on an older\n   * server would otherwise see an empty list rather than too many rows.\n   *\n   * Reflects the caller's ACL grant. The `MANAGE_AGENTS` capability bypasses ACL on write,\n   * so a capability holder can edit agents this flag reports as not editable.\n   */\n  isEditable?: boolean;\n  version?: number;\n  category?: string;\n  support_contact?: SupportContact;\n  owner_contact?: AgentOwnerContact;\n  /** Per-tool configuration options (deferred loading, allowed callers, etc.) */\n  tool_options?: AgentToolOptions;\n  /** Attached action registrations, each `${encodedDomain}${actionDelimiter}${action_id}` */\n  actions?: string[];\n  /** Optional allowlist of skill ObjectIds. Only applies when `skills_enabled`. */\n  skills?: string[];\n  /** Master toggle for skill use on this agent. `true` = active (full catalog unless\n   *  `skills` narrows it). `false`/undefined = inactive (no skills available). */\n  skills_enabled?: boolean;\n  /** Enables runtime skill creation without exposing an existing skill catalog. */\n  skill_authoring_enabled?: boolean;\n  /** Explicit catalog exposure while skills are enabled. Missing preserves legacy semantics. */\n  skills_scope?: SkillsScope;\n  /** Subagent spawning configuration — isolated-context child agents. */\n  subagents?: AgentSubagentsConfig;\n  /** Memory partition: `agent` isolates memories per (user, agent); default shared pool */\n  memory_scope?: MemoryScope;\n};\n\nexport type TAgentsMap = Record<string, Agent | undefined>;\n\nexport type AgentCreateParams = {\n  git_identity?: AgentGitIdentity;\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  | 'stateful_code_sessions'\n  | 'stateful_code_environment'\n  | 'code_environment_id'\n  | 'code_workspace_id'\n  | 'artifacts'\n  | 'recursion_limit'\n  | 'category'\n  | 'support_contact'\n  | 'tool_options'\n  | 'skills'\n  | 'skills_enabled'\n  | 'skill_authoring_enabled'\n  | 'skills_scope'\n  | 'subagents'\n  | 'memory_scope'\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  | 'stateful_code_sessions'\n  | 'stateful_code_environment'\n  | 'code_environment_id'\n  | 'git_identity'\n  | 'code_workspace_id'\n  | 'artifacts'\n  | 'recursion_limit'\n  | 'category'\n  | 'support_contact'\n  | 'tool_options'\n  | 'skills'\n  | 'skills_enabled'\n  | 'skill_authoring_enabled'\n  | 'skills_scope'\n  | 'subagents'\n  | 'memory_scope'\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  /** Host-resolved execution identity for a saved subagent invocation. */\n  subagentIdentity?: SubagentIdentity;\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   * Terminal lifecycle status of the run step that produced this part, from\n   * `on_run_step_closed`. Distinct from `status`, which is already claimed by\n   * activity-label and question-form parts. Absent on parts predating the\n   * event or from endpoints that do not emit it, in which case renderers fall\n   * back to inferring \"stopped\" from `progress` and `isSubmitting`.\n   */\n  runStepStatus?: Agents.RunStepClosedStatus;\n  /**\n   * Wall-clock milliseconds the run step took, derived from the same\n   * `on_run_step_closed` event as {@link runStepStatus} via\n   * `getRunStepDurationMs`. Only written when the event carried both\n   * timestamps and they agree in order — so its absence means \"not\n   * derivable\", never \"instant\". The raw value is persisted unfiltered;\n   * whether it is worth showing (`isReportableRunStepDuration`) is decided\n   * at render time.\n   */\n  runStepDurationMs?: number;\n  /**\n   * Stamped by the background harvester when a detached task's final output\n   * replaces the dispatch handle in `tool_call.output`. The handle JSON and\n   * the live status-marker attachment are both transient, so after the patch\n   * (or a reload) this is the only signal that the call ran in the\n   * background — renderers use it to keep treating {@link runStepDurationMs}\n   * as dispatch time rather than the task's runtime.\n   */\n  backgrounded?: boolean;\n  /**\n   * Content index this part occupied while its run streamed. The aggregator\n   * writes parts at provider-source indexes, so the streamed array is sparse;\n   * persistence compacts it and every part after a hole shifts down. The\n   * client's final handler stamps the streamed position onto the compacted\n   * parts it adopts, so index-derived render identity survives the swap\n   * instead of remounting the settled message. Client-only and absent\n   * everywhere else — persisted content never carries it.\n   */\n  streamedIndex?: number;\n};\n\n/** Metadata for parallel content rendering - subset of PartMetadata */\nexport type ContentMetadata = Pick<PartMetadata, 'agentId' | 'groupId' | 'streamedIndex'>;\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  /** A summarize round that ended in error. Partial deltas already streamed\n   *  into this slot are kept, so the renderer needs this to avoid presenting\n   *  truncated text under the \"Conversation summarized\" label. */\n  failed?: boolean;\n  /** Set when the user compacted the context manually rather than the\n   *  automatic detour firing on context pressure. */\n  initiatedBy?: 'user';\n  summaryVersion?: number;\n  model?: string;\n  provider?: string;\n  createdAt?: string;\n  boundary?: {\n    messageId: string;\n    contentIndex: number;\n  };\n};\n\n/**\n * A user steering message injected mid-run at a tool-batch boundary.\n * Persisted inline in the response message's content array (keyed by the\n * type name like `text`/`think` so token counting reads it for free);\n * replayed as a user message on subsequent turns by `formatAgentMessages`.\n */\nexport type SteerContentPart = {\n  type: ContentTypes.STEER;\n  steer: string;\n  steerId?: string;\n  /** Stable optimistic-client id used to settle a POST whose response was lost. */\n  clientSteerId?: string;\n  createdAt?: number;\n  /** Attachments steered with the message; re-encoded per turn on replay\n   *  like any other user-message media (refs only, never encoded data). */\n  files?: Partial<TFile>[];\n  /** Quoted excerpts steered with the message, persisted separately from the\n   *  typed text (mirroring `TMessage.quotes`) so the UI renders them as\n   *  reference blocks; merged into the model-bound user turn on every replay. */\n  quotes?: string[];\n};\n\nexport type TMessageContentParts =\n  | ({\n      type: ContentTypes.ERROR;\n      text?: string | TextData;\n      error?: string;\n    } & ContentMetadata)\n  | ({\n      type: ContentTypes.THINK;\n      think?: string | TextData;\n      /** Generated orientation for this user-visible reasoning step. */\n      reasoning_label?: string;\n      /** Stable SDK run-step identity used to correlate live revisions. */\n      reasoning_label_step_id?: string;\n      /** Durable provider-call count used to enforce the per-run cost cap across resumes. */\n      reasoning_label_attempts?: number;\n      /** Visible reasoning length included in this step's latest provider call. */\n      reasoning_label_submitted_chars?: number;\n      /** Monotonic provider-call revision; gaps are allowed after unsuccessful attempts. */\n      reasoning_label_revision?: number;\n      /** Whether the reasoning step can still produce a newer label. */\n      reasoning_label_status?: 'streaming' | 'complete';\n      /** The reasoning happened but its text is not available to this view\n       *  (e.g. detached subagent projections retain only a marker). */\n      reasoning_unavailable?: boolean;\n    } & ContentMetadata)\n  | (SteerContentPart & ContentMetadata)\n  | ({\n      type: ContentTypes.TEXT;\n      text?: string | TextData;\n      tool_call_ids?: string[];\n      /** Open Responses semantic channel for assistant text. */\n      phase?: 'commentary' | 'final_answer';\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  | ({\n      /** One-line LLM-generated note describing a completed tool batch. UI-only:\n       *  never sent to the model (stripped before payload formatting). */\n      type: ContentTypes.ACTIVITY_LABEL;\n      activity_label?: string;\n      /** Missing means the legacy/per-batch activity label. */\n      activity_label_type?: 'phase';\n      tool_call_ids?: string[];\n      /** Parent phase bounds and telemetry. */\n      activity_start_index?: number;\n      /** Exclusive end of the grouped content; may precede the marker itself. */\n      activity_end_index?: number;\n      activity_count?: number;\n      agent_ids?: string[];\n      /** ok = all tools succeeded, failed = all failed, partial = mixed. */\n      status?: 'ok' | 'partial' | 'failed';\n      pending?: boolean;\n    } & 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 = '---';\n/** Mirrors `Constants.mcp_delimiter`; duplicated here to avoid a circular import from `config.ts`. */\nconst mcpDelimiter = '_mcp_';\n\n/**\n * Checks whether a tool name is an OpenAPI action tool.\n *\n * Action format: `operationId_action_normalizedDomain`\n * MCP format:    `toolName_mcp_serverName`\n *\n * Cross-delimiter collision: an MCP tool like `get_action_mcp_srv` contains\n * `_action_` as a false positive. Guarded by checking whether `_mcp_` appears\n * after `_action_`. In the collision case the `_mcp_` suffix always follows\n * `_action_`; in a valid action tool whose operationId contains `_mcp_`, the\n * `_mcp_` precedes `_action_`.\n *\n * Theoretical limitation: a non-RFC-compliant domain containing literal\n * underscores that form `_mcp_` (e.g. `api_mcp_internal.com`) would produce\n * a false negative. RFC 952/1123 prohibit underscores in hostnames, so this\n * is not expected in practice.\n */\nexport function isActionTool(toolName: string): boolean {\n  const actionIdx = toolName.indexOf(actionDelimiter);\n  if (actionIdx < 0) {\n    return false;\n  }\n  const mcpIdx = toolName.indexOf(mcpDelimiter);\n  return mcpIdx < 0 || mcpIdx < actionIdx;\n}\n\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';\nimport type { TMessageContentParts, AgentSubagentGraph, FunctionTool } from './types/assistants';\nimport type { SearchResultData } from './types/web';\nimport type { TFile } from './types/files';\nimport { CODE_ENVIRONMENT_MODES, CODE_WORKSPACE_ID_PATTERN } from './code/workspace';\nimport { userSubmittedMessageFieldPathSchema } from './filters';\nimport { TFeedback, feedbackSchema } from './feedback';\nimport { CODE_APPROVAL_MODES } from './code/approval';\nimport { Tools } from './types/assistants';\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\n/**\n * Providers whose `usage_metadata.input_tokens` ALREADY INCLUDES cached tokens\n * (`input_token_details.cache_*` is a subset, not an additional charge):\n * Google/Vertex (`promptTokenCount`), OpenAI/Azure (`prompt_tokens`), and the\n * OpenAI-compatible family. `@librechat/agents`' `getAnthropicUsageMetadata`\n * folds `cache_creation` + `cache_read` into `input_tokens`, so Anthropic is a\n * subset provider too; without this the cache portion is billed twice. Bedrock\n * stays additive — its Converse path passes AWS `inputTokens` through unmodified.\n * Single source of truth shared by the backend billing path\n * (`packages/api/src/agents/usage.ts`) and the client usage normalization.\n */\nexport const cacheSubsetProviders = new Set<string>([\n  Providers.OPENAI,\n  Providers.AZURE,\n  Providers.GOOGLE,\n  Providers.VERTEXAI,\n  Providers.XAI,\n  Providers.DEEPSEEK,\n  Providers.OPENROUTER,\n  Providers.MOONSHOT,\n  Providers.ANTHROPIC,\n]);\n\nexport const inputTokensIncludesCache = (provider?: string | null): boolean => {\n  return cacheSubsetProviders.has(provider ?? '');\n};\n\nexport const isDocumentSupportedProvider = (provider?: string | null): boolean => {\n  const normalized = provider?.toLowerCase() ?? '';\n  return Array.from(documentSupportedProviders).some(\n    (candidate) => candidate.toLowerCase() === normalized,\n  );\n};\n\n/**\n * Endpoints whose encoders actually build native audio/video payloads. Narrower than\n * `documentSupportedProviders`: a provider can accept PDFs and still emit nothing for\n * media, in which case the upload has to fall back to text/STT.\n */\nexport const mediaSupportedProviders = new Set<string>([\n  EModelEndpoint.google,\n  Providers.VERTEXAI,\n  Providers.OPENROUTER,\n]);\n\nexport const isMediaSupportedProvider = (provider?: string | null): boolean => {\n  return mediaSupportedProviders.has(provider?.toLowerCase() ?? '');\n};\n\n/**\n * Built-in endpoint and provider identifiers. A name outside this set is a custom\n * endpoint whose real provider is resolved at request time, so its capabilities\n * cannot be judged from the name alone.\n */\nconst knownProviderIdentifiers = new Set<string>([\n  ...Object.values(EModelEndpoint),\n  ...Object.values(Providers),\n  ...Object.values(EModelEndpoint).map((provider) => provider.toLowerCase()),\n  ...Object.values(Providers).map((provider) => provider.toLowerCase()),\n]);\n\nexport const isKnownProviderIdentifier = (provider?: string | null): boolean => {\n  return knownProviderIdentifiers.has(provider?.toLowerCase() ?? '');\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  max = 'max',\n}\n\nexport enum ReasoningParameterFormat {\n  disabled = 'disabled',\n  reasoningEffort = 'reasoning_effort',\n  reasoningObject = 'reasoning_object',\n}\n\nexport enum ReasoningResponseKey {\n  reasoning = 'reasoning',\n  reasoningContent = 'reasoning_content',\n}\n\nexport enum AnthropicEffort {\n  unset = '',\n  low = 'low',\n  medium = 'medium',\n  high = 'high',\n  xhigh = 'xhigh',\n  max = 'max',\n}\n\n/**\n * Controls whether the model's reasoning content is returned in responses.\n *\n * - `'auto'` - LibreChat decides: opt in to `'summarized'` for models that\n *   omit by default (Opus 4.7+), leave the field off for older models.\n * - `'summarized'` - always request a post-hoc summary of the reasoning.\n * - `'omitted'` - always suppress reasoning content. Slightly lower latency.\n *\n * See https://platform.claude.com/docs/en/about-claude/models/whats-new-claude-4-7#thinking-content-omitted-by-default\n */\nexport enum ThinkingDisplay {\n  auto = 'auto',\n  summarized = 'summarized',\n  omitted = 'omitted',\n}\n\n/**\n * Wire-level values accepted by the Anthropic Messages API `thinking.display`\n * field. Excludes the LibreChat-only `'auto'` sentinel.\n */\nexport type ThinkingDisplayWireValue = Exclude<ThinkingDisplay, ThinkingDisplay.auto>;\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\n/** OpenAI Responses API `reasoning.mode` (GPT-5.6+). */\nexport enum ReasoningMode {\n  unset = '',\n  standard = 'standard',\n  pro = 'pro',\n}\n\n/** OpenAI Responses API `reasoning.context` (GPT-5.6+). */\nexport enum ReasoningContext {\n  unset = '',\n  auto = 'auto',\n  current_turn = 'current_turn',\n  all_turns = 'all_turns',\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 eReasoningParameterFormatSchema = z.nativeEnum(ReasoningParameterFormat);\nexport const eReasoningResponseKeySchema = z.nativeEnum(ReasoningResponseKey);\nexport const eAnthropicEffortSchema = z.nativeEnum(AnthropicEffort);\nexport const eThinkingDisplaySchema = z.nativeEnum(ThinkingDisplay);\nexport const eReasoningSummarySchema = z.nativeEnum(ReasoningSummary);\nexport const eVerbositySchema = z.nativeEnum(Verbosity);\nexport const eThinkingLevelSchema = z.nativeEnum(ThinkingLevel);\nexport const eReasoningModeSchema = z.nativeEnum(ReasoningMode);\nexport const eReasoningContextSchema = z.nativeEnum(ReasoningContext);\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  [Tools.memory]: false,\n  stateful_code_environment: 'user' as const,\n  code_environment_id: undefined as string | null | undefined,\n  code_workspace_id: undefined as string | undefined,\n  category: 'general',\n  support_contact: {\n    name: '',\n    email: '',\n  },\n  /** Optional allowlist. Only applies when `skills_enabled === true`.\n   *  Empty/undefined + enabled = full catalog; non-empty + enabled = narrow to ids. */\n  skills: undefined as string[] | undefined,\n  /** Master toggle for skill use on this agent. `true` activates skills\n   *  (full catalog unless `skills` narrows it). Anything else = inactive. */\n  skills_enabled: undefined as boolean | undefined,\n  /** Enables runtime skill creation without exposing an existing skill catalog. */\n  skill_authoring_enabled: undefined as boolean | undefined,\n  /** Explicit catalog scope. Missing preserves the legacy enabled + empty = all behavior. */\n  skills_scope: undefined as SkillsScope | undefined,\n  /** `undefined` = feature disabled by default (no subagent tool injected). */\n  subagents: undefined as\n    | {\n        enabled?: boolean;\n        allowSelf?: boolean;\n        agent_ids?: string[];\n        graphs?: AgentSubagentGraph[];\n      }\n    | undefined,\n  /** Memory partition: 'agent' isolates memories per (user, agent); default shared pool */\n  memory_scope: undefined as MemoryScope | undefined,\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\n/** Structural on purpose: accepts assistants tools/tool calls and agents function tool\n *  calls alike — the check only ever reads `type` and `function.name`. */\nexport const isImageVisionTool = (tool: { type?: string; function?: { name?: string } }) =>\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\n/**\n * `65535` (not 65536) is the value valid on both Google AI Studio and Vertex AI:\n * Vertex caps current Gemini text models at 65,535 output tokens, so defaulting to\n * 65,536 would make otherwise-default Vertex requests fail validation.\n */\nconst GOOGLE_MAX_OUTPUT = 65535 as const;\nconst GOOGLE_IMAGE_MAX_OUTPUT = 32768 as const;\nconst GOOGLE_LEGACY_MAX_OUTPUT = 8192 as const;\n\n/**\n * Resolves the documented max output-token limit for a Google/Gemini model.\n * Current Gemini text models (2.5 and 3+) support 64K output tokens; their image\n * variants (e.g. `gemini-2.5-flash-image`) cap at 32K; legacy/deprecated models\n * (2.0 and earlier, including legacy image models) and Gemma retain the 8K limit.\n */\nconst getGoogleMaxOutputTokens = (modelName: string): number => {\n  if (/gemini-(?:2\\.5|[3-9]|\\d{2,})/i.test(modelName)) {\n    if (/image/i.test(modelName)) {\n      return GOOGLE_IMAGE_MAX_OUTPUT;\n    }\n    return GOOGLE_MAX_OUTPUT;\n  }\n  return GOOGLE_LEGACY_MAX_OUTPUT;\n};\n\n/**\n * Per-model thinking budget bounds, documented in\n * `com_endpoint_google_thinking_budget`: Gemini 2.5 Pro accepts 128-32,768,\n * Flash accepts 0-24,576, and Flash Lite accepts 512-24,576. The generic\n * 32,000 in the shared definition both under-limits Pro and lets invalid\n * Flash values through.\n *\n * `-1` remains the \"decide automatically\" sentinel and is not part of these\n * floors. Callers must keep `range.min` at -1 and apply `min` only to\n * non-negative values.\n */\nconst GOOGLE_THINKING_BUDGET_PRO_MAX = 32768 as const;\nconst GOOGLE_THINKING_BUDGET_FLASH_MAX = 24576 as const;\nconst GOOGLE_THINKING_BUDGET_PRO_MIN = 128 as const;\nconst GOOGLE_THINKING_BUDGET_FLASH_MIN = 0 as const;\nconst GOOGLE_THINKING_BUDGET_FLASH_LITE_MIN = 512 as const;\n\nexport type GoogleThinkingBudgetBounds = { min: number; max: number };\n\nexport const getGoogleThinkingBudgetBounds = (\n  modelName: string,\n): GoogleThinkingBudgetBounds | undefined => {\n  if (!/gemini-2\\.5/i.test(modelName)) {\n    return undefined;\n  }\n  if (/flash[-_.]?lite/i.test(modelName)) {\n    return { min: GOOGLE_THINKING_BUDGET_FLASH_LITE_MIN, max: GOOGLE_THINKING_BUDGET_FLASH_MAX };\n  }\n  if (/flash/i.test(modelName)) {\n    return { min: GOOGLE_THINKING_BUDGET_FLASH_MIN, max: GOOGLE_THINKING_BUDGET_FLASH_MAX };\n  }\n  if (/pro/i.test(modelName)) {\n    return { min: GOOGLE_THINKING_BUDGET_PRO_MIN, max: GOOGLE_THINKING_BUDGET_PRO_MAX };\n  }\n  return undefined;\n};\n\nexport const getGoogleThinkingBudgetMax = (modelName: string): number | undefined =>\n  getGoogleThinkingBudgetBounds(modelName)?.max;\n\nexport const googleSettings = {\n  model: {\n    default: 'gemini-1.5-flash-latest' as const,\n  },\n  maxContextTokens: {\n    min: 10 as const,\n    max: 2000000 as const,\n    step: 1000 as const,\n  },\n  maxOutputTokens: {\n    min: 1 as const,\n    max: GOOGLE_MAX_OUTPUT,\n    step: 1 as const,\n    default: GOOGLE_LEGACY_MAX_OUTPUT,\n    reset: (modelName: string): number => getGoogleMaxOutputTokens(modelName),\n    set: (value: number, modelName: string): number => {\n      const max = getGoogleMaxOutputTokens(modelName);\n      return value > max ? max : value;\n    },\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;\nconst CLAUDE_SONNET_128K_OUTPUT_PATTERN =\n  /claude-sonnet[-.]?(?:4[-.]?(?:[6-9]|\\d{2})|[5-9]|\\d{2,})(?=$|[^0-9])/;\n\n/**\n * Claude \"Mythos-class\" model families — new top-level classes (peers of\n * `opus`/`sonnet`/`haiku`) that ship with the post-Opus-4.7 modern profile:\n * adaptive thinking always on, raw thinking omitted by default (summarized\n * opt-in), sampling parameters rejected, and a 1M context window. The tier\n * word is the class name itself, so the `opus`/`sonnet` version parsers don't\n * cover them.\n *\n * Single source of truth: add a future sibling class name here and every\n * Mythos-class gate (adaptive thinking, sampling omission, prompt caching, 1M\n * context, 128K output) picks it up.\n */\nexport const MYTHOS_CLASS_FAMILIES = ['fable', 'mythos'] as const;\nconst MYTHOS_CLASS_PATTERN = new RegExp(`claude-(?:${MYTHOS_CLASS_FAMILIES.join('|')})[-.]?\\\\d`);\n\n/** Whether the model is a Claude Mythos-class model (e.g. `claude-fable-5`). */\nexport function isMythosClassModel(model: string): boolean {\n  return MYTHOS_CLASS_PATTERN.test(model);\n}\n\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  promptCacheTtl: {\n    default: undefined,\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 (isMythosClassModel(modelName)) {\n        return ANTHROPIC_MAX_OUTPUT;\n      }\n\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_128K_OUTPUT_PATTERN.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 (isMythosClassModel(modelName)) {\n        if (value > ANTHROPIC_MAX_OUTPUT) {\n          return ANTHROPIC_MAX_OUTPUT;\n        }\n        return value;\n      }\n\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_128K_OUTPUT_PATTERN.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.xhigh,\n      AnthropicEffort.max,\n    ],\n  },\n  thinkingDisplay: {\n    default: ThinkingDisplay.auto,\n    options: [ThinkingDisplay.auto, ThinkingDisplay.summarized, ThinkingDisplay.omitted],\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  /** Whether the field holds a secret and should be masked in the UI (defaults to masked when omitted). */\n  sensitive: 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  /** Raw upstream tool name when the model-facing key stripped a redundant\n   *  server-name prefix — proves upstream identity for legacy id migration. */\n  serverToolName: z.string().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\n/** Compact context-fading tier persisted beside a message's calibration ratio. */\nconst agentFadingTierSchema = z.object({\n  v: z.literal(1),\n  budgetTokens: z.number().positive(),\n  masked: z.boolean(),\n});\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  /** True when the complete stored row came from outside the model. */\n  isUserSubmitted: z.boolean().optional(),\n  /** JSON pointers to caller-authored fields in an otherwise mixed model response. */\n  userSubmittedPaths: z.array(z.string().startsWith('/')).optional(),\n  /** Exact HITL message-field identity for caller-authored values stored in mixed responses. */\n  userSubmittedMessageFieldPaths: z.array(userSubmittedMessageFieldPathSchema).optional(),\n  isTemporary: z.boolean().optional(),\n  expiredAt: z.string().nullable().optional(),\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  /** Output tokens for assistant messages, calibrated prompt-side estimate for user messages */\n  tokenCount: z.number().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      fading: agentFadingTierSchema\n        .optional()\n        .describe(\n          'Latched context-fading tier of the default agent; seeds the next run so the provider projection of history keeps the same bytes',\n        ),\n      fadingTiers: z\n        .array(agentFadingTierSchema.extend({ agentId: z.string().min(1) }))\n        .optional()\n        .describe('Latched context-fading tiers keyed by agent ID, stored as entries'),\n    })\n    .optional(),\n  /**\n   * Skill names the user invoked manually via the `$` popover on this turn.\n   * Purely UI metadata — `SkillPills` renders these above the message\n   * bubble so users can see which skills they asked for in history and on\n   * reload. Runtime resolution uses the top-level payload field with the\n   * same name. Empty / absent for model-invoked skills (shown as tool_call\n   * content parts on the assistant message instead).\n   */\n  manualSkills: z.array(z.string()).optional(),\n  /**\n   * Skill names auto-primed on this turn because their `always-apply`\n   * frontmatter flag is set. Persisted at turn time so the pinned-variant\n   * pills on the user bubble survive reload and stay stable across later\n   * edits to the skill's `alwaysApply` flag (the user bubble reflects\n   * what actually ran, not the current catalog).\n   */\n  alwaysAppliedSkills: z.array(z.string()).optional(),\n  /**\n   * Verbatim excerpts the user quoted (via the \"Add to chat\" selection\n   * popup) to reference on this turn. UI metadata that `MessageQuotes`\n   * renders above the user bubble so the references persist on reload. The\n   * excerpts are merged into the user message text sent to the model at\n   * request time and counted in the user message token count.\n   */\n  quotes: z.array(z.string()).optional(),\n});\n\n/**\n * Which memory partition an agent reads/writes.\n * `user` = the shared personal pool (default); `agent` = a partition\n * isolated per (user, agent) so the agent only sees its own memories.\n */\nexport enum MemoryScope {\n  user = 'user',\n  agent = 'agent',\n}\n\n/** Catalog exposure for a persisted agent with skills enabled. */\nexport enum SkillsScope {\n  all = 'all',\n  selected = 'selected',\n  none = 'none',\n}\n\n/** Resolves explicit and legacy persisted-agent skill catalog states. */\nexport function resolveAgentSkillsScope(\n  skills: readonly string[] | undefined,\n  enabled: boolean | undefined,\n  scope: SkillsScope | undefined,\n): SkillsScope {\n  if (enabled !== true) {\n    return SkillsScope.none;\n  }\n  if (scope !== undefined) {\n    return scope;\n  }\n  return (skills ?? []).length > 0 ? SkillsScope.selected : SkillsScope.all;\n}\n\nexport type MemoryArtifact = {\n  key: string;\n  value?: string;\n  tokenCount?: number;\n  type: 'update' | 'delete' | 'error';\n  /** Agent partition the write targeted; absent = shared personal pool */\n  agentId?: string;\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 WorkspaceChange = {\n  profile: 'stateful';\n  operation: 'created' | 'updated';\n  path: string;\n};\n\nexport type TAttachmentMetadata = {\n  type?: Tools;\n  messageId: string;\n  toolCallId: string;\n  /** Saved-agent owner when provider tool-call ids repeat across handoffs. */\n  agentId?: string;\n  /** Host run-step owner when one agent repeats a provider tool-call id. */\n  stepId?: string;\n  workspaceChange?: WorkspaceChange;\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  /** Client-only durable branch anchor while this message is an optimistic response. */\n  clientQueueParentMessageId?: 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 subagentThreadLineageSchema = z.object({\n  rootConversationId: z.string().min(1),\n  parentConversationId: z.string().min(1),\n  parentMessageId: z.string().min(1),\n  parentToolCallId: z.string().min(1),\n  parentAgentId: z.string().min(1).optional(),\n  subagentType: z.string().min(1),\n  subagentKind: z.enum(['agent', 'graph']),\n  depth: z.number().int().positive(),\n});\n\nexport type TSubagentThreadLineage = z.infer<typeof subagentThreadLineageSchema>;\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  /** When the chat was archived; absent on chats archived before this was recorded. */\n  archivedAt: z.string().nullable().optional(),\n  pinned: z.boolean().optional(),\n  /** Server-derived: an active shared link exists for this conversation. Not persisted. */\n  isShared: z.boolean().optional(),\n  codeApprovalMode: z.enum(CODE_APPROVAL_MODES).optional(),\n  codeEnvironmentMode: z.enum(CODE_ENVIRONMENT_MODES).optional(),\n  codeWorkspaces: z\n    .array(\n      z\n        .object({\n          environmentId: z.string().regex(CODE_WORKSPACE_ID_PATTERN),\n          workspaceId: z.string().regex(CODE_WORKSPACE_ID_PATTERN),\n        })\n        .strict(),\n    )\n    .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  promptCacheTtl: z.enum(['5m', '1h']).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  chatProjectId: z.string().nullable().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 Responses API: reasoning mode (standard/pro) + context */\n  reasoning_mode: eReasoningModeSchema.optional().nullable(),\n  reasoning_context: eReasoningContextSchema.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  /* Anthropic: Thinking visibility (Opus 4.7+ opt-in) */\n  thinkingDisplay: eThinkingDisplaySchema.optional().nullable(),\n  /* OpenAI Responses API / Anthropic API / Google API */\n  web_search: z.boolean().optional(),\n  /* Google API: URL Context tool (+ native YouTube video understanding) */\n  url_context: 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  /** Durable parent/child navigation for a subagent thread. */\n  subagentThread: subagentThreadLineageSchema.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  isTemporary: z.boolean().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    chatProjectId: 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    reasoning_mode: true,\n    /** @endpoints openAI, custom, azureOpenAI */\n    reasoning_context: 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 google */\n    url_context: 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    promptCacheTtl: true,\n    thinking: true,\n    thinkingBudget: true,\n    thinkingLevel: true,\n    effort: true,\n    thinkingDisplay: 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.\n *\n * `greeting` and `iconURL` are admin-configurable display fields on a model spec's\n * preset (landing greeting, preset-level icon fallback) and must be preserved.\n * `spec` is set by the client from `modelSpec.name` via `getModelSpecPreset` and is\n * omitted to avoid duplicate configuration surface.\n */\nexport const tModelSpecPresetSchema = tPresetSchema\n  .omit({\n    conversationId: true,\n    presetId: true,\n    title: true,\n    defaultPreset: true,\n    order: true,\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    spec: true,\n  })\n  .merge(\n    z.object({\n      /**\n       * Optional here, unlike `tPresetSchema`, where the key is required (though\n       * nullable). A preset naming an `agent_id` has an unambiguous endpoint, so\n       * config may omit it and `resolveModelSpecEndpoint` infers `agents` when\n       * specs are materialized at config load.\n       */\n      endpoint: extendedModelEndpointSchema.nullish(),\n    }),\n  )\n  .superRefine((preset, ctx) => {\n    /**\n     * Omission is only legal when the endpoint is inferable, which requires a\n     * NON-EMPTY `agent_id` — form-backed writers persist untouched fields as\n     * `''`, which names no agent. An explicit `endpoint: null` stays accepted:\n     * it validated before the key became optional, so rejecting it now would\n     * break previously valid configs.\n     */\n    if (preset.endpoint === undefined && !preset.agent_id) {\n      ctx.addIssue({\n        code: z.ZodIssueCode.custom,\n        path: ['endpoint'],\n        message:\n          'endpoint is required unless the preset names a non-empty agent_id (the agents endpoint is then inferred)',\n      });\n    }\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  targetMessageId: z.string().optional(),\n  messages: z.array(z.string()),\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  chatProjectId: true,\n  model: true,\n  modelLabel: true,\n  promptPrefix: true,\n  examples: true,\n  temperature: true,\n  maxOutputTokens: true,\n  resendFiles: true,\n  artifacts: true,\n  topP: true,\n  topK: true,\n  thinking: true,\n  thinkingBudget: true,\n  thinkingLevel: true,\n  web_search: true,\n  url_context: 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    url_context: 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  chatProjectId: true,\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  chatProjectId: true,\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  chatProjectId: true,\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  chatProjectId: true,\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  reasoning_mode: true,\n  reasoning_context: 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 openRouterSchema = openAIBaseSchema\n  .merge(tConversationSchema.pick({ promptCache: true, promptCacheTtl: true }))\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.reset(newObj.model ?? '')) {\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  chatProjectId: true,\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  promptCacheTtl: true,\n  thinking: true,\n  thinkingBudget: true,\n  effort: true,\n  thinkingDisplay: 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  chatProjectId: true,\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 type { ZodIssue } from 'zod';\nimport type { TConversation, TSetOption, TPreset } from './schemas';\nimport { tConversationSchema, googleSettings as google, openAISettings as openAI } 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   * Inclusive floor for non-negative values. Use when `min` is a sentinel\n   * (Google thinkingBudget `-1` for auto) and positive values have a higher\n   * documented minimum.\n   */\n  positiveMin?: number;\n  /**\n   * Set when this range came from the selected model rather than the shared\n   * fallback. Only then is it safe to normalize a stored value against it: a\n   * model that does not use the parameter leaves the generic range in place,\n   * and clamping to that would discard a value set for another model.\n   */\n  modelSpecific?: boolean;\n}\n\nexport function clampSettingRange(value: number, range: SettingRange): number {\n  if (range.positiveMin != null) {\n    /** The minimum carries its own meaning here (Google's -1 for automatic),\n     *  and the schema admits it outright, so it survives rather than being\n     *  lifted to the floor. It need not be negative to be the sentinel. */\n    if (value === range.min) {\n      return range.min;\n    }\n    /** Below the sentinel there is nothing admissible to lift to, so the value\n     *  resolves to it. Between the sentinel and the floor, the floor is the\n     *  nearest value the generated schema accepts. */\n    if (value < Math.max(range.min, 0)) {\n      return range.min;\n    }\n    return Math.min(Math.max(value, range.positiveMin), range.max);\n  }\n  return Math.min(Math.max(value, range.min), range.max);\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 numberSchema = z.number();\n      if (range) {\n        numberSchema = numberSchema.min(range.min);\n        numberSchema = numberSchema.max(range.max);\n      }\n      /** Widened deliberately: refine returns ZodEffects, not ZodNumber, and\n       *  the number-specific chaining is already done above. */\n      let schema: z.ZodTypeAny = numberSchema;\n      if (range?.positiveMin != null) {\n        /** Mirrors clampSettingRange so the generated schema and the clamp\n         *  agree: `min` only admits the sentinel, and any non-negative value\n         *  must clear the documented floor. */\n        const { positiveMin, min } = range;\n        schema = numberSchema.refine(\n          (value) => value === min || value >= positiveMin,\n          `Expected ${min} or a value of at least ${positiveMin}`,\n        );\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        /** The midpoint of the admissible interval, which a positive floor\n         *  narrows: the span between the sentinel and that floor holds no value\n         *  the generated schema accepts, so a midpoint taken across it would\n         *  fail the validation below. */\n        const floor = Math.max(setting.range.min, setting.range.positiveMin ?? setting.range.min);\n        setting.default = Math.round((floor + 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    if (\n      setting.type === SettingTypes.Number &&\n      setting.range?.positiveMin != null &&\n      setting.range.positiveMin > setting.range.max\n    ) {\n      errors.push({\n        code: ZodIssueCode.custom,\n        message: `Invalid range for setting ${setting.key}. positiveMin (${setting.range.positiveMin}) cannot exceed max (${setting.range.max}).`,\n        path: ['range'],\n      });\n    }\n\n    if (\n      setting.type === SettingTypes.Number &&\n      setting.range?.positiveMin != null &&\n      typeof setting.default === 'number' &&\n      setting.default !== setting.range.min &&\n      setting.default < setting.range.positiveMin\n    ) {\n      errors.push({\n        code: ZodIssueCode.custom,\n        message: `Invalid default value for setting ${setting.key}. Must be ${setting.range.min} or at least ${setting.range.positiveMin}.`,\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:\n          obj.maxOutputTokens ??\n          defaults.maxOutputTokens.reset(obj.model ?? defaults.model.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","/** Maximum number of explicit subagents per parent agent. UI + Zod schema share this. */\nexport const MAX_SUBAGENTS = 10;\n\n/** Hard upper bound for `endpoints.agents.maxSubagents`, keeping the request-validation\n *  cap bounded no matter what the config file says. */\nexport const MAX_SUBAGENTS_CEILING = 50;\n\nlet maxSubagents = MAX_SUBAGENTS;\n\n/** Effective subagents-per-agent cap; initialized from `endpoints.agents.maxSubagents` at startup. */\nexport const getMaxSubagents = (): number => maxSubagents;\n\n/** Applies a configured cap; any missing or out-of-range value resets to the default. */\nexport const setMaxSubagents = (value: number | undefined): void => {\n  maxSubagents =\n    typeof value === 'number' &&\n    Number.isInteger(value) &&\n    value >= 1 &&\n    value <= MAX_SUBAGENTS_CEILING\n      ? value\n      : MAX_SUBAGENTS;\n};\n\n/** Chat project field limits. The dialogs and the persistence layer share these,\n *  so the inputs stop at the same point the server would otherwise truncate. */\nexport const MAX_CHAT_PROJECT_NAME_LENGTH = 100;\nexport const MAX_CHAT_PROJECT_DESCRIPTION_LENGTH = 1000;\n\n/** Mirrors the bounded graph-child member limit in `@librechat/agents`. */\nexport const MAX_GRAPH_SUBAGENT_MEMBERS = 32;\n","import { z } from 'zod';\nimport type { AgentSubagentsConfig } from './types/assistants';\nimport type { TModelSpecPreset } from './schemas';\nimport {\n  EModelEndpoint,\n  tModelSpecPresetSchema,\n  eModelEndpointSchema,\n  AuthType,\n  authTypeSchema,\n} from './schemas';\nimport { getMaxSubagents } from './limits';\n\ntype ModelSpecSubagentsConfig = Omit<AgentSubagentsConfig, 'graphs'>;\n\nexport type TModelSpec = {\n  name: string;\n  label: string;\n  preset: TModelSpecPreset;\n  order?: number;\n  default?: boolean;\n  softDefault?: 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  /** Show this spec's label and description on the chat landing in place of the greeting. */\n  showOnLanding?: boolean;\n  /** Conversation starter prompts shown on the chat landing while this spec is active. */\n  conversation_starters?: string[];\n  /**\n   * When false, the spec is omitted from the model selector menu and from the\n   * client startup config, but remains usable when invoked explicitly by name\n   * via the `spec` field (server-side resolution uses the full, unfiltered list).\n   * Unlike `showIconInMenu` (which only hides the icon), this hides the whole entry.\n   * Defaults to true (listed).\n   */\n  showInMenu?: boolean;\n  iconURL?: string | EModelEndpoint; // Allow using project-included icons\n  authType?: AuthType;\n  /** Hide the chat input tool badge row while this model spec is active. */\n  hideBadgeRow?: boolean;\n  webSearch?: boolean;\n  fileSearch?: boolean;\n  executeCode?: boolean;\n  memory?: boolean;\n  /** Equip the spec's ephemeral agent with the `ask_user_question` HITL tool. */\n  askUserQuestion?: boolean;\n  /**\n   * Let the model dispatch tool calls in the background (poll results via\n   * `check_background_task`). Code execution is background-NATIVE: when the\n   * admin enables the `run_in_background` agent capability, an\n   * `executeCode: true` spec backgrounds code with no flag here. `true` opts\n   * in every other eligible tool; a string array opts in only the named\n   * tools, matched against the spec's resolved tool ids (e.g.\n   * `['slow_report_mcp_analytics']`; `execute_code` and `bash_tool` both\n   * select the code pair). `false`, the empty list, or a list that omits the\n   * code pair explicitly opts it back out. Requires the `run_in_background`\n   * agent capability.\n   */\n  runInBackground?: boolean | string[];\n  /**\n   * Inject the `intent` label param so each call streams a live status label.\n   * `true` opts in every eligible tool; a string array opts in only the named\n   * tools, matched against the spec's resolved tool ids (e.g.\n   * `['web_search', 'search_code_mcp_github']`). Requires the `tool_intents`\n   * agent capability to be enabled by the admin.\n   */\n  describeIntent?: boolean | string[];\n  artifacts?: string | boolean;\n  mcpServers?: string[];\n  skills?: boolean | string[];\n  subagents?: ModelSpecSubagentsConfig;\n};\n\nexport const modelSpecSubagentsSchema = z\n  .object({\n    enabled: z.boolean().optional(),\n    allowSelf: z.boolean().optional(),\n    shareFiles: z.boolean().optional(),\n    agent_ids: z.array(z.string()).optional(),\n  })\n  .superRefine((subagents, ctx) => {\n    const maxSubagents = getMaxSubagents();\n    if ((subagents.agent_ids?.length ?? 0) > maxSubagents) {\n      ctx.addIssue({\n        code: z.ZodIssueCode.custom,\n        path: ['agent_ids'],\n        message: `agent_ids must contain at most ${maxSubagents} item(s)`,\n      });\n    }\n  });\n\n/**\n * The endpoint a spec targets. Only the agents endpoint can serve a preset that\n * names an `agent_id`, so an omitted `endpoint` is inferred rather than left\n * undefined — otherwise the spec matches no endpoint at all, the client sends\n * no endpoint when it is selected, and the request is rejected as a mismatch.\n *\n * Shared so the selector and the request pipeline resolve a spec identically.\n */\n/**\n * Structural view of the fields endpoint resolution reads, so partial spec\n * shapes (e.g. `AppConfig['modelSpecs']`, which is deep-partial) qualify.\n */\ntype ModelSpecEndpointSource = {\n  preset?: Pick<TModelSpecPreset, 'endpoint' | 'agent_id'> | null;\n};\n\nexport function resolveModelSpecEndpoint(\n  modelSpec: ModelSpecEndpointSource | undefined,\n): string | undefined {\n  const preset = modelSpec?.preset;\n  if (preset?.endpoint != null) {\n    return preset.endpoint;\n  }\n  /**\n   * An explicit `endpoint: null` is a statement, not an omission — such specs\n   * validated (and were skipped downstream) before inference existed, so\n   * inferring here would silently activate them. Only an absent key infers,\n   * and only from a non-empty `agent_id`: form-backed writers persist\n   * untouched fields as `''`, which names no agent.\n   */\n  if (preset?.endpoint === null) {\n    return undefined;\n  }\n  return preset?.agent_id ? EModelEndpoint.agents : undefined;\n}\n\n/**\n * Writes each spec's resolved endpoint back onto its preset so every consumer —\n * endpoint matching, the selector, access filters, startup presets, provider-key\n * reachability — reads a complete spec instead of re-deriving it. Apply once\n * where the effective config is assembled (YAML load and DB-override merge);\n * downstream code then needs no awareness of inference.\n *\n * Returns the original object, and the original spec objects, when nothing\n * needs filling in, so cached configs and memoized consumers see no new\n * identities.\n */\nexport function materializeModelSpecEndpoints<\n  T extends { list?: ModelSpecEndpointSource[] } | null | undefined,\n>(modelSpecs: T): T {\n  const list = modelSpecs?.list;\n  if (!list?.length) {\n    return modelSpecs;\n  }\n\n  let changed = false;\n  const materialized = list.map((spec) => {\n    if (spec?.preset == null || spec.preset.endpoint != null) {\n      return spec;\n    }\n    const endpoint = resolveModelSpecEndpoint(spec);\n    if (endpoint == null) {\n      return spec;\n    }\n    changed = true;\n    return { ...spec, preset: { ...spec.preset, endpoint } };\n  });\n\n  if (!changed) {\n    return modelSpecs;\n  }\n  return { ...modelSpecs, list: materialized } as T;\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  softDefault: 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  showOnLanding: z.boolean().optional(),\n  conversation_starters: z.array(z.string()).optional(),\n  showInMenu: z.boolean().optional(),\n  iconURL: z.union([z.string(), eModelEndpointSchema]).optional(),\n  authType: authTypeSchema.optional(),\n  hideBadgeRow: z.boolean().optional(),\n  webSearch: z.boolean().optional(),\n  fileSearch: z.boolean().optional(),\n  executeCode: z.boolean().optional(),\n  memory: z.boolean().optional(),\n  askUserQuestion: z.boolean().optional(),\n  runInBackground: z.union([z.boolean(), z.array(z.string())]).optional(),\n  describeIntent: z.union([z.boolean(), z.array(z.string())]).optional(),\n  artifacts: z.union([z.string(), z.boolean()]).optional(),\n  mcpServers: z.array(z.string()).optional(),\n  skills: z.union([z.boolean(), z.array(z.string())]).optional(),\n  subagents: modelSpecSubagentsSchema.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).default([]),\n  addedEndpoints: z.array(z.union([z.string(), eModelEndpointSchema])).optional(),\n});\n\nexport type TSpecsConfig = z.infer<typeof specsConfigSchema>;\n","export const REFILL_INTERVAL_UNITS = [\n  'seconds',\n  'minutes',\n  'hours',\n  'days',\n  'weeks',\n  'months',\n] as const;\n\nexport type RefillIntervalUnit = (typeof REFILL_INTERVAL_UNITS)[number];\n\nfunction ensureExhaustive(value: never): void {\n  void value;\n}\n\nexport function getRefillEligibilityDate(\n  lastRefill: Date,\n  value: number,\n  unit: RefillIntervalUnit,\n): Date {\n  const result = new Date(lastRefill);\n  switch (unit) {\n    case 'seconds':\n      result.setSeconds(result.getSeconds() + value);\n      return result;\n    case 'minutes':\n      result.setMinutes(result.getMinutes() + value);\n      return result;\n    case 'hours':\n      result.setHours(result.getHours() + value);\n      return result;\n    case 'days':\n      result.setDate(result.getDate() + value);\n      return result;\n    case 'weeks':\n      result.setDate(result.getDate() + value * 7);\n      return result;\n    case 'months':\n      result.setMonth(result.getMonth() + value);\n      return result;\n    default: {\n      ensureExhaustive(unit);\n      return result;\n    }\n  }\n}\n","import { z } from 'zod';\nimport type { EndpointFileConfig, FileConfig, RegexLike } 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  'application/vnd.openxmlformats-officedocument.presentationml.template',\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/calendar',\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-zip-compressed',\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  'message/rfc822',\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  'application/vnd.openxmlformats-officedocument.presentationml.template',\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/calendar',\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-zip-compressed',\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  'application/vnd.openxmlformats-officedocument.presentationml.template',\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\n/**\n * Whether an upload belongs to the conversation rather than to the agent. The value\n * arrives from multipart form data, so it can be the string \"false\", which is truthy.\n * Shared so the route, the authorization check and processing cannot disagree about it.\n */\nexport const isMessageFileUpload = (value?: boolean | string | null): boolean =>\n  value === true || value === 'true';\n\n/**\n * Whether the upload's conversation uses the Responses API, which decides whether Azure\n * can carry a document natively. Multipart form data has no booleans, so it arrives as\n * the string \"true\".\n */\nexport const isResponsesApiUpload = (value?: boolean | string | null): boolean =>\n  value === true || value === 'true';\n\n/**\n * The name a file carries inside the code sandbox.\n *\n * Image uploads are converted to the configured output type while the record keeps the\n * original filename, so the extension has to follow the stored bytes or the sandbox\n * decoder is handed a mismatch. Provisioning and priming both resolve the mount path\n * from here: deriving it twice under different rules leaves a later turn advertising a\n * path that does not exist in the sandbox.\n */\nexport const resolveSandboxFilename = (filename: string, mimeType?: string | null): string => {\n  if (!mimeType?.startsWith('image/')) {\n    return filename;\n  }\n  const subtype = mimeType.slice('image/'.length);\n  if (!['webp', 'png', 'jpeg', 'gif'].includes(subtype)) {\n    return filename;\n  }\n  const accepted = subtype === 'jpeg' ? ['.jpg', '.jpeg'] : [`.${subtype}`];\n  const lastDot = filename.lastIndexOf('.');\n  const currentExt = lastDot > 0 ? filename.slice(lastDot).toLowerCase() : '';\n  if (accepted.includes(currentExt)) {\n    return filename;\n  }\n  const base = lastDot > 0 ? filename.slice(0, lastDot) : filename;\n  return `${base}${accepted[0]}`;\n};\n\n/**\n * The Responses setting a turn actually runs on. A saved agent's own record wins, since\n * execution reads its model parameters; a conversation only answers for itself. Upload\n * and delivery must agree here, or a document is stored as raw provider content and then\n * re-resolved to text it has no extraction for.\n */\nexport const resolveUseResponsesApi = (\n  agentValue?: boolean | null,\n  conversationValue?: boolean | null,\n): boolean | undefined => agentValue ?? conversationValue ?? undefined;\n\nexport const isBedrockDocumentType = (mimeType?: string): boolean =>\n  mimeType != null && mimeType in bedrockDocumentFormats;\n\n/** MIME types Bedrock's Converse document path can send to the model (mirrors `bedrockDocumentFormats`). */\nexport const bedrockDocumentMimeTypes: readonly string[] = Object.keys(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\n/** Textual `application/*` MIME types that can be decoded and sent as plain text */\nconst textualApplicationTypes = new Set([\n  'application/json',\n  'application/xml',\n  'application/yaml',\n  'application/sql',\n  'application/typescript',\n  'application/x-sh',\n  'application/csv',\n]);\n\n/**\n * MIME types the Anthropic Messages API accepts as a plain-text document source\n * (`source.type: 'text'`)\n */\nexport const isAnthropicTextDocumentType = (mimeType?: string): boolean =>\n  mimeType != null && (mimeType.startsWith('text/') || textualApplicationTypes.has(mimeType));\n\n/**\n * MIME types the Anthropic Messages API document path can send to the model\n * (mirrors `isBedrockDocumentType`): PDF via base64, textual types via a\n * plain-text document source. All other types are rejected with a provider 400.\n */\nexport const isAnthropicDocumentType = (mimeType?: string): boolean =>\n  mimeType === 'application/pdf' || isAnthropicTextDocumentType(mimeType);\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|calendar))$/;\n\nexport const applicationMimeTypes =\n  /^(application\\/(epub\\+zip|csv|json|msword|pdf|x-tar|x-sh|x-zip-compressed|typescript|sql|yaml|x-parquet|vnd\\.apache\\.parquet|vnd\\.coffeescript|vnd\\.openxmlformats-officedocument\\.(wordprocessingml\\.document|presentationml\\.(presentation|template)|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\\.openxmlformats-officedocument\\.presentationml\\.template$/,\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  /** .eml email files */\n  /^message\\/rfc822$/,\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  eml: 'message/rfc822', // .eml - Email message (RFC 822)\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  doc: 'application/msword', // .doc - Word (legacy)\n  docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx - Word\n  xls: 'application/vnd.ms-excel', // .xls - Excel (legacy)\n  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx - Excel\n  ppt: 'application/vnd.ms-powerpoint', // .ppt - PowerPoint (legacy)\n  pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx - PowerPoint\n  potx: 'application/vnd.openxmlformats-officedocument.presentationml.template', // .potx - PowerPoint template\n  ics: 'text/calendar', // .ics - iCalendar\n  ical: 'text/calendar', // .ical - iCalendar\n  ifb: 'text/calendar', // .ifb - iCalendar free/busy\n  icalendar: 'text/calendar', // .icalendar - iCalendar\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  'application/x-zip-compressed': 'application/zip',\n  'text/x-python-script': 'text/x-python',\n  'text/x-markdown': 'text/markdown',\n  /** freedesktop shared-mime-info (Chrome on Linux) */\n  'application/x-shellscript': 'application/x-sh',\n  /** libmagic, i.e. `file --mime-type` */\n  'text/x-shellscript': 'application/x-sh',\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|template))))$/,\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 defaultSkillImportSizeLimit = mbToBytes(50);\nconst defaultTokenLimit = 100000;\nconst defaultContextSizeLimit = mbToBytes(128);\nconst defaultContextCharLimit = 1_000_000;\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  skills: {\n    fileSizeLimit: defaultSkillImportSizeLimit,\n  },\n  serverFileSizeLimit: defaultSizeLimit,\n  avatarSizeLimit: mbToBytes(2),\n  fileTokenLimit: defaultTokenLimit,\n  fileContextSizeLimit: defaultContextSizeLimit,\n  fileContextCharLimit: defaultContextCharLimit,\n  clientImageResize: {\n    enabled: false,\n    maxWidth: 1900,\n    maxHeight: 1900,\n    quality: 0.92,\n    enforced: false,\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: RegexLike[] = supportedMimeTypes) {\n    return supportedTypes.some((regex) => regex.test(fileType));\n  },\n};\n\nconst supportedMimeTypesSchema = z.array(z.string()).optional();\n\nexport const DefaultLLMDeliveryPath = z.enum(['provider', 'text', 'none']);\nexport type TDefaultLLMDeliveryPath = z.infer<typeof DefaultLLMDeliveryPath>;\n\nexport const defaultLLMDeliveryPathSchema = z.object({\n  fallback: DefaultLLMDeliveryPath.optional(),\n  overrides: z.record(DefaultLLMDeliveryPath).optional(),\n});\nexport type TDefaultLLMDeliveryPathConfig = z.infer<typeof defaultLLMDeliveryPathSchema>;\ntype TDeliveryPathOverrides = NonNullable<TDefaultLLMDeliveryPathConfig['overrides']>;\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  defaultLLMDeliveryPath: defaultLLMDeliveryPathSchema.optional(),\n  legacyFileUploadUX: z.boolean().optional(),\n});\n\nconst skillFileConfigSchema = z.object({\n  fileSizeLimit: z.number().min(0).optional(),\n});\n\nexport const fileConfigSchema = z.object({\n  endpoints: z.record(endpointFileConfigSchema).optional(),\n  skills: skillFileConfigSchema.optional(),\n  serverFileSizeLimit: z.number().min(0).optional(),\n  avatarSizeLimit: z.number().min(0).optional(),\n  fileTokenLimit: z.number().min(0).optional(),\n  fileContextSizeLimit: z.number().min(0).optional(),\n  fileContextCharLimit: z.number().min(0).optional(),\n  codeEnvLivenessSafeWindowMs: 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(1).optional(),\n      maxHeight: z.number().min(1).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  defaultLLMDeliveryPath: defaultLLMDeliveryPathSchema.optional(),\n  legacyFileUploadUX: z.boolean().optional(),\n});\n\nexport type TFileConfig = z.infer<typeof fileConfigSchema>;\n\n/**\n * Compiler for admin-supplied MIME patterns. Defaults to native `RegExp`, which browser\n * builds keep so no extra dependency is bundled. The server swaps in a linear-time engine\n * via `setFileConfigRegexCompiler` so an admin-authored catastrophic-backtracking pattern\n * cannot ReDoS the shared event loop when tested against an uploaded file's MIME type.\n */\nlet compileMimeRegex: (pattern: string) => RegexLike = (pattern) => new RegExp(pattern);\n\n/** Override the MIME-pattern compiler; the server injects a linear-time engine at startup. */\nexport const setFileConfigRegexCompiler = (compile: (pattern: string) => RegexLike): void => {\n  compileMimeRegex = compile;\n};\n\n/** Returned when every configured pattern fails to compile, so consumers that read an empty\n *  allowlist as \"no restriction\" fail closed instead of allowing every file. */\nconst rejectAllMimeMatcher: RegexLike = { test: () => false };\n\n/** Helper function to safely convert string patterns to matcher objects */\nexport const convertStringsToRegex = (patterns: string[]): RegexLike[] => {\n  const compiled = patterns.reduce((acc: RegexLike[], pattern) => {\n    try {\n      acc.push(compileMimeRegex(pattern));\n    } catch (error) {\n      console.error(`Invalid regex pattern \"${pattern}\" skipped.`, error);\n    }\n    return acc;\n  }, [] as RegexLike[]);\n  // Every configured pattern was dropped. Return an explicit reject-all matcher so consumers that\n  // read an empty allowlist as \"no restriction\" fail closed instead of allowing every file.\n  if (patterns.length > 0 && compiled.length === 0) {\n    console.error(\n      `All ${patterns.length} MIME type pattern(s) were invalid and skipped; the resulting allowlist rejects every file.`,\n    );\n    return [rejectAllMimeMatcher];\n  }\n  return compiled;\n};\n\n/** Detects whether the given MIME type patterns accept all file types (e.g., `.*` or `.+`). */\nexport const isPermissiveMimeConfig = (types?: RegexLike[]): boolean => {\n  if (!types || types.length === 0) {\n    return false;\n  }\n  return types.some((regex) => regex.test('x-librechat/x-probe'));\n};\n\n/** The kind of content a provider upload path can actually send to the model. */\nexport type MimeUploadCategory = 'image' | 'document' | 'audio' | 'video';\n\n/** Describes what an upload path can send, used to scope a configured allowlist to selectable files. */\nexport interface MimeUploadCapability {\n  /** Content categories the path forwards to the model. */\n  categories: ReadonlyArray<MimeUploadCategory>;\n  /** When `document` is permitted, restrict document types to this set (e.g. Bedrock formats); default: all. */\n  documentMimeTypes?: readonly string[];\n}\n\n/** Media categories that collapse to a wildcard `accept` token when any member type is allowed. */\nconst mimeAcceptCategories: ReadonlyArray<{\n  category: Exclude<MimeUploadCategory, 'document'>;\n  token: string;\n  samples: readonly string[];\n  extras?: readonly string[];\n}> = [\n  {\n    /** Mirrors `imageMimeTypes` (+ the code-interpreter svg variants) so every accepted type is known. */\n    category: 'image',\n    token: 'image/*',\n    samples: [\n      'image/jpeg',\n      'image/gif',\n      'image/png',\n      'image/webp',\n      'image/heic',\n      'image/heif',\n      'image/svg',\n      'image/svg+xml',\n    ],\n    extras: ['.heif', '.heic'],\n  },\n  {\n    /** Mirrors `audioMimeTypes`. */\n    category: 'audio',\n    token: 'audio/*',\n    samples: [\n      'audio/mp3',\n      'audio/mpeg',\n      'audio/mpeg3',\n      'audio/wav',\n      'audio/wave',\n      'audio/x-wav',\n      'audio/ogg',\n      'audio/vorbis',\n      'audio/mp4',\n      'audio/m4a',\n      'audio/x-m4a',\n      'audio/flac',\n      'audio/x-flac',\n      'audio/webm',\n      'audio/aac',\n      'audio/wma',\n      'audio/opus',\n    ],\n  },\n  {\n    /** Mirrors `videoMimeTypes`. */\n    category: 'video',\n    token: 'video/*',\n    samples: [\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    ],\n  },\n];\n\n/** Document/text MIME types paired with the extension(s) browsers filter on in the file picker. */\nconst documentMimeExtensions: ReadonlyArray<readonly [string, readonly string[]]> = [\n  ['application/pdf', ['.pdf']],\n  ['application/msword', ['.doc']],\n  ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', ['.docx']],\n  ['application/vnd.ms-excel', ['.xls']],\n  ['application/msexcel', ['.xls']],\n  ['application/x-msexcel', ['.xls']],\n  ['application/x-ms-excel', ['.xls']],\n  ['application/x-excel', ['.xls']],\n  ['application/x-dos_ms_excel', ['.xls']],\n  ['application/xls', ['.xls']],\n  ['application/x-xls', ['.xls']],\n  ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ['.xlsx']],\n  ['application/vnd.ms-powerpoint', ['.ppt']],\n  ['application/vnd.openxmlformats-officedocument.presentationml.presentation', ['.pptx']],\n  ['application/vnd.openxmlformats-officedocument.presentationml.template', ['.potx']],\n  ['application/vnd.oasis.opendocument.text', ['.odt']],\n  ['application/vnd.oasis.opendocument.spreadsheet', ['.ods']],\n  ['application/vnd.oasis.opendocument.presentation', ['.odp']],\n  ['application/vnd.oasis.opendocument.graphics', ['.odg']],\n  ['application/rtf', ['.rtf']],\n  ['application/json', ['.json']],\n  ['application/xml', ['.xml']],\n  ['application/yaml', ['.yaml', '.yml']],\n  ['application/zip', ['.zip']],\n  ['application/x-zip-compressed', ['.zip']],\n  ['application/epub+zip', ['.epub']],\n  ['application/x-parquet', ['.parquet']],\n  ['application/vnd.apache.parquet', ['.parquet']],\n  ['text/csv', ['.csv']],\n  ['application/csv', ['.csv']],\n  ['text/tab-separated-values', ['.tsv']],\n  ['text/plain', ['.txt']],\n  ['text/markdown', ['.md']],\n  ['text/html', ['.html', '.htm']],\n  ['text/calendar', ['.ics']],\n  ['message/rfc822', ['.eml']],\n];\n\n/** Preferred extension for a known document MIME type, including its leading dot. */\nexport function getDocumentFileExtension(mimeType?: string): string | undefined {\n  const normalized = mimeType?.split(';', 1)[0].trim().toLowerCase();\n  const canonical = normalized === 'text/comma-separated-values' ? 'text/csv' : normalized;\n  return documentMimeExtensions.find(([type]) => type === canonical)?.[1][0];\n}\n\nconst documentMimeSet = new Set(documentMimeExtensions.map(([mimeType]) => mimeType));\n\n/** Every MIME type LibreChat may accept, used to detect patterns that reach beyond the representable set. */\nconst knownMimeUniverse: readonly string[] = Array.from(\n  new Set<string>([\n    ...fullMimeTypesList,\n    ...documentMimeExtensions.map(([mimeType]) => mimeType),\n    ...mimeAcceptCategories.flatMap((category) => category.samples),\n  ]),\n);\n\nconst categoryOf = (mimeType: string): MimeUploadCategory => {\n  if (mimeType.startsWith('image/')) {\n    return 'image';\n  }\n  if (mimeType.startsWith('audio/')) {\n    return 'audio';\n  }\n  if (mimeType.startsWith('video/')) {\n    return 'video';\n  }\n  return 'document';\n};\n\n/** Media types are covered by their `<cat>/*` wildcard token; document types need an explicit entry. */\nconst isRepresentable = (mimeType: string): boolean =>\n  categoryOf(mimeType) !== 'document' || documentMimeSet.has(mimeType);\n\n/**\n * Translates a finite MIME allowlist into a file-input `accept` string, intersected with what the\n * provider upload path can actually send. Returns `undefined` (keep the provider filter) when a\n * configured pattern matches a supported, path-handleable type that cannot be represented, so the\n * picker never hides a file the path would have accepted.\n */\nconst buildMimeAccept = (\n  types: RegexLike[],\n  { categories, documentMimeTypes }: MimeUploadCapability,\n): string | undefined => {\n  const permittedSet = new Set<MimeUploadCategory>(categories);\n  const documentAllowSet = documentMimeTypes ? new Set(documentMimeTypes) : null;\n  const emittedMedia = new Set<MimeUploadCategory>();\n  const emittedDocuments = new Set<string>();\n\n  /** A pattern matching nothing known may still accept a supported type we can't represent; fall back. */\n  const everyPatternKnown = types.every((regex) =>\n    knownMimeUniverse.some((mimeType) => regex.test(mimeType)),\n  );\n  if (!everyPatternKnown) {\n    return undefined;\n  }\n\n  for (const regex of types) {\n    for (const mimeType of knownMimeUniverse) {\n      if (!regex.test(mimeType)) {\n        continue;\n      }\n      const category = categoryOf(mimeType);\n      if (!permittedSet.has(category)) {\n        continue;\n      }\n      /** The path handles documents but drops this specific type (e.g. Bedrock ignores pptx/ODF). */\n      if (category === 'document' && documentAllowSet && !documentAllowSet.has(mimeType)) {\n        continue;\n      }\n      if (!isRepresentable(mimeType)) {\n        return undefined;\n      }\n      if (category === 'document') {\n        emittedDocuments.add(mimeType);\n      } else {\n        emittedMedia.add(category);\n      }\n    }\n  }\n\n  const tokens: string[] = [];\n  const seen = new Set<string>();\n  const push = (token: string): void => {\n    if (!seen.has(token)) {\n      seen.add(token);\n      tokens.push(token);\n    }\n  };\n\n  for (const category of mimeAcceptCategories) {\n    if (emittedMedia.has(category.category)) {\n      push(category.token);\n      category.extras?.forEach(push);\n    }\n  }\n\n  for (const [mimeType, extensions] of documentMimeExtensions) {\n    if (emittedDocuments.has(mimeType)) {\n      extensions.forEach(push);\n      push(mimeType);\n    }\n  }\n\n  return tokens.length > 0 ? tokens.join(',') : undefined;\n};\n\n/**\n * Resolves the file-input `accept` value for a configured `supportedMimeTypes` allowlist, scoped to\n * what the current upload path (`capability`) can send to the model.\n * - `undefined` for the built-in default or a config that can't be represented safely, so callers\n *   keep their provider-specific filter.\n * - `''` for permissive configs (e.g. `.*`), leaving the picker unrestricted.\n * - a translated `accept` string for a recognized finite allowlist (images, PDFs, Office docs, etc.).\n *\n * The picker `accept` is a UX convenience, not a security boundary: the backend still enforces\n * `supportedMimeTypes` on upload.\n */\nexport const getConfiguredMimeAccept = (\n  types: RegexLike[] | undefined,\n  capability: MimeUploadCapability,\n): string | undefined => {\n  /** Referential identity with the built-in list signals an unconfigured endpoint (keep provider filter). */\n  if (!types || types.length === 0 || types === supportedMimeTypes) {\n    return undefined;\n  }\n  if (isPermissiveMimeConfig(types)) {\n    return '';\n  }\n  return buildMimeAccept(types, capability);\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    defaultLLMDeliveryPath: mergeDeliveryPathConfig(\n      endpointConfig.defaultLLMDeliveryPath,\n      defaultConfig.defaultLLMDeliveryPath,\n    ),\n    legacyFileUploadUX: endpointConfig.legacyFileUploadUX ?? defaultConfig.legacyFileUploadUX,\n  };\n}\n\n/**\n * Deep-merges delivery-path config so an endpoint that supplies only one override\n * still inherits the default's fallback and shared overrides. Whole-object\n * replacement would silently drop the inherited routing.\n */\nfunction mergeDeliveryPathConfig(\n  endpointValue?: TDefaultLLMDeliveryPathConfig,\n  defaultValue?: TDefaultLLMDeliveryPathConfig,\n): TDefaultLLMDeliveryPathConfig | undefined {\n  if (!endpointValue) {\n    return defaultValue;\n  }\n  if (!defaultValue) {\n    return endpointValue;\n  }\n  /* An endpoint fallback terminates resolution after that endpoint's own overrides,\n   * so inheriting the lower layer's overrides would promote them above it. Only when\n   * the endpoint declares no fallback does resolution continue downward, and then the\n   * merged map reproduces the chain exactly: endpoint overrides, default overrides,\n   * default fallback. */\n  if (endpointValue.fallback != null) {\n    return endpointValue;\n  }\n  const hasOverrides = endpointValue.overrides != null || defaultValue.overrides != null;\n  return {\n    ...(defaultValue.fallback != null ? { fallback: defaultValue.fallback } : {}),\n    ...(hasOverrides\n      ? { overrides: { ...shadowByWildcard(defaultValue.overrides, endpointValue.overrides) } }\n      : {}),\n  };\n}\n\n/**\n * Flattens two override layers into one map that still resolves like the layered chain.\n * Resolution reads exact keys before wildcards, so a plain spread would let a lower\n * layer's `image/png` outrank the upper layer's `image/*`. Dropping the entries an\n * upper wildcard covers restores precedence without changing how lookups work.\n */\nfunction shadowByWildcard(\n  lower?: TDeliveryPathOverrides,\n  upper?: TDeliveryPathOverrides,\n): TDeliveryPathOverrides {\n  if (!lower) {\n    return { ...upper };\n  }\n  const upperWildcards = new Set<string>();\n  for (const key in upper) {\n    if (key.endsWith('/*')) {\n      upperWildcards.add(key.slice(0, -1));\n    }\n  }\n  if (upperWildcards.size === 0) {\n    return { ...lower, ...upper };\n  }\n  const retained: TDeliveryPathOverrides = {};\n  for (const key in lower) {\n    const isShadowed =\n      !key.endsWith('/*') &&\n      upperWildcards.has(key.slice(0, key.indexOf('/') + 1)) &&\n      upper?.[key] == null;\n    if (!isShadowed) {\n      retained[key] = lower[key];\n    }\n  }\n  return { ...retained, ...upper };\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: EndpointFileConfig = fileConfig.endpoints.default;\n  const globalDefaultConfig: EndpointFileConfig = {\n    ...baseDefaultConfig,\n    defaultLLMDeliveryPath: mergeDeliveryPathConfig(\n      mergedFileConfig.defaultLLMDeliveryPath,\n      baseDefaultConfig.defaultLLMDeliveryPath,\n    ),\n    legacyFileUploadUX: mergedFileConfig.legacyFileUploadUX ?? baseDefaultConfig.legacyFileUploadUX,\n  };\n  const userDefaultConfig = mergedFileConfig.endpoints.default;\n  const defaultConfig = userDefaultConfig\n    ? mergeWithDefault(userDefaultConfig, globalDefaultConfig, 'default')\n    : globalDefaultConfig;\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    skills: {\n      ...fileConfig.skills,\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.defaultLLMDeliveryPath !== undefined) {\n    mergedConfig.defaultLLMDeliveryPath = dynamic.defaultLLMDeliveryPath;\n  }\n\n  if (dynamic.legacyFileUploadUX !== undefined) {\n    mergedConfig.legacyFileUploadUX = dynamic.legacyFileUploadUX;\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  if (dynamic.fileContextSizeLimit !== undefined) {\n    mergedConfig.fileContextSizeLimit = mbToBytes(dynamic.fileContextSizeLimit);\n  }\n\n  if (dynamic.fileContextCharLimit !== undefined) {\n    mergedConfig.fileContextCharLimit = dynamic.fileContextCharLimit;\n  }\n\n  if (dynamic.skills?.fileSizeLimit !== undefined) {\n    mergedConfig.skills = {\n      ...mergedConfig.skills,\n      fileSizeLimit: mbToBytes(dynamic.skills.fileSizeLimit),\n    };\n  }\n\n  // Merge clientImageResize configuration; an admin-provided `enabled` overrides the user's setting\n  if (dynamic.clientImageResize !== undefined) {\n    mergedConfig.clientImageResize = {\n      ...mergedConfig.clientImageResize,\n      ...dynamic.clientImageResize,\n      enforced: dynamic.clientImageResize.enabled !== undefined,\n    };\n  }\n\n  if (dynamic.ocr !== undefined) {\n    const { supportedMimeTypes: ocrMimeTypes, ...ocrRest } = dynamic.ocr;\n    mergedConfig.ocr = {\n      ...mergedConfig.ocr,\n      ...ocrRest,\n    };\n    if (ocrMimeTypes) {\n      mergedConfig.ocr.supportedMimeTypes = convertStringsToRegex(ocrMimeTypes);\n    }\n  }\n\n  if (dynamic.text !== undefined) {\n    const { supportedMimeTypes: textMimeTypes, ...textRest } = dynamic.text;\n    mergedConfig.text = {\n      ...mergedConfig.text,\n      ...textRest,\n    };\n    if (textMimeTypes) {\n      mergedConfig.text.supportedMimeTypes = convertStringsToRegex(textMimeTypes);\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    if (dynamicEndpoint.defaultLLMDeliveryPath !== undefined) {\n      mergedEndpoint.defaultLLMDeliveryPath = dynamicEndpoint.defaultLLMDeliveryPath;\n    }\n\n    if (dynamicEndpoint.legacyFileUploadUX !== undefined) {\n      mergedEndpoint.legacyFileUploadUX = dynamicEndpoint.legacyFileUploadUX;\n    }\n  }\n\n  return mergedConfig;\n}\n","import type { StartupConfigContext } from './config';\nimport type { AssistantsEndpoint } from './schemas';\nimport { ResourceType } from './accessPermissions';\nimport * as q from './types/queries';\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`;\nexport const userPreferences = () => `${user()}/preferences`;\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`;\nexport const codeEnvironments = () => `${BASE_URL}/api/code-environments`;\nexport const codeEnvironmentPairings = () => `${codeEnvironments()}/pairings`;\nexport const codeEnvironmentById = (id: string) =>\n  `${codeEnvironments()}/${encodeURIComponent(id)}`;\nexport const codeEnvironmentSettings = (id: string) => `${codeEnvironmentById(id)}/settings`;\nexport const codeEnvironmentStatus = (id: string) => `${codeEnvironmentById(id)}/status`;\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 forkSharedMessages = (shareId: string) => `${shareRoot}/${shareId}/fork`;\nexport const sharedStartupConfig = (shareId: string) => `${shareMessages(shareId)}/config`;\nexport const getSharedLink = (conversationId: string) => `${shareRoot}/link/${conversationId}`;\nexport const getSharedLinks = (\n  pageSize: number,\n  sortBy: 'title' | 'createdAt',\n  sortDirection: 'asc' | 'desc',\n  search?: string,\n  cursor?: string,\n) => `${shareRoot}${buildQuery({ pageSize, sortBy, sortDirection, search, cursor })}`;\nexport const createSharedLink = (conversationId: string) => `${shareRoot}/${conversationId}`;\nexport const updateSharedLink = (shareId: string) => `${shareRoot}/${shareId}`;\n/** Share-scoped file routes: serve snapshotted files via shared-link permission. */\nexport const sharedFile = (shareId: string, fileId: string) =>\n  `${shareRoot}/${shareId}/files/${encodeURIComponent(fileId)}`;\nexport const sharedFileDownload = (shareId: string, fileId: string) =>\n  `${sharedFile(shareId, fileId)}/download`;\nexport const sharedFilePreview = (shareId: string, fileId: string) =>\n  `${sharedFile(shareId, fileId)}/preview`;\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 parentSubagents = (parentConversationId: string) =>\n  `${conversationsRoot}/${encodeURIComponent(parentConversationId)}/subagents`;\n\nexport const subagentThread = (\n  parentConversationId: string,\n  threadId: string,\n  taskId?: string,\n  cursor?: string,\n) => {\n  const endpoint = `${conversationsRoot}/${encodeURIComponent(parentConversationId)}/subagents/${encodeURIComponent(threadId)}`;\n  if (taskId != null) return `${endpoint}?taskId=${encodeURIComponent(taskId)}`;\n  return cursor == null ? endpoint : `${endpoint}?cursor=${encodeURIComponent(cursor)}`;\n};\n\nexport const subagentControl = (parentConversationId: string, threadId: string) =>\n  `${conversationsRoot}/${encodeURIComponent(parentConversationId)}/subagents/${encodeURIComponent(threadId)}/control`;\n\nexport const genTitle = (conversationId: string) =>\n  `${conversationsRoot}/gen_title/${encodeURIComponent(conversationId)}`;\n\nexport const updateConversation = () => `${conversationsRoot}/update`;\n\nexport const archiveConversation = () => `${conversationsRoot}/archive`;\nexport const archiveAllConversations = () => `${conversationsRoot}/archive/all`;\nexport const pinConversation = () => `${conversationsRoot}/pin`;\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 projectsRoot = `${BASE_URL}/api/projects`;\n\nexport const projects = (params: q.ProjectListParams = {}) => {\n  return `${projectsRoot}${buildQuery(params)}`;\n};\n\nexport const projectById = (id: string) => `${projectsRoot}/${encodeURIComponent(id)}`;\n\nexport const projectConversation = (conversationId: string) =>\n  `${projectsRoot}/conversations/${encodeURIComponent(conversationId)}`;\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 tokenConfig = () => `${BASE_URL}/api/endpoints/token-config`;\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 mcpOAuthStatus = (flowId: string) =>\n  `${BASE_URL}/api/mcp/oauth/status/${encodeURIComponent(flowId)}`;\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 = (context?: StartupConfigContext) =>\n  `${BASE_URL}/api/config${buildQuery({ context })}`;\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\nconst agentQueuedTurnsRoot = `${BASE_URL}/api/agents/chat/queued-turns`;\nexport const agentQueuedTurns = () => agentQueuedTurnsRoot;\nexport const agentQueuedTurnsByConversation = (\n  conversationId: string,\n  clientRequestIds: string[] = [],\n) => {\n  const uniqueIds = Array.from(new Set(clientRequestIds)).slice(0, 100);\n  const knownIds =\n    uniqueIds.length > 0\n      ? `&${uniqueIds.map((id) => `clientRequestIds=${encodeURIComponent(id)}`).join('&')}`\n      : '';\n  return `${agentQueuedTurnsRoot}?conversationId=${encodeURIComponent(conversationId)}${knownIds}`;\n};\nexport const agentQueuedTurn = (queuedTurnId: string) =>\n  `${agentQueuedTurnsRoot}/${encodeURIComponent(queuedTurnId)}`;\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}`;\n/* Deferred-preview lifecycle endpoint. Returns\n * `{ status, text?, textFormat?, previewError? }` so the frontend can\n * poll while background HTML extraction is in flight. See PR #12957. */\nexport const filePreview = (fileId: string) =>\n  `${BASE_URL}/api/files/${encodeURIComponent(fileId)}/preview`;\nexport const fileConfig = () => `${BASE_URL}/api/files/config`;\n/** Owner-scoped usage touch so queued attachments outlive the upload-window TTL. */\nexport const fileUsage = () => `${BASE_URL}/api/files/usage`;\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/* Scheduled chats */\nexport const schedules = () => `${BASE_URL}/api/schedules`;\nexport const schedule = (id: string) => `${schedules()}/${encodeURIComponent(id)}`;\nexport const runSchedule = (id: string) => `${schedule(id)}/run`;\n\n/* Skills */\nexport const skills = () => `${BASE_URL}/api/skills`;\nexport const importSkill = () => `${skills()}/import`;\n\nexport const getSkill = (id: string) => `${skills()}/${encodeURIComponent(id)}`;\n\nexport const listSkillsWithFilters = (\n  filter: Record<string, string | number | undefined | null>,\n) => {\n  const cleaned = Object.entries(filter).reduce(\n    (acc, [key, value]) => {\n      if (value !== undefined && value !== null && value !== '') {\n        acc[key] = String(value);\n      }\n      return acc;\n    },\n    {} as Record<string, string>,\n  );\n  const query =\n    Object.keys(cleaned).length > 0 ? `?${new URLSearchParams(cleaned).toString()}` : '';\n  return `${skills()}${query}`;\n};\n\nexport const skillFiles = (id: string) => `${getSkill(id)}/files`;\n\nexport const skillFile = (id: string, relativePath: string) =>\n  `${skillFiles(id)}/${encodeURIComponent(relativePath)}`;\n\nexport const insights = () => `${BASE_URL}/api/insights`;\nexport const insightsAccess = () => `${insights()}/access`;\n\n/* Conversation traces */\nexport const conversationTrace = (conversationId: string) =>\n  `${BASE_URL}/api/traces/${encodeURIComponent(conversationId)}`;\nexport const conversationTraceAvailability = (conversationId: string) =>\n  `${conversationTrace(conversationId)}/availability`;\nexport const conversationTraceRecords = (conversationId: string, cursor?: string) =>\n  `${conversationTrace(conversationId)}/records${\n    cursor ? `?${new URLSearchParams({ cursor }).toString()}` : ''\n  }`;\nexport const conversationTraceRecord = (\n  conversationId: string,\n  recordId: string,\n  messageId: string,\n  sourceId?: string,\n) =>\n  `${conversationTrace(conversationId)}/records/${encodeURIComponent(recordId)}?${new URLSearchParams(\n    { message: messageId, ...(sourceId ? { source: sourceId } : {}) },\n  ).toString()}`;\n\nexport const adminSkillsSync = () => `${BASE_URL}/api/admin/skills/sync`;\nexport const adminSkillsSyncStatus = () => `${adminSkillsSync()}/status`;\nexport const adminSkillsSyncRun = () => `${adminSkillsSync()}/run`;\nexport const adminSkillsSyncCredential = (credentialKey: string) =>\n  `${adminSkillsSync()}/credentials/${encodeURIComponent(credentialKey)}`;\n\n/**\n * Skill filesystem tree (phase 2). URL shape mirrors the original UI PR so\n * the tree hooks keep their call surface. `path` is pre-encoded by the\n * caller (e.g. `${nodeId}/content`).\n */\nexport const skillTree = ({ skillId, path = '' }: { skillId: string; path?: string }) => {\n  let url = `${BASE_URL}/api/skills/${encodeURIComponent(skillId)}/tree`;\n  if (path) {\n    url += `/${path}`;\n  }\n  return url;\n};\n\n/* Skill active states (per-user overrides) */\nexport const skillStates = () => `${BASE_URL}/api/user/settings/skills/active`;\n\n/* Langfuse connection (admin) */\nexport const adminLangfuseConnection = () => `${BASE_URL}/api/admin/langfuse/connection`;\nexport const adminLangfuseConnectionTest = () => `${adminLangfuseConnection()}/test`;\nexport const adminLangfuseSessionLink = (conversationId: string) =>\n  `${adminLangfuseConnection()}/session/${encodeURIComponent(conversationId)}`;\n\n/* Combined Pinned-section display order: favorite and pinned-chat entry keys interleaved. */\nexport const pinnedOrder = () => `${BASE_URL}/api/user/settings/pinned-order`;\n\n/* Tool favorites (starred marketplace items) */\nexport const toolFavorites = () => `${BASE_URL}/api/user/settings/favorites/tools`;\nexport const toolFavorite = (itemType: string, itemId: string) =>\n  `${toolFavorites()}/${itemType}/${encodeURIComponent(itemId)}`;\n\n/* Roles */\nexport const roles = () => `${BASE_URL}/api/roles`;\nexport const adminRoles = () => `${BASE_URL}/api/admin/roles`;\nexport const getRole = (roleName: string) => `${roles()}/${encodeURIComponent(roleName)}`;\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`;\nexport const updateSkillPermissions = (roleName: string) => `${getRole(roleName)}/skills`;\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, agentId?: string) =>\n  `${memories()}/${encodeURIComponent(key)}${agentId ? `?agentId=${encodeURIComponent(agentId)}` : ''}`;\nexport const memoryById = (id: string, agentId?: string) =>\n  `${memories()}/id/${encodeURIComponent(id)}${agentId ? `?agentId=${encodeURIComponent(agentId)}` : ''}`;\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 type { TDefaultLLMDeliveryPathConfig } from '../file-config';\nimport type { CodeEnvRef, CodeEnvRefMap } from '../codeEnvRef';\nimport { 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  cloudfront = 'cloudfront',\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  run_artifact = 'run_artifact',\n  skill_file = 'skill_file',\n  filename = 'filename',\n  updatedAt = 'updatedAt',\n  source = 'source',\n  filterSource = 'filterSource',\n  context = 'context',\n  bytes = 'bytes',\n}\n\n/** Structural type for a compiled matcher: a native `RegExp` or a linear-time engine both satisfy it. Only `test` is ever called on `supportedMimeTypes`. */\nexport type RegexLike = { test(input: string): boolean };\n\nexport type EndpointFileConfig = {\n  disabled?: boolean;\n  fileLimit?: number;\n  fileSizeLimit?: number;\n  totalSizeLimit?: number;\n  supportedMimeTypes?: RegexLike[];\n  defaultLLMDeliveryPath?: TDefaultLLMDeliveryPathConfig;\n  legacyFileUploadUX?: boolean;\n};\n\nexport type FileConfig = {\n  endpoints: {\n    [key: string]: EndpointFileConfig;\n  };\n  skills?: {\n    fileSizeLimit?: number;\n  };\n  fileTokenLimit?: number;\n  /** Maximum aggregate model-bound attachment bytes admitted into one agent turn. */\n  fileContextSizeLimit?: number;\n  /** Maximum aggregate extracted-text characters admitted into one agent turn. */\n  fileContextCharLimit?: number;\n  serverFileSizeLimit?: number;\n  avatarSizeLimit?: number;\n  clientImageResize?: {\n    enabled?: boolean;\n    maxWidth?: number;\n    maxHeight?: number;\n    quality?: number;\n    /** Set when `enabled` came from the admin config, in which case it wins over the user's setting */\n    enforced?: boolean;\n  };\n  ocr?: {\n    supportedMimeTypes?: RegexLike[];\n  };\n  text?: {\n    supportedMimeTypes?: RegexLike[];\n  };\n  stt?: {\n    supportedMimeTypes?: RegexLike[];\n  };\n  checkType?: (fileType: string, supportedTypes: RegexLike[]) => boolean;\n  defaultLLMDeliveryPath?: TDefaultLLMDeliveryPathConfig;\n  legacyFileUploadUX?: boolean;\n};\n\nexport type FileConfigInput = {\n  endpoints?: {\n    [key: string]: EndpointFileConfig;\n  };\n  skills?: {\n    fileSizeLimit?: number;\n  };\n  serverFileSizeLimit?: number;\n  avatarSizeLimit?: number;\n  fileContextSizeLimit?: number;\n  fileContextCharLimit?: 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: RegexLike[]) => boolean;\n  defaultLLMDeliveryPath?: TDefaultLLMDeliveryPathConfig;\n  legacyFileUploadUX?: boolean;\n};\n\n/** The immutable origin of a file explicitly published from an agent execution. */\nexport type RunFileProvenance = {\n  runId: string;\n  executionId: string;\n  agentId: string;\n  parentExecutionId?: string;\n  parentAgentId?: string;\n  recipientAgentIds?: string[];\n  sourceFileId: string;\n  publishedAt: string;\n  inputFileIds: string[];\n};\n\nexport type TFile = {\n  _id?: string;\n  __v?: number;\n  user: string;\n  tenantId?: string;\n  storageRegion?: string;\n  storageKey?: 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  text?: string;\n  /**\n   * Format of the `text` field. `'html'` means the backend produced\n   * a sanitized full-document HTML preview the client may inject as\n   * `index.html` inside the office artifact iframe. `'text'` (or\n   * `undefined` for legacy records) is plain text and MUST NOT be\n   * injected as HTML — render through the markdown/escaping path.\n   * See Codex P1 review on PR #12934.\n   */\n  textFormat?: 'html' | 'text' | null;\n  /**\n   * Lifecycle of the inline preview rendered from `text`. `'pending'`\n   * while background HTML extraction is in flight (deferred-preview\n   * code-execution flow), `'ready'` once `text`/`textFormat` are set,\n   * `'failed'` if extraction errored or hit the 60s ceiling. `undefined`\n   * for legacy records and for files that never expect a preview —\n   * clients MUST treat that as `'ready'`.\n   */\n  status?: 'pending' | 'ready' | 'failed';\n  /**\n   * Short machine-readable failure reason when `status === 'failed'`.\n   * Suitable for tooltip text but not user-facing prose.\n   */\n  previewError?: string;\n  metadata?: {\n    runFile?: RunFileProvenance;\n    fileIdentifier?: string;\n    /**\n     * Structured form of `fileIdentifier`. Persisted alongside the\n     * legacy string during the dual-write transition; readers should\n     * resolve via `resolveCodeEnvRef`.\n     */\n    codeEnvRef?: CodeEnvRef;\n    codeEnvRefs?: CodeEnvRefMap;\n    /** Dispatch-order stamp for the current source artifact generation. */\n    sourceDispatchedAt?: number;\n    /** Vector namespaces this file has been embedded into. */\n    embeddedEntities?: string[];\n    /** The user named this destination, so absent ones were declined. */\n    destinationChosen?: boolean;\n    /** The type the delivery route was resolved against, when conversion changed it. */\n    routingMimeType?: string;\n  };\n  llmDeliveryPath?: 'provider' | 'text' | 'none';\n  createdAt?: string | Date;\n  updatedAt?: string | Date;\n};\n\nexport type TFileUpload = TFile & {\n  temp_file_id: string;\n};\n\n/**\n * Shape returned by `GET /api/files/:file_id/preview`. The deferred-\n * preview code-execution flow polls this until status is terminal:\n *   - `pending`: HTML extraction is still running. No `text`.\n *   - `ready`: extraction succeeded; `text` + `textFormat` populated\n *     iff the file produced inline preview content (binary/oversized\n *     files reach `ready` with no text — render download-only).\n *   - `failed`: extraction errored or hit the 60s ceiling;\n *     `previewError` carries the short reason (`timeout`,\n *     `parser-error`, `orphaned`, etc.).\n *\n * Legacy records pre-dating the field are surfaced as `'ready'` server-\n * side so existing attachments keep rendering normally.\n */\nexport type TFilePreview = {\n  file_id: string;\n  status: 'pending' | 'ready' | 'failed';\n  text?: string;\n  textFormat?: 'html' | 'text' | null;\n  previewError?: string;\n};\n\nexport type AvatarUploadResponse = {\n  url: string;\n};\n\nexport type FileDownloadURLResponse = {\n  url: string;\n  filename: string;\n  type: string;\n  metadata: Partial<TFile>;\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 TFilesUsageBody = {\n  file_ids: string[];\n};\n\nexport type TFilesUsageResponse = {\n  /** Count of queued uploads whose TTL hold was extended. */\n  held: number;\n};\n\nexport type DeleteFilesResponse = {\n  message: string;\n  result?: Record<string, unknown>;\n  deletedFileIds?: string[];\n  failedFileIds?: string[];\n};\n\nexport type BatchFile = {\n  file_id: string;\n  filepath: string;\n  storageRegion?: string;\n  storageKey?: 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  /** Suppresses the result toasts. Background cleanup runs on a timer the user never asked for,\n   * and a storage failure that keeps failing would otherwise announce itself on every retry. */\n  silent?: boolean;\n};\n","/* eslint-disable @typescript-eslint/no-namespace */\nimport type { TTokenUsageEvent, TContextUsageEvent, TPendingSteer } from './runs';\nimport type { TAttachment, TPlugin } from 'src/schemas';\nimport type { SummaryContentPart } from './assistants';\nimport { StepTypes, ContentTypes, ToolCallTypes } from './runs';\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; optional literal\n     *  form included to mirror langchain's ToolCall, whose `type` is optional. */\n    type?: ToolCallTypes.TOOL_CALL | 'tool_call';\n    /** The name of the tool to be called */\n    name: string;\n    /** Host-derived MCP server identity retained to disambiguate historical tool keys. */\n    mcpServerName?: 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    /** Host run-step identity; unlike provider ids, this is unique across turns. */\n    stepId?: string;\n    /** If provided, the output of the tool call */\n    output?: string;\n    /** Host-owned durable receipt for a detached ordinary tool result.\n     * It lives beside the original call so reload, manual collection, and\n     * automatic continuation all arbitrate the same result identity. */\n    backgroundTask?: {\n      version: 1;\n      taskId: string;\n      toolName: string;\n      status: 'completed' | 'error';\n      /** Additive rolling-deploy-compatible cancellation discriminator. */\n      cancelled?: true;\n      settledAt: Date;\n      resultClaim?: {\n        kind: 'manual' | 'wakeup';\n        claimId: string;\n        claimedAt: Date;\n        /** Response generation that owns a manual delivery claim. */\n        generationId?: string;\n      };\n    };\n    /** The tool call was rejected before execution because its input failed schema validation. */\n    inputValidationError?: true;\n    /** Auth URL */\n    auth?: string;\n    /** Expiration time */\n    expires_at?: number;\n    /**\n     * When set, this tool call is paused for human review.\n     * The presence of this field signals the UI to render approval controls\n     * instead of the in-flight tool execution state.\n     */\n    approval?: {\n      actionId: string;\n      allowed_decisions: ToolApprovalDecisionType[];\n      description?: string;\n    };\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    /** Optional to mirror the agents SDK, which omits usage until a step reports it. */\n    usage?: null | object;\n    /** Epoch ms the step was opened. Emitted by `@librechat/agents` >= 3.4.6. */\n    created_at?: number;\n    status?: RunStepStatus;\n  };\n\n  /** Lifecycle status of a run step. `in_progress` until a terminal close. */\n  export type RunStepStatus = 'in_progress' | 'completed' | 'cancelled' | 'failed';\n\n  /** Terminal status a run step can close with. */\n  export type RunStepClosedStatus = Exclude<RunStepStatus, 'in_progress'>;\n\n  /**\n   * Payload of {@link StepEvents.ON_RUN_STEP_CLOSED}. Emitted once per step\n   * when it reaches a terminal state, including steps swept at end-of-run\n   * because the caller aborted — which is the only signal that distinguishes\n   * a stopped step from one still in flight.\n   */\n  export type RunStepClosedEvent = {\n    id: string;\n    index: number;\n    type: StepTypes;\n    status: RunStepClosedStatus;\n    /** Epoch ms the step was opened, when the emitter knows it. */\n    created_at?: number;\n    /** Epoch ms the step reached its terminal state. */\n    closed_at: number;\n    runId?: string;\n    agentId?: string;\n    groupId?: number;\n    stepIndex?: number;\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    /** Skill selections on the turn, carried so a HITL-resumed turn's reconstructed\n     *  requestMessage keeps its skill pills (they aren't on the DB row the client refetches\n     *  until reload). */\n    manualSkills?: string[];\n    alwaysAppliedSkills?: string[];\n  }\n\n  /** Client-safe state for one MCP authorization prompt that remains actionable. */\n  export interface PendingMCPOAuthPrompt {\n    stepId: string;\n    runId?: string;\n    index: number;\n    toolCallId?: string;\n    toolName: string;\n    authURL: string;\n    expiresAt?: number;\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    /** True when the live generation replaces an existing assistant branch. */\n    isRegenerate?: boolean;\n    conversationId?: string;\n    sender?: string;\n    iconURL?: string;\n    model?: string;\n    titleEvent?: {\n      event: 'title';\n      data?: {\n        conversationId?: string;\n        title?: string;\n      };\n    };\n    replayEvents?: Array<{\n      event: string;\n      data?: unknown;\n      [key: string]: unknown;\n    }>;\n    /** Pending MCP authorization prompts projected from durable stream state. */\n    pendingOAuthPrompts?: PendingMCPOAuthPrompt[];\n    /** Cumulative provider-reported usage for the run; backfills usage totals on resume */\n    collectedUsage?: TTokenUsageEvent[];\n    /** Latest context window snapshot; restores the usage gauge on resume */\n    contextUsage?: TContextUsageEvent;\n    /**\n     * Live pending approval when the run is paused for human review. Carried in\n     * the resume contract (not just /chat/status) so a reloading or\n     * cross-replica client can rebuild and render the prompt from `resumeState`.\n     */\n    pendingAction?: PendingAction;\n    /**\n     * Steers queued server-side but not yet injected into the run. Injected\n     * steers already live inside `aggregatedContent`; these are the remainder,\n     * so a reconnecting client can rebuild its pending-steer chips.\n     */\n    pendingSteers?: TPendingSteer[];\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      /** Provider content kind and Open Responses semantic text channel. */\n      content_type?: 'text' | 'think';\n      phase?: 'commentary' | 'final_answer';\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    /** Approval metadata, set when a tool call is paused for human review. */\n    approval?: {\n      actionId: string;\n      allowed_decisions: ToolApprovalDecisionType[];\n      description?: string;\n    };\n  };\n  /**\n   * Mirrors the agents SDK's function tool-call variant: `arguments` may arrive as a\n   * parsed object, and `output` is attached by LibreChat aggregation only once available\n   * (the legacy assistants `FunctionToolCall` requires both as string/present).\n   */\n  export type AgentFunctionToolCall = {\n    id: string;\n    type: 'function';\n    function: {\n      name: string;\n      arguments: string | object;\n      output?: string | null;\n    };\n  };\n\n  export type AgentToolCall = AgentFunctionToolCall | ToolCall;\n\n  /**\n   * Human-in-the-loop interrupt categories. The discriminator on\n   * {@link HumanInterruptPayload}.\n   *\n   * - `tool_approval`: agent paused before executing one or more tools; user\n   *   approves / rejects / edits each call.\n   * - `ask_user_question`: agent invoked the `AskUserQuestion` tool to gather\n   *   clarification; user replies with free-form text (or selects an option).\n   *\n   * `tool_approval` is a permission gate; `ask_user_question` is a clarification\n   * channel — they share the {@link PendingAction} envelope but have different\n   * UI affordances and resume payloads.\n   */\n  export type HumanInterruptType = 'tool_approval' | 'ask_user_question';\n\n  /** String enum of decision kinds the user can make on a paused tool call. */\n  export type ToolApprovalDecisionType = 'approve' | 'reject' | 'edit' | 'respond';\n\n  /**\n   * One pending tool execution awaiting user review.\n   * Field naming mirrors LangChain HumanInterrupt's `ActionRequest`.\n   */\n  export interface ToolApprovalRequest {\n    /** Tool name as registered with the agent */\n    name: string;\n    /** Sanitized arguments (no auth tokens / file blobs). May be string or parsed object. */\n    arguments: string | Record<string, unknown>;\n    /** Provider tool_call_id linking this request to the model's tool_use block */\n    tool_call_id: string;\n    /** Optional human-readable description shown alongside the prompt */\n    description?: string;\n    /** Server-authored provenance. Absent for user, MCP, action, and older tool calls. */\n    source?: 'librechat_code';\n  }\n\n  /**\n   * Per-call review configuration: which decisions the user is allowed to make.\n   *\n   * `tool_call_id` (NOT `action_name`) is the join key against\n   * {@link ToolApprovalRequest.tool_call_id}. By-position mapping breaks the\n   * moment a single batch contains the same tool called twice — e.g. a model\n   * fanning out two `mcp:server:search` calls in parallel — so always join\n   * by `tool_call_id`. `action_name` is retained for display only.\n   */\n  export interface ToolReviewConfig {\n    action_name: string;\n    tool_call_id: string;\n    allowed_decisions: ToolApprovalDecisionType[];\n  }\n\n  /** Interrupt payload for a tool-approval pause. */\n  export interface ToolApprovalInterruptPayload {\n    type: 'tool_approval';\n    action_requests: ToolApprovalRequest[];\n    review_configs: ToolReviewConfig[];\n  }\n\n  /** A selectable answer for an ask-user-question prompt. */\n  export interface AskUserQuestionOption {\n    label: string;\n    value: string;\n  }\n\n  /** The question itself: free-form prompt with optional curated answers. */\n  export interface AskUserQuestionRequest {\n    question: string;\n    /** Optional descriptive context for the prompt; mirrors the SDK field. */\n    description?: string;\n    options?: AskUserQuestionOption[];\n    /** When true the user may pick several options; the answer is their\n     *  selected option values joined with \", \". */\n    multiSelect?: boolean;\n  }\n\n  /** One independently answerable question in a batched clarification. */\n  export interface AskUserQuestionBatchItem extends AskUserQuestionRequest {\n    /** Batch-unique identifier used to map the submitted answer. */\n    id: string;\n    /** Optional short heading rendered above the question. */\n    header?: string;\n  }\n\n  /** Input shape for one tool call that asks several related questions. */\n  export interface AskUserQuestionsRequest {\n    questions: AskUserQuestionBatchItem[];\n  }\n\n  /** Interrupt payload for an ask-user-question pause. */\n  export interface AskUserQuestionInterruptPayload {\n    type: 'ask_user_question';\n    question: AskUserQuestionRequest;\n    /** Present for a batched clarification; `question` remains the first-item fallback. */\n    questions?: AskUserQuestionBatchItem[];\n    /**\n     * The ask tool call that raised this interrupt (mirrors the SDK field,\n     * present from `@librechat/agents` > 3.3.8). Lets the question/answer\n     * stamps target the exact tool-call part instead of guessing by\n     * position when a model emits several ask calls in one turn.\n     */\n    tool_call_id?: string;\n  }\n\n  /**\n   * Discriminated by `type`. Mirrors `@librechat/agents`'s `HumanInterruptPayload`\n   * so the SDK's `Run.getInterrupt()` output can be embedded directly.\n   */\n  export type HumanInterruptPayload =\n    | ToolApprovalInterruptPayload\n    | AskUserQuestionInterruptPayload;\n\n  /**\n   * Server-side record of a job that is waiting for user input.\n   * Persisted with the job; consumed by approval routes and the status endpoint.\n   */\n  export interface PendingAction {\n    /** Stable identifier used in approval URLs */\n    actionId: string;\n    streamId: string;\n    conversationId?: string;\n    /** Stable per-turn identifier (LangGraph checkpoint_ns) when available */\n    runId?: string;\n    responseMessageId?: string;\n    payload: HumanInterruptPayload;\n    createdAt: number;\n    /** Optional expiry; clients should treat past `expiresAt` as stale */\n    expiresAt?: number;\n    /**\n     * SDK interrupt id (`RunInterruptResult.interruptId`). Persisted so a\n     * cross-process resume can correlate the decision with the LangGraph\n     * interrupt after the original `Run` object is gone.\n     */\n    interruptId?: string;\n    /**\n     * LangGraph `thread_id` the run was bound to (`RunInterruptResult.threadId`).\n     * Required, with the checkpointer, to rebuild `Command({ resume })` on a\n     * worker that didn't originate the run.\n     */\n    threadId?: string;\n    /**\n     * Fingerprint of the request fields that determine the agent/graph + tool set\n     * (endpoint, agent_id, model, spec, ephemeralAgent), captured at pause time. The\n     * resume route recomputes it from the resume request and rejects a mismatch — the\n     * guard that catches an ephemeral-agent config swap, where `agent_id` is undefined\n     * so the id check can't.\n     */\n    requestFingerprint?: string;\n    /** Current-version fingerprint; server-only and omitted from client projections. */\n    requestFingerprintV2?: string;\n    /**\n     * Graph-determining request fields (endpoint, agent_id, model, spec, promptPrefix,\n     * ephemeralAgent) captured at pause. The resume route REPLAYS these onto the request\n     * before rebuilding the run, so a reload/cross-replica resume — where the client can\n     * no longer reconstruct the ephemeral config — still rebuilds the same agent/graph.\n     */\n    resumeContext?: Record<string, unknown>;\n    /**\n     * Opaque, server-only identity of the stateful code targets selected when a\n     * tool approval paused. Resume rejects a changed target before provider or\n     * tool execution so an approval cannot migrate to another VM or workspace.\n     */\n    codeExecutionBinding?: CodeExecutionApprovalBinding;\n  }\n\n  export interface CodeExecutionApprovalTargetBinding {\n    /** Agent identity when available; anonymous ephemeral agents use null. */\n    agentId: string | null;\n    /** SHA-256 of the resolved route, worker and runtime-session identity. */\n    targetHash: string;\n  }\n\n  export interface CodeExecutionApprovalBinding {\n    version: 1;\n    targets: CodeExecutionApprovalTargetBinding[];\n  }\n\n  /**\n   * Scope of a tool-approval decision — drives the \"remember this\" persistence\n   * envelope. Storage of session/always decisions is a Slice B+ concern; the\n   * field is on the wire today so route signatures don't break later.\n   */\n  export type DecisionScope = 'once' | 'session' | 'always';\n\n  /**\n   * Per-tool decision returned from the approval UI.\n   * Wire format. The host adapts each entry to the SDK's discriminated\n   * `ToolApprovalDecision` (e.g. `{ type: 'edit', updatedInput }`) at the resume route.\n   *\n   * Constraints:\n   * - `editedArguments` is required when `decision === 'edit'`.\n   * - `responseText` is required when `decision === 'respond'`.\n   * - `reason` is optional metadata; useful for reject/edit audit trails.\n   * - `scope` defaults to `'once'`.\n   */\n  export interface ToolApprovalResolution {\n    tool_call_id: string;\n    decision: ToolApprovalDecisionType;\n    editedArguments?: Record<string, unknown>;\n    responseText?: string;\n    reason?: string;\n    scope?: DecisionScope;\n  }\n\n  /** Wire format for an ask-user-question response. */\n  export interface AskUserQuestionResolution {\n    answer: string;\n  }\n\n  /** Wire format for a batched ask-user-question response. */\n  export interface AskUserQuestionsResolution {\n    answers: Record<string, string>;\n  }\n\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   * The callback receives a minimal structural view of the run's messages (data-provider\n   * cannot depend on langchain's BaseMessage): every langchain message satisfies\n   * `{ content: unknown }`, and callbacks typed against richer structural message shapes\n   * remain assignable. The promise branch mirrors the agents SDK signature exactly —\n   * widening it (e.g. to `Promise<string | undefined>`) would break assignability of\n   * stored edges into the SDK's `GraphEdge`.\n   */\n  prompt?:\n    | string\n    | ((\n        messages: { content: unknown }[],\n        runStartIndex: number,\n      ) => string | Promise<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\n/**\n * Upper bound on a stored MCP `iconPath` (URL or data URI). Enforced by\n * `sanitizeMcpIconPath`, not a schema `.max()`, so re-submitting a server whose\n * stored icon predates the cap clears the icon instead of rejecting the update.\n */\nexport const MAX_MCP_ICON_PATH_LENGTH = 256 * 1024;\n\nconst validateOAuthClientCredentials = (\n  oauth: {\n    client_id?: string;\n    client_secret?: string;\n    authorization_url?: string;\n    token_url?: string;\n  },\n  ctx: z.RefinementCtx,\n): void => {\n  if (oauth.client_secret && !oauth.client_id) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      path: ['client_secret'],\n      message: 'OAuth client_secret requires client_id',\n    });\n  }\n\n  if (oauth.client_id && oauth.client_secret && (!oauth.authorization_url || !oauth.token_url)) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      path: ['client_secret'],\n      message: 'OAuth client_secret with client_id requires both authorization_url and token_url',\n    });\n  }\n};\n\nconst OAuthOptionsBaseSchema = z.object({\n  /** OAuth authorization endpoint (optional - can be auto-discovered) */\n  authorization_url: z\n    .string()\n    .transform((val) => extractEnvVariable(val))\n    .pipe(z.string().url())\n    .optional(),\n  /** OAuth token endpoint (optional - can be auto-discovered) */\n  token_url: z\n    .string()\n    .transform((val) => extractEnvVariable(val))\n    .pipe(z.string().url())\n    .optional(),\n  /** OAuth client ID (optional - can use dynamic registration) */\n  client_id: z.string().optional(),\n  /** OAuth client secret (requires explicit authorization and token endpoints) */\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\n    .string()\n    .transform((val) => extractEnvVariable(val))\n    .pipe(z.string().url())\n    .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  /**\n   * Auth0/Cognito-style `audience` parameter. Authorization servers that pre-date\n   * RFC 8707 — most prominently Auth0 — issue API-scoped access tokens only when\n   * the `/authorize` request advertises an `audience`. RFC 8707 `resource` (set\n   * automatically from Protected Resource Metadata) is the standards-conformant\n   * route; `audience` covers the providers that ignore it.\n   *\n   * When set, the value is forwarded as-is on `/authorize` (both pre-configured\n   * and DCR-discovered paths). Whether it is also forwarded on the\n   * `refresh_token` grant is controlled by `forward_audience_on_refresh` below.\n   *\n   * The `authorization_code` exchange intentionally never receives `audience` —\n   * Auth0 binds audience from the original `/authorize` request and embeds it\n   * in the issued access token; sending it again is redundant.\n   *\n   * No canonicalization is applied — the audience identifier is provider-defined\n   * and may differ from the MCP server URL. This field is only accepted from\n   * trusted/admin MCP configuration and is rejected from user-managed servers.\n   */\n  audience: z.string().min(1).optional(),\n  /**\n   * Whether to also forward `audience` on the `refresh_token` grant body.\n   *\n   * Default: `true`. Required for Auth0, which strips the API audience from\n   * refreshed access tokens unless `audience` is re-supplied on every refresh\n   * — without it the next MCP call 401s once the initial access token expires.\n   *\n   * Set to `false` for providers that document refresh requests as\n   * `grant_type` + `client_id` + `refresh_token` only (Cognito and other\n   * strict OAuth 2.0 token endpoints). Those providers maintain the original\n   * `aud` claim across refreshes when the initial token was resource-bound,\n   * so the extra parameter is redundant and may be rejected as\n   * `invalid_request`.\n   *\n   * Ignored when `audience` itself is not configured.\n   */\n  forward_audience_on_refresh: z.boolean().optional(),\n  /** OAuth revocation endpoint (optional - can be auto-discovered) */\n  revocation_endpoint: z\n    .string()\n    .transform((val) => extractEnvVariable(val))\n    .pipe(z.string().url())\n    .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\nconst OAuthOptionsSchema = OAuthOptionsBaseSchema.superRefine(validateOAuthClientCredentials);\n\nconst BLOCKED_USER_OAUTH_ENDPOINT_PARAMS = ['audience', 'resource'] as const;\nconst envVarPattern = /\\$\\{[^}]+\\}/;\n\nconst userOAuthEndpointUrlSchema = 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(\n    (value) => {\n      try {\n        const { searchParams } = new URL(value);\n        return BLOCKED_USER_OAUTH_ENDPOINT_PARAMS.every((param) => !searchParams.has(param));\n      } catch {\n        return true;\n      }\n    },\n    { message: 'OAuth endpoint URLs cannot include audience or resource query parameters' },\n  );\n\nconst UserOAuthOptionsSchema = OAuthOptionsBaseSchema.omit({\n  audience: true,\n  forward_audience_on_refresh: true,\n})\n  .extend({\n    authorization_url: userOAuthEndpointUrlSchema.optional(),\n    token_url: userOAuthEndpointUrlSchema.optional(),\n    redirect_uri: userOAuthEndpointUrlSchema.optional(),\n    revocation_endpoint: userOAuthEndpointUrlSchema.optional(),\n    audience: z.never().optional(),\n    forward_audience_on_refresh: z.never().optional(),\n  })\n  .superRefine(validateOAuthClientCredentials);\n\nconst OboOptionsSchema = z.object({\n  /** Scopes to request for the downstream MCP server (e.g., \"api://<client-id>/Mcp.Tools.ReadWrite\") */\n  scopes: z.string().min(1),\n});\n\nexport const MCP_SERVER_TITLE_PATTERN = new RegExp(\n  \"^[\\\\p{L}\\\\p{N}][\\\\p{L}\\\\p{N}\\\\p{M}'’ -]*$\",\n  'u',\n);\nexport const MCP_SERVER_TITLE_ERROR =\n  'Title must start with a letter or number and can include spaces, hyphens, and apostrophes';\n\nconst BaseOptionsSchema = z.object({\n  /** Display name for the MCP server */\n  title: z.string().regex(MCP_SERVER_TITLE_PATTERN, MCP_SERVER_TITLE_ERROR).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().int().nonnegative().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().int().positive().optional(),\n  initTimeout: z.number().int().nonnegative().optional(),\n  /**\n   * Whether the server is offered in chat.\n   *\n   * `false` hides it from the chat dropdown (MCPSelect) AND bars it from the\n   * chat selection a request carries, so a stale or hand-written request cannot\n   * reach it either. It does not restrict agents, nor a server a model spec\n   * pins through `mcpServers` — both are the operator's own choice.\n   */\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 confidential clients must pin both OAuth endpoints\n   */\n  oauth: OAuthOptionsSchema.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         * Whether the field holds a secret and should be masked in the UI.\n         * Defaults to masked when omitted; set to `false` for non-secret setup\n         * values (e.g. username, project key, base URL) to render as plain text.\n         */\n        sensitive: z.boolean().optional(),\n      }),\n    )\n    .optional(),\n});\n\nconst ProxyUrlSchema = 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 (\n        protocol === 'http:' ||\n        protocol === 'https:' ||\n        protocol === 'socks:' ||\n        protocol === 'socks5:'\n      );\n    },\n    {\n      message: 'Proxy URL must use http://, https://, socks://, or socks5://',\n    },\n  );\n\nconst PROCESS_MCP_SERVER_FIELDS = new Set(['command', 'args', 'env', 'cwd', 'stderr']);\n\nexport function isProcessMCPServerField(field: string): boolean {\n  return PROCESS_MCP_SERVER_FIELDS.has(field);\n}\n\nexport function isProcessMCPServerConfig(value: unknown): boolean {\n  if (value == null || typeof value !== 'object' || Array.isArray(value)) {\n    return false;\n  }\n\n  const config = value as Record<string, unknown>;\n  if (config.type === 'stdio') {\n    return true;\n  }\n\n  return Object.keys(config).some(isProcessMCPServerField);\n}\n\nexport function hasProcessMCPServerConfig(value: unknown): boolean {\n  if (value == null || typeof value !== 'object' || Array.isArray(value)) {\n    return false;\n  }\n\n  return Object.values(value).some(isProcessMCPServerConfig);\n}\n\nexport const StdioOptionsSchema = BaseOptionsSchema.extend({\n  type: z.literal('stdio').default('stdio'),\n  obo: z.undefined().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.\n   * Accepts: 'pipe' | 'ignore' | 'inherit' | file descriptor number.\n   * Defaults to \"inherit\".\n   */\n  stderr: z\n    .union([z.enum(['pipe', 'ignore', 'inherit']), z.number().int().nonnegative()])\n    .optional(),\n  /**\n   * Working directory for the spawned process. Supplied by Agent Plugins\n   * packages, which resolve and contain the path before it reaches this schema.\n   */\n  cwd: z.string().optional(),\n});\n\nexport const WebSocketOptionsSchema = BaseOptionsSchema.extend({\n  type: z.literal('websocket').default('websocket'),\n  obo: z.undefined().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').default('sse'),\n  headers: z.record(z.string(), z.string()).optional(),\n  /**\n   * On-Behalf-Of (OBO) token exchange configuration.\n   * When configured, LibreChat exchanges the logged-in user's federated access token\n   * for a token scoped to this MCP server via the OAuth 2.0 OBO flow (jwt-bearer grant).\n   * The exchanged token is injected as a Bearer Authorization header automatically.\n   * Requires the user to be authenticated via OpenID Connect (e.g., Entra ID).\n   */\n  obo: OboOptionsSchema.optional(),\n  /** Optional outbound proxy URL for this remote MCP transport */\n  proxy: ProxyUrlSchema.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  /**\n   * On-Behalf-Of (OBO) token exchange configuration.\n   * When configured, LibreChat exchanges the logged-in user's federated access token\n   * for a token scoped to this MCP server via the OAuth 2.0 OBO flow (jwt-bearer grant).\n   * The exchanged token is injected as a Bearer Authorization header automatically.\n   * Requires the user to be authenticated via OpenID Connect (e.g., Entra ID).\n   */\n  obo: OboOptionsSchema.optional(),\n  /** Optional outbound proxy URL for this remote MCP transport */\n  proxy: ProxyUrlSchema.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 userManagedServerFields = <T extends z.ZodObject<z.ZodRawShape>>(schema: T) =>\n  omitServerManagedFields(schema).extend({\n    oauth: UserOAuthOptionsSchema.optional(),\n  });\n\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 * Admin-only OAuth audience fields are rejected for user-managed servers.\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  userManagedServerFields(WebSocketOptionsSchema).extend({\n    url: userUrlSchema(isWsProtocol, 'WebSocket URL must use ws:// or wss://'),\n  }),\n  userManagedServerFields(SSEOptionsSchema).extend({\n    proxy: z.never().optional(),\n    url: userUrlSchema(isHttpProtocol, 'SSE URL must use http:// or https://'),\n  }),\n  userManagedServerFields(StreamableHTTPOptionsSchema).extend({\n    proxy: z.never().optional(),\n    url: userUrlSchema(isHttpProtocol, 'Streamable HTTP URL must use http:// or https://'),\n  }),\n]);\n\nexport type MCPServerUserInput = z.infer<typeof MCPServerUserInputSchema>;\n\n/**\n * Set of every field name that may appear in a user-submitted MCP server config,\n * derived from `MCPServerUserInputSchema`'s union members. Used as the comparison\n * surface for the OBO lockdown check in `updateMCPServerController` so that\n * server-managed fields on the existing config (`dbId`, `source`, `author`,\n * `requiresOAuth`, `oauthMetadata`, etc.) don't show up as differences and\n * cause spurious 403s on legitimate saves.\n *\n * Schema-derived rather than hand-maintained: when a new field is added to\n * `BaseOptionsSchema` or any transport variant, it flows into this set\n * automatically. The OBO lockdown then locks the new field by default\n * (since it won't be in the hand-curated `OBO_USER_EDITABLE_FIELDS`\n * allowlist), preventing a silent privilege regression.\n */\nexport const MCP_USER_INPUT_FIELDS: ReadonlySet<string> = (() => {\n  const fields = new Set<string>();\n  for (const variant of MCPServerUserInputSchema.options) {\n    const shape = (variant as unknown as { shape: Record<string, unknown> }).shape;\n    for (const key of Object.keys(shape)) {\n      fields.add(key);\n    }\n  }\n  return fields;\n})();\n","import { z } from 'zod';\nimport type { ZodError } from 'zod';\nimport type { TEndpointsConfig, TModelsConfig, TConfig } from './types';\nimport {\n  filtersConfigSchema,\n  MAX_PII_CUSTOM_REGEX_CHARACTERS,\n  MAX_PII_CUSTOM_REGEX_INSTRUCTIONS,\n  MAX_PII_PATTERN_ID_LENGTH,\n  MAX_PII_PATTERN_LABEL_LENGTH,\n  MAX_PII_PATTERNS_PER_SOURCE,\n  MAX_PII_PATTERN_LENGTH,\n} from './filters';\nimport {\n  EModelEndpoint,\n  eModelEndpointSchema,\n  isAgentsEndpoint,\n  eReasoningParameterFormatSchema,\n  eReasoningResponseKeySchema,\n} from './schemas';\nimport { ComponentTypes, SettingTypes, OptionTypes } from './generate';\nimport { CODE_ENVIRONMENT_DECISION_VERSION } from './code/workspace';\nimport { MAX_SUBAGENTS, MAX_SUBAGENTS_CEILING } from './limits';\nimport { STATEFUL_CODE_ENVIRONMENTS } from './stateful-code';\nimport { specsConfigSchema, TSpecsConfig } from './models';\nimport { isActionTool } from './types/assistants';\nimport { REFILL_INTERVAL_UNITS } from './balance';\nimport { fileConfigSchema } from './file-config';\nimport { apiBaseUrl } from './api-endpoints';\nimport { FileSources } from './types/files';\nimport { MCPServersSchema } from './mcp';\nexport {\n  MAX_SUBAGENTS,\n  MAX_SUBAGENTS_CEILING,\n  getMaxSubagents,\n  setMaxSubagents,\n  MAX_GRAPH_SUBAGENT_MEMBERS,\n  MAX_CHAT_PROJECT_NAME_LENGTH,\n  MAX_CHAT_PROJECT_DESCRIPTION_LENGTH,\n} from './limits';\n\nexport const defaultSocialLogins = ['google', 'facebook', 'openid', 'github', 'discord', 'saml'];\n\nexport const BASE_ONLY_CONFIG_SECTIONS = ['filters'] as const;\n/** Sections that may be stored in the tenant's base config document but must\n * not be overridden or tombstoned by role, group, or user config documents. */\nexport const BASE_PRINCIPAL_CONFIG_SECTIONS = ['langfuse'] as const;\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  'agentEventBinding',\n  'agentEventActor',\n  'agentEventActorCleanup',\n  'agentEventActorSuspension',\n  'agentEventActorReconciliations',\n  'agentEventActorEpoch',\n  'agentEventActorLegacyTurn',\n  'subagentThread',\n  'title',\n  'iconURL',\n  'greeting',\n  'endpoint',\n  'endpointType',\n  'createdAt',\n  'updatedAt',\n  'expiredAt',\n  'isTemporary',\n  'messages',\n  'isArchived',\n  'pinned',\n  'archivedAt',\n  'tags',\n  'user',\n  '__v',\n  '_id',\n  'tools',\n  'model',\n  'files',\n  'spec',\n  'disableParams',\n  'chatProjectId',\n]);\n\nexport enum SettingsViews {\n  default = 'default',\n  advanced = 'advanced',\n}\n\n/** Validates any FileSources value — use for file metadata, DB records, and upload routing. */\nexport const fileSourceSchema = z.nativeEnum(FileSources);\n\n/**\n * `allowedAddresses` is an SSRF exemption list scoped to private IP space.\n * Validate at config-load time:\n *  - Reject URLs, paths, CIDR ranges, bare host/IP forms, and whitespace.\n *  - Require `host:port` or `[ipv6]:port` entries so an exemption is scoped\n *    to one service port instead of every port on a private host.\n *  - Reject IPv4 literals that fall outside the private/loopback/link-local\n *    ranges. Public IPs are never SSRF targets, so listing one has no\n *    defensive purpose and must not silently grant trust.\n *  - Hostnames pass through; their resolved IP is checked at runtime by\n *    `resolveHostnameSSRF` and only a private resolved IP is meaningful.\n *\n * Mirrors a minimal subset of `isPrivateIP` from `@librechat/api` to avoid a\n * circular package dependency. The runtime helper is the authoritative check;\n * this refinement is a UX guardrail.\n */\nfunction isPrivateIPv4Literal(value: string): boolean {\n  const match = value.match(/^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/);\n  if (!match) {\n    return false;\n  }\n  const [a, b, c] = match.slice(1).map(Number) as [number, number, number, number];\n  if (a === 0 || a === 10 || a === 127) return true;\n  if (a === 169 && b === 254) return true;\n  if (a === 172 && b >= 16 && b <= 31) return true;\n  if (a === 192 && b === 168) return true;\n  if (a === 192 && b === 0 && c === 0) return true; // RFC 5736 IETF protocol assignments\n  if (a === 100 && b >= 64 && b <= 127) return true;\n  if (a === 198 && (b === 18 || b === 19)) return true;\n  if (a >= 224) return true; // multicast/reserved\n  return false;\n}\n\n/**\n * Mirrors `hasPrivateEmbeddedIPv4` in `@librechat/api`'s ip helpers: 6to4, NAT64, and Teredo\n * carry an IPv4 address inside the IPv6 one, and the runtime guard blocks those when the\n * embedded address is private. Kept in sync so an operator can exempt what the runtime blocks.\n */\nfunction hasPrivateEmbeddedIPv4Literal(value: string): boolean {\n  const is6to4 = value.startsWith('2002:');\n  const isNat64 = value.startsWith('64:ff9b::');\n  const isTeredo = value.startsWith('2001::');\n  if (!is6to4 && !isNat64 && !isTeredo) {\n    return false;\n  }\n\n  const segments = value.split(':').filter((segment) => segment !== '');\n  const pair = is6to4 ? segments.slice(1, 3) : segments.slice(-2);\n  if (pair.length !== 2) {\n    return false;\n  }\n\n  const hi = parseInt(pair[0], 16);\n  const lo = parseInt(pair[1], 16);\n  if (isNaN(hi) || isNaN(lo)) {\n    return false;\n  }\n\n  /** RFC 4380: Teredo stores the external IPv4 as a bitwise complement. */\n  const high = isTeredo ? ~hi : hi;\n  const low = isTeredo ? ~lo : lo;\n  const octets = [(high >> 8) & 0xff, high & 0xff, (low >> 8) & 0xff, low & 0xff];\n  return isPrivateIPv4Literal(octets.join('.'));\n}\n\nfunction isPrivateIPv6Literal(value: string): boolean {\n  if (!value.includes(':')) return false;\n  if (value === '::1' || value === '::') return true;\n  if (value.startsWith('fc') || value.startsWith('fd')) return true; // fc00::/7\n  // fe80::/10 — first hextet 0xfe80–0xfebf\n  const firstHextet = value.split(':', 1)[0];\n  if (/^[0-9a-f]{1,4}$/.test(firstHextet ?? '')) {\n    const hextet = parseInt(firstHextet, 16);\n    if ((hextet & 0xffc0) === 0xfe80) return true;\n  }\n  // 4-in-6: ::ffff:A.B.C.D\n  const mappedMatch = value.match(/^::ffff:(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$/);\n  if (mappedMatch) return isPrivateIPv4Literal(mappedMatch[1]);\n  return hasPrivateEmbeddedIPv4Literal(value);\n}\n\n/**\n * Mirrors the allowedAddresses parser in `@librechat/api`'s auth helpers.\n * Kept as a local copy because the data-provider package cannot import from\n * `@librechat/api` without creating a circular dependency. Keep the two\n * implementations in sync.\n */\nfunction normalizePort(port: unknown): string {\n  if (typeof port !== 'string' && typeof port !== 'number') return '';\n  const portString = String(port).trim();\n  if (!/^\\d+$/.test(portString)) return '';\n  const parsed = Number(portString);\n  if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) return '';\n  return String(parsed);\n}\n\nfunction parseAllowedAddressEntry(entry: string): { address: string; port: string } | null {\n  const trimmed = entry.toLowerCase().trim();\n  const bracketedIPv6 = trimmed.match(/^\\[([^\\]]+)\\]:(\\d+)$/);\n  const hostPort = bracketedIPv6 ? null : trimmed.match(/^([^:]+):(\\d+)$/);\n  const address = (bracketedIPv6?.[1] ?? hostPort?.[1] ?? '').replace(/^\\[|\\]$/g, '');\n  const port = normalizePort(bracketedIPv6?.[2] ?? hostPort?.[2] ?? '');\n  if (!address || !port) return null;\n  return { address, port };\n}\n\nconst allowedAddressEntrySchema = z\n  .string()\n  .refine((entry) => entry.length > 0 && entry.trim().length > 0, {\n    message: 'allowedAddresses entries must be non-empty',\n  })\n  .refine((entry) => !entry.includes('://') && !entry.includes('/') && !/\\s/.test(entry), {\n    message:\n      'allowedAddresses entries must be host:port pairs — no URLs, paths, CIDR ranges, or whitespace',\n  })\n  .refine((entry) => parseAllowedAddressEntry(entry) != null, {\n    message:\n      'allowedAddresses entries must include a port, for example localhost:11434 or [::1]:11434',\n  })\n  .refine(\n    (entry) => {\n      const parsed = parseAllowedAddressEntry(entry);\n      if (!parsed) return false;\n      const stripped = parsed.address;\n      const isIPv4 = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.test(stripped);\n      const isIPv6 = !isIPv4 && stripped.includes(':');\n      if (!isIPv4 && !isIPv6) {\n        return true; // hostname — checked at runtime via DNS\n      }\n      return isIPv4 ? isPrivateIPv4Literal(stripped) : isPrivateIPv6Literal(stripped);\n    },\n    {\n      message:\n        'allowedAddresses is scoped to private IP space — public IP literals are not permitted (use hostname:port if it resolves to a private IP)',\n    },\n  );\n\nexport const allowedAddressesSchema = z.array(allowedAddressEntrySchema).optional();\n\n/** Storage backend strategies only — use for config fields that set where files are stored. */\nconst FILE_STORAGE_BACKENDS = [\n  FileSources.local,\n  FileSources.firebase,\n  FileSources.s3,\n  FileSources.azure_blob,\n  FileSources.cloudfront,\n] as const satisfies ReadonlyArray<FileSources>;\n\nexport const fileStorageSchema = z.enum(FILE_STORAGE_BACKENDS);\n\nexport type FileStorage = z.infer<typeof fileStorageSchema>;\n\nexport const fileStrategiesSchema = z\n  .object({\n    default: fileStorageSchema.optional(),\n    avatar: fileStorageSchema.optional(),\n    image: fileStorageSchema.optional(),\n    document: fileStorageSchema.optional(),\n    skills: fileStorageSchema.optional(),\n  })\n  .optional();\n\nconst cloudfrontSigningSchema = z.enum(['none', 'cookies', 'url']);\n\nexport const cloudfrontConfigSchema = z\n  .object({\n    domain: z.string().url(),\n    distributionId: z.string().optional(),\n    invalidateOnDelete: z.boolean().default(false),\n    imageSigning: cloudfrontSigningSchema.default('none'),\n    urlExpiry: z.number().positive().default(3600),\n    cookieExpiry: z.number().positive().max(604800).default(1800),\n    cookieDomain: z\n      .string()\n      .min(1)\n      .refine((d) => d.startsWith('.'), {\n        message: 'cookieDomain must start with a dot (e.g., \".example.com\") to apply to subdomains',\n      })\n      .optional(),\n    storageRegion: z.string().min(1).optional(),\n    includeRegionInPath: z.boolean().default(false),\n    requireSignedAccess: z.boolean().default(false),\n  })\n  .refine((data) => !data.invalidateOnDelete || !!data.distributionId, {\n    message: 'distributionId is required when invalidateOnDelete is true',\n    path: ['distributionId'],\n  })\n  .refine((data) => data.imageSigning !== 'cookies' || !!data.cookieDomain, {\n    message:\n      'cookieDomain is required when imageSigning is \"cookies\" (e.g., \".example.com\" for API at api.example.com and CDN at cdn.example.com)',\n    path: ['cookieDomain'],\n  })\n  .refine((data) => !data.requireSignedAccess || data.imageSigning === 'cookies', {\n    message:\n      'cloudfront.requireSignedAccess=true requires cloudfront.imageSigning=\"cookies\" (signed URL mode is not yet implemented)',\n    path: ['requireSignedAccess'],\n  })\n  .optional();\n\nexport type CloudFrontConfig = z.infer<typeof cloudfrontConfigSchema>;\n\nconst skillSyncIdentifierSchema = z\n  .string()\n  .min(1)\n  .max(64)\n  .regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/, {\n    message:\n      'must start with a letter or digit and contain only letters, digits, underscores, or hyphens',\n  });\n\nexport const SKILL_SYNC_MIN_INTERVAL_MINUTES = 5;\nexport const SKILL_SYNC_MAX_INTERVAL_MINUTES = Math.floor(2147483647 / 60_000);\nexport const SKILL_SYNC_DEFAULT_DISCOVERY_DEPTH = 2;\nexport const SKILL_SYNC_MAX_DISCOVERY_DEPTH = 10;\n\nconst skillSyncGitHubOwnerSchema = z\n  .string()\n  .min(1)\n  .max(39)\n  .regex(/^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/, {\n    message: 'must be a valid GitHub owner name',\n  });\n\nconst skillSyncGitHubRepoSchema = z\n  .string()\n  .min(1)\n  .max(100)\n  .regex(/^[a-zA-Z0-9._-]+$/, {\n    message: 'must be a valid GitHub repository name',\n  });\n\nconst invalidGitRefChars = new Set(['~', '^', ':', '?', '*', '[']);\n\nfunction hasInvalidGitRefCharacter(value: string): boolean {\n  for (const char of value) {\n    const code = char.charCodeAt(0);\n    if (code <= 32 || code === 127 || invalidGitRefChars.has(char)) {\n      return true;\n    }\n  }\n  return false;\n}\n\nconst skillSyncGitHubRefSchema = z\n  .string()\n  .min(1)\n  .max(255)\n  .refine((value) => !value.startsWith('/') && !value.endsWith('/'), {\n    message: 'must not start or end with a slash',\n  })\n  .refine((value) => !value.includes('..') && !value.includes('//') && !value.includes('\\\\'), {\n    message: 'must not contain traversal segments, empty path segments, or backslashes',\n  })\n  .refine((value) => !value.includes('@{') && value !== '@', {\n    message: 'must not contain invalid Git ref syntax',\n  })\n  .refine((value) => !value.endsWith('.'), {\n    message: 'must not end with a dot',\n  })\n  .refine((value) => !hasInvalidGitRefCharacter(value), {\n    message: 'must not contain invalid Git ref characters',\n  })\n  .refine(\n    (value) =>\n      value\n        .split('/')\n        .every((segment) => segment && !segment.startsWith('.') && !segment.endsWith('.lock')),\n    {\n      message: 'must contain valid Git ref path segments',\n    },\n  );\n\nconst skillSyncPathSchema = z\n  .string()\n  .max(500)\n  .refine((value) => value.trim().length > 0, { message: 'must not be empty' })\n  .transform((value) => {\n    const trimmed = value.trim().replace(/^\\/+|\\/+$/g, '');\n    return trimmed === '.' ? '' : trimmed;\n  })\n  .refine((value) => !value.includes('\\\\') && !value.includes('..'), {\n    message: 'must not contain traversal segments or backslashes',\n  })\n  .refine((value) => value === '' || /^[a-zA-Z0-9._\\-/]+$/.test(value), {\n    message: 'must contain only letters, digits, dots, underscores, hyphens, and slashes',\n  })\n  .refine(\n    (value) =>\n      value === '' || value.split('/').every((segment) => segment.length > 0 && segment !== '.'),\n    {\n      message: 'must not contain empty or dot path segments',\n    },\n  );\n\nconst skillSyncTokenReferenceSchema = z\n  .string()\n  .trim()\n  .regex(/^\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}$/, {\n    message: 'must be an environment variable reference like ${GITHUB_SKILLS_TOKEN}',\n  });\n\n/**\n * Tenant that owns the skills mirrored from a source. When set, the sync runner\n * executes that source's database writes inside the tenant's async context so\n * synced skills are created, listed, and shared within the tenant under strict\n * tenant isolation. Mirrors the request tenant-id contract: no reserved system id.\n */\nconst skillSyncTenantIdSchema = z\n  .string()\n  .max(128)\n  .refine((value) => /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(value), {\n    message: 'must be a valid tenant id',\n  })\n  .refine((value) => value !== '__SYSTEM__', {\n    message: 'must not be the reserved system tenant id',\n  });\n\nexport const skillSyncGitHubSourceSchema = z\n  .object({\n    id: skillSyncIdentifierSchema,\n    owner: skillSyncGitHubOwnerSchema,\n    repo: skillSyncGitHubRepoSchema,\n    ref: skillSyncGitHubRefSchema.default('main'),\n    paths: z.array(skillSyncPathSchema).min(1),\n    skillDiscoveryDepth: z.number().int().min(0).max(SKILL_SYNC_MAX_DISCOVERY_DEPTH).optional(),\n    credentialKey: skillSyncIdentifierSchema.optional(),\n    token: skillSyncTokenReferenceSchema.optional(),\n    tenantId: skillSyncTenantIdSchema.optional(),\n  })\n  .superRefine((source, ctx) => {\n    if (!source.credentialKey && !source.token) {\n      ctx.addIssue({\n        code: z.ZodIssueCode.custom,\n        path: ['credentialKey'],\n        message: 'Either credentialKey or token is required',\n      });\n    }\n    if (source.credentialKey && source.token) {\n      ctx.addIssue({\n        code: z.ZodIssueCode.custom,\n        path: ['token'],\n        message: 'Use either credentialKey or token, not both',\n      });\n    }\n  });\n\nexport const skillSyncConfigSchema = z\n  .object({\n    github: z\n      .object({\n        enabled: z.boolean().default(false),\n        intervalMinutes: z\n          .number()\n          .int()\n          .min(SKILL_SYNC_MIN_INTERVAL_MINUTES)\n          .max(SKILL_SYNC_MAX_INTERVAL_MINUTES)\n          .default(60),\n        runOnStartup: z.boolean().default(false),\n        sources: z.array(skillSyncGitHubSourceSchema).default([]),\n      })\n      .superRefine((github, ctx) => {\n        if (github.enabled && github.sources.length === 0) {\n          ctx.addIssue({\n            code: z.ZodIssueCode.custom,\n            path: ['sources'],\n            message: 'At least one GitHub source is required when skill sync is enabled',\n          });\n        }\n        const seen = new Set<string>();\n        for (const source of github.sources) {\n          if (seen.has(source.id)) {\n            ctx.addIssue({\n              code: z.ZodIssueCode.custom,\n              path: ['sources'],\n              message: `Duplicate GitHub skill sync source id \"${source.id}\"`,\n            });\n          }\n          seen.add(source.id);\n        }\n      })\n      .optional(),\n  })\n  .optional();\n\nexport type SkillSyncConfig = z.infer<typeof skillSyncConfigSchema>;\nexport type SkillSyncGitHubSourceConfig = z.infer<typeof skillSyncGitHubSourceSchema>;\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\nconst paramValueSchema: z.ZodType<unknown> = z.lazy(() =>\n  z.union([\n    z.string(),\n    z.number(),\n    z.boolean(),\n    z.null(),\n    z.array(paramValueSchema),\n    z.record(z.string(), paramValueSchema),\n  ]),\n);\n\n/** Validates addParams while keeping web_search aligned with current runtime boolean handling. */\nconst addParamsSchema: z.ZodType<Record<string, unknown>> = z\n  .record(z.string(), paramValueSchema)\n  .superRefine((params, ctx) => {\n    if (params.web_search === undefined || typeof params.web_search === 'boolean') {\n      return;\n    }\n\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      path: ['web_search'],\n      message: '`web_search` must be a boolean in addParams',\n    });\n  });\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: addParamsSchema.optional(),\n  dropParams: z.array(z.string()).optional(),\n  version: z.string().optional(),\n  baseURL: z.string().optional(),\n  additionalHeaders: z.record(z.string()).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  stateful_code_sessions = 'stateful_code_sessions',\n  file_search = 'file_search',\n  web_search = 'web_search',\n  artifacts = 'artifacts',\n  subagents = 'subagents',\n  actions = 'actions',\n  context = 'context',\n  skills = 'skills',\n  memory = 'memory',\n  ask_user_question = 'ask_user_question',\n  tools = 'tools',\n  chain = 'chain',\n  ocr = 'ocr',\n  run_in_background = 'run_in_background',\n  tool_intents = 'tool_intents',\n}\n\nexport const defaultAssistantsVersion = {\n  [EModelEndpoint.assistants]: 2,\n  [EModelEndpoint.azureAssistants]: 1,\n};\n\nexport const baseEndpointSchema = z.object({\n  /**\n   * Milliseconds between visible streamed chunks. Agents SDK-backed\n   * providers (openAI, custom, anthropic, google, bedrock, agents) smooth\n   * adaptively at 25ms by default; set to override the cadence, 0 to\n   * disable smoothing. Legacy Assistants and Ollama paths instead sleep\n   * this long per provider chunk (default 1ms), with no adaptive smoothing.\n   */\n  streamRate: z.number().min(0).optional(),\n  baseURL: z.string().optional(),\n  /**\n   * Custom request headers forwarded to the provider on every request. Values\n   * support the same placeholder resolution as custom endpoints — env vars\n   * (`${VAR}`), user fields (`{{LIBRECHAT_USER_*}}`), and request-body fields\n   * (`{{LIBRECHAT_BODY_CONVERSATIONID}}`). Primarily for routing built-in\n   * providers through an AI gateway / reverse proxy that consumes metadata\n   * headers (provider-native request shaping is preserved).\n   */\n  headers: z.record(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  /**\n   * When conversation titles are generated. `immediate` (default) generates the\n   * title as soon as the request is made, in parallel with the response, from the\n   * user's first message. `final` defers generation until the full response\n   * completes (legacy behavior).\n   */\n  titleTiming: z.union([z.literal('immediate'), z.literal('final')]).optional(),\n  /**\n   * Agent activity groups: collapse each contiguous block of reasoning and\n   * tool calls under a generated one-line header. Mirrors the title options\n   * above — `activityLabel` enables it (like `titleConvo`), the rest tune\n   * the fast model that writes the label.\n   *\n   * NOTE: fields added here reach `endpoints.all` automatically (that schema\n   * is `baseEndpointSchema.omit({ baseURL })`), but NOT Azure — see the\n   * enumerated `.pick()` in `azureEndpointSchema` below.\n   */\n  activityLabel: z.boolean().optional(),\n  /** Model used to write activity labels. Defaults to `titleModel`, then the agent's model. */\n  activityModel: z.string().optional(),\n  /** Endpoint whose credentials the label model runs on. Defaults to the agent's endpoint. */\n  activityEndpoint: z.string().optional(),\n  /** Overrides the system prompt used to write activity labels. */\n  activityPrompt: z.string().optional(),\n  /** Cost cap: maximum labels generated per run. Default 20. */\n  activityMaxPerRun: z.number().int().positive().optional(),\n  /** Per-entry truncation of tool input/output in the label prompt. Default 600. */\n  activityCharLimit: z.number().int().positive().optional(),\n  /** Generates one parent summary for each run phase containing 2+ activities. */\n  activityPhaseLabel: z.boolean().optional(),\n  /** Model used for phase summaries. Defaults to activityModel, titleModel, then the run model. */\n  activityPhaseModel: z.string().optional(),\n  /** Endpoint whose credentials the phase summary model uses. Defaults to activityEndpoint. */\n  activityPhaseEndpoint: z.string().optional(),\n  /** Overrides the dedicated phase-summary system prompt. */\n  activityPhasePrompt: z.string().optional(),\n  /** Cost cap: maximum phase summaries generated per run. Default 5. */\n  activityPhaseMaxPerRun: z.number().int().positive().optional(),\n  /** Generates a live orientation label for sufficiently long top-level response reasoning. */\n  reasoningLabel: z.boolean().optional(),\n  /** Model used for reasoning labels. Defaults to activityModel, titleModel, then run model. */\n  reasoningLabelModel: z.string().optional(),\n  /** Endpoint receiving the bounded visible-reasoning snapshot. Defaults to activityEndpoint. */\n  reasoningLabelEndpoint: z.string().optional(),\n  /** Overrides the dedicated reasoning-label system prompt. */\n  reasoningLabelPrompt: z.string().optional(),\n  /** Characters required before the first reasoning label. Default 500. */\n  reasoningLabelMinChars: z.number().int().positive().optional(),\n  /** New characters required between streaming revisions. Default 400. */\n  reasoningLabelUpdateChars: z.number().int().positive().optional(),\n  /** Minimum milliseconds between streaming revisions. Default 3000. */\n  reasoningLabelUpdateIntervalMs: z.number().int().nonnegative().optional(),\n  /** Cost cap: maximum reasoning-label provider calls attempted per run. Default 8. */\n  reasoningLabelMaxPerRun: z.number().int().positive().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 bedrockGuardrailConfigSchema = z.object({\n  guardrailIdentifier: z.string(),\n  guardrailVersion: z.string(),\n  trace: z.enum(['enabled', 'disabled', 'enabled_full']).optional(),\n  streamProcessingMode: z.enum(['sync', 'async']).optional(),\n});\n\nexport const bedrockEndpointSchema = baseEndpointSchema.merge(\n  z.object({\n    availableRegions: z.array(z.string()).optional(),\n    models: z.array(z.string()).optional(),\n    guardrailConfig: bedrockGuardrailConfigSchema.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    /** Masked preview of the API key, stored at write time so admin\n     * reads can show which key is configured without returning the secret.\n     * Shared by both `endpoints.assistants` and `endpoints.azureAssistants`,\n     * which both use this schema. */\n    apiKeyPreview: 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.string()).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.subagents,\n  AgentCapabilities.actions,\n  AgentCapabilities.context,\n  AgentCapabilities.skills,\n  AgentCapabilities.memory,\n  AgentCapabilities.ask_user_question,\n  AgentCapabilities.tools,\n  AgentCapabilities.chain,\n  AgentCapabilities.ocr,\n];\n\nconst LOCAL_REMOTE_OIDC_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nexport function isRemoteOidcUrlAllowed(value: string): boolean {\n  try {\n    const url = new URL(value);\n    if (url.protocol === 'https:') return true;\n    if (url.protocol !== 'http:') return false;\n\n    const hostname = url.hostname.toLowerCase();\n    return LOCAL_REMOTE_OIDC_HOSTS.has(hostname) || hostname.endsWith('.localhost');\n  } catch {\n    return false;\n  }\n}\n\nconst remoteApiOidcUrlSchema = z\n  .string()\n  .url()\n  .refine(isRemoteOidcUrlAllowed, { message: 'must use https:// unless targeting localhost' });\n\nconst remoteApiOidcScopeSchema = z.string().refine((scope) => !scope.includes(','), {\n  message: 'scopes must be space-separated',\n});\n\nconst oidcAccessTokenSchema = z.object({\n  enabled: z.boolean().default(false),\n  issuer: remoteApiOidcUrlSchema.optional(),\n  audience: z.string().min(1).optional(),\n  jwksUri: remoteApiOidcUrlSchema.optional(),\n});\n\nfunction validateEnabledOidc(\n  oidc: z.infer<typeof oidcAccessTokenSchema>,\n  ctx: z.RefinementCtx,\n): void {\n  if (oidc.enabled === true && !oidc.issuer) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      path: ['issuer'],\n      message: 'issuer is required when OIDC auth is enabled',\n    });\n  }\n  if (oidc.enabled === true && !oidc.audience) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      path: ['audience'],\n      message: 'audience is required when OIDC auth is enabled',\n    });\n  }\n}\n\nconst remoteApiOidcSchema = oidcAccessTokenSchema\n  .extend({ scope: remoteApiOidcScopeSchema.optional() })\n  .superRefine(validateEnabledOidc);\n\nconst remoteApiAuthSchema = z.object({\n  apiKey: z\n    .object({\n      enabled: z.boolean().default(true),\n    })\n    .optional(),\n  oidc: remoteApiOidcSchema.optional(),\n});\n\nconst remoteApiSchema = z.object({\n  auth: remoteApiAuthSchema.optional(),\n});\n\nconst managementClientBindingSchema = z\n  .object({\n    clientId: z.string().trim().min(1).max(128),\n    subject: z.string().trim().min(1).max(512).optional(),\n    userId: z\n      .string()\n      .trim()\n      .regex(/^[a-f\\d]{24}$/i, 'must be a MongoDB ObjectId')\n      .transform((userId) => userId.toLowerCase()),\n    tenantId: z\n      .string()\n      .trim()\n      .min(1)\n      .max(128)\n      .regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/, 'must be a valid tenant id')\n      .refine((tenantId) => tenantId !== '__SYSTEM__', 'system tenant is not allowed'),\n    enabled: z.boolean().default(true),\n  })\n  .strict();\n\nconst managementApiOidcSchema = oidcAccessTokenSchema.strict().superRefine(validateEnabledOidc);\n\nconst managementApiAuthSchema = z\n  .object({\n    oidc: managementApiOidcSchema,\n    clients: z.array(managementClientBindingSchema).max(100).default([]),\n  })\n  .strict()\n  .superRefine((auth, ctx) => {\n    if (auth.oidc.enabled === true && auth.clients.length === 0) {\n      ctx.addIssue({\n        code: z.ZodIssueCode.custom,\n        path: ['clients'],\n        message: 'at least one client binding is required when management auth is enabled',\n      });\n    }\n\n    const clientIds = new Set<string>();\n    for (let index = 0; index < auth.clients.length; index++) {\n      const client = auth.clients[index];\n      if (clientIds.has(client.clientId)) {\n        ctx.addIssue({\n          code: z.ZodIssueCode.custom,\n          path: ['clients', index, 'clientId'],\n          message: 'client IDs must be unique',\n        });\n      }\n      clientIds.add(client.clientId);\n    }\n  });\n\nconst managementApiSchema = z.object({ auth: managementApiAuthSchema.optional() }).strict();\n\n/**\n * Permission mode applied to a tool call. Mirrors `@librechat/agents`'s\n * `ToolPolicyMode` 1:1.\n *\n * - `default`: ask the user about anything not explicitly allowed (default-on).\n * - `dontAsk`: deny anything not explicitly allowed (headless / API-key flows).\n * - `bypass`: auto-approve everything that isn't explicitly denied\n *   (the user-facing \"stop asking me\" toggle).\n *\n * Subagents inherit the parent's mode; this is enforced by the SDK and not\n * overridable per-subagent.\n */\nexport const toolApprovalModeSchema = z.enum(['default', 'dontAsk', 'bypass']);\nexport type ToolApprovalMode = z.infer<typeof toolApprovalModeSchema>;\n\n/**\n * Per-endpoint tool-approval policy.\n *\n * Shape mirrors `@librechat/agents`'s `ToolPolicyConfig` so the host can map it\n * directly into `createToolPolicyHook(config)`. The SDK does the evaluation\n * (`deny → ask → allow → bypass → dontAsk → fallthrough(ask)`); this config\n * just describes the surface.\n *\n * Conventions:\n * - All list entries are matched as globs (`*`). Use `mcp:server:*` to scope\n *   a rule to every tool from a single MCP server.\n * - `deny` always wins, including under `bypass`.\n * - `enabled: false` is a LibreChat-only kill switch that disables the entire\n *   HITL machinery for this endpoint (no checkpointer, no hooks, no prompts).\n *   This is admin-level; users toggle prompting via `mode: 'bypass'` instead.\n */\n/**\n * A programmatic tool-approval hook loaded from a module at startup.\n *\n * The referenced module's default export must be a builder\n * `(options?) => ToolApprovalHookFactory` (see `@librechat/api`'s `registerToolApprovalHook`).\n * Hooks compose with the static `allow`/`deny`/`ask` policy above and can only TIGHTEN it\n * (the SDK folds decisions `deny → ask → allow`). This is admin-level config — the module is\n * dynamically imported and executed in-process, so only reference trusted code.\n */\nexport const toolApprovalHookConfigSchema = z.object({\n  /**\n   * Module specifier to import: a bare package name (e.g. `@acme/approval-hooks`) or a path —\n   * absolute, or relative to the app root. Its default export is the hook builder.\n   */\n  module: z.string().min(1),\n  /** Optional regex matched against the tool name; omit to run for every tool. */\n  matcher: z.string().optional(),\n  /** Static options forwarded to the module's builder; the hook's own per-call config. */\n  options: z.record(z.unknown()).optional(),\n});\n\nexport type TToolApprovalHookConfig = z.infer<typeof toolApprovalHookConfigSchema>;\n\nexport const toolApprovalPolicySchema = z\n  .object({\n    enabled: z.boolean().optional(),\n    mode: toolApprovalModeSchema.optional(),\n    allow: z.array(z.string()).optional(),\n    deny: z.array(z.string()).optional(),\n    ask: z.array(z.string()).optional(),\n    /** Optional reason template surfaced in the prompt; `{tool}` is interpolated. */\n    reason: z.string().optional(),\n    /**\n     * Programmatic policy hooks loaded from modules at startup. They layer on top of the\n     * static lists above for dynamic, context-aware decisions the lists can't express\n     * (per-args, per-agent, per-user). See {@link toolApprovalHookConfigSchema}.\n     *\n     * BASE-CONFIG ONLY: hooks are imported + registered once, process-wide, at server\n     * startup — they are NOT reloaded from per-role/user/tenant admin overrides. Encode\n     * per-user/tenant behavior INSIDE the hook (via its runtime context), not by varying the\n     * module list per override. Honored only when `enabled` is true.\n     */\n    hooks: z.array(toolApprovalHookConfigSchema).optional(),\n  })\n  .optional();\n\nexport type TToolApprovalPolicy = z.infer<typeof toolApprovalPolicySchema>;\n\n/**\n * Durable checkpointer backing human-in-the-loop resume.\n *\n * When `toolApproval.enabled` is true, a run that pauses for review suspends its\n * LangGraph state to a checkpoint; resuming rebuilds that state on a *fresh* `Run`\n * — possibly on a different replica, or the same worker after a restart. That only\n * works if the checkpoint outlives the original request, so HITL needs a durable\n * saver, not the SDK's process-local `MemorySaver` fallback.\n *\n * Defaults are zero-config: with `toolApproval.enabled` on and no `checkpointer`\n * block, LibreChat persists checkpoints to its primary MongoDB, so resume works\n * across replicas out of the box.\n *\n * - `type: 'mongo'` (default) — persist to the app database; survives restarts and\n *   resolves on any replica. A TTL index reclaims runs that are never resolved.\n * - `type: 'memory'` — process-local only. Paused runs do NOT survive a restart and\n *   can only be resolved on the originating worker. Single-process / dev only.\n */\nexport const checkpointerTypeSchema = z.enum(['mongo', 'memory']);\nexport type TCheckpointerType = z.infer<typeof checkpointerTypeSchema>;\n\nexport const checkpointerSchema = z\n  .object({\n    type: checkpointerTypeSchema.optional(),\n    /**\n     * Approval window, in seconds: how long a paused run waits for a decision\n     * before it is reclaimed. Drives both the Mongo TTL index on checkpoints and\n     * the pending-action expiry, keeping the two layers in lockstep. Defaults to\n     * 86400 (24h). Raise it for longer review windows.\n     */\n    ttl: z.number().int().positive().optional(),\n    /** Advanced: override the Mongo collection names used for checkpoints. */\n    checkpointCollectionName: z.string().optional(),\n    checkpointWritesCollectionName: z.string().optional(),\n  })\n  .optional();\n\nexport type TCheckpointerConfig = z.infer<typeof checkpointerSchema>;\n\nconst codeEnvironmentBaseURLSchema = z\n  .string()\n  .trim()\n  .url()\n  .refine(\n    (value) => {\n      try {\n        const url = new URL(value);\n        return (\n          (url.protocol === 'http:' || url.protocol === 'https:') &&\n          !value.includes('?') &&\n          !value.includes('#') &&\n          url.search.length === 0 &&\n          url.hash.length === 0\n        );\n      } catch {\n        return false;\n      }\n    },\n    { message: 'Code environment baseURL must be an HTTP(S) base URL without query or fragment' },\n  );\n\nexport function isSecureCodeEnvironmentControlURL(baseURL: string): boolean {\n  try {\n    const url = new URL(baseURL.trim());\n    if (url.protocol === 'https:') return true;\n    if (url.protocol !== 'http:') return false;\n    return url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]';\n  } catch {\n    return false;\n  }\n}\n\nexport const codeEnvironmentPermissionDecisionSchema = z.enum(['allow', 'ask', 'deny']);\nexport type CodeEnvironmentPermissionDecision = z.infer<\n  typeof codeEnvironmentPermissionDecisionSchema\n>;\n\nconst codeEnvironmentPermissionFieldSchema = z\n  .object({\n    allowed: z.array(codeEnvironmentPermissionDecisionSchema).min(1),\n    default: codeEnvironmentPermissionDecisionSchema.optional().default('ask'),\n  })\n  .strict()\n  .superRefine((field, context) => {\n    if (!field.allowed.includes(field.default)) {\n      context.addIssue({\n        code: z.ZodIssueCode.custom,\n        path: ['default'],\n        message: 'Permission default must be included in allowed values',\n      });\n    }\n  });\n\n/** Existing attached commands used a fixed 30-second execution budget. */\nexport const CODE_ENVIRONMENT_COMMAND_TIMEOUT_DEFAULT_MS = 30_000;\n/** Protocol-level ceiling; deployments may only lower this value. */\nexport const CODE_ENVIRONMENT_COMMAND_TIMEOUT_HARD_MAX_MS = 5 * 60_000;\n\n/**\n * Typed user-tunable surface for one attached code environment. Omitted fields\n * remain fixed at LibreChat's safe baseline. Isolation, networking, mounts,\n * privileged execution, and secrets are deliberately not representable here.\n */\nexport const codeEnvironmentUserConfigSchema = z\n  .object({\n    permissions: z\n      .object({\n        fileWrite: codeEnvironmentPermissionFieldSchema.optional(),\n        commandExecution: codeEnvironmentPermissionFieldSchema.optional(),\n      })\n      .strict()\n      .optional(),\n    limits: z\n      .object({\n        /** Maximum timeout a Bash invocation may request. Omission preserves\n         * the historical 30-second command budget. */\n        maxCommandTimeoutMs: z\n          .number()\n          .int()\n          .min(1)\n          .max(CODE_ENVIRONMENT_COMMAND_TIMEOUT_HARD_MAX_MS)\n          .optional(),\n      })\n      .strict()\n      .optional(),\n  })\n  .strict();\n\nexport type CodeEnvironmentUserConfigSchema = z.infer<typeof codeEnvironmentUserConfigSchema>;\n\nexport const codeEnvironmentUserSettingsSchema = z\n  .object({\n    permissions: z\n      .object({\n        fileWrite: codeEnvironmentPermissionDecisionSchema.optional(),\n        commandExecution: codeEnvironmentPermissionDecisionSchema.optional(),\n      })\n      .strict()\n      .optional(),\n  })\n  .strict();\n\nexport type CodeEnvironmentUserSettings = z.infer<typeof codeEnvironmentUserSettingsSchema>;\n\nexport type CodeWorkerEnrollmentPolicy = NonNullable<\n  NonNullable<z.infer<typeof agentsEndpointSchema>['statefulCodeSessions']>['principalWorkers']\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      /** Max cumulative bytes a single streamed tool call's arguments may reach before the run\n       * aborts. Defaults to 64 KiB in the agents SDK; `0` disables the guard. */\n      maxToolCallArgBytes: z.number().optional(),\n      /** Max streamed chunk events per model generation before the run aborts. Off by default. */\n      maxDeltaEventsPerTurn: z.number().optional(),\n      /** Per-tool overrides of `maxToolCallArgBytes`, keyed by model-facing tool name; `0`\n       * disables the guard for that tool only. Merged over LibreChat's shipped default of\n       * `{ create_file: 131072 }`. */\n      maxToolCallArgBytesByTool: z.record(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      /** Maximum explicit subagents per agent (`agent_ids` and `graphs`); raised from\n       * the shipped default of 10 for orchestration-heavy deployments, bounded by\n       * `MAX_SUBAGENTS_CEILING`. */\n      maxSubagents: z\n        .number()\n        .int()\n        .min(1)\n        .max(MAX_SUBAGENTS_CEILING)\n        .optional()\n        .default(MAX_SUBAGENTS),\n      /** Run-scoped file access for explicitly opted-in subagent delegations. */\n      fileSharing: z\n        .object({\n          enabled: z.boolean().optional().default(false),\n          allowSiblingSharing: z.boolean().optional().default(false),\n          maxFiles: z.number().int().min(1).max(1_000).optional().default(100),\n          /** Aggregate disk budget for private output versions retained during a run. */\n          maxPrivateBytes: z\n            .number()\n            .int()\n            .min(1)\n            .max(10_737_418_240)\n            .optional()\n            .default(268_435_456),\n          ttlMs: z.number().int().min(1).max(86_400_000).optional().default(3_600_000),\n        })\n        .optional(),\n      /** Maximum concurrent Code API uploads per route and authenticated principal. */\n      codeApiUploadConcurrency: z.number().int().min(1).max(100).optional().default(3),\n      /** Maximum wall-clock time spent waiting on Code API rate limits per operation. */\n      codeApiMaxRetryWaitMs: z.number().int().min(0).max(300_000).optional().default(20_000),\n      allowedProviders: z.array(z.union([z.string(), eModelEndpointSchema])).optional(),\n      capabilities: z\n        .array(z.nativeEnum(AgentCapabilities))\n        .optional()\n        .default(defaultAgentCapabilities),\n      /** Controls which workspace-sharing scopes users may select for stateful code sessions.\n       *  Omit this block to preserve the legacy behavior of allowing every scope. */\n      statefulCodeSessions: z\n        .object({\n          allowedEnvironments: z.array(z.enum(STATEFUL_CODE_ENVIRONMENTS)).min(1),\n          /** Server-only personal worker enrollment policy. Effective principal\n           * policy may tighten, but never raise, the deployment ceiling. */\n          principalWorkers: z\n            .object({\n              enabled: z.boolean().optional(),\n              /** Defaults to five. Zero disables enrollment; existing machines remain usable. */\n              maxPerUser: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),\n            })\n            .optional(),\n          /** Operator-managed execution environments. Attached entries route to a\n           * Code API deployment backed by an outbound librechat-code worker. */\n          environments: z\n            .array(\n              z.object({\n                id: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/),\n                name: z.string().min(1).max(100),\n                type: z.enum(['managed', 'attached']),\n                baseURL: codeEnvironmentBaseURLSchema,\n                default: z.boolean().optional(),\n                /** Server-only outbound worker route. Removed from public config. */\n                workerId: z\n                  .string()\n                  .regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/)\n                  .optional(),\n                /** Distinguishes operator policy from a principal-authorized\n                 * environment merged into request-scoped server config. */\n                owner: z.enum(['deployment', 'principal']).optional().default('deployment'),\n                /** Administrator-controlled user-tunable settings. Only fields\n                 * represented here may be changed by a principal. */\n                configSchema: codeEnvironmentUserConfigSchema.optional(),\n                /** Request-scoped effective settings for a principal-owned environment.\n                 * Deployment config should define defaults through configSchema instead. */\n                settings: codeEnvironmentUserSettingsSchema.optional(),\n                /** Server-only enrollment metadata. `tokenEnv` names an\n                 * environment variable and never contains the token itself. */\n                pairing: z\n                  .object({\n                    workerId: z\n                      .string()\n                      .regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/)\n                      .optional(),\n                    allowPrincipalWorkers: z.boolean().optional().default(false),\n                    tokenEnv: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),\n                  })\n                  .superRefine((pairing, pairingContext) => {\n                    if (pairing.workerId != null || pairing.allowPrincipalWorkers === true) {\n                      return;\n                    }\n                    pairingContext.addIssue({\n                      code: z.ZodIssueCode.custom,\n                      message: 'Pairing requires a workerId or principal workers',\n                    });\n                  })\n                  .optional(),\n              }),\n            )\n            .optional(),\n        })\n        .superRefine((value, context) => {\n          if (!value?.environments) return;\n          const ids = new Set<string>();\n          let defaults = 0;\n          let executableEnvironments = 0;\n          for (const environment of value.environments) {\n            const pairingOnly =\n              environment.pairing?.allowPrincipalWorkers === true &&\n              environment.pairing.workerId == null &&\n              environment.workerId == null;\n            if (environment.pairing != null && environment.type !== 'attached') {\n              context.addIssue({\n                code: z.ZodIssueCode.custom,\n                message: 'Only attached code environments may configure pairing',\n                path: ['environments', environment.id, 'pairing'],\n              });\n            }\n            if (environment.pairing != null && environment.owner !== 'deployment') {\n              context.addIssue({\n                code: z.ZodIssueCode.custom,\n                message: 'Only deployment-owned code environments may configure pairing',\n                path: ['environments', environment.id, 'pairing'],\n              });\n            }\n            if (\n              environment.pairing != null &&\n              !isSecureCodeEnvironmentControlURL(environment.baseURL)\n            ) {\n              context.addIssue({\n                code: z.ZodIssueCode.custom,\n                message: 'Paired code environments require HTTPS outside loopback development',\n                path: ['environments', environment.id, 'baseURL'],\n              });\n            }\n            if (\n              environment.workerId != null &&\n              environment.pairing?.workerId != null &&\n              environment.workerId !== environment.pairing.workerId\n            ) {\n              context.addIssue({\n                code: z.ZodIssueCode.custom,\n                message: 'Code environment workerId must match pairing.workerId',\n                path: ['environments', environment.id, 'workerId'],\n              });\n            }\n            if (pairingOnly && environment.default === true) {\n              context.addIssue({\n                code: z.ZodIssueCode.custom,\n                message: 'Pairing-only code control planes cannot be execution defaults',\n                path: ['environments', environment.id, 'default'],\n              });\n            }\n            if (ids.has(environment.id)) {\n              context.addIssue({\n                code: z.ZodIssueCode.custom,\n                message: `Duplicate code environment id: ${environment.id}`,\n                path: ['environments'],\n              });\n            }\n            ids.add(environment.id);\n            if (!pairingOnly) {\n              executableEnvironments += 1;\n              if (environment.default === true) defaults += 1;\n            }\n          }\n          if (executableEnvironments > 0 && defaults !== 1) {\n            context.addIssue({\n              code: z.ZodIssueCode.custom,\n              message: 'Exactly one stateful code environment must be the default',\n              path: ['environments'],\n            });\n          }\n        })\n        .optional(),\n      /** Optional trusted origin for in-process agent event delivery. */\n      eventDriven: z\n        .object({\n          selfUrl: z.string().url().optional(),\n        })\n        .optional(),\n      /** Conversational background-task delivery policy. Automatic completion wakeups are\n       * enabled unless an administrator explicitly restores poll-only behavior. */\n      backgroundTasks: z\n        .object({\n          completionWakeups: z.boolean().optional().default(true),\n          /** Cooperative cancellation for process-local ordinary tools. Off\n           * by default so existing deployments opt into the new control. */\n          ordinaryToolCancellation: z.boolean().optional().default(false),\n        })\n        .optional(),\n      skills: z\n        .object({\n          maxCatalogSkills: z.number().int().min(1).max(100).optional(),\n        })\n        .optional(),\n      managementApi: managementApiSchema.optional(),\n      remoteApi: remoteApiSchema.optional(),\n      /** Human-in-the-loop tool approval policy. Off by default. */\n      toolApproval: toolApprovalPolicySchema,\n      /** Durable checkpointer backing tool-approval and Ask User resume.\n       *  Defaults to the app's MongoDB when either flow needs it. */\n      checkpointer: checkpointerSchema,\n    }),\n  )\n  .default({\n    disableBuilder: false,\n    capabilities: defaultAgentCapabilities,\n    maxCitations: 30,\n    maxCitationsPerFile: 7,\n    minRelevanceScore: 0.45,\n    maxSubagents: MAX_SUBAGENTS,\n  });\n\nexport type TAgentsEndpoint = z.infer<typeof agentsEndpointSchema>;\n\nexport const paramDefinitionSchema = z.object({\n  key: z.string(),\n  description: z.string().optional(),\n  type: z.nativeEnum(SettingTypes).optional(),\n  default: z.union([z.number(), z.boolean(), z.string(), z.array(z.string())]).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      positiveMin: z.number().optional(),\n    })\n    /** A floor above the ceiling admits nothing but the sentinel, while the\n     *  clamp maps every non-negative input onto a maximum the generated schema\n     *  then rejects. */\n    .refine((value) => value.positiveMin == null || value.positiveMin <= value.max, {\n      message: 'range.positiveMin cannot exceed range.max',\n      path: ['positiveMin'],\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().int().nonnegative().optional(),\n  columns: z.number().int().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\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    /** Masked preview of the API key, stored at write time so admin\n     * reads can show which key is configured without returning the secret. */\n    apiKeyPreview: z.string().optional(),\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    /**\n     * Forces the endpoint to use a provider's native client / request format\n     * instead of the default OpenAI-compatible client. Currently supports\n     * `anthropic`, for endpoints that speak the Anthropic `/v1/messages` API\n     * (Anthropic itself or Anthropic-compatible gateways). Omit for\n     * OpenAI-compatible endpoints.\n     */\n    provider: z.literal(EModelEndpoint.anthropic).optional(),\n    headers: z.record(z.string()).optional(),\n    addParams: addParamsSchema.optional(),\n    dropParams: z.array(z.string()).optional(),\n    customParams: z\n      .object({\n        defaultParamsEndpoint: z.string().default('custom'),\n        reasoningFormat: eReasoningParameterFormatSchema.optional(),\n        reasoningKey: eReasoningResponseKeySchema.optional(),\n        /** Replays `reasoning_content` within a run's tool-call turns (e.g. Xiaomi MiMo, Kimi). */\n        includeReasoningContent: z.boolean().optional(),\n        /** Also reconstructs `reasoning_content` from persisted history across turns (implies `includeReasoningContent`). */\n        includeReasoningHistory: z.boolean().optional(),\n        paramDefinitions: z.array(paramDefinitionSchema).optional(),\n      })\n      .strict()\n      .optional(),\n    directEndpoint: z.boolean().optional(),\n    titleMessageRole: z.enum(['system', 'user', 'assistant']).optional(),\n    /** Static per-model token config: context window and per-million-token rates */\n    tokenConfig: z\n      .record(\n        z.object({\n          prompt: z.number(),\n          completion: z.number(),\n          context: z.number(),\n          cacheRead: z.number().optional(),\n          cacheWrite: z.number().optional(),\n        }),\n      )\n      .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    /**\n     * Azure carries only the base-endpoint fields enumerated here. This is a\n     * `.pick()`, NOT an omit, so a field added to `baseEndpointSchema` is\n     * silently unavailable on Azure endpoints until it is listed below —\n     * unlike `endpoints.all`, which omits and therefore inherits new fields\n     * automatically. Keep this list in sync when adding endpoint options.\n     */\n    endpointSchema\n      .pick({\n        streamRate: true,\n        titleConvo: true,\n        titleMethod: true,\n        titleModel: true,\n        titlePrompt: true,\n        titleTiming: true,\n        titlePromptTemplate: true,\n        activityLabel: true,\n        activityModel: true,\n        activityEndpoint: true,\n        activityPrompt: true,\n        activityMaxPerRun: true,\n        activityCharLimit: true,\n        activityPhaseLabel: true,\n        activityPhaseModel: true,\n        activityPhaseEndpoint: true,\n        activityPhasePrompt: true,\n        activityPhaseMaxPerRun: true,\n        reasoningLabel: true,\n        reasoningLabelModel: true,\n        reasoningLabelEndpoint: true,\n        reasoningLabelPrompt: true,\n        reasoningLabelMinChars: true,\n        reasoningLabelUpdateChars: true,\n        reasoningLabelUpdateIntervalMs: true,\n        reasoningLabelMaxPerRun: 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\n/** Masked preview of the API key, stored at write time so admin\n * reads can show which key is configured without returning the secret. */\nconst apiKeyPreviewSchema = z.string().optional();\n\nconst ttsOpenaiSchema = z.object({\n  url: z.string().optional(),\n  apiKey: z.string(),\n  apiKeyPreview: apiKeyPreviewSchema,\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  apiKeyPreview: apiKeyPreviewSchema,\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  apiKeyPreview: apiKeyPreviewSchema,\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  apiKeyPreview: apiKeyPreviewSchema,\n  voices: z.array(z.string()),\n  backend: z.string(),\n});\n\nconst ttsSchema = z.object({\n  allowedAddresses: allowedAddressesSchema,\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  apiKeyPreview: apiKeyPreviewSchema,\n  model: z.string(),\n});\n\nconst sttAzureOpenAISchema = z.object({\n  instanceName: z.string(),\n  apiKey: z.string(),\n  apiKeyPreview: apiKeyPreviewSchema,\n  deploymentName: z.string(),\n  apiVersion: z.string(),\n});\n\nconst sttSchema = z.object({\n  allowedAddresses: allowedAddressesSchema,\n  openai: sttOpenaiSchema.optional(),\n  azureOpenAI: sttAzureOpenAISchema.optional(),\n});\n\n/**\n * The speech providers a schema actually configures. `allowedAddresses` is transport\n * policy rather than a provider, and a provider key present but empty configures\n * nothing. The speech services accept a schema only when exactly one survives here, so\n * the upload router reads availability from the same list and never routes audio to a\n * transcription that cannot run.\n */\nexport function listConfiguredSpeechProviders(\n  schema?: Record<string, unknown> | null,\n): Array<[string, Record<string, unknown>]> {\n  if (schema == null) {\n    return [];\n  }\n  return Object.entries(schema).filter(\n    ([key, value]) =>\n      key !== 'allowedAddresses' &&\n      value != null &&\n      typeof value === 'object' &&\n      Object.keys(value).length > 0,\n  ) as Array<[string, Record<string, unknown>]>;\n}\n\n/** Whether a speech schema names exactly one usable provider. */\nexport function isSpeechProviderConfigured(schema?: Record<string, unknown> | null): boolean {\n  return listConfiguredSpeechProviders(schema).length === 1;\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          /** Provider names remain valid for backward compatibility and are normalized for clients. */\n          engineSTT: z.enum(['browser', 'external', 'openai', 'azureOpenAI']).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          /** Provider names remain valid for backward compatibility and are normalized for clients. */\n          engineTTS: z\n            .enum(['browser', 'external', 'openai', 'azureOpenAI', 'elevenlabs', 'localai'])\n            .optional(),\n          voice: z.string().optional(),\n          languageTTS: z.string().optional(),\n          automaticPlayback: z.boolean().optional(),\n          playbackRate: z.number().min(0.25).max(4).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  agentEvents: z\n    .object({\n      userMax: z.number().int().positive().optional(),\n      userWindowInMinutes: z.number().positive().optional(),\n    })\n    .optional(),\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\nexport const mcpRefreshDefaults = {\n  toolsRefreshInterval: 5 * 60 * 1000,\n  statusRefreshInterval: 30 * 1000,\n};\n\nconst mcpServersSchema = z\n  .object({\n    /** Foreground polling intervals in milliseconds; 0 disables polling. */\n    toolsRefreshInterval: z.number().int().nonnegative().max(2_147_483_647).optional(),\n    statusRefreshInterval: z.number().int().nonnegative().max(2_147_483_647).optional(),\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    configureObo: 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\n/** Values the trace viewer uses for any `interface.traceViewer` field left unset. */\nexport const traceViewerDefaults = {\n  enabled: false,\n  showInputOutput: false,\n  maxRecords: 1000,\n  maxContentLength: 50_000,\n  requestsPerMinute: 30,\n  requestTimeoutMs: 10_000,\n} as const;\n\ntype TraceViewerLimitField =\n  | 'maxRecords'\n  | 'maxContentLength'\n  | 'requestsPerMinute'\n  | 'requestTimeoutMs';\n\n/** Inclusive bounds for the numeric `interface.traceViewer` fields. */\nexport const traceViewerLimits: Readonly<\n  Record<TraceViewerLimitField, { readonly min: number; readonly max: number }>\n> = {\n  maxRecords: { min: 1, max: 10_000 },\n  maxContentLength: { min: 1, max: 1_000_000 },\n  requestsPerMinute: { min: 1, max: 1000 },\n  requestTimeoutMs: { min: 1000, max: 300_000 },\n};\n\nconst boundedIntegerSchema = (field: TraceViewerLimitField) =>\n  z.number().int().min(traceViewerLimits[field].min).max(traceViewerLimits[field].max).optional();\n\nconst traceViewerSchema = z.object({\n  /** Shows the conversation trace control for traces this deployment exported. */\n  enabled: z.boolean().optional(),\n  /** Returns observation input, output and metadata in the record inspector. */\n  showInputOutput: z.boolean().optional(),\n  /** Observations read from the tracing backend per request. */\n  maxRecords: boundedIntegerSchema('maxRecords'),\n  /** Characters kept from each input, output and metadata value before truncation. */\n  maxContentLength: boundedIntegerSchema('maxContentLength'),\n  /** Trace reads one user may start per minute. */\n  requestsPerMinute: boundedIntegerSchema('requestsPerMinute'),\n  /** Budget for each round trip to the tracing backend, in milliseconds. */\n  requestTimeoutMs: boundedIntegerSchema('requestTimeoutMs'),\n});\n\nexport type TTraceViewerConfig = z.infer<typeof traceViewerSchema>;\nexport type TResolvedTraceViewerConfig = {\n  enabled: boolean;\n  showInputOutput: boolean;\n} & Record<TraceViewerLimitField, number>;\n\nfunction boundedInteger(value: unknown, field: TraceViewerLimitField): number {\n  const { min, max } = traceViewerLimits[field];\n  return typeof value === 'number' && Number.isSafeInteger(value) && value >= min\n    ? Math.min(value, max)\n    : traceViewerDefaults[field];\n}\n\n/**\n * Fills unset or invalid `interface.traceViewer` fields from\n * {@link traceViewerDefaults}. Admin config overrides reach runtime without\n * schema validation, so every consumer reads the section through this.\n */\nexport function resolveTraceViewerConfig(\n  config?: Partial<Record<keyof TTraceViewerConfig, unknown>> | null,\n): TResolvedTraceViewerConfig {\n  return {\n    enabled: config?.enabled === true,\n    showInputOutput: config?.showInputOutput === true,\n    maxRecords: boundedInteger(config?.maxRecords, 'maxRecords'),\n    maxContentLength: boundedInteger(config?.maxContentLength, 'maxContentLength'),\n    requestsPerMinute: boundedInteger(config?.requestsPerMinute, 'requestsPerMinute'),\n    requestTimeoutMs: boundedInteger(config?.requestTimeoutMs, 'requestTimeoutMs'),\n  };\n}\n\nexport enum RetentionMode {\n  ALL = 'all',\n  TEMPORARY = 'temporary',\n}\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    modelSelect: z.boolean().optional(),\n    parameters: 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    generalChatRetention: z.number().min(1).max(8760).optional(),\n    autoSubmitFromUrl: z.boolean().optional(),\n    retentionMode: z.nativeEnum(RetentionMode).default(RetentionMode.TEMPORARY),\n    retainAgentFiles: z.boolean().optional(),\n    runCode: z.boolean().optional(),\n    webSearch: z.boolean().optional(),\n    contextUsage: z.boolean().optional(),\n    contextCost: z.boolean().optional(),\n    feedback: z.boolean().optional(),\n    currency: z\n      .object({\n        code: z.string(),\n        rate: z.number().positive(),\n      })\n      .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    traceViewer: traceViewerSchema.optional(),\n    /** Tool keys (and `'mcp'` or an MCP server name) pinned to the prompt bar by default */\n    defaultPinnedTools: z.array(z.string()).optional(),\n    buildInfo: 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    skills: 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          defaultActiveOnShare: z.boolean().optional(),\n        }),\n      ])\n      .optional(),\n    sharedLinks: z\n      .union([\n        z.boolean(),\n        z.object({\n          create: z.boolean().optional(),\n          share: z.boolean().optional(),\n          public: z.boolean().optional(),\n          snapshotFiles: z.boolean().optional(),\n        }),\n      ])\n      .optional(),\n    schedules: z\n      .union([\n        z.boolean(),\n        z.object({\n          use: z.boolean().optional(),\n          create: z.boolean().optional(),\n          maxPerUser: z.number().int().min(0).optional(),\n          minIntervalMinutes: z.number().int().min(1).optional(),\n          autoDisableAfterFailures: z.number().int().min(1).optional(),\n          admissionConcurrency: z.number().int().min(1).max(100).optional(),\n          fireConcurrency: z.number().int().min(1).optional(),\n          mcpPreflightConcurrency: z.number().int().min(1).max(10).optional(),\n          mcpPreflightTimeoutMs: z.number().int().min(1000).max(600000).optional(),\n          /** Refuse schedules that are not filed under a chat project. Enforced on\n           *  create/update AND at every fire, so raising it later stops schedules\n           *  that predate the policy instead of grandfathering them. */\n          requireProject: z.boolean().optional(),\n          /** Pins every scheduled run to ONE chat project, ignoring any client\n           *  choice. Implies `requireProject`. The project must belong to the\n           *  schedule's owner, so a deployment-wide value only makes sense with a\n           *  per-user/per-role config override. */\n          projectId: z.string().trim().min(1).optional(),\n        }),\n      ])\n      .optional(),\n  })\n  .default({\n    modelSelect: true,\n    parameters: 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    autoSubmitFromUrl: true,\n    runCode: true,\n    webSearch: true,\n    contextUsage: true,\n    contextCost: false,\n    feedback: 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    buildInfo: true,\n    remoteAgents: {\n      use: false,\n      create: false,\n      share: false,\n      public: false,\n    },\n    skills: {\n      use: true,\n      create: true,\n      share: false,\n      public: false,\n      defaultActiveOnShare: false,\n    },\n    sharedLinks: {\n      create: true,\n      share: true,\n      public: true,\n      snapshotFiles: true,\n    },\n    // `schedules` is deliberately ABSENT from this default. It is experimental and\n    // default-off in v1, and zod applies this whole object when `interface` is omitted\n    // from librechat.yaml — including it would silently enable the feature (and permit\n    // billable scheduled runs) on every deployment that never opted in. The PERMISSION\n    // defaults live in updateInterfacePermissions, which is a separate concern.\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 TRumConfig = {\n  provider: 'hyperdx';\n  enabled: boolean;\n  url: string;\n  serviceName: string;\n  authMode: 'publicToken' | 'proxy';\n  publicToken?: string;\n  tracePropagationTargets?: string[];\n  consoleCapture?: boolean;\n  disableReplay?: boolean;\n  advancedNetworkCapture?: boolean;\n  sampleRate?: number;\n  environment?: string;\n};\n\nexport type StartupConfigContext = 'share';\n\n/**\n * Per-endpoint dropParams for the startup config. Most endpoints (e.g. `custom`) map a\n * provider name directly to its dropParams. `azureOpenAI` instead maps a provider name to\n * a per-model dropParams lookup, since each Azure group can drop different parameters.\n */\nexport type EndpointsDropParamsMap = Record<string, string[] | Record<string, string[]>>;\n\nexport type TStartupConfig = {\n  appTitle: string;\n  socialLogins?: string[];\n  langfuseFanoutEnabled?: boolean;\n  langfuseConnectionAccess?: boolean;\n  insightsEnabled?: boolean;\n  /** Manual context compaction, gated by the same `summarization.enabled`\n   *  switch that governs the automatic detour. */\n  compactionEnabled?: boolean;\n  /** Conversation-owned code-environment decision protocol supported by the API.\n   * Clients must not emit selection-less decisions unless this is advertised. */\n  codeEnvironmentDecisionVersion?: typeof CODE_ENVIRONMENT_DECISION_VERSION;\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  /** Admin panel link, only present for users with admin access */\n  adminPanelURL?: string;\n  customFooter?: string;\n  modelSpecs?: TSpecsConfig;\n  modelDescriptions?: Record<string, Record<string, string>>;\n  sharedLinksEnabled: boolean;\n  publicSharedLinksEnabled: boolean;\n  /** Whether shared links snapshot conversation files (gates the per-link \"share files\" checkbox). */\n  sharedLinksSnapshotFilesEnabled?: boolean;\n  /** Effective default timing for when conversation titles become fetchable.\n   * `immediate` = fetch in parallel with the active stream (default);\n   * `final` = fetch only after the stream completes (legacy). */\n  titleGenerationTiming?: 'immediate' | 'final';\n  analyticsGtmId?: string;\n  rum?: TRumConfig;\n  bundlerURL?: string;\n  staticBundlerURL?: string;\n  sharePointFilePickerEnabled?: boolean;\n  sharePointBaseUrl?: string;\n  sharePointPickerGraphScope?: string;\n  sharePointPickerSharePointScope?: string;\n  openidReuseTokens?: boolean;\n  allowAccountDeletion: boolean;\n  minPasswordLength?: number;\n  webSearch?: {\n    searchProvider?: SearchProviders;\n    scraperProvider?: ScraperProviders;\n    rerankerType?: RerankerTypes;\n  };\n  cloudFront?: {\n    cookieRefresh?: {\n      endpoint: string;\n      domain: string;\n    };\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  buildInfo?: {\n    commit?: string | null;\n    commitShort?: string | null;\n    branch?: string | null;\n    buildDate?: string | null;\n  };\n  fileUploadSseEnabled?: boolean;\n  endpointsDropParamsMap?: EndpointsDropParamsMap;\n};\n\nexport type TSharedLinkStartupInterface = Pick<\n  Partial<TInterfaceConfig>,\n  'privacyPolicy' | 'termsOfService'\n>;\n\nexport type TSharedLinkStartupConfig = Pick<TStartupConfig, 'appTitle'> &\n  Pick<\n    Partial<TStartupConfig>,\n    'analyticsGtmId' | 'bundlerURL' | 'customFooter' | 'staticBundlerURL'\n  > & {\n    interface?: TSharedLinkStartupInterface;\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  TAVILY = 'tavily',\n  KEENABLE = 'keenable',\n}\n\nexport enum ScraperProviders {\n  FIRECRAWL = 'firecrawl',\n  SERPER = 'serper',\n  TAVILY = 'tavily',\n  KEENABLE = 'keenable',\n}\n\nexport enum RerankerTypes {\n  JINA = 'jina',\n  COHERE = 'cohere',\n  NONE = 'none',\n}\n\nexport enum SafeSearchTypes {\n  OFF = 0,\n  MODERATE = 1,\n  STRICT = 2,\n}\n\n/**\n * Normalizes a SearXNG engine list into the comma-separated form the API expects.\n * Accepts the YAML list or comma-separated string an operator may write, and is\n * applied both at the schema boundary and when loading the runtime config, since\n * `loadCustomConfig` returns the raw YAML object rather than the parsed result.\n */\nexport function normalizeSearxngEngines(engines?: string | string[]): string | undefined {\n  if (engines == null) {\n    return undefined;\n  }\n  const normalized = (Array.isArray(engines) ? engines : engines.split(','))\n    .map((engine) => engine.trim())\n    .filter(Boolean);\n  return normalized.length ? normalized.join(',') : undefined;\n}\n\nexport const webSearchSchema = z.object({\n  allowedAddresses: allowedAddressesSchema,\n  serperApiKey: z.string().optional().default('${SERPER_API_KEY}'),\n  serperApiKeyPreview: apiKeyPreviewSchema,\n  searxngInstanceUrl: z.string().optional().default('${SEARXNG_INSTANCE_URL}'),\n  searxngApiKey: z.string().optional().default('${SEARXNG_API_KEY}'),\n  searxngApiKeyPreview: apiKeyPreviewSchema,\n  firecrawlApiKey: z.string().optional().default('${FIRECRAWL_API_KEY}'),\n  firecrawlApiKeyPreview: apiKeyPreviewSchema,\n  firecrawlApiUrl: z.string().optional().default('${FIRECRAWL_API_URL}'),\n  firecrawlVersion: z.string().optional().default('${FIRECRAWL_VERSION}'),\n  tavilyApiKey: z.string().optional().default('${TAVILY_API_KEY}'),\n  tavilyApiKeyPreview: apiKeyPreviewSchema,\n  tavilySearchUrl: z.string().optional().default('${TAVILY_SEARCH_URL}'),\n  tavilyExtractUrl: z.string().optional().default('${TAVILY_EXTRACT_URL}'),\n  keenableApiKey: z.string().optional().default('${KEENABLE_API_KEY}'),\n  keenableApiUrl: z.string().optional().default('${KEENABLE_API_URL}'),\n  jinaApiKey: z.string().optional().default('${JINA_API_KEY}'),\n  jinaApiKeyPreview: apiKeyPreviewSchema,\n  jinaApiUrl: z.string().optional().default('${JINA_API_URL}'),\n  cohereApiKey: z.string().optional().default('${COHERE_API_KEY}'),\n  cohereApiKeyPreview: apiKeyPreviewSchema,\n  searchProvider: z.nativeEnum(SearchProviders).optional(),\n  scraperProvider: z.nativeEnum(ScraperProviders).optional(),\n  rerankerType: z.nativeEnum(RerankerTypes).optional(),\n  scraperTimeout: z.number().int().nonnegative().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().int().nonnegative().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  searxngSearchOptions: z\n    .object({\n      engines: z\n        .union([z.string(), z.array(z.string())])\n        .transform(normalizeSearxngEngines)\n        .optional(),\n      language: z.string().optional(),\n      timeRange: z.enum(['day', 'month', 'year']).optional(),\n      timeout: z.number().int().positive().max(120000).optional(),\n    })\n    .optional(),\n  tavilySearchOptions: z\n    .object({\n      searchDepth: z.enum(['basic', 'advanced', 'fast', 'ultra-fast']).optional(),\n      maxResults: z.number().int().min(1).max(20).optional(),\n      includeImages: z.boolean().optional(),\n      includeAnswer: z.union([z.boolean(), z.enum(['basic', 'advanced'])]).optional(),\n      includeRawContent: z.union([z.boolean(), z.enum(['markdown', 'text'])]).optional(),\n      includeDomains: z.array(z.string()).optional(),\n      excludeDomains: z.array(z.string()).optional(),\n      topic: z.enum(['general', 'news', 'finance']).optional(),\n      timeRange: z.enum(['day', 'week', 'month', 'year', 'd', 'w', 'm', 'y']).optional(),\n      includeImageDescriptions: z.boolean().optional(),\n      includeFavicon: z.boolean().optional(),\n      chunksPerSource: z.number().int().min(1).max(3).optional(),\n      safeSearch: z.boolean().optional(),\n      timeout: z.number().int().nonnegative().max(120000).optional(),\n    })\n    .optional(),\n  tavilyScraperOptions: z\n    .object({\n      extractDepth: z.enum(['basic', 'advanced']).optional(),\n      includeImages: z.boolean().optional(),\n      includeFavicon: z.boolean().optional(),\n      format: z.enum(['markdown', 'text']).optional(),\n      timeout: z.number().int().nonnegative().max(120000).optional(),\n    })\n    .optional(),\n  keenableSearchOptions: z\n    .object({\n      maxResults: z.number().int().min(1).max(20).optional(),\n      site: z.string().optional(),\n      attributionTitle: z.string().optional(),\n      timeout: z.number().int().nonnegative().max(120000).optional(),\n    })\n    .optional(),\n  keenableScraperOptions: z\n    .object({\n      attributionTitle: z.string().optional(),\n      timeout: z.number().int().nonnegative().max(120000).optional(),\n    })\n    .optional(),\n});\n\nexport type TWebSearchConfig = DeepPartial<z.infer<typeof webSearchSchema>>;\n\nexport const ocrSchema = z.object({\n  allowedAddresses: allowedAddressesSchema,\n  mistralModel: z.string().optional(),\n  apiKey: z.string().optional().default('${OCR_API_KEY}'),\n  apiKeyPreview: apiKeyPreviewSchema,\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.enum(REFILL_INTERVAL_UNITS).optional().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 DEFAULT_MEMORY_MAX_INPUT_TOKENS = 12000;\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  maxInputTokens: z.number().int().positive().optional().default(DEFAULT_MEMORY_MAX_INPUT_TOKENS),\n  personalize: z.boolean().default(true),\n  messageWindowSize: z.number().optional().default(5),\n  agent: z\n    .union([\n      z.object({\n        enabled: z.boolean().optional(),\n        id: z.string(),\n      }),\n      z.object({\n        enabled: z.boolean().optional(),\n        provider: z.string(),\n        model: z.string(),\n        instructions: z.string().optional(),\n        model_parameters: z.record(z.union([z.string(), z.number(), z.boolean()])).optional(),\n      }),\n    ])\n    .optional(),\n});\n\nexport type TMemoryConfig = DeepPartial<z.infer<typeof memorySchema>>;\n\nexport const summarizationTriggerSchema = z.discriminatedUnion('type', [\n  z.object({\n    type: z.literal('token_ratio'),\n    value: z.number().finite().min(0).max(1),\n  }),\n  z.object({\n    type: z.literal('remaining_tokens'),\n    value: z.number().finite().int().positive(),\n  }),\n  z.object({\n    type: z.literal('messages_to_refine'),\n    value: z.number().finite().int().positive(),\n  }),\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 retainRecentConfigSchema = z.object({\n  turns: z.number().min(0).max(20).optional(),\n  tokens: z.number().positive().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  retainRecent: retainRecentConfigSchema.optional(),\n});\n\nexport type SummarizationConfig = z.infer<typeof summarizationConfigSchema>;\n\nconst customEndpointsSchema = z.array(endpointSchema.partial()).optional();\n\n/**\n * Validates a messageFilter PII regex at config load. Defaults to native RegExp so browser\n * builds add no extra engine; the server injects a check backed by the linear-time runtime\n * engine (RE2) via setMessageFilterRegexValidator, so a pattern the runtime cannot compile\n * (backreferences, lookaround, control escapes, and so on) is rejected at load rather than\n * silently dropped at request time.\n */\ninterface MessageFilterRegexValidation {\n  readonly supported: boolean;\n  readonly programSize?: number;\n}\n\ntype MessageFilterRegexValidationResult = boolean | MessageFilterRegexValidation;\n\nlet messageFilterRegexValidator: (pattern: string) => MessageFilterRegexValidationResult = (\n  value,\n) => {\n  try {\n    new RegExp(value, 'g');\n    return true;\n  } catch {\n    return false;\n  }\n};\n\nexport const setMessageFilterRegexValidator = (\n  validate: (pattern: string) => MessageFilterRegexValidationResult,\n): void => {\n  messageFilterRegexValidator = validate;\n};\n\nconst messageFilterPiiCustomPatternSchema = z.object({\n  id: z.string().min(1).max(MAX_PII_PATTERN_ID_LENGTH),\n  label: z.string().min(1).max(MAX_PII_PATTERN_LABEL_LENGTH),\n  regex: z.string().min(1).max(MAX_PII_PATTERN_LENGTH),\n});\n\nexport const messageFilterPiiSchema = z\n  .object({\n    starterPatterns: z\n      .array(z.string().max(MAX_PII_PATTERN_ID_LENGTH))\n      .max(MAX_PII_PATTERNS_PER_SOURCE)\n      .optional(),\n    customPatterns: z\n      .array(messageFilterPiiCustomPatternSchema)\n      .max(MAX_PII_PATTERNS_PER_SOURCE)\n      .optional(),\n  })\n  .superRefine((pii, context) => {\n    let regexCharacters = 0;\n    let regexInstructions = 0;\n    for (let index = 0; index < (pii.customPatterns?.length ?? 0); index++) {\n      const pattern = pii.customPatterns?.[index];\n      if (pattern == null) {\n        continue;\n      }\n      regexCharacters += pattern.regex.length;\n      const result = messageFilterRegexValidator(pattern.regex);\n      const supported = typeof result === 'boolean' ? result : result.supported;\n      if (!supported) {\n        context.addIssue({\n          code: z.ZodIssueCode.custom,\n          path: ['customPatterns', index, 'regex'],\n          message:\n            'Unsupported regex: not compatible with the RE2 engine (no backreferences, lookaround, or control escapes)',\n        });\n        continue;\n      }\n      if (typeof result !== 'boolean' && result.programSize != null) {\n        regexInstructions += result.programSize;\n      }\n    }\n    if (regexCharacters > MAX_PII_CUSTOM_REGEX_CHARACTERS) {\n      context.addIssue({\n        code: z.ZodIssueCode.custom,\n        path: ['customPatterns'],\n        message: `Custom PII regexes may contain at most ${MAX_PII_CUSTOM_REGEX_CHARACTERS} characters in total`,\n      });\n    }\n    if (regexInstructions > MAX_PII_CUSTOM_REGEX_INSTRUCTIONS) {\n      context.addIssue({\n        code: z.ZodIssueCode.custom,\n        path: ['customPatterns'],\n        message: `Custom PII regexes may compile to at most ${MAX_PII_CUSTOM_REGEX_INSTRUCTIONS} instructions in total`,\n      });\n    }\n  });\n\nexport type MessageFilterPiiConfig = z.infer<typeof messageFilterPiiSchema>;\n\nexport const messageFilterSchema = z.object({\n  pii: messageFilterPiiSchema.optional(),\n});\n\nexport type MessageFilterConfig = z.infer<typeof messageFilterSchema>;\n\n/** User fields a deployment may select as the Langfuse trace `userId`. */\nexport const LANGFUSE_TRACE_USER_ID_FIELDS = [\n  'id',\n  'email',\n  'username',\n  'name',\n  'openidId',\n  'samlId',\n  'ldapId',\n  'googleId',\n  'githubId',\n  'discordId',\n  'appleId',\n  'facebookId',\n] as const;\nexport type LangfuseTraceUserIdField = (typeof LANGFUSE_TRACE_USER_ID_FIELDS)[number];\n\n/** User fields a deployment may copy into Langfuse trace metadata. */\nexport const LANGFUSE_TRACE_USER_METADATA_FIELDS = [\n  ...LANGFUSE_TRACE_USER_ID_FIELDS,\n  'role',\n  'provider',\n] as const;\nexport type LangfuseTraceUserMetadataField = (typeof LANGFUSE_TRACE_USER_METADATA_FIELDS)[number];\n\n/** Request fields a deployment may copy into Langfuse trace metadata. */\nexport const LANGFUSE_TRACE_CONVERSATION_METADATA_FIELDS = [\n  'conversationId',\n  'endpoint',\n  'endpointType',\n  'provider',\n  'model',\n  'modelLabel',\n  'spec',\n] as const;\nexport type LangfuseTraceConversationMetadataField =\n  (typeof LANGFUSE_TRACE_CONVERSATION_METADATA_FIELDS)[number];\n\n/**\n * What a deployment attaches to every Langfuse trace beyond the defaults.\n * Nothing here is exported unless explicitly listed, so the default trace\n * carries only the internal user id and no user or request metadata.\n */\nexport const langfuseTraceConfigSchema = z.object({\n  /**\n   * Which user field becomes the trace `userId`. Defaults to the internal user\n   * id; a user with no value for the chosen field keeps the internal id.\n   */\n  userIdField: z.enum(LANGFUSE_TRACE_USER_ID_FIELDS).optional(),\n  /** User fields exported as `librechat.user.<field>` trace metadata. */\n  userMetadataFields: z.array(z.enum(LANGFUSE_TRACE_USER_METADATA_FIELDS)).optional(),\n  /**\n   * Request fields exported as trace metadata: `librechat.conversation.id`,\n   * `librechat.endpoint`, `librechat.endpoint.type`, `librechat.provider`,\n   * `librechat.model`, `librechat.model.label`, and `librechat.spec`.\n   */\n  conversationMetadataFields: z\n    .array(z.enum(LANGFUSE_TRACE_CONVERSATION_METADATA_FIELDS))\n    .optional(),\n});\n\nexport type LangfuseTraceConfig = z.infer<typeof langfuseTraceConfigSchema>;\n\nexport const langfuseConfigSchema = z.object({\n  enabled: z.boolean().optional(),\n  publicKey: z.string().optional(),\n  secretKey: z.string().optional(),\n  /** Stable Langfuse project identity returned when credentials are verified. */\n  projectId: z.string().optional(),\n  /** Masked preview of the secret key, stored at write time so\n   * admin reads can show which secret key is configured without returning the secret. */\n  secretKeyPreview: z.string().optional(),\n  /** Routing key for one of the deployment-configured tenant Langfuse destinations. */\n  destination: z.string().optional(),\n  /**\n   * Custom request headers sent on every outbound Langfuse request — trace and\n   * media export, feedback scores, and credential verification — for\n   * self-hosted instances behind an authenticating proxy or gateway. Values\n   * support `${ENV_VAR}` interpolation.\n   *\n   * Deployment-level only. Trace export batches spans from every user through\n   * one exporter, so unlike endpoint headers these cannot carry per-user\n   * placeholders. Headers referencing an unset variable, naming an\n   * infrastructure secret, or carrying an invalid HTTP field name are dropped\n   * with a warning rather than sent.\n   *\n   * Sent only when the deployment configures exactly one Langfuse origin, and\n   * only to that origin. The map cannot say which endpoint it authenticates\n   * to, so with several configured origins any choice of recipient would risk\n   * disclosing a gateway credential to the others; a warning is logged instead.\n   * Multi-destination deployments need per-destination headers, which this\n   * schema does not yet express — and note the fanout collector forwards only\n   * `Authorization` upstream regardless.\n   */\n  headers: z.record(z.string()).optional(),\n  /** Trace user identity and allowlisted user/request metadata. */\n  trace: langfuseTraceConfigSchema.optional(),\n});\n\nexport type LangfuseConfig = z.infer<typeof langfuseConfigSchema>;\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  langfuse: langfuseConfigSchema.optional(),\n  memory: memorySchema.optional(),\n  summarization: summarizationConfigSchema.optional(),\n  skillSync: skillSyncConfigSchema,\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      allowedAddresses: allowedAddressesSchema,\n      catalogRecovery: z\n        .object({\n          discoveryBackoffMs: z\n            .array(\n              z\n                .number()\n                .int()\n                .positive()\n                .max(24 * 60 * 60_000),\n            )\n            .min(1)\n            .max(8)\n            .default([5 * 60_000, 10 * 60_000, 20 * 60_000, 30 * 60_000]),\n          discoveryTimeoutMs: z\n            .number()\n            .int()\n            .positive()\n            .max(5 * 60_000)\n            .default(3_000),\n          /** How long past `discoveryTimeoutMs` a stalled discovery may hold its catalog slot and\n           * coalesced requests. It is never cancelled, so OAuth tokens it redeemed still persist,\n           * and no other discovery for the same server state starts until it settles. */\n          discoverySettleGraceMs: z\n            .number()\n            .int()\n            .nonnegative()\n            .max(5 * 60_000)\n            .default(10_000),\n          reauthRetryMs: z\n            .number()\n            .int()\n            .positive()\n            .max(24 * 60 * 60_000)\n            .default(30 * 60_000),\n          maxStateEntries: z.number().int().positive().max(1_000_000).default(10_000),\n          /** Process-wide: how many discoveries released past `discoverySettleGraceMs` may still be\n           * running before recovery starts no new discovery until one settles. The default matches\n           * the three catalog slots a stalled dependency could hold before discoveries were released. */\n          maxDetachedDiscoveries: z.number().int().positive().max(1_000).default(3),\n          generationReadTimeoutMs: z.number().int().positive().max(10_000).default(500),\n          authorizationFenceRetryMs: z\n            .array(z.number().int().nonnegative().max(60_000))\n            .min(1)\n            .max(8)\n            .default([0, 50, 200]),\n          authorizationFenceTimeoutMs: z.number().int().positive().max(30_000).default(1_000),\n          authorizationFenceRetryIntervalMs: z\n            .number()\n            .int()\n            .positive()\n            .max(60 * 60_000)\n            .default(30_000),\n          authorizationFenceRetryBatchSize: z.number().int().positive().max(10_000).default(100),\n        })\n        .default({}),\n    })\n    .optional(),\n  interface: interfaceSchema,\n  turnstile: turnstileSchema.optional(),\n  fileStrategy: fileStorageSchema.default(FileSources.local),\n  fileStrategies: fileStrategiesSchema,\n  cloudfront: cloudfrontConfigSchema,\n  actions: z\n    .object({\n      allowedDomains: z.array(z.string()).optional(),\n      allowedAddresses: allowedAddressesSchema,\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  filters: filtersConfigSchema.optional(),\n  messageFilter: messageFilterSchema.optional(),\n  endpoints: z\n    .object({\n      allowedAddresses: allowedAddressesSchema,\n      /**\n       * Defaults applied to every endpoint. Omit-based, so options added to\n       * `baseEndpointSchema` are inherited here automatically — no list to\n       * maintain (contrast `azureEndpointSchema`, which enumerates via\n       * `.pick()`). Resolution order at read sites is `all` > the named\n       * endpoint > a custom endpoint's own config.\n       */\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>>;\n\n/**\n * Shape of the `webSearch` block as written in `librechat.yaml`, where\n * `searxngSearchOptions.engines` may still be the YAML list or untrimmed string an\n * operator wrote. `loadCustomConfig` returns the raw YAML object rather than the\n * parsed result, so the runtime loader receives this shape, not the parsed one.\n */\nexport type TWebSearchConfigInput = Omit<\n  NonNullable<TCustomConfig['webSearch']>,\n  'searxngSearchOptions'\n> & {\n  searxngSearchOptions?: z.input<typeof webSearchSchema>['searxngSearchOptions'];\n};\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  lemonade = 'lemonade',\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.lemonade]: 'AMD Lemonade',\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\n/**\n * Models the Assistants endpoints cannot run. GPT-6 Astra serves tool calls only\n * from the Responses API, and the Assistants surface does not route through\n * `getOpenAILLMConfig`, so listing it there would offer a configuration the\n * provider rejects. Kept out of `sharedOpenAIModels`, which both Assistants\n * catalogs consume.\n */\nconst responsesOnlyOpenAIModels = ['gpt-6-astra'];\n\nconst sharedOpenAIModels = [\n  'gpt-5.6',\n  'gpt-5.6-terra',\n  'gpt-5.6-luna',\n  'gpt-5.5',\n  'gpt-5.5-pro',\n  'chat-latest',\n  'gpt-5.4',\n  'gpt-5.4-pro',\n  'gpt-5.4-mini',\n  'gpt-5.4-nano',\n  'gpt-5.3-codex',\n  'gpt-5.2',\n  'gpt-5.1',\n  'gpt-5.1-codex',\n  'gpt-5.1-codex-max',\n  'gpt-5.1-codex-mini',\n  'gpt-5',\n  'gpt-5-mini',\n  'gpt-5-nano',\n  'gpt-4.1',\n  'gpt-4.1-mini',\n  'gpt-4.1-nano',\n  'gpt-4o-mini',\n  'gpt-4o',\n];\n\nconst sharedAnthropicModels = [\n  'claude-fable-5-1',\n  'claude-fable-5',\n  'claude-opus-5',\n  'claude-opus-4-8',\n  'claude-opus-4-7',\n  'claude-sonnet-5',\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\n/**\n * Claude 4+ models are not invocable on-demand by their bare foundation-model\n * ID on the Converse path — Bedrock rejects those with \"Invocation of model ID\n * ... with on-demand throughput isn't supported. Retry your request with the ID\n * or ARN of an inference profile that contains this model.\" Default to the\n * `global.` cross-region profile (no regional pricing premium, widest\n * availability); Opus 4.1 has no global profile, so it uses `us.`.\n */\nexport const bedrockModels = [\n  'global.anthropic.claude-fable-5-1',\n  'global.anthropic.claude-fable-5',\n  'global.anthropic.claude-opus-5',\n  'global.anthropic.claude-opus-4-8',\n  'global.anthropic.claude-opus-4-7',\n  'global.anthropic.claude-sonnet-5',\n  'global.anthropic.claude-sonnet-4-6',\n  'global.anthropic.claude-opus-4-6-v1',\n  'global.anthropic.claude-sonnet-4-5-20250929-v1:0',\n  'global.anthropic.claude-haiku-4-5-20251001-v1:0',\n  'us.anthropic.claude-opus-4-1-20250805-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  // TODO: Add agent models (agentsModels)\n  [EModelEndpoint.agents]: [...responsesOnlyOpenAIModels, ...sharedOpenAIModels],\n  [EModelEndpoint.google]: [\n    // Gemini 3.8 Models\n    'gemini-3.8-flash',\n    // Gemini 3.7 Models\n    'gemini-3.7-flash',\n    // Gemini 3.6 Models\n    'gemini-3.6-flash',\n    // Gemini 3.5 Models\n    'gemini-3.5-flash',\n    'gemini-3.5-flash-lite',\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  ],\n  [EModelEndpoint.anthropic]: sharedAnthropicModels,\n  [EModelEndpoint.openAI]: [\n    ...responsesOnlyOpenAIModels,\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\n/**\n * The OpenAI catalog without the models only the first-party OpenAI endpoint\n * can run. Azure OpenAI shares this list, but Astra is neither routed to the\n * Responses API nor given its request constraints there, and listing it first\n * would let it become the default selection.\n */\nconst nonResponsesOnlyOpenAIModels = openAIModels.filter(\n  (model) => !responsesOnlyOpenAIModels.includes(model),\n);\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]: nonResponsesOnlyOpenAIModels,\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 cached group memberships used to resolve ACL user principals.\n   */\n  USER_PRINCIPALS = 'USER_PRINCIPALS',\n  /**\n   * Key for cached prompt group access ID sets (accessible, public, owned).\n   */\n  PROMPT_GROUPS_ACCESS = 'PROMPT_GROUPS_ACCESS',\n  /**\n   * Key for per-conversation stateful code sandbox prewarm/warm state.\n   */\n  SANDBOX_PREWARM = 'SANDBOX_PREWARM',\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 cached authenticated user documents.\n   */\n  AUTH_USER_DOC = 'AUTH_USER_DOC',\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\nexport const AUTH_USER_DOC_BY_ID_PREFIX = 'auth-user-doc-byid';\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   * Shared link retrieval limit violations.\n   */\n  SHARE_LIMIT = 'share_limit',\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   * Google provider could not process a linked video (most often longer than the model accepts)\n   */\n  GOOGLE_VIDEO_UNPROCESSABLE = 'google_video_unprocessable',\n  /**\n   * Required CodeAPI resources could not be restored before model invocation.\n   */\n  RESOURCE_RECOVERY_REQUIRED = 'resource_recovery_required',\n  /**\n   * Agent selected a stateful Code API workspace scope disabled by the deployment.\n   */\n  STATEFUL_CODE_ENVIRONMENT_NOT_ALLOWED = 'stateful_code_environment_not_allowed',\n  /**\n   * A conversation's selected attached workspace cannot be used as requested.\n   */\n  CODE_WORKSPACE_UNAVAILABLE = 'code_workspace_unavailable',\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   * Authentication rejected by a rate limiter\n   */\n  AUTH_RATE_LIMITED = 'auth_rate_limited',\n  /**\n   * Authentication rejected because the account or IP is banned\n   */\n  AUTH_BANNED = 'auth_banned',\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   * Provider does not serve the requested model\n   */\n  MODEL_NOT_FOUND = 'model_not_found',\n  /**\n   * Provider throttled or refused the request for exceeding a rate/spend allowance\n   */\n  MODEL_RATE_LIMIT = 'model_rate_limit',\n  /**\n   * An agent model provider failed and the run could not recover.\n   */\n  UPSTREAM_MODEL_ERROR = 'upstream_model_error',\n  /**\n   * Context pruning removed every message; nothing fits the configured context window\n   */\n  EMPTY_MESSAGES = 'empty_messages',\n  /**\n   * Formatted provider payload exceeded the context budget before invocation\n   */\n  FINAL_CONTEXT_OVERFLOW = 'final_context_overflow',\n  /**\n   * A manual compaction the graph could not attempt; `reason` says why\n   */\n  COMPACTION_SKIPPED = 'compaction_skipped',\n  /**\n   * A manual compaction whose summarizer produced nothing; history is untouched\n   */\n  COMPACTION_FAILED = 'compaction_failed',\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 Langfuse Settings\n   */\n  LANGFUSE = 'langfuse',\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   * Tab for About / Build Info\n   */\n  ABOUT = 'about',\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  /**\n   * Key for the app's version. The placeholder `__LIBRECHAT_VERSION__` is\n   * swapped in by `@rollup/plugin-replace` during `npm run build:data-provider`\n   * using the value of the root `package.json`'s `version` field. Consumers\n   * always import this via the built dist bundle (see `main` field in\n   * `packages/data-provider/package.json`), so production and UI code get the\n   * substituted value. Only tests that import the TypeScript source directly\n   * would observe the raw placeholder.\n   */\n  VERSION = '__LIBRECHAT_VERSION__',\n  /** Key for the Custom Config's version (librechat.yaml). */\n  CONFIG_VERSION = '1.3.16',\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  /** Bash Programmatic Tool Calling tool name */\n  BASH_PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_bash',\n  /** Subagent spawn tool name (must match `@librechat/agents` `Constants.SUBAGENT`). */\n  SUBAGENT = 'subagent',\n  /** Poll tool for retrieving the status/result of a backgrounded tool call. */\n  CHECK_BACKGROUND_TASK = 'check_background_task',\n  /**\n   * `finish_reason` stamped on an assistant message whose turn ended because the\n   * agent exhausted its per-turn graph step budget (`recursionLimit`) rather than\n   * because the model chose to stop. Distinct from a user abort: nothing failed and\n   * nothing was cancelled, the turn simply ran out of room. The UI keys its\n   * \"tool call limit reached\" notice off this value. The hover Continue control\n   * is withheld for this reason because the notice already offers the way forward.\n   */\n  TOOL_CALL_LIMIT_FINISH_REASON = 'tool_call_limit',\n}\n\n/**\n * Normalizes a server name into the character set tool keys are built from.\n * Tool keys embed this output, so any candidate list matched against a key must\n * be normalized the same way.\n */\nexport function normalizeServerName(serverName: string): string {\n  if (/^[a-zA-Z0-9_.-]+$/.test(serverName)) {\n    return serverName;\n  }\n\n  const normalized = serverName.replace(/[^a-zA-Z0-9_.-]/g, '_').replace(/^_+|_+$/g, '');\n  if (normalized) {\n    return normalized;\n  }\n\n  /** All characters were stripped; hash the original so the name stays unique. */\n  let hash = 0;\n  for (let i = 0; i < serverName.length; i++) {\n    hash = (hash << 5) - hash + serverName.charCodeAt(i);\n    hash |= 0;\n  }\n  return `server_${Math.abs(hash)}`;\n}\n\n/**\n * Splits a combined MCP tool key (`${rawToolName}${mcp_delimiter}${serverName}`)\n * back into its two parts.\n *\n * Both halves can legitimately contain the delimiter, so position alone cannot\n * identify the boundary. Raw tool names come from the upstream server and are\n * untrusted (`get_mcp_server_version`, or a gateway-prefixed\n * `gitlab-get_mcp_server_version`), and `normalizeServerName` preserves\n * underscores, so a configured server may be named `Google_mcp_Workspace`.\n *\n * When `knownServerNames` is supplied the boundary is resolved against it: the\n * longest configured name the key actually ends with wins. Otherwise this falls\n * back to the last delimiter, which is correct whenever only the tool half\n * contains one and matches `.split()` when neither does.\n *\n * One case stays undecidable from the key alone: if both `bar` and `foo_mcp_bar`\n * are configured, `tool_mcp_foo_mcp_bar` is a valid key for either. Longest match\n * is the deterministic tiebreak; resolving it properly needs the tool/server\n * mapping carried alongside the key rather than re-derived from the string.\n */\n/**\n * Maps each configured server name's normalized form back to the raw config\n * name. Model-facing tool keys embed `normalizeServerName(server)`, while the\n * registry, config maps, tool cache, and plugin-auth rows are keyed by the raw\n * name — any consumer that parses a server out of a tool key must resolve it\n * through this map before those lookups. Identity entries are included so\n * `aliases.get(name) ?? name` works uniformly.\n *\n * When two configured names normalize to the same value their tool keys are\n * inherently ambiguous; the FIRST configured name wins deterministically here,\n * and `resolveMCPServerContext` warns about the collision so the operator can\n * rename one server.\n */\nexport function buildServerNameAliases(rawServerNames: readonly string[]): Map<string, string> {\n  const aliases = new Map<string, string>();\n  /** Identity entries claim their slot FIRST regardless of configuration\n   *  order: a server literally named `foo` must never have its keys rerouted\n   *  to a `foo!` whose normalized form collides with it. */\n  for (const raw of rawServerNames) {\n    if (raw && normalizeServerName(raw) === raw) {\n      aliases.set(raw, raw);\n    }\n  }\n  for (const raw of rawServerNames) {\n    if (!raw) {\n      continue;\n    }\n    const normalized = normalizeServerName(raw);\n    if (!aliases.has(normalized)) {\n      aliases.set(normalized, raw);\n    }\n  }\n  return aliases;\n}\n\n/**\n * Rewrites a tool key's server segment into the normalized form model-facing\n * keys carry, resolving the boundary against the configured raw names (longest\n * suffix wins, mirroring {@link splitMCPToolKey}). Returns the key unchanged\n * when no configured raw name matches — already-normalized keys, placeholder\n * tokens, and keys for servers that are no longer configured all pass through.\n * Idempotent: a normalized segment never matches a raw candidate that needs\n * rewriting.\n */\nexport function normalizeMCPToolKey(toolKey: string, rawServerNames: readonly string[]): string {\n  let matched: string | undefined;\n  for (let i = 0; i < rawServerNames.length; i++) {\n    const raw = rawServerNames[i];\n    if (!raw || raw.length <= (matched?.length ?? 0)) {\n      continue;\n    }\n    if (toolKey.endsWith(`${Constants.mcp_delimiter}${raw}`)) {\n      matched = raw;\n    }\n  }\n  if (matched == null) {\n    return toolKey;\n  }\n  const normalized = normalizeServerName(matched);\n  if (normalized === matched) {\n    return toolKey;\n  }\n  return `${toolKey.slice(0, toolKey.length - matched.length)}${normalized}`;\n}\n\n/**\n * Strips a redundant leading server-name prefix from a raw upstream tool name\n * before it is embedded into a model-facing key, so the key doesn't carry the\n * server twice (`acme_trace_..._mcp_acme`) and push long tool names\n * past provider function-name limits (64 chars). The match is case-insensitive\n * because display-cased server names (\"Acme\") conventionally prefix their\n * tools in lowercase. Ingestion that strips must record the original name\n * (`serverToolName` on the cached definition) — tool calls send THAT name back\n * to the server, never the stripped one. Catalog producers must not call this\n * directly: only {@link stripServerNamePrefixes} sees the whole sibling set and\n * can keep colliding results apart.\n */\nexport function stripServerNamePrefix(toolName: string, normalizedServerName: string): string {\n  const prefixLength = normalizedServerName.length + 1;\n  if (toolName.length <= prefixLength) {\n    return toolName;\n  }\n  const prefix = toolName.slice(0, prefixLength).toLowerCase();\n  if (prefix !== `${normalizedServerName.toLowerCase()}_`) {\n    return toolName;\n  }\n  const stripped = toolName.slice(prefixLength);\n  if (isReservedMCPToolName(stripped)) {\n    return toolName;\n  }\n  /** `isActionTool` classifies keys by the RELATIVE position of `_action_`\n   *  and `_mcp_`; stripping moves the first `_mcp_` earlier, so a server\n   *  whose normalized name contains `_action_` could see a real MCP tool\n   *  reclassified as an OpenAPI action (bypassing MCP authorization). Never\n   *  produce a key whose classification differs from the raw key's. */\n  const keySuffix = `${Constants.mcp_delimiter}${normalizedServerName}`;\n  if (isActionTool(`${stripped}${keySuffix}`) !== isActionTool(`${toolName}${keySuffix}`)) {\n    return toolName;\n  }\n  return stripped;\n}\n\n/**\n * Synthetic markers consumed by prefix (`isMCPAllPlaceholder`, the server-pin\n * skip, the client's OAuth stream classification), so each reserves BOTH its\n * exact name and its `${marker}${mcp_delimiter}` namespace: a stripped\n * remainder inside any of them would turn a real upstream tool into the\n * server-wide wildcard, the UI pin placeholder, or a synthetic OAuth call.\n */\nconst RESERVED_MCP_TOOL_MARKERS: readonly string[] = [\n  `${Constants.mcp_all}`,\n  `${Constants.mcp_server}`,\n  'oauth',\n];\n\nfunction isReservedMCPToolName(toolName: string): boolean {\n  /** `mcp_` opens the server-scoped pluginKey namespace (`mcp_${serverName}`),\n   *  and `lc_transfer_to_` opens the agent-handoff namespace (the client\n   *  renders such calls as handoffs; the background and intent passes exclude\n   *  them) — pre-strip tool keys could never enter either, since they always\n   *  began with the server name itself. */\n  if (\n    toolName.startsWith(`${Constants.mcp_prefix}`) ||\n    toolName.startsWith(`${Constants.LC_TRANSFER_TO_}`)\n  ) {\n    return true;\n  }\n  return RESERVED_MCP_TOOL_MARKERS.some(\n    (marker) => toolName === marker || toolName.startsWith(`${marker}${Constants.mcp_delimiter}`),\n  );\n}\n\n/**\n * Maps every raw tool name in a server's catalog to its model-facing name,\n * stripping redundant server-name prefixes collision-free: when two names\n * yield the same result — a bare `foo` next to `<server>_foo`, or the\n * case-variant pair `<server>_Foo` / `<Server>_Foo` under the case-insensitive\n * prefix match — every collider keeps its raw name, so two distinct upstream\n * tools can never collapse onto one key. Unprefixed names count against the\n * result set through their identity mapping, which is what makes the bare-name\n * case fall out of the same counter.\n */\nexport function stripServerNamePrefixes(\n  toolNames: readonly string[],\n  normalizedServerName: string,\n): Map<string, string> {\n  const rawNames = new Set(toolNames);\n  const finalNames = new Map<string, string>(\n    toolNames.map((name) => {\n      const stripped = stripServerNamePrefix(name, normalizedServerName);\n      /** Every sibling's RAW name is reserved even when that sibling itself\n       *  strips away: keys persisted BEFORE stripping embed raw names, so a\n       *  stripped result landing on another sibling's raw name would route\n       *  that sibling's legacy references to the wrong upstream tool. */\n      return [name, stripped !== name && rawNames.has(stripped) ? name : stripped];\n    }),\n  );\n  /** Reverting a collider to its raw name can itself collide with ANOTHER\n   *  sibling's stripped result (`foo` / `acme_foo` / `acme_acme_foo`), so the\n   *  guard iterates to a fixpoint. Each pass converts at least one stripped\n   *  result back to its unique raw name, so it terminates within the catalog\n   *  size. */\n  let changed = true;\n  while (changed) {\n    changed = false;\n    const counts = new Map<string, number>();\n    finalNames.forEach((result) => {\n      counts.set(result, (counts.get(result) ?? 0) + 1);\n    });\n    finalNames.forEach((result, raw) => {\n      if (result !== raw && (counts.get(result) ?? 0) > 1) {\n        finalNames.set(raw, raw);\n        changed = true;\n      }\n    });\n  }\n  return finalNames;\n}\n\nexport function splitMCPToolKey(\n  toolKey: string,\n  knownServerNames?: readonly string[],\n): [string, string | undefined] {\n  if (knownServerNames?.length) {\n    let matched: string | undefined;\n    for (let i = 0; i < knownServerNames.length; i++) {\n      const serverName = knownServerNames[i];\n      if (!serverName || serverName.length <= (matched?.length ?? 0)) {\n        continue;\n      }\n      if (toolKey.endsWith(`${Constants.mcp_delimiter}${serverName}`)) {\n        matched = serverName;\n      }\n    }\n    if (matched != null) {\n      return [\n        toolKey.slice(0, toolKey.length - matched.length - Constants.mcp_delimiter.length),\n        matched,\n      ];\n    }\n  }\n\n  const idx = toolKey.lastIndexOf(Constants.mcp_delimiter);\n  if (idx === -1) {\n    return [toolKey, undefined];\n  }\n  return [toolKey.slice(0, idx), toolKey.slice(idx + Constants.mcp_delimiter.length)];\n}\n\n/**\n * Splits a tool-call name for display, where the key may be a synthetic MCP OAuth\n * call (`oauth${mcp_delimiter}${serverName}`) rather than a real tool key.\n *\n * A configured server name is authoritative when one matches, because a real tool key\n * always ends in its server. Only when none matches does the `oauth` prefix decide,\n * which keeps a genuine upstream tool named `oauth${mcp_delimiter}...` from being read\n * as a synthetic call while still resolving OAuth prompts for unconfigured servers.\n */\nexport function splitToolCallName(\n  toolCallName: string,\n  knownServerNames?: readonly string[],\n): [string, string | undefined] {\n  if (knownServerNames?.length) {\n    const [toolName, serverName] = splitMCPToolKey(toolCallName, knownServerNames);\n    if (serverName != null && knownServerNames.includes(serverName)) {\n      return [toolName, serverName];\n    }\n  }\n\n  const oauthPrefix = `oauth${Constants.mcp_delimiter}`;\n  if (toolCallName.startsWith(oauthPrefix)) {\n    return ['oauth', toolCallName.slice(oauthPrefix.length)];\n  }\n  return splitMCPToolKey(toolCallName, knownServerNames);\n}\n\n/** Maximum explicit subagent hops allowed from any root agent at runtime. */\nexport const MAX_SUBAGENT_DEPTH = 5;\n\n/** Maximum unique explicit subagent targets that may be loaded at runtime. */\nexport const MAX_SUBAGENT_GRAPH_NODES = 50;\n\n/** Maximum expanded SubagentConfig entries embedded into one run request. */\nexport const MAX_SUBAGENT_RUN_CONFIGS = 100;\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  /** Last checked toggle for Skills per conversation ID */\n  LAST_SKILLS_TOGGLE_ = 'LAST_SKILLS_TOGGLE_',\n  /** Last checked toggle for Memory per conversation ID */\n  LAST_MEMORY_TOGGLE_ = 'LAST_MEMORY_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","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  CODE_ENVIRONMENT = 'codeEnvironment',\n  PROMPTGROUP = 'promptGroup',\n  MCPSERVER = 'mcpServer',\n  REMOTE_AGENT = 'remoteAgent',\n  SKILL = 'skill',\n  SHARED_LINK = 'sharedLink',\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  /** 10000 - Can view Insights data for an agent when VIEW is also present */\n  VIEW_INSIGHTS = 16,\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  CODE_ENVIRONMENT_VIEWER = 'codeEnvironment_viewer',\n  CODE_ENVIRONMENT_EDITOR = 'codeEnvironment_editor',\n  CODE_ENVIRONMENT_OWNER = 'codeEnvironment_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  SKILL_VIEWER = 'skill_viewer',\n  SKILL_EDITOR = 'skill_editor',\n  SKILL_OWNER = 'skill_owner',\n  SHARED_LINK_VIEWER = 'sharedLink_viewer',\n  SHARED_LINK_OWNER = 'sharedLink_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  viewInsights: z.boolean().optional(),\n  isAdmin: z.boolean().optional(),\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().optional(),\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().optional(),\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  isAdmin?: boolean;\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.CODE_ENVIRONMENT_VIEWER:\n    case AccessRoleIds.PROMPTGROUP_VIEWER:\n    case AccessRoleIds.MCPSERVER_VIEWER:\n    case AccessRoleIds.REMOTE_AGENT_VIEWER:\n    case AccessRoleIds.SKILL_VIEWER:\n    case AccessRoleIds.SHARED_LINK_VIEWER:\n      return PermissionBits.VIEW;\n    case AccessRoleIds.AGENT_EDITOR:\n    case AccessRoleIds.CODE_ENVIRONMENT_EDITOR:\n    case AccessRoleIds.PROMPTGROUP_EDITOR:\n    case AccessRoleIds.MCPSERVER_EDITOR:\n    case AccessRoleIds.REMOTE_AGENT_EDITOR:\n    case AccessRoleIds.SKILL_EDITOR:\n      return PermissionBits.VIEW | PermissionBits.EDIT;\n    case AccessRoleIds.AGENT_OWNER:\n    case AccessRoleIds.CODE_ENVIRONMENT_OWNER:\n    case AccessRoleIds.PROMPTGROUP_OWNER:\n    case AccessRoleIds.MCPSERVER_OWNER:\n    case AccessRoleIds.REMOTE_AGENT_OWNER:\n    case AccessRoleIds.SKILL_OWNER:\n    case AccessRoleIds.SHARED_LINK_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","export enum QueryKeys {\n  messages = 'messages',\n  sharedMessages = 'sharedMessages',\n  sharedStartupConfig = 'sharedStartupConfig',\n  sharedLinks = 'sharedLinks',\n  allConversations = 'allConversations',\n  archivedConversations = 'archivedConversations',\n  pinnedConversations = 'pinnedConversations',\n  searchConversations = 'searchConversations',\n  conversation = 'conversation',\n  searchEnabled = 'searchEnabled',\n  langfuseConnection = 'langfuseConnection',\n  langfuseSessionLink = 'langfuseSessionLink',\n  conversationTraceAvailability = 'conversationTraceAvailability',\n  conversationTraceRecords = 'conversationTraceRecords',\n  conversationTraceRecord = 'conversationTraceRecord',\n  user = 'user',\n  name = 'name', // user key name\n  models = 'models',\n  balance = 'balance',\n  endpoints = 'endpoints',\n  tokenConfig = 'tokenConfig',\n  presets = 'presets',\n  searchResults = 'searchResults',\n  tokenCount = 'tokenCount',\n  availablePlugins = 'availablePlugins',\n  startupConfig = 'startupConfig',\n  insights = 'insights',\n  insightsAccess = 'insightsAccess',\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  filePreview = 'filePreview',\n  voices = 'voices',\n  customConfigSpeech = 'customConfigSpeech',\n  prompts = 'prompts',\n  prompt = 'prompt',\n  promptGroups = 'promptGroups',\n  allPromptGroups = 'allPromptGroups',\n  promptGroup = 'promptGroup',\n  projects = 'projects',\n  project = 'project',\n  projectConversations = 'projectConversations',\n  categories = 'categories',\n  randomPrompts = 'randomPrompts',\n  agentCategories = 'agentCategories',\n  marketplaceAgents = 'marketplaceAgents',\n  roles = 'roles',\n  rolesList = 'rolesList',\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  /* Skills */\n  skills = 'skills',\n  skill = 'skill',\n  skillFiles = 'skillFiles',\n  skillFileContent = 'skillFileContent',\n  /* Skill tree (phase 2 — filesystem-style node view) */\n  skillTree = 'skillTree',\n  skillNodeContent = 'skillNodeContent',\n  /* Tool favorites (starred marketplace items) */\n  toolFavorites = 'toolFavorites',\n  /* Per-user skill active/inactive overrides */\n  skillStates = 'skillStates',\n  /* General user favorites */\n  favorites = 'favorites',\n  /* Scheduled chats */\n  schedules = 'schedules',\n  schedule = 'schedule',\n  parentSubagents = 'parentSubagents',\n  subagentThread = 'subagentThread',\n  codeEnvironments = 'codeEnvironments',\n  agentQueuedTurns = 'agentQueuedTurns',\n  /* Combined Pinned-section display order (favorites + pinned chats) */\n  pinnedOrder = 'pinnedOrder',\n}\n\n// Dynamic query keys that require parameters\nexport const DynamicQueryKeys = {\n  agentFiles: (agentId: string) => ['agentFiles', agentId] as const,\n  codeEnvironmentStatus: (id: string) => [QueryKeys.codeEnvironments, id, 'status'] as const,\n} as const;\n\nexport enum MutationKeys {\n  subagentControl = 'subagentControl',\n  enqueueAgentQueuedTurn = 'enqueueAgentQueuedTurn',\n  cancelAgentQueuedTurn = 'cancelAgentQueuedTurn',\n  /** Whole-array favorites write, keyed so every hook instance's write is\n   *  visible to the others through the query client. */\n  updateFavorites = 'updateFavorites',\n  /** Pinned-section display order write, keyed for the same reason. */\n  updatePinnedOrder = 'updatePinnedOrder',\n  updateLangfuseConnection = 'updateLangfuseConnection',\n  testLangfuseConnection = 'testLangfuseConnection',\n  createAgentApiKey = 'createAgentApiKey',\n  deleteAgentApiKey = 'deleteAgentApiKey',\n  fileUpload = 'fileUpload',\n  fileDelete = 'fileDelete',\n  fileUsage = 'fileUsage',\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  updateUserPreferences = 'updateUserPreferences',\n  updateRole = 'updateRole',\n  enableTwoFactor = 'enableTwoFactor',\n  verifyTwoFactor = 'verifyTwoFactor',\n  updateMemoryPreferences = 'updateMemoryPreferences',\n  createProject = 'createProject',\n  updateProject = 'updateProject',\n  deleteProject = 'deleteProject',\n  assignConversationToProject = 'assignConversationToProject',\n  /* Skill mutations from the original UI PR — tree/node operations are\n   * phase 2 and currently stubbed in the data-service layer. */\n  createSkillNode = 'createSkillNode',\n  updateSkillNode = 'updateSkillNode',\n  deleteSkillNode = 'deleteSkillNode',\n  updateSkillNodeContent = 'updateSkillNodeContent',\n  convoPin = 'convoPin',\n  archiveAllConversations = 'archiveAllConversations',\n  createSchedule = 'createSchedule',\n  updateSchedule = 'updateSchedule',\n  deleteSchedule = 'deleteSchedule',\n  runSchedule = 'runSchedule',\n  pairCodeEnvironment = 'pairCodeEnvironment',\n  updateCodeEnvironmentSettings = 'updateCodeEnvironmentSettings',\n  deleteCodeEnvironment = 'deleteCodeEnvironment',\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\nexport function getTokenHeader(): string | undefined {\n  const authorization = axios.defaults.headers.common['Authorization'];\n  return typeof authorization === 'string' ? authorization : undefined;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport axios from 'axios';\nimport type { AxiosRequestConfig, AxiosResponse } from 'axios';\nimport type * as t from './types';\nimport { setTokenHeader } from './headers-helpers';\nimport * as endpoints from './api-endpoints';\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 = unknown>(\n  url: string,\n  options?: AxiosRequestConfig,\n): Promise<AxiosResponse<T>> {\n  return await axios.get<T>(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\nconst AUTH_RECOVERY_EVENT = 'authRecovery';\nconst AUTH_REDIRECT_EVENT = 'authRedirectStarted';\nconst AUTH_REDIRECT_STORAGE_KEY = 'librechat.auth.redirect.startedAt';\nconst AUTH_REDIRECT_DEDUPE_MS = 15_000;\nconst TOKEN_REFRESH_BUFFER_MS = 2 * 60 * 1000;\n\ntype RetryableAxiosRequestConfig = AxiosRequestConfig & { _retry?: boolean };\n\ntype AuthRecoveryState = {\n  lastRedirectStartedAt: number;\n  refreshPromise: Promise<string | null> | null;\n};\n\ntype AuthRecoveryWindow = Window & {\n  __librechatAuthRecovery?: AuthRecoveryState;\n};\n\nconst refreshToken = (retry?: boolean): Promise<t.TRefreshTokenResponse | undefined> =>\n  _post(endpoints.refreshToken(retry));\n\nconst SHARE_PAGE_PATH_REGEX = /^\\/share\\/[^/]+\\/?$/;\nconst SHARED_MESSAGES_PATH_REGEX = /^\\/api\\/share\\/[^/]+$/;\nconst SHARE_FORK_PATH_REGEX = /^\\/api\\/share\\/[^/]+\\/fork$/;\n\nconst normalizePathname = (pathname: string) =>\n  pathname.startsWith('/') ? pathname : `/${pathname}`;\n\nconst stripBasePath = (pathname: string) => {\n  const normalizedPathname = normalizePathname(pathname);\n  const baseUrl = endpoints.apiBaseUrl();\n  if (!baseUrl) {\n    return normalizedPathname;\n  }\n\n  const normalizedBaseUrl = normalizePathname(baseUrl);\n  if (\n    normalizedPathname === normalizedBaseUrl ||\n    normalizedPathname.startsWith(`${normalizedBaseUrl}/`)\n  ) {\n    return normalizedPathname.slice(normalizedBaseUrl.length) || '/';\n  }\n  return normalizedPathname;\n};\n\nconst isSharePage = () => SHARE_PAGE_PATH_REGEX.test(stripBasePath(window.location.pathname));\n\nconst getRequestPathname = (url?: string) => {\n  if (typeof url !== 'string') {\n    return '';\n  }\n  try {\n    return new URL(url, window.location.origin).pathname;\n  } catch {\n    return url.split(/[?#]/)[0] ?? '';\n  }\n};\n\nconst isSharedMessagesRequest = (url?: string, method?: string) =>\n  method?.toLowerCase() === 'get' &&\n  SHARED_MESSAGES_PATH_REGEX.test(stripBasePath(getRequestPathname(url)));\n\n/** The \"continue this chat\" fork is a deliberate authenticated action initiated\n *  from a share page, so it must reach auth recovery/redirect like the shared\n *  data request — otherwise a logged-out (or cold-loaded) viewer's 401 is\n *  rejected silently instead of routing them through login. */\nconst isShareForkRequest = (url?: string, method?: string) =>\n  method?.toLowerCase() === 'post' &&\n  SHARE_FORK_PATH_REGEX.test(stripBasePath(getRequestPathname(url)));\n\nconst dispatchTokenUpdatedEvent = (token: string) => {\n  setTokenHeader(token);\n  clearAuthRedirectStartedAt();\n  window.dispatchEvent(new CustomEvent('tokenUpdated', { detail: token }));\n};\n\nconst getAuthRecoveryState = (): AuthRecoveryState => {\n  const browserWindow = window as AuthRecoveryWindow;\n  browserWindow.__librechatAuthRecovery ??= {\n    lastRedirectStartedAt: 0,\n    refreshPromise: null,\n  };\n  return browserWindow.__librechatAuthRecovery;\n};\n\nconst getAuthRedirectStartedAt = () => {\n  const state = getAuthRecoveryState();\n  try {\n    const startedAt = window.localStorage.getItem(AUTH_REDIRECT_STORAGE_KEY);\n    const storedStartedAt = startedAt != null ? Number(startedAt) : 0;\n    const finiteStartedAt = Number.isFinite(storedStartedAt) ? storedStartedAt : 0;\n    return Math.max(finiteStartedAt, state.lastRedirectStartedAt);\n  } catch {\n    return state.lastRedirectStartedAt;\n  }\n};\n\nconst setAuthRedirectStartedAt = () => {\n  const state = getAuthRecoveryState();\n  state.lastRedirectStartedAt = Date.now();\n  try {\n    window.localStorage.setItem(AUTH_REDIRECT_STORAGE_KEY, String(state.lastRedirectStartedAt));\n  } catch {\n    // localStorage can be blocked in embedded/private contexts.\n  }\n};\n\nconst clearAuthRedirectStartedAt = () => {\n  const state = getAuthRecoveryState();\n  state.lastRedirectStartedAt = 0;\n  try {\n    window.localStorage.removeItem(AUTH_REDIRECT_STORAGE_KEY);\n  } catch {\n    // Ignore unavailable storage.\n  }\n};\n\nconst isAuthRedirectInProgress = () => {\n  const startedAt = getAuthRedirectStartedAt();\n  return (\n    Number.isFinite(startedAt) && startedAt > 0 && Date.now() - startedAt < AUTH_REDIRECT_DEDUPE_MS\n  );\n};\n\nconst dispatchAuthRecoveryEvent = (state: 'started' | 'finished') => {\n  window.dispatchEvent(new CustomEvent(AUTH_RECOVERY_EVENT, { detail: { state } }));\n};\n\nconst setRequestAuthorizationHeader = (config: AxiosRequestConfig, token: string) => {\n  const headers = (config.headers ?? {}) as Record<string, string>;\n  headers['Authorization'] = `Bearer ${token}`;\n  config.headers = headers;\n};\n\nconst isAuthRecoveryEndpoint = (url?: string) =>\n  url?.includes('/api/auth/2fa') === true ||\n  url?.includes('/api/auth/logout') === true ||\n  url?.includes('/api/auth/refresh') === true;\n\nconst startAuthRecovery = (retryRefresh?: boolean) => {\n  const state = getAuthRecoveryState();\n  if (state.refreshPromise) {\n    return state.refreshPromise;\n  }\n\n  dispatchAuthRecoveryEvent('started');\n  state.refreshPromise = refreshToken(retryRefresh)\n    .then((response) => {\n      const token = response?.token ?? '';\n      if (!token) {\n        return null;\n      }\n      dispatchTokenUpdatedEvent(token);\n      return token;\n    })\n    .finally(() => {\n      state.refreshPromise = null;\n      dispatchAuthRecoveryEvent('finished');\n    });\n\n  return state.refreshPromise;\n};\n\nconst redirectToLoginOnce = () => {\n  if (isAuthRedirectInProgress()) {\n    return;\n  }\n\n  const href = endpoints.apiBaseUrl() + endpoints.buildLoginRedirectUrl();\n  setAuthRedirectStartedAt();\n  window.dispatchEvent(new CustomEvent(AUTH_REDIRECT_EVENT, { detail: { href } }));\n  window.location.href = href;\n};\n\nconst getBearerToken = () => {\n  const authorization = axios.defaults.headers.common['Authorization'];\n  if (typeof authorization !== 'string' || !authorization.startsWith('Bearer ')) {\n    return null;\n  }\n  return authorization.slice('Bearer '.length);\n};\n\nconst getJwtExpiryMs = (token: string) => {\n  const payload = token.split('.')[1];\n  if (!payload) {\n    return null;\n  }\n\n  try {\n    const normalizedPayload = payload.replace(/-/g, '+').replace(/_/g, '/');\n    const paddedPayload = normalizedPayload.padEnd(\n      normalizedPayload.length + ((4 - (normalizedPayload.length % 4)) % 4),\n      '=',\n    );\n    const decodedPayload = JSON.parse(window.atob(paddedPayload)) as { exp?: number };\n    return typeof decodedPayload.exp === 'number' ? decodedPayload.exp * 1000 : null;\n  } catch {\n    return null;\n  }\n};\n\nconst shouldRefreshBeforeRequest = (url?: string) => {\n  if (isAuthRecoveryEndpoint(url) || isAuthRedirectInProgress()) {\n    return false;\n  }\n\n  const token = getBearerToken();\n  if (!token) {\n    return false;\n  }\n\n  const expiresAt = getJwtExpiryMs(token);\n  if (expiresAt == null) {\n    return false;\n  }\n\n  const timeUntilExpiry = expiresAt - Date.now();\n  return timeUntilExpiry > 0 && timeUntilExpiry <= TOKEN_REFRESH_BUFFER_MS;\n};\n\nconst refreshBeforeRequest = async (url?: string) => {\n  const state = getAuthRecoveryState();\n  if (state.refreshPromise && !isAuthRecoveryEndpoint(url)) {\n    return state.refreshPromise.catch(() => null);\n  }\n\n  if (!shouldRefreshBeforeRequest(url)) {\n    return null;\n  }\n\n  return startAuthRecovery(false).catch(() => null);\n};\n\nconst withAuthorization = (options: RequestInit | undefined, token: string | null): RequestInit => {\n  const headers = new Headers(options?.headers);\n  if (token) {\n    headers.set('Authorization', `Bearer ${token}`);\n  }\n  return { ...options, headers };\n};\n\nasync function _authenticatedFetch(url: string, options?: RequestInit): Promise<Response> {\n  if (typeof window === 'undefined') {\n    return fetch(url, options);\n  }\n\n  const token = (await refreshBeforeRequest(url)) ?? getBearerToken();\n  const response = await fetch(url, withAuthorization(options, token));\n  if (\n    response.status !== 401 ||\n    isAuthRecoveryEndpoint(url) ||\n    isAuthRedirectInProgress() ||\n    !getBearerToken()\n  ) {\n    return response;\n  }\n\n  let refreshedToken: string | null;\n  try {\n    refreshedToken = await startAuthRecovery(false);\n  } catch {\n    redirectToLoginOnce();\n    return response;\n  }\n\n  if (!refreshedToken) {\n    redirectToLoginOnce();\n    return response;\n  }\n\n  await response.body?.cancel().catch(() => undefined);\n  return fetch(url, withAuthorization(options, refreshedToken));\n}\n\nif (typeof window !== 'undefined') {\n  axios.interceptors.request.use(async (config) => {\n    const token = await refreshBeforeRequest(config.url);\n    if (token) {\n      setRequestAuthorizationHeader(config, token);\n    }\n    return config;\n  });\n\n  axios.interceptors.response.use(\n    (response) => response,\n    async (error) => {\n      const originalRequest = error.config as RetryableAxiosRequestConfig | undefined;\n      if (!error.response) {\n        return Promise.reject(error);\n      }\n      if (!originalRequest) {\n        return Promise.reject(error);\n      }\n\n      const isRefreshRequest = originalRequest.url?.includes('/api/auth/refresh') === true;\n      if (isAuthRecoveryEndpoint(originalRequest.url) && !isRefreshRequest) {\n        return Promise.reject(error);\n      }\n\n      if (isRefreshRequest && getAuthRecoveryState().refreshPromise) {\n        return Promise.reject(error);\n      }\n\n      /** Skip refresh when the Authorization header has been cleared (e.g. during logout),\n       *  but allow the shared link data request to proceed so private shares can still\n       *  recover auth/redirect without unrelated share-page queries forcing login. */\n      if (\n        !axios.defaults.headers.common['Authorization'] &&\n        !(\n          isSharePage() &&\n          (isSharedMessagesRequest(originalRequest.url, originalRequest.method) ||\n            isShareForkRequest(originalRequest.url, originalRequest.method))\n        )\n      ) {\n        return Promise.reject(error);\n      }\n\n      if (isAuthRedirectInProgress()) {\n        return Promise.reject(error);\n      }\n\n      if (error.response.status === 401 && !originalRequest._retry) {\n        const hasActiveRecovery = getAuthRecoveryState().refreshPromise != null;\n        if (!hasActiveRecovery) {\n          console.warn('401 error, refreshing token');\n        }\n        originalRequest._retry = true;\n\n        try {\n          const token = await startAuthRecovery(\n            // Handle edge case where we get a blank screen if the initial 401 error is from a refresh token request\n            isRefreshRequest,\n          );\n\n          if (token) {\n            setRequestAuthorizationHeader(originalRequest, token);\n            return await axios(originalRequest);\n          }\n\n          redirectToLoginOnce();\n          return Promise.reject(error);\n        } catch {\n          /** A rejected refresh (stale/invalid session → 401/403) must route to\n           *  login just like an empty-token refresh, otherwise the original 401\n           *  surfaces to the caller (e.g. the share fork button) with no redirect. */\n          redirectToLoginOnce();\n          return Promise.reject(error);\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  authenticatedFetch: _authenticatedFetch,\n  refreshToken,\n  dispatchTokenUpdatedEvent,\n};\n","import type { EToolResources } from './types/assistants';\nimport type { TFileUpload } from './types/files';\nimport request from './request';\n\nconst EVENT_STREAM_MEDIA_TYPE = 'text/event-stream';\nconst HEARTBEAT_TIMEOUT_MS = 15_000;\n\ninterface UploadErrorData {\n  message?: string;\n  code?: number;\n  temp_file_id?: string;\n  tool_resource?: EToolResources;\n  display_to_user?: boolean;\n}\n\ninterface ParsedEvent {\n  type: string;\n  data: string;\n}\n\nclass FileUploadError extends Error {\n  public code: number;\n  public file_id: string;\n  public tool_resource?: EToolResources;\n  public display_to_user: boolean;\n  public response: { data: { message: string } };\n\n  constructor(\n    message: string,\n    fileId: string,\n    toolResource?: EToolResources,\n    displayToUser = false,\n    code = 0,\n  ) {\n    super(message);\n    this.name = 'CustomAppError';\n    this.code = code;\n    this.file_id = fileId;\n    this.tool_resource = toolResource;\n    this.display_to_user = displayToUser;\n    this.response = { data: { message: displayToUser ? message : '' } };\n  }\n}\n\nclass UploadCanceledError extends Error {\n  public code = 'ERR_CANCELED' as const;\n}\n\nconst getFileId = (formData: FormData) => String(formData.get('file_id') ?? '');\n\nconst getToolResource = (formData: FormData) =>\n  (formData.get('tool_resource') as EToolResources | null) ?? undefined;\n\nconst parseEvent = (message: string): ParsedEvent => {\n  let type = 'message';\n  const data: string[] = [];\n\n  for (const line of message.split(/\\r?\\n/)) {\n    if (line.startsWith('event:')) {\n      type = line.slice('event:'.length).trim();\n      continue;\n    }\n    if (line.startsWith('data:')) {\n      data.push(line.slice('data:'.length).trimStart());\n    }\n  }\n\n  return { type, data: data.join('\\n') };\n};\n\nconst createHttpError = async (response: Response, formData: FormData) => {\n  let message = `Server responded with status: ${response.status}`;\n  try {\n    const data = (await response.json()) as { message?: string };\n    message = data.message || message;\n  } catch {\n    // Preserve the status-based fallback for non-JSON responses.\n  }\n\n  return new FileUploadError(\n    message,\n    getFileId(formData),\n    getToolResource(formData),\n    true,\n    response.status,\n  );\n};\n\nconst createStreamError = (data: string, formData: FormData) => {\n  let error: UploadErrorData;\n  try {\n    error = JSON.parse(data) as UploadErrorData;\n  } catch {\n    error = { message: data };\n  }\n\n  return new FileUploadError(\n    error.message || 'File upload failed.',\n    error.temp_file_id || getFileId(formData),\n    error.tool_resource || getToolResource(formData),\n    error.display_to_user ?? false,\n    error.code ?? 0,\n  );\n};\n\nconst readEventStream = async (\n  stream: ReadableStream<Uint8Array>,\n  formData: FormData,\n): Promise<TFileUpload> => {\n  const reader = stream.getReader();\n  const decoder = new TextDecoder();\n  let buffer = '';\n  let result: TFileUpload | null = null;\n  let streamEnded = false;\n  let timeoutError: Error | null = null;\n  let heartbeatTimer: ReturnType<typeof setTimeout> | undefined;\n\n  const resetHeartbeatTimer = () => {\n    clearTimeout(heartbeatTimer);\n    heartbeatTimer = setTimeout(() => {\n      timeoutError = new Error('Upload connection timed out waiting for a heartbeat.');\n      void reader.cancel(timeoutError);\n    }, HEARTBEAT_TIMEOUT_MS);\n  };\n\n  resetHeartbeatTimer();\n\n  try {\n    while (true) {\n      const { value, done } = await reader.read();\n      if (done) {\n        streamEnded = true;\n        if (timeoutError) {\n          throw timeoutError;\n        }\n        if (result) {\n          return result;\n        }\n        throw new Error('Upload connection closed before completion.');\n      }\n\n      buffer += decoder.decode(value, { stream: true });\n      const messages = buffer.split(/\\r?\\n\\r?\\n/);\n      buffer = messages.pop() ?? '';\n\n      for (const message of messages) {\n        const event = parseEvent(message);\n        if (event.type === 'heartbeat') {\n          resetHeartbeatTimer();\n          continue;\n        }\n        if (event.type === 'error') {\n          throw createStreamError(event.data, formData);\n        }\n        if (event.type === 'data') {\n          result = JSON.parse(event.data) as TFileUpload;\n          continue;\n        }\n        if (event.type === 'close') {\n          if (result) {\n            return result;\n          }\n          throw new Error('Upload stream closed without a result.');\n        }\n      }\n    }\n  } catch (error) {\n    if (error instanceof Error && error.name === 'AbortError') {\n      throw new UploadCanceledError('Upload canceled.');\n    }\n    throw error;\n  } finally {\n    clearTimeout(heartbeatTimer);\n    if (!streamEnded) {\n      await reader.cancel().catch(() => undefined);\n    }\n    reader.releaseLock();\n  }\n};\n\nexport async function uploadEventStream(\n  url: string,\n  formData: FormData,\n  signal?: AbortSignal | null,\n): Promise<TFileUpload> {\n  try {\n    const response = await request.authenticatedFetch(url, {\n      method: 'POST',\n      body: formData,\n      headers: { Accept: EVENT_STREAM_MEDIA_TYPE },\n      signal: signal ?? undefined,\n    });\n    if (!response.ok) {\n      throw await createHttpError(response, formData);\n    }\n\n    const contentType = response.headers.get('Content-Type')?.toLowerCase() ?? '';\n    if (!contentType.includes(EVENT_STREAM_MEDIA_TYPE)) {\n      return (await response.json()) as TFileUpload;\n    }\n    if (!response.body) {\n      throw new Error('No upload response body received.');\n    }\n\n    return await readEventStream(response.body, formData);\n  } catch (error) {\n    if (signal?.aborted || (error instanceof Error && error.name === 'AbortError')) {\n      throw new UploadCanceledError('Upload canceled.');\n    }\n    throw error;\n  }\n}\n","import type { AxiosResponse } from 'axios';\nimport type {\n  TTracePage,\n  TTracePageParams,\n  TTraceAvailability,\n  TTraceRecordParams,\n  TTraceRecordDetail,\n} from './types/traces';\nimport type { TInsightsAccessResponse, TInsightsParams, TInsightsResponse } from './types/insights';\nimport type { TFileConfig } from './file-config';\nimport type * as t from './types';\nimport * as permissions from './accessPermissions';\nimport * as endpoints from './api-endpoints';\nimport { uploadEventStream } from './upload';\nimport * as mcp from './types/mcpServers';\nimport * as qt from './types/queuedTurns';\nimport * as sch from './types/schedules';\nimport * as a from './types/assistants';\nimport * as m from './types/mutations';\nimport * as ag from './types/agents';\nimport * as q from './types/queries';\nimport * as sk from './types/skills';\nimport * as f from './types/files';\nimport * as config from './config';\nimport request from './request';\nimport * as s from './schemas';\nimport * as r from './roles';\n\nexport function getInsights(params: TInsightsParams = {}): Promise<TInsightsResponse> {\n  const query = new URLSearchParams();\n  for (const [key, value] of Object.entries(params)) {\n    if (Array.isArray(value)) {\n      value.forEach((item) => query.append(key, String(item)));\n    } else if (value !== undefined && value !== null && value !== '') {\n      query.set(key, String(value));\n    }\n  }\n  const suffix = query.toString() ? `?${query.toString()}` : '';\n  return request.get(`${endpoints.insights()}${suffix}`);\n}\n\nexport function getInsightsAccess(): Promise<TInsightsAccessResponse> {\n  return request.get(endpoints.insightsAccess());\n}\n\nexport function getConversationTraceAvailability(\n  conversationId: string,\n): Promise<TTraceAvailability> {\n  return request.get(endpoints.conversationTraceAvailability(conversationId));\n}\n\nexport function getConversationTraceRecords(\n  { conversationId, cursor }: TTracePageParams,\n  signal?: AbortSignal,\n): Promise<TTracePage> {\n  return request.get(\n    endpoints.conversationTraceRecords(conversationId, cursor),\n    signal ? { signal } : undefined,\n  );\n}\n\nexport function getConversationTraceRecord(\n  { conversationId, recordId, messageId, sourceId }: TTraceRecordParams,\n  signal?: AbortSignal,\n): Promise<TTraceRecordDetail> {\n  return request.get(\n    endpoints.conversationTraceRecord(conversationId, recordId, messageId, sourceId),\n    signal ? { signal } : undefined,\n  );\n}\n\nexport function getLangfuseConnection(): Promise<t.TLangfuseConnectionStatus> {\n  return request.get(endpoints.adminLangfuseConnection());\n}\n\nexport function updateLangfuseConnection(\n  payload: t.TUpdateLangfuseConnectionRequest,\n): Promise<t.TLangfuseConnectionStatus> {\n  return request.put(endpoints.adminLangfuseConnection(), payload);\n}\n\nexport function testLangfuseConnection(\n  payload: t.TLangfuseConnectionTestRequest,\n): Promise<t.TLangfuseConnectionTestResponse> {\n  return request.post(endpoints.adminLangfuseConnectionTest(), payload);\n}\n\nexport function getLangfuseSessionLink(\n  conversationId: string,\n): Promise<t.TLangfuseSessionLinkResponse> {\n  return request.get(endpoints.adminLangfuseSessionLink(conversationId));\n}\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 function getCodeEnvironments(): Promise<t.TCodeEnvironmentsResponse> {\n  return request.get(endpoints.codeEnvironments());\n}\n\nexport function getCodeEnvironmentStatus(id: string): Promise<t.TCodeEnvironmentStatusResponse> {\n  return request.get(endpoints.codeEnvironmentStatus(id));\n}\n\nexport function pairCodeEnvironment(payload: {\n  name: string;\n  controlPlaneId: string;\n}): Promise<t.TCodeEnvironmentPairingResponse> {\n  return request.post(endpoints.codeEnvironmentPairings(), payload);\n}\n\nexport function deleteCodeEnvironment(\n  id: string,\n): Promise<{ environment: t.TCodeEnvironmentSummary }> {\n  return request.delete(endpoints.codeEnvironmentById(id));\n}\n\nexport function updateCodeEnvironmentSettings({\n  id,\n  settings,\n}: {\n  id: string;\n  settings: config.CodeEnvironmentUserSettings;\n}): Promise<{ environment: t.TCodeEnvironmentSummary }> {\n  return request.patch(endpoints.codeEnvironmentSettings(id), { settings });\n}\n\nexport function getFavorites(): Promise<q.TUserFavorite[]> {\n  return request.get(`${endpoints.apiBaseUrl()}/api/user/settings/favorites`);\n}\n\nexport function updateFavorites(favorites: q.TUserFavorite[]): Promise<q.TUserFavorite[]> {\n  return request.post(`${endpoints.apiBaseUrl()}/api/user/settings/favorites`, {\n    favorites,\n  });\n}\n\n/** Combined Pinned-section display order: favorite and pinned-chat entry keys interleaved. */\nexport function getPinnedOrder(): Promise<string[]> {\n  return request.get(endpoints.pinnedOrder());\n}\n\nexport function updatePinnedOrder(pinnedOrder: string[]): Promise<string[]> {\n  return request.post(endpoints.pinnedOrder(), { pinnedOrder });\n}\n\n/** Tool favorites — starred marketplace items (builtins, tools, MCP servers, skills). */\nexport function getToolFavorites(): Promise<q.TToolFavorite[]> {\n  return request.get(endpoints.toolFavorites());\n}\n\nexport function addToolFavorite(favorite: q.TToolFavorite): Promise<q.TToolFavorite> {\n  return request.put(endpoints.toolFavorite(favorite.itemType, favorite.itemId));\n}\n\nexport function removeToolFavorite(favorite: q.TToolFavorite): Promise<{ ok: boolean }> {\n  return request.delete(endpoints.toolFavorite(favorite.itemType, favorite.itemId));\n}\n\n/** Per-user skill active/inactive overrides. */\nexport function getSkillStates(): Promise<sk.TSkillStatesResponse> {\n  return request.get(endpoints.skillStates());\n}\n\nexport function updateSkillStates(\n  skillStates: sk.TSkillStatesResponse,\n): Promise<sk.TSkillStatesResponse> {\n  return request.post(endpoints.skillStates(), { skillStates });\n}\n\nexport function getSharedMessages(shareId: string): Promise<t.TSharedMessagesResponse> {\n  return request.get(endpoints.shareMessages(shareId));\n}\n\nexport function getSharedStartupConfig(shareId: string): Promise<config.TSharedLinkStartupConfig> {\n  return request.get(endpoints.sharedStartupConfig(shareId));\n}\n\nexport const listSharedLinks = async (\n  params: q.SharedLinksListParams,\n): Promise<q.SharedLinksResponse> => {\n  const { pageSize, sortBy, sortDirection, search, cursor } = params;\n\n  return request.get(endpoints.getSharedLinks(pageSize, sortBy, sortDirection, search, cursor));\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  snapshotFiles?: boolean,\n): Promise<t.TSharedLinkResponse> {\n  return request.post(endpoints.createSharedLink(conversationId), {\n    targetMessageId,\n    snapshotFiles,\n  });\n}\n\nexport function updateSharedLink(\n  shareId: string,\n  targetMessageId?: string,\n  snapshotFiles?: boolean,\n): Promise<t.TSharedLinkResponse> {\n  return request.patch(endpoints.updateSharedLink(shareId), {\n    targetMessageId,\n    snapshotFiles,\n  });\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 updateUserPreferences(\n  preferences: t.TUpdateUserPreferencesRequest,\n): Promise<t.TUpdateUserPreferencesResponse> {\n  return request.patch(endpoints.userPreferences(), preferences);\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): Promise<mcp.MCPReinitializeResponse> => {\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\nexport function getMCPOAuthStatus(flowId: string): Promise<mcp.MCPOAuthStatusResponse> {\n  return request.get(endpoints.mcpOAuthStatus(flowId));\n}\n\n/* Config */\n\nexport type StartupConfigOptions = {\n  context?: config.StartupConfigContext;\n};\n\nexport const getStartupConfig = (\n  options?: StartupConfigOptions,\n): Promise<\n  config.TStartupConfig & {\n    mcpCustomUserVars?: Record<string, { title: string; description: string }>;\n  }\n> => {\n  return request.get(endpoints.config(options?.context));\n};\n\nexport const getAIEndpoints = (): Promise<t.TEndpointsConfig> => {\n  return request.get(endpoints.aiEndpoints());\n};\n\nexport const getTokenConfig = (): Promise<t.TTokenConfigMap> => {\n  return request.get(endpoints.tokenConfig());\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\n/**\n * Poll the lifecycle of an inline file preview. Returns the smallest\n * shape needed to drive the UI:\n *   - `status` always present (defaults to `'ready'` server-side for\n *     legacy records that pre-date the field).\n *   - `text` and `textFormat` only when `status === 'ready'` and text\n *     was extracted (preserves the HTML-or-null security contract).\n *   - `previewError` only when `status === 'failed'`.\n *\n * Called from `useFilePreview`; React Query's `refetchInterval`\n * polls while `status === 'pending'` and stops on terminal status.\n */\nexport const getFilePreview = (fileId: string): Promise<f.TFilePreview> => {\n  return request.get(endpoints.filePreview(fileId));\n};\n\n/** Preview status for a snapshotted file served through a shared link. */\nexport const getSharedFilePreview = (shareId: string, fileId: string): Promise<f.TFilePreview> => {\n  return request.get(endpoints.sharedFilePreview(shareId, fileId));\n};\n\nexport const getAgentFiles = (agentId: string): Promise<f.TFile[]> => {\n  return request.get(endpoints.agentFiles(agentId));\n};\n\nexport const getFileConfig = (): Promise<TFileConfig> => {\n  return request.get(`${endpoints.files()}/config`);\n};\n\nexport const uploadImage = (\n  data: FormData,\n  signal?: AbortSignal | null,\n  sseEnabled = false,\n): Promise<f.TFileUpload> => {\n  const requestConfig = signal ? { signal } : undefined;\n  if (sseEnabled) {\n    return uploadEventStream(endpoints.images(), data, signal);\n  }\n  return request.postMultiPart(endpoints.images(), data, requestConfig);\n};\n\nexport const uploadFile = (\n  data: FormData,\n  signal?: AbortSignal | null,\n  sseEnabled = false,\n): Promise<f.TFileUpload> => {\n  const requestConfig = signal ? { signal } : undefined;\n  if (sseEnabled) {\n    return uploadEventStream(endpoints.files(), data, signal);\n  }\n  return request.postMultiPart(endpoints.files(), data, requestConfig);\n};\n\n/**\n * Marks uploaded files as used (owner-scoped TTL touch) so the upload-window\n * TTL cannot reap attachments held in a client-side queue during a long run.\n * Best-effort: callers fire-and-forget — send-time marking is the backstop.\n */\nexport const markFilesUsage = (body: f.TFilesUsageBody): Promise<f.TFilesUsageResponse> => {\n  return request.post(endpoints.fileUsage(), body);\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 getAgentVersions = ({ agent_id }: { agent_id: string }): Promise<a.Agent[]> => {\n  return request.get(\n    endpoints.agents({\n      path: `${agent_id}/versions`,\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 getFileDownloadURL = async (\n  userId: string,\n  file_id: string,\n): Promise<f.FileDownloadURLResponse> => {\n  return request.get(`${endpoints.files()}/download-url/${userId}/${file_id}`);\n};\n\n/** Blob download for a snapshotted file served through a shared link. */\nexport const getSharedFileDownload = async (\n  shareId: string,\n  file_id: string,\n): Promise<AxiosResponse> => {\n  return request.getResponse(endpoints.sharedFileDownload(shareId, 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 forkSharedConversation(\n  shareId: string,\n  targetMessageIndex?: number,\n  shareRevision?: string,\n): Promise<t.TForkConvoResponse> {\n  return request.post(endpoints.forkSharedMessages(shareId), {\n    targetMessageIndex,\n    shareRevision,\n  });\n}\n\nexport function deleteConversation(payload: t.TDeleteConversationRequest) {\n  return request.deleteWithOptions(endpoints.deleteConversation(), {\n    data: { arg: payload },\n  });\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 archiveAllConversations(): Promise<t.TArchiveAllConversationsResponse> {\n  return request.post(endpoints.archiveAllConversations(), {});\n}\n\nexport function listProjects(params?: q.ProjectListParams): Promise<q.ProjectListResponse> {\n  return request.get(endpoints.projects(params ?? {}));\n}\n\nexport function createProject(payload: t.TCreateChatProjectRequest): Promise<t.TChatProject> {\n  return request.post(endpoints.projects(), payload);\n}\n\nexport function getProjectById(projectId: string): Promise<t.TChatProject> {\n  return request.get(endpoints.projectById(projectId));\n}\n\nexport function updateProject(payload: t.TUpdateChatProjectRequest): Promise<t.TChatProject> {\n  const { projectId, ...data } = payload;\n  return request.patch(endpoints.projectById(projectId), data);\n}\n\nexport function deleteProject(projectId: string): Promise<t.TDeleteChatProjectResponse> {\n  return request.delete(endpoints.projectById(projectId));\n}\n\nexport function assignConversationToProject(\n  payload: t.TAssignConversationToProjectRequest,\n): Promise<t.TAssignConversationToProjectResponse> {\n  const { conversationId, projectId } = payload;\n  return request.put(endpoints.projectConversation(conversationId), {\n    projectId,\n  });\n}\n\nexport function pinConversation(\n  payload: t.TPinConversationRequest,\n): Promise<t.TPinConversationResponse> {\n  return request.post(endpoints.pinConversation(), { 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 }), {\n    text,\n  });\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 }), {\n    text,\n    index,\n  });\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 getMessageById(conversationId: string, messageId: string): Promise<s.TMessage[]> {\n  return request.get(endpoints.messages({ conversationId, messageId }));\n}\n\nexport function getParentSubagents(parentConversationId: string): Promise<t.ParentSubagentIndex> {\n  return request.get(endpoints.parentSubagents(parentConversationId));\n}\n\nexport function getSubagentThread(\n  parentConversationId: string,\n  threadId: string,\n  taskId?: string,\n  cursor?: string,\n): Promise<t.SubagentThreadView> {\n  return request.get(endpoints.subagentThread(parentConversationId, threadId, taskId, cursor));\n}\n\nexport function controlSubagentTask(\n  parentConversationId: string,\n  threadId: string,\n  body: t.SubagentControlRequest,\n): Promise<t.SubagentControlResponse> {\n  return request.post(endpoints.subagentControl(parentConversationId, threadId), body);\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/* Skills */\n\nexport function listSkills(params?: sk.TSkillListRequest): Promise<sk.TSkillListResponse> {\n  return request.get(endpoints.listSkillsWithFilters(params ?? {}));\n}\n\nexport function getSchedules(): Promise<sch.TSchedulesResponse> {\n  return request.get(endpoints.schedules());\n}\n\nexport function enqueueAgentQueuedTurn(\n  payload: qt.TEnqueueAgentQueuedTurnRequest,\n): Promise<qt.TEnqueueAgentQueuedTurnResponse> {\n  return request.post(endpoints.agentQueuedTurns(), payload);\n}\n\nexport function listAgentQueuedTurns(\n  conversationId: string,\n  clientRequestIds?: string[],\n): Promise<qt.TListAgentQueuedTurnsResponse> {\n  return request.get(endpoints.agentQueuedTurnsByConversation(conversationId, clientRequestIds));\n}\n\nexport function cancelAgentQueuedTurn(\n  queuedTurnId: string,\n): Promise<qt.TCancelAgentQueuedTurnResponse> {\n  return request.delete(endpoints.agentQueuedTurn(queuedTurnId));\n}\n\nexport function getSchedule(id: string): Promise<sch.TSchedule> {\n  return request.get(endpoints.schedule(id));\n}\n\nexport function createSchedule(payload: sch.TCreateSchedule): Promise<sch.TSchedule> {\n  return request.post(endpoints.schedules(), payload);\n}\n\nexport function updateSchedule(id: string, payload: sch.TUpdateSchedule): Promise<sch.TSchedule> {\n  return request.patch(endpoints.schedule(id), payload);\n}\n\nexport function deleteSchedule(id: string): Promise<{ id: string }> {\n  return request.delete(endpoints.schedule(id));\n}\n\nexport function runScheduleNow(id: string): Promise<sch.TScheduleRunNowResponse> {\n  return request.post(endpoints.runSchedule(id), {});\n}\n\nexport function getSkill(id: string): Promise<sk.TSkill> {\n  return request.get(endpoints.getSkill(id));\n}\n\nexport function createSkill(payload: sk.TCreateSkill): Promise<sk.TSkill> {\n  return request.post(endpoints.skills(), payload);\n}\n\nexport function updateSkill(variables: sk.TUpdateSkillVariables): Promise<sk.TUpdateSkillResponse> {\n  return request.patch(endpoints.getSkill(variables.id), {\n    expectedVersion: variables.expectedVersion,\n    ...variables.payload,\n  });\n}\n\nexport function deleteSkill(id: string): Promise<sk.TDeleteSkillResponse> {\n  return request.delete(endpoints.getSkill(id));\n}\n\nexport function listSkillFiles(skillId: string): Promise<sk.TListSkillFilesResponse> {\n  return request.get(endpoints.skillFiles(skillId));\n}\n\nexport function uploadSkillFile(skillId: string, formData: FormData): Promise<sk.TSkillFile> {\n  return request.postMultiPart(endpoints.skillFiles(skillId), formData);\n}\n\n/**\n * Import a skill from a .md, .zip, or .skill file. The backend extracts the\n * archive, creates the skill from SKILL.md, and persists all additional files.\n * Single HTTP request — no client-side zip processing needed.\n */\nexport function importSkill(formData: FormData): Promise<sk.TSkill> {\n  return request.postMultiPart(endpoints.importSkill(), formData);\n}\n\nexport function getSkillFileContent(\n  skillId: string,\n  relativePath: string,\n): Promise<sk.TSkillFileContentResponse> {\n  return request.get(endpoints.skillFile(skillId, relativePath));\n}\n\nexport function deleteSkillFile(\n  skillId: string,\n  relativePath: string,\n): Promise<sk.TDeleteSkillFileResponse> {\n  return request.delete(endpoints.skillFile(skillId, relativePath));\n}\n\n/* -------------------------------------------------------------------------- */\n/* Skill Tree (nodes) — phase 2 backend                                       */\n/* -------------------------------------------------------------------------- */\n/* These were introduced by the original UI PR and are shipped as stubs in    */\n/* phase 1 so the tree UI compiles. Each resolves with empty/no-op data until */\n/* the backend persists a folder hierarchy. The call surface matches what the */\n/* tree hooks expect so wiring real endpoints later is a one-line swap.       */\n\nexport const getSkillTree = (_skillId: string): Promise<t.TSkillTreeResponse> => {\n  return Promise.resolve({ nodes: [] });\n};\n\nexport const createSkillNode = (\n  skillId: string,\n  data: FormData | t.TCreateSkillNodeRequest,\n): Promise<t.TSkillNode> => {\n  const name = data instanceof FormData ? (data.get('name') as string) || 'untitled' : data.name;\n  const type = data instanceof FormData ? 'file' : data.type;\n  const now = new Date().toISOString();\n  return Promise.resolve({\n    _id: `pending-${now}`,\n    skillId,\n    parentId: null,\n    type,\n    name,\n    order: 0,\n    author: '',\n    createdAt: now,\n    updatedAt: now,\n  });\n};\n\nexport const updateSkillNode = (variables: {\n  skillId: string;\n  nodeId: string;\n  data: t.TUpdateSkillNodeRequest;\n}): Promise<t.TSkillNode> => {\n  const now = new Date().toISOString();\n  return Promise.resolve({\n    _id: variables.nodeId,\n    skillId: variables.skillId,\n    parentId: variables.data.parentId ?? null,\n    type: 'file',\n    name: variables.data.name ?? '',\n    order: variables.data.order ?? 0,\n    author: '',\n    createdAt: now,\n    updatedAt: now,\n  });\n};\n\nexport const deleteSkillNode = (_variables: { skillId: string; nodeId: string }): Promise<void> => {\n  return Promise.resolve();\n};\n\nexport const getSkillNodeContent = (_variables: {\n  skillId: string;\n  nodeId: string;\n}): Promise<{ content: string; mimeType: string }> => {\n  return Promise.resolve({ content: '', mimeType: 'text/plain' });\n};\n\nexport const updateSkillNodeContent = (variables: {\n  skillId: string;\n  nodeId: string;\n  content: string;\n}): Promise<t.TSkillNode> => {\n  const now = new Date().toISOString();\n  return Promise.resolve({\n    _id: variables.nodeId,\n    skillId: variables.skillId,\n    parentId: null,\n    type: 'file',\n    name: '',\n    order: 0,\n    author: '',\n    createdAt: now,\n    updatedAt: now,\n  });\n};\n\nexport function getGitHubSkillSyncStatus(): Promise<sk.TGitHubSkillSyncStatusResponse> {\n  return request.get(endpoints.adminSkillsSyncStatus());\n}\n\nexport function runGitHubSkillSync(): Promise<sk.TGitHubSkillSyncManualRunResponse> {\n  return request.post(endpoints.adminSkillsSyncRun());\n}\n\nexport function setGitHubSkillSyncCredential(variables: {\n  credentialKey: string;\n  token: string;\n}): Promise<sk.TGitHubSkillSyncCredentialSummary> {\n  return request.put(endpoints.adminSkillsSyncCredential(variables.credentialKey), {\n    token: variables.token,\n  } satisfies sk.TGitHubSkillSyncCredentialUpdateRequest);\n}\n\nexport function deleteGitHubSkillSyncCredential(\n  credentialKey: string,\n): Promise<{ credentialKey: string; deleted: boolean }> {\n  return request.delete(endpoints.adminSkillsSyncCredential(credentialKey));\n}\n\n/* Roles */\nexport function listRoles(): Promise<q.ListRolesResponse> {\n  return request.get(`${endpoints.adminRoles()}?limit=200`);\n}\n\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\nexport function updateSkillPermissions(\n  variables: m.UpdateSkillPermVars,\n): Promise<m.UpdatePermResponse> {\n  return request.put(endpoints.updateSkillPermissions(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, agentId?: string): Promise<q.DeleteMemoryResponse> => {\n  return request.delete(endpoints.memory(key, agentId));\n};\n\nexport const deleteMemoryById = (id: string, agentId?: string): Promise<q.DeleteMemoryResponse> => {\n  return request.delete(endpoints.memoryById(id, agentId));\n};\n\nexport const updateMemory = (\n  key: string,\n  value: string,\n  originalKey?: string,\n  agentId?: string,\n): Promise<q.UpdateMemoryResponse> => {\n  return request.patch(endpoints.memory(originalKey || key, agentId), {\n    key,\n    value,\n  });\n};\n\nexport const updateMemoryById = (\n  id: string,\n  value: string,\n  key?: string,\n  agentId?: string,\n): Promise<q.UpdateMemoryResponse> => {\n  return request.patch(endpoints.memoryById(id, agentId), {\n    value,\n    ...(key ? { key } : {}),\n  });\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  agentId?: 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"],"mappings":";;;;;;;;;;;;;;;;AAAA,MAAa,cAAc;;;;;;;;;AAU3B,MAAM,qBAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,kBAAkB,SAA0B;CAC1D,OAAO,mBAAmB,IAAI,OAAO;AACvC;;AAGA,SAAgB,oBAAoB,OAA8B;CAChE,IAAI,CAAC,OACH,OAAO;CAGT,MAAM,QAAQ,MAAM,KAAK,CAAC,CAAC,MAAM,WAAW;CAC5C,OAAO,QAAQ,MAAM,KAAK;AAC5B;;AAGA,SAAgB,mBAAmB,OAAe;CAChD,IAAI,CAAC,OACH,OAAO;CAGT,MAAM,UAAU,MAAM,KAAK;CAE3B,MAAM,cAAc,QAAQ,MAAM,WAAW;CAC7C,IAAI,aAAa;EACf,MAAM,UAAU,YAAY;EAC5B,IAAI,kBAAkB,OAAO,GAC3B,OAAO;EAET,OAAO,QAAQ,IAAI,YAAY;CACjC;CAEA,MAAM,QAAQ;CACd,IAAI,SAAS;CAEb,MAAM,UAAU,CAAC;CACjB,IAAI;CACJ,QAAQ,QAAQ,MAAM,KAAK,OAAO,OAAO,MACvC,QAAQ,KAAK;EACX,WAAW,MAAM;EACjB,SAAS,MAAM;EACf,OAAO,MAAM;CACf,CAAC;CAGH,KAAK,IAAI,IAAI,QAAQ,SAAS,GAAG,KAAK,GAAG,KAAK;EAC5C,MAAM,EAAE,WAAW,SAAS,UAAU,QAAQ;EAC9C,IAAI,kBAAkB,OAAO,GAC3B;EAEF,MAAM,WAAW,QAAQ,IAAI,YAAY;EACzC,SAAS,OAAO,UAAU,GAAG,KAAK,IAAI,WAAW,OAAO,UAAU,QAAQ,UAAU,MAAM;CAC5F;CAEA,OAAO;AACT;;;;;A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A;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,GAAG;AACL;AAEA,MAAa,+BAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,GAAG;AACL;AAEA,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,gBAAgB;;AAe7B,MAAa,yBAAgE;CAC3E,mBAAmB;CACnB,YAAY;CACZ,mBAAmB;CACnB,sBAAsB;CACtB,2EAA2E;CAC3E,4BAA4B;CAC5B,qEAAqE;CACrE,aAAa;CACb,cAAc;CACd,iBAAiB;AACnB;;;;;;AAOA,MAAa,uBAAuB,UAClC,UAAU,QAAQ,UAAU;;;;;;AAO9B,MAAa,wBAAwB,UACnC,UAAU,QAAQ,UAAU;;;;;;;;;;AAW9B,MAAa,0BAA0B,UAAkB,aAAqC;CAC5F,IAAI,CAAC,UAAU,WAAW,QAAQ,GAChC,OAAO;CAET,MAAM,UAAU,SAAS,MAAM,CAAe;CAC9C,IAAI,CAAC;EAAC;EAAQ;EAAO;EAAQ;CAAK,CAAC,CAAC,SAAS,OAAO,GAClD,OAAO;CAET,MAAM,WAAW,YAAY,SAAS,CAAC,QAAQ,OAAO,IAAI,CAA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;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAUA,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;AACF;AAEA,MAAa,gBAAgB;sBACO;iBACL,CAAC,GAAG,oBAAoB,mBAAmB;aAE/C,CAAC,GAAG,2BAA2B,GAAG,kBAAkB;aACpD;EAEvB;EAEA;EAEA;EAEA;EACA;EAEA;EACA;EACA;EAEA;EACA;EAEA;EACA;EACA;CACF;gBAC4B;aACH;EACvB,GAAG;EACH,GAAG;EACH;EACA;EACA;EACA;CACF;cAC0B;AAC5B;AAEA,MAAM,yBAAyB,QAAgB;CAC7C,OAAO,mBAAmB,KAAK,GAAG,KAAK,CAAC,mBAAmB,KAAK,GAAG;AACrE;AAEA,MAAM,eAAe,cAAA;;;;;;;AAQrB,MAAM,+BAA+B,aAAa,QAC/C,UAAU,CAAC,0BAA0B,SAAS,KAAK,CACtD;AAEA,MAAa,sBAAqC;CAChD,SAAS,CAAC;aACe;iBACI,aAAa,OAAO,qBAAqB;aAC7C;kBACK;aACL,cAAA;gBACG,cAAA;cACF,cAAA;AAC5B;AAEA,MAAa,eAAe;iBACG,GAAG,WAAW,EAAE;sBACX,GAAG,WAAW,EAAE;aACzB,GAAG,WAAW,EAAE;AAC3C;AAEA,MAAa,mBAAmB,IAAI,IAA6B;;;;;;;;AAQjE,CAAC;AAED,MAAa,uBAAuB;aACT;aACA;gBACG;iBACC;aACJ;sBACS;kBACJ;cACJ;aACD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